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
25pub mod notice;
26
27use std::collections::BTreeMap;
28use std::hash::Hash;
29use std::string::ToString;
30use std::sync::LazyLock;
31use std::sync::Mutex;
32
33use clap::clap_derive::ValueEnum;
34use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
35use mz_ore::collections::HashMap;
36use mz_pgrepr::oid;
37use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
38use mz_repr::adt::numeric::NumericMaxScale;
39use mz_repr::namespaces::{
40    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_INTROSPECTION_SCHEMA,
41    MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA,
42};
43use mz_repr::role_id::RoleId;
44use mz_repr::{RelationDesc, RelationType, ScalarType};
45use mz_sql::catalog::{
46    CatalogItemType, CatalogType, CatalogTypeDetails, CatalogTypePgMetadata, NameReference,
47    ObjectType, RoleAttributes, 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 rand::Rng;
64use serde::Serialize;
65
66use crate::durable::objects::SystemObjectDescription;
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(Debug)]
89pub enum Builtin<T: 'static + TypeReference> {
90    Log(&'static BuiltinLog),
91    Table(&'static BuiltinTable),
92    View(&'static BuiltinView),
93    Type(&'static BuiltinType<T>),
94    Func(BuiltinFunc),
95    Source(&'static BuiltinSource),
96    ContinualTask(&'static BuiltinContinualTask),
97    Index(&'static BuiltinIndex),
98    Connection(&'static BuiltinConnection),
99}
100
101impl<T: TypeReference> Builtin<T> {
102    pub fn name(&self) -> &'static str {
103        match self {
104            Builtin::Log(log) => log.name,
105            Builtin::Table(table) => table.name,
106            Builtin::View(view) => view.name,
107            Builtin::Type(typ) => typ.name,
108            Builtin::Func(func) => func.name,
109            Builtin::Source(coll) => coll.name,
110            Builtin::ContinualTask(ct) => ct.name,
111            Builtin::Index(index) => index.name,
112            Builtin::Connection(connection) => connection.name,
113        }
114    }
115
116    pub fn schema(&self) -> &'static str {
117        match self {
118            Builtin::Log(log) => log.schema,
119            Builtin::Table(table) => table.schema,
120            Builtin::View(view) => view.schema,
121            Builtin::Type(typ) => typ.schema,
122            Builtin::Func(func) => func.schema,
123            Builtin::Source(coll) => coll.schema,
124            Builtin::ContinualTask(ct) => ct.schema,
125            Builtin::Index(index) => index.schema,
126            Builtin::Connection(connection) => connection.schema,
127        }
128    }
129
130    pub fn catalog_item_type(&self) -> CatalogItemType {
131        match self {
132            Builtin::Log(_) => CatalogItemType::Source,
133            Builtin::Source(_) => CatalogItemType::Source,
134            Builtin::ContinualTask(_) => CatalogItemType::ContinualTask,
135            Builtin::Table(_) => CatalogItemType::Table,
136            Builtin::View(_) => CatalogItemType::View,
137            Builtin::Type(_) => CatalogItemType::Type,
138            Builtin::Func(_) => CatalogItemType::Func,
139            Builtin::Index(_) => CatalogItemType::Index,
140            Builtin::Connection(_) => CatalogItemType::Connection,
141        }
142    }
143
144    /// Whether the object can be altered at runtime by its owner.
145    pub fn runtime_alterable(&self) -> bool {
146        match self {
147            Builtin::Connection(c) => c.runtime_alterable,
148            _ => false,
149        }
150    }
151}
152
153#[derive(Clone, Debug, Hash, Serialize)]
154pub struct BuiltinLog {
155    pub variant: LogVariant,
156    pub name: &'static str,
157    pub schema: &'static str,
158    pub oid: u32,
159    /// ACL items to apply to the object
160    pub access: Vec<MzAclItem>,
161}
162
163#[derive(Hash, Debug, PartialEq, Eq)]
164pub struct BuiltinTable {
165    pub name: &'static str,
166    pub schema: &'static str,
167    pub oid: u32,
168    pub desc: RelationDesc,
169    pub column_comments: BTreeMap<&'static str, &'static str>,
170    /// Whether the table's retention policy is controlled by
171    /// the system variable `METRICS_RETENTION`
172    pub is_retained_metrics_object: bool,
173    /// ACL items to apply to the object
174    pub access: Vec<MzAclItem>,
175}
176
177#[derive(Clone, Debug, Hash, Serialize)]
178pub struct BuiltinSource {
179    pub name: &'static str,
180    pub schema: &'static str,
181    pub oid: u32,
182    pub desc: RelationDesc,
183    pub column_comments: BTreeMap<&'static str, &'static str>,
184    pub data_source: IntrospectionType,
185    /// Whether the source's retention policy is controlled by
186    /// the system variable `METRICS_RETENTION`
187    pub is_retained_metrics_object: bool,
188    /// ACL items to apply to the object
189    pub access: Vec<MzAclItem>,
190}
191
192#[derive(Hash, Debug, PartialEq, Eq)]
193pub struct BuiltinContinualTask {
194    pub name: &'static str,
195    pub schema: &'static str,
196    pub oid: u32,
197    pub desc: RelationDesc,
198    pub sql: &'static str,
199    /// ACL items to apply to the object
200    pub access: Vec<MzAclItem>,
201}
202
203#[derive(Hash, Debug)]
204pub struct BuiltinView {
205    pub name: &'static str,
206    pub schema: &'static str,
207    pub oid: u32,
208    pub desc: RelationDesc,
209    pub column_comments: BTreeMap<&'static str, &'static str>,
210    pub sql: &'static str,
211    /// ACL items to apply to the object
212    pub access: Vec<MzAclItem>,
213}
214
215impl BuiltinView {
216    pub fn create_sql(&self) -> String {
217        format!("CREATE VIEW {}.{} AS {}", self.schema, self.name, self.sql)
218    }
219}
220
221#[derive(Debug)]
222pub struct BuiltinType<T: TypeReference> {
223    pub name: &'static str,
224    pub schema: &'static str,
225    pub oid: u32,
226    pub details: CatalogTypeDetails<T>,
227}
228
229#[derive(Debug)]
230pub struct BuiltinFunc {
231    pub schema: &'static str,
232    pub name: &'static str,
233    pub inner: &'static mz_sql::func::Func,
234}
235
236/// Note: When creating a built-in index, it's usually best to choose a key that has only one
237/// component. For example, if you created an index
238/// `ON mz_internal.mz_object_lifetimes (id, object_type)`, then this index couldn't be used for a
239/// lookup for `WHERE object_type = ...`, and neither for joins keyed on just `id`.
240/// See <https://materialize.com/docs/transform-data/optimization/#matching-multi-column-indexes-to-multi-column-where-clauses>
241#[derive(Debug)]
242pub struct BuiltinIndex {
243    pub name: &'static str,
244    pub schema: &'static str,
245    pub oid: u32,
246    /// SQL fragment for the index, following `CREATE INDEX [name]`
247    ///
248    /// Format: `IN CLUSTER [cluster_name] ON [table_name] ([column_exprs])`
249    pub sql: &'static str,
250    pub is_retained_metrics_object: bool,
251}
252
253impl BuiltinIndex {
254    pub fn create_sql(&self) -> String {
255        format!("CREATE INDEX {}\n{}", self.name, self.sql)
256    }
257}
258
259impl BuiltinContinualTask {
260    pub fn create_sql(&self) -> String {
261        format!(
262            "CREATE CONTINUAL TASK {}.{}\n{}",
263            self.schema, self.name, self.sql
264        )
265    }
266}
267
268#[derive(Hash, Debug)]
269pub struct BuiltinConnection {
270    pub name: &'static str,
271    pub schema: &'static str,
272    pub oid: u32,
273    pub sql: &'static str,
274    pub access: &'static [MzAclItem],
275    pub owner_id: &'static RoleId,
276    /// Whether the object can be altered at runtime by its owner.
277    ///
278    /// Note that when `runtime_alterable` is true, changing the `sql` in future
279    /// versions does not trigger a migration.
280    pub runtime_alterable: bool,
281}
282
283#[derive(Clone, Debug)]
284pub struct BuiltinRole {
285    pub id: RoleId,
286    /// Name of the builtin role.
287    ///
288    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
289    pub name: &'static str,
290    pub oid: u32,
291    pub attributes: RoleAttributes,
292}
293
294#[derive(Clone, Debug)]
295pub struct BuiltinCluster {
296    /// Name of the cluster.
297    ///
298    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
299    pub name: &'static str,
300    pub privileges: &'static [MzAclItem],
301    pub owner_id: &'static RoleId,
302}
303
304#[derive(Clone, Debug, PartialEq, Eq)]
305pub struct BuiltinClusterReplica {
306    /// Name of the compute replica.
307    pub name: &'static str,
308    /// Name of the cluster that this replica belongs to.
309    pub cluster_name: &'static str,
310}
311
312/// Uniquely identifies the definition of a builtin object.
313pub trait Fingerprint {
314    fn fingerprint(&self) -> String;
315}
316
317impl<T: TypeReference> Fingerprint for &Builtin<T> {
318    fn fingerprint(&self) -> String {
319        match self {
320            Builtin::Log(log) => log.fingerprint(),
321            Builtin::Table(table) => table.fingerprint(),
322            Builtin::View(view) => view.fingerprint(),
323            Builtin::Type(typ) => typ.fingerprint(),
324            Builtin::Func(func) => func.fingerprint(),
325            Builtin::Source(coll) => coll.fingerprint(),
326            Builtin::ContinualTask(ct) => ct.fingerprint(),
327            Builtin::Index(index) => index.fingerprint(),
328            Builtin::Connection(connection) => connection.fingerprint(),
329        }
330    }
331}
332
333// Types and Funcs never change fingerprints so we just return constant 0
334impl<T: TypeReference> Fingerprint for &BuiltinType<T> {
335    fn fingerprint(&self) -> String {
336        "".to_string()
337    }
338}
339
340impl Fingerprint for &BuiltinFunc {
341    fn fingerprint(&self) -> String {
342        "".to_string()
343    }
344}
345
346impl Fingerprint for &BuiltinLog {
347    fn fingerprint(&self) -> String {
348        self.variant.desc().fingerprint()
349    }
350}
351
352/// Allows tests to inject arbitrary amounts of whitespace to forcibly change the fingerprint and
353/// trigger a builtin migration.
354#[derive(Debug, Clone, ValueEnum)]
355pub enum UnsafeBuiltinTableFingerprintWhitespace {
356    /// Inject whitespace into all builtin table fingerprints.
357    All,
358    /// Inject whitespace into half of the builtin table fingerprints,
359    /// which are randomly selected.
360    Half,
361}
362pub static UNSAFE_DO_NOT_CALL_THIS_IN_PRODUCTION_BUILTIN_TABLE_FINGERPRINT_WHITESPACE: Mutex<
363    Option<(UnsafeBuiltinTableFingerprintWhitespace, String)>,
364> = Mutex::new(None);
365
366impl Fingerprint for &BuiltinTable {
367    fn fingerprint(&self) -> String {
368        // This is only called during bootstrapping, so it's not that big of a deal to lock a mutex,
369        // though it's not great.
370        let guard = UNSAFE_DO_NOT_CALL_THIS_IN_PRODUCTION_BUILTIN_TABLE_FINGERPRINT_WHITESPACE
371            .lock()
372            .expect("lock poisoned");
373        match &*guard {
374            // `mz_storage_usage_by_shard` can never be migrated.
375            _ if self.schema == MZ_STORAGE_USAGE_BY_SHARD.schema
376                && self.name == MZ_STORAGE_USAGE_BY_SHARD.name =>
377            {
378                self.desc.fingerprint()
379            }
380            Some((UnsafeBuiltinTableFingerprintWhitespace::All, whitespace)) => {
381                format!("{}{}", self.desc.fingerprint(), whitespace)
382            }
383            Some((UnsafeBuiltinTableFingerprintWhitespace::Half, whitespace)) => {
384                let mut rng = rand::thread_rng();
385                let migrate: bool = rng.r#gen();
386                if migrate {
387                    format!("{}{}", self.desc.fingerprint(), whitespace)
388                } else {
389                    self.desc.fingerprint()
390                }
391            }
392            None => self.desc.fingerprint(),
393        }
394    }
395}
396
397impl Fingerprint for &BuiltinView {
398    fn fingerprint(&self) -> String {
399        self.sql.to_string()
400    }
401}
402
403impl Fingerprint for &BuiltinSource {
404    fn fingerprint(&self) -> String {
405        self.desc.fingerprint()
406    }
407}
408
409impl Fingerprint for &BuiltinContinualTask {
410    fn fingerprint(&self) -> String {
411        self.create_sql()
412    }
413}
414
415impl Fingerprint for &BuiltinIndex {
416    fn fingerprint(&self) -> String {
417        self.create_sql()
418    }
419}
420
421impl Fingerprint for &BuiltinConnection {
422    fn fingerprint(&self) -> String {
423        self.sql.to_string()
424    }
425}
426
427impl Fingerprint for RelationDesc {
428    fn fingerprint(&self) -> String {
429        self.typ().fingerprint()
430    }
431}
432
433impl Fingerprint for RelationType {
434    fn fingerprint(&self) -> String {
435        serde_json::to_string(self).expect("serialization cannot fail")
436    }
437}
438
439// Builtin definitions below. Ensure you add new builtins to the `BUILTINS` map.
440//
441// You SHOULD NOT delete a builtin. If you do, you will break any downstream
442// user objects that depended on the builtin.
443//
444// Builtins are loaded in dependency order, so a builtin must appear in `BUILTINS`
445// before any items it depends upon.
446//
447// WARNING: if you change the definition of an existing builtin item, you must
448// be careful to maintain backwards compatibility! Adding new columns is safe.
449// Removing a column, changing the name of a column, or changing the type of a
450// column is not safe, as persisted user views may depend upon that column.
451
452// The following types are the list of builtin data types available
453// in Materialize. This list is derived from the `pg_type` table in PostgreSQL.
454//
455// Builtin types cannot be created, updated, or deleted. Their OIDs
456// are static, unlike other objects, to match the type OIDs defined by Postgres.
457
458pub const TYPE_BOOL: BuiltinType<NameReference> = BuiltinType {
459    name: "bool",
460    schema: PG_CATALOG_SCHEMA,
461    oid: oid::TYPE_BOOL_OID,
462    details: CatalogTypeDetails {
463        typ: CatalogType::Bool,
464        array_id: None,
465        pg_metadata: Some(CatalogTypePgMetadata {
466            typinput_oid: 1242,
467            typreceive_oid: 2436,
468        }),
469    },
470};
471
472pub const TYPE_BYTEA: BuiltinType<NameReference> = BuiltinType {
473    name: "bytea",
474    schema: PG_CATALOG_SCHEMA,
475    oid: oid::TYPE_BYTEA_OID,
476    details: CatalogTypeDetails {
477        typ: CatalogType::Bytes,
478        array_id: None,
479        pg_metadata: Some(CatalogTypePgMetadata {
480            typinput_oid: 1244,
481            typreceive_oid: 2412,
482        }),
483    },
484};
485
486pub const TYPE_INT8: BuiltinType<NameReference> = BuiltinType {
487    name: "int8",
488    schema: PG_CATALOG_SCHEMA,
489    oid: oid::TYPE_INT8_OID,
490    details: CatalogTypeDetails {
491        typ: CatalogType::Int64,
492        array_id: None,
493        pg_metadata: Some(CatalogTypePgMetadata {
494            typinput_oid: 460,
495            typreceive_oid: 2408,
496        }),
497    },
498};
499
500pub const TYPE_INT4: BuiltinType<NameReference> = BuiltinType {
501    name: "int4",
502    schema: PG_CATALOG_SCHEMA,
503    oid: oid::TYPE_INT4_OID,
504    details: CatalogTypeDetails {
505        typ: CatalogType::Int32,
506        array_id: None,
507        pg_metadata: Some(CatalogTypePgMetadata {
508            typinput_oid: 42,
509            typreceive_oid: 2406,
510        }),
511    },
512};
513
514pub const TYPE_TEXT: BuiltinType<NameReference> = BuiltinType {
515    name: "text",
516    schema: PG_CATALOG_SCHEMA,
517    oid: oid::TYPE_TEXT_OID,
518    details: CatalogTypeDetails {
519        typ: CatalogType::String,
520        array_id: None,
521        pg_metadata: Some(CatalogTypePgMetadata {
522            typinput_oid: 46,
523            typreceive_oid: 2414,
524        }),
525    },
526};
527
528pub const TYPE_OID: BuiltinType<NameReference> = BuiltinType {
529    name: "oid",
530    schema: PG_CATALOG_SCHEMA,
531    oid: oid::TYPE_OID_OID,
532    details: CatalogTypeDetails {
533        typ: CatalogType::Oid,
534        array_id: None,
535        pg_metadata: Some(CatalogTypePgMetadata {
536            typinput_oid: 1798,
537            typreceive_oid: 2418,
538        }),
539    },
540};
541
542pub const TYPE_FLOAT4: BuiltinType<NameReference> = BuiltinType {
543    name: "float4",
544    schema: PG_CATALOG_SCHEMA,
545    oid: oid::TYPE_FLOAT4_OID,
546    details: CatalogTypeDetails {
547        typ: CatalogType::Float32,
548        array_id: None,
549        pg_metadata: Some(CatalogTypePgMetadata {
550            typinput_oid: 200,
551            typreceive_oid: 2424,
552        }),
553    },
554};
555
556pub const TYPE_FLOAT8: BuiltinType<NameReference> = BuiltinType {
557    name: "float8",
558    schema: PG_CATALOG_SCHEMA,
559    oid: oid::TYPE_FLOAT8_OID,
560    details: CatalogTypeDetails {
561        typ: CatalogType::Float64,
562        array_id: None,
563        pg_metadata: Some(CatalogTypePgMetadata {
564            typinput_oid: 214,
565            typreceive_oid: 2426,
566        }),
567    },
568};
569
570pub const TYPE_BOOL_ARRAY: BuiltinType<NameReference> = BuiltinType {
571    name: "_bool",
572    schema: PG_CATALOG_SCHEMA,
573    oid: oid::TYPE_BOOL_ARRAY_OID,
574    details: CatalogTypeDetails {
575        typ: CatalogType::Array {
576            element_reference: TYPE_BOOL.name,
577        },
578        array_id: None,
579        pg_metadata: Some(CatalogTypePgMetadata {
580            typinput_oid: 750,
581            typreceive_oid: 2400,
582        }),
583    },
584};
585
586pub const TYPE_BYTEA_ARRAY: BuiltinType<NameReference> = BuiltinType {
587    name: "_bytea",
588    schema: PG_CATALOG_SCHEMA,
589    oid: oid::TYPE_BYTEA_ARRAY_OID,
590    details: CatalogTypeDetails {
591        typ: CatalogType::Array {
592            element_reference: TYPE_BYTEA.name,
593        },
594        array_id: None,
595        pg_metadata: Some(CatalogTypePgMetadata {
596            typinput_oid: 750,
597            typreceive_oid: 2400,
598        }),
599    },
600};
601
602pub const TYPE_INT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
603    name: "_int4",
604    schema: PG_CATALOG_SCHEMA,
605    oid: oid::TYPE_INT4_ARRAY_OID,
606    details: CatalogTypeDetails {
607        typ: CatalogType::Array {
608            element_reference: TYPE_INT4.name,
609        },
610        array_id: None,
611        pg_metadata: Some(CatalogTypePgMetadata {
612            typinput_oid: 750,
613            typreceive_oid: 2400,
614        }),
615    },
616};
617
618pub const TYPE_TEXT_ARRAY: BuiltinType<NameReference> = BuiltinType {
619    name: "_text",
620    schema: PG_CATALOG_SCHEMA,
621    oid: oid::TYPE_TEXT_ARRAY_OID,
622    details: CatalogTypeDetails {
623        typ: CatalogType::Array {
624            element_reference: TYPE_TEXT.name,
625        },
626        array_id: None,
627        pg_metadata: Some(CatalogTypePgMetadata {
628            typinput_oid: 750,
629            typreceive_oid: 2400,
630        }),
631    },
632};
633
634pub const TYPE_INT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
635    name: "_int8",
636    schema: PG_CATALOG_SCHEMA,
637    oid: oid::TYPE_INT8_ARRAY_OID,
638    details: CatalogTypeDetails {
639        typ: CatalogType::Array {
640            element_reference: TYPE_INT8.name,
641        },
642        array_id: None,
643        pg_metadata: Some(CatalogTypePgMetadata {
644            typinput_oid: 750,
645            typreceive_oid: 2400,
646        }),
647    },
648};
649
650pub const TYPE_FLOAT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
651    name: "_float4",
652    schema: PG_CATALOG_SCHEMA,
653    oid: oid::TYPE_FLOAT4_ARRAY_OID,
654    details: CatalogTypeDetails {
655        typ: CatalogType::Array {
656            element_reference: TYPE_FLOAT4.name,
657        },
658        array_id: None,
659        pg_metadata: Some(CatalogTypePgMetadata {
660            typinput_oid: 750,
661            typreceive_oid: 2400,
662        }),
663    },
664};
665
666pub const TYPE_FLOAT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
667    name: "_float8",
668    schema: PG_CATALOG_SCHEMA,
669    oid: oid::TYPE_FLOAT8_ARRAY_OID,
670    details: CatalogTypeDetails {
671        typ: CatalogType::Array {
672            element_reference: TYPE_FLOAT8.name,
673        },
674        array_id: None,
675        pg_metadata: Some(CatalogTypePgMetadata {
676            typinput_oid: 750,
677            typreceive_oid: 2400,
678        }),
679    },
680};
681
682pub const TYPE_OID_ARRAY: BuiltinType<NameReference> = BuiltinType {
683    name: "_oid",
684    schema: PG_CATALOG_SCHEMA,
685    oid: oid::TYPE_OID_ARRAY_OID,
686    details: CatalogTypeDetails {
687        typ: CatalogType::Array {
688            element_reference: TYPE_OID.name,
689        },
690        array_id: None,
691        pg_metadata: Some(CatalogTypePgMetadata {
692            typinput_oid: 750,
693            typreceive_oid: 2400,
694        }),
695    },
696};
697
698pub const TYPE_DATE: BuiltinType<NameReference> = BuiltinType {
699    name: "date",
700    schema: PG_CATALOG_SCHEMA,
701    oid: oid::TYPE_DATE_OID,
702    details: CatalogTypeDetails {
703        typ: CatalogType::Date,
704        array_id: None,
705        pg_metadata: Some(CatalogTypePgMetadata {
706            typinput_oid: 1084,
707            typreceive_oid: 2468,
708        }),
709    },
710};
711
712pub const TYPE_TIME: BuiltinType<NameReference> = BuiltinType {
713    name: "time",
714    schema: PG_CATALOG_SCHEMA,
715    oid: oid::TYPE_TIME_OID,
716    details: CatalogTypeDetails {
717        typ: CatalogType::Time,
718        array_id: None,
719        pg_metadata: Some(CatalogTypePgMetadata {
720            typinput_oid: 1143,
721            typreceive_oid: 2470,
722        }),
723    },
724};
725
726pub const TYPE_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
727    name: "timestamp",
728    schema: PG_CATALOG_SCHEMA,
729    oid: oid::TYPE_TIMESTAMP_OID,
730    details: CatalogTypeDetails {
731        typ: CatalogType::Timestamp,
732        array_id: None,
733        pg_metadata: Some(CatalogTypePgMetadata {
734            typinput_oid: 1312,
735            typreceive_oid: 2474,
736        }),
737    },
738};
739
740pub const TYPE_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
741    name: "_timestamp",
742    schema: PG_CATALOG_SCHEMA,
743    oid: oid::TYPE_TIMESTAMP_ARRAY_OID,
744    details: CatalogTypeDetails {
745        typ: CatalogType::Array {
746            element_reference: TYPE_TIMESTAMP.name,
747        },
748        array_id: None,
749        pg_metadata: Some(CatalogTypePgMetadata {
750            typinput_oid: 750,
751            typreceive_oid: 2400,
752        }),
753    },
754};
755
756pub const TYPE_DATE_ARRAY: BuiltinType<NameReference> = BuiltinType {
757    name: "_date",
758    schema: PG_CATALOG_SCHEMA,
759    oid: oid::TYPE_DATE_ARRAY_OID,
760    details: CatalogTypeDetails {
761        typ: CatalogType::Array {
762            element_reference: TYPE_DATE.name,
763        },
764        array_id: None,
765        pg_metadata: Some(CatalogTypePgMetadata {
766            typinput_oid: 750,
767            typreceive_oid: 2400,
768        }),
769    },
770};
771
772pub const TYPE_TIME_ARRAY: BuiltinType<NameReference> = BuiltinType {
773    name: "_time",
774    schema: PG_CATALOG_SCHEMA,
775    oid: oid::TYPE_TIME_ARRAY_OID,
776    details: CatalogTypeDetails {
777        typ: CatalogType::Array {
778            element_reference: TYPE_TIME.name,
779        },
780        array_id: None,
781        pg_metadata: Some(CatalogTypePgMetadata {
782            typinput_oid: 750,
783            typreceive_oid: 2400,
784        }),
785    },
786};
787
788pub const TYPE_TIMESTAMPTZ: BuiltinType<NameReference> = BuiltinType {
789    name: "timestamptz",
790    schema: PG_CATALOG_SCHEMA,
791    oid: oid::TYPE_TIMESTAMPTZ_OID,
792    details: CatalogTypeDetails {
793        typ: CatalogType::TimestampTz,
794        array_id: None,
795        pg_metadata: Some(CatalogTypePgMetadata {
796            typinput_oid: 1150,
797            typreceive_oid: 2476,
798        }),
799    },
800};
801
802pub const TYPE_TIMESTAMPTZ_ARRAY: BuiltinType<NameReference> = BuiltinType {
803    name: "_timestamptz",
804    schema: PG_CATALOG_SCHEMA,
805    oid: oid::TYPE_TIMESTAMPTZ_ARRAY_OID,
806    details: CatalogTypeDetails {
807        typ: CatalogType::Array {
808            element_reference: TYPE_TIMESTAMPTZ.name,
809        },
810        array_id: None,
811        pg_metadata: Some(CatalogTypePgMetadata {
812            typinput_oid: 750,
813            typreceive_oid: 2400,
814        }),
815    },
816};
817
818pub const TYPE_INTERVAL: BuiltinType<NameReference> = BuiltinType {
819    name: "interval",
820    schema: PG_CATALOG_SCHEMA,
821    oid: oid::TYPE_INTERVAL_OID,
822    details: CatalogTypeDetails {
823        typ: CatalogType::Interval,
824        array_id: None,
825        pg_metadata: Some(CatalogTypePgMetadata {
826            typinput_oid: 1160,
827            typreceive_oid: 2478,
828        }),
829    },
830};
831
832pub const TYPE_INTERVAL_ARRAY: BuiltinType<NameReference> = BuiltinType {
833    name: "_interval",
834    schema: PG_CATALOG_SCHEMA,
835    oid: oid::TYPE_INTERVAL_ARRAY_OID,
836    details: CatalogTypeDetails {
837        typ: CatalogType::Array {
838            element_reference: TYPE_INTERVAL.name,
839        },
840        array_id: None,
841        pg_metadata: Some(CatalogTypePgMetadata {
842            typinput_oid: 750,
843            typreceive_oid: 2400,
844        }),
845    },
846};
847
848pub const TYPE_NAME: BuiltinType<NameReference> = BuiltinType {
849    name: "name",
850    schema: PG_CATALOG_SCHEMA,
851    oid: oid::TYPE_NAME_OID,
852    details: CatalogTypeDetails {
853        typ: CatalogType::PgLegacyName,
854        array_id: None,
855        pg_metadata: Some(CatalogTypePgMetadata {
856            typinput_oid: 34,
857            typreceive_oid: 2422,
858        }),
859    },
860};
861
862pub const TYPE_NAME_ARRAY: BuiltinType<NameReference> = BuiltinType {
863    name: "_name",
864    schema: PG_CATALOG_SCHEMA,
865    oid: oid::TYPE_NAME_ARRAY_OID,
866    details: CatalogTypeDetails {
867        typ: CatalogType::Array {
868            element_reference: TYPE_NAME.name,
869        },
870        array_id: None,
871        pg_metadata: Some(CatalogTypePgMetadata {
872            typinput_oid: 750,
873            typreceive_oid: 2400,
874        }),
875    },
876};
877
878pub const TYPE_NUMERIC: BuiltinType<NameReference> = BuiltinType {
879    name: "numeric",
880    schema: PG_CATALOG_SCHEMA,
881    oid: oid::TYPE_NUMERIC_OID,
882    details: CatalogTypeDetails {
883        typ: CatalogType::Numeric,
884        array_id: None,
885        pg_metadata: Some(CatalogTypePgMetadata {
886            typinput_oid: 1701,
887            typreceive_oid: 2460,
888        }),
889    },
890};
891
892pub const TYPE_NUMERIC_ARRAY: BuiltinType<NameReference> = BuiltinType {
893    name: "_numeric",
894    schema: PG_CATALOG_SCHEMA,
895    oid: oid::TYPE_NUMERIC_ARRAY_OID,
896    details: CatalogTypeDetails {
897        typ: CatalogType::Array {
898            element_reference: TYPE_NUMERIC.name,
899        },
900        array_id: None,
901        pg_metadata: Some(CatalogTypePgMetadata {
902            typinput_oid: 750,
903            typreceive_oid: 2400,
904        }),
905    },
906};
907
908pub const TYPE_RECORD: BuiltinType<NameReference> = BuiltinType {
909    name: "record",
910    schema: PG_CATALOG_SCHEMA,
911    oid: oid::TYPE_RECORD_OID,
912    details: CatalogTypeDetails {
913        typ: CatalogType::Pseudo,
914        array_id: None,
915        pg_metadata: Some(CatalogTypePgMetadata {
916            typinput_oid: 2290,
917            typreceive_oid: 2402,
918        }),
919    },
920};
921
922pub const TYPE_RECORD_ARRAY: BuiltinType<NameReference> = BuiltinType {
923    name: "_record",
924    schema: PG_CATALOG_SCHEMA,
925    oid: oid::TYPE_RECORD_ARRAY_OID,
926    details: CatalogTypeDetails {
927        typ: CatalogType::Array {
928            element_reference: TYPE_RECORD.name,
929        },
930        array_id: None,
931        pg_metadata: Some(CatalogTypePgMetadata {
932            typinput_oid: 750,
933            typreceive_oid: 2400,
934        }),
935    },
936};
937
938pub const TYPE_UUID: BuiltinType<NameReference> = BuiltinType {
939    name: "uuid",
940    schema: PG_CATALOG_SCHEMA,
941    oid: oid::TYPE_UUID_OID,
942    details: CatalogTypeDetails {
943        typ: CatalogType::Uuid,
944        array_id: None,
945        pg_metadata: Some(CatalogTypePgMetadata {
946            typinput_oid: 2952,
947            typreceive_oid: 2961,
948        }),
949    },
950};
951
952pub const TYPE_UUID_ARRAY: BuiltinType<NameReference> = BuiltinType {
953    name: "_uuid",
954    schema: PG_CATALOG_SCHEMA,
955    oid: oid::TYPE_UUID_ARRAY_OID,
956    details: CatalogTypeDetails {
957        typ: CatalogType::Array {
958            element_reference: TYPE_UUID.name,
959        },
960        array_id: None,
961        pg_metadata: Some(CatalogTypePgMetadata {
962            typinput_oid: 750,
963            typreceive_oid: 2400,
964        }),
965    },
966};
967
968pub const TYPE_JSONB: BuiltinType<NameReference> = BuiltinType {
969    name: "jsonb",
970    schema: PG_CATALOG_SCHEMA,
971    oid: oid::TYPE_JSONB_OID,
972    details: CatalogTypeDetails {
973        typ: CatalogType::Jsonb,
974        array_id: None,
975        pg_metadata: Some(CatalogTypePgMetadata {
976            typinput_oid: 3806,
977            typreceive_oid: 3805,
978        }),
979    },
980};
981
982pub const TYPE_JSONB_ARRAY: BuiltinType<NameReference> = BuiltinType {
983    name: "_jsonb",
984    schema: PG_CATALOG_SCHEMA,
985    oid: oid::TYPE_JSONB_ARRAY_OID,
986    details: CatalogTypeDetails {
987        typ: CatalogType::Array {
988            element_reference: TYPE_JSONB.name,
989        },
990        array_id: None,
991        pg_metadata: Some(CatalogTypePgMetadata {
992            typinput_oid: 750,
993            typreceive_oid: 2400,
994        }),
995    },
996};
997
998pub const TYPE_ANY: BuiltinType<NameReference> = BuiltinType {
999    name: "any",
1000    schema: PG_CATALOG_SCHEMA,
1001    oid: oid::TYPE_ANY_OID,
1002    details: CatalogTypeDetails {
1003        typ: CatalogType::Pseudo,
1004        array_id: None,
1005        pg_metadata: Some(CatalogTypePgMetadata {
1006            typinput_oid: 2294,
1007            typreceive_oid: 0,
1008        }),
1009    },
1010};
1011
1012pub const TYPE_ANYARRAY: BuiltinType<NameReference> = BuiltinType {
1013    name: "anyarray",
1014    schema: PG_CATALOG_SCHEMA,
1015    oid: oid::TYPE_ANYARRAY_OID,
1016    details: CatalogTypeDetails {
1017        typ: CatalogType::Pseudo,
1018        array_id: None,
1019        pg_metadata: Some(CatalogTypePgMetadata {
1020            typinput_oid: 2296,
1021            typreceive_oid: 2502,
1022        }),
1023    },
1024};
1025
1026pub const TYPE_ANYELEMENT: BuiltinType<NameReference> = BuiltinType {
1027    name: "anyelement",
1028    schema: PG_CATALOG_SCHEMA,
1029    oid: oid::TYPE_ANYELEMENT_OID,
1030    details: CatalogTypeDetails {
1031        typ: CatalogType::Pseudo,
1032        array_id: None,
1033        pg_metadata: Some(CatalogTypePgMetadata {
1034            typinput_oid: 2312,
1035            typreceive_oid: 0,
1036        }),
1037    },
1038};
1039
1040pub const TYPE_ANYNONARRAY: BuiltinType<NameReference> = BuiltinType {
1041    name: "anynonarray",
1042    schema: PG_CATALOG_SCHEMA,
1043    oid: oid::TYPE_ANYNONARRAY_OID,
1044    details: CatalogTypeDetails {
1045        typ: CatalogType::Pseudo,
1046        array_id: None,
1047        pg_metadata: Some(CatalogTypePgMetadata {
1048            typinput_oid: 2777,
1049            typreceive_oid: 0,
1050        }),
1051    },
1052};
1053
1054pub const TYPE_ANYRANGE: BuiltinType<NameReference> = BuiltinType {
1055    name: "anyrange",
1056    schema: PG_CATALOG_SCHEMA,
1057    oid: oid::TYPE_ANYRANGE_OID,
1058    details: CatalogTypeDetails {
1059        typ: CatalogType::Pseudo,
1060        array_id: None,
1061        pg_metadata: Some(CatalogTypePgMetadata {
1062            typinput_oid: 3832,
1063            typreceive_oid: 0,
1064        }),
1065    },
1066};
1067
1068pub const TYPE_CHAR: BuiltinType<NameReference> = BuiltinType {
1069    name: "char",
1070    schema: PG_CATALOG_SCHEMA,
1071    oid: oid::TYPE_CHAR_OID,
1072    details: CatalogTypeDetails {
1073        typ: CatalogType::PgLegacyChar,
1074        array_id: None,
1075        pg_metadata: Some(CatalogTypePgMetadata {
1076            typinput_oid: 1245,
1077            typreceive_oid: 2434,
1078        }),
1079    },
1080};
1081
1082pub const TYPE_VARCHAR: BuiltinType<NameReference> = BuiltinType {
1083    name: "varchar",
1084    schema: PG_CATALOG_SCHEMA,
1085    oid: oid::TYPE_VARCHAR_OID,
1086    details: CatalogTypeDetails {
1087        typ: CatalogType::VarChar,
1088        array_id: None,
1089        pg_metadata: Some(CatalogTypePgMetadata {
1090            typinput_oid: 1046,
1091            typreceive_oid: 2432,
1092        }),
1093    },
1094};
1095
1096pub const TYPE_INT2: BuiltinType<NameReference> = BuiltinType {
1097    name: "int2",
1098    schema: PG_CATALOG_SCHEMA,
1099    oid: oid::TYPE_INT2_OID,
1100    details: CatalogTypeDetails {
1101        typ: CatalogType::Int16,
1102        array_id: None,
1103        pg_metadata: Some(CatalogTypePgMetadata {
1104            typinput_oid: 38,
1105            typreceive_oid: 2404,
1106        }),
1107    },
1108};
1109
1110pub const TYPE_INT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1111    name: "_int2",
1112    schema: PG_CATALOG_SCHEMA,
1113    oid: oid::TYPE_INT2_ARRAY_OID,
1114    details: CatalogTypeDetails {
1115        typ: CatalogType::Array {
1116            element_reference: TYPE_INT2.name,
1117        },
1118        array_id: None,
1119        pg_metadata: Some(CatalogTypePgMetadata {
1120            typinput_oid: 750,
1121            typreceive_oid: 2400,
1122        }),
1123    },
1124};
1125
1126pub const TYPE_BPCHAR: BuiltinType<NameReference> = BuiltinType {
1127    name: "bpchar",
1128    schema: PG_CATALOG_SCHEMA,
1129    oid: oid::TYPE_BPCHAR_OID,
1130    details: CatalogTypeDetails {
1131        typ: CatalogType::Char,
1132        array_id: None,
1133        pg_metadata: Some(CatalogTypePgMetadata {
1134            typinput_oid: 1044,
1135            typreceive_oid: 2430,
1136        }),
1137    },
1138};
1139
1140pub const TYPE_CHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1141    name: "_char",
1142    schema: PG_CATALOG_SCHEMA,
1143    oid: oid::TYPE_CHAR_ARRAY_OID,
1144    details: CatalogTypeDetails {
1145        typ: CatalogType::Array {
1146            element_reference: TYPE_CHAR.name,
1147        },
1148        array_id: None,
1149        pg_metadata: Some(CatalogTypePgMetadata {
1150            typinput_oid: 750,
1151            typreceive_oid: 2400,
1152        }),
1153    },
1154};
1155
1156pub const TYPE_VARCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1157    name: "_varchar",
1158    schema: PG_CATALOG_SCHEMA,
1159    oid: oid::TYPE_VARCHAR_ARRAY_OID,
1160    details: CatalogTypeDetails {
1161        typ: CatalogType::Array {
1162            element_reference: TYPE_VARCHAR.name,
1163        },
1164        array_id: None,
1165        pg_metadata: Some(CatalogTypePgMetadata {
1166            typinput_oid: 750,
1167            typreceive_oid: 2400,
1168        }),
1169    },
1170};
1171
1172pub const TYPE_BPCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1173    name: "_bpchar",
1174    schema: PG_CATALOG_SCHEMA,
1175    oid: oid::TYPE_BPCHAR_ARRAY_OID,
1176    details: CatalogTypeDetails {
1177        typ: CatalogType::Array {
1178            element_reference: TYPE_BPCHAR.name,
1179        },
1180        array_id: None,
1181        pg_metadata: Some(CatalogTypePgMetadata {
1182            typinput_oid: 750,
1183            typreceive_oid: 2400,
1184        }),
1185    },
1186};
1187
1188pub const TYPE_REGPROC: BuiltinType<NameReference> = BuiltinType {
1189    name: "regproc",
1190    schema: PG_CATALOG_SCHEMA,
1191    oid: oid::TYPE_REGPROC_OID,
1192    details: CatalogTypeDetails {
1193        typ: CatalogType::RegProc,
1194        array_id: None,
1195        pg_metadata: Some(CatalogTypePgMetadata {
1196            typinput_oid: 44,
1197            typreceive_oid: 2444,
1198        }),
1199    },
1200};
1201
1202pub const TYPE_REGPROC_ARRAY: BuiltinType<NameReference> = BuiltinType {
1203    name: "_regproc",
1204    schema: PG_CATALOG_SCHEMA,
1205    oid: oid::TYPE_REGPROC_ARRAY_OID,
1206    details: CatalogTypeDetails {
1207        typ: CatalogType::Array {
1208            element_reference: TYPE_REGPROC.name,
1209        },
1210        array_id: None,
1211        pg_metadata: Some(CatalogTypePgMetadata {
1212            typinput_oid: 750,
1213            typreceive_oid: 2400,
1214        }),
1215    },
1216};
1217
1218pub const TYPE_REGTYPE: BuiltinType<NameReference> = BuiltinType {
1219    name: "regtype",
1220    schema: PG_CATALOG_SCHEMA,
1221    oid: oid::TYPE_REGTYPE_OID,
1222    details: CatalogTypeDetails {
1223        typ: CatalogType::RegType,
1224        array_id: None,
1225        pg_metadata: Some(CatalogTypePgMetadata {
1226            typinput_oid: 2220,
1227            typreceive_oid: 2454,
1228        }),
1229    },
1230};
1231
1232pub const TYPE_REGTYPE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1233    name: "_regtype",
1234    schema: PG_CATALOG_SCHEMA,
1235    oid: oid::TYPE_REGTYPE_ARRAY_OID,
1236    details: CatalogTypeDetails {
1237        typ: CatalogType::Array {
1238            element_reference: TYPE_REGTYPE.name,
1239        },
1240        array_id: None,
1241        pg_metadata: Some(CatalogTypePgMetadata {
1242            typinput_oid: 750,
1243            typreceive_oid: 2400,
1244        }),
1245    },
1246};
1247
1248pub const TYPE_REGCLASS: BuiltinType<NameReference> = BuiltinType {
1249    name: "regclass",
1250    schema: PG_CATALOG_SCHEMA,
1251    oid: oid::TYPE_REGCLASS_OID,
1252    details: CatalogTypeDetails {
1253        typ: CatalogType::RegClass,
1254        array_id: None,
1255        pg_metadata: Some(CatalogTypePgMetadata {
1256            typinput_oid: 2218,
1257            typreceive_oid: 2452,
1258        }),
1259    },
1260};
1261
1262pub const TYPE_REGCLASS_ARRAY: BuiltinType<NameReference> = BuiltinType {
1263    name: "_regclass",
1264    schema: PG_CATALOG_SCHEMA,
1265    oid: oid::TYPE_REGCLASS_ARRAY_OID,
1266    details: CatalogTypeDetails {
1267        typ: CatalogType::Array {
1268            element_reference: TYPE_REGCLASS.name,
1269        },
1270        array_id: None,
1271        pg_metadata: Some(CatalogTypePgMetadata {
1272            typinput_oid: 750,
1273            typreceive_oid: 2400,
1274        }),
1275    },
1276};
1277
1278pub const TYPE_INT2_VECTOR: BuiltinType<NameReference> = BuiltinType {
1279    name: "int2vector",
1280    schema: PG_CATALOG_SCHEMA,
1281    oid: oid::TYPE_INT2_VECTOR_OID,
1282    details: CatalogTypeDetails {
1283        typ: CatalogType::Int2Vector,
1284        array_id: None,
1285        pg_metadata: Some(CatalogTypePgMetadata {
1286            typinput_oid: 40,
1287            typreceive_oid: 2410,
1288        }),
1289    },
1290};
1291
1292pub const TYPE_INT2_VECTOR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1293    name: "_int2vector",
1294    schema: PG_CATALOG_SCHEMA,
1295    oid: oid::TYPE_INT2_VECTOR_ARRAY_OID,
1296    details: CatalogTypeDetails {
1297        typ: CatalogType::Array {
1298            element_reference: TYPE_INT2_VECTOR.name,
1299        },
1300        array_id: None,
1301        pg_metadata: Some(CatalogTypePgMetadata {
1302            typinput_oid: 750,
1303            typreceive_oid: 2400,
1304        }),
1305    },
1306};
1307
1308pub const TYPE_ANYCOMPATIBLE: BuiltinType<NameReference> = BuiltinType {
1309    name: "anycompatible",
1310    schema: PG_CATALOG_SCHEMA,
1311    oid: oid::TYPE_ANYCOMPATIBLE_OID,
1312    details: CatalogTypeDetails {
1313        typ: CatalogType::Pseudo,
1314        array_id: None,
1315        pg_metadata: Some(CatalogTypePgMetadata {
1316            typinput_oid: 5086,
1317            typreceive_oid: 0,
1318        }),
1319    },
1320};
1321
1322pub const TYPE_ANYCOMPATIBLEARRAY: BuiltinType<NameReference> = BuiltinType {
1323    name: "anycompatiblearray",
1324    schema: PG_CATALOG_SCHEMA,
1325    oid: oid::TYPE_ANYCOMPATIBLEARRAY_OID,
1326    details: CatalogTypeDetails {
1327        typ: CatalogType::Pseudo,
1328        array_id: None,
1329        pg_metadata: Some(CatalogTypePgMetadata {
1330            typinput_oid: 5088,
1331            typreceive_oid: 5090,
1332        }),
1333    },
1334};
1335
1336pub const TYPE_ANYCOMPATIBLENONARRAY: BuiltinType<NameReference> = BuiltinType {
1337    name: "anycompatiblenonarray",
1338    schema: PG_CATALOG_SCHEMA,
1339    oid: oid::TYPE_ANYCOMPATIBLENONARRAY_OID,
1340    details: CatalogTypeDetails {
1341        typ: CatalogType::Pseudo,
1342        array_id: None,
1343        pg_metadata: Some(CatalogTypePgMetadata {
1344            typinput_oid: 5092,
1345            typreceive_oid: 0,
1346        }),
1347    },
1348};
1349
1350pub const TYPE_ANYCOMPATIBLERANGE: BuiltinType<NameReference> = BuiltinType {
1351    name: "anycompatiblerange",
1352    schema: PG_CATALOG_SCHEMA,
1353    oid: oid::TYPE_ANYCOMPATIBLERANGE_OID,
1354    details: CatalogTypeDetails {
1355        typ: CatalogType::Pseudo,
1356        array_id: None,
1357        pg_metadata: Some(CatalogTypePgMetadata {
1358            typinput_oid: 5094,
1359            typreceive_oid: 0,
1360        }),
1361    },
1362};
1363
1364pub const TYPE_LIST: BuiltinType<NameReference> = BuiltinType {
1365    name: "list",
1366    schema: MZ_CATALOG_SCHEMA,
1367    oid: mz_pgrepr::oid::TYPE_LIST_OID,
1368    details: CatalogTypeDetails {
1369        typ: CatalogType::Pseudo,
1370        array_id: None,
1371        pg_metadata: None,
1372    },
1373};
1374
1375pub const TYPE_MAP: BuiltinType<NameReference> = BuiltinType {
1376    name: "map",
1377    schema: MZ_CATALOG_SCHEMA,
1378    oid: mz_pgrepr::oid::TYPE_MAP_OID,
1379    details: CatalogTypeDetails {
1380        typ: CatalogType::Pseudo,
1381        array_id: None,
1382        pg_metadata: None,
1383    },
1384};
1385
1386pub const TYPE_ANYCOMPATIBLELIST: BuiltinType<NameReference> = BuiltinType {
1387    name: "anycompatiblelist",
1388    schema: MZ_CATALOG_SCHEMA,
1389    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLELIST_OID,
1390    details: CatalogTypeDetails {
1391        typ: CatalogType::Pseudo,
1392        array_id: None,
1393        pg_metadata: None,
1394    },
1395};
1396
1397pub const TYPE_ANYCOMPATIBLEMAP: BuiltinType<NameReference> = BuiltinType {
1398    name: "anycompatiblemap",
1399    schema: MZ_CATALOG_SCHEMA,
1400    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLEMAP_OID,
1401    details: CatalogTypeDetails {
1402        typ: CatalogType::Pseudo,
1403        array_id: None,
1404        pg_metadata: None,
1405    },
1406};
1407
1408pub const TYPE_UINT2: BuiltinType<NameReference> = BuiltinType {
1409    name: "uint2",
1410    schema: MZ_CATALOG_SCHEMA,
1411    oid: mz_pgrepr::oid::TYPE_UINT2_OID,
1412    details: CatalogTypeDetails {
1413        typ: CatalogType::UInt16,
1414        array_id: None,
1415        pg_metadata: None,
1416    },
1417};
1418
1419pub const TYPE_UINT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1420    name: "_uint2",
1421    schema: MZ_CATALOG_SCHEMA,
1422    oid: mz_pgrepr::oid::TYPE_UINT2_ARRAY_OID,
1423    details: CatalogTypeDetails {
1424        typ: CatalogType::Array {
1425            element_reference: TYPE_UINT2.name,
1426        },
1427        array_id: None,
1428        pg_metadata: None,
1429    },
1430};
1431
1432pub const TYPE_UINT4: BuiltinType<NameReference> = BuiltinType {
1433    name: "uint4",
1434    schema: MZ_CATALOG_SCHEMA,
1435    oid: mz_pgrepr::oid::TYPE_UINT4_OID,
1436    details: CatalogTypeDetails {
1437        typ: CatalogType::UInt32,
1438        array_id: None,
1439        pg_metadata: None,
1440    },
1441};
1442
1443pub const TYPE_UINT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
1444    name: "_uint4",
1445    schema: MZ_CATALOG_SCHEMA,
1446    oid: mz_pgrepr::oid::TYPE_UINT4_ARRAY_OID,
1447    details: CatalogTypeDetails {
1448        typ: CatalogType::Array {
1449            element_reference: TYPE_UINT4.name,
1450        },
1451        array_id: None,
1452        pg_metadata: None,
1453    },
1454};
1455
1456pub const TYPE_UINT8: BuiltinType<NameReference> = BuiltinType {
1457    name: "uint8",
1458    schema: MZ_CATALOG_SCHEMA,
1459    oid: mz_pgrepr::oid::TYPE_UINT8_OID,
1460    details: CatalogTypeDetails {
1461        typ: CatalogType::UInt64,
1462        array_id: None,
1463        pg_metadata: None,
1464    },
1465};
1466
1467pub const TYPE_UINT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
1468    name: "_uint8",
1469    schema: MZ_CATALOG_SCHEMA,
1470    oid: mz_pgrepr::oid::TYPE_UINT8_ARRAY_OID,
1471    details: CatalogTypeDetails {
1472        typ: CatalogType::Array {
1473            element_reference: TYPE_UINT8.name,
1474        },
1475        array_id: None,
1476        pg_metadata: None,
1477    },
1478};
1479
1480pub const TYPE_MZ_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
1481    name: "mz_timestamp",
1482    schema: MZ_CATALOG_SCHEMA,
1483    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_OID,
1484    details: CatalogTypeDetails {
1485        typ: CatalogType::MzTimestamp,
1486        array_id: None,
1487        pg_metadata: None,
1488    },
1489};
1490
1491pub const TYPE_MZ_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
1492    name: "_mz_timestamp",
1493    schema: MZ_CATALOG_SCHEMA,
1494    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_ARRAY_OID,
1495    details: CatalogTypeDetails {
1496        typ: CatalogType::Array {
1497            element_reference: TYPE_MZ_TIMESTAMP.name,
1498        },
1499        array_id: None,
1500        pg_metadata: None,
1501    },
1502};
1503
1504pub const TYPE_INT4_RANGE: BuiltinType<NameReference> = BuiltinType {
1505    name: "int4range",
1506    schema: PG_CATALOG_SCHEMA,
1507    oid: mz_pgrepr::oid::TYPE_INT4RANGE_OID,
1508    details: CatalogTypeDetails {
1509        typ: CatalogType::Range {
1510            element_reference: TYPE_INT4.name,
1511        },
1512        array_id: None,
1513        pg_metadata: Some(CatalogTypePgMetadata {
1514            typinput_oid: 3834,
1515            typreceive_oid: 3836,
1516        }),
1517    },
1518};
1519
1520pub const TYPE_INT4_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1521    name: "_int4range",
1522    schema: PG_CATALOG_SCHEMA,
1523    oid: mz_pgrepr::oid::TYPE_INT4RANGE_ARRAY_OID,
1524    details: CatalogTypeDetails {
1525        typ: CatalogType::Array {
1526            element_reference: TYPE_INT4_RANGE.name,
1527        },
1528        array_id: None,
1529        pg_metadata: Some(CatalogTypePgMetadata {
1530            typinput_oid: 750,
1531            typreceive_oid: 2400,
1532        }),
1533    },
1534};
1535
1536pub const TYPE_INT8_RANGE: BuiltinType<NameReference> = BuiltinType {
1537    name: "int8range",
1538    schema: PG_CATALOG_SCHEMA,
1539    oid: mz_pgrepr::oid::TYPE_INT8RANGE_OID,
1540    details: CatalogTypeDetails {
1541        typ: CatalogType::Range {
1542            element_reference: TYPE_INT8.name,
1543        },
1544        array_id: None,
1545        pg_metadata: Some(CatalogTypePgMetadata {
1546            typinput_oid: 3834,
1547            typreceive_oid: 3836,
1548        }),
1549    },
1550};
1551
1552pub const TYPE_INT8_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1553    name: "_int8range",
1554    schema: PG_CATALOG_SCHEMA,
1555    oid: mz_pgrepr::oid::TYPE_INT8RANGE_ARRAY_OID,
1556    details: CatalogTypeDetails {
1557        typ: CatalogType::Array {
1558            element_reference: TYPE_INT8_RANGE.name,
1559        },
1560        array_id: None,
1561        pg_metadata: Some(CatalogTypePgMetadata {
1562            typinput_oid: 750,
1563            typreceive_oid: 2400,
1564        }),
1565    },
1566};
1567
1568pub const TYPE_DATE_RANGE: BuiltinType<NameReference> = BuiltinType {
1569    name: "daterange",
1570    schema: PG_CATALOG_SCHEMA,
1571    oid: mz_pgrepr::oid::TYPE_DATERANGE_OID,
1572    details: CatalogTypeDetails {
1573        typ: CatalogType::Range {
1574            element_reference: TYPE_DATE.name,
1575        },
1576        array_id: None,
1577        pg_metadata: Some(CatalogTypePgMetadata {
1578            typinput_oid: 3834,
1579            typreceive_oid: 3836,
1580        }),
1581    },
1582};
1583
1584pub const TYPE_DATE_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1585    name: "_daterange",
1586    schema: PG_CATALOG_SCHEMA,
1587    oid: mz_pgrepr::oid::TYPE_DATERANGE_ARRAY_OID,
1588    details: CatalogTypeDetails {
1589        typ: CatalogType::Array {
1590            element_reference: TYPE_DATE_RANGE.name,
1591        },
1592        array_id: None,
1593        pg_metadata: Some(CatalogTypePgMetadata {
1594            typinput_oid: 750,
1595            typreceive_oid: 2400,
1596        }),
1597    },
1598};
1599
1600pub const TYPE_NUM_RANGE: BuiltinType<NameReference> = BuiltinType {
1601    name: "numrange",
1602    schema: PG_CATALOG_SCHEMA,
1603    oid: mz_pgrepr::oid::TYPE_NUMRANGE_OID,
1604    details: CatalogTypeDetails {
1605        typ: CatalogType::Range {
1606            element_reference: TYPE_NUMERIC.name,
1607        },
1608        array_id: None,
1609        pg_metadata: Some(CatalogTypePgMetadata {
1610            typinput_oid: 3834,
1611            typreceive_oid: 3836,
1612        }),
1613    },
1614};
1615
1616pub const TYPE_NUM_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1617    name: "_numrange",
1618    schema: PG_CATALOG_SCHEMA,
1619    oid: mz_pgrepr::oid::TYPE_NUMRANGE_ARRAY_OID,
1620    details: CatalogTypeDetails {
1621        typ: CatalogType::Array {
1622            element_reference: TYPE_NUM_RANGE.name,
1623        },
1624        array_id: None,
1625        pg_metadata: Some(CatalogTypePgMetadata {
1626            typinput_oid: 750,
1627            typreceive_oid: 2400,
1628        }),
1629    },
1630};
1631
1632pub const TYPE_TS_RANGE: BuiltinType<NameReference> = BuiltinType {
1633    name: "tsrange",
1634    schema: PG_CATALOG_SCHEMA,
1635    oid: mz_pgrepr::oid::TYPE_TSRANGE_OID,
1636    details: CatalogTypeDetails {
1637        typ: CatalogType::Range {
1638            element_reference: TYPE_TIMESTAMP.name,
1639        },
1640        array_id: None,
1641        pg_metadata: Some(CatalogTypePgMetadata {
1642            typinput_oid: 3834,
1643            typreceive_oid: 3836,
1644        }),
1645    },
1646};
1647
1648pub const TYPE_TS_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1649    name: "_tsrange",
1650    schema: PG_CATALOG_SCHEMA,
1651    oid: mz_pgrepr::oid::TYPE_TSRANGE_ARRAY_OID,
1652    details: CatalogTypeDetails {
1653        typ: CatalogType::Array {
1654            element_reference: TYPE_TS_RANGE.name,
1655        },
1656        array_id: None,
1657        pg_metadata: Some(CatalogTypePgMetadata {
1658            typinput_oid: 750,
1659            typreceive_oid: 2400,
1660        }),
1661    },
1662};
1663
1664pub const TYPE_TSTZ_RANGE: BuiltinType<NameReference> = BuiltinType {
1665    name: "tstzrange",
1666    schema: PG_CATALOG_SCHEMA,
1667    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_OID,
1668    details: CatalogTypeDetails {
1669        typ: CatalogType::Range {
1670            element_reference: TYPE_TIMESTAMPTZ.name,
1671        },
1672        array_id: None,
1673        pg_metadata: Some(CatalogTypePgMetadata {
1674            typinput_oid: 3834,
1675            typreceive_oid: 3836,
1676        }),
1677    },
1678};
1679
1680pub const TYPE_TSTZ_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1681    name: "_tstzrange",
1682    schema: PG_CATALOG_SCHEMA,
1683    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_ARRAY_OID,
1684    details: CatalogTypeDetails {
1685        typ: CatalogType::Array {
1686            element_reference: TYPE_TSTZ_RANGE.name,
1687        },
1688        array_id: None,
1689        pg_metadata: Some(CatalogTypePgMetadata {
1690            typinput_oid: 750,
1691            typreceive_oid: 2400,
1692        }),
1693    },
1694};
1695
1696pub const TYPE_MZ_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1697    name: "mz_aclitem",
1698    schema: MZ_CATALOG_SCHEMA,
1699    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_OID,
1700    details: CatalogTypeDetails {
1701        typ: CatalogType::MzAclItem,
1702        array_id: None,
1703        pg_metadata: None,
1704    },
1705};
1706
1707pub const TYPE_MZ_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1708    name: "_mz_aclitem",
1709    schema: MZ_CATALOG_SCHEMA,
1710    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_ARRAY_OID,
1711    details: CatalogTypeDetails {
1712        typ: CatalogType::Array {
1713            element_reference: TYPE_MZ_ACL_ITEM.name,
1714        },
1715        array_id: None,
1716        pg_metadata: Some(CatalogTypePgMetadata {
1717            typinput_oid: 750,
1718            typreceive_oid: 2400,
1719        }),
1720    },
1721};
1722
1723pub const TYPE_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1724    name: "aclitem",
1725    schema: PG_CATALOG_SCHEMA,
1726    oid: 1033,
1727    details: CatalogTypeDetails {
1728        typ: CatalogType::AclItem,
1729        array_id: None,
1730        pg_metadata: Some(CatalogTypePgMetadata {
1731            typinput_oid: 1031,
1732            typreceive_oid: 0,
1733        }),
1734    },
1735};
1736
1737pub const TYPE_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1738    name: "_aclitem",
1739    schema: PG_CATALOG_SCHEMA,
1740    oid: 1034,
1741    details: CatalogTypeDetails {
1742        typ: CatalogType::Array {
1743            element_reference: TYPE_ACL_ITEM.name,
1744        },
1745        array_id: None,
1746        pg_metadata: Some(CatalogTypePgMetadata {
1747            typinput_oid: 750,
1748            typreceive_oid: 2400,
1749        }),
1750    },
1751};
1752
1753pub const TYPE_INTERNAL: BuiltinType<NameReference> = BuiltinType {
1754    name: "internal",
1755    schema: PG_CATALOG_SCHEMA,
1756    oid: 2281,
1757    details: CatalogTypeDetails {
1758        typ: CatalogType::Pseudo,
1759        array_id: None,
1760        pg_metadata: Some(CatalogTypePgMetadata {
1761            typinput_oid: 2304,
1762            typreceive_oid: 0,
1763        }),
1764    },
1765};
1766
1767const PUBLIC_SELECT: MzAclItem = MzAclItem {
1768    grantee: RoleId::Public,
1769    grantor: MZ_SYSTEM_ROLE_ID,
1770    acl_mode: AclMode::SELECT,
1771};
1772
1773const SUPPORT_SELECT: MzAclItem = MzAclItem {
1774    grantee: MZ_SUPPORT_ROLE_ID,
1775    grantor: MZ_SYSTEM_ROLE_ID,
1776    acl_mode: AclMode::SELECT,
1777};
1778
1779const ANALYTICS_SELECT: MzAclItem = MzAclItem {
1780    grantee: MZ_ANALYTICS_ROLE_ID,
1781    grantor: MZ_SYSTEM_ROLE_ID,
1782    acl_mode: AclMode::SELECT,
1783};
1784
1785const MONITOR_SELECT: MzAclItem = MzAclItem {
1786    grantee: MZ_MONITOR_ROLE_ID,
1787    grantor: MZ_SYSTEM_ROLE_ID,
1788    acl_mode: AclMode::SELECT,
1789};
1790
1791const MONITOR_REDACTED_SELECT: MzAclItem = MzAclItem {
1792    grantee: MZ_MONITOR_REDACTED_ROLE_ID,
1793    grantor: MZ_SYSTEM_ROLE_ID,
1794    acl_mode: AclMode::SELECT,
1795};
1796
1797pub static MZ_DATAFLOW_OPERATORS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1798    name: "mz_dataflow_operators_per_worker",
1799    schema: MZ_INTROSPECTION_SCHEMA,
1800    oid: oid::LOG_MZ_DATAFLOW_OPERATORS_PER_WORKER_OID,
1801    variant: LogVariant::Timely(TimelyLog::Operates),
1802    access: vec![PUBLIC_SELECT],
1803});
1804
1805pub static MZ_DATAFLOW_ADDRESSES_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1806    name: "mz_dataflow_addresses_per_worker",
1807    schema: MZ_INTROSPECTION_SCHEMA,
1808    oid: oid::LOG_MZ_DATAFLOW_ADDRESSES_PER_WORKER_OID,
1809    variant: LogVariant::Timely(TimelyLog::Addresses),
1810    access: vec![PUBLIC_SELECT],
1811});
1812
1813pub static MZ_DATAFLOW_CHANNELS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1814    name: "mz_dataflow_channels_per_worker",
1815    schema: MZ_INTROSPECTION_SCHEMA,
1816    oid: oid::LOG_MZ_DATAFLOW_CHANNELS_PER_WORKER_OID,
1817    variant: LogVariant::Timely(TimelyLog::Channels),
1818    access: vec![PUBLIC_SELECT],
1819});
1820
1821pub static MZ_SCHEDULING_ELAPSED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1822    name: "mz_scheduling_elapsed_raw",
1823    schema: MZ_INTROSPECTION_SCHEMA,
1824    oid: oid::LOG_MZ_SCHEDULING_ELAPSED_RAW_OID,
1825    variant: LogVariant::Timely(TimelyLog::Elapsed),
1826    access: vec![PUBLIC_SELECT],
1827});
1828
1829pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1830    LazyLock::new(|| BuiltinLog {
1831        name: "mz_compute_operator_durations_histogram_raw",
1832        schema: MZ_INTROSPECTION_SCHEMA,
1833        oid: oid::LOG_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW_OID,
1834        variant: LogVariant::Timely(TimelyLog::Histogram),
1835        access: vec![PUBLIC_SELECT],
1836    });
1837
1838pub static MZ_SCHEDULING_PARKS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1839    name: "mz_scheduling_parks_histogram_raw",
1840    schema: MZ_INTROSPECTION_SCHEMA,
1841    oid: oid::LOG_MZ_SCHEDULING_PARKS_HISTOGRAM_RAW_OID,
1842    variant: LogVariant::Timely(TimelyLog::Parks),
1843    access: vec![PUBLIC_SELECT],
1844});
1845
1846pub static MZ_ARRANGEMENT_RECORDS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1847    name: "mz_arrangement_records_raw",
1848    schema: MZ_INTROSPECTION_SCHEMA,
1849    oid: oid::LOG_MZ_ARRANGEMENT_RECORDS_RAW_OID,
1850    variant: LogVariant::Differential(DifferentialLog::ArrangementRecords),
1851    access: vec![PUBLIC_SELECT],
1852});
1853
1854pub static MZ_ARRANGEMENT_BATCHES_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1855    name: "mz_arrangement_batches_raw",
1856    schema: MZ_INTROSPECTION_SCHEMA,
1857    oid: oid::LOG_MZ_ARRANGEMENT_BATCHES_RAW_OID,
1858    variant: LogVariant::Differential(DifferentialLog::ArrangementBatches),
1859    access: vec![PUBLIC_SELECT],
1860});
1861
1862pub static MZ_ARRANGEMENT_SHARING_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1863    name: "mz_arrangement_sharing_raw",
1864    schema: MZ_INTROSPECTION_SCHEMA,
1865    oid: oid::LOG_MZ_ARRANGEMENT_SHARING_RAW_OID,
1866    variant: LogVariant::Differential(DifferentialLog::Sharing),
1867    access: vec![PUBLIC_SELECT],
1868});
1869
1870pub static MZ_ARRANGEMENT_BATCHER_RECORDS_RAW: LazyLock<BuiltinLog> =
1871    LazyLock::new(|| BuiltinLog {
1872        name: "mz_arrangement_batcher_records_raw",
1873        schema: MZ_INTROSPECTION_SCHEMA,
1874        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_RECORDS_RAW_OID,
1875        variant: LogVariant::Differential(DifferentialLog::BatcherRecords),
1876        access: vec![PUBLIC_SELECT],
1877    });
1878
1879pub static MZ_ARRANGEMENT_BATCHER_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1880    name: "mz_arrangement_batcher_size_raw",
1881    schema: MZ_INTROSPECTION_SCHEMA,
1882    oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_SIZE_RAW_OID,
1883    variant: LogVariant::Differential(DifferentialLog::BatcherSize),
1884    access: vec![PUBLIC_SELECT],
1885});
1886
1887pub static MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW: LazyLock<BuiltinLog> =
1888    LazyLock::new(|| BuiltinLog {
1889        name: "mz_arrangement_batcher_capacity_raw",
1890        schema: MZ_INTROSPECTION_SCHEMA,
1891        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW_OID,
1892        variant: LogVariant::Differential(DifferentialLog::BatcherCapacity),
1893        access: vec![PUBLIC_SELECT],
1894    });
1895
1896pub static MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1897    LazyLock::new(|| BuiltinLog {
1898        name: "mz_arrangement_batcher_allocations_raw",
1899        schema: MZ_INTROSPECTION_SCHEMA,
1900        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW_OID,
1901        variant: LogVariant::Differential(DifferentialLog::BatcherAllocations),
1902        access: vec![PUBLIC_SELECT],
1903    });
1904
1905pub static MZ_COMPUTE_EXPORTS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1906    name: "mz_compute_exports_per_worker",
1907    schema: MZ_INTROSPECTION_SCHEMA,
1908    oid: oid::LOG_MZ_COMPUTE_EXPORTS_PER_WORKER_OID,
1909    variant: LogVariant::Compute(ComputeLog::DataflowCurrent),
1910    access: vec![PUBLIC_SELECT],
1911});
1912
1913pub static MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER: LazyLock<BuiltinLog> =
1914    LazyLock::new(|| BuiltinLog {
1915        name: "mz_compute_dataflow_global_ids_per_worker",
1916        schema: MZ_INTROSPECTION_SCHEMA,
1917        oid: oid::LOG_MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER_OID,
1918        variant: LogVariant::Compute(ComputeLog::DataflowGlobal),
1919        access: vec![PUBLIC_SELECT],
1920    });
1921
1922pub static MZ_COMPUTE_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1923    name: "mz_compute_frontiers_per_worker",
1924    schema: MZ_INTROSPECTION_SCHEMA,
1925    oid: oid::LOG_MZ_COMPUTE_FRONTIERS_PER_WORKER_OID,
1926    variant: LogVariant::Compute(ComputeLog::FrontierCurrent),
1927    access: vec![PUBLIC_SELECT],
1928});
1929
1930pub static MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> =
1931    LazyLock::new(|| BuiltinLog {
1932        name: "mz_compute_import_frontiers_per_worker",
1933        schema: MZ_INTROSPECTION_SCHEMA,
1934        oid: oid::LOG_MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER_OID,
1935        variant: LogVariant::Compute(ComputeLog::ImportFrontierCurrent),
1936        access: vec![PUBLIC_SELECT],
1937    });
1938
1939pub static MZ_COMPUTE_ERROR_COUNTS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1940    name: "mz_compute_error_counts_raw",
1941    schema: MZ_INTROSPECTION_SCHEMA,
1942    oid: oid::LOG_MZ_COMPUTE_ERROR_COUNTS_RAW_OID,
1943    variant: LogVariant::Compute(ComputeLog::ErrorCount),
1944    access: vec![PUBLIC_SELECT],
1945});
1946
1947pub static MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER: LazyLock<BuiltinLog> =
1948    LazyLock::new(|| BuiltinLog {
1949        name: "mz_compute_hydration_times_per_worker",
1950        schema: MZ_INTROSPECTION_SCHEMA,
1951        oid: oid::LOG_MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER_OID,
1952        variant: LogVariant::Compute(ComputeLog::HydrationTime),
1953        access: vec![PUBLIC_SELECT],
1954    });
1955
1956pub static MZ_ACTIVE_PEEKS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1957    name: "mz_active_peeks_per_worker",
1958    schema: MZ_INTROSPECTION_SCHEMA,
1959    oid: oid::LOG_MZ_ACTIVE_PEEKS_PER_WORKER_OID,
1960    variant: LogVariant::Compute(ComputeLog::PeekCurrent),
1961    access: vec![PUBLIC_SELECT],
1962});
1963
1964pub static MZ_COMPUTE_LIR_MAPPING_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1965    name: "mz_compute_lir_mapping_per_worker",
1966    schema: MZ_INTROSPECTION_SCHEMA,
1967    oid: oid::LOG_MZ_COMPUTE_LIR_MAPPING_PER_WORKER_OID,
1968    variant: LogVariant::Compute(ComputeLog::LirMapping),
1969    access: vec![PUBLIC_SELECT],
1970});
1971
1972pub static MZ_PEEK_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1973    name: "mz_peek_durations_histogram_raw",
1974    schema: MZ_INTROSPECTION_SCHEMA,
1975    oid: oid::LOG_MZ_PEEK_DURATIONS_HISTOGRAM_RAW_OID,
1976    variant: LogVariant::Compute(ComputeLog::PeekDuration),
1977    access: vec![PUBLIC_SELECT],
1978});
1979
1980pub static MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1981    LazyLock::new(|| BuiltinLog {
1982        name: "mz_dataflow_shutdown_durations_histogram_raw",
1983        schema: MZ_INTROSPECTION_SCHEMA,
1984        oid: oid::LOG_MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_RAW_OID,
1985        variant: LogVariant::Compute(ComputeLog::ShutdownDuration),
1986        access: vec![PUBLIC_SELECT],
1987    });
1988
1989pub static MZ_ARRANGEMENT_HEAP_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1990    name: "mz_arrangement_heap_size_raw",
1991    schema: MZ_INTROSPECTION_SCHEMA,
1992    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_SIZE_RAW_OID,
1993    variant: LogVariant::Compute(ComputeLog::ArrangementHeapSize),
1994    access: vec![PUBLIC_SELECT],
1995});
1996
1997pub static MZ_ARRANGEMENT_HEAP_CAPACITY_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1998    name: "mz_arrangement_heap_capacity_raw",
1999    schema: MZ_INTROSPECTION_SCHEMA,
2000    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_CAPACITY_RAW_OID,
2001    variant: LogVariant::Compute(ComputeLog::ArrangementHeapCapacity),
2002    access: vec![PUBLIC_SELECT],
2003});
2004
2005pub static MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
2006    LazyLock::new(|| BuiltinLog {
2007        name: "mz_arrangement_heap_allocations_raw",
2008        schema: MZ_INTROSPECTION_SCHEMA,
2009        oid: oid::LOG_MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW_OID,
2010        variant: LogVariant::Compute(ComputeLog::ArrangementHeapAllocations),
2011        access: vec![PUBLIC_SELECT],
2012    });
2013
2014pub static MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> =
2015    LazyLock::new(|| BuiltinLog {
2016        name: "mz_message_batch_counts_received_raw",
2017        schema: MZ_INTROSPECTION_SCHEMA,
2018        oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW_OID,
2019        variant: LogVariant::Timely(TimelyLog::BatchesReceived),
2020        access: vec![PUBLIC_SELECT],
2021    });
2022
2023pub static MZ_MESSAGE_BATCH_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2024    name: "mz_message_batch_counts_sent_raw",
2025    schema: MZ_INTROSPECTION_SCHEMA,
2026    oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_SENT_RAW_OID,
2027    variant: LogVariant::Timely(TimelyLog::BatchesSent),
2028    access: vec![PUBLIC_SELECT],
2029});
2030
2031pub static MZ_MESSAGE_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2032    name: "mz_message_counts_received_raw",
2033    schema: MZ_INTROSPECTION_SCHEMA,
2034    oid: oid::LOG_MZ_MESSAGE_COUNTS_RECEIVED_RAW_OID,
2035    variant: LogVariant::Timely(TimelyLog::MessagesReceived),
2036    access: vec![PUBLIC_SELECT],
2037});
2038
2039pub static MZ_MESSAGE_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2040    name: "mz_message_counts_sent_raw",
2041    schema: MZ_INTROSPECTION_SCHEMA,
2042    oid: oid::LOG_MZ_MESSAGE_COUNTS_SENT_RAW_OID,
2043    variant: LogVariant::Timely(TimelyLog::MessagesSent),
2044    access: vec![PUBLIC_SELECT],
2045});
2046
2047pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW: LazyLock<BuiltinLog> =
2048    LazyLock::new(|| BuiltinLog {
2049        name: "mz_dataflow_operator_reachability_raw",
2050        schema: MZ_INTROSPECTION_SCHEMA,
2051        oid: oid::LOG_MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW_OID,
2052        variant: LogVariant::Timely(TimelyLog::Reachability),
2053        access: vec![PUBLIC_SELECT],
2054    });
2055
2056pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2057    name: "mz_kafka_sinks",
2058    schema: MZ_CATALOG_SCHEMA,
2059    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2060    desc: RelationDesc::builder()
2061        .with_column("id", ScalarType::String.nullable(false))
2062        .with_column("topic", ScalarType::String.nullable(false))
2063        .with_key(vec![0])
2064        .finish(),
2065    column_comments: BTreeMap::from_iter([
2066        ("id", "The ID of the sink."),
2067        (
2068            "topic",
2069            "The name of the Kafka topic into which the sink is writing.",
2070        ),
2071    ]),
2072    is_retained_metrics_object: false,
2073    access: vec![PUBLIC_SELECT],
2074});
2075pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2076    name: "mz_kafka_connections",
2077    schema: MZ_CATALOG_SCHEMA,
2078    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2079    desc: RelationDesc::builder()
2080        .with_column("id", ScalarType::String.nullable(false))
2081        .with_column(
2082            "brokers",
2083            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
2084        )
2085        .with_column("sink_progress_topic", ScalarType::String.nullable(false))
2086        .finish(),
2087    column_comments: BTreeMap::from_iter([
2088        ("id", "The ID of the connection."),
2089        (
2090            "brokers",
2091            "The addresses of the Kafka brokers to connect to.",
2092        ),
2093        (
2094            "sink_progress_topic",
2095            "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.",
2096        ),
2097    ]),
2098    is_retained_metrics_object: false,
2099    access: vec![PUBLIC_SELECT],
2100});
2101pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2102    name: "mz_kafka_sources",
2103    schema: MZ_CATALOG_SCHEMA,
2104    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2105    desc: RelationDesc::builder()
2106        .with_column("id", ScalarType::String.nullable(false))
2107        .with_column("group_id_prefix", ScalarType::String.nullable(false))
2108        .with_column("topic", ScalarType::String.nullable(false))
2109        .finish(),
2110    column_comments: BTreeMap::from_iter([
2111        (
2112            "id",
2113            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2114        ),
2115        (
2116            "group_id_prefix",
2117            "The value of the `GROUP ID PREFIX` connection option.",
2118        ),
2119        (
2120            "topic",
2121            "The name of the Kafka topic the source is reading from.",
2122        ),
2123    ]),
2124    is_retained_metrics_object: false,
2125    access: vec![PUBLIC_SELECT],
2126});
2127pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2128    name: "mz_postgres_sources",
2129    schema: MZ_INTERNAL_SCHEMA,
2130    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2131    desc: RelationDesc::builder()
2132        .with_column("id", ScalarType::String.nullable(false))
2133        .with_column("replication_slot", ScalarType::String.nullable(false))
2134        .with_column("timeline_id", ScalarType::UInt64.nullable(true))
2135        .finish(),
2136    column_comments: BTreeMap::from_iter([
2137        (
2138            "id",
2139            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2140        ),
2141        (
2142            "replication_slot",
2143            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2144        ),
2145        (
2146            "timeline_id",
2147            "The PostgreSQL timeline ID determined on source creation.",
2148        ),
2149    ]),
2150    is_retained_metrics_object: false,
2151    access: vec![PUBLIC_SELECT],
2152});
2153pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2154    name: "mz_postgres_source_tables",
2155    schema: MZ_INTERNAL_SCHEMA,
2156    oid: oid::TABLE_MZ_POSTGRES_SOURCE_TABLES_OID,
2157    desc: RelationDesc::builder()
2158        .with_column("id", ScalarType::String.nullable(false))
2159        .with_column("schema_name", ScalarType::String.nullable(false))
2160        .with_column("table_name", ScalarType::String.nullable(false))
2161        .finish(),
2162    column_comments: BTreeMap::from_iter([
2163        (
2164            "id",
2165            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2166        ),
2167        (
2168            "schema_name",
2169            "The schema of the upstream table being ingested.",
2170        ),
2171        (
2172            "table_name",
2173            "The name of the upstream table being ingested.",
2174        ),
2175    ]),
2176    is_retained_metrics_object: true,
2177    access: vec![PUBLIC_SELECT],
2178});
2179pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2180    name: "mz_mysql_source_tables",
2181    schema: MZ_INTERNAL_SCHEMA,
2182    oid: oid::TABLE_MZ_MYSQL_SOURCE_TABLES_OID,
2183    desc: RelationDesc::builder()
2184        .with_column("id", ScalarType::String.nullable(false))
2185        .with_column("schema_name", ScalarType::String.nullable(false))
2186        .with_column("table_name", ScalarType::String.nullable(false))
2187        .finish(),
2188    column_comments: BTreeMap::from_iter([
2189        (
2190            "id",
2191            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2192        ),
2193        (
2194            "schema_name",
2195            "The schema (or, database) of the upstream table being ingested.",
2196        ),
2197        (
2198            "table_name",
2199            "The name of the upstream table being ingested.",
2200        ),
2201    ]),
2202    is_retained_metrics_object: true,
2203    access: vec![PUBLIC_SELECT],
2204});
2205pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2206    name: "mz_sql_server_source_tables",
2207    schema: MZ_INTERNAL_SCHEMA,
2208    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2209    desc: RelationDesc::builder()
2210        .with_column("id", ScalarType::String.nullable(false))
2211        .with_column("schema_name", ScalarType::String.nullable(false))
2212        .with_column("table_name", ScalarType::String.nullable(false))
2213        .finish(),
2214    column_comments: BTreeMap::from_iter([
2215        (
2216            "id",
2217            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2218        ),
2219        (
2220            "schema_name",
2221            "The schema (or, database) of the upstream table being ingested.",
2222        ),
2223        (
2224            "table_name",
2225            "The name of the upstream table being ingested.",
2226        ),
2227    ]),
2228    is_retained_metrics_object: true,
2229    access: vec![PUBLIC_SELECT],
2230});
2231pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2232    name: "mz_kafka_source_tables",
2233    schema: MZ_INTERNAL_SCHEMA,
2234    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2235    desc: RelationDesc::builder()
2236        .with_column("id", ScalarType::String.nullable(false))
2237        .with_column("topic", ScalarType::String.nullable(false))
2238        .with_column("envelope_type", ScalarType::String.nullable(true))
2239        .with_column("key_format", ScalarType::String.nullable(true))
2240        .with_column("value_format", ScalarType::String.nullable(true))
2241        .finish(),
2242    column_comments: BTreeMap::from_iter([
2243        (
2244            "id",
2245            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2246        ),
2247        ("topic", "The topic being ingested."),
2248        (
2249            "envelope_type",
2250            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2251        ),
2252        (
2253            "key_format",
2254            "The format of the Kafka message key: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2255        ),
2256        (
2257            "value_format",
2258            "The format of the Kafka message value: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2259        ),
2260    ]),
2261    is_retained_metrics_object: true,
2262    access: vec![PUBLIC_SELECT],
2263});
2264pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2265    name: "mz_object_dependencies",
2266    schema: MZ_INTERNAL_SCHEMA,
2267    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2268    desc: RelationDesc::builder()
2269        .with_column("object_id", ScalarType::String.nullable(false))
2270        .with_column("referenced_object_id", ScalarType::String.nullable(false))
2271        .finish(),
2272    column_comments: BTreeMap::from_iter([
2273        (
2274            "object_id",
2275            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2276        ),
2277        (
2278            "referenced_object_id",
2279            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2280        ),
2281    ]),
2282    is_retained_metrics_object: true,
2283    access: vec![PUBLIC_SELECT],
2284});
2285pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2286    name: "mz_compute_dependencies",
2287    schema: MZ_INTERNAL_SCHEMA,
2288    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2289    data_source: IntrospectionType::ComputeDependencies,
2290    desc: RelationDesc::builder()
2291        .with_column("object_id", ScalarType::String.nullable(false))
2292        .with_column("dependency_id", ScalarType::String.nullable(false))
2293        .finish(),
2294    column_comments: BTreeMap::from_iter([
2295        (
2296            "object_id",
2297            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2298        ),
2299        (
2300            "dependency_id",
2301            "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`.",
2302        ),
2303    ]),
2304    is_retained_metrics_object: false,
2305    access: vec![PUBLIC_SELECT],
2306});
2307pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER: LazyLock<BuiltinSource> =
2308    LazyLock::new(|| BuiltinSource {
2309        name: "mz_compute_operator_hydration_statuses_per_worker",
2310        schema: MZ_INTERNAL_SCHEMA,
2311        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER_OID,
2312        data_source: IntrospectionType::ComputeOperatorHydrationStatus,
2313        desc: RelationDesc::builder()
2314            .with_column("object_id", ScalarType::String.nullable(false))
2315            .with_column("physical_plan_node_id", ScalarType::UInt64.nullable(false))
2316            .with_column("replica_id", ScalarType::String.nullable(false))
2317            .with_column("worker_id", ScalarType::UInt64.nullable(false))
2318            .with_column("hydrated", ScalarType::Bool.nullable(false))
2319            .finish(),
2320        column_comments: BTreeMap::new(),
2321        is_retained_metrics_object: false,
2322        access: vec![PUBLIC_SELECT],
2323    });
2324
2325pub static MZ_DATABASES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2326    name: "mz_databases",
2327    schema: MZ_CATALOG_SCHEMA,
2328    oid: oid::TABLE_MZ_DATABASES_OID,
2329    desc: RelationDesc::builder()
2330        .with_column("id", ScalarType::String.nullable(false))
2331        .with_column("oid", ScalarType::Oid.nullable(false))
2332        .with_column("name", ScalarType::String.nullable(false))
2333        .with_column("owner_id", ScalarType::String.nullable(false))
2334        .with_column(
2335            "privileges",
2336            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2337        )
2338        .with_key(vec![0])
2339        .with_key(vec![1])
2340        .finish(),
2341    column_comments: BTreeMap::from_iter([
2342        ("id", "Materialize's unique ID for the database."),
2343        (
2344            "oid",
2345            "A [PostgreSQL-compatible OID][`oid`] for the database.",
2346        ),
2347        ("name", "The name of the database."),
2348        (
2349            "owner_id",
2350            "The role ID of the owner of the database. Corresponds to `mz_roles.id`.",
2351        ),
2352        ("privileges", "The privileges belonging to the database."),
2353    ]),
2354    is_retained_metrics_object: false,
2355    access: vec![PUBLIC_SELECT],
2356});
2357pub static MZ_SCHEMAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2358    name: "mz_schemas",
2359    schema: MZ_CATALOG_SCHEMA,
2360    oid: oid::TABLE_MZ_SCHEMAS_OID,
2361    desc: RelationDesc::builder()
2362        .with_column("id", ScalarType::String.nullable(false))
2363        .with_column("oid", ScalarType::Oid.nullable(false))
2364        .with_column("database_id", ScalarType::String.nullable(true))
2365        .with_column("name", ScalarType::String.nullable(false))
2366        .with_column("owner_id", ScalarType::String.nullable(false))
2367        .with_column(
2368            "privileges",
2369            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2370        )
2371        .with_key(vec![0])
2372        .with_key(vec![1])
2373        .finish(),
2374    column_comments: BTreeMap::from_iter([
2375        ("id", "Materialize's unique ID for the schema."),
2376        (
2377            "oid",
2378            "A [PostgreSQL-compatible oid][`oid`] for the schema.",
2379        ),
2380        (
2381            "database_id",
2382            "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2383        ),
2384        ("name", "The name of the schema."),
2385        (
2386            "owner_id",
2387            "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2388        ),
2389        ("privileges", "The privileges belonging to the schema."),
2390    ]),
2391    is_retained_metrics_object: false,
2392    access: vec![PUBLIC_SELECT],
2393});
2394pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2395    name: "mz_columns",
2396    schema: MZ_CATALOG_SCHEMA,
2397    oid: oid::TABLE_MZ_COLUMNS_OID,
2398    desc: RelationDesc::builder()
2399        .with_column("id", ScalarType::String.nullable(false)) // not a key
2400        .with_column("name", ScalarType::String.nullable(false))
2401        .with_column("position", ScalarType::UInt64.nullable(false))
2402        .with_column("nullable", ScalarType::Bool.nullable(false))
2403        .with_column("type", ScalarType::String.nullable(false))
2404        .with_column("default", ScalarType::String.nullable(true))
2405        .with_column("type_oid", ScalarType::Oid.nullable(false))
2406        .with_column("type_mod", ScalarType::Int32.nullable(false))
2407        .finish(),
2408    column_comments: BTreeMap::from_iter([
2409        (
2410            "id",
2411            "The unique ID of the table, source, or view containing the column.",
2412        ),
2413        ("name", "The name of the column."),
2414        (
2415            "position",
2416            "The 1-indexed position of the column in its containing table, source, or view.",
2417        ),
2418        ("nullable", "Can the column contain a `NULL` value?"),
2419        ("type", "The data type of the column."),
2420        ("default", "The default expression of the column."),
2421        (
2422            "type_oid",
2423            "The OID of the type of the column (references `mz_types`).",
2424        ),
2425        ("type_mod", "The packed type identifier of the column."),
2426    ]),
2427    is_retained_metrics_object: false,
2428    access: vec![PUBLIC_SELECT],
2429});
2430pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2431    name: "mz_indexes",
2432    schema: MZ_CATALOG_SCHEMA,
2433    oid: oid::TABLE_MZ_INDEXES_OID,
2434    desc: RelationDesc::builder()
2435        .with_column("id", ScalarType::String.nullable(false))
2436        .with_column("oid", ScalarType::Oid.nullable(false))
2437        .with_column("name", ScalarType::String.nullable(false))
2438        .with_column("on_id", ScalarType::String.nullable(false))
2439        .with_column("cluster_id", ScalarType::String.nullable(false))
2440        .with_column("owner_id", ScalarType::String.nullable(false))
2441        .with_column("create_sql", ScalarType::String.nullable(false))
2442        .with_column("redacted_create_sql", ScalarType::String.nullable(false))
2443        .with_key(vec![0])
2444        .with_key(vec![1])
2445        .finish(),
2446    column_comments: BTreeMap::from_iter([
2447        ("id", "Materialize's unique ID for the index."),
2448        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the index."),
2449        ("name", "The name of the index."),
2450        (
2451            "on_id",
2452            "The ID of the relation on which the index is built.",
2453        ),
2454        (
2455            "cluster_id",
2456            "The ID of the cluster in which the index is built.",
2457        ),
2458        (
2459            "owner_id",
2460            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2461        ),
2462        ("create_sql", "The `CREATE` SQL statement for the index."),
2463        (
2464            "redacted_create_sql",
2465            "The redacted `CREATE` SQL statement for the index.",
2466        ),
2467    ]),
2468    is_retained_metrics_object: false,
2469    access: vec![PUBLIC_SELECT],
2470});
2471pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2472    name: "mz_index_columns",
2473    schema: MZ_CATALOG_SCHEMA,
2474    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2475    desc: RelationDesc::builder()
2476        .with_column("index_id", ScalarType::String.nullable(false))
2477        .with_column("index_position", ScalarType::UInt64.nullable(false))
2478        .with_column("on_position", ScalarType::UInt64.nullable(true))
2479        .with_column("on_expression", ScalarType::String.nullable(true))
2480        .with_column("nullable", ScalarType::Bool.nullable(false))
2481        .finish(),
2482    column_comments: BTreeMap::from_iter([
2483        (
2484            "index_id",
2485            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2486        ),
2487        (
2488            "index_position",
2489            "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.)",
2490        ),
2491        (
2492            "on_position",
2493            "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.",
2494        ),
2495        (
2496            "on_expression",
2497            "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.",
2498        ),
2499        (
2500            "nullable",
2501            "Can this column of the index evaluate to `NULL`?",
2502        ),
2503    ]),
2504    is_retained_metrics_object: false,
2505    access: vec![PUBLIC_SELECT],
2506});
2507pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2508    name: "mz_tables",
2509    schema: MZ_CATALOG_SCHEMA,
2510    oid: oid::TABLE_MZ_TABLES_OID,
2511    desc: RelationDesc::builder()
2512        .with_column("id", ScalarType::String.nullable(false))
2513        .with_column("oid", ScalarType::Oid.nullable(false))
2514        .with_column("schema_id", ScalarType::String.nullable(false))
2515        .with_column("name", ScalarType::String.nullable(false))
2516        .with_column("owner_id", ScalarType::String.nullable(false))
2517        .with_column(
2518            "privileges",
2519            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2520        )
2521        .with_column("create_sql", ScalarType::String.nullable(true))
2522        .with_column("redacted_create_sql", ScalarType::String.nullable(true))
2523        .with_column("source_id", ScalarType::String.nullable(true))
2524        .with_key(vec![0])
2525        .with_key(vec![1])
2526        .finish(),
2527    column_comments: BTreeMap::from_iter([
2528        ("id", "Materialize's unique ID for the table."),
2529        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the table."),
2530        (
2531            "schema_id",
2532            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2533        ),
2534        ("name", "The name of the table."),
2535        (
2536            "owner_id",
2537            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2538        ),
2539        ("privileges", "The privileges belonging to the table."),
2540        ("create_sql", "The `CREATE` SQL statement for the table."),
2541        (
2542            "redacted_create_sql",
2543            "The redacted `CREATE` SQL statement for the table.",
2544        ),
2545        (
2546            "source_id",
2547            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2548        ),
2549    ]),
2550    is_retained_metrics_object: true,
2551    access: vec![PUBLIC_SELECT],
2552});
2553pub static MZ_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2554    name: "mz_connections",
2555    schema: MZ_CATALOG_SCHEMA,
2556    oid: oid::TABLE_MZ_CONNECTIONS_OID,
2557    desc: RelationDesc::builder()
2558        .with_column("id", ScalarType::String.nullable(false))
2559        .with_column("oid", ScalarType::Oid.nullable(false))
2560        .with_column("schema_id", ScalarType::String.nullable(false))
2561        .with_column("name", ScalarType::String.nullable(false))
2562        .with_column("type", ScalarType::String.nullable(false))
2563        .with_column("owner_id", ScalarType::String.nullable(false))
2564        .with_column(
2565            "privileges",
2566            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2567        )
2568        .with_column("create_sql", ScalarType::String.nullable(false))
2569        .with_column("redacted_create_sql", ScalarType::String.nullable(false))
2570        .with_key(vec![0])
2571        .with_key(vec![1])
2572        .finish(),
2573    column_comments: BTreeMap::from_iter([
2574        ("id", "The unique ID of the connection."),
2575        (
2576            "oid",
2577            "A [PostgreSQL-compatible OID][`oid`] for the connection.",
2578        ),
2579        (
2580            "schema_id",
2581            "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2582        ),
2583        ("name", "The name of the connection."),
2584        (
2585            "type",
2586            "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2587        ),
2588        (
2589            "owner_id",
2590            "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2591        ),
2592        ("privileges", "The privileges belonging to the connection."),
2593        (
2594            "create_sql",
2595            "The `CREATE` SQL statement for the connection.",
2596        ),
2597        (
2598            "redacted_create_sql",
2599            "The redacted `CREATE` SQL statement for the connection.",
2600        ),
2601    ]),
2602    is_retained_metrics_object: false,
2603    access: vec![PUBLIC_SELECT],
2604});
2605pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2606    name: "mz_ssh_tunnel_connections",
2607    schema: MZ_CATALOG_SCHEMA,
2608    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2609    desc: RelationDesc::builder()
2610        .with_column("id", ScalarType::String.nullable(false))
2611        .with_column("public_key_1", ScalarType::String.nullable(false))
2612        .with_column("public_key_2", ScalarType::String.nullable(false))
2613        .finish(),
2614    column_comments: BTreeMap::from_iter([
2615        ("id", "The ID of the connection."),
2616        (
2617            "public_key_1",
2618            "The first public key associated with the SSH tunnel.",
2619        ),
2620        (
2621            "public_key_2",
2622            "The second public key associated with the SSH tunnel.",
2623        ),
2624    ]),
2625    is_retained_metrics_object: false,
2626    access: vec![PUBLIC_SELECT],
2627});
2628pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2629    name: "mz_sources",
2630    schema: MZ_CATALOG_SCHEMA,
2631    oid: oid::TABLE_MZ_SOURCES_OID,
2632    desc: RelationDesc::builder()
2633        .with_column("id", ScalarType::String.nullable(false))
2634        .with_column("oid", ScalarType::Oid.nullable(false))
2635        .with_column("schema_id", ScalarType::String.nullable(false))
2636        .with_column("name", ScalarType::String.nullable(false))
2637        .with_column("type", ScalarType::String.nullable(false))
2638        .with_column("connection_id", ScalarType::String.nullable(true))
2639        .with_column("size", ScalarType::String.nullable(true))
2640        .with_column("envelope_type", ScalarType::String.nullable(true))
2641        .with_column("key_format", ScalarType::String.nullable(true))
2642        .with_column("value_format", ScalarType::String.nullable(true))
2643        .with_column("cluster_id", ScalarType::String.nullable(true))
2644        .with_column("owner_id", ScalarType::String.nullable(false))
2645        .with_column(
2646            "privileges",
2647            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2648        )
2649        .with_column("create_sql", ScalarType::String.nullable(true))
2650        .with_column("redacted_create_sql", ScalarType::String.nullable(true))
2651        .with_key(vec![0])
2652        .with_key(vec![1])
2653        .finish(),
2654    column_comments: BTreeMap::from_iter([
2655        ("id", "Materialize's unique ID for the source."),
2656        (
2657            "oid",
2658            "A [PostgreSQL-compatible OID][`oid`] for the source.",
2659        ),
2660        (
2661            "schema_id",
2662            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2663        ),
2664        ("name", "The name of the source."),
2665        (
2666            "type",
2667            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2668        ),
2669        (
2670            "connection_id",
2671            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2672        ),
2673        ("size", "Deprecated The size of the source."),
2674        (
2675            "envelope_type",
2676            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2677        ),
2678        (
2679            "key_format",
2680            "For Kafka sources, the format of the Kafka message key: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2681        ),
2682        (
2683            "value_format",
2684            "For Kafka sources, the format of the Kafka message value: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2685        ),
2686        (
2687            "cluster_id",
2688            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2689        ),
2690        (
2691            "owner_id",
2692            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2693        ),
2694        ("privileges", "The privileges granted on the source."),
2695        ("create_sql", "The `CREATE` SQL statement for the source."),
2696        (
2697            "redacted_create_sql",
2698            "The redacted `CREATE` SQL statement for the source.",
2699        ),
2700    ]),
2701    is_retained_metrics_object: true,
2702    access: vec![PUBLIC_SELECT],
2703});
2704pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2705    BuiltinTable {
2706        name: "mz_sinks",
2707        schema: MZ_CATALOG_SCHEMA,
2708        oid: oid::TABLE_MZ_SINKS_OID,
2709        desc: RelationDesc::builder()
2710            .with_column("id", ScalarType::String.nullable(false))
2711            .with_column("oid", ScalarType::Oid.nullable(false))
2712            .with_column("schema_id", ScalarType::String.nullable(false))
2713            .with_column("name", ScalarType::String.nullable(false))
2714            .with_column("type", ScalarType::String.nullable(false))
2715            .with_column("connection_id", ScalarType::String.nullable(true))
2716            .with_column("size", ScalarType::String.nullable(true))
2717            .with_column("envelope_type", ScalarType::String.nullable(true))
2718            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2719            // below. This should be removed in the future.
2720            .with_column("format", ScalarType::String.nullable(false))
2721            .with_column("key_format", ScalarType::String.nullable(true))
2722            .with_column("value_format", ScalarType::String.nullable(false))
2723            .with_column("cluster_id", ScalarType::String.nullable(false))
2724            .with_column("owner_id", ScalarType::String.nullable(false))
2725            .with_column("create_sql", ScalarType::String.nullable(false))
2726            .with_column("redacted_create_sql", ScalarType::String.nullable(false))
2727            .with_key(vec![0])
2728            .with_key(vec![1])
2729            .finish(),
2730        column_comments: BTreeMap::from_iter([
2731            ("id", "Materialize's unique ID for the sink."),
2732            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the sink."),
2733            (
2734                "schema_id",
2735                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2736            ),
2737            ("name", "The name of the sink."),
2738            ("type", "The type of the sink: `kafka`."),
2739            (
2740                "connection_id",
2741                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2742            ),
2743            ("size", "The size of the sink."),
2744            (
2745                "envelope_type",
2746                "The envelope of the sink: `upsert`, or `debezium`.",
2747            ),
2748            (
2749                "format",
2750                "Deprecated The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2751            ),
2752            (
2753                "key_format",
2754                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2755            ),
2756            (
2757                "value_format",
2758                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2759            ),
2760            (
2761                "cluster_id",
2762                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2763            ),
2764            (
2765                "owner_id",
2766                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2767            ),
2768            ("create_sql", "The `CREATE` SQL statement for the sink."),
2769            (
2770                "redacted_create_sql",
2771                "The redacted `CREATE` SQL statement for the sink.",
2772            ),
2773        ]),
2774        is_retained_metrics_object: true,
2775        access: vec![PUBLIC_SELECT],
2776    }
2777});
2778pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2779    name: "mz_views",
2780    schema: MZ_CATALOG_SCHEMA,
2781    oid: oid::TABLE_MZ_VIEWS_OID,
2782    desc: RelationDesc::builder()
2783        .with_column("id", ScalarType::String.nullable(false))
2784        .with_column("oid", ScalarType::Oid.nullable(false))
2785        .with_column("schema_id", ScalarType::String.nullable(false))
2786        .with_column("name", ScalarType::String.nullable(false))
2787        .with_column("definition", ScalarType::String.nullable(false))
2788        .with_column("owner_id", ScalarType::String.nullable(false))
2789        .with_column(
2790            "privileges",
2791            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2792        )
2793        .with_column("create_sql", ScalarType::String.nullable(false))
2794        .with_column("redacted_create_sql", ScalarType::String.nullable(false))
2795        .with_key(vec![0])
2796        .with_key(vec![1])
2797        .finish(),
2798    column_comments: BTreeMap::from_iter([
2799        ("id", "Materialize's unique ID for the view."),
2800        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the view."),
2801        (
2802            "schema_id",
2803            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2804        ),
2805        ("name", "The name of the view."),
2806        ("definition", "The view definition (a `SELECT` query)."),
2807        (
2808            "owner_id",
2809            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2810        ),
2811        ("privileges", "The privileges belonging to the view."),
2812        ("create_sql", "The `CREATE` SQL statement for the view."),
2813        (
2814            "redacted_create_sql",
2815            "The redacted `CREATE` SQL statement for the view.",
2816        ),
2817    ]),
2818    is_retained_metrics_object: false,
2819    access: vec![PUBLIC_SELECT],
2820});
2821pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2822    name: "mz_materialized_views",
2823    schema: MZ_CATALOG_SCHEMA,
2824    oid: oid::TABLE_MZ_MATERIALIZED_VIEWS_OID,
2825    desc: RelationDesc::builder()
2826        .with_column("id", ScalarType::String.nullable(false))
2827        .with_column("oid", ScalarType::Oid.nullable(false))
2828        .with_column("schema_id", ScalarType::String.nullable(false))
2829        .with_column("name", ScalarType::String.nullable(false))
2830        .with_column("cluster_id", ScalarType::String.nullable(false))
2831        .with_column("definition", ScalarType::String.nullable(false))
2832        .with_column("owner_id", ScalarType::String.nullable(false))
2833        .with_column(
2834            "privileges",
2835            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2836        )
2837        .with_column("create_sql", ScalarType::String.nullable(false))
2838        .with_column("redacted_create_sql", ScalarType::String.nullable(false))
2839        .with_key(vec![0])
2840        .with_key(vec![1])
2841        .finish(),
2842    column_comments: BTreeMap::from_iter([
2843        ("id", "Materialize's unique ID for the materialized view."),
2844        (
2845            "oid",
2846            "A [PostgreSQL-compatible OID][`oid`] for the materialized view.",
2847        ),
2848        (
2849            "schema_id",
2850            "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2851        ),
2852        ("name", "The name of the materialized view."),
2853        (
2854            "cluster_id",
2855            "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2856        ),
2857        (
2858            "definition",
2859            "The materialized view definition (a `SELECT` query).",
2860        ),
2861        (
2862            "owner_id",
2863            "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2864        ),
2865        (
2866            "privileges",
2867            "The privileges belonging to the materialized view.",
2868        ),
2869        (
2870            "create_sql",
2871            "The `CREATE` SQL statement for the materialized view.",
2872        ),
2873        (
2874            "redacted_create_sql",
2875            "The redacted `CREATE` SQL statement for the materialized view.",
2876        ),
2877    ]),
2878    is_retained_metrics_object: false,
2879    access: vec![PUBLIC_SELECT],
2880});
2881pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
2882    BuiltinTable {
2883        name: "mz_materialized_view_refresh_strategies",
2884        schema: MZ_INTERNAL_SCHEMA,
2885        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
2886        desc: RelationDesc::builder()
2887            .with_column("materialized_view_id", ScalarType::String.nullable(false))
2888            .with_column("type", ScalarType::String.nullable(false))
2889            .with_column("interval", ScalarType::Interval.nullable(true))
2890            .with_column(
2891                "aligned_to",
2892                ScalarType::TimestampTz { precision: None }.nullable(true),
2893            )
2894            .with_column(
2895                "at",
2896                ScalarType::TimestampTz { precision: None }.nullable(true),
2897            )
2898            .finish(),
2899        column_comments: BTreeMap::from_iter([
2900            (
2901                "materialized_view_id",
2902                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
2903            ),
2904            (
2905                "type",
2906                "`at`, `every`, or `on-commit`. Default: `on-commit`",
2907            ),
2908            (
2909                "interval",
2910                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2911            ),
2912            (
2913                "aligned_to",
2914                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2915            ),
2916            (
2917                "at",
2918                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
2919            ),
2920        ]),
2921        is_retained_metrics_object: false,
2922        access: vec![PUBLIC_SELECT],
2923    }
2924});
2925pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2926    name: "mz_types",
2927    schema: MZ_CATALOG_SCHEMA,
2928    oid: oid::TABLE_MZ_TYPES_OID,
2929    desc: RelationDesc::builder()
2930        .with_column("id", ScalarType::String.nullable(false))
2931        .with_column("oid", ScalarType::Oid.nullable(false))
2932        .with_column("schema_id", ScalarType::String.nullable(false))
2933        .with_column("name", ScalarType::String.nullable(false))
2934        .with_column("category", ScalarType::String.nullable(false))
2935        .with_column("owner_id", ScalarType::String.nullable(false))
2936        .with_column(
2937            "privileges",
2938            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2939        )
2940        .with_column("create_sql", ScalarType::String.nullable(true))
2941        .with_column("redacted_create_sql", ScalarType::String.nullable(true))
2942        .with_key(vec![0])
2943        .with_key(vec![1])
2944        .finish(),
2945    column_comments: BTreeMap::from_iter([
2946        ("id", "Materialize's unique ID for the type."),
2947        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the type."),
2948        (
2949            "schema_id",
2950            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
2951        ),
2952        ("name", "The name of the type."),
2953        ("category", "The category of the type."),
2954        (
2955            "owner_id",
2956            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
2957        ),
2958        ("privileges", "The privileges belonging to the type."),
2959        ("create_sql", "The `CREATE` SQL statement for the type."),
2960        (
2961            "redacted_create_sql",
2962            "The redacted `CREATE` SQL statement for the type.",
2963        ),
2964    ]),
2965    is_retained_metrics_object: false,
2966    access: vec![PUBLIC_SELECT],
2967});
2968pub static MZ_CONTINUAL_TASKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2969    name: "mz_continual_tasks",
2970    schema: MZ_INTERNAL_SCHEMA,
2971    oid: oid::TABLE_MZ_CONTINUAL_TASKS_OID,
2972    desc: RelationDesc::builder()
2973        .with_column("id", ScalarType::String.nullable(false))
2974        .with_column("oid", ScalarType::Oid.nullable(false))
2975        .with_column("schema_id", ScalarType::String.nullable(false))
2976        .with_column("name", ScalarType::String.nullable(false))
2977        .with_column("cluster_id", ScalarType::String.nullable(false))
2978        .with_column("definition", ScalarType::String.nullable(false))
2979        .with_column("owner_id", ScalarType::String.nullable(false))
2980        .with_column(
2981            "privileges",
2982            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
2983        )
2984        .with_column("create_sql", ScalarType::String.nullable(false))
2985        .with_column("redacted_create_sql", ScalarType::String.nullable(false))
2986        .with_key(vec![0])
2987        .with_key(vec![1])
2988        .finish(),
2989    column_comments: BTreeMap::new(),
2990    is_retained_metrics_object: false,
2991    access: vec![PUBLIC_SELECT],
2992});
2993pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2994    name: "mz_network_policies",
2995    schema: MZ_INTERNAL_SCHEMA,
2996    oid: oid::TABLE_MZ_NETWORK_POLICIES_OID,
2997    desc: RelationDesc::builder()
2998        .with_column("id", ScalarType::String.nullable(false))
2999        .with_column("name", ScalarType::String.nullable(false))
3000        .with_column("owner_id", ScalarType::String.nullable(false))
3001        .with_column(
3002            "privileges",
3003            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
3004        )
3005        .with_column("oid", ScalarType::Oid.nullable(false))
3006        .finish(),
3007    column_comments: BTreeMap::from_iter([
3008        ("id", "The ID of the network policy."),
3009        ("name", "The name of the network policy."),
3010        (
3011            "owner_id",
3012            "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
3013        ),
3014        (
3015            "privileges",
3016            "The privileges belonging to the network policy.",
3017        ),
3018        (
3019            "oid",
3020            "A [PostgreSQL-compatible OID][`oid`] for the network policy.",
3021        ),
3022    ]),
3023    is_retained_metrics_object: false,
3024    access: vec![PUBLIC_SELECT],
3025});
3026pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3027    name: "mz_network_policy_rules",
3028    schema: MZ_INTERNAL_SCHEMA,
3029    oid: oid::TABLE_MZ_NETWORK_POLICY_RULES_OID,
3030    desc: RelationDesc::builder()
3031        .with_column("name", ScalarType::String.nullable(false))
3032        .with_column("policy_id", ScalarType::String.nullable(false))
3033        .with_column("action", ScalarType::String.nullable(false))
3034        .with_column("address", ScalarType::String.nullable(false))
3035        .with_column("direction", ScalarType::String.nullable(false))
3036        .finish(),
3037    column_comments: BTreeMap::from_iter([
3038        (
3039            "name",
3040            "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
3041        ),
3042        (
3043            "policy_id",
3044            "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
3045        ),
3046        (
3047            "action",
3048            "The action of the rule. `allow` is the only supported action.",
3049        ),
3050        ("address", "The address the rule will take action on."),
3051        (
3052            "direction",
3053            "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3054        ),
3055    ]),
3056    is_retained_metrics_object: false,
3057    access: vec![PUBLIC_SELECT],
3058});
3059/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3060/// in the `mz_types` table as part of our public, stable API.
3061pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3062    name: "mz_type_pg_metadata",
3063    schema: MZ_INTERNAL_SCHEMA,
3064    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3065    desc: RelationDesc::builder()
3066        .with_column("id", ScalarType::String.nullable(false))
3067        .with_column("typinput", ScalarType::Oid.nullable(false))
3068        .with_column("typreceive", ScalarType::Oid.nullable(false))
3069        .finish(),
3070    column_comments: BTreeMap::new(),
3071    is_retained_metrics_object: false,
3072    access: vec![PUBLIC_SELECT],
3073});
3074pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3075    name: "mz_array_types",
3076    schema: MZ_CATALOG_SCHEMA,
3077    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3078    desc: RelationDesc::builder()
3079        .with_column("id", ScalarType::String.nullable(false))
3080        .with_column("element_id", ScalarType::String.nullable(false))
3081        .finish(),
3082    column_comments: BTreeMap::from_iter([
3083        ("id", "The ID of the array type."),
3084        ("element_id", "The ID of the array's element type."),
3085    ]),
3086    is_retained_metrics_object: false,
3087    access: vec![PUBLIC_SELECT],
3088});
3089pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3090    name: "mz_base_types",
3091    schema: MZ_CATALOG_SCHEMA,
3092    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3093    desc: RelationDesc::builder()
3094        .with_column("id", ScalarType::String.nullable(false))
3095        .finish(),
3096    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3097    is_retained_metrics_object: false,
3098    access: vec![PUBLIC_SELECT],
3099});
3100pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3101    name: "mz_list_types",
3102    schema: MZ_CATALOG_SCHEMA,
3103    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3104    desc: RelationDesc::builder()
3105        .with_column("id", ScalarType::String.nullable(false))
3106        .with_column("element_id", ScalarType::String.nullable(false))
3107        .with_column(
3108            "element_modifiers",
3109            ScalarType::List {
3110                element_type: Box::new(ScalarType::Int64),
3111                custom_id: None,
3112            }
3113            .nullable(true),
3114        )
3115        .finish(),
3116    column_comments: BTreeMap::from_iter([
3117        ("id", "The ID of the list type."),
3118        ("element_id", "The IID of the list's element type."),
3119        (
3120            "element_modifiers",
3121            "The element type modifiers, or `NULL` if none.",
3122        ),
3123    ]),
3124    is_retained_metrics_object: false,
3125    access: vec![PUBLIC_SELECT],
3126});
3127pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3128    name: "mz_map_types",
3129    schema: MZ_CATALOG_SCHEMA,
3130    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3131    desc: RelationDesc::builder()
3132        .with_column("id", ScalarType::String.nullable(false))
3133        .with_column("key_id", ScalarType::String.nullable(false))
3134        .with_column("value_id", ScalarType::String.nullable(false))
3135        .with_column(
3136            "key_modifiers",
3137            ScalarType::List {
3138                element_type: Box::new(ScalarType::Int64),
3139                custom_id: None,
3140            }
3141            .nullable(true),
3142        )
3143        .with_column(
3144            "value_modifiers",
3145            ScalarType::List {
3146                element_type: Box::new(ScalarType::Int64),
3147                custom_id: None,
3148            }
3149            .nullable(true),
3150        )
3151        .finish(),
3152    column_comments: BTreeMap::from_iter([
3153        ("id", "The ID of the map type."),
3154        ("key_id", "The ID of the map's key type."),
3155        ("value_id", "The ID of the map's value type."),
3156        (
3157            "key_modifiers",
3158            "The key type modifiers, or `NULL` if none.",
3159        ),
3160        (
3161            "value_modifiers",
3162            "The value type modifiers, or `NULL` if none.",
3163        ),
3164    ]),
3165    is_retained_metrics_object: false,
3166    access: vec![PUBLIC_SELECT],
3167});
3168pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3169    name: "mz_roles",
3170    schema: MZ_CATALOG_SCHEMA,
3171    oid: oid::TABLE_MZ_ROLES_OID,
3172    desc: RelationDesc::builder()
3173        .with_column("id", ScalarType::String.nullable(false))
3174        .with_column("oid", ScalarType::Oid.nullable(false))
3175        .with_column("name", ScalarType::String.nullable(false))
3176        .with_column("inherit", ScalarType::Bool.nullable(false))
3177        .with_key(vec![0])
3178        .with_key(vec![1])
3179        .finish(),
3180    column_comments: BTreeMap::from_iter([
3181        ("id", "Materialize's unique ID for the role."),
3182        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the role."),
3183        ("name", "The name of the role."),
3184        (
3185            "inherit",
3186            "Indicates whether the role has inheritance of privileges.",
3187        ),
3188    ]),
3189    is_retained_metrics_object: false,
3190    access: vec![PUBLIC_SELECT],
3191});
3192pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3193    name: "mz_role_members",
3194    schema: MZ_CATALOG_SCHEMA,
3195    oid: oid::TABLE_MZ_ROLE_MEMBERS_OID,
3196    desc: RelationDesc::builder()
3197        .with_column("role_id", ScalarType::String.nullable(false))
3198        .with_column("member", ScalarType::String.nullable(false))
3199        .with_column("grantor", ScalarType::String.nullable(false))
3200        .finish(),
3201    column_comments: BTreeMap::from_iter([
3202        (
3203            "role_id",
3204            "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3205        ),
3206        (
3207            "member",
3208            "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3209        ),
3210        (
3211            "grantor",
3212            "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3213        ),
3214    ]),
3215    is_retained_metrics_object: false,
3216    access: vec![PUBLIC_SELECT],
3217});
3218pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3219    name: "mz_role_parameters",
3220    schema: MZ_CATALOG_SCHEMA,
3221    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3222    desc: RelationDesc::builder()
3223        .with_column("role_id", ScalarType::String.nullable(false))
3224        .with_column("parameter_name", ScalarType::String.nullable(false))
3225        .with_column("parameter_value", ScalarType::String.nullable(false))
3226        .finish(),
3227    column_comments: BTreeMap::from_iter([
3228        (
3229            "role_id",
3230            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3231        ),
3232        (
3233            "parameter_name",
3234            "The configuration parameter name. One of the supported configuration parameters.",
3235        ),
3236        (
3237            "parameter_value",
3238            "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.",
3239        ),
3240    ]),
3241    is_retained_metrics_object: false,
3242    access: vec![PUBLIC_SELECT],
3243});
3244pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3245    name: "mz_pseudo_types",
3246    schema: MZ_CATALOG_SCHEMA,
3247    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3248    desc: RelationDesc::builder()
3249        .with_column("id", ScalarType::String.nullable(false))
3250        .finish(),
3251    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3252    is_retained_metrics_object: false,
3253    access: vec![PUBLIC_SELECT],
3254});
3255pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3256    BuiltinTable {
3257        name: "mz_functions",
3258        schema: MZ_CATALOG_SCHEMA,
3259        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3260        desc: RelationDesc::builder()
3261            .with_column("id", ScalarType::String.nullable(false)) // not a key!
3262            .with_column("oid", ScalarType::Oid.nullable(false))
3263            .with_column("schema_id", ScalarType::String.nullable(false))
3264            .with_column("name", ScalarType::String.nullable(false))
3265            .with_column(
3266                "argument_type_ids",
3267                ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
3268            )
3269            .with_column(
3270                "variadic_argument_type_id",
3271                ScalarType::String.nullable(true),
3272            )
3273            .with_column("return_type_id", ScalarType::String.nullable(true))
3274            .with_column("returns_set", ScalarType::Bool.nullable(false))
3275            .with_column("owner_id", ScalarType::String.nullable(false))
3276            .finish(),
3277        column_comments: BTreeMap::from_iter([
3278            ("id", "Materialize's unique ID for the function."),
3279            (
3280                "oid",
3281                "A [PostgreSQL-compatible OID][`oid`] for the function.",
3282            ),
3283            (
3284                "schema_id",
3285                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3286            ),
3287            ("name", "The name of the function."),
3288            (
3289                "argument_type_ids",
3290                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3291            ),
3292            (
3293                "variadic_argument_type_id",
3294                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3295            ),
3296            (
3297                "return_type_id",
3298                "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`].",
3299            ),
3300            (
3301                "returns_set",
3302                "Whether the function returns a set, i.e. the function is a table function.",
3303            ),
3304            (
3305                "owner_id",
3306                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3307            ),
3308        ]),
3309        is_retained_metrics_object: false,
3310        access: vec![PUBLIC_SELECT],
3311    }
3312});
3313pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3314    name: "mz_operators",
3315    schema: MZ_CATALOG_SCHEMA,
3316    oid: oid::TABLE_MZ_OPERATORS_OID,
3317    desc: RelationDesc::builder()
3318        .with_column("oid", ScalarType::Oid.nullable(false))
3319        .with_column("name", ScalarType::String.nullable(false))
3320        .with_column(
3321            "argument_type_ids",
3322            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
3323        )
3324        .with_column("return_type_id", ScalarType::String.nullable(true))
3325        .finish(),
3326    column_comments: BTreeMap::new(),
3327    is_retained_metrics_object: false,
3328    access: vec![PUBLIC_SELECT],
3329});
3330pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3331    name: "mz_aggregates",
3332    schema: MZ_INTERNAL_SCHEMA,
3333    oid: oid::TABLE_MZ_AGGREGATES_OID,
3334    desc: RelationDesc::builder()
3335        .with_column("oid", ScalarType::Oid.nullable(false))
3336        .with_column("agg_kind", ScalarType::String.nullable(false))
3337        .with_column("agg_num_direct_args", ScalarType::Int16.nullable(false))
3338        .finish(),
3339    column_comments: BTreeMap::new(),
3340    is_retained_metrics_object: false,
3341    access: vec![PUBLIC_SELECT],
3342});
3343
3344pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3345    name: "mz_clusters",
3346    schema: MZ_CATALOG_SCHEMA,
3347    oid: oid::TABLE_MZ_CLUSTERS_OID,
3348    desc: RelationDesc::builder()
3349        .with_column("id", ScalarType::String.nullable(false))
3350        .with_column("name", ScalarType::String.nullable(false))
3351        .with_column("owner_id", ScalarType::String.nullable(false))
3352        .with_column(
3353            "privileges",
3354            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
3355        )
3356        .with_column("managed", ScalarType::Bool.nullable(false))
3357        .with_column("size", ScalarType::String.nullable(true))
3358        .with_column("replication_factor", ScalarType::UInt32.nullable(true))
3359        .with_column("disk", ScalarType::Bool.nullable(true))
3360        .with_column(
3361            "availability_zones",
3362            ScalarType::List {
3363                element_type: Box::new(ScalarType::String),
3364                custom_id: None,
3365            }
3366            .nullable(true),
3367        )
3368        .with_column("introspection_debugging", ScalarType::Bool.nullable(true))
3369        .with_column(
3370            "introspection_interval",
3371            ScalarType::Interval.nullable(true),
3372        )
3373        .with_key(vec![0])
3374        .finish(),
3375    column_comments: BTreeMap::from_iter([
3376        ("id", "Materialize's unique ID for the cluster."),
3377        ("name", "The name of the cluster."),
3378        (
3379            "owner_id",
3380            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3381        ),
3382        ("privileges", "The privileges belonging to the cluster."),
3383        (
3384            "managed",
3385            "Whether the cluster is a managed cluster with automatically managed replicas.",
3386        ),
3387        (
3388            "size",
3389            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3390        ),
3391        (
3392            "replication_factor",
3393            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3394        ),
3395        (
3396            "disk",
3397            "Unstable If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3398        ),
3399        (
3400            "availability_zones",
3401            "Unstable If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3402        ),
3403        (
3404            "introspection_debugging",
3405            "Whether introspection of the gathering of the introspection data is enabled.",
3406        ),
3407        (
3408            "introspection_interval",
3409            "The interval at which to collect introspection data.",
3410        ),
3411    ]),
3412    is_retained_metrics_object: false,
3413    access: vec![PUBLIC_SELECT],
3414});
3415
3416pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3417    name: "mz_cluster_workload_classes",
3418    schema: MZ_INTERNAL_SCHEMA,
3419    oid: oid::TABLE_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3420    desc: RelationDesc::builder()
3421        .with_column("id", ScalarType::String.nullable(false))
3422        .with_column("workload_class", ScalarType::String.nullable(true))
3423        .with_key(vec![0])
3424        .finish(),
3425    column_comments: BTreeMap::new(),
3426    is_retained_metrics_object: false,
3427    access: vec![PUBLIC_SELECT],
3428});
3429
3430pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3431    name: "mz_cluster_workload_classes_ind",
3432    schema: MZ_INTERNAL_SCHEMA,
3433    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3434    sql: "IN CLUSTER mz_catalog_server
3435ON mz_internal.mz_cluster_workload_classes (id)",
3436    is_retained_metrics_object: false,
3437};
3438
3439pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3440    name: "mz_cluster_schedules",
3441    schema: MZ_INTERNAL_SCHEMA,
3442    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3443    desc: RelationDesc::builder()
3444        .with_column("cluster_id", ScalarType::String.nullable(false))
3445        .with_column("type", ScalarType::String.nullable(false))
3446        .with_column(
3447            "refresh_hydration_time_estimate",
3448            ScalarType::Interval.nullable(true),
3449        )
3450        .finish(),
3451    column_comments: BTreeMap::from_iter([
3452        (
3453            "cluster_id",
3454            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3455        ),
3456        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3457        (
3458            "refresh_hydration_time_estimate",
3459            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3460        ),
3461    ]),
3462    is_retained_metrics_object: false,
3463    access: vec![PUBLIC_SELECT],
3464});
3465
3466pub static MZ_SECRETS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3467    name: "mz_secrets",
3468    schema: MZ_CATALOG_SCHEMA,
3469    oid: oid::TABLE_MZ_SECRETS_OID,
3470    desc: RelationDesc::builder()
3471        .with_column("id", ScalarType::String.nullable(false))
3472        .with_column("oid", ScalarType::Oid.nullable(false))
3473        .with_column("schema_id", ScalarType::String.nullable(false))
3474        .with_column("name", ScalarType::String.nullable(false))
3475        .with_column("owner_id", ScalarType::String.nullable(false))
3476        .with_column(
3477            "privileges",
3478            ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false),
3479        )
3480        .finish(),
3481    column_comments: BTreeMap::from_iter([
3482        ("id", "The unique ID of the secret."),
3483        (
3484            "oid",
3485            "A [PostgreSQL-compatible oid][`oid`] for the secret.",
3486        ),
3487        (
3488            "schema_id",
3489            "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3490        ),
3491        ("name", "The name of the secret."),
3492        (
3493            "owner_id",
3494            "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3495        ),
3496        ("privileges", "The privileges belonging to the secret."),
3497    ]),
3498    is_retained_metrics_object: false,
3499    access: vec![PUBLIC_SELECT],
3500});
3501
3502pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3503    name: "mz_cluster_replicas",
3504    schema: MZ_CATALOG_SCHEMA,
3505    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3506    desc: RelationDesc::builder()
3507        .with_column("id", ScalarType::String.nullable(false))
3508        .with_column("name", ScalarType::String.nullable(false))
3509        .with_column("cluster_id", ScalarType::String.nullable(false))
3510        .with_column("size", ScalarType::String.nullable(true))
3511        // `NULL` for un-orchestrated clusters and for replicas where the user
3512        // hasn't specified them.
3513        .with_column("availability_zone", ScalarType::String.nullable(true))
3514        .with_column("owner_id", ScalarType::String.nullable(false))
3515        .with_column("disk", ScalarType::Bool.nullable(true))
3516        .finish(),
3517    column_comments: BTreeMap::from_iter([
3518        ("id", "Materialize's unique ID for the cluster replica."),
3519        ("name", "The name of the cluster replica."),
3520        (
3521            "cluster_id",
3522            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3523        ),
3524        (
3525            "size",
3526            "The cluster replica's size, selected during creation.",
3527        ),
3528        (
3529            "availability_zone",
3530            "The availability zone in which the cluster is running.",
3531        ),
3532        (
3533            "owner_id",
3534            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3535        ),
3536        ("disk", "If the replica has a local disk."),
3537    ]),
3538    is_retained_metrics_object: true,
3539    access: vec![PUBLIC_SELECT],
3540});
3541
3542pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3543    name: "mz_internal_cluster_replicas",
3544    schema: MZ_INTERNAL_SCHEMA,
3545    oid: oid::TABLE_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3546    desc: RelationDesc::builder()
3547        .with_column("id", ScalarType::String.nullable(false))
3548        .finish(),
3549    column_comments: BTreeMap::from_iter([(
3550        "id",
3551        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3552    )]),
3553    is_retained_metrics_object: false,
3554    access: vec![PUBLIC_SELECT],
3555});
3556
3557pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3558    name: "mz_pending_cluster_replicas",
3559    schema: MZ_INTERNAL_SCHEMA,
3560    oid: oid::TABLE_MZ_PENDING_CLUSTER_REPLICAS_OID,
3561    desc: RelationDesc::builder()
3562        .with_column("id", ScalarType::String.nullable(false))
3563        .finish(),
3564    column_comments: BTreeMap::from_iter([(
3565        "id",
3566        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3567    )]),
3568    is_retained_metrics_object: false,
3569    access: vec![PUBLIC_SELECT],
3570});
3571
3572// TODO(teskje) Remove this table in favor of `MZ_CLUSTER_REPLICA_STATUS_HISTORY`, once internal
3573//              clients have been migrated.
3574pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3575    name: "mz_cluster_replica_statuses",
3576    schema: MZ_INTERNAL_SCHEMA,
3577    oid: oid::TABLE_MZ_CLUSTER_REPLICA_STATUSES_OID,
3578    desc: RelationDesc::builder()
3579        .with_column("replica_id", ScalarType::String.nullable(false))
3580        .with_column("process_id", ScalarType::UInt64.nullable(false))
3581        .with_column("status", ScalarType::String.nullable(false))
3582        .with_column("reason", ScalarType::String.nullable(true))
3583        .with_column(
3584            "updated_at",
3585            ScalarType::TimestampTz { precision: None }.nullable(false),
3586        )
3587        .finish(),
3588    column_comments: BTreeMap::from_iter([
3589        (
3590            "replica_id",
3591            "Materialize's unique ID for the cluster replica.",
3592        ),
3593        (
3594            "process_id",
3595            "The ID of the process within the cluster replica.",
3596        ),
3597        (
3598            "status",
3599            "The status of the cluster replica: `online` or `offline`.",
3600        ),
3601        (
3602            "reason",
3603            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3604        ),
3605        (
3606            "updated_at",
3607            "The time at which the status was last updated.",
3608        ),
3609    ]),
3610    is_retained_metrics_object: true,
3611    access: vec![PUBLIC_SELECT],
3612});
3613
3614pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3615    BuiltinSource {
3616        name: "mz_cluster_replica_status_history",
3617        schema: MZ_INTERNAL_SCHEMA,
3618        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3619        data_source: IntrospectionType::ReplicaStatusHistory,
3620        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3621        column_comments: BTreeMap::from_iter([
3622            ("replica_id", "The ID of a cluster replica."),
3623            ("process_id", "The ID of a process within the replica."),
3624            (
3625                "status",
3626                "The status of the cluster replica: `online` or `offline`.",
3627            ),
3628            (
3629                "reason",
3630                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3631            ),
3632            (
3633                "occurred_at",
3634                "Wall-clock timestamp at which the event occurred.",
3635            ),
3636        ]),
3637        is_retained_metrics_object: false,
3638        access: vec![PUBLIC_SELECT],
3639    }
3640});
3641
3642pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
3643    || {
3644        BuiltinContinualTask {
3645            name: "mz_cluster_replica_status_history_ct",
3646            schema: MZ_INTERNAL_SCHEMA,
3647            oid: oid::CT_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3648            desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3649            sql: "
3650IN CLUSTER mz_catalog_server
3651ON INPUT mz_internal.mz_cluster_replica_status_history AS (
3652    DELETE FROM mz_internal.mz_cluster_replica_status_history_ct WHERE occurred_at + '30d' < mz_now();
3653    INSERT INTO mz_internal.mz_cluster_replica_status_history_ct SELECT * FROM mz_internal.mz_cluster_replica_status_history;
3654)",
3655            access: vec![PUBLIC_SELECT],
3656        }
3657    },
3658);
3659
3660pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3661    name: "mz_cluster_replica_sizes",
3662    schema: MZ_CATALOG_SCHEMA,
3663    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3664    desc: RelationDesc::builder()
3665        .with_column("size", ScalarType::String.nullable(false))
3666        .with_column("processes", ScalarType::UInt64.nullable(false))
3667        .with_column("workers", ScalarType::UInt64.nullable(false))
3668        .with_column("cpu_nano_cores", ScalarType::UInt64.nullable(false))
3669        .with_column("memory_bytes", ScalarType::UInt64.nullable(false))
3670        .with_column("disk_bytes", ScalarType::UInt64.nullable(true))
3671        .with_column(
3672            "credits_per_hour",
3673            ScalarType::Numeric { max_scale: None }.nullable(false),
3674        )
3675        .finish(),
3676    column_comments: BTreeMap::from_iter([
3677        ("size", "The human-readable replica size."),
3678        ("processes", "The number of processes in the replica."),
3679        (
3680            "workers",
3681            "The number of Timely Dataflow workers per process.",
3682        ),
3683        (
3684            "cpu_nano_cores",
3685            "The CPU allocation per process, in billionths of a vCPU core.",
3686        ),
3687        (
3688            "memory_bytes",
3689            "The RAM allocation per process, in billionths of a vCPU core.",
3690        ),
3691        ("disk_bytes", "The disk allocation per process."),
3692        (
3693            "credits_per_hour",
3694            "The number of compute credits consumed per hour.",
3695        ),
3696    ]),
3697    is_retained_metrics_object: true,
3698    access: vec![PUBLIC_SELECT],
3699});
3700
3701pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3702    name: "mz_audit_events",
3703    schema: MZ_CATALOG_SCHEMA,
3704    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
3705    desc: RelationDesc::builder()
3706        .with_column("id", ScalarType::UInt64.nullable(false))
3707        .with_column("event_type", ScalarType::String.nullable(false))
3708        .with_column("object_type", ScalarType::String.nullable(false))
3709        .with_column("details", ScalarType::Jsonb.nullable(false))
3710        .with_column("user", ScalarType::String.nullable(true))
3711        .with_column(
3712            "occurred_at",
3713            ScalarType::TimestampTz { precision: None }.nullable(false),
3714        )
3715        .with_key(vec![0])
3716        .finish(),
3717    column_comments: BTreeMap::from_iter([
3718        (
3719            "id",
3720            "Materialize's unique, monotonically increasing ID for the event.",
3721        ),
3722        (
3723            "event_type",
3724            "The type of the event: `create`, `drop`, or `alter`.",
3725        ),
3726        (
3727            "object_type",
3728            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
3729        ),
3730        (
3731            "details",
3732            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
3733        ),
3734        (
3735            "user",
3736            "The user who triggered the event, or `NULL` if triggered by the system.",
3737        ),
3738        (
3739            "occurred_at",
3740            "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.",
3741        ),
3742    ]),
3743    is_retained_metrics_object: false,
3744    access: vec![PUBLIC_SELECT],
3745});
3746
3747pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3748    name: "mz_source_status_history",
3749    schema: MZ_INTERNAL_SCHEMA,
3750    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
3751    data_source: IntrospectionType::SourceStatusHistory,
3752    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
3753    column_comments: BTreeMap::from_iter([
3754        (
3755            "occurred_at",
3756            "Wall-clock timestamp of the source status change.",
3757        ),
3758        (
3759            "source_id",
3760            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
3761        ),
3762        (
3763            "status",
3764            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
3765        ),
3766        (
3767            "error",
3768            "If the source is in an error state, the error message.",
3769        ),
3770        (
3771            "details",
3772            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
3773        ),
3774        (
3775            "replica_id",
3776            "The ID of the replica that an instance of a source is running on.",
3777        ),
3778    ]),
3779    is_retained_metrics_object: false,
3780    access: vec![PUBLIC_SELECT],
3781});
3782
3783pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
3784    || BuiltinSource {
3785        name: "mz_aws_privatelink_connection_status_history",
3786        schema: MZ_INTERNAL_SCHEMA,
3787        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
3788        data_source: IntrospectionType::PrivatelinkConnectionStatusHistory,
3789        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
3790        column_comments: BTreeMap::from_iter([
3791            ("occurred_at", "Wall-clock timestamp of the status change."),
3792            (
3793                "connection_id",
3794                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
3795            ),
3796            (
3797                "status",
3798                "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`.",
3799            ),
3800        ]),
3801        is_retained_metrics_object: false,
3802        access: vec![PUBLIC_SELECT],
3803    },
3804);
3805
3806pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> =
3807    LazyLock::new(|| BuiltinView {
3808        name: "mz_aws_privatelink_connection_statuses",
3809        schema: MZ_INTERNAL_SCHEMA,
3810        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
3811        desc: RelationDesc::builder()
3812            .with_column("id", ScalarType::String.nullable(false))
3813            .with_column("name", ScalarType::String.nullable(false))
3814            .with_column(
3815                "last_status_change_at",
3816                ScalarType::TimestampTz { precision: None }.nullable(true),
3817            )
3818            .with_column("status", ScalarType::String.nullable(true))
3819            .with_key(vec![0])
3820            .finish(),
3821        column_comments: BTreeMap::from_iter([
3822            (
3823                "id",
3824                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
3825            ),
3826            ("name", "The name of the connection."),
3827            (
3828                "last_status_change_at",
3829                "Wall-clock timestamp of the connection status change.",
3830            ),
3831            ("status", ""),
3832        ]),
3833        sql: "
3834    WITH statuses_w_last_status AS (
3835        SELECT
3836            connection_id,
3837            occurred_at,
3838            status,
3839            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
3840        FROM mz_internal.mz_aws_privatelink_connection_status_history
3841    ),
3842    latest_events AS (
3843        -- Only take the most recent transition for each ID
3844        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
3845        FROM statuses_w_last_status
3846        -- Only keep first status transitions
3847        WHERE status <> last_status OR last_status IS NULL
3848        ORDER BY connection_id, occurred_at DESC
3849    )
3850    SELECT
3851        conns.id,
3852        name,
3853        occurred_at as last_status_change_at,
3854        status
3855    FROM latest_events
3856    JOIN mz_catalog.mz_connections AS conns
3857    ON conns.id = latest_events.connection_id",
3858        access: vec![PUBLIC_SELECT],
3859    });
3860
3861pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
3862    LazyLock::new(|| BuiltinSource {
3863        name: "mz_statement_execution_history",
3864        schema: MZ_INTERNAL_SCHEMA,
3865        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
3866        data_source: IntrospectionType::StatementExecutionHistory,
3867        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
3868        column_comments: BTreeMap::new(),
3869        is_retained_metrics_object: false,
3870        access: vec![MONITOR_SELECT],
3871    });
3872
3873pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
3874    BuiltinView {
3875    name: "mz_statement_execution_history_redacted",
3876    schema: MZ_INTERNAL_SCHEMA,
3877    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
3878    // everything but `params` and `error_message`
3879    desc: RelationDesc::builder()
3880        .with_column("id", ScalarType::Uuid.nullable(false))
3881        .with_column("prepared_statement_id", ScalarType::Uuid.nullable(false))
3882        .with_column("sample_rate", ScalarType::Float64.nullable(false))
3883        .with_column("cluster_id", ScalarType::String.nullable(true))
3884        .with_column("application_name", ScalarType::String.nullable(false))
3885        .with_column("cluster_name", ScalarType::String.nullable(true))
3886        .with_column("database_name", ScalarType::String.nullable(false))
3887        .with_column("search_path", ScalarType::List { element_type: Box::new(ScalarType::String), custom_id: None }.nullable(false))
3888        .with_column("transaction_isolation", ScalarType::String.nullable(false))
3889        .with_column("execution_timestamp", ScalarType::UInt64.nullable(true))
3890        .with_column("transaction_id", ScalarType::UInt64.nullable(false))
3891        .with_column("transient_index_id", ScalarType::String.nullable(true))
3892        .with_column("mz_version", ScalarType::String.nullable(false))
3893        .with_column("began_at", ScalarType::TimestampTz { precision: None }.nullable(false))
3894        .with_column("finished_at", ScalarType::TimestampTz { precision: None }.nullable(true))
3895        .with_column("finished_status", ScalarType::String.nullable(true))
3896        .with_column("result_size", ScalarType::Int64.nullable(true))
3897        .with_column("rows_returned", ScalarType::Int64.nullable(true))
3898        .with_column("execution_strategy", ScalarType::String.nullable(true))
3899        .finish(),
3900    column_comments: BTreeMap::new(),
3901    sql: "
3902SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
3903cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
3904transient_index_id, mz_version, began_at, finished_at, finished_status,
3905result_size, rows_returned, execution_strategy
3906FROM mz_internal.mz_statement_execution_history",
3907    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
3908}
3909});
3910
3911pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
3912    LazyLock::new(|| BuiltinSource {
3913        name: "mz_prepared_statement_history",
3914        schema: MZ_INTERNAL_SCHEMA,
3915        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
3916        data_source: IntrospectionType::PreparedStatementHistory,
3917        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
3918        column_comments: BTreeMap::new(),
3919        is_retained_metrics_object: false,
3920        access: vec![
3921            SUPPORT_SELECT,
3922            ANALYTICS_SELECT,
3923            MONITOR_REDACTED_SELECT,
3924            MONITOR_SELECT,
3925        ],
3926    });
3927
3928pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3929    name: "mz_sql_text",
3930    schema: MZ_INTERNAL_SCHEMA,
3931    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
3932    desc: MZ_SQL_TEXT_DESC.clone(),
3933    data_source: IntrospectionType::SqlText,
3934    column_comments: BTreeMap::new(),
3935    is_retained_metrics_object: false,
3936    access: vec![MONITOR_SELECT],
3937});
3938
3939pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3940    name: "mz_sql_text_redacted",
3941    schema: MZ_INTERNAL_SCHEMA,
3942    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
3943    desc: RelationDesc::builder()
3944        .with_column("sql_hash", ScalarType::Bytes.nullable(false))
3945        .with_column("redacted_sql", ScalarType::String.nullable(false))
3946        .finish(),
3947    column_comments: BTreeMap::new(),
3948    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
3949    access: vec![
3950        MONITOR_SELECT,
3951        MONITOR_REDACTED_SELECT,
3952        SUPPORT_SELECT,
3953        ANALYTICS_SELECT,
3954    ],
3955});
3956
3957pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
3958    BuiltinView {
3959        name: "mz_recent_sql_text",
3960        schema: MZ_INTERNAL_SCHEMA,
3961        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
3962        // This should always be 1 day more than the interval in
3963        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
3964        // is rounded down to the nearest day.  Thus something that actually happened three days ago
3965        // could have a `prepared day` anywhere from 3 to 4 days back.
3966        desc: RelationDesc::builder()
3967            .with_column("sql_hash", ScalarType::Bytes.nullable(false))
3968            .with_column("sql", ScalarType::String.nullable(false))
3969            .with_column("redacted_sql", ScalarType::String.nullable(false))
3970            .with_key(vec![0, 1, 2])
3971            .finish(),
3972        column_comments: BTreeMap::new(),
3973        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
3974        access: vec![MONITOR_SELECT],
3975    }
3976});
3977
3978pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3979    name: "mz_recent_sql_text_redacted",
3980    schema: MZ_INTERNAL_SCHEMA,
3981    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
3982    desc: RelationDesc::builder()
3983        .with_column("sql_hash", ScalarType::Bytes.nullable(false))
3984        .with_column("redacted_sql", ScalarType::String.nullable(false))
3985        .finish(),
3986    column_comments: BTreeMap::new(),
3987    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
3988    access: vec![
3989        MONITOR_SELECT,
3990        MONITOR_REDACTED_SELECT,
3991        SUPPORT_SELECT,
3992        ANALYTICS_SELECT,
3993    ],
3994});
3995
3996pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
3997    name: "mz_recent_sql_text_ind",
3998    schema: MZ_INTERNAL_SCHEMA,
3999    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
4000    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4001    is_retained_metrics_object: false,
4002});
4003
4004pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4005    name: "mz_session_history",
4006    schema: MZ_INTERNAL_SCHEMA,
4007    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4008    data_source: IntrospectionType::SessionHistory,
4009    desc: MZ_SESSION_HISTORY_DESC.clone(),
4010    column_comments: BTreeMap::new(),
4011    is_retained_metrics_object: false,
4012    access: vec![PUBLIC_SELECT],
4013});
4014
4015pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4016    BuiltinView {
4017        name: "mz_activity_log_thinned",
4018        schema: MZ_INTERNAL_SCHEMA,
4019        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
4020        desc: RelationDesc::builder()
4021            .with_column("execution_id", ScalarType::Uuid.nullable(false))
4022            .with_column("sample_rate", ScalarType::Float64.nullable(false))
4023            .with_column("cluster_id", ScalarType::String.nullable(true))
4024            .with_column("application_name", ScalarType::String.nullable(false))
4025            .with_column("cluster_name", ScalarType::String.nullable(true))
4026            .with_column("database_name", ScalarType::String.nullable(false))
4027            .with_column("search_path", ScalarType::List { element_type: Box::new(ScalarType::String), custom_id: None }.nullable(false))
4028            .with_column("transaction_isolation", ScalarType::String.nullable(false))
4029            .with_column("execution_timestamp", ScalarType::UInt64.nullable(true))
4030            .with_column("transient_index_id", ScalarType::String.nullable(true))
4031            .with_column("params", ScalarType::Array(Box::new(ScalarType::String)).nullable(false))
4032            .with_column("mz_version", ScalarType::String.nullable(false))
4033            .with_column("began_at", ScalarType::TimestampTz { precision: None }.nullable(false))
4034            .with_column("finished_at", ScalarType::TimestampTz { precision: None }.nullable(true))
4035            .with_column("finished_status", ScalarType::String.nullable(true))
4036            .with_column("error_message", ScalarType::String.nullable(true))
4037            .with_column("result_size", ScalarType::Int64.nullable(true))
4038            .with_column("rows_returned", ScalarType::Int64.nullable(true))
4039            .with_column("execution_strategy", ScalarType::String.nullable(true))
4040            .with_column("transaction_id", ScalarType::UInt64.nullable(false))
4041            .with_column("prepared_statement_id", ScalarType::Uuid.nullable(false))
4042            .with_column("sql_hash", ScalarType::Bytes.nullable(false))
4043            .with_column("prepared_statement_name", ScalarType::String.nullable(false))
4044            .with_column("session_id", ScalarType::Uuid.nullable(false))
4045            .with_column("prepared_at", ScalarType::TimestampTz { precision: None }.nullable(false))
4046            .with_column("statement_type", ScalarType::String.nullable(true))
4047            .with_column("throttled_count", ScalarType::UInt64.nullable(false))
4048            .with_column("initial_application_name", ScalarType::String.nullable(false))
4049            .with_column("authenticated_user", ScalarType::String.nullable(false))
4050            .finish(),
4051        column_comments: BTreeMap::new(),
4052        sql: "
4053SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
4054transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
4055error_message, result_size, rows_returned, execution_strategy, transaction_id,
4056mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
4057mpsh.session_id, prepared_at, statement_type, throttled_count,
4058initial_application_name, authenticated_user
4059FROM mz_internal.mz_statement_execution_history mseh,
4060     mz_internal.mz_prepared_statement_history mpsh,
4061     mz_internal.mz_session_history msh
4062WHERE mseh.prepared_statement_id = mpsh.id
4063AND mpsh.session_id = msh.session_id",
4064        access: vec![MONITOR_SELECT],
4065    }
4066});
4067
4068pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4069    BuiltinView {
4070        name: "mz_recent_activity_log_thinned",
4071        schema: MZ_INTERNAL_SCHEMA,
4072        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
4073        desc: RelationDesc::builder()
4074            .with_column("execution_id", ScalarType::Uuid.nullable(false))
4075            .with_column("sample_rate", ScalarType::Float64.nullable(false))
4076            .with_column("cluster_id", ScalarType::String.nullable(true))
4077            .with_column("application_name", ScalarType::String.nullable(false))
4078            .with_column("cluster_name", ScalarType::String.nullable(true))
4079            .with_column("database_name", ScalarType::String.nullable(false))
4080            .with_column("search_path", ScalarType::List { element_type: Box::new(ScalarType::String), custom_id: None }.nullable(false))
4081            .with_column("transaction_isolation", ScalarType::String.nullable(false))
4082            .with_column("execution_timestamp", ScalarType::UInt64.nullable(true))
4083            .with_column("transient_index_id", ScalarType::String.nullable(true))
4084            .with_column("params", ScalarType::Array(Box::new(ScalarType::String)).nullable(false))
4085            .with_column("mz_version", ScalarType::String.nullable(false))
4086            .with_column("began_at", ScalarType::TimestampTz { precision: None }.nullable(false))
4087            .with_column("finished_at", ScalarType::TimestampTz { precision: None }.nullable(true))
4088            .with_column("finished_status", ScalarType::String.nullable(true))
4089            .with_column("error_message", ScalarType::String.nullable(true))
4090            .with_column("result_size", ScalarType::Int64.nullable(true))
4091            .with_column("rows_returned", ScalarType::Int64.nullable(true))
4092            .with_column("execution_strategy", ScalarType::String.nullable(true))
4093            .with_column("transaction_id", ScalarType::UInt64.nullable(false))
4094            .with_column("prepared_statement_id", ScalarType::Uuid.nullable(false))
4095            .with_column("sql_hash", ScalarType::Bytes.nullable(false))
4096            .with_column("prepared_statement_name", ScalarType::String.nullable(false))
4097            .with_column("session_id", ScalarType::Uuid.nullable(false))
4098            .with_column("prepared_at", ScalarType::TimestampTz { precision: None }.nullable(false))
4099            .with_column("statement_type", ScalarType::String.nullable(true))
4100            .with_column("throttled_count", ScalarType::UInt64.nullable(false))
4101            .with_column("initial_application_name", ScalarType::String.nullable(false))
4102            .with_column("authenticated_user", ScalarType::String.nullable(false))
4103            .finish(),
4104        column_comments: BTreeMap::new(),
4105        sql:
4106        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
4107AND began_at + INTERVAL '1 day' > mz_now()",
4108        access: vec![MONITOR_SELECT],
4109    }
4110});
4111
4112pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4113    name: "mz_recent_activity_log",
4114    schema: MZ_INTERNAL_SCHEMA,
4115    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
4116    desc: RelationDesc::builder()
4117        .with_column("execution_id", ScalarType::Uuid.nullable(false))
4118        .with_column("sample_rate", ScalarType::Float64.nullable(false))
4119        .with_column("cluster_id", ScalarType::String.nullable(true))
4120        .with_column("application_name", ScalarType::String.nullable(false))
4121        .with_column("cluster_name", ScalarType::String.nullable(true))
4122        .with_column("database_name", ScalarType::String.nullable(false))
4123        .with_column(
4124            "search_path",
4125            ScalarType::List {
4126                element_type: Box::new(ScalarType::String),
4127                custom_id: None,
4128            }
4129            .nullable(false),
4130        )
4131        .with_column("transaction_isolation", ScalarType::String.nullable(false))
4132        .with_column("execution_timestamp", ScalarType::UInt64.nullable(true))
4133        .with_column("transient_index_id", ScalarType::String.nullable(true))
4134        .with_column(
4135            "params",
4136            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
4137        )
4138        .with_column("mz_version", ScalarType::String.nullable(false))
4139        .with_column(
4140            "began_at",
4141            ScalarType::TimestampTz { precision: None }.nullable(false),
4142        )
4143        .with_column(
4144            "finished_at",
4145            ScalarType::TimestampTz { precision: None }.nullable(true),
4146        )
4147        .with_column("finished_status", ScalarType::String.nullable(true))
4148        .with_column("error_message", ScalarType::String.nullable(true))
4149        .with_column("result_size", ScalarType::Int64.nullable(true))
4150        .with_column("rows_returned", ScalarType::Int64.nullable(true))
4151        .with_column("execution_strategy", ScalarType::String.nullable(true))
4152        .with_column("transaction_id", ScalarType::UInt64.nullable(false))
4153        .with_column("prepared_statement_id", ScalarType::Uuid.nullable(false))
4154        .with_column("sql_hash", ScalarType::Bytes.nullable(false))
4155        .with_column(
4156            "prepared_statement_name",
4157            ScalarType::String.nullable(false),
4158        )
4159        .with_column("session_id", ScalarType::Uuid.nullable(false))
4160        .with_column(
4161            "prepared_at",
4162            ScalarType::TimestampTz { precision: None }.nullable(false),
4163        )
4164        .with_column("statement_type", ScalarType::String.nullable(true))
4165        .with_column("throttled_count", ScalarType::UInt64.nullable(false))
4166        .with_column(
4167            "initial_application_name",
4168            ScalarType::String.nullable(false),
4169        )
4170        .with_column("authenticated_user", ScalarType::String.nullable(false))
4171        .with_column("sql", ScalarType::String.nullable(false))
4172        .finish(),
4173    column_comments: BTreeMap::from_iter([
4174        (
4175            "execution_id",
4176            "An ID that is unique for each executed statement.",
4177        ),
4178        (
4179            "sample_rate",
4180            "The actual rate at which the statement was sampled.",
4181        ),
4182        (
4183            "cluster_id",
4184            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
4185        ),
4186        (
4187            "application_name",
4188            "The value of the `application_name` configuration parameter at execution time.",
4189        ),
4190        (
4191            "cluster_name",
4192            "The name of the cluster with ID `cluster_id` at execution time.",
4193        ),
4194        (
4195            "database_name",
4196            "The value of the `database` configuration parameter at execution time.",
4197        ),
4198        (
4199            "search_path",
4200            "The value of the `search_path` configuration parameter at execution time.",
4201        ),
4202        (
4203            "transaction_isolation",
4204            "The value of the `transaction_isolation` configuration parameter at execution time.",
4205        ),
4206        (
4207            "execution_timestamp",
4208            "The logical timestamp at which execution was scheduled.",
4209        ),
4210        (
4211            "transient_index_id",
4212            "The internal index of the compute dataflow created for the query, if any.",
4213        ),
4214        (
4215            "params",
4216            "The parameters with which the statement was executed.",
4217        ),
4218        (
4219            "mz_version",
4220            "The version of Materialize that was running when the statement was executed.",
4221        ),
4222        (
4223            "began_at",
4224            "The wall-clock time at which the statement began executing.",
4225        ),
4226        (
4227            "finished_at",
4228            "The wall-clock time at which the statement finished executing.",
4229        ),
4230        (
4231            "finished_status",
4232            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). `aborted` means that Materialize exited before the statement finished executing.",
4233        ),
4234        (
4235            "error_message",
4236            "The error message, if the statement failed.",
4237        ),
4238        (
4239            "result_size",
4240            "The size in bytes of the result, for statements that return rows.",
4241        ),
4242        (
4243            "rows_returned",
4244            "The number of rows returned, for statements that return rows.",
4245        ),
4246        (
4247            "execution_strategy",
4248            "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.",
4249        ),
4250        (
4251            "transaction_id",
4252            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
4253        ),
4254        (
4255            "prepared_statement_id",
4256            "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`).",
4257        ),
4258        (
4259            "sql_hash",
4260            "An opaque value uniquely identifying the text of the query.",
4261        ),
4262        (
4263            "prepared_statement_name",
4264            "The name given by the client library to the prepared statement.",
4265        ),
4266        (
4267            "session_id",
4268            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
4269        ),
4270        (
4271            "prepared_at",
4272            "The time at which the statement was prepared.",
4273        ),
4274        (
4275            "statement_type",
4276            "The type of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
4277        ),
4278        (
4279            "throttled_count",
4280            "The number of statements 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.",
4281        ),
4282        (
4283            "initial_application_name",
4284            "The initial value of `application_name` at the beginning of the session.",
4285        ),
4286        (
4287            "authenticated_user",
4288            "The name of the user for which the session was established.",
4289        ),
4290        ("sql", "The SQL text of the statement."),
4291    ]),
4292    sql: "SELECT mralt.*, mrst.sql
4293FROM mz_internal.mz_recent_activity_log_thinned mralt,
4294     mz_internal.mz_recent_sql_text mrst
4295WHERE mralt.sql_hash = mrst.sql_hash",
4296    access: vec![MONITOR_SELECT],
4297});
4298
4299pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4300    BuiltinView {
4301    name: "mz_recent_activity_log_redacted",
4302    schema: MZ_INTERNAL_SCHEMA,
4303    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
4304    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
4305    desc: RelationDesc::builder()
4306        .with_column("execution_id", ScalarType::Uuid.nullable(false))
4307        .with_column("sample_rate", ScalarType::Float64.nullable(false))
4308        .with_column("cluster_id", ScalarType::String.nullable(true))
4309        .with_column("application_name", ScalarType::String.nullable(false))
4310        .with_column("cluster_name", ScalarType::String.nullable(true))
4311        .with_column("database_name", ScalarType::String.nullable(false))
4312        .with_column("search_path", ScalarType::List { element_type: Box::new(ScalarType::String), custom_id: None }.nullable(false))
4313        .with_column("transaction_isolation", ScalarType::String.nullable(false))
4314        .with_column("execution_timestamp", ScalarType::UInt64.nullable(true))
4315        .with_column("transient_index_id", ScalarType::String.nullable(true))
4316        .with_column("params", ScalarType::Array(Box::new(ScalarType::String)).nullable(false))
4317        .with_column("mz_version", ScalarType::String.nullable(false))
4318        .with_column("began_at", ScalarType::TimestampTz { precision: None }.nullable(false))
4319        .with_column("finished_at", ScalarType::TimestampTz { precision: None }.nullable(true))
4320        .with_column("finished_status", ScalarType::String.nullable(true))
4321        .with_column("result_size", ScalarType::Int64.nullable(true))
4322        .with_column("rows_returned", ScalarType::Int64.nullable(true))
4323        .with_column("execution_strategy", ScalarType::String.nullable(true))
4324        .with_column("transaction_id", ScalarType::UInt64.nullable(false))
4325        .with_column("prepared_statement_id", ScalarType::Uuid.nullable(false))
4326        .with_column("sql_hash", ScalarType::Bytes.nullable(false))
4327        .with_column("prepared_statement_name", ScalarType::String.nullable(false))
4328        .with_column("session_id", ScalarType::Uuid.nullable(false))
4329        .with_column("prepared_at", ScalarType::TimestampTz { precision: None }.nullable(false))
4330        .with_column("statement_type", ScalarType::String.nullable(true))
4331        .with_column("throttled_count", ScalarType::UInt64.nullable(false))
4332        .with_column("initial_application_name", ScalarType::String.nullable(false))
4333        .with_column("authenticated_user", ScalarType::String.nullable(false))
4334        .with_column("redacted_sql", ScalarType::String.nullable(false))
4335        .finish(),
4336    column_comments: BTreeMap::new(),
4337    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4338    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4339    mralt.transient_index_id, mralt.params, mralt.mz_version, mralt.began_at, mralt.finished_at,
4340    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4341    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4342    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4343    mralt.initial_application_name, mralt.authenticated_user,
4344    mrst.redacted_sql
4345FROM mz_internal.mz_recent_activity_log_thinned mralt,
4346     mz_internal.mz_recent_sql_text mrst
4347WHERE mralt.sql_hash = mrst.sql_hash",
4348    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4349}
4350});
4351
4352pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4353    BuiltinSource {
4354        name: "mz_statement_lifecycle_history",
4355        schema: MZ_INTERNAL_SCHEMA,
4356        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4357        desc: RelationDesc::builder()
4358            .with_column("statement_id", ScalarType::Uuid.nullable(false))
4359            .with_column("event_type", ScalarType::String.nullable(false))
4360            .with_column(
4361                "occurred_at",
4362                ScalarType::TimestampTz { precision: None }.nullable(false),
4363            )
4364            .finish(),
4365        data_source: IntrospectionType::StatementLifecycleHistory,
4366        column_comments: BTreeMap::from_iter([
4367            (
4368                "statement_id",
4369                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4370            ),
4371            (
4372                "event_type",
4373                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4374            ),
4375            ("occurred_at", "The time at which the event took place."),
4376        ]),
4377        is_retained_metrics_object: false,
4378        // TODO[btv]: Maybe this should be public instead of
4379        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4380        // chagne, we probably don't need to worry about it now.
4381        access: vec![
4382            SUPPORT_SELECT,
4383            ANALYTICS_SELECT,
4384            MONITOR_REDACTED_SELECT,
4385            MONITOR_SELECT,
4386        ],
4387    }
4388});
4389
4390pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4391    name: "mz_source_statuses",
4392    schema: MZ_INTERNAL_SCHEMA,
4393    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4394    desc: RelationDesc::builder()
4395        .with_column("id", ScalarType::String.nullable(false))
4396        .with_column("name", ScalarType::String.nullable(false))
4397        .with_column("type", ScalarType::String.nullable(false))
4398        .with_column(
4399            "last_status_change_at",
4400            ScalarType::TimestampTz { precision: None }.nullable(true),
4401        )
4402        .with_column("status", ScalarType::String.nullable(false))
4403        .with_column("error", ScalarType::String.nullable(true))
4404        .with_column("details", ScalarType::Jsonb.nullable(true))
4405        .finish(),
4406    column_comments: BTreeMap::from_iter([
4407        (
4408            "id",
4409            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4410        ),
4411        ("name", "The name of the source."),
4412        ("type", "The type of the source."),
4413        (
4414            "last_status_change_at",
4415            "Wall-clock timestamp of the source status change.",
4416        ),
4417        (
4418            "status",
4419            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4420        ),
4421        (
4422            "error",
4423            "If the source is in an error state, the error message.",
4424        ),
4425        (
4426            "details",
4427            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4428        ),
4429    ]),
4430    sql: "
4431    WITH
4432    -- The status history contains per-replica events and source-global events.
4433    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4434    -- we can treat them uniformly below.
4435    uniform_status_history AS
4436    (
4437        SELECT
4438            s.source_id,
4439            COALESCE(s.replica_id, '<source>') as replica_id,
4440            s.occurred_at,
4441            s.status,
4442            s.error,
4443            s.details
4444        FROM mz_internal.mz_source_status_history s
4445    ),
4446    -- For getting the latest events, we first determine the latest per-replica
4447    -- events here and then apply precedence rules below.
4448    latest_per_replica_events AS
4449    (
4450        SELECT DISTINCT ON (source_id, replica_id)
4451            occurred_at, source_id, replica_id, status, error, details
4452        FROM uniform_status_history
4453        ORDER BY source_id, replica_id, occurred_at DESC
4454    ),
4455    -- We have a precedence list that determines the overall status in case
4456    -- there is differing per-replica (including source-global) statuses. If
4457    -- there is no 'dropped' status, and any replica reports 'running', the
4458    -- overall status is 'running' even if there might be some replica that has
4459    -- errors or is paused.
4460    latest_events AS
4461    (
4462       SELECT DISTINCT ON (source_id)
4463            source_id,
4464            occurred_at,
4465            status,
4466            error,
4467            details
4468        FROM latest_per_replica_events
4469        ORDER BY source_id, CASE status
4470                    WHEN 'dropped' THEN 1
4471                    WHEN 'running' THEN 2
4472                    WHEN 'stalled' THEN 3
4473                    WHEN 'starting' THEN 4
4474                    WHEN 'paused' THEN 5
4475                    WHEN 'ceased' THEN 6
4476                    ELSE 7  -- For any other status values
4477                END
4478    ),
4479    -- Determine which sources are subsources and which are parent sources
4480    subsources AS
4481    (
4482        SELECT subsources.id AS self, sources.id AS parent
4483        FROM
4484            mz_catalog.mz_sources AS subsources
4485                JOIN
4486                    mz_internal.mz_object_dependencies AS deps
4487                    ON subsources.id = deps.object_id
4488                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4489    ),
4490    -- Determine which sources are source tables
4491    tables AS
4492    (
4493        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4494        FROM mz_catalog.mz_tables AS tables
4495        WHERE tables.source_id IS NOT NULL
4496    ),
4497    -- Determine which collection's ID to use for the status
4498    id_of_status_to_use AS
4499    (
4500        SELECT
4501            self_events.source_id,
4502            -- If self not errored, but parent is, use parent; else self
4503            CASE
4504                WHEN
4505                    self_events.status <> 'ceased' AND
4506                    parent_events.status = 'stalled'
4507                THEN parent_events.source_id
4508                -- TODO: Remove this once subsources eagerly propogate their status
4509                -- Subsources move from starting to running lazily once they see
4510                -- a record flow through, even though they are online and healthy.
4511                -- This has been repeatedly brought up as confusing by users.
4512                -- So now, if the parent source is running, and the subsource is
4513                -- starting, we override its status to running to relfect its healthy
4514                -- status.
4515                WHEN
4516                    self_events.status = 'starting' AND
4517                    parent_events.status = 'running'
4518                THEN parent_events.source_id
4519                ELSE self_events.source_id
4520            END AS id_to_use
4521        FROM
4522            latest_events AS self_events
4523                LEFT JOIN subsources ON self_events.source_id = subsources.self
4524                LEFT JOIN tables ON self_events.source_id = tables.self
4525                LEFT JOIN
4526                    latest_events AS parent_events
4527                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4528    ),
4529    -- Swap out events for the ID of the event we plan to use instead
4530    latest_events_to_use AS
4531    (
4532        SELECT occurred_at, s.source_id, status, error, details
4533        FROM
4534            id_of_status_to_use AS s
4535                JOIN latest_events AS e ON e.source_id = s.id_to_use
4536    ),
4537    combined AS (
4538        SELECT
4539            mz_sources.id,
4540            mz_sources.name,
4541            mz_sources.type,
4542            occurred_at,
4543            status,
4544            error,
4545            details
4546        FROM
4547            mz_catalog.mz_sources
4548            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4549        UNION ALL
4550        SELECT
4551            tables.self AS id,
4552            tables.name,
4553            'table' AS type,
4554            occurred_at,
4555            status,
4556            error,
4557            details
4558        FROM
4559            tables
4560            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4561    )
4562SELECT
4563    id,
4564    name,
4565    type,
4566    occurred_at AS last_status_change_at,
4567    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4568    CASE
4569        WHEN
4570            type = 'webhook' OR
4571            type = 'progress'
4572        THEN 'running'
4573        ELSE COALESCE(status, 'created')
4574    END AS status,
4575    error,
4576    details
4577FROM combined
4578WHERE id NOT LIKE 's%';",
4579    access: vec![PUBLIC_SELECT],
4580});
4581
4582pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4583    name: "mz_sink_status_history",
4584    schema: MZ_INTERNAL_SCHEMA,
4585    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4586    data_source: IntrospectionType::SinkStatusHistory,
4587    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4588    column_comments: BTreeMap::from_iter([
4589        (
4590            "occurred_at",
4591            "Wall-clock timestamp of the sink status change.",
4592        ),
4593        (
4594            "sink_id",
4595            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4596        ),
4597        (
4598            "status",
4599            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4600        ),
4601        (
4602            "error",
4603            "If the sink is in an error state, the error message.",
4604        ),
4605        (
4606            "details",
4607            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4608        ),
4609        (
4610            "replica_id",
4611            "The ID of the replica that an instance of a sink is running on.",
4612        ),
4613    ]),
4614    is_retained_metrics_object: false,
4615    access: vec![PUBLIC_SELECT],
4616});
4617
4618pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4619    name: "mz_sink_statuses",
4620    schema: MZ_INTERNAL_SCHEMA,
4621    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4622    desc: RelationDesc::builder()
4623        .with_column("id", ScalarType::String.nullable(false))
4624        .with_column("name", ScalarType::String.nullable(false))
4625        .with_column("type", ScalarType::String.nullable(false))
4626        .with_column(
4627            "last_status_change_at",
4628            ScalarType::TimestampTz { precision: None }.nullable(true),
4629        )
4630        .with_column("status", ScalarType::String.nullable(false))
4631        .with_column("error", ScalarType::String.nullable(true))
4632        .with_column("details", ScalarType::Jsonb.nullable(true))
4633        .finish(),
4634    column_comments: BTreeMap::from_iter([
4635        (
4636            "id",
4637            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4638        ),
4639        ("name", "The name of the sink."),
4640        ("type", "The type of the sink."),
4641        (
4642            "last_status_change_at",
4643            "Wall-clock timestamp of the sink status change.",
4644        ),
4645        (
4646            "status",
4647            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4648        ),
4649        (
4650            "error",
4651            "If the sink is in an error state, the error message.",
4652        ),
4653        (
4654            "details",
4655            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4656        ),
4657    ]),
4658    sql: "
4659WITH
4660-- The status history contains per-replica events and sink-global events.
4661-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
4662-- we can treat them uniformly below.
4663uniform_status_history AS
4664(
4665    SELECT
4666        s.sink_id,
4667        COALESCE(s.replica_id, '<sink>') as replica_id,
4668        s.occurred_at,
4669        s.status,
4670        s.error,
4671        s.details
4672    FROM mz_internal.mz_sink_status_history s
4673),
4674-- For getting the latest events, we first determine the latest per-replica
4675-- events here and then apply precedence rules below.
4676latest_per_replica_events AS
4677(
4678    SELECT DISTINCT ON (sink_id, replica_id)
4679        occurred_at, sink_id, replica_id, status, error, details
4680    FROM uniform_status_history
4681    ORDER BY sink_id, replica_id, occurred_at DESC
4682),
4683-- We have a precedence list that determines the overall status in case
4684-- there is differing per-replica (including sink-global) statuses. If
4685-- there is no 'dropped' status, and any replica reports 'running', the
4686-- overall status is 'running' even if there might be some replica that has
4687-- errors or is paused.
4688latest_events AS
4689(
4690    SELECT DISTINCT ON (sink_id)
4691        sink_id,
4692        occurred_at,
4693        status,
4694        error,
4695        details
4696    FROM latest_per_replica_events
4697    ORDER BY sink_id, CASE status
4698                WHEN 'dropped' THEN 1
4699                WHEN 'running' THEN 2
4700                WHEN 'stalled' THEN 3
4701                WHEN 'starting' THEN 4
4702                WHEN 'paused' THEN 5
4703                WHEN 'ceased' THEN 6
4704                ELSE 7  -- For any other status values
4705            END
4706)
4707SELECT
4708    mz_sinks.id,
4709    name,
4710    mz_sinks.type,
4711    occurred_at as last_status_change_at,
4712    coalesce(status, 'created') as status,
4713    error,
4714    details
4715FROM mz_catalog.mz_sinks
4716LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
4717WHERE
4718    -- This is a convenient way to filter out system sinks, like the status_history table itself.
4719    mz_sinks.id NOT LIKE 's%'",
4720    access: vec![PUBLIC_SELECT],
4721});
4722
4723pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
4724    LazyLock::new(|| SystemObjectDescription {
4725        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
4726        object_type: CatalogItemType::Table,
4727        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
4728    });
4729
4730pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4731    name: "mz_storage_usage_by_shard",
4732    schema: MZ_INTERNAL_SCHEMA,
4733    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
4734    desc: RelationDesc::builder()
4735        .with_column("id", ScalarType::UInt64.nullable(false))
4736        .with_column("shard_id", ScalarType::String.nullable(true))
4737        .with_column("size_bytes", ScalarType::UInt64.nullable(false))
4738        .with_column(
4739            "collection_timestamp",
4740            ScalarType::TimestampTz { precision: None }.nullable(false),
4741        )
4742        .finish(),
4743    column_comments: BTreeMap::new(),
4744    is_retained_metrics_object: false,
4745    access: vec![PUBLIC_SELECT],
4746});
4747
4748pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4749    name: "mz_egress_ips",
4750    schema: MZ_CATALOG_SCHEMA,
4751    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
4752    desc: RelationDesc::builder()
4753        .with_column("egress_ip", ScalarType::String.nullable(false))
4754        .with_column("prefix_length", ScalarType::Int32.nullable(false))
4755        .with_column("cidr", ScalarType::String.nullable(false))
4756        .finish(),
4757    column_comments: BTreeMap::from_iter([
4758        ("egress_ip", "The start of the range of IP addresses."),
4759        (
4760            "prefix_length",
4761            "The number of leading bits in the CIDR netmask.",
4762        ),
4763        ("cidr", "The CIDR representation."),
4764    ]),
4765    is_retained_metrics_object: false,
4766    access: vec![PUBLIC_SELECT],
4767});
4768
4769pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
4770    LazyLock::new(|| BuiltinTable {
4771        name: "mz_aws_privatelink_connections",
4772        schema: MZ_CATALOG_SCHEMA,
4773        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
4774        desc: RelationDesc::builder()
4775            .with_column("id", ScalarType::String.nullable(false))
4776            .with_column("principal", ScalarType::String.nullable(false))
4777            .finish(),
4778        column_comments: BTreeMap::from_iter([
4779            ("id", "The ID of the connection."),
4780            (
4781                "principal",
4782                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
4783            ),
4784        ]),
4785        is_retained_metrics_object: false,
4786        access: vec![PUBLIC_SELECT],
4787    });
4788
4789pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4790    name: "mz_aws_connections",
4791    schema: MZ_INTERNAL_SCHEMA,
4792    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
4793    desc: RelationDesc::builder()
4794        .with_column("id", ScalarType::String.nullable(false))
4795        .with_column("endpoint", ScalarType::String.nullable(true))
4796        .with_column("region", ScalarType::String.nullable(true))
4797        .with_column("access_key_id", ScalarType::String.nullable(true))
4798        .with_column("access_key_id_secret_id", ScalarType::String.nullable(true))
4799        .with_column(
4800            "secret_access_key_secret_id",
4801            ScalarType::String.nullable(true),
4802        )
4803        .with_column("session_token", ScalarType::String.nullable(true))
4804        .with_column("session_token_secret_id", ScalarType::String.nullable(true))
4805        .with_column("assume_role_arn", ScalarType::String.nullable(true))
4806        .with_column(
4807            "assume_role_session_name",
4808            ScalarType::String.nullable(true),
4809        )
4810        .with_column("principal", ScalarType::String.nullable(true))
4811        .with_column("external_id", ScalarType::String.nullable(true))
4812        .with_column("example_trust_policy", ScalarType::Jsonb.nullable(true))
4813        .finish(),
4814    column_comments: BTreeMap::from_iter([
4815        ("id", "The ID of the connection."),
4816        ("endpoint", "The value of the `ENDPOINT` option, if set."),
4817        ("region", "The value of the `REGION` option, if set."),
4818        (
4819            "access_key_id",
4820            "The value of the `ACCESS KEY ID` option, if provided in line.",
4821        ),
4822        (
4823            "access_key_id_secret_id",
4824            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
4825        ),
4826        (
4827            "secret_access_key_secret_id",
4828            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
4829        ),
4830        (
4831            "session_token",
4832            "The value of the `SESSION TOKEN` option, if provided in line.",
4833        ),
4834        (
4835            "session_token_secret_id",
4836            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
4837        ),
4838        (
4839            "assume_role_arn",
4840            "The value of the `ASSUME ROLE ARN` option, if set.",
4841        ),
4842        (
4843            "assume_role_session_name",
4844            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
4845        ),
4846        (
4847            "principal",
4848            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4849        ),
4850        (
4851            "external_id",
4852            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4853        ),
4854        (
4855            "example_trust_policy",
4856            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
4857        ),
4858    ]),
4859    is_retained_metrics_object: false,
4860    access: vec![PUBLIC_SELECT],
4861});
4862
4863// TODO(teskje) Remove this table in favor of `MZ_CLUSTER_REPLICA_METRICS_HISTORY`, once the latter
4864//              has been backfilled to 30 days worth of data.
4865pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4866    name: "mz_cluster_replica_metrics",
4867    schema: MZ_INTERNAL_SCHEMA,
4868    oid: oid::TABLE_MZ_CLUSTER_REPLICA_METRICS_OID,
4869    desc: RelationDesc::builder()
4870        .with_column("replica_id", ScalarType::String.nullable(false))
4871        .with_column("process_id", ScalarType::UInt64.nullable(false))
4872        .with_column("cpu_nano_cores", ScalarType::UInt64.nullable(true))
4873        .with_column("memory_bytes", ScalarType::UInt64.nullable(true))
4874        .with_column("disk_bytes", ScalarType::UInt64.nullable(true))
4875        .finish(),
4876    column_comments: BTreeMap::from_iter([
4877        ("replica_id", "The ID of a cluster replica."),
4878        ("process_id", "The ID of a process within the replica."),
4879        (
4880            "cpu_nano_cores",
4881            "Approximate CPU usage, in billionths of a vCPU core.",
4882        ),
4883        ("memory_bytes", "Approximate RAM usage, in bytes."),
4884        ("disk_bytes", "Approximate disk usage in bytes."),
4885    ]),
4886    is_retained_metrics_object: true,
4887    access: vec![PUBLIC_SELECT],
4888});
4889
4890pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
4891    LazyLock::new(|| BuiltinSource {
4892        name: "mz_cluster_replica_metrics_history",
4893        schema: MZ_INTERNAL_SCHEMA,
4894        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4895        data_source: IntrospectionType::ReplicaMetricsHistory,
4896        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4897        column_comments: BTreeMap::from_iter([
4898            ("replica_id", "The ID of a cluster replica."),
4899            ("process_id", "The ID of a process within the replica."),
4900            (
4901                "cpu_nano_cores",
4902                "Approximate CPU usage in billionths of a vCPU core.",
4903            ),
4904            ("memory_bytes", "Approximate memory usage in bytes."),
4905            ("disk_bytes", "Approximate disk usage in bytes."),
4906            (
4907                "occurred_at",
4908                "Wall-clock timestamp at which the event occurred.",
4909            ),
4910        ]),
4911        is_retained_metrics_object: false,
4912        access: vec![PUBLIC_SELECT],
4913    });
4914
4915pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
4916    || {
4917        BuiltinContinualTask {
4918            name: "mz_cluster_replica_metrics_history_ct",
4919            schema: MZ_INTERNAL_SCHEMA,
4920            oid: oid::CT_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4921            desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4922            sql: "
4923IN CLUSTER mz_catalog_server
4924ON INPUT mz_internal.mz_cluster_replica_metrics_history AS (
4925    DELETE FROM mz_internal.mz_cluster_replica_metrics_history_ct WHERE occurred_at + '30d' < mz_now();
4926    INSERT INTO mz_internal.mz_cluster_replica_metrics_history_ct SELECT * FROM mz_internal.mz_cluster_replica_metrics_history;
4927)",
4928            access: vec![PUBLIC_SELECT],
4929        }
4930    },
4931);
4932
4933pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
4934    LazyLock::new(|| BuiltinSource {
4935        name: "mz_cluster_replica_frontiers",
4936        schema: MZ_CATALOG_SCHEMA,
4937        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
4938        data_source: IntrospectionType::ReplicaFrontiers,
4939        desc: RelationDesc::builder()
4940            .with_column("object_id", ScalarType::String.nullable(false))
4941            .with_column("replica_id", ScalarType::String.nullable(false))
4942            .with_column("write_frontier", ScalarType::MzTimestamp.nullable(true))
4943            .finish(),
4944        column_comments: BTreeMap::from_iter([
4945            (
4946                "object_id",
4947                "The ID of the source, sink, index, materialized view, or subscription.",
4948            ),
4949            ("replica_id", "The ID of a cluster replica."),
4950            (
4951                "write_frontier",
4952                "The next timestamp at which the output may change.",
4953            ),
4954        ]),
4955        is_retained_metrics_object: false,
4956        access: vec![PUBLIC_SELECT],
4957    });
4958
4959pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
4960    LazyLock::new(|| BuiltinIndex {
4961        name: "mz_cluster_replica_frontiers_ind",
4962        schema: MZ_CATALOG_SCHEMA,
4963        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
4964        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
4965        is_retained_metrics_object: false,
4966    });
4967
4968pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4969    name: "mz_frontiers",
4970    schema: MZ_INTERNAL_SCHEMA,
4971    oid: oid::SOURCE_MZ_FRONTIERS_OID,
4972    data_source: IntrospectionType::Frontiers,
4973    desc: RelationDesc::builder()
4974        .with_column("object_id", ScalarType::String.nullable(false))
4975        .with_column("read_frontier", ScalarType::MzTimestamp.nullable(true))
4976        .with_column("write_frontier", ScalarType::MzTimestamp.nullable(true))
4977        .finish(),
4978    column_comments: BTreeMap::from_iter([
4979        (
4980            "object_id",
4981            "The ID of the source, sink, table, index, materialized view, or subscription.",
4982        ),
4983        (
4984            "read_frontier",
4985            "The earliest timestamp at which the output is still readable.",
4986        ),
4987        (
4988            "write_frontier",
4989            "The next timestamp at which the output may change.",
4990        ),
4991    ]),
4992    is_retained_metrics_object: false,
4993    access: vec![PUBLIC_SELECT],
4994});
4995
4996/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
4997pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4998    name: "mz_global_frontiers",
4999    schema: MZ_INTERNAL_SCHEMA,
5000    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5001    desc: RelationDesc::builder()
5002        .with_column("object_id", ScalarType::String.nullable(false))
5003        .with_column("time", ScalarType::MzTimestamp.nullable(false))
5004        .finish(),
5005    column_comments: BTreeMap::new(),
5006    sql: "
5007SELECT object_id, write_frontier AS time
5008FROM mz_internal.mz_frontiers
5009WHERE write_frontier IS NOT NULL",
5010    access: vec![PUBLIC_SELECT],
5011});
5012
5013pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5014    name: "mz_wallclock_lag_history",
5015    schema: MZ_INTERNAL_SCHEMA,
5016    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5017    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5018    data_source: IntrospectionType::WallclockLagHistory,
5019    column_comments: BTreeMap::from_iter([
5020        (
5021            "object_id",
5022            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5023        ),
5024        (
5025            "replica_id",
5026            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5027        ),
5028        (
5029            "lag",
5030            "The amount of time the object's write frontier lags behind wallclock time.",
5031        ),
5032        (
5033            "occurred_at",
5034            "Wall-clock timestamp at which the event occurred.",
5035        ),
5036    ]),
5037    is_retained_metrics_object: false,
5038    access: vec![PUBLIC_SELECT],
5039});
5040
5041pub static MZ_WALLCLOCK_LAG_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(|| {
5042    BuiltinContinualTask {
5043    name: "mz_wallclock_lag_history_ct",
5044    schema: MZ_INTERNAL_SCHEMA,
5045    oid: oid::CT_MZ_WALLCLOCK_LAG_HISTORY_OID,
5046    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5047    sql: "
5048IN CLUSTER mz_catalog_server
5049ON INPUT mz_internal.mz_wallclock_lag_history AS (
5050    DELETE FROM mz_internal.mz_wallclock_lag_history_ct WHERE occurred_at + '30d' < mz_now();
5051    INSERT INTO mz_internal.mz_wallclock_lag_history_ct SELECT * FROM mz_internal.mz_wallclock_lag_history;
5052)",
5053            access: vec![PUBLIC_SELECT],
5054        }
5055});
5056
5057pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5058    name: "mz_wallclock_global_lag_history",
5059    schema: MZ_INTERNAL_SCHEMA,
5060    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5061    desc: RelationDesc::builder()
5062        .with_column("object_id", ScalarType::String.nullable(false))
5063        .with_column("lag", ScalarType::Interval.nullable(false))
5064        .with_column(
5065            "occurred_at",
5066            ScalarType::TimestampTz { precision: None }.nullable(false),
5067        )
5068        .with_key(vec![0, 2])
5069        .finish(),
5070    column_comments: BTreeMap::new(),
5071    sql: "
5072WITH times_binned AS (
5073    SELECT
5074        object_id,
5075        lag,
5076        date_trunc('minute', occurred_at) AS occurred_at
5077    FROM mz_internal.mz_wallclock_lag_history
5078)
5079SELECT
5080    object_id,
5081    min(lag) AS lag,
5082    occurred_at
5083FROM times_binned
5084GROUP BY object_id, occurred_at
5085OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5086    access: vec![PUBLIC_SELECT],
5087});
5088
5089pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> =
5090    LazyLock::new(|| BuiltinView {
5091        name: "mz_wallclock_global_lag_recent_history",
5092        schema: MZ_INTERNAL_SCHEMA,
5093        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5094        desc: RelationDesc::builder()
5095            .with_column("object_id", ScalarType::String.nullable(false))
5096            .with_column("lag", ScalarType::Interval.nullable(false))
5097            .with_column(
5098                "occurred_at",
5099                ScalarType::TimestampTz { precision: None }.nullable(false),
5100            )
5101            .with_key(vec![0, 2])
5102            .finish(),
5103        column_comments: BTreeMap::new(),
5104        sql: "
5105SELECT object_id, lag, occurred_at
5106FROM mz_internal.mz_wallclock_global_lag_history
5107WHERE occurred_at + '1 day' > mz_now()",
5108        access: vec![PUBLIC_SELECT],
5109    });
5110
5111pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5112    name: "mz_wallclock_global_lag",
5113    schema: MZ_INTERNAL_SCHEMA,
5114    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5115    desc: RelationDesc::builder()
5116        .with_column("object_id", ScalarType::String.nullable(false))
5117        .with_column("lag", ScalarType::Interval.nullable(false))
5118        .with_key(vec![0])
5119        .finish(),
5120    column_comments: BTreeMap::from_iter([
5121        (
5122            "object_id",
5123            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5124        ),
5125        (
5126            "lag",
5127            "The amount of time the object's write frontier lags behind wallclock time.",
5128        ),
5129    ]),
5130    sql: "
5131SELECT DISTINCT ON (object_id) object_id, lag
5132FROM mz_internal.mz_wallclock_global_lag_recent_history
5133WHERE occurred_at + '5 minutes' > mz_now()
5134ORDER BY object_id, occurred_at DESC",
5135    access: vec![PUBLIC_SELECT],
5136});
5137
5138pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5139    LazyLock::new(|| BuiltinSource {
5140        name: "mz_wallclock_global_lag_histogram_raw",
5141        schema: MZ_INTERNAL_SCHEMA,
5142        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5143        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5144        column_comments: BTreeMap::new(),
5145        data_source: IntrospectionType::WallclockLagHistogram,
5146        is_retained_metrics_object: false,
5147        access: vec![PUBLIC_SELECT],
5148    });
5149
5150pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5151    LazyLock::new(|| BuiltinView {
5152        name: "mz_wallclock_global_lag_histogram",
5153        schema: MZ_INTERNAL_SCHEMA,
5154        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5155        desc: RelationDesc::builder()
5156            .with_column(
5157                "period_start",
5158                ScalarType::TimestampTz { precision: None }.nullable(false),
5159            )
5160            .with_column(
5161                "period_end",
5162                ScalarType::TimestampTz { precision: None }.nullable(false),
5163            )
5164            .with_column("object_id", ScalarType::String.nullable(false))
5165            .with_column("lag_seconds", ScalarType::UInt64.nullable(false))
5166            .with_column("labels", ScalarType::Jsonb.nullable(false))
5167            .with_column("count", ScalarType::Int64.nullable(false))
5168            .with_key(vec![0, 1, 2, 3, 4])
5169            .finish(),
5170        column_comments: BTreeMap::new(),
5171        sql: "
5172SELECT *, count(*) AS count
5173FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5174GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5175        access: vec![PUBLIC_SELECT],
5176    });
5177
5178pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5179    BuiltinSource {
5180        name: "mz_materialized_view_refreshes",
5181        schema: MZ_INTERNAL_SCHEMA,
5182        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5183        data_source: IntrospectionType::ComputeMaterializedViewRefreshes,
5184        desc: RelationDesc::builder()
5185            .with_column("materialized_view_id", ScalarType::String.nullable(false))
5186            .with_column(
5187                "last_completed_refresh",
5188                ScalarType::MzTimestamp.nullable(true),
5189            )
5190            .with_column("next_refresh", ScalarType::MzTimestamp.nullable(true))
5191            .finish(),
5192        column_comments: BTreeMap::from_iter([
5193            (
5194                "materialized_view_id",
5195                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5196            ),
5197            (
5198                "last_completed_refresh",
5199                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5200            ),
5201            (
5202                "next_refresh",
5203                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5204            ),
5205        ]),
5206        is_retained_metrics_object: false,
5207        access: vec![PUBLIC_SELECT],
5208    }
5209});
5210
5211pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5212    name: "mz_subscriptions",
5213    schema: MZ_INTERNAL_SCHEMA,
5214    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5215    desc: RelationDesc::builder()
5216        .with_column("id", ScalarType::String.nullable(false))
5217        .with_column("session_id", ScalarType::Uuid.nullable(false))
5218        .with_column("cluster_id", ScalarType::String.nullable(false))
5219        .with_column(
5220            "created_at",
5221            ScalarType::TimestampTz { precision: None }.nullable(false),
5222        )
5223        .with_column(
5224            "referenced_object_ids",
5225            ScalarType::List {
5226                element_type: Box::new(ScalarType::String),
5227                custom_id: None,
5228            }
5229            .nullable(false),
5230        )
5231        .finish(),
5232    column_comments: BTreeMap::from_iter([
5233        ("id", "The ID of the subscription."),
5234        (
5235            "session_id",
5236            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5237        ),
5238        (
5239            "cluster_id",
5240            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5241        ),
5242        (
5243            "created_at",
5244            "The time at which the subscription was created.",
5245        ),
5246        (
5247            "referenced_object_ids",
5248            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5249        ),
5250    ]),
5251    is_retained_metrics_object: false,
5252    access: vec![PUBLIC_SELECT],
5253});
5254
5255pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5256    name: "mz_sessions",
5257    schema: MZ_INTERNAL_SCHEMA,
5258    oid: oid::TABLE_MZ_SESSIONS_OID,
5259    desc: RelationDesc::builder()
5260        .with_column("id", ScalarType::Uuid.nullable(false))
5261        .with_column("connection_id", ScalarType::UInt32.nullable(false))
5262        .with_column("role_id", ScalarType::String.nullable(false))
5263        .with_column("client_ip", ScalarType::String.nullable(true))
5264        .with_column(
5265            "connected_at",
5266            ScalarType::TimestampTz { precision: None }.nullable(false),
5267        )
5268        .finish(),
5269    column_comments: BTreeMap::from_iter([
5270        ("id", "The globally unique ID of the session."),
5271        (
5272            "connection_id",
5273            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5274        ),
5275        (
5276            "role_id",
5277            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5278        ),
5279        (
5280            "client_ip",
5281            "The IP address of the client that initiated the session.",
5282        ),
5283        (
5284            "connected_at",
5285            "The time at which the session connected to the system.",
5286        ),
5287    ]),
5288    is_retained_metrics_object: false,
5289    access: vec![PUBLIC_SELECT],
5290});
5291
5292pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5293    name: "mz_default_privileges",
5294    schema: MZ_CATALOG_SCHEMA,
5295    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5296    desc: RelationDesc::builder()
5297        .with_column("role_id", ScalarType::String.nullable(false))
5298        .with_column("database_id", ScalarType::String.nullable(true))
5299        .with_column("schema_id", ScalarType::String.nullable(true))
5300        .with_column("object_type", ScalarType::String.nullable(false))
5301        .with_column("grantee", ScalarType::String.nullable(false))
5302        .with_column("privileges", ScalarType::String.nullable(false))
5303        .finish(),
5304    column_comments: BTreeMap::from_iter([
5305        (
5306            "role_id",
5307            "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.",
5308        ),
5309        (
5310            "database_id",
5311            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5312        ),
5313        (
5314            "schema_id",
5315            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5316        ),
5317        (
5318            "object_type",
5319            "Privileges described in this row will be granted only on objects of type `object_type`.",
5320        ),
5321        (
5322            "grantee",
5323            "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.",
5324        ),
5325        ("privileges", "The set of privileges that will be granted."),
5326    ]),
5327    is_retained_metrics_object: false,
5328    access: vec![PUBLIC_SELECT],
5329});
5330
5331pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5332    name: "mz_system_privileges",
5333    schema: MZ_CATALOG_SCHEMA,
5334    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5335    desc: RelationDesc::builder()
5336        .with_column("privileges", ScalarType::MzAclItem.nullable(false))
5337        .finish(),
5338    column_comments: BTreeMap::from_iter([(
5339        "privileges",
5340        "The privileges belonging to the system.",
5341    )]),
5342    is_retained_metrics_object: false,
5343    access: vec![PUBLIC_SELECT],
5344});
5345
5346pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5347    name: "mz_comments",
5348    schema: MZ_INTERNAL_SCHEMA,
5349    oid: oid::TABLE_MZ_COMMENTS_OID,
5350    desc: RelationDesc::builder()
5351        .with_column("id", ScalarType::String.nullable(false))
5352        .with_column("object_type", ScalarType::String.nullable(false))
5353        .with_column("object_sub_id", ScalarType::Int32.nullable(true))
5354        .with_column("comment", ScalarType::String.nullable(false))
5355        .finish(),
5356    column_comments: BTreeMap::from_iter([
5357        (
5358            "id",
5359            "The ID of the object. Corresponds to `mz_objects.id`.",
5360        ),
5361        (
5362            "object_type",
5363            "The type of object the comment is associated with.",
5364        ),
5365        (
5366            "object_sub_id",
5367            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5368        ),
5369        ("comment", "The comment itself."),
5370    ]),
5371    is_retained_metrics_object: false,
5372    access: vec![PUBLIC_SELECT],
5373});
5374
5375pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5376    name: "mz_source_references",
5377    schema: MZ_INTERNAL_SCHEMA,
5378    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5379    desc: RelationDesc::builder()
5380        .with_column("source_id", ScalarType::String.nullable(false))
5381        .with_column("namespace", ScalarType::String.nullable(true))
5382        .with_column("name", ScalarType::String.nullable(false))
5383        .with_column(
5384            "updated_at",
5385            ScalarType::TimestampTz { precision: None }.nullable(false),
5386        )
5387        .with_column(
5388            "columns",
5389            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
5390        )
5391        .finish(),
5392    column_comments: BTreeMap::new(),
5393    is_retained_metrics_object: false,
5394    access: vec![PUBLIC_SELECT],
5395});
5396
5397pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5398    name: "mz_webhook_sources",
5399    schema: MZ_INTERNAL_SCHEMA,
5400    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5401    desc: RelationDesc::builder()
5402        .with_column("id", ScalarType::String.nullable(false))
5403        .with_column("name", ScalarType::String.nullable(false))
5404        .with_column("url", ScalarType::String.nullable(false))
5405        .finish(),
5406    column_comments: BTreeMap::from_iter([
5407        (
5408            "id",
5409            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5410        ),
5411        ("name", "The name of the webhook source."),
5412        (
5413            "url",
5414            "The URL which can be used to send events to the source.",
5415        ),
5416    ]),
5417    is_retained_metrics_object: false,
5418    access: vec![PUBLIC_SELECT],
5419});
5420
5421pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5422    BuiltinTable {
5423        name: "mz_history_retention_strategies",
5424        schema: MZ_INTERNAL_SCHEMA,
5425        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5426        desc: RelationDesc::builder()
5427            .with_column("id", ScalarType::String.nullable(false))
5428            .with_column("strategy", ScalarType::String.nullable(false))
5429            .with_column("value", ScalarType::Jsonb.nullable(false))
5430            .finish(),
5431        column_comments: BTreeMap::from_iter([
5432            ("id", "The ID of the object."),
5433            (
5434                "strategy",
5435                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5436            ),
5437            (
5438                "value",
5439                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5440            ),
5441        ]),
5442        is_retained_metrics_object: false,
5443        access: vec![PUBLIC_SELECT],
5444    }
5445});
5446
5447// These will be replaced with per-replica tables once source/sink multiplexing on
5448// a single cluster is supported.
5449pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5450    name: "mz_source_statistics_raw",
5451    schema: MZ_INTERNAL_SCHEMA,
5452    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5453    data_source: IntrospectionType::StorageSourceStatistics,
5454    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5455    column_comments: BTreeMap::new(),
5456    is_retained_metrics_object: true,
5457    access: vec![PUBLIC_SELECT],
5458});
5459pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5460    name: "mz_sink_statistics_raw",
5461    schema: MZ_INTERNAL_SCHEMA,
5462    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5463    data_source: IntrospectionType::StorageSinkStatistics,
5464    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5465    column_comments: BTreeMap::new(),
5466    is_retained_metrics_object: true,
5467    access: vec![PUBLIC_SELECT],
5468});
5469
5470pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5471    name: "mz_storage_shards",
5472    schema: MZ_INTERNAL_SCHEMA,
5473    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5474    data_source: IntrospectionType::ShardMapping,
5475    desc: RelationDesc::builder()
5476        .with_column("object_id", ScalarType::String.nullable(false))
5477        .with_column("shard_id", ScalarType::String.nullable(false))
5478        .finish(),
5479    column_comments: BTreeMap::new(),
5480    is_retained_metrics_object: false,
5481    access: vec![PUBLIC_SELECT],
5482});
5483
5484pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5485    name: "mz_storage_usage",
5486    schema: MZ_CATALOG_SCHEMA,
5487    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5488    desc: RelationDesc::builder()
5489        .with_column("object_id", ScalarType::String.nullable(false))
5490        .with_column("size_bytes", ScalarType::UInt64.nullable(false))
5491        .with_column(
5492            "collection_timestamp",
5493            ScalarType::TimestampTz { precision: None }.nullable(false),
5494        )
5495        .with_key(vec![0, 2])
5496        .finish(),
5497    column_comments: BTreeMap::from_iter([
5498        (
5499            "object_id",
5500            "The ID of the table, source, or materialized view.",
5501        ),
5502        (
5503            "size_bytes",
5504            "The number of storage bytes used by the object.",
5505        ),
5506        (
5507            "collection_timestamp",
5508            "The time at which storage usage of the object was assessed.",
5509        ),
5510    ]),
5511    sql: "
5512SELECT
5513    object_id,
5514    sum(size_bytes)::uint8 AS size_bytes,
5515    collection_timestamp
5516FROM
5517    mz_internal.mz_storage_shards
5518    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5519GROUP BY object_id, collection_timestamp",
5520    access: vec![PUBLIC_SELECT],
5521});
5522
5523pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5524    BuiltinView {
5525    name: "mz_recent_storage_usage",
5526    schema: MZ_CATALOG_SCHEMA,
5527    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
5528    desc: RelationDesc::builder()
5529        .with_column("object_id", ScalarType::String.nullable(false))
5530        .with_column("size_bytes", ScalarType::UInt64.nullable(true))
5531        .with_key(vec![0])
5532        .finish(),
5533    column_comments: BTreeMap::from_iter([
5534        ("object_id", "The ID of the table, source, or materialized view."),
5535        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
5536    ]),
5537    sql: "
5538WITH
5539
5540recent_storage_usage_by_shard AS (
5541    SELECT shard_id, size_bytes, collection_timestamp
5542    FROM mz_internal.mz_storage_usage_by_shard
5543    -- Restricting to the last 6 hours makes it feasible to index the view.
5544    WHERE collection_timestamp + '6 hours' >= mz_now()
5545),
5546
5547most_recent_collection_timestamp_by_shard AS (
5548    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
5549    FROM recent_storage_usage_by_shard
5550    GROUP BY shard_id
5551)
5552
5553SELECT
5554    object_id,
5555    sum(size_bytes)::uint8 AS size_bytes
5556FROM
5557    mz_internal.mz_storage_shards
5558    LEFT JOIN most_recent_collection_timestamp_by_shard
5559        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
5560    LEFT JOIN recent_storage_usage_by_shard
5561        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
5562        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
5563GROUP BY object_id",
5564    access: vec![PUBLIC_SELECT],
5565}
5566});
5567
5568pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
5569    name: "mz_recent_storage_usage_ind",
5570    schema: MZ_CATALOG_SCHEMA,
5571    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
5572    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
5573    is_retained_metrics_object: false,
5574});
5575
5576pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
5577    BuiltinView {
5578        name: "mz_relations",
5579        schema: MZ_CATALOG_SCHEMA,
5580        oid: oid::VIEW_MZ_RELATIONS_OID,
5581        desc: RelationDesc::builder()
5582            .with_column("id", ScalarType::String.nullable(false))
5583            .with_column("oid", ScalarType::Oid.nullable(false))
5584            .with_column("schema_id", ScalarType::String.nullable(false))
5585            .with_column("name", ScalarType::String.nullable(false))
5586            .with_column("type", ScalarType::String.nullable(false))
5587            .with_column("owner_id", ScalarType::String.nullable(false))
5588            .with_column("cluster_id", ScalarType::String.nullable(true))
5589            .with_column("privileges", ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(false))
5590            .finish(),
5591        column_comments: BTreeMap::from_iter([
5592            ("id", "Materialize's unique ID for the relation."),
5593            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the relation."),
5594            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
5595            ("name", "The name of the relation."),
5596            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
5597            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
5598            ("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."),
5599            ("privileges", "The privileges belonging to the relation."),
5600        ]),
5601        sql: "
5602      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
5603UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
5604UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
5605UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views
5606UNION ALL SELECT id, oid, schema_id, name, 'continual-task', owner_id, cluster_id, privileges FROM mz_internal.mz_continual_tasks",
5607        access: vec![PUBLIC_SELECT],
5608    }
5609});
5610
5611pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5612    name: "mz_objects_id_namespace_types",
5613    schema: MZ_INTERNAL_SCHEMA,
5614    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
5615    desc: RelationDesc::builder()
5616        .with_column("object_type", ScalarType::String.nullable(false))
5617        .with_key(vec![0])
5618        .finish(),
5619    column_comments: BTreeMap::new(),
5620    sql: r#"SELECT *
5621    FROM (
5622        VALUES
5623            ('table'),
5624            ('view'),
5625            ('materialized-view'),
5626            ('source'),
5627            ('sink'),
5628            ('index'),
5629            ('connection'),
5630            ('type'),
5631            ('function'),
5632            ('secret')
5633    )
5634    AS _ (object_type)"#,
5635    access: vec![PUBLIC_SELECT],
5636});
5637
5638pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5639    name: "mz_object_oid_alias",
5640    schema: MZ_INTERNAL_SCHEMA,
5641    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
5642    desc: RelationDesc::builder()
5643        .with_column("object_type", ScalarType::String.nullable(false))
5644        .with_column("oid_alias", ScalarType::String.nullable(false))
5645        .with_key(vec![0])
5646        .finish(),
5647    column_comments: BTreeMap::new(),
5648    sql: "SELECT object_type, oid_alias
5649    FROM (
5650        VALUES
5651            (
5652                'table'::pg_catalog.text,
5653                'regclass'::pg_catalog.text
5654            ),
5655            ('source', 'regclass'),
5656            ('view', 'regclass'),
5657            ('materialized-view', 'regclass'),
5658            ('index', 'regclass'),
5659            ('type', 'regtype'),
5660            ('function', 'regproc')
5661    )
5662    AS _ (object_type, oid_alias);",
5663    access: vec![PUBLIC_SELECT],
5664});
5665
5666pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
5667    BuiltinView {
5668        name: "mz_objects",
5669        schema: MZ_CATALOG_SCHEMA,
5670        oid: oid::VIEW_MZ_OBJECTS_OID,
5671        desc: RelationDesc::builder()
5672            .with_column("id", ScalarType::String.nullable(false))
5673            .with_column("oid", ScalarType::Oid.nullable(false))
5674            .with_column("schema_id", ScalarType::String.nullable(false))
5675            .with_column("name", ScalarType::String.nullable(false))
5676            .with_column("type", ScalarType::String.nullable(false))
5677            .with_column("owner_id", ScalarType::String.nullable(false))
5678            .with_column("cluster_id", ScalarType::String.nullable(true))
5679            .with_column("privileges", ScalarType::Array(Box::new(ScalarType::MzAclItem)).nullable(true))
5680            .finish(),
5681        column_comments: BTreeMap::from_iter([
5682            ("id", "Materialize's unique ID for the object."),
5683            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the object."),
5684            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
5685            ("name", "The name of the object."),
5686            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
5687            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
5688            ("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."),
5689            ("privileges", "The privileges belonging to the object."),
5690        ]),
5691        sql:
5692        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
5693UNION ALL
5694    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
5695UNION ALL
5696    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[]
5697    FROM mz_catalog.mz_indexes
5698    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
5699UNION ALL
5700    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
5701UNION ALL
5702    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
5703UNION ALL
5704    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
5705UNION ALL
5706    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
5707        access: vec![PUBLIC_SELECT],
5708    }
5709});
5710
5711pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5712    name: "mz_object_fully_qualified_names",
5713    schema: MZ_INTERNAL_SCHEMA,
5714    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
5715    desc: RelationDesc::builder()
5716        .with_column("id", ScalarType::String.nullable(false))
5717        .with_column("name", ScalarType::String.nullable(false))
5718        .with_column("object_type", ScalarType::String.nullable(false))
5719        .with_column("schema_id", ScalarType::String.nullable(false))
5720        .with_column("schema_name", ScalarType::String.nullable(false))
5721        .with_column("database_id", ScalarType::String.nullable(true))
5722        .with_column("database_name", ScalarType::String.nullable(true))
5723        .with_column("cluster_id", ScalarType::String.nullable(true))
5724        .finish(),
5725    column_comments: BTreeMap::from_iter([
5726        ("id", "Materialize's unique ID for the object."),
5727        ("name", "The name of the object."),
5728        (
5729            "object_type",
5730            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5731        ),
5732        (
5733            "schema_id",
5734            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
5735        ),
5736        (
5737            "schema_name",
5738            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
5739        ),
5740        (
5741            "database_id",
5742            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
5743        ),
5744        (
5745            "database_name",
5746            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
5747        ),
5748        (
5749            "cluster_id",
5750            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
5751        ),
5752    ]),
5753    sql: "
5754    SELECT o.id,
5755        o.name,
5756        o.type as object_type,
5757        sc.id as schema_id,
5758        sc.name as schema_name,
5759        db.id as database_id,
5760        db.name as database_name,
5761        o.cluster_id
5762    FROM mz_catalog.mz_objects o
5763    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
5764    -- LEFT JOIN accounts for objects in the ambient database.
5765    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
5766    access: vec![PUBLIC_SELECT],
5767});
5768
5769// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
5770pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5771    name: "mz_object_lifetimes",
5772    schema: MZ_INTERNAL_SCHEMA,
5773    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
5774    desc: RelationDesc::builder()
5775        .with_column("id", ScalarType::String.nullable(true))
5776        .with_column("previous_id", ScalarType::String.nullable(true))
5777        .with_column("object_type", ScalarType::String.nullable(false))
5778        .with_column("event_type", ScalarType::String.nullable(false))
5779        .with_column(
5780            "occurred_at",
5781            ScalarType::TimestampTz { precision: None }.nullable(false),
5782        )
5783        .finish(),
5784    column_comments: BTreeMap::from_iter([
5785        ("id", "Materialize's unique ID for the object."),
5786        ("previous_id", "The object's previous ID, if one exists."),
5787        (
5788            "object_type",
5789            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5790        ),
5791        (
5792            "event_type",
5793            "The lifetime event, either `create` or `drop`.",
5794        ),
5795        (
5796            "occurred_at",
5797            "Wall-clock timestamp of when the event occurred.",
5798        ),
5799    ]),
5800    sql: "
5801    SELECT
5802        CASE
5803            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
5804            ELSE a.details ->> 'id'
5805        END id,
5806        a.details ->> 'previous_id' as previous_id,
5807        a.object_type,
5808        a.event_type,
5809        a.occurred_at
5810    FROM mz_catalog.mz_audit_events a
5811    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
5812    access: vec![PUBLIC_SELECT],
5813});
5814
5815pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5816    name: "mz_object_history",
5817    schema: MZ_INTERNAL_SCHEMA,
5818    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
5819    desc: RelationDesc::builder()
5820        .with_column("id", ScalarType::String.nullable(true))
5821        .with_column("cluster_id", ScalarType::String.nullable(true))
5822        .with_column("object_type", ScalarType::String.nullable(false))
5823        .with_column(
5824            "created_at",
5825            ScalarType::TimestampTz { precision: None }.nullable(true),
5826        )
5827        .with_column(
5828            "dropped_at",
5829            ScalarType::TimestampTz { precision: None }.nullable(true),
5830        )
5831        .finish(),
5832    column_comments: BTreeMap::from_iter([
5833        ("id", "Materialize's unique ID for the object."),
5834        (
5835            "cluster_id",
5836            "The object's cluster ID. `NULL` if the object has no associated cluster.",
5837        ),
5838        (
5839            "object_type",
5840            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5841        ),
5842        (
5843            "created_at",
5844            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
5845        ),
5846        (
5847            "dropped_at",
5848            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
5849        ),
5850    ]),
5851    sql: r#"
5852    WITH
5853        creates AS
5854        (
5855            SELECT
5856                details ->> 'id' AS id,
5857                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
5858                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
5859                object_type,
5860                occurred_at
5861            FROM
5862                mz_catalog.mz_audit_events AS events
5863                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
5864            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
5865        ),
5866        drops AS
5867        (
5868            SELECT details ->> 'id' AS id, occurred_at
5869            FROM mz_catalog.mz_audit_events
5870            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
5871        ),
5872        user_object_history AS
5873        (
5874            SELECT
5875                creates.id,
5876                creates.cluster_id,
5877                creates.object_type,
5878                creates.occurred_at AS created_at,
5879                drops.occurred_at AS dropped_at
5880            FROM creates LEFT JOIN drops ON creates.id = drops.id
5881            WHERE creates.id LIKE 'u%'
5882        ),
5883        -- We need to union built in objects since they aren't in the audit log
5884        built_in_objects AS
5885        (
5886            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
5887            SELECT DISTINCT ON (objects.id)
5888                objects.id,
5889                objects.cluster_id,
5890                objects.type AS object_type,
5891                NULL::timestamptz AS created_at,
5892                NULL::timestamptz AS dropped_at
5893            FROM mz_catalog.mz_objects AS objects
5894            WHERE objects.id LIKE 's%'
5895        )
5896    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
5897    access: vec![PUBLIC_SELECT],
5898});
5899
5900pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5901    name: "mz_dataflows_per_worker",
5902    schema: MZ_INTROSPECTION_SCHEMA,
5903    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
5904    desc: RelationDesc::builder()
5905        .with_column("id", ScalarType::UInt64.nullable(true))
5906        .with_column("worker_id", ScalarType::UInt64.nullable(false))
5907        .with_column("name", ScalarType::String.nullable(false))
5908        .finish(),
5909    column_comments: BTreeMap::new(),
5910    sql: "SELECT
5911    addrs.address[1] AS id,
5912    ops.worker_id,
5913    ops.name
5914FROM
5915    mz_introspection.mz_dataflow_addresses_per_worker addrs,
5916    mz_introspection.mz_dataflow_operators_per_worker ops
5917WHERE
5918    addrs.id = ops.id AND
5919    addrs.worker_id = ops.worker_id AND
5920    mz_catalog.list_length(addrs.address) = 1",
5921    access: vec![PUBLIC_SELECT],
5922});
5923
5924pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5925    name: "mz_dataflows",
5926    schema: MZ_INTROSPECTION_SCHEMA,
5927    oid: oid::VIEW_MZ_DATAFLOWS_OID,
5928    desc: RelationDesc::builder()
5929        .with_column("id", ScalarType::UInt64.nullable(true))
5930        .with_column("name", ScalarType::String.nullable(false))
5931        .finish(),
5932    column_comments: BTreeMap::from_iter([
5933        ("id", "The ID of the dataflow."),
5934        ("name", "The internal name of the dataflow."),
5935    ]),
5936    sql: "
5937SELECT id, name
5938FROM mz_introspection.mz_dataflows_per_worker
5939WHERE worker_id = 0",
5940    access: vec![PUBLIC_SELECT],
5941});
5942
5943pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5944    name: "mz_dataflow_addresses",
5945    schema: MZ_INTROSPECTION_SCHEMA,
5946    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
5947    desc: RelationDesc::builder()
5948        .with_column("id", ScalarType::UInt64.nullable(false))
5949        .with_column(
5950            "address",
5951            ScalarType::List {
5952                element_type: Box::new(ScalarType::UInt64),
5953                custom_id: None,
5954            }
5955            .nullable(false),
5956        )
5957        .finish(),
5958    column_comments: BTreeMap::from_iter([
5959        (
5960            "id",
5961            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
5962        ),
5963        (
5964            "address",
5965            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
5966        ),
5967    ]),
5968    sql: "
5969SELECT id, address
5970FROM mz_introspection.mz_dataflow_addresses_per_worker
5971WHERE worker_id = 0",
5972    access: vec![PUBLIC_SELECT],
5973});
5974
5975pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5976    name: "mz_dataflow_channels",
5977    schema: MZ_INTROSPECTION_SCHEMA,
5978    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
5979    desc: RelationDesc::builder()
5980        .with_column("id", ScalarType::UInt64.nullable(false))
5981        .with_column("from_index", ScalarType::UInt64.nullable(false))
5982        .with_column("from_port", ScalarType::UInt64.nullable(false))
5983        .with_column("to_index", ScalarType::UInt64.nullable(false))
5984        .with_column("to_port", ScalarType::UInt64.nullable(false))
5985        .finish(),
5986    column_comments: BTreeMap::from_iter([
5987        ("id", "The ID of the channel."),
5988        (
5989            "from_index",
5990            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
5991        ),
5992        ("from_port", "The source operator's output port."),
5993        (
5994            "to_index",
5995            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
5996        ),
5997        ("to_port", "The target operator's input port."),
5998    ]),
5999    sql: "
6000SELECT id, from_index, from_port, to_index, to_port
6001FROM mz_introspection.mz_dataflow_channels_per_worker
6002WHERE worker_id = 0",
6003    access: vec![PUBLIC_SELECT],
6004});
6005
6006pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6007    name: "mz_dataflow_operators",
6008    schema: MZ_INTROSPECTION_SCHEMA,
6009    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6010    desc: RelationDesc::builder()
6011        .with_column("id", ScalarType::UInt64.nullable(false))
6012        .with_column("name", ScalarType::String.nullable(false))
6013        .finish(),
6014    column_comments: BTreeMap::from_iter([
6015        ("id", "The ID of the operator."),
6016        ("name", "The internal name of the operator."),
6017    ]),
6018    sql: "
6019SELECT id, name
6020FROM mz_introspection.mz_dataflow_operators_per_worker
6021WHERE worker_id = 0",
6022    access: vec![PUBLIC_SELECT],
6023});
6024
6025pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6026    name: "mz_dataflow_global_ids",
6027    schema: MZ_INTROSPECTION_SCHEMA,
6028    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6029    desc: RelationDesc::builder()
6030        .with_column("id", ScalarType::UInt64.nullable(false))
6031        .with_column("global_id", ScalarType::String.nullable(false))
6032        .finish(),
6033    column_comments: BTreeMap::from_iter([
6034        ("id", "The dataflow ID."),
6035        ("global_id", "A global ID associated with that dataflow."),
6036    ]),
6037    sql: "
6038SELECT id, global_id
6039FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6040WHERE worker_id = 0",
6041    access: vec![PUBLIC_SELECT],
6042});
6043
6044pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6045    BuiltinView {
6046    name: "mz_mappable_objects",
6047    schema: MZ_INTROSPECTION_SCHEMA,
6048    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6049    desc: RelationDesc::builder()
6050        .with_column("name", ScalarType::String.nullable(false))
6051        .with_column("global_id", ScalarType::String.nullable(false))
6052        .finish(),
6053    column_comments: BTreeMap::from_iter([
6054        ("name", "The name of the object."),
6055        ("global_id", "The global ID of the object."),
6056    ]),
6057    sql: "
6058SELECT SUBSTRING(name FROM 11) AS name, global_id
6059FROM mz_introspection.mz_dataflows md JOIN mz_introspection.mz_dataflow_global_ids mdgi USING (id)
6060WHERE name LIKE 'Dataflow: %' AND
6061      (global_id IN (SELECT id FROM mz_catalog.mz_indexes UNION SELECT on_id FROM mz_catalog.mz_indexes)
6062       OR EXISTS (SELECT 1 FROM mz_catalog.mz_materialized_views mmv WHERE POSITION(mmv.name IN name) <> 0))",
6063    access: vec![PUBLIC_SELECT],
6064}
6065});
6066
6067pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6068    name: "mz_lir_mapping",
6069    schema: MZ_INTROSPECTION_SCHEMA,
6070    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6071    desc: RelationDesc::builder()
6072        .with_column("global_id", ScalarType::String.nullable(false))
6073        .with_column("lir_id", ScalarType::UInt64.nullable(false))
6074        .with_column("operator", ScalarType::String.nullable(false))
6075        .with_column("parent_lir_id", ScalarType::UInt64.nullable(true))
6076        .with_column("nesting", ScalarType::UInt16.nullable(false))
6077        .with_column("operator_id_start", ScalarType::UInt64.nullable(false))
6078        .with_column("operator_id_end", ScalarType::UInt64.nullable(false))
6079        .finish(),
6080    column_comments: BTreeMap::from_iter([
6081        ("global_id", "The global ID."),
6082        ("lir_id", "The LIR node ID."),
6083        (
6084            "operator",
6085            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6086        ),
6087        (
6088            "parent_lir_id",
6089            "The parent of this LIR node. May be `NULL`.",
6090        ),
6091        ("nesting", "The nesting level of this LIR node."),
6092        (
6093            "operator_id_start",
6094            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6095        ),
6096        (
6097            "operator_id_end",
6098            "The first dataflow operator ID after this LIR operator (exclusive).",
6099        ),
6100    ]),
6101    sql: "
6102SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6103FROM mz_introspection.mz_compute_lir_mapping_per_worker
6104WHERE worker_id = 0",
6105    access: vec![PUBLIC_SELECT],
6106});
6107
6108pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6109    LazyLock::new(|| BuiltinView {
6110        name: "mz_dataflow_operator_dataflows_per_worker",
6111        schema: MZ_INTROSPECTION_SCHEMA,
6112        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6113        desc: RelationDesc::builder()
6114            .with_column("id", ScalarType::UInt64.nullable(false))
6115            .with_column("name", ScalarType::String.nullable(false))
6116            .with_column("worker_id", ScalarType::UInt64.nullable(false))
6117            .with_column("dataflow_id", ScalarType::UInt64.nullable(false))
6118            .with_column("dataflow_name", ScalarType::String.nullable(false))
6119            .finish(),
6120        column_comments: BTreeMap::new(),
6121        sql: "SELECT
6122    ops.id,
6123    ops.name,
6124    ops.worker_id,
6125    dfs.id as dataflow_id,
6126    dfs.name as dataflow_name
6127FROM
6128    mz_introspection.mz_dataflow_operators_per_worker ops,
6129    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6130    mz_introspection.mz_dataflows_per_worker dfs
6131WHERE
6132    ops.id = addrs.id AND
6133    ops.worker_id = addrs.worker_id AND
6134    dfs.id = addrs.address[1] AND
6135    dfs.worker_id = addrs.worker_id",
6136        access: vec![PUBLIC_SELECT],
6137    });
6138
6139pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6140    name: "mz_dataflow_operator_dataflows",
6141    schema: MZ_INTROSPECTION_SCHEMA,
6142    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6143    desc: RelationDesc::builder()
6144        .with_column("id", ScalarType::UInt64.nullable(false))
6145        .with_column("name", ScalarType::String.nullable(false))
6146        .with_column("dataflow_id", ScalarType::UInt64.nullable(false))
6147        .with_column("dataflow_name", ScalarType::String.nullable(false))
6148        .finish(),
6149    column_comments: BTreeMap::from_iter([
6150        (
6151            "id",
6152            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6153        ),
6154        ("name", "The internal name of the operator."),
6155        (
6156            "dataflow_id",
6157            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6158        ),
6159        (
6160            "dataflow_name",
6161            "The internal name of the dataflow hosting the operator.",
6162        ),
6163    ]),
6164    sql: "
6165SELECT id, name, dataflow_id, dataflow_name
6166FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6167WHERE worker_id = 0",
6168    access: vec![PUBLIC_SELECT],
6169});
6170
6171pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6172    BuiltinView {
6173        name: "mz_object_transitive_dependencies",
6174        schema: MZ_INTERNAL_SCHEMA,
6175        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6176        desc: RelationDesc::builder()
6177            .with_column("object_id", ScalarType::String.nullable(false))
6178            .with_column("referenced_object_id", ScalarType::String.nullable(false))
6179            .with_key(vec![0, 1])
6180            .finish(),
6181        column_comments: BTreeMap::from_iter([
6182            (
6183                "object_id",
6184                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6185            ),
6186            (
6187                "referenced_object_id",
6188                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6189            ),
6190        ]),
6191        sql: "
6192WITH MUTUALLY RECURSIVE
6193  reach(object_id text, referenced_object_id text) AS (
6194    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6195    UNION
6196    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6197  )
6198SELECT object_id, referenced_object_id FROM reach;",
6199        access: vec![PUBLIC_SELECT],
6200    }
6201});
6202
6203pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6204    name: "mz_compute_exports",
6205    schema: MZ_INTROSPECTION_SCHEMA,
6206    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6207    desc: RelationDesc::builder()
6208        .with_column("export_id", ScalarType::String.nullable(false))
6209        .with_column("dataflow_id", ScalarType::UInt64.nullable(false))
6210        .finish(),
6211    column_comments: BTreeMap::from_iter([
6212        (
6213            "export_id",
6214            "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`.",
6215        ),
6216        (
6217            "dataflow_id",
6218            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6219        ),
6220    ]),
6221    sql: "
6222SELECT export_id, dataflow_id
6223FROM mz_introspection.mz_compute_exports_per_worker
6224WHERE worker_id = 0",
6225    access: vec![PUBLIC_SELECT],
6226});
6227
6228pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6229    name: "mz_compute_frontiers",
6230    schema: MZ_INTROSPECTION_SCHEMA,
6231    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6232    desc: RelationDesc::builder()
6233        .with_column("export_id", ScalarType::String.nullable(false))
6234        .with_column("time", ScalarType::MzTimestamp.nullable(false))
6235        .with_key(vec![0])
6236        .finish(),
6237    column_comments: BTreeMap::from_iter([
6238        (
6239            "export_id",
6240            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6241        ),
6242        (
6243            "time",
6244            "The next timestamp at which the dataflow output may change.",
6245        ),
6246    ]),
6247    sql: "SELECT
6248    export_id, pg_catalog.min(time) AS time
6249FROM mz_introspection.mz_compute_frontiers_per_worker
6250GROUP BY export_id",
6251    access: vec![PUBLIC_SELECT],
6252});
6253
6254pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6255    LazyLock::new(|| BuiltinView {
6256        name: "mz_dataflow_channel_operators_per_worker",
6257        schema: MZ_INTROSPECTION_SCHEMA,
6258        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6259        desc: RelationDesc::builder()
6260            .with_column("id", ScalarType::UInt64.nullable(false))
6261            .with_column("worker_id", ScalarType::UInt64.nullable(false))
6262            .with_column("from_operator_id", ScalarType::UInt64.nullable(true))
6263            .with_column(
6264                "from_operator_address",
6265                ScalarType::List {
6266                    element_type: Box::new(ScalarType::UInt64),
6267                    custom_id: None,
6268                }
6269                .nullable(true),
6270            )
6271            .with_column("to_operator_id", ScalarType::UInt64.nullable(true))
6272            .with_column(
6273                "to_operator_address",
6274                ScalarType::List {
6275                    element_type: Box::new(ScalarType::UInt64),
6276                    custom_id: None,
6277                }
6278                .nullable(true),
6279            )
6280            .finish(),
6281        column_comments: BTreeMap::new(),
6282        sql: "
6283WITH
6284channel_addresses(id, worker_id, address, from_index, to_index) AS (
6285     SELECT id, worker_id, address, from_index, to_index
6286     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6287     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6288     USING (id, worker_id)
6289),
6290channel_operator_addresses(id, worker_id, from_address, to_address) AS (
6291     SELECT id, worker_id,
6292            address || from_index AS from_address,
6293            address || to_index AS to_address
6294     FROM channel_addresses
6295),
6296operator_addresses(id, worker_id, address) AS (
6297     SELECT id, worker_id, address
6298     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6299     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6300     USING (id, worker_id)
6301)
6302SELECT coa.id,
6303       coa.worker_id,
6304       from_ops.id AS from_operator_id,
6305       coa.from_address AS from_operator_address,
6306       to_ops.id AS to_operator_id,
6307       coa.to_address AS to_operator_address
6308FROM channel_operator_addresses coa
6309     LEFT OUTER JOIN operator_addresses from_ops
6310          ON coa.from_address = from_ops.address AND
6311             coa.worker_id = from_ops.worker_id
6312     LEFT OUTER JOIN operator_addresses to_ops
6313          ON coa.to_address = to_ops.address AND
6314             coa.worker_id = to_ops.worker_id
6315",
6316        access: vec![PUBLIC_SELECT],
6317    });
6318
6319pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6320    name: "mz_dataflow_channel_operators",
6321    schema: MZ_INTROSPECTION_SCHEMA,
6322    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6323    desc: RelationDesc::builder()
6324        .with_column("id", ScalarType::UInt64.nullable(false))
6325        .with_column("from_operator_id", ScalarType::UInt64.nullable(true))
6326        .with_column(
6327            "from_operator_address",
6328            ScalarType::List {
6329                element_type: Box::new(ScalarType::UInt64),
6330                custom_id: None,
6331            }
6332            .nullable(true),
6333        )
6334        .with_column("to_operator_id", ScalarType::UInt64.nullable(true))
6335        .with_column(
6336            "to_operator_address",
6337            ScalarType::List {
6338                element_type: Box::new(ScalarType::UInt64),
6339                custom_id: None,
6340            }
6341            .nullable(true),
6342        )
6343        .finish(),
6344    column_comments: BTreeMap::from_iter([
6345        (
6346            "id",
6347            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6348        ),
6349        (
6350            "from_operator_id",
6351            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6352        ),
6353        (
6354            "from_operator_address",
6355            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6356        ),
6357        (
6358            "to_operator_id",
6359            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6360        ),
6361        (
6362            "to_operator_address",
6363            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6364        ),
6365    ]),
6366    sql: "
6367SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address
6368FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6369WHERE worker_id = 0",
6370    access: vec![PUBLIC_SELECT],
6371});
6372
6373pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6374    name: "mz_compute_import_frontiers",
6375    schema: MZ_INTROSPECTION_SCHEMA,
6376    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6377    desc: RelationDesc::builder()
6378        .with_column("export_id", ScalarType::String.nullable(false))
6379        .with_column("import_id", ScalarType::String.nullable(false))
6380        .with_column("time", ScalarType::MzTimestamp.nullable(false))
6381        .with_key(vec![0, 1])
6382        .finish(),
6383    column_comments: BTreeMap::from_iter([
6384        (
6385            "export_id",
6386            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6387        ),
6388        (
6389            "import_id",
6390            "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`.",
6391        ),
6392        (
6393            "time",
6394            "The next timestamp at which the dataflow input may change.",
6395        ),
6396    ]),
6397    sql: "SELECT
6398    export_id, import_id, pg_catalog.min(time) AS time
6399FROM mz_introspection.mz_compute_import_frontiers_per_worker
6400GROUP BY export_id, import_id",
6401    access: vec![PUBLIC_SELECT],
6402});
6403
6404pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6405    LazyLock::new(|| BuiltinView {
6406        name: "mz_records_per_dataflow_operator_per_worker",
6407        schema: MZ_INTROSPECTION_SCHEMA,
6408        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6409        desc: RelationDesc::builder()
6410            .with_column("id", ScalarType::UInt64.nullable(false))
6411            .with_column("name", ScalarType::String.nullable(false))
6412            .with_column("worker_id", ScalarType::UInt64.nullable(false))
6413            .with_column("dataflow_id", ScalarType::UInt64.nullable(false))
6414            .with_column("records", ScalarType::Int64.nullable(false))
6415            .with_column("batches", ScalarType::Int64.nullable(false))
6416            .with_column("size", ScalarType::Int64.nullable(false))
6417            .with_column("capacity", ScalarType::Int64.nullable(false))
6418            .with_column("allocations", ScalarType::Int64.nullable(false))
6419            .finish(),
6420        column_comments: BTreeMap::new(),
6421        sql: "
6422SELECT
6423    dod.id,
6424    dod.name,
6425    dod.worker_id,
6426    dod.dataflow_id,
6427    COALESCE(ar_size.records, 0) AS records,
6428    COALESCE(ar_size.batches, 0) AS batches,
6429    COALESCE(ar_size.size, 0) AS size,
6430    COALESCE(ar_size.capacity, 0) AS capacity,
6431    COALESCE(ar_size.allocations, 0) AS allocations
6432FROM
6433    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6434    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6435        dod.id = ar_size.operator_id AND
6436        dod.worker_id = ar_size.worker_id",
6437        access: vec![PUBLIC_SELECT],
6438    });
6439
6440pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6441    LazyLock::new(|| BuiltinView {
6442        name: "mz_records_per_dataflow_operator",
6443        schema: MZ_INTROSPECTION_SCHEMA,
6444        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6445        desc: RelationDesc::builder()
6446            .with_column("id", ScalarType::UInt64.nullable(false))
6447            .with_column("name", ScalarType::String.nullable(false))
6448            .with_column("dataflow_id", ScalarType::UInt64.nullable(false))
6449            .with_column(
6450                "records",
6451                ScalarType::Numeric {
6452                    max_scale: Some(NumericMaxScale::ZERO),
6453                }
6454                .nullable(false),
6455            )
6456            .with_column(
6457                "batches",
6458                ScalarType::Numeric {
6459                    max_scale: Some(NumericMaxScale::ZERO),
6460                }
6461                .nullable(false),
6462            )
6463            .with_column(
6464                "size",
6465                ScalarType::Numeric {
6466                    max_scale: Some(NumericMaxScale::ZERO),
6467                }
6468                .nullable(false),
6469            )
6470            .with_column(
6471                "capacity",
6472                ScalarType::Numeric {
6473                    max_scale: Some(NumericMaxScale::ZERO),
6474                }
6475                .nullable(false),
6476            )
6477            .with_column(
6478                "allocations",
6479                ScalarType::Numeric {
6480                    max_scale: Some(NumericMaxScale::ZERO),
6481                }
6482                .nullable(false),
6483            )
6484            .with_key(vec![0, 1, 2])
6485            .finish(),
6486        column_comments: BTreeMap::from_iter([
6487            (
6488                "id",
6489                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6490            ),
6491            ("name", "The internal name of the operator."),
6492            (
6493                "dataflow_id",
6494                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6495            ),
6496            ("records", "The number of records in the operator."),
6497            ("batches", "The number of batches in the dataflow."),
6498            ("size", "The utilized size in bytes of the arrangement."),
6499            (
6500                "capacity",
6501                "The capacity in bytes of the arrangement. Can be larger than the size.",
6502            ),
6503            (
6504                "allocations",
6505                "The number of separate memory allocations backing the arrangement.",
6506            ),
6507        ]),
6508        sql: "
6509SELECT
6510    id,
6511    name,
6512    dataflow_id,
6513    pg_catalog.sum(records) AS records,
6514    pg_catalog.sum(batches) AS batches,
6515    pg_catalog.sum(size) AS size,
6516    pg_catalog.sum(capacity) AS capacity,
6517    pg_catalog.sum(allocations) AS allocations
6518FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
6519GROUP BY id, name, dataflow_id",
6520        access: vec![PUBLIC_SELECT],
6521    });
6522
6523pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
6524    LazyLock::new(|| BuiltinView {
6525        name: "mz_records_per_dataflow_per_worker",
6526        schema: MZ_INTROSPECTION_SCHEMA,
6527        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
6528        desc: RelationDesc::builder()
6529            .with_column("id", ScalarType::UInt64.nullable(false))
6530            .with_column("name", ScalarType::String.nullable(false))
6531            .with_column("worker_id", ScalarType::UInt64.nullable(false))
6532            .with_column(
6533                "records",
6534                ScalarType::Numeric {
6535                    max_scale: Some(NumericMaxScale::ZERO),
6536                }
6537                .nullable(false),
6538            )
6539            .with_column(
6540                "batches",
6541                ScalarType::Numeric {
6542                    max_scale: Some(NumericMaxScale::ZERO),
6543                }
6544                .nullable(false),
6545            )
6546            .with_column(
6547                "size",
6548                ScalarType::Numeric {
6549                    max_scale: Some(NumericMaxScale::ZERO),
6550                }
6551                .nullable(false),
6552            )
6553            .with_column(
6554                "capacity",
6555                ScalarType::Numeric {
6556                    max_scale: Some(NumericMaxScale::ZERO),
6557                }
6558                .nullable(false),
6559            )
6560            .with_column(
6561                "allocations",
6562                ScalarType::Numeric {
6563                    max_scale: Some(NumericMaxScale::ZERO),
6564                }
6565                .nullable(false),
6566            )
6567            .with_key(vec![0, 1, 2])
6568            .finish(),
6569        column_comments: BTreeMap::new(),
6570        sql: "
6571SELECT
6572    rdo.dataflow_id as id,
6573    dfs.name,
6574    rdo.worker_id,
6575    pg_catalog.SUM(rdo.records) as records,
6576    pg_catalog.SUM(rdo.batches) as batches,
6577    pg_catalog.SUM(rdo.size) as size,
6578    pg_catalog.SUM(rdo.capacity) as capacity,
6579    pg_catalog.SUM(rdo.allocations) as allocations
6580FROM
6581    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
6582    mz_introspection.mz_dataflows_per_worker dfs
6583WHERE
6584    rdo.dataflow_id = dfs.id AND
6585    rdo.worker_id = dfs.worker_id
6586GROUP BY
6587    rdo.dataflow_id,
6588    dfs.name,
6589    rdo.worker_id",
6590        access: vec![PUBLIC_SELECT],
6591    });
6592
6593pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6594    name: "mz_records_per_dataflow",
6595    schema: MZ_INTROSPECTION_SCHEMA,
6596    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
6597    desc: RelationDesc::builder()
6598        .with_column("id", ScalarType::UInt64.nullable(false))
6599        .with_column("name", ScalarType::String.nullable(false))
6600        .with_column(
6601            "records",
6602            ScalarType::Numeric {
6603                max_scale: Some(NumericMaxScale::ZERO),
6604            }
6605            .nullable(false),
6606        )
6607        .with_column(
6608            "batches",
6609            ScalarType::Numeric {
6610                max_scale: Some(NumericMaxScale::ZERO),
6611            }
6612            .nullable(false),
6613        )
6614        .with_column(
6615            "size",
6616            ScalarType::Numeric {
6617                max_scale: Some(NumericMaxScale::ZERO),
6618            }
6619            .nullable(false),
6620        )
6621        .with_column(
6622            "capacity",
6623            ScalarType::Numeric {
6624                max_scale: Some(NumericMaxScale::ZERO),
6625            }
6626            .nullable(false),
6627        )
6628        .with_column(
6629            "allocations",
6630            ScalarType::Numeric {
6631                max_scale: Some(NumericMaxScale::ZERO),
6632            }
6633            .nullable(false),
6634        )
6635        .with_key(vec![0, 1])
6636        .finish(),
6637    column_comments: BTreeMap::from_iter([
6638        (
6639            "id",
6640            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6641        ),
6642        ("name", "The internal name of the dataflow."),
6643        ("records", "The number of records in the dataflow."),
6644        ("batches", "The number of batches in the dataflow."),
6645        ("size", "The utilized size in bytes of the arrangements."),
6646        (
6647            "capacity",
6648            "The capacity in bytes of the arrangements. Can be larger than the size.",
6649        ),
6650        (
6651            "allocations",
6652            "The number of separate memory allocations backing the arrangements.",
6653        ),
6654    ]),
6655    sql: "
6656SELECT
6657    id,
6658    name,
6659    pg_catalog.SUM(records) as records,
6660    pg_catalog.SUM(batches) as batches,
6661    pg_catalog.SUM(size) as size,
6662    pg_catalog.SUM(capacity) as capacity,
6663    pg_catalog.SUM(allocations) as allocations
6664FROM
6665    mz_introspection.mz_records_per_dataflow_per_worker
6666GROUP BY
6667    id,
6668    name",
6669    access: vec![PUBLIC_SELECT],
6670});
6671
6672/// Peeled version of `PG_NAMESPACE`:
6673/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6674///   in order to make this view indexable.
6675/// - This has the database name as an extra column, so that downstream views can check it against
6676///  `current_database()`.
6677pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6678    name: "pg_namespace_all_databases",
6679    schema: MZ_INTERNAL_SCHEMA,
6680    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
6681    desc: RelationDesc::builder()
6682        .with_column("oid", ScalarType::Oid.nullable(false))
6683        .with_column("nspname", ScalarType::String.nullable(false))
6684        .with_column("nspowner", ScalarType::Oid.nullable(false))
6685        .with_column(
6686            "nspacl",
6687            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
6688        )
6689        .with_column("database_name", ScalarType::String.nullable(true))
6690        .finish(),
6691    column_comments: BTreeMap::new(),
6692    sql: "
6693SELECT
6694    s.oid AS oid,
6695    s.name AS nspname,
6696    role_owner.oid AS nspowner,
6697    NULL::pg_catalog.text[] AS nspacl,
6698    d.name as database_name
6699FROM mz_catalog.mz_schemas s
6700LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
6701JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
6702    access: vec![PUBLIC_SELECT],
6703});
6704
6705pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6706    name: "pg_namespace_all_databases_ind",
6707    schema: MZ_INTERNAL_SCHEMA,
6708    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
6709    sql: "IN CLUSTER mz_catalog_server
6710ON mz_internal.pg_namespace_all_databases (nspname)",
6711    is_retained_metrics_object: false,
6712};
6713
6714pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6715    name: "pg_namespace",
6716    schema: PG_CATALOG_SCHEMA,
6717    oid: oid::VIEW_PG_NAMESPACE_OID,
6718    desc: RelationDesc::builder()
6719        .with_column("oid", ScalarType::Oid.nullable(false))
6720        .with_column("nspname", ScalarType::String.nullable(false))
6721        .with_column("nspowner", ScalarType::Oid.nullable(false))
6722        .with_column(
6723            "nspacl",
6724            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
6725        )
6726        .finish(),
6727    column_comments: BTreeMap::new(),
6728    sql: "
6729SELECT
6730    oid, nspname, nspowner, nspacl
6731FROM mz_internal.pg_namespace_all_databases
6732WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
6733    access: vec![PUBLIC_SELECT],
6734});
6735
6736/// Peeled version of `PG_CLASS`:
6737/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6738///   in order to make this view indexable.
6739/// - This has the database name as an extra column, so that downstream views can check it against
6740///  `current_database()`.
6741pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
6742    BuiltinView {
6743        name: "pg_class_all_databases",
6744        schema: MZ_INTERNAL_SCHEMA,
6745        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
6746        desc: RelationDesc::builder()
6747            .with_column("oid", ScalarType::Oid.nullable(false))
6748            .with_column("relname", ScalarType::String.nullable(false))
6749            .with_column("relnamespace", ScalarType::Oid.nullable(false))
6750            .with_column("reloftype", ScalarType::Oid.nullable(false))
6751            .with_column("relowner", ScalarType::Oid.nullable(false))
6752            .with_column("relam", ScalarType::Oid.nullable(false))
6753            .with_column("reltablespace", ScalarType::Oid.nullable(false))
6754            .with_column("reltuples", ScalarType::Float32.nullable(false))
6755            .with_column("reltoastrelid", ScalarType::Oid.nullable(false))
6756            .with_column("relhasindex", ScalarType::Bool.nullable(false))
6757            .with_column("relpersistence", ScalarType::PgLegacyChar.nullable(false))
6758            .with_column("relkind", ScalarType::String.nullable(true))
6759            .with_column("relchecks", ScalarType::Int16.nullable(false))
6760            .with_column("relhasrules", ScalarType::Bool.nullable(false))
6761            .with_column("relhastriggers", ScalarType::Bool.nullable(false))
6762            .with_column("relhassubclass", ScalarType::Bool.nullable(false))
6763            .with_column("relrowsecurity", ScalarType::Bool.nullable(false))
6764            .with_column("relforcerowsecurity", ScalarType::Bool.nullable(false))
6765            .with_column("relreplident", ScalarType::PgLegacyChar.nullable(false))
6766            .with_column("relispartition", ScalarType::Bool.nullable(false))
6767            .with_column("relhasoids", ScalarType::Bool.nullable(false))
6768            .with_column("reloptions", ScalarType::Array(Box::new(ScalarType::String)).nullable(true))
6769            .with_column("database_name", ScalarType::String.nullable(true))
6770            .finish(),
6771        column_comments: BTreeMap::new(),
6772        sql: "
6773SELECT
6774    class_objects.oid,
6775    class_objects.name AS relname,
6776    mz_schemas.oid AS relnamespace,
6777    -- MZ doesn't support typed tables so reloftype is filled with 0
6778    0::pg_catalog.oid AS reloftype,
6779    role_owner.oid AS relowner,
6780    0::pg_catalog.oid AS relam,
6781    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
6782    0::pg_catalog.oid AS reltablespace,
6783    -- MZ doesn't support (estimated) row counts currently.
6784    -- Postgres defines a value of -1 as unknown.
6785    -1::float4 as reltuples,
6786    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
6787    0::pg_catalog.oid AS reltoastrelid,
6788    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
6789    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
6790    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
6791    -- TODO(jkosh44): update this column when issue is resolved.
6792    'p'::pg_catalog.\"char\" AS relpersistence,
6793    CASE
6794        WHEN class_objects.type = 'table' THEN 'r'
6795        WHEN class_objects.type = 'source' THEN 'r'
6796        WHEN class_objects.type = 'index' THEN 'i'
6797        WHEN class_objects.type = 'view' THEN 'v'
6798        WHEN class_objects.type = 'materialized-view' THEN 'm'
6799    END relkind,
6800    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
6801    0::pg_catalog.int2 AS relchecks,
6802    -- MZ doesn't support creating rules so relhasrules is filled with false
6803    false AS relhasrules,
6804    -- MZ doesn't support creating triggers so relhastriggers is filled with false
6805    false AS relhastriggers,
6806    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
6807    false AS relhassubclass,
6808    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
6809    false AS relrowsecurity,
6810    false AS relforcerowsecurity,
6811    -- MZ doesn't support replication so relreplident is filled with 'd' for default
6812    'd'::pg_catalog.\"char\" AS relreplident,
6813    -- MZ doesn't support table partitioning so relispartition is filled with false
6814    false AS relispartition,
6815    -- PG removed relhasoids in v12 so it's filled with false
6816    false AS relhasoids,
6817    -- MZ doesn't support options for relations
6818    NULL::pg_catalog.text[] as reloptions,
6819    d.name as database_name
6820FROM (
6821    -- pg_class catalogs relations and indexes
6822    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
6823    UNION ALL
6824        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
6825        FROM mz_catalog.mz_indexes
6826        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6827) AS class_objects
6828JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6829LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6830JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
6831        access: vec![PUBLIC_SELECT],
6832    }
6833});
6834
6835pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6836    name: "pg_class_all_databases_ind",
6837    schema: MZ_INTERNAL_SCHEMA,
6838    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
6839    sql: "IN CLUSTER mz_catalog_server
6840ON mz_internal.pg_class_all_databases (relname)",
6841    is_retained_metrics_object: false,
6842};
6843
6844pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6845    name: "pg_class",
6846    schema: PG_CATALOG_SCHEMA,
6847    oid: oid::VIEW_PG_CLASS_OID,
6848    desc: RelationDesc::builder()
6849        .with_column("oid", ScalarType::Oid.nullable(false))
6850        .with_column("relname", ScalarType::String.nullable(false))
6851        .with_column("relnamespace", ScalarType::Oid.nullable(false))
6852        .with_column("reloftype", ScalarType::Oid.nullable(false))
6853        .with_column("relowner", ScalarType::Oid.nullable(false))
6854        .with_column("relam", ScalarType::Oid.nullable(false))
6855        .with_column("reltablespace", ScalarType::Oid.nullable(false))
6856        .with_column("reltuples", ScalarType::Float32.nullable(false))
6857        .with_column("reltoastrelid", ScalarType::Oid.nullable(false))
6858        .with_column("relhasindex", ScalarType::Bool.nullable(false))
6859        .with_column("relpersistence", ScalarType::PgLegacyChar.nullable(false))
6860        .with_column("relkind", ScalarType::String.nullable(true))
6861        .with_column("relchecks", ScalarType::Int16.nullable(false))
6862        .with_column("relhasrules", ScalarType::Bool.nullable(false))
6863        .with_column("relhastriggers", ScalarType::Bool.nullable(false))
6864        .with_column("relhassubclass", ScalarType::Bool.nullable(false))
6865        .with_column("relrowsecurity", ScalarType::Bool.nullable(false))
6866        .with_column("relforcerowsecurity", ScalarType::Bool.nullable(false))
6867        .with_column("relreplident", ScalarType::PgLegacyChar.nullable(false))
6868        .with_column("relispartition", ScalarType::Bool.nullable(false))
6869        .with_column("relhasoids", ScalarType::Bool.nullable(false))
6870        .with_column(
6871            "reloptions",
6872            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
6873        )
6874        .finish(),
6875    column_comments: BTreeMap::new(),
6876    sql: "
6877SELECT
6878    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
6879    relhasindex, relpersistence, relkind, relchecks, relhasrules, relhastriggers, relhassubclass,
6880    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
6881FROM mz_internal.pg_class_all_databases
6882WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
6883",
6884    access: vec![PUBLIC_SELECT],
6885});
6886
6887pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6888    name: "pg_depend",
6889    schema: PG_CATALOG_SCHEMA,
6890    oid: oid::VIEW_PG_DEPEND_OID,
6891    desc: RelationDesc::builder()
6892        .with_column("classid", ScalarType::Oid.nullable(true))
6893        .with_column("objid", ScalarType::Oid.nullable(false))
6894        .with_column("objsubid", ScalarType::Int32.nullable(false))
6895        .with_column("refclassid", ScalarType::Oid.nullable(true))
6896        .with_column("refobjid", ScalarType::Oid.nullable(false))
6897        .with_column("refobjsubid", ScalarType::Int32.nullable(false))
6898        .with_column("deptype", ScalarType::PgLegacyChar.nullable(false))
6899        .finish(),
6900    column_comments: BTreeMap::new(),
6901    sql: "
6902WITH class_objects AS (
6903    SELECT
6904        CASE
6905            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6906            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6907            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
6908            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
6909        END classid,
6910        id,
6911        oid,
6912        schema_id
6913    FROM mz_catalog.mz_relations
6914    UNION ALL
6915    SELECT
6916        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
6917        i.id,
6918        i.oid,
6919        r.schema_id
6920    FROM mz_catalog.mz_indexes i
6921    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
6922),
6923
6924current_objects AS (
6925    SELECT class_objects.*
6926    FROM class_objects
6927    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6928    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6929    -- This filter is tricky, as it filters out not just objects outside the
6930    -- database, but *dependencies* on objects outside this database. It's not
6931    -- clear that this is the right choice, but because PostgreSQL doesn't
6932    -- support cross-database references, it's not clear that the other choice
6933    -- is better.
6934    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
6935)
6936
6937SELECT
6938    objects.classid::pg_catalog.oid,
6939    objects.oid::pg_catalog.oid AS objid,
6940    0::pg_catalog.int4 AS objsubid,
6941    dependents.classid::pg_catalog.oid AS refclassid,
6942    dependents.oid::pg_catalog.oid AS refobjid,
6943    0::pg_catalog.int4 AS refobjsubid,
6944    'n'::pg_catalog.char AS deptype
6945FROM mz_internal.mz_object_dependencies
6946JOIN current_objects objects ON object_id = objects.id
6947JOIN current_objects dependents ON referenced_object_id = dependents.id",
6948    access: vec![PUBLIC_SELECT],
6949});
6950
6951pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6952    name: "pg_database",
6953    schema: PG_CATALOG_SCHEMA,
6954    oid: oid::VIEW_PG_DATABASE_OID,
6955    desc: RelationDesc::builder()
6956        .with_column("oid", ScalarType::Oid.nullable(false))
6957        .with_column("datname", ScalarType::String.nullable(false))
6958        .with_column("datdba", ScalarType::Oid.nullable(false))
6959        .with_column("encoding", ScalarType::Int32.nullable(false))
6960        .with_column("datistemplate", ScalarType::Bool.nullable(false))
6961        .with_column("datallowconn", ScalarType::Bool.nullable(false))
6962        .with_column("datcollate", ScalarType::String.nullable(false))
6963        .with_column("datctype", ScalarType::String.nullable(false))
6964        .with_column(
6965            "datacl",
6966            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
6967        )
6968        .with_key(vec![0])
6969        .finish(),
6970    column_comments: BTreeMap::new(),
6971    sql: "SELECT
6972    d.oid as oid,
6973    d.name as datname,
6974    role_owner.oid as datdba,
6975    6 as encoding,
6976    -- Materialize doesn't support database cloning.
6977    FALSE AS datistemplate,
6978    TRUE AS datallowconn,
6979    'C' as datcollate,
6980    'C' as datctype,
6981    NULL::pg_catalog.text[] as datacl
6982FROM mz_catalog.mz_databases d
6983JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
6984    access: vec![PUBLIC_SELECT],
6985});
6986
6987pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
6988    BuiltinView {
6989        name: "pg_index",
6990        schema: PG_CATALOG_SCHEMA,
6991        oid: oid::VIEW_PG_INDEX_OID,
6992        desc: RelationDesc::builder()
6993            .with_column("indexrelid", ScalarType::Oid.nullable(false))
6994            .with_column("indrelid", ScalarType::Oid.nullable(false))
6995            .with_column("indisunique", ScalarType::Bool.nullable(false))
6996            .with_column("indisprimary", ScalarType::Bool.nullable(false))
6997            .with_column("indimmediate", ScalarType::Bool.nullable(false))
6998            .with_column("indisclustered", ScalarType::Bool.nullable(false))
6999            .with_column("indisvalid", ScalarType::Bool.nullable(false))
7000            .with_column("indisreplident", ScalarType::Bool.nullable(false))
7001            .with_column("indkey", ScalarType::Int2Vector.nullable(false))
7002            .with_column("indoption", ScalarType::Int2Vector.nullable(false))
7003            .with_column("indexprs", ScalarType::String.nullable(true))
7004            .with_column("indpred", ScalarType::String.nullable(true))
7005            .with_key(vec![0, 1])
7006            .finish(),
7007        column_comments: BTreeMap::new(),
7008        sql: "SELECT
7009    mz_indexes.oid AS indexrelid,
7010    mz_relations.oid AS indrelid,
7011    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7012    false::pg_catalog.bool AS indisunique,
7013    false::pg_catalog.bool AS indisprimary,
7014    -- MZ doesn't support unique indexes so indimmediate is filled with false
7015    false::pg_catalog.bool AS indimmediate,
7016    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7017    false::pg_catalog.bool AS indisclustered,
7018    -- MZ never creates invalid indexes so indisvalid is filled with true
7019    true::pg_catalog.bool AS indisvalid,
7020    -- MZ doesn't support replication so indisreplident is filled with false
7021    false::pg_catalog.bool AS indisreplident,
7022    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7023    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,
7024    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7025    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7026    -- Index expressions are returned in MZ format
7027    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7028    WHEN NULL THEN NULL
7029    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7030    END AS indexprs,
7031    -- MZ doesn't support indexes with predicates
7032    NULL::pg_catalog.text AS indpred
7033FROM mz_catalog.mz_indexes
7034JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7035JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7036JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7037LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7038WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7039GROUP BY mz_indexes.oid, mz_relations.oid",
7040        access: vec![PUBLIC_SELECT],
7041    }
7042});
7043
7044pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7045    name: "pg_indexes",
7046    schema: PG_CATALOG_SCHEMA,
7047    oid: oid::VIEW_PG_INDEXES_OID,
7048    desc: RelationDesc::builder()
7049        .with_column("table_catalog", ScalarType::String.nullable(false))
7050        .with_column("schemaname", ScalarType::String.nullable(false))
7051        .with_column("tablename", ScalarType::String.nullable(false))
7052        .with_column("indexname", ScalarType::String.nullable(false))
7053        .with_column("tablespace", ScalarType::String.nullable(true))
7054        .with_column("indexdef", ScalarType::String.nullable(true))
7055        .finish(),
7056    column_comments: BTreeMap::new(),
7057    sql: "SELECT
7058    current_database() as table_catalog,
7059    s.name AS schemaname,
7060    r.name AS tablename,
7061    i.name AS indexname,
7062    NULL::text AS tablespace,
7063    -- TODO(jkosh44) Fill in with actual index definition.
7064    NULL::text AS indexdef
7065FROM mz_catalog.mz_indexes i
7066JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7067JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7068LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7069WHERE s.database_id IS NULL OR d.name = current_database()",
7070    access: vec![PUBLIC_SELECT],
7071});
7072
7073/// Peeled version of `PG_DESCRIPTION`:
7074/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7075///   in order to make this view indexable.
7076/// - This has 2 extra columns for the database names, so that downstream views can check them
7077///   against `current_database()`.
7078pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7079    BuiltinView {
7080        name: "pg_description_all_databases",
7081        schema: MZ_INTERNAL_SCHEMA,
7082        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7083        desc: RelationDesc::builder()
7084            .with_column("objoid", ScalarType::Oid.nullable(false))
7085            .with_column("classoid", ScalarType::Oid.nullable(true))
7086            .with_column("objsubid", ScalarType::Int32.nullable(false))
7087            .with_column("description", ScalarType::String.nullable(false))
7088            .with_column("oid_database_name", ScalarType::String.nullable(true))
7089            .with_column("class_database_name", ScalarType::String.nullable(true))
7090            .finish(),
7091        column_comments: BTreeMap::new(),
7092        sql: "
7093(
7094    -- Gather all of the class oid's for objects that can have comments.
7095    WITH pg_classoids AS (
7096        SELECT oid, database_name as oid_database_name,
7097          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7098          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7099        FROM mz_internal.pg_class_all_databases
7100        UNION ALL
7101        SELECT oid, database_name as oid_database_name,
7102          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7103          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7104        FROM mz_internal.pg_type_all_databases
7105        UNION ALL
7106        SELECT oid, database_name as oid_database_name,
7107          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7108          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7109        FROM mz_internal.pg_namespace_all_databases
7110    ),
7111
7112    -- Gather all of the MZ ids for objects that can have comments.
7113    mz_objects AS (
7114        SELECT id, oid, type FROM mz_catalog.mz_objects
7115        UNION ALL
7116        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7117    )
7118    SELECT
7119        pg_classoids.oid AS objoid,
7120        pg_classoids.classoid as classoid,
7121        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7122        cmt.comment AS description,
7123        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7124        oid_database_name,
7125        class_database_name
7126    FROM
7127        pg_classoids
7128    JOIN
7129        mz_objects ON pg_classoids.oid = mz_objects.oid
7130    JOIN
7131        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7132)",
7133        access: vec![PUBLIC_SELECT],
7134    }
7135});
7136
7137pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7138    name: "pg_description_all_databases_ind",
7139    schema: MZ_INTERNAL_SCHEMA,
7140    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7141    sql: "IN CLUSTER mz_catalog_server
7142ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7143    is_retained_metrics_object: false,
7144};
7145
7146/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7147/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7148/// which is required for this view.
7149pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7150    name: "pg_description",
7151    schema: PG_CATALOG_SCHEMA,
7152    oid: oid::VIEW_PG_DESCRIPTION_OID,
7153    desc: RelationDesc::builder()
7154        .with_column("objoid", ScalarType::Oid.nullable(false))
7155        .with_column("classoid", ScalarType::Oid.nullable(true))
7156        .with_column("objsubid", ScalarType::Int32.nullable(false))
7157        .with_column("description", ScalarType::String.nullable(false))
7158        .finish(),
7159    column_comments: BTreeMap::new(),
7160    sql: "
7161SELECT
7162    objoid,
7163    classoid,
7164    objsubid,
7165    description
7166FROM
7167    mz_internal.pg_description_all_databases
7168WHERE
7169    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7170    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7171    access: vec![PUBLIC_SELECT],
7172});
7173
7174/// Peeled version of `PG_TYPE`:
7175/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7176///   in order to make this view indexable.
7177/// - This has the database name as an extra column, so that downstream views can check it against
7178///  `current_database()`.
7179pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7180    BuiltinView {
7181        name: "pg_type_all_databases",
7182        schema: MZ_INTERNAL_SCHEMA,
7183        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7184        desc: RelationDesc::builder()
7185            .with_column("oid", ScalarType::Oid.nullable(false))
7186            .with_column("typname", ScalarType::String.nullable(false))
7187            .with_column("typnamespace", ScalarType::Oid.nullable(false))
7188            .with_column("typowner", ScalarType::Oid.nullable(false))
7189            .with_column("typlen", ScalarType::Int16.nullable(true))
7190            .with_column("typtype", ScalarType::PgLegacyChar.nullable(false))
7191            .with_column("typcategory", ScalarType::PgLegacyChar.nullable(true))
7192            .with_column("typdelim", ScalarType::PgLegacyChar.nullable(false))
7193            .with_column("typrelid", ScalarType::Oid.nullable(false))
7194            .with_column("typelem", ScalarType::Oid.nullable(false))
7195            .with_column("typarray", ScalarType::Oid.nullable(false))
7196            .with_column("typinput", ScalarType::RegProc.nullable(true))
7197            .with_column("typreceive", ScalarType::Oid.nullable(false))
7198            .with_column("typnotnull", ScalarType::Bool.nullable(false))
7199            .with_column("typbasetype", ScalarType::Oid.nullable(false))
7200            .with_column("typtypmod", ScalarType::Int32.nullable(false))
7201            .with_column("typcollation", ScalarType::Oid.nullable(false))
7202            .with_column("typdefault", ScalarType::String.nullable(true))
7203            .with_column("database_name", ScalarType::String.nullable(true))
7204            .finish(),
7205        column_comments: BTreeMap::new(),
7206        sql: "
7207SELECT
7208    mz_types.oid,
7209    mz_types.name AS typname,
7210    mz_schemas.oid AS typnamespace,
7211    role_owner.oid AS typowner,
7212    NULL::pg_catalog.int2 AS typlen,
7213    -- 'a' is used internally to denote an array type, but in postgres they show up
7214    -- as 'b'.
7215    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7216    (CASE category
7217        WHEN 'array' THEN 'A'
7218        WHEN 'bit-string' THEN 'V'
7219        WHEN 'boolean' THEN 'B'
7220        WHEN 'composite' THEN 'C'
7221        WHEN 'date-time' THEN 'D'
7222        WHEN 'enum' THEN 'E'
7223        WHEN 'geometric' THEN 'G'
7224        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7225        WHEN 'network-address' THEN 'I'
7226        WHEN 'numeric' THEN 'N'
7227        WHEN 'pseudo' THEN 'P'
7228        WHEN 'string' THEN 'S'
7229        WHEN 'timespan' THEN 'T'
7230        WHEN 'user-defined' THEN 'U'
7231        WHEN 'unknown' THEN 'X'
7232    END)::pg_catalog.char AS typcategory,
7233    -- In pg only the 'box' type is not ','.
7234    ','::pg_catalog.char AS typdelim,
7235    0::pg_catalog.oid AS typrelid,
7236    coalesce(
7237        (
7238            SELECT t.oid
7239            FROM mz_catalog.mz_array_types a
7240            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7241            WHERE a.id = mz_types.id
7242        ),
7243        0
7244    ) AS typelem,
7245    coalesce(
7246        (
7247            SELECT
7248                t.oid
7249            FROM
7250                mz_catalog.mz_array_types AS a
7251                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7252            WHERE
7253                a.element_id = mz_types.id
7254        ),
7255        0
7256    )
7257        AS typarray,
7258    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7259    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7260    false::pg_catalog.bool AS typnotnull,
7261    0::pg_catalog.oid AS typbasetype,
7262    -1::pg_catalog.int4 AS typtypmod,
7263    -- MZ doesn't support COLLATE so typcollation is filled with 0
7264    0::pg_catalog.oid AS typcollation,
7265    NULL::pg_catalog.text AS typdefault,
7266    d.name as database_name
7267FROM
7268    mz_catalog.mz_types
7269    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7270    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7271    JOIN (
7272            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7273            -- converted to the correct value above.
7274            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7275            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7276            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7277            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7278            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7279        )
7280            AS t ON mz_types.id = t.id
7281    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7282    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7283        access: vec![PUBLIC_SELECT],
7284    }
7285});
7286
7287pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7288    name: "pg_type_all_databases_ind",
7289    schema: MZ_INTERNAL_SCHEMA,
7290    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7291    sql: "IN CLUSTER mz_catalog_server
7292ON mz_internal.pg_type_all_databases (oid)",
7293    is_retained_metrics_object: false,
7294};
7295
7296pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7297    name: "pg_type",
7298    schema: PG_CATALOG_SCHEMA,
7299    oid: oid::VIEW_PG_TYPE_OID,
7300    desc: RelationDesc::builder()
7301        .with_column("oid", ScalarType::Oid.nullable(false))
7302        .with_column("typname", ScalarType::String.nullable(false))
7303        .with_column("typnamespace", ScalarType::Oid.nullable(false))
7304        .with_column("typowner", ScalarType::Oid.nullable(false))
7305        .with_column("typlen", ScalarType::Int16.nullable(true))
7306        .with_column("typtype", ScalarType::PgLegacyChar.nullable(false))
7307        .with_column("typcategory", ScalarType::PgLegacyChar.nullable(true))
7308        .with_column("typdelim", ScalarType::PgLegacyChar.nullable(false))
7309        .with_column("typrelid", ScalarType::Oid.nullable(false))
7310        .with_column("typelem", ScalarType::Oid.nullable(false))
7311        .with_column("typarray", ScalarType::Oid.nullable(false))
7312        .with_column("typinput", ScalarType::RegProc.nullable(true))
7313        .with_column("typreceive", ScalarType::Oid.nullable(false))
7314        .with_column("typnotnull", ScalarType::Bool.nullable(false))
7315        .with_column("typbasetype", ScalarType::Oid.nullable(false))
7316        .with_column("typtypmod", ScalarType::Int32.nullable(false))
7317        .with_column("typcollation", ScalarType::Oid.nullable(false))
7318        .with_column("typdefault", ScalarType::String.nullable(true))
7319        .finish(),
7320    column_comments: BTreeMap::new(),
7321    sql: "SELECT
7322    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7323    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7324FROM mz_internal.pg_type_all_databases
7325WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7326    access: vec![PUBLIC_SELECT],
7327});
7328
7329/// Peeled version of `PG_ATTRIBUTE`:
7330/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7331///   in order to make this view indexable.
7332/// - This has 2 extra columns for the database names, so that downstream views can check them
7333///   against `current_database()`.
7334pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7335    BuiltinView {
7336        name: "pg_attribute_all_databases",
7337        schema: MZ_INTERNAL_SCHEMA,
7338        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7339        desc: RelationDesc::builder()
7340            .with_column("attrelid", ScalarType::Oid.nullable(false))
7341            .with_column("attname", ScalarType::String.nullable(false))
7342            .with_column("atttypid", ScalarType::Oid.nullable(false))
7343            .with_column("attlen", ScalarType::Int16.nullable(true))
7344            .with_column("attnum", ScalarType::Int16.nullable(false))
7345            .with_column("atttypmod", ScalarType::Int32.nullable(false))
7346            .with_column("attnotnull", ScalarType::Bool.nullable(false))
7347            .with_column("atthasdef", ScalarType::Bool.nullable(false))
7348            .with_column("attidentity", ScalarType::PgLegacyChar.nullable(false))
7349            .with_column("attgenerated", ScalarType::PgLegacyChar.nullable(false))
7350            .with_column("attisdropped", ScalarType::Bool.nullable(false))
7351            .with_column("attcollation", ScalarType::Oid.nullable(false))
7352            .with_column("database_name", ScalarType::String.nullable(true))
7353            .with_column("pg_type_database_name", ScalarType::String.nullable(true))
7354            .finish(),
7355        column_comments: BTreeMap::new(),
7356        sql: "
7357SELECT
7358    class_objects.oid as attrelid,
7359    mz_columns.name as attname,
7360    mz_columns.type_oid AS atttypid,
7361    pg_type_all_databases.typlen AS attlen,
7362    position::int8::int2 as attnum,
7363    mz_columns.type_mod as atttypmod,
7364    NOT nullable as attnotnull,
7365    mz_columns.default IS NOT NULL as atthasdef,
7366    ''::pg_catalog.\"char\" as attidentity,
7367    -- MZ doesn't support generated columns so attgenerated is filled with ''
7368    ''::pg_catalog.\"char\" as attgenerated,
7369    FALSE as attisdropped,
7370    -- MZ doesn't support COLLATE so attcollation is filled with 0
7371    0::pg_catalog.oid as attcollation,
7372    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7373    d.name as database_name,
7374    pg_type_all_databases.database_name as pg_type_database_name
7375FROM (
7376    -- pg_attribute catalogs columns on relations and indexes
7377    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7378    UNION ALL
7379        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7380        FROM mz_catalog.mz_indexes
7381        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7382) AS class_objects
7383JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7384JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7385JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7386LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7387        // Since this depends on pg_type, its id must be higher due to initialization
7388        // ordering.
7389        access: vec![PUBLIC_SELECT],
7390    }
7391});
7392
7393pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7394    name: "pg_attribute_all_databases_ind",
7395    schema: MZ_INTERNAL_SCHEMA,
7396    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7397    sql: "IN CLUSTER mz_catalog_server
7398ON mz_internal.pg_attribute_all_databases (
7399    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7400    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7401)",
7402    is_retained_metrics_object: false,
7403};
7404
7405pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7406    BuiltinView {
7407        name: "pg_attribute",
7408        schema: PG_CATALOG_SCHEMA,
7409        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7410        desc: RelationDesc::builder()
7411            .with_column("attrelid", ScalarType::Oid.nullable(false))
7412            .with_column("attname", ScalarType::String.nullable(false))
7413            .with_column("atttypid", ScalarType::Oid.nullable(false))
7414            .with_column("attlen", ScalarType::Int16.nullable(true))
7415            .with_column("attnum", ScalarType::Int16.nullable(false))
7416            .with_column("atttypmod", ScalarType::Int32.nullable(false))
7417            .with_column("attnotnull", ScalarType::Bool.nullable(false))
7418            .with_column("atthasdef", ScalarType::Bool.nullable(false))
7419            .with_column("attidentity", ScalarType::PgLegacyChar.nullable(false))
7420            .with_column("attgenerated", ScalarType::PgLegacyChar.nullable(false))
7421            .with_column("attisdropped", ScalarType::Bool.nullable(false))
7422            .with_column("attcollation", ScalarType::Oid.nullable(false))
7423            .finish(),
7424        column_comments: BTreeMap::new(),
7425        sql: "
7426SELECT
7427    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7428    attgenerated, attisdropped, attcollation
7429FROM mz_internal.pg_attribute_all_databases
7430WHERE
7431  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7432  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7433        // Since this depends on pg_type, its id must be higher due to initialization
7434        // ordering.
7435        access: vec![PUBLIC_SELECT],
7436    }
7437});
7438
7439pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7440    name: "pg_proc",
7441    schema: PG_CATALOG_SCHEMA,
7442    oid: oid::VIEW_PG_PROC_OID,
7443    desc: RelationDesc::builder()
7444        .with_column("oid", ScalarType::Oid.nullable(false))
7445        .with_column("proname", ScalarType::String.nullable(false))
7446        .with_column("pronamespace", ScalarType::Oid.nullable(false))
7447        .with_column("proowner", ScalarType::Oid.nullable(false))
7448        .with_column("proargdefaults", ScalarType::String.nullable(true))
7449        .with_column("prorettype", ScalarType::Oid.nullable(false))
7450        .finish(),
7451    column_comments: BTreeMap::new(),
7452    sql: "SELECT
7453    mz_functions.oid,
7454    mz_functions.name AS proname,
7455    mz_schemas.oid AS pronamespace,
7456    role_owner.oid AS proowner,
7457    NULL::pg_catalog.text AS proargdefaults,
7458    ret_type.oid AS prorettype
7459FROM mz_catalog.mz_functions
7460JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7461LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7462JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7463JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7464WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7465    access: vec![PUBLIC_SELECT],
7466});
7467
7468pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7469    name: "pg_operator",
7470    schema: PG_CATALOG_SCHEMA,
7471    oid: oid::VIEW_PG_OPERATOR_OID,
7472    desc: RelationDesc::builder()
7473        .with_column("oid", ScalarType::Oid.nullable(false))
7474        .with_column("oprname", ScalarType::String.nullable(false))
7475        .with_column("oprresult", ScalarType::Oid.nullable(false))
7476        .with_column("oprleft", ScalarType::Oid.nullable(false))
7477        .with_column("oprright", ScalarType::Oid.nullable(false))
7478        .with_key(vec![0, 1, 2, 3, 4])
7479        .finish(),
7480    column_comments: BTreeMap::new(),
7481    sql: "SELECT
7482    mz_operators.oid,
7483    mz_operators.name AS oprname,
7484    ret_type.oid AS oprresult,
7485    left_type.oid as oprleft,
7486    right_type.oid as oprright
7487FROM mz_catalog.mz_operators
7488JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7489JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7490JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7491WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7492UNION SELECT
7493    mz_operators.oid,
7494    mz_operators.name AS oprname,
7495    ret_type.oid AS oprresult,
7496    0 as oprleft,
7497    right_type.oid as oprright
7498FROM mz_catalog.mz_operators
7499JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7500JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7501WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7502    access: vec![PUBLIC_SELECT],
7503});
7504
7505pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7506    name: "pg_range",
7507    schema: PG_CATALOG_SCHEMA,
7508    oid: oid::VIEW_PG_RANGE_OID,
7509    desc: RelationDesc::builder()
7510        .with_column("rngtypid", ScalarType::Oid.nullable(false))
7511        .with_column("rngsubtype", ScalarType::Oid.nullable(false))
7512        .with_key(vec![])
7513        .finish(),
7514    column_comments: BTreeMap::new(),
7515    sql: "SELECT
7516    NULL::pg_catalog.oid AS rngtypid,
7517    NULL::pg_catalog.oid AS rngsubtype
7518WHERE false",
7519    access: vec![PUBLIC_SELECT],
7520});
7521
7522pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7523    name: "pg_enum",
7524    schema: PG_CATALOG_SCHEMA,
7525    oid: oid::VIEW_PG_ENUM_OID,
7526    desc: RelationDesc::builder()
7527        .with_column("oid", ScalarType::Oid.nullable(false))
7528        .with_column("enumtypid", ScalarType::Oid.nullable(false))
7529        .with_column("enumsortorder", ScalarType::Float32.nullable(false))
7530        .with_column("enumlabel", ScalarType::String.nullable(false))
7531        .with_key(vec![])
7532        .finish(),
7533    column_comments: BTreeMap::new(),
7534    sql: "SELECT
7535    NULL::pg_catalog.oid AS oid,
7536    NULL::pg_catalog.oid AS enumtypid,
7537    NULL::pg_catalog.float4 AS enumsortorder,
7538    NULL::pg_catalog.text AS enumlabel
7539WHERE false",
7540    access: vec![PUBLIC_SELECT],
7541});
7542
7543/// Peeled version of `PG_ATTRDEF`:
7544/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7545///   in order to make this view indexable.
7546pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7547    name: "pg_attrdef_all_databases",
7548    schema: MZ_INTERNAL_SCHEMA,
7549    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
7550    desc: RelationDesc::builder()
7551        .with_column("oid", ScalarType::Oid.nullable(true))
7552        .with_column("adrelid", ScalarType::Oid.nullable(false))
7553        .with_column("adnum", ScalarType::Int64.nullable(false))
7554        .with_column("adbin", ScalarType::String.nullable(false))
7555        .with_column("adsrc", ScalarType::String.nullable(false))
7556        .finish(),
7557    column_comments: BTreeMap::new(),
7558    sql: "
7559SELECT
7560    NULL::pg_catalog.oid AS oid,
7561    mz_objects.oid AS adrelid,
7562    mz_columns.position::int8 AS adnum,
7563    mz_columns.default AS adbin,
7564    mz_columns.default AS adsrc
7565FROM mz_catalog.mz_columns
7566    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
7567WHERE default IS NOT NULL",
7568    access: vec![PUBLIC_SELECT],
7569});
7570
7571pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7572    name: "pg_attrdef_all_databases_ind",
7573    schema: MZ_INTERNAL_SCHEMA,
7574    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
7575    sql: "IN CLUSTER mz_catalog_server
7576ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
7577    is_retained_metrics_object: false,
7578};
7579
7580pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7581    name: "pg_attrdef",
7582    schema: PG_CATALOG_SCHEMA,
7583    oid: oid::VIEW_PG_ATTRDEF_OID,
7584    desc: RelationDesc::builder()
7585        .with_column("oid", ScalarType::Oid.nullable(true))
7586        .with_column("adrelid", ScalarType::Oid.nullable(false))
7587        .with_column("adnum", ScalarType::Int64.nullable(false))
7588        .with_column("adbin", ScalarType::String.nullable(false))
7589        .with_column("adsrc", ScalarType::String.nullable(false))
7590        .finish(),
7591    column_comments: BTreeMap::new(),
7592    sql: "
7593SELECT
7594    pg_attrdef_all_databases.oid as oid,
7595    adrelid,
7596    adnum,
7597    adbin,
7598    adsrc
7599FROM mz_internal.pg_attrdef_all_databases
7600    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
7601    access: vec![PUBLIC_SELECT],
7602});
7603
7604pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7605    name: "pg_settings",
7606    schema: PG_CATALOG_SCHEMA,
7607    oid: oid::VIEW_PG_SETTINGS_OID,
7608    desc: RelationDesc::builder()
7609        .with_column("name", ScalarType::String.nullable(false))
7610        .with_column("setting", ScalarType::String.nullable(false))
7611        .with_key(vec![])
7612        .finish(),
7613    column_comments: BTreeMap::new(),
7614    sql: "SELECT
7615    name, setting
7616FROM (VALUES
7617    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
7618) AS _ (name, setting)",
7619    access: vec![PUBLIC_SELECT],
7620});
7621
7622pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7623    name: "pg_auth_members",
7624    schema: PG_CATALOG_SCHEMA,
7625    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
7626    desc: RelationDesc::builder()
7627        .with_column("roleid", ScalarType::Oid.nullable(false))
7628        .with_column("member", ScalarType::Oid.nullable(false))
7629        .with_column("grantor", ScalarType::Oid.nullable(false))
7630        .with_column("admin_option", ScalarType::Bool.nullable(false))
7631        .finish(),
7632    column_comments: BTreeMap::new(),
7633    sql: "SELECT
7634    role.oid AS roleid,
7635    member.oid AS member,
7636    grantor.oid AS grantor,
7637    -- Materialize hasn't implemented admin_option.
7638    false as admin_option
7639FROM mz_catalog.mz_role_members membership
7640JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
7641JOIN mz_catalog.mz_roles member ON membership.member = member.id
7642JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
7643    access: vec![PUBLIC_SELECT],
7644});
7645
7646pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7647    name: "pg_event_trigger",
7648    schema: PG_CATALOG_SCHEMA,
7649    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
7650    desc: RelationDesc::builder()
7651        .with_column("oid", ScalarType::Oid.nullable(false))
7652        .with_column("evtname", ScalarType::String.nullable(false))
7653        .with_column("evtevent", ScalarType::String.nullable(false))
7654        .with_column("evtowner", ScalarType::Oid.nullable(false))
7655        .with_column("evtfoid", ScalarType::Oid.nullable(false))
7656        .with_column("evtenabled", ScalarType::PgLegacyChar.nullable(false))
7657        .with_column(
7658            "evttags",
7659            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
7660        )
7661        .with_key(vec![])
7662        .finish(),
7663    column_comments: BTreeMap::new(),
7664    sql: "SELECT
7665        NULL::pg_catalog.oid AS oid,
7666        NULL::pg_catalog.text AS evtname,
7667        NULL::pg_catalog.text AS evtevent,
7668        NULL::pg_catalog.oid AS evtowner,
7669        NULL::pg_catalog.oid AS evtfoid,
7670        NULL::pg_catalog.char AS evtenabled,
7671        NULL::pg_catalog.text[] AS evttags
7672    WHERE false",
7673    access: vec![PUBLIC_SELECT],
7674});
7675
7676pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7677    name: "pg_language",
7678    schema: PG_CATALOG_SCHEMA,
7679    oid: oid::VIEW_PG_LANGUAGE_OID,
7680    desc: RelationDesc::builder()
7681        .with_column("oid", ScalarType::Oid.nullable(false))
7682        .with_column("lanname", ScalarType::String.nullable(false))
7683        .with_column("lanowner", ScalarType::Oid.nullable(false))
7684        .with_column("lanispl", ScalarType::Bool.nullable(false))
7685        .with_column("lanpltrusted", ScalarType::Bool.nullable(false))
7686        .with_column("lanplcallfoid", ScalarType::Oid.nullable(false))
7687        .with_column("laninline", ScalarType::Oid.nullable(false))
7688        .with_column("lanvalidator", ScalarType::Oid.nullable(false))
7689        .with_column(
7690            "lanacl",
7691            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
7692        )
7693        .with_key(vec![])
7694        .finish(),
7695    column_comments: BTreeMap::new(),
7696    sql: "SELECT
7697        NULL::pg_catalog.oid  AS oid,
7698        NULL::pg_catalog.text AS lanname,
7699        NULL::pg_catalog.oid  AS lanowner,
7700        NULL::pg_catalog.bool AS lanispl,
7701        NULL::pg_catalog.bool AS lanpltrusted,
7702        NULL::pg_catalog.oid  AS lanplcallfoid,
7703        NULL::pg_catalog.oid  AS laninline,
7704        NULL::pg_catalog.oid  AS lanvalidator,
7705        NULL::pg_catalog.text[] AS lanacl
7706    WHERE false",
7707    access: vec![PUBLIC_SELECT],
7708});
7709
7710pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7711    name: "pg_shdescription",
7712    schema: PG_CATALOG_SCHEMA,
7713    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
7714    desc: RelationDesc::builder()
7715        .with_column("objoid", ScalarType::Oid.nullable(false))
7716        .with_column("classoid", ScalarType::Oid.nullable(false))
7717        .with_column("description", ScalarType::String.nullable(false))
7718        .with_key(vec![])
7719        .finish(),
7720    column_comments: BTreeMap::new(),
7721    sql: "SELECT
7722        NULL::pg_catalog.oid AS objoid,
7723        NULL::pg_catalog.oid AS classoid,
7724        NULL::pg_catalog.text AS description
7725    WHERE false",
7726    access: vec![PUBLIC_SELECT],
7727});
7728
7729pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
7730    BuiltinView {
7731        name: "pg_timezone_abbrevs",
7732        schema: PG_CATALOG_SCHEMA,
7733        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
7734        desc: RelationDesc::builder()
7735            .with_column("abbrev", ScalarType::String.nullable(false))
7736            .with_column("utc_offset", ScalarType::Interval.nullable(true))
7737            .with_column("is_dst", ScalarType::Bool.nullable(true))
7738            .with_key(vec![0])
7739            .finish(),
7740        column_comments: BTreeMap::new(),
7741        sql: "SELECT
7742    abbreviation AS abbrev,
7743    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
7744        AS utc_offset,
7745    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
7746        AS is_dst
7747FROM mz_catalog.mz_timezone_abbreviations",
7748        access: vec![PUBLIC_SELECT],
7749    }
7750});
7751
7752pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7753    name: "pg_timezone_names",
7754    schema: PG_CATALOG_SCHEMA,
7755    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
7756    desc: RelationDesc::builder()
7757        .with_column("name", ScalarType::String.nullable(false))
7758        .with_column("abbrev", ScalarType::String.nullable(true))
7759        .with_column("utc_offset", ScalarType::Interval.nullable(true))
7760        .with_column("is_dst", ScalarType::Bool.nullable(true))
7761        .with_key(vec![0])
7762        .finish(),
7763    column_comments: BTreeMap::new(),
7764    sql: "SELECT
7765    name,
7766    timezone_offset(name, now()).abbrev AS abbrev,
7767    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
7768        AS utc_offset,
7769    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
7770        AS is_dst
7771FROM mz_catalog.mz_timezone_names",
7772    access: vec![PUBLIC_SELECT],
7773});
7774
7775pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7776    name: "mz_timezone_abbreviations",
7777    schema: MZ_CATALOG_SCHEMA,
7778    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
7779    desc: RelationDesc::builder()
7780        .with_column("abbreviation", ScalarType::String.nullable(false))
7781        .with_column("utc_offset", ScalarType::Interval.nullable(true))
7782        .with_column("dst", ScalarType::Bool.nullable(true))
7783        .with_column("timezone_name", ScalarType::String.nullable(true))
7784        .with_key(vec![0])
7785        .finish(),
7786    column_comments: BTreeMap::from_iter([
7787        ("abbreviation", "The timezone abbreviation."),
7788        (
7789            "utc_offset",
7790            "The UTC offset of the timezone or `NULL` if fixed.",
7791        ),
7792        (
7793            "dst",
7794            "Whether the timezone is in daylight savings or `NULL` if fixed.",
7795        ),
7796        (
7797            "timezone_name",
7798            "The full name of the non-fixed timezone or `NULL` if not fixed.",
7799        ),
7800    ]),
7801    sql: format!(
7802        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
7803        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
7804    )
7805    .leak(),
7806    access: vec![PUBLIC_SELECT],
7807});
7808
7809pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7810    name: "mz_timezone_names",
7811    schema: MZ_CATALOG_SCHEMA,
7812    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
7813    desc: RelationDesc::builder()
7814        .with_column("name", ScalarType::String.nullable(false))
7815        .with_key(vec![0])
7816        .finish(),
7817    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
7818    sql: format!(
7819        "SELECT * FROM ({}) _ (name)",
7820        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
7821    )
7822    .leak(),
7823    access: vec![PUBLIC_SELECT],
7824});
7825
7826pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7827    LazyLock::new(|| BuiltinView {
7828        name: "mz_peek_durations_histogram_per_worker",
7829        schema: MZ_INTROSPECTION_SCHEMA,
7830        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
7831        desc: RelationDesc::builder()
7832            .with_column("worker_id", ScalarType::UInt64.nullable(false))
7833            .with_column("type", ScalarType::String.nullable(false))
7834            .with_column("duration_ns", ScalarType::UInt64.nullable(false))
7835            .with_column("count", ScalarType::Int64.nullable(false))
7836            .with_key(vec![0, 1, 2])
7837            .finish(),
7838        column_comments: BTreeMap::new(),
7839        sql: "SELECT
7840    worker_id, type, duration_ns, pg_catalog.count(*) AS count
7841FROM
7842    mz_introspection.mz_peek_durations_histogram_raw
7843GROUP BY
7844    worker_id, type, duration_ns",
7845        access: vec![PUBLIC_SELECT],
7846    });
7847
7848pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7849    name: "mz_peek_durations_histogram",
7850    schema: MZ_INTROSPECTION_SCHEMA,
7851    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
7852    desc: RelationDesc::builder()
7853        .with_column("type", ScalarType::String.nullable(false))
7854        .with_column("duration_ns", ScalarType::UInt64.nullable(false))
7855        .with_column(
7856            "count",
7857            ScalarType::Numeric {
7858                max_scale: Some(NumericMaxScale::ZERO),
7859            }
7860            .nullable(false),
7861        )
7862        .with_key(vec![0, 1])
7863        .finish(),
7864    column_comments: BTreeMap::from_iter([
7865        ("type", "The peek variant: `index` or `persist`."),
7866        (
7867            "duration_ns",
7868            "The upper bound of the bucket in nanoseconds.",
7869        ),
7870        (
7871            "count",
7872            "The (noncumulative) count of peeks in this bucket.",
7873        ),
7874    ]),
7875    sql: "
7876SELECT
7877    type, duration_ns,
7878    pg_catalog.sum(count) AS count
7879FROM mz_introspection.mz_peek_durations_histogram_per_worker
7880GROUP BY type, duration_ns",
7881    access: vec![PUBLIC_SELECT],
7882});
7883
7884pub static MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7885    LazyLock::new(|| BuiltinView {
7886        name: "mz_dataflow_shutdown_durations_histogram_per_worker",
7887        schema: MZ_INTROSPECTION_SCHEMA,
7888        oid: oid::VIEW_MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_PER_WORKER_OID,
7889        desc: RelationDesc::builder()
7890            .with_column("worker_id", ScalarType::UInt64.nullable(false))
7891            .with_column("duration_ns", ScalarType::UInt64.nullable(false))
7892            .with_column("count", ScalarType::Int64.nullable(false))
7893            .with_key(vec![0, 1])
7894            .finish(),
7895        column_comments: BTreeMap::new(),
7896        sql: "SELECT
7897    worker_id, duration_ns, pg_catalog.count(*) AS count
7898FROM
7899    mz_introspection.mz_dataflow_shutdown_durations_histogram_raw
7900GROUP BY
7901    worker_id, duration_ns",
7902        access: vec![PUBLIC_SELECT],
7903    });
7904
7905pub static MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
7906    LazyLock::new(|| BuiltinView {
7907        name: "mz_dataflow_shutdown_durations_histogram",
7908        schema: MZ_INTROSPECTION_SCHEMA,
7909        oid: oid::VIEW_MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_OID,
7910        desc: RelationDesc::builder()
7911            .with_column("duration_ns", ScalarType::UInt64.nullable(false))
7912            .with_column(
7913                "count",
7914                ScalarType::Numeric {
7915                    max_scale: Some(NumericMaxScale::ZERO),
7916                }
7917                .nullable(false),
7918            )
7919            .with_key(vec![0])
7920            .finish(),
7921        column_comments: BTreeMap::from_iter([
7922            (
7923                "duration_ns",
7924                "The upper bound of the bucket in nanoseconds.",
7925            ),
7926            (
7927                "count",
7928                "The (noncumulative) count of dataflows in this bucket.",
7929            ),
7930        ]),
7931        sql: "
7932SELECT
7933    duration_ns,
7934    pg_catalog.sum(count) AS count
7935FROM mz_introspection.mz_dataflow_shutdown_durations_histogram_per_worker
7936GROUP BY duration_ns",
7937        access: vec![PUBLIC_SELECT],
7938    });
7939
7940pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
7941    LazyLock::new(|| BuiltinView {
7942        name: "mz_scheduling_elapsed_per_worker",
7943        schema: MZ_INTROSPECTION_SCHEMA,
7944        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
7945        desc: RelationDesc::builder()
7946            .with_column("id", ScalarType::UInt64.nullable(false))
7947            .with_column("worker_id", ScalarType::UInt64.nullable(false))
7948            .with_column("elapsed_ns", ScalarType::Int64.nullable(false))
7949            .with_key(vec![0, 1])
7950            .finish(),
7951        column_comments: BTreeMap::new(),
7952        sql: "SELECT
7953    id, worker_id, pg_catalog.count(*) AS elapsed_ns
7954FROM
7955    mz_introspection.mz_scheduling_elapsed_raw
7956GROUP BY
7957    id, worker_id",
7958        access: vec![PUBLIC_SELECT],
7959    });
7960
7961pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7962    name: "mz_scheduling_elapsed",
7963    schema: MZ_INTROSPECTION_SCHEMA,
7964    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
7965    desc: RelationDesc::builder()
7966        .with_column("id", ScalarType::UInt64.nullable(false))
7967        .with_column(
7968            "elapsed_ns",
7969            ScalarType::Numeric {
7970                max_scale: Some(NumericMaxScale::ZERO),
7971            }
7972            .nullable(false),
7973        )
7974        .with_key(vec![0])
7975        .finish(),
7976    column_comments: BTreeMap::from_iter([
7977        (
7978            "id",
7979            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
7980        ),
7981        (
7982            "elapsed_ns",
7983            "The total elapsed time spent in the operator in nanoseconds.",
7984        ),
7985    ]),
7986    sql: "
7987SELECT
7988    id,
7989    pg_catalog.sum(elapsed_ns) AS elapsed_ns
7990FROM mz_introspection.mz_scheduling_elapsed_per_worker
7991GROUP BY id",
7992    access: vec![PUBLIC_SELECT],
7993});
7994
7995pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7996    LazyLock::new(|| BuiltinView {
7997        name: "mz_compute_operator_durations_histogram_per_worker",
7998        schema: MZ_INTROSPECTION_SCHEMA,
7999        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8000        desc: RelationDesc::builder()
8001            .with_column("id", ScalarType::UInt64.nullable(false))
8002            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8003            .with_column("duration_ns", ScalarType::UInt64.nullable(false))
8004            .with_column("count", ScalarType::Int64.nullable(false))
8005            .with_key(vec![0, 1, 2])
8006            .finish(),
8007        column_comments: BTreeMap::new(),
8008        sql: "SELECT
8009    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8010FROM
8011    mz_introspection.mz_compute_operator_durations_histogram_raw
8012GROUP BY
8013    id, worker_id, duration_ns",
8014        access: vec![PUBLIC_SELECT],
8015    });
8016
8017pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8018    LazyLock::new(|| BuiltinView {
8019        name: "mz_compute_operator_durations_histogram",
8020        schema: MZ_INTROSPECTION_SCHEMA,
8021        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8022        desc: RelationDesc::builder()
8023            .with_column("id", ScalarType::UInt64.nullable(false))
8024            .with_column("duration_ns", ScalarType::UInt64.nullable(false))
8025            .with_column(
8026                "count",
8027                ScalarType::Numeric {
8028                    max_scale: Some(NumericMaxScale::ZERO),
8029                }
8030                .nullable(false),
8031            )
8032            .with_key(vec![0, 1])
8033            .finish(),
8034        column_comments: BTreeMap::from_iter([
8035            (
8036                "id",
8037                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8038            ),
8039            (
8040                "duration_ns",
8041                "The upper bound of the duration bucket in nanoseconds.",
8042            ),
8043            (
8044                "count",
8045                "The (noncumulative) count of invocations in the bucket.",
8046            ),
8047        ]),
8048        sql: "
8049SELECT
8050    id,
8051    duration_ns,
8052    pg_catalog.sum(count) AS count
8053FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8054GROUP BY id, duration_ns",
8055        access: vec![PUBLIC_SELECT],
8056    });
8057
8058pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8059    LazyLock::new(|| BuiltinView {
8060        name: "mz_scheduling_parks_histogram_per_worker",
8061        schema: MZ_INTROSPECTION_SCHEMA,
8062        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8063        desc: RelationDesc::builder()
8064            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8065            .with_column("slept_for_ns", ScalarType::UInt64.nullable(false))
8066            .with_column("requested_ns", ScalarType::UInt64.nullable(false))
8067            .with_column("count", ScalarType::Int64.nullable(false))
8068            .with_key(vec![0, 1, 2])
8069            .finish(),
8070        column_comments: BTreeMap::new(),
8071        sql: "SELECT
8072    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8073FROM
8074    mz_introspection.mz_scheduling_parks_histogram_raw
8075GROUP BY
8076    worker_id, slept_for_ns, requested_ns",
8077        access: vec![PUBLIC_SELECT],
8078    });
8079
8080pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8081    name: "mz_scheduling_parks_histogram",
8082    schema: MZ_INTROSPECTION_SCHEMA,
8083    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8084    desc: RelationDesc::builder()
8085        .with_column("slept_for_ns", ScalarType::UInt64.nullable(false))
8086        .with_column("requested_ns", ScalarType::UInt64.nullable(false))
8087        .with_column(
8088            "count",
8089            ScalarType::Numeric {
8090                max_scale: Some(NumericMaxScale::ZERO),
8091            }
8092            .nullable(false),
8093        )
8094        .with_key(vec![0, 1])
8095        .finish(),
8096    column_comments: BTreeMap::from_iter([
8097        (
8098            "slept_for_ns",
8099            "The actual length of the park event in nanoseconds.",
8100        ),
8101        (
8102            "requested_ns",
8103            "The requested length of the park event in nanoseconds.",
8104        ),
8105        (
8106            "count",
8107            "The (noncumulative) count of park events in this bucket.",
8108        ),
8109    ]),
8110    sql: "
8111SELECT
8112    slept_for_ns,
8113    requested_ns,
8114    pg_catalog.sum(count) AS count
8115FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8116GROUP BY slept_for_ns, requested_ns",
8117    access: vec![PUBLIC_SELECT],
8118});
8119
8120pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8121    LazyLock::new(|| BuiltinView {
8122        name: "mz_compute_error_counts_per_worker",
8123        schema: MZ_INTROSPECTION_SCHEMA,
8124        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8125        desc: RelationDesc::builder()
8126            .with_column("export_id", ScalarType::String.nullable(false))
8127            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8128            .with_column("count", ScalarType::Int64.nullable(false))
8129            .with_key(vec![0, 1, 2])
8130            .finish(),
8131        column_comments: BTreeMap::new(),
8132        sql: "
8133WITH MUTUALLY RECURSIVE
8134    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8135    -- For these we don't log error counts separately, so we need to forward the error counts from
8136    -- their dependencies instead.
8137    index_reuses(reuse_id text, index_id text) AS (
8138        SELECT d.object_id, d.dependency_id
8139        FROM mz_internal.mz_compute_dependencies d
8140        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8141        WHERE NOT EXISTS (
8142            SELECT 1 FROM mz_introspection.mz_dataflows
8143            WHERE id = e.dataflow_id
8144        )
8145    ),
8146    -- Error counts that were directly logged on compute exports.
8147    direct_errors(export_id text, worker_id uint8, count int8) AS (
8148        SELECT export_id, worker_id, count
8149        FROM mz_introspection.mz_compute_error_counts_raw
8150    ),
8151    -- Error counts propagated to index reused.
8152    all_errors(export_id text, worker_id uint8, count int8) AS (
8153        SELECT * FROM direct_errors
8154        UNION
8155        SELECT r.reuse_id, e.worker_id, e.count
8156        FROM all_errors e
8157        JOIN index_reuses r ON (r.index_id = e.export_id)
8158    )
8159SELECT * FROM all_errors",
8160        access: vec![PUBLIC_SELECT],
8161    });
8162
8163pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8164    name: "mz_compute_error_counts",
8165    schema: MZ_INTROSPECTION_SCHEMA,
8166    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8167    desc: RelationDesc::builder()
8168        .with_column("export_id", ScalarType::String.nullable(false))
8169        .with_column(
8170            "count",
8171            ScalarType::Numeric {
8172                max_scale: Some(NumericMaxScale::ZERO),
8173            }
8174            .nullable(false),
8175        )
8176        .with_key(vec![0])
8177        .finish(),
8178    column_comments: BTreeMap::from_iter([
8179        (
8180            "export_id",
8181            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8182        ),
8183        (
8184            "count",
8185            "The count of errors present in this dataflow export.",
8186        ),
8187    ]),
8188    sql: "
8189SELECT
8190    export_id,
8191    pg_catalog.sum(count) AS count
8192FROM mz_introspection.mz_compute_error_counts_per_worker
8193GROUP BY export_id
8194HAVING pg_catalog.sum(count) != 0",
8195    access: vec![PUBLIC_SELECT],
8196});
8197
8198pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8199    LazyLock::new(|| BuiltinSource {
8200        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8201        // naming conflict because the resolver stumbles over the source with the same name in
8202        // `mz_introspection` due to the automatic schema translation.
8203        name: "mz_compute_error_counts_raw_unified",
8204        schema: MZ_INTERNAL_SCHEMA,
8205        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8206        desc: RelationDesc::builder()
8207            .with_column("replica_id", ScalarType::String.nullable(false))
8208            .with_column("object_id", ScalarType::String.nullable(false))
8209            .with_column(
8210                "count",
8211                ScalarType::Numeric { max_scale: None }.nullable(false),
8212            )
8213            .finish(),
8214        data_source: IntrospectionType::ComputeErrorCounts,
8215        column_comments: BTreeMap::new(),
8216        is_retained_metrics_object: false,
8217        access: vec![PUBLIC_SELECT],
8218    });
8219
8220pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8221    name: "mz_compute_hydration_times",
8222    schema: MZ_INTERNAL_SCHEMA,
8223    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8224    desc: RelationDesc::builder()
8225        .with_column("replica_id", ScalarType::String.nullable(false))
8226        .with_column("object_id", ScalarType::String.nullable(false))
8227        .with_column("time_ns", ScalarType::UInt64.nullable(true))
8228        .finish(),
8229    data_source: IntrospectionType::ComputeHydrationTimes,
8230    column_comments: BTreeMap::new(),
8231    is_retained_metrics_object: true,
8232    access: vec![PUBLIC_SELECT],
8233});
8234
8235pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8236    LazyLock::new(|| BuiltinIndex {
8237        name: "mz_compute_hydration_times_ind",
8238        schema: MZ_INTERNAL_SCHEMA,
8239        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8240        sql: "IN CLUSTER mz_catalog_server
8241    ON mz_internal.mz_compute_hydration_times (replica_id)",
8242        is_retained_metrics_object: true,
8243    });
8244
8245pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8246    name: "mz_compute_hydration_statuses",
8247    schema: MZ_INTERNAL_SCHEMA,
8248    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8249    desc: RelationDesc::builder()
8250        .with_column("object_id", ScalarType::String.nullable(false))
8251        .with_column("replica_id", ScalarType::String.nullable(false))
8252        .with_column("hydrated", ScalarType::Bool.nullable(false))
8253        .with_column("hydration_time", ScalarType::Interval.nullable(true))
8254        .finish(),
8255    column_comments: BTreeMap::from_iter([
8256        (
8257            "object_id",
8258            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8259        ),
8260        ("replica_id", "The ID of a cluster replica."),
8261        (
8262            "hydrated",
8263            "Whether the compute object is hydrated on the replica.",
8264        ),
8265        (
8266            "hydration_time",
8267            "The amount of time it took for the replica to hydrate the compute object.",
8268        ),
8269    ]),
8270    sql: "
8271WITH
8272    dataflows AS (
8273        SELECT
8274            object_id,
8275            replica_id,
8276            time_ns IS NOT NULL AS hydrated,
8277            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8278        FROM mz_internal.mz_compute_hydration_times
8279    ),
8280    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8281    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8282    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8283    -- blue-green readiness query does), so we include them as 'hydrated'.
8284    complete_mvs AS (
8285        SELECT
8286            mv.id,
8287            f.replica_id,
8288            true AS hydrated,
8289            NULL::interval AS hydration_time
8290        FROM mz_materialized_views mv
8291        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8292        WHERE f.write_frontier IS NULL
8293    ),
8294    -- Ditto CTs
8295    complete_cts AS (
8296        SELECT
8297            ct.id,
8298            f.replica_id,
8299            true AS hydrated,
8300            NULL::interval AS hydration_time
8301        FROM mz_internal.mz_continual_tasks ct
8302        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = ct.id
8303        WHERE f.write_frontier IS NULL
8304    )
8305SELECT * FROM dataflows
8306UNION ALL
8307SELECT * FROM complete_mvs
8308UNION ALL
8309SELECT * FROM complete_cts",
8310    access: vec![PUBLIC_SELECT],
8311});
8312
8313pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| {
8314    BuiltinView {
8315        name: "mz_compute_operator_hydration_statuses",
8316        schema: MZ_INTERNAL_SCHEMA,
8317        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8318        desc: RelationDesc::builder()
8319            .with_column("object_id", ScalarType::String.nullable(false))
8320            .with_column("physical_plan_node_id", ScalarType::UInt64.nullable(false))
8321            .with_column("replica_id", ScalarType::String.nullable(false))
8322            .with_column("hydrated", ScalarType::Bool.nullable(false))
8323            .with_key(vec![0, 1, 2])
8324            .finish(),
8325        column_comments: BTreeMap::from_iter([
8326            (
8327                "object_id",
8328                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8329            ),
8330            (
8331                "physical_plan_node_id",
8332                "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)`.",
8333            ),
8334            ("replica_id", "The ID of a cluster replica."),
8335            ("hydrated", "Whether the node is hydrated on the replica."),
8336        ]),
8337        sql: "
8338SELECT
8339    object_id,
8340    physical_plan_node_id,
8341    replica_id,
8342    bool_and(hydrated) AS hydrated
8343FROM mz_internal.mz_compute_operator_hydration_statuses_per_worker
8344GROUP BY object_id, physical_plan_node_id, replica_id",
8345        access: vec![PUBLIC_SELECT],
8346    }
8347});
8348
8349pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8350    name: "mz_message_counts_per_worker",
8351    schema: MZ_INTROSPECTION_SCHEMA,
8352    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8353    desc: RelationDesc::builder()
8354        .with_column("channel_id", ScalarType::UInt64.nullable(false))
8355        .with_column("from_worker_id", ScalarType::UInt64.nullable(false))
8356        .with_column("to_worker_id", ScalarType::UInt64.nullable(false))
8357        .with_column("sent", ScalarType::Int64.nullable(false))
8358        .with_column("received", ScalarType::Int64.nullable(false))
8359        .with_column("batch_sent", ScalarType::Int64.nullable(false))
8360        .with_column("batch_received", ScalarType::Int64.nullable(false))
8361        .with_key(vec![0, 1, 2])
8362        .finish(),
8363    column_comments: BTreeMap::new(),
8364    sql: "
8365WITH batch_sent_cte AS (
8366    SELECT
8367        channel_id,
8368        from_worker_id,
8369        to_worker_id,
8370        pg_catalog.count(*) AS sent
8371    FROM
8372        mz_introspection.mz_message_batch_counts_sent_raw
8373    GROUP BY
8374        channel_id, from_worker_id, to_worker_id
8375),
8376batch_received_cte AS (
8377    SELECT
8378        channel_id,
8379        from_worker_id,
8380        to_worker_id,
8381        pg_catalog.count(*) AS received
8382    FROM
8383        mz_introspection.mz_message_batch_counts_received_raw
8384    GROUP BY
8385        channel_id, from_worker_id, to_worker_id
8386),
8387sent_cte AS (
8388    SELECT
8389        channel_id,
8390        from_worker_id,
8391        to_worker_id,
8392        pg_catalog.count(*) AS sent
8393    FROM
8394        mz_introspection.mz_message_counts_sent_raw
8395    GROUP BY
8396        channel_id, from_worker_id, to_worker_id
8397),
8398received_cte AS (
8399    SELECT
8400        channel_id,
8401        from_worker_id,
8402        to_worker_id,
8403        pg_catalog.count(*) AS received
8404    FROM
8405        mz_introspection.mz_message_counts_received_raw
8406    GROUP BY
8407        channel_id, from_worker_id, to_worker_id
8408)
8409SELECT
8410    sent_cte.channel_id,
8411    sent_cte.from_worker_id,
8412    sent_cte.to_worker_id,
8413    sent_cte.sent,
8414    received_cte.received,
8415    batch_sent_cte.sent AS batch_sent,
8416    batch_received_cte.received AS batch_received
8417FROM sent_cte
8418JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8419JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8420JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8421    access: vec![PUBLIC_SELECT],
8422});
8423
8424pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8425    name: "mz_message_counts",
8426    schema: MZ_INTROSPECTION_SCHEMA,
8427    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8428    desc: RelationDesc::builder()
8429        .with_column("channel_id", ScalarType::UInt64.nullable(false))
8430        .with_column(
8431            "sent",
8432            ScalarType::Numeric {
8433                max_scale: Some(NumericMaxScale::ZERO),
8434            }
8435            .nullable(false),
8436        )
8437        .with_column(
8438            "received",
8439            ScalarType::Numeric {
8440                max_scale: Some(NumericMaxScale::ZERO),
8441            }
8442            .nullable(false),
8443        )
8444        .with_column(
8445            "batch_sent",
8446            ScalarType::Numeric {
8447                max_scale: Some(NumericMaxScale::ZERO),
8448            }
8449            .nullable(false),
8450        )
8451        .with_column(
8452            "batch_received",
8453            ScalarType::Numeric {
8454                max_scale: Some(NumericMaxScale::ZERO),
8455            }
8456            .nullable(false),
8457        )
8458        .with_key(vec![0])
8459        .finish(),
8460    column_comments: BTreeMap::from_iter([
8461        (
8462            "channel_id",
8463            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8464        ),
8465        ("sent", "The number of messages sent."),
8466        ("received", "The number of messages received."),
8467        ("batch_sent", "The number of batches sent."),
8468        ("batch_received", "The number of batches received."),
8469    ]),
8470    sql: "
8471SELECT
8472    channel_id,
8473    pg_catalog.sum(sent) AS sent,
8474    pg_catalog.sum(received) AS received,
8475    pg_catalog.sum(batch_sent) AS batch_sent,
8476    pg_catalog.sum(batch_received) AS batch_received
8477FROM mz_introspection.mz_message_counts_per_worker
8478GROUP BY channel_id",
8479    access: vec![PUBLIC_SELECT],
8480});
8481
8482pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8483    name: "mz_active_peeks",
8484    schema: MZ_INTROSPECTION_SCHEMA,
8485    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8486    desc: RelationDesc::builder()
8487        .with_column("id", ScalarType::Uuid.nullable(false))
8488        .with_column("object_id", ScalarType::String.nullable(false))
8489        .with_column("type", ScalarType::String.nullable(false))
8490        .with_column("time", ScalarType::MzTimestamp.nullable(false))
8491        .finish(),
8492    column_comments: BTreeMap::from_iter([
8493        ("id", "The ID of the peek request."),
8494        (
8495            "object_id",
8496            "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`.",
8497        ),
8498        (
8499            "type",
8500            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8501        ),
8502        ("time", "The timestamp the peek has requested."),
8503    ]),
8504    sql: "
8505SELECT id, object_id, type, time
8506FROM mz_introspection.mz_active_peeks_per_worker
8507WHERE worker_id = 0",
8508    access: vec![PUBLIC_SELECT],
8509});
8510
8511pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8512    LazyLock::new(|| BuiltinView {
8513        name: "mz_dataflow_operator_reachability_per_worker",
8514        schema: MZ_INTROSPECTION_SCHEMA,
8515        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8516        desc: RelationDesc::builder()
8517            .with_column("id", ScalarType::UInt64.nullable(false))
8518            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8519            .with_column("port", ScalarType::UInt64.nullable(false))
8520            .with_column("update_type", ScalarType::String.nullable(false))
8521            .with_column("time", ScalarType::MzTimestamp.nullable(true))
8522            .with_column("count", ScalarType::Int64.nullable(false))
8523            .with_key(vec![0, 1, 2, 3, 4])
8524            .finish(),
8525        column_comments: BTreeMap::new(),
8526        sql: "SELECT
8527    addr2.id,
8528    reachability.worker_id,
8529    port,
8530    update_type,
8531    time,
8532    pg_catalog.count(*) as count
8533FROM
8534    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8535    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8536    mz_introspection.mz_dataflow_addresses_per_worker addr2
8537WHERE
8538    addr2.address =
8539    CASE
8540        WHEN source = 0 THEN addr1.address
8541        ELSE addr1.address || reachability.source
8542    END
8543    AND addr1.id = reachability.id
8544    AND addr1.worker_id = reachability.worker_id
8545    AND addr2.worker_id = reachability.worker_id
8546GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8547        access: vec![PUBLIC_SELECT],
8548    });
8549
8550pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8551    LazyLock::new(|| BuiltinView {
8552        name: "mz_dataflow_operator_reachability",
8553        schema: MZ_INTROSPECTION_SCHEMA,
8554        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8555        desc: RelationDesc::builder()
8556            .with_column("id", ScalarType::UInt64.nullable(false))
8557            .with_column("port", ScalarType::UInt64.nullable(false))
8558            .with_column("update_type", ScalarType::String.nullable(false))
8559            .with_column("time", ScalarType::MzTimestamp.nullable(true))
8560            .with_column(
8561                "count",
8562                ScalarType::Numeric {
8563                    max_scale: Some(NumericMaxScale::ZERO),
8564                }
8565                .nullable(false),
8566            )
8567            .with_key(vec![0, 1, 2, 3])
8568            .finish(),
8569        column_comments: BTreeMap::new(),
8570        sql: "
8571SELECT
8572    id,
8573    port,
8574    update_type,
8575    time,
8576    pg_catalog.sum(count) as count
8577FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8578GROUP BY id, port, update_type, time",
8579        access: vec![PUBLIC_SELECT],
8580    });
8581
8582pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8583    BuiltinView {
8584        name: "mz_arrangement_sizes_per_worker",
8585        schema: MZ_INTROSPECTION_SCHEMA,
8586        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8587        desc: RelationDesc::builder()
8588            .with_column("operator_id", ScalarType::UInt64.nullable(false))
8589            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8590            .with_column("records", ScalarType::Int64.nullable(false))
8591            .with_column("batches", ScalarType::Int64.nullable(false))
8592            .with_column("size", ScalarType::Int64.nullable(false))
8593            .with_column("capacity", ScalarType::Int64.nullable(false))
8594            .with_column("allocations", ScalarType::Int64.nullable(false))
8595            .finish(),
8596        column_comments: BTreeMap::new(),
8597        sql: "
8598WITH batches_cte AS (
8599    SELECT
8600        operator_id,
8601        worker_id,
8602        pg_catalog.count(*) AS batches
8603    FROM
8604        mz_introspection.mz_arrangement_batches_raw
8605    GROUP BY
8606        operator_id, worker_id
8607),
8608records_cte AS (
8609    SELECT
8610        operator_id,
8611        worker_id,
8612        pg_catalog.count(*) AS records
8613    FROM
8614        mz_introspection.mz_arrangement_records_raw
8615    GROUP BY
8616        operator_id, worker_id
8617),
8618heap_size_cte AS (
8619    SELECT
8620        operator_id,
8621        worker_id,
8622        pg_catalog.count(*) AS size
8623    FROM
8624        mz_introspection.mz_arrangement_heap_size_raw
8625    GROUP BY
8626        operator_id, worker_id
8627),
8628heap_capacity_cte AS (
8629    SELECT
8630        operator_id,
8631        worker_id,
8632        pg_catalog.count(*) AS capacity
8633    FROM
8634        mz_introspection.mz_arrangement_heap_capacity_raw
8635    GROUP BY
8636        operator_id, worker_id
8637),
8638heap_allocations_cte AS (
8639    SELECT
8640        operator_id,
8641        worker_id,
8642        pg_catalog.count(*) AS allocations
8643    FROM
8644        mz_introspection.mz_arrangement_heap_allocations_raw
8645    GROUP BY
8646        operator_id, worker_id
8647),
8648batcher_records_cte AS (
8649    SELECT
8650        operator_id,
8651        worker_id,
8652        pg_catalog.count(*) AS records
8653    FROM
8654        mz_introspection.mz_arrangement_batcher_records_raw
8655    GROUP BY
8656        operator_id, worker_id
8657),
8658batcher_size_cte AS (
8659    SELECT
8660        operator_id,
8661        worker_id,
8662        pg_catalog.count(*) AS size
8663    FROM
8664        mz_introspection.mz_arrangement_batcher_size_raw
8665    GROUP BY
8666        operator_id, worker_id
8667),
8668batcher_capacity_cte AS (
8669    SELECT
8670        operator_id,
8671        worker_id,
8672        pg_catalog.count(*) AS capacity
8673    FROM
8674        mz_introspection.mz_arrangement_batcher_capacity_raw
8675    GROUP BY
8676        operator_id, worker_id
8677),
8678batcher_allocations_cte AS (
8679    SELECT
8680        operator_id,
8681        worker_id,
8682        pg_catalog.count(*) AS allocations
8683    FROM
8684        mz_introspection.mz_arrangement_batcher_allocations_raw
8685    GROUP BY
8686        operator_id, worker_id
8687)
8688SELECT
8689    batches_cte.operator_id,
8690    batches_cte.worker_id,
8691    COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0) AS records,
8692    batches_cte.batches,
8693    COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0) AS size,
8694    COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0) AS capacity,
8695    COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0) AS allocations
8696FROM batches_cte
8697LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
8698LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
8699LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
8700LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
8701LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
8702LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
8703LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
8704LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)",
8705        access: vec![PUBLIC_SELECT],
8706    }
8707});
8708
8709pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8710    name: "mz_arrangement_sizes",
8711    schema: MZ_INTROSPECTION_SCHEMA,
8712    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
8713    desc: RelationDesc::builder()
8714        .with_column("operator_id", ScalarType::UInt64.nullable(false))
8715        .with_column(
8716            "records",
8717            ScalarType::Numeric {
8718                max_scale: Some(NumericMaxScale::ZERO),
8719            }
8720            .nullable(false),
8721        )
8722        .with_column(
8723            "batches",
8724            ScalarType::Numeric {
8725                max_scale: Some(NumericMaxScale::ZERO),
8726            }
8727            .nullable(false),
8728        )
8729        .with_column(
8730            "size",
8731            ScalarType::Numeric {
8732                max_scale: Some(NumericMaxScale::ZERO),
8733            }
8734            .nullable(false),
8735        )
8736        .with_column(
8737            "capacity",
8738            ScalarType::Numeric {
8739                max_scale: Some(NumericMaxScale::ZERO),
8740            }
8741            .nullable(false),
8742        )
8743        .with_column(
8744            "allocations",
8745            ScalarType::Numeric {
8746                max_scale: Some(NumericMaxScale::ZERO),
8747            }
8748            .nullable(false),
8749        )
8750        .with_key(vec![0])
8751        .finish(),
8752    column_comments: BTreeMap::from_iter([
8753        (
8754            "operator_id",
8755            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8756        ),
8757        ("records", "The number of records in the arrangement."),
8758        ("batches", "The number of batches in the arrangement."),
8759        ("size", "The utilized size in bytes of the arrangement."),
8760        (
8761            "capacity",
8762            "The capacity in bytes of the arrangement. Can be larger than the size.",
8763        ),
8764        (
8765            "allocations",
8766            "The number of separate memory allocations backing the arrangement.",
8767        ),
8768    ]),
8769    sql: "
8770SELECT
8771    operator_id,
8772    pg_catalog.sum(records) AS records,
8773    pg_catalog.sum(batches) AS batches,
8774    pg_catalog.sum(size) AS size,
8775    pg_catalog.sum(capacity) AS capacity,
8776    pg_catalog.sum(allocations) AS allocations
8777FROM mz_introspection.mz_arrangement_sizes_per_worker
8778GROUP BY operator_id",
8779    access: vec![PUBLIC_SELECT],
8780});
8781
8782pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
8783    LazyLock::new(|| BuiltinView {
8784        name: "mz_arrangement_sharing_per_worker",
8785        schema: MZ_INTROSPECTION_SCHEMA,
8786        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
8787        desc: RelationDesc::builder()
8788            .with_column("operator_id", ScalarType::UInt64.nullable(false))
8789            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8790            .with_column("count", ScalarType::Int64.nullable(false))
8791            .with_key(vec![0, 1])
8792            .finish(),
8793        column_comments: BTreeMap::new(),
8794        sql: "
8795SELECT
8796    operator_id,
8797    worker_id,
8798    pg_catalog.count(*) AS count
8799FROM mz_introspection.mz_arrangement_sharing_raw
8800GROUP BY operator_id, worker_id",
8801        access: vec![PUBLIC_SELECT],
8802    });
8803
8804pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8805    name: "mz_arrangement_sharing",
8806    schema: MZ_INTROSPECTION_SCHEMA,
8807    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
8808    desc: RelationDesc::builder()
8809        .with_column("operator_id", ScalarType::UInt64.nullable(false))
8810        .with_column("count", ScalarType::Int64.nullable(false))
8811        .finish(),
8812    column_comments: BTreeMap::from_iter([
8813        (
8814            "operator_id",
8815            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8816        ),
8817        (
8818            "count",
8819            "The number of operators that share the arrangement.",
8820        ),
8821    ]),
8822    sql: "
8823SELECT operator_id, count
8824FROM mz_introspection.mz_arrangement_sharing_per_worker
8825WHERE worker_id = 0",
8826    access: vec![PUBLIC_SELECT],
8827});
8828
8829pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8830    name: "mz_cluster_replica_utilization",
8831    schema: MZ_INTERNAL_SCHEMA,
8832    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
8833    desc: RelationDesc::builder()
8834        .with_column("replica_id", ScalarType::String.nullable(false))
8835        .with_column("process_id", ScalarType::UInt64.nullable(false))
8836        .with_column("cpu_percent", ScalarType::Float64.nullable(true))
8837        .with_column("memory_percent", ScalarType::Float64.nullable(true))
8838        .with_column("disk_percent", ScalarType::Float64.nullable(true))
8839        .finish(),
8840    column_comments: BTreeMap::from_iter([
8841        ("replica_id", "The ID of a cluster replica."),
8842        ("process_id", "The ID of a process within the replica."),
8843        (
8844            "cpu_percent",
8845            "Approximate CPU usage in percent of the total allocation.",
8846        ),
8847        (
8848            "memory_percent",
8849            "Approximate RAM usage in percent of the total allocation.",
8850        ),
8851        (
8852            "disk_percent",
8853            "Approximate disk usage in percent of the total allocation.",
8854        ),
8855    ]),
8856    sql: "
8857SELECT
8858    r.id AS replica_id,
8859    m.process_id,
8860    m.cpu_nano_cores::float8 / s.cpu_nano_cores * 100 AS cpu_percent,
8861    m.memory_bytes::float8 / s.memory_bytes * 100 AS memory_percent,
8862    m.disk_bytes::float8 / s.disk_bytes * 100 AS disk_percent
8863FROM
8864    mz_catalog.mz_cluster_replicas AS r
8865        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8866        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
8867    access: vec![PUBLIC_SELECT],
8868});
8869
8870pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
8871    LazyLock::new(|| BuiltinView {
8872        name: "mz_cluster_replica_utilization_history",
8873        schema: MZ_INTERNAL_SCHEMA,
8874        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
8875        desc: RelationDesc::builder()
8876            .with_column("replica_id", ScalarType::String.nullable(false))
8877            .with_column("process_id", ScalarType::UInt64.nullable(false))
8878            .with_column("cpu_percent", ScalarType::Float64.nullable(true))
8879            .with_column("memory_percent", ScalarType::Float64.nullable(true))
8880            .with_column("disk_percent", ScalarType::Float64.nullable(true))
8881            .with_column(
8882                "occurred_at",
8883                ScalarType::TimestampTz { precision: None }.nullable(false),
8884            )
8885            .finish(),
8886        column_comments: BTreeMap::from_iter([
8887            ("replica_id", "The ID of a cluster replica."),
8888            ("process_id", "The ID of a process within the replica."),
8889            (
8890                "cpu_percent",
8891                "Approximate CPU usage in percent of the total allocation.",
8892            ),
8893            (
8894                "memory_percent",
8895                "Approximate RAM usage in percent of the total allocation.",
8896            ),
8897            (
8898                "disk_percent",
8899                "Approximate disk usage in percent of the total allocation.",
8900            ),
8901            (
8902                "occurred_at",
8903                "Wall-clock timestamp at which the event occurred.",
8904            ),
8905        ]),
8906        sql: "
8907SELECT
8908    r.id AS replica_id,
8909    m.process_id,
8910    m.cpu_nano_cores::float8 / s.cpu_nano_cores * 100 AS cpu_percent,
8911    m.memory_bytes::float8 / s.memory_bytes * 100 AS memory_percent,
8912    m.disk_bytes::float8 / s.disk_bytes * 100 AS disk_percent,
8913    m.occurred_at
8914FROM
8915    mz_catalog.mz_cluster_replicas AS r
8916        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8917        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
8918        access: vec![PUBLIC_SELECT],
8919    });
8920
8921pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
8922    LazyLock::new(|| BuiltinView {
8923        name: "mz_dataflow_operator_parents_per_worker",
8924        schema: MZ_INTROSPECTION_SCHEMA,
8925        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
8926        desc: RelationDesc::builder()
8927            .with_column("id", ScalarType::UInt64.nullable(false))
8928            .with_column("parent_id", ScalarType::UInt64.nullable(false))
8929            .with_column("worker_id", ScalarType::UInt64.nullable(false))
8930            .finish(),
8931        column_comments: BTreeMap::new(),
8932        sql: "
8933WITH operator_addrs AS(
8934    SELECT
8935        id, address, worker_id
8936    FROM mz_introspection.mz_dataflow_addresses_per_worker
8937        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
8938            USING (id, worker_id)
8939),
8940parent_addrs AS (
8941    SELECT
8942        id,
8943        address[1:list_length(address) - 1] AS parent_address,
8944        worker_id
8945    FROM operator_addrs
8946)
8947SELECT pa.id, oa.id AS parent_id, pa.worker_id
8948FROM parent_addrs AS pa
8949    INNER JOIN operator_addrs AS oa
8950        ON pa.parent_address = oa.address
8951        AND pa.worker_id = oa.worker_id",
8952        access: vec![PUBLIC_SELECT],
8953    });
8954
8955pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8956    name: "mz_dataflow_operator_parents",
8957    schema: MZ_INTROSPECTION_SCHEMA,
8958    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
8959    desc: RelationDesc::builder()
8960        .with_column("id", ScalarType::UInt64.nullable(false))
8961        .with_column("parent_id", ScalarType::UInt64.nullable(false))
8962        .finish(),
8963    column_comments: BTreeMap::from_iter([
8964        (
8965            "id",
8966            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8967        ),
8968        (
8969            "parent_id",
8970            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
8971        ),
8972    ]),
8973    sql: "
8974SELECT id, parent_id
8975FROM mz_introspection.mz_dataflow_operator_parents_per_worker
8976WHERE worker_id = 0",
8977    access: vec![PUBLIC_SELECT],
8978});
8979
8980pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8981    name: "mz_dataflow_arrangement_sizes",
8982    schema: MZ_INTROSPECTION_SCHEMA,
8983    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
8984    desc: RelationDesc::builder()
8985        .with_column("id", ScalarType::UInt64.nullable(false))
8986        .with_column("name", ScalarType::String.nullable(false))
8987        .with_column(
8988            "records",
8989            ScalarType::Numeric { max_scale: None }.nullable(false),
8990        )
8991        .with_column(
8992            "batches",
8993            ScalarType::Numeric { max_scale: None }.nullable(false),
8994        )
8995        .with_column(
8996            "size",
8997            ScalarType::Numeric { max_scale: None }.nullable(false),
8998        )
8999        .with_column(
9000            "capacity",
9001            ScalarType::Numeric { max_scale: None }.nullable(false),
9002        )
9003        .with_column(
9004            "allocations",
9005            ScalarType::Numeric { max_scale: None }.nullable(false),
9006        )
9007        .with_key(vec![0, 1])
9008        .finish(),
9009    column_comments: BTreeMap::from_iter([
9010        (
9011            "id",
9012            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9013        ),
9014        ("name", "The name of the [dataflow]."),
9015        (
9016            "records",
9017            "The number of records in all arrangements in the dataflow.",
9018        ),
9019        (
9020            "batches",
9021            "The number of batches in all arrangements in the dataflow.",
9022        ),
9023        ("size", "The utilized size in bytes of the arrangements."),
9024        (
9025            "capacity",
9026            "The capacity in bytes of the arrangements. Can be larger than the size.",
9027        ),
9028        (
9029            "allocations",
9030            "The number of separate memory allocations backing the arrangements.",
9031        ),
9032    ]),
9033    sql: "
9034SELECT
9035    mdod.dataflow_id AS id,
9036    mdod.dataflow_name AS name,
9037    COALESCE(sum(mas.records), 0) AS records,
9038    COALESCE(sum(mas.batches), 0) AS batches,
9039    COALESCE(sum(mas.size), 0) AS size,
9040    COALESCE(sum(mas.capacity), 0) AS capacity,
9041    COALESCE(sum(mas.allocations), 0) AS allocations
9042FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9043LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9044    ON mdod.id = mas.operator_id
9045GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9046    access: vec![PUBLIC_SELECT],
9047});
9048
9049pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9050    name: "mz_expected_group_size_advice",
9051    schema: MZ_INTROSPECTION_SCHEMA,
9052    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9053    desc: RelationDesc::builder()
9054        .with_column("dataflow_id", ScalarType::UInt64.nullable(false))
9055        .with_column("dataflow_name", ScalarType::String.nullable(false))
9056        .with_column("region_id", ScalarType::UInt64.nullable(false))
9057        .with_column("region_name", ScalarType::String.nullable(false))
9058        .with_column("levels", ScalarType::Int64.nullable(false))
9059        .with_column("to_cut", ScalarType::Int64.nullable(false))
9060        .with_column(
9061            "savings",
9062            ScalarType::Numeric {
9063                max_scale: Some(NumericMaxScale::ZERO),
9064            }
9065            .nullable(false),
9066        )
9067        .with_column("hint", ScalarType::Float64.nullable(false))
9068        .finish(),
9069    column_comments: BTreeMap::from_iter([
9070        (
9071            "dataflow_id",
9072            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9073        ),
9074        (
9075            "dataflow_name",
9076            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9077        ),
9078        (
9079            "region_id",
9080            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9081        ),
9082        (
9083            "region_name",
9084            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9085        ),
9086        (
9087            "levels",
9088            "The number of levels in the hierarchical scheme implemented by the region.",
9089        ),
9090        (
9091            "to_cut",
9092            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9093        ),
9094        (
9095            "savings",
9096            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9097        ),
9098        (
9099            "hint",
9100            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9101        ),
9102    ]),
9103    sql: "
9104        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9105        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9106        -- of arrangements must be built. For each dataflow and region corresponding to one
9107        -- such pattern, we look for how many levels can be eliminated without hitting a level
9108        -- that actually substantially filters the input. The advice is constructed so that
9109        -- setting the hint for the affected region will eliminate these redundant levels of
9110        -- the hierachical rendering.
9111        --
9112        -- A number of helper CTEs are used for the view definition. The first one, operators,
9113        -- looks for operator names that comprise arrangements of inputs to each level of a
9114        -- min/max/top-k hierarchy.
9115        WITH operators AS (
9116            SELECT
9117                dod.dataflow_id,
9118                dor.id AS region_id,
9119                dod.id,
9120                ars.records,
9121                ars.size
9122            FROM
9123                mz_introspection.mz_dataflow_operator_dataflows dod
9124                JOIN mz_introspection.mz_dataflow_addresses doa
9125                    ON dod.id = doa.id
9126                JOIN mz_introspection.mz_dataflow_addresses dra
9127                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9128                JOIN mz_introspection.mz_dataflow_operators dor
9129                    ON dor.id = dra.id
9130                JOIN mz_introspection.mz_arrangement_sizes ars
9131                    ON ars.operator_id = dod.id
9132            WHERE
9133                dod.name = 'Arranged TopK input'
9134                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9135                OR dod.name = 'Arrange ReduceMinsMaxes'
9136            ),
9137        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9138        -- identified in operators above.
9139        levels AS (
9140            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9141            FROM operators o
9142            GROUP BY o.dataflow_id, o.region_id
9143        ),
9144        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9145        -- operator. This operator is crucially important, as it records the number of records
9146        -- that was given as input to the gadget as a whole.
9147        pivot AS (
9148            SELECT
9149                o1.dataflow_id,
9150                o1.region_id,
9151                o1.id,
9152                o1.records
9153            FROM operators o1
9154            WHERE
9155                o1.id = (
9156                    SELECT MIN(o2.id)
9157                    FROM operators o2
9158                    WHERE
9159                        o2.dataflow_id = o1.dataflow_id
9160                        AND o2.region_id = o1.region_id
9161                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9162                )
9163        ),
9164        -- The fourth CTE, candidates, will look for operators where the number of records
9165        -- maintained is not significantly different from the number at the pivot (excluding
9166        -- the pivot itself). These are the candidates for being cut from the dataflow region
9167        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9168        -- load generator data, to give some room for small deviations in number of records.
9169        -- The intuition for allowing for this deviation is that we are looking for a strongly
9170        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9171        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9172        -- among groups where the min/max/top-k computation is (partially) applied. If the
9173        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9174        -- groups might be empty or contain only one row. Each subsequent level will have a number
9175        -- of groups that is reduced exponentially. So at some point, we will find the level where
9176        -- we actually start having a few rows per group. That's where we will see the row counts
9177        -- significantly drop off.
9178        candidates AS (
9179            SELECT
9180                o.dataflow_id,
9181                o.region_id,
9182                o.id,
9183                o.records,
9184                o.size
9185            FROM
9186                operators o
9187                JOIN pivot p
9188                    ON o.dataflow_id = p.dataflow_id
9189                        AND o.region_id = p.region_id
9190                        AND o.id <> p.id
9191            WHERE o.records >= p.records * (1 - 0.15)
9192        ),
9193        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9194        -- candidate levels that should be cut. We only return here dataflow regions where at
9195        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9196        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9197        -- cutting the height of the hierarchy further. This is because we will have way less
9198        -- groups in the next level, so there should be even further reduction happening or there
9199        -- is some substantial skew in the data. But if the latter is the case, then we should not
9200        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9201        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9202        -- compute a conservative estimate of the memory savings in bytes that will result from
9203        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9204        -- input arrangements for each level to be cut. These arrangements should dominate the
9205        -- size of each level that can be cut, since the reduction gadget internal to the level
9206        -- does not remove much data at these levels.
9207        cuts AS (
9208            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9209            FROM candidates c
9210            GROUP BY c.dataflow_id, c.region_id
9211            HAVING COUNT(*) > 0
9212        )
9213        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9214        -- levels and the number of candidates to be cut. The hint is computed taking into account
9215        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9216        -- currently equal to 16.
9217        SELECT
9218            dod.dataflow_id,
9219            dod.dataflow_name,
9220            dod.id AS region_id,
9221            dod.name AS region_name,
9222            l.levels,
9223            c.to_cut,
9224            c.savings,
9225            pow(16, l.levels - c.to_cut) - 1 AS hint
9226        FROM cuts c
9227            JOIN levels l
9228                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9229            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9230                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9231    access: vec![PUBLIC_SELECT],
9232});
9233
9234pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9235    BuiltinView {
9236        name: "mz_index_advice",
9237        schema: MZ_INTERNAL_SCHEMA,
9238        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9239        desc: RelationDesc::builder()
9240            .with_column("object_id", ScalarType::String.nullable(true))
9241            .with_column("hint", ScalarType::String.nullable(false))
9242            .with_column("details", ScalarType::String.nullable(false))
9243            .with_column("referenced_object_ids", ScalarType::List { element_type: Box::new(ScalarType::String), custom_id: None }.nullable(true))
9244            .finish(),
9245        column_comments: BTreeMap::from_iter([
9246            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9247            ("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."),
9248            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9249            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9250        ]),
9251        sql: "
9252-- To avoid confusion with sources and sinks in the materialize sense,
9253-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9254-- when referring to the object dependency graph.
9255--
9256-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9257-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9258-- that are not depended on by other maintained objects and have a justification why they must
9259-- be maintained (e.g. a materialized view that is depended on by a sink).
9260-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9261-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9262-- downstream objects, that node is marked to be converted into a maintained object and this
9263-- node is then propagated further up. Once completed, the list of objects that are marked as
9264-- maintained is checked against all objects to generate appropriate recommendations.
9265--
9266-- Note that the recommendations only incorporate dependencies between objects.
9267-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9268-- a sink if an index is added in between the sink and the filter. For very selective filters,
9269-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9270-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9271-- dependencies.
9272WITH MUTUALLY RECURSIVE
9273    -- for all objects, understand if they have an index on them and on which cluster they are running
9274    -- this avoids having different cases for views with an index and materialized views later on
9275    objects(id text, type text, cluster_id text, indexes text list) AS (
9276        -- views and materialized views without an index
9277        SELECT
9278            o.id,
9279            o.type,
9280            o.cluster_id,
9281            '{}'::text list AS indexes
9282        FROM mz_catalog.mz_objects o
9283        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9284            SELECT FROM mz_internal.mz_object_dependencies d
9285            JOIN mz_catalog.mz_objects AS i
9286                ON (i.id = d.object_id AND i.type = 'index')
9287            WHERE (o.id = d.referenced_object_id)
9288        )
9289
9290        UNION ALL
9291
9292        -- views and materialized views with an index
9293        SELECT
9294            o.id,
9295            o.type,
9296            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9297            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9298            list_agg(i.id) AS indexes
9299        FROM mz_catalog.mz_objects o
9300        JOIN mz_internal.mz_object_dependencies AS d
9301            ON (o.id = d.referenced_object_id)
9302        JOIN mz_catalog.mz_objects AS i
9303            ON (i.id = d.object_id AND i.type = 'index')
9304        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9305        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9306    ),
9307
9308    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9309    maintained_leafs(id text, justification text) AS (
9310        -- materialized views that are connected to a sink
9311        SELECT
9312            m.id,
9313            s.id AS justification
9314        FROM objects AS m
9315        JOIN mz_internal.mz_object_dependencies AS d
9316            ON (m.id = d.referenced_object_id)
9317        JOIN mz_catalog.mz_objects AS s
9318            ON (s.id = d.object_id AND s.type = 'sink')
9319        WHERE m.type = 'materialized-view'
9320
9321        UNION ALL
9322
9323        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9324        SELECT
9325            v.id,
9326            unnest(v.indexes) AS justification
9327        FROM objects AS v
9328        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9329            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9330            INNER JOIN mz_catalog.mz_objects AS child
9331                ON (d.object_id = child.id)
9332            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]
9333        )
9334    ),
9335
9336    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9337    agg_maintained_children(id text, maintained_children text list) AS (
9338        SELECT
9339            parent_id AS id,
9340            list_agg(maintained_child) AS maintained_leafs
9341        FROM (
9342            SELECT DISTINCT
9343                d.referenced_object_id AS parent_id,
9344                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9345                unnest(child.maintained_children) AS maintained_child
9346            FROM propagate_dependencies AS child
9347            INNER JOIN mz_internal.mz_object_dependencies AS d
9348                ON (child.id = d.object_id)
9349        )
9350        GROUP BY parent_id
9351    ),
9352
9353    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9354    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9355    -- 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
9356    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9357        -- base case: start with the leafs
9358        SELECT DISTINCT
9359            id,
9360            LIST[id] AS maintained_children,
9361            list_agg(justification) AS justification
9362        FROM maintained_leafs
9363        GROUP BY id
9364
9365        UNION
9366
9367        -- recursive case: if there is a child with the same dependencies as the parent,
9368        -- the parent is only reused by a single child
9369        SELECT
9370            parent.id,
9371            child.maintained_children,
9372            NULL::text list AS justification
9373        FROM agg_maintained_children AS parent
9374        INNER JOIN mz_internal.mz_object_dependencies AS d
9375            ON (parent.id = d.referenced_object_id)
9376        INNER JOIN propagate_dependencies AS child
9377            ON (d.object_id = child.id)
9378        WHERE parent.maintained_children = child.maintained_children
9379
9380        UNION
9381
9382        -- recursive case: if there is NO child with the same dependencies as the parent,
9383        -- different children are reusing the parent so maintaining the object is justified by itself
9384        SELECT DISTINCT
9385            parent.id,
9386            LIST[parent.id] AS maintained_children,
9387            parent.maintained_children AS justification
9388        FROM agg_maintained_children AS parent
9389        WHERE NOT EXISTS (
9390            SELECT FROM mz_internal.mz_object_dependencies AS d
9391            INNER JOIN propagate_dependencies AS child
9392                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9393            WHERE parent.maintained_children = child.maintained_children
9394        )
9395    ),
9396
9397    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9398        SELECT
9399            p.id,
9400            o.type,
9401            o.cluster_id,
9402            p.maintained_children,
9403            p.justification,
9404            o.indexes
9405        FROM propagate_dependencies p
9406        JOIN objects AS o
9407            ON (p.id = o.id)
9408    ),
9409
9410    hints(id text, hint text, details text, justification text list) AS (
9411        -- materialized views that are not required
9412        SELECT
9413            id,
9414            'convert to a view' AS hint,
9415            'no dependencies from sinks nor from objects on different clusters' AS details,
9416            justification
9417        FROM objects_with_justification
9418        WHERE type = 'materialized-view' AND justification IS NULL
9419
9420        UNION ALL
9421
9422        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9423        SELECT
9424            id,
9425            'keep' AS hint,
9426            'dependencies from sinks or objects on different clusters: ' AS details,
9427            justification
9428        FROM objects_with_justification AS m
9429        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9430            SELECT FROM unnest(justification) AS dependency
9431            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9432
9433            UNION ALL
9434
9435            SELECT FROM unnest(justification) AS dependency
9436            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9437            WHERE d.cluster_id != m.cluster_id
9438        )
9439
9440        UNION ALL
9441
9442        -- 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
9443        SELECT
9444            id,
9445            'convert to a view with an index' AS hint,
9446            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9447            justification
9448        FROM objects_with_justification AS m
9449        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
9450            SELECT FROM unnest(justification) AS dependency
9451            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9452
9453            UNION ALL
9454
9455            SELECT FROM unnest(justification) AS dependency
9456            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9457            WHERE d.cluster_id != m.cluster_id
9458        )
9459
9460        UNION ALL
9461
9462        -- views that have indexes on different clusters should be a materialized view
9463        SELECT
9464            o.id,
9465            'convert to materialized view' AS hint,
9466            'dependencies on multiple clusters: ' AS details,
9467            o.justification
9468        FROM objects_with_justification o,
9469            LATERAL unnest(o.justification) j
9470        LEFT JOIN mz_catalog.mz_objects AS m
9471            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9472        WHERE o.type = 'view' AND o.justification IS NOT NULL
9473        GROUP BY o.id, o.justification
9474        HAVING count(DISTINCT m.cluster_id) >= 2
9475
9476        UNION ALL
9477
9478        -- views without an index that should be maintained
9479        SELECT
9480            id,
9481            'add index' AS hint,
9482            'multiple downstream dependencies: ' AS details,
9483            justification
9484        FROM objects_with_justification
9485        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9486
9487        UNION ALL
9488
9489        -- index inside the dependency graph (not a leaf)
9490        SELECT
9491            unnest(indexes) AS id,
9492            'drop unless queried directly' AS hint,
9493            'fewer than two downstream dependencies: ' AS details,
9494            maintained_children AS justification
9495        FROM objects_with_justification
9496        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9497
9498        UNION ALL
9499
9500        -- index on a leaf of the dependency graph
9501        SELECT
9502            unnest(indexes) AS id,
9503            'drop unless queried directly' AS hint,
9504            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9505            NULL::text list AS justification
9506        FROM objects_with_justification
9507        -- indexes can only be part of justification for leaf nodes
9508        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9509
9510        UNION ALL
9511
9512        -- index on a source
9513        SELECT
9514            unnest(indexes) AS id,
9515            'drop unless queried directly' AS hint,
9516            'sources do not transform data and can expose data directly' AS details,
9517            NULL::text list AS justification
9518        FROM objects_with_justification
9519        -- indexes can only be part of justification for leaf nodes
9520        WHERE type = 'source' AND NOT indexes = '{}'::text list
9521
9522        UNION ALL
9523
9524        -- indexes on views inside the dependency graph
9525        SELECT
9526            unnest(indexes) AS id,
9527            'keep' AS hint,
9528            'multiple downstream dependencies: ' AS details,
9529            justification
9530        FROM objects_with_justification
9531        -- indexes can only be part of justification for leaf nodes
9532        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9533    ),
9534
9535    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9536        SELECT
9537            h.id,
9538            h.hint,
9539            h.details || list_agg(o.name)::text AS details,
9540            h.justification
9541        FROM hints AS h,
9542            LATERAL unnest(h.justification) j
9543        JOIN mz_catalog.mz_objects AS o
9544            ON (o.id = j)
9545        GROUP BY h.id, h.hint, h.details, h.justification
9546
9547        UNION ALL
9548
9549        SELECT
9550            id,
9551            hint,
9552            details,
9553            justification
9554        FROM hints
9555        WHERE justification IS NULL
9556    )
9557
9558SELECT
9559    h.id AS object_id,
9560    h.hint AS hint,
9561    h.details,
9562    h.justification AS referenced_object_ids
9563FROM hints_resolved_ids AS h",
9564        access: vec![PUBLIC_SELECT],
9565    }
9566});
9567
9568// NOTE: If you add real data to this implementation, then please update
9569// the related `pg_` function implementations (like `pg_get_constraintdef`)
9570pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9571    name: "pg_constraint",
9572    schema: PG_CATALOG_SCHEMA,
9573    oid: oid::VIEW_PG_CONSTRAINT_OID,
9574    desc: RelationDesc::builder()
9575        .with_column("oid", ScalarType::Oid.nullable(false))
9576        .with_column("conname", ScalarType::String.nullable(false))
9577        .with_column("connamespace", ScalarType::Oid.nullable(false))
9578        .with_column("contype", ScalarType::PgLegacyChar.nullable(false))
9579        .with_column("condeferrable", ScalarType::Bool.nullable(false))
9580        .with_column("condeferred", ScalarType::Bool.nullable(false))
9581        .with_column("convalidated", ScalarType::Bool.nullable(false))
9582        .with_column("conrelid", ScalarType::Oid.nullable(false))
9583        .with_column("contypid", ScalarType::Oid.nullable(false))
9584        .with_column("conindid", ScalarType::Oid.nullable(false))
9585        .with_column("conparentid", ScalarType::Oid.nullable(false))
9586        .with_column("confrelid", ScalarType::Oid.nullable(false))
9587        .with_column("confupdtype", ScalarType::PgLegacyChar.nullable(false))
9588        .with_column("confdeltype", ScalarType::PgLegacyChar.nullable(false))
9589        .with_column("confmatchtype", ScalarType::PgLegacyChar.nullable(false))
9590        .with_column("conislocal", ScalarType::Bool.nullable(false))
9591        .with_column("coninhcount", ScalarType::Int32.nullable(false))
9592        .with_column("connoinherit", ScalarType::Bool.nullable(false))
9593        .with_column(
9594            "conkey",
9595            ScalarType::Array(Box::new(ScalarType::Int16)).nullable(false),
9596        )
9597        .with_column(
9598            "confkey",
9599            ScalarType::Array(Box::new(ScalarType::Int16)).nullable(false),
9600        )
9601        .with_column(
9602            "conpfeqop",
9603            ScalarType::Array(Box::new(ScalarType::Oid)).nullable(false),
9604        )
9605        .with_column(
9606            "conppeqop",
9607            ScalarType::Array(Box::new(ScalarType::Oid)).nullable(false),
9608        )
9609        .with_column(
9610            "conffeqop",
9611            ScalarType::Array(Box::new(ScalarType::Oid)).nullable(false),
9612        )
9613        .with_column(
9614            "conexclop",
9615            ScalarType::Array(Box::new(ScalarType::Oid)).nullable(false),
9616        )
9617        .with_column("conbin", ScalarType::String.nullable(false))
9618        .with_key(vec![])
9619        .finish(),
9620    column_comments: BTreeMap::new(),
9621    sql: "SELECT
9622    NULL::pg_catalog.oid as oid,
9623    NULL::pg_catalog.text as conname,
9624    NULL::pg_catalog.oid as connamespace,
9625    NULL::pg_catalog.\"char\" as contype,
9626    NULL::pg_catalog.bool as condeferrable,
9627    NULL::pg_catalog.bool as condeferred,
9628    NULL::pg_catalog.bool as convalidated,
9629    NULL::pg_catalog.oid as conrelid,
9630    NULL::pg_catalog.oid as contypid,
9631    NULL::pg_catalog.oid as conindid,
9632    NULL::pg_catalog.oid as conparentid,
9633    NULL::pg_catalog.oid as confrelid,
9634    NULL::pg_catalog.\"char\" as confupdtype,
9635    NULL::pg_catalog.\"char\" as confdeltype,
9636    NULL::pg_catalog.\"char\" as confmatchtype,
9637    NULL::pg_catalog.bool as conislocal,
9638    NULL::pg_catalog.int4 as coninhcount,
9639    NULL::pg_catalog.bool as connoinherit,
9640    NULL::pg_catalog.int2[] as conkey,
9641    NULL::pg_catalog.int2[] as confkey,
9642    NULL::pg_catalog.oid[] as conpfeqop,
9643    NULL::pg_catalog.oid[] as conppeqop,
9644    NULL::pg_catalog.oid[] as conffeqop,
9645    NULL::pg_catalog.oid[] as conexclop,
9646    NULL::pg_catalog.text as conbin
9647WHERE false",
9648    access: vec![PUBLIC_SELECT],
9649});
9650
9651pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9652    name: "pg_tables",
9653    schema: PG_CATALOG_SCHEMA,
9654    oid: oid::VIEW_PG_TABLES_OID,
9655    desc: RelationDesc::builder()
9656        .with_column("schemaname", ScalarType::String.nullable(true))
9657        .with_column("tablename", ScalarType::String.nullable(false))
9658        .with_column("tableowner", ScalarType::String.nullable(false))
9659        .finish(),
9660    column_comments: BTreeMap::new(),
9661    sql: "
9662SELECT n.nspname AS schemaname,
9663    c.relname AS tablename,
9664    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
9665FROM pg_catalog.pg_class c
9666LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
9667WHERE c.relkind IN ('r', 'p')",
9668    access: vec![PUBLIC_SELECT],
9669});
9670
9671pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9672    name: "pg_tablespace",
9673    schema: PG_CATALOG_SCHEMA,
9674    oid: oid::VIEW_PG_TABLESPACE_OID,
9675    desc: RelationDesc::builder()
9676        .with_column("oid", ScalarType::Oid.nullable(false))
9677        .with_column("spcname", ScalarType::String.nullable(false))
9678        .with_column("spcowner", ScalarType::Oid.nullable(true))
9679        .with_column(
9680            "spcacl",
9681            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
9682        )
9683        .with_column(
9684            "spcoptions",
9685            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
9686        )
9687        .with_key(vec![])
9688        .finish(),
9689    column_comments: BTreeMap::new(),
9690    sql: "
9691    SELECT oid, spcname, spcowner, spcacl, spcoptions
9692    FROM (
9693        VALUES (
9694            --These are the same defaults CockroachDB uses.
9695            0::pg_catalog.oid,
9696            'pg_default'::pg_catalog.text,
9697            NULL::pg_catalog.oid,
9698            NULL::pg_catalog.text[],
9699            NULL::pg_catalog.text[]
9700        )
9701    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
9702",
9703    access: vec![PUBLIC_SELECT],
9704});
9705
9706pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9707    name: "pg_am",
9708    schema: PG_CATALOG_SCHEMA,
9709    oid: oid::VIEW_PG_AM_OID,
9710    desc: RelationDesc::builder()
9711        .with_column("oid", ScalarType::Oid.nullable(false))
9712        .with_column("amname", ScalarType::String.nullable(false))
9713        .with_column("amhandler", ScalarType::RegProc.nullable(false))
9714        .with_column("amtype", ScalarType::PgLegacyChar.nullable(false))
9715        .with_key(vec![])
9716        .finish(),
9717    column_comments: BTreeMap::new(),
9718    sql: "
9719SELECT NULL::pg_catalog.oid AS oid,
9720    NULL::pg_catalog.text AS amname,
9721    NULL::pg_catalog.regproc AS amhandler,
9722    NULL::pg_catalog.\"char\" AS amtype
9723WHERE false",
9724    access: vec![PUBLIC_SELECT],
9725});
9726
9727pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9728    name: "pg_roles",
9729    schema: PG_CATALOG_SCHEMA,
9730    oid: oid::VIEW_PG_ROLES_OID,
9731    desc: RelationDesc::builder()
9732        .with_column("rolname", ScalarType::String.nullable(false))
9733        .with_column("rolsuper", ScalarType::Bool.nullable(true))
9734        .with_column("rolinherit", ScalarType::Bool.nullable(false))
9735        .with_column("rolcreaterole", ScalarType::Bool.nullable(true))
9736        .with_column("rolcreatedb", ScalarType::Bool.nullable(true))
9737        .with_column("rolcanlogin", ScalarType::Bool.nullable(false))
9738        .with_column("rolreplication", ScalarType::Bool.nullable(false))
9739        .with_column("rolconnlimit", ScalarType::Int32.nullable(false))
9740        .with_column("rolpassword", ScalarType::String.nullable(false))
9741        .with_column(
9742            "rolvaliduntil",
9743            ScalarType::TimestampTz { precision: None }.nullable(true),
9744        )
9745        .with_column("rolbypassrls", ScalarType::Bool.nullable(false))
9746        .with_column(
9747            "rolconfig",
9748            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
9749        )
9750        .with_column("oid", ScalarType::Oid.nullable(false))
9751        .finish(),
9752    column_comments: BTreeMap::new(),
9753    sql: "SELECT
9754    rolname,
9755    rolsuper,
9756    rolinherit,
9757    rolcreaterole,
9758    rolcreatedb,
9759    rolcanlogin,
9760    rolreplication,
9761    rolconnlimit,
9762    rolpassword,
9763    rolvaliduntil,
9764    rolbypassrls,
9765    (
9766        SELECT array_agg(parameter_name || '=' || parameter_value)
9767        FROM mz_catalog.mz_role_parameters rp
9768        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9769        WHERE ai.oid = r.oid
9770    ) AS rolconfig,
9771    oid
9772FROM pg_catalog.pg_authid ai",
9773    access: vec![PUBLIC_SELECT],
9774});
9775
9776pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9777    name: "pg_user",
9778    schema: PG_CATALOG_SCHEMA,
9779    oid: oid::VIEW_PG_USER_OID,
9780    desc: RelationDesc::builder()
9781        .with_column("usename", ScalarType::String.nullable(false))
9782        .with_column("usesysid", ScalarType::Oid.nullable(false))
9783        .with_column("usecreatedb", ScalarType::Bool.nullable(true))
9784        .with_column("usesuper", ScalarType::Bool.nullable(true))
9785        .with_column("userepl", ScalarType::Bool.nullable(false))
9786        .with_column("usebypassrls", ScalarType::Bool.nullable(false))
9787        .with_column("passwd", ScalarType::String.nullable(false))
9788        .with_column(
9789            "valuntil",
9790            ScalarType::TimestampTz { precision: None }.nullable(true),
9791        )
9792        .with_column(
9793            "useconfig",
9794            ScalarType::Array(Box::new(ScalarType::String)).nullable(true),
9795        )
9796        .finish(),
9797    column_comments: BTreeMap::new(),
9798    sql: "
9799SELECT
9800    rolname as usename,
9801    ai.oid as usesysid,
9802    rolcreatedb AS usecreatedb,
9803    rolsuper AS usesuper,
9804    rolreplication AS userepl,
9805    rolbypassrls AS usebypassrls,
9806    rolpassword as passwd,
9807    rolvaliduntil as valuntil,
9808    (
9809        SELECT array_agg(parameter_name || '=' || parameter_value)
9810        FROM mz_catalog.mz_role_parameters rp
9811        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9812        WHERE ai.oid = r.oid
9813    ) AS useconfig
9814FROM pg_catalog.pg_authid ai
9815WHERE rolcanlogin",
9816    access: vec![PUBLIC_SELECT],
9817});
9818
9819pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9820    name: "pg_views",
9821    schema: PG_CATALOG_SCHEMA,
9822    oid: oid::VIEW_PG_VIEWS_OID,
9823    desc: RelationDesc::builder()
9824        .with_column("schemaname", ScalarType::String.nullable(true))
9825        .with_column("viewname", ScalarType::String.nullable(false))
9826        .with_column("viewowner", ScalarType::Oid.nullable(false))
9827        .with_column("definition", ScalarType::String.nullable(false))
9828        .finish(),
9829    column_comments: BTreeMap::new(),
9830    sql: "SELECT
9831    s.name AS schemaname,
9832    v.name AS viewname,
9833    role_owner.oid AS viewowner,
9834    v.definition AS definition
9835FROM mz_catalog.mz_views v
9836LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
9837LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9838JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
9839WHERE s.database_id IS NULL OR d.name = current_database()",
9840    access: vec![PUBLIC_SELECT],
9841});
9842
9843pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9844    name: "pg_matviews",
9845    schema: PG_CATALOG_SCHEMA,
9846    oid: oid::VIEW_PG_MATVIEWS_OID,
9847    desc: RelationDesc::builder()
9848        .with_column("schemaname", ScalarType::String.nullable(true))
9849        .with_column("matviewname", ScalarType::String.nullable(false))
9850        .with_column("matviewowner", ScalarType::Oid.nullable(false))
9851        .with_column("definition", ScalarType::String.nullable(false))
9852        .finish(),
9853    column_comments: BTreeMap::new(),
9854    sql: "SELECT
9855    s.name AS schemaname,
9856    m.name AS matviewname,
9857    role_owner.oid AS matviewowner,
9858    m.definition AS definition
9859FROM mz_catalog.mz_materialized_views m
9860LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
9861LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9862JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
9863WHERE s.database_id IS NULL OR d.name = current_database()",
9864    access: vec![PUBLIC_SELECT],
9865});
9866
9867pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
9868    LazyLock::new(|| BuiltinView {
9869        name: "applicable_roles",
9870        schema: INFORMATION_SCHEMA,
9871        oid: oid::VIEW_APPLICABLE_ROLES_OID,
9872        desc: RelationDesc::builder()
9873            .with_column("grantee", ScalarType::String.nullable(false))
9874            .with_column("role_name", ScalarType::String.nullable(false))
9875            .with_column("is_grantable", ScalarType::String.nullable(false))
9876            .finish(),
9877        column_comments: BTreeMap::new(),
9878        sql: "
9879SELECT
9880    member.name AS grantee,
9881    role.name AS role_name,
9882    -- ADMIN OPTION isn't implemented.
9883    'NO' AS is_grantable
9884FROM mz_catalog.mz_role_members membership
9885JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
9886JOIN mz_catalog.mz_roles member ON membership.member = member.id
9887WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
9888        access: vec![PUBLIC_SELECT],
9889    });
9890
9891pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9892    name: "columns",
9893    schema: INFORMATION_SCHEMA,
9894    oid: oid::VIEW_COLUMNS_OID,
9895    desc: RelationDesc::builder()
9896        .with_column("table_catalog", ScalarType::String.nullable(false))
9897        .with_column("table_schema", ScalarType::String.nullable(false))
9898        .with_column("table_name", ScalarType::String.nullable(false))
9899        .with_column("column_name", ScalarType::String.nullable(false))
9900        .with_column("ordinal_position", ScalarType::Int64.nullable(false))
9901        .with_column("column_default", ScalarType::String.nullable(true))
9902        .with_column("is_nullable", ScalarType::String.nullable(false))
9903        .with_column("data_type", ScalarType::String.nullable(false))
9904        .with_column("character_maximum_length", ScalarType::Int32.nullable(true))
9905        .with_column("numeric_precision", ScalarType::Int32.nullable(true))
9906        .with_column("numeric_scale", ScalarType::Int32.nullable(true))
9907        .finish(),
9908    column_comments: BTreeMap::new(),
9909    sql: "
9910SELECT
9911    current_database() as table_catalog,
9912    s.name AS table_schema,
9913    o.name AS table_name,
9914    c.name AS column_name,
9915    c.position::int8 AS ordinal_position,
9916    c.default AS column_default,
9917    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
9918    c.type AS data_type,
9919    NULL::pg_catalog.int4 AS character_maximum_length,
9920    NULL::pg_catalog.int4 AS numeric_precision,
9921    NULL::pg_catalog.int4 AS numeric_scale
9922FROM mz_catalog.mz_columns c
9923JOIN mz_catalog.mz_objects o ON o.id = c.id
9924JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
9925LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9926WHERE s.database_id IS NULL OR d.name = current_database()",
9927    access: vec![PUBLIC_SELECT],
9928});
9929
9930pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
9931    LazyLock::new(|| BuiltinView {
9932        name: "enabled_roles",
9933        schema: INFORMATION_SCHEMA,
9934        oid: oid::VIEW_ENABLED_ROLES_OID,
9935        desc: RelationDesc::builder()
9936            .with_column("role_name", ScalarType::String.nullable(false))
9937            .finish(),
9938        column_comments: BTreeMap::new(),
9939        sql: "
9940SELECT name AS role_name
9941FROM mz_catalog.mz_roles
9942WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
9943        access: vec![PUBLIC_SELECT],
9944    });
9945
9946pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
9947    BuiltinView {
9948        name: "role_table_grants",
9949        schema: INFORMATION_SCHEMA,
9950        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
9951        desc: RelationDesc::builder()
9952            .with_column("grantor", ScalarType::String.nullable(false))
9953            .with_column("grantee", ScalarType::String.nullable(true))
9954            .with_column("table_catalog", ScalarType::String.nullable(true))
9955            .with_column("table_schema", ScalarType::String.nullable(false))
9956            .with_column("table_name", ScalarType::String.nullable(false))
9957            .with_column("privilege_type", ScalarType::String.nullable(true))
9958            .with_column("is_grantable", ScalarType::String.nullable(false))
9959            .with_column("with_hierarchy", ScalarType::String.nullable(false))
9960            .finish(),
9961        column_comments: BTreeMap::new(),
9962        sql: "
9963SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
9964FROM information_schema.table_privileges
9965WHERE
9966    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
9967    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
9968        access: vec![PUBLIC_SELECT],
9969    }
9970});
9971
9972pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
9973    LazyLock::new(|| BuiltinView {
9974        name: "key_column_usage",
9975        schema: INFORMATION_SCHEMA,
9976        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
9977        desc: RelationDesc::builder()
9978            .with_column("constraint_catalog", ScalarType::String.nullable(false))
9979            .with_column("constraint_schema", ScalarType::String.nullable(false))
9980            .with_column("constraint_name", ScalarType::String.nullable(false))
9981            .with_column("table_catalog", ScalarType::String.nullable(false))
9982            .with_column("table_schema", ScalarType::String.nullable(false))
9983            .with_column("table_name", ScalarType::String.nullable(false))
9984            .with_column("column_name", ScalarType::String.nullable(false))
9985            .with_column("ordinal_position", ScalarType::Int32.nullable(false))
9986            .with_column(
9987                "position_in_unique_constraint",
9988                ScalarType::Int32.nullable(false),
9989            )
9990            .with_key(vec![])
9991            .finish(),
9992        column_comments: BTreeMap::new(),
9993        sql: "SELECT
9994    NULL::text AS constraint_catalog,
9995    NULL::text AS constraint_schema,
9996    NULL::text AS constraint_name,
9997    NULL::text AS table_catalog,
9998    NULL::text AS table_schema,
9999    NULL::text AS table_name,
10000    NULL::text AS column_name,
10001    NULL::integer AS ordinal_position,
10002    NULL::integer AS position_in_unique_constraint
10003WHERE false",
10004        access: vec![PUBLIC_SELECT],
10005    });
10006
10007pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10008    LazyLock::new(|| BuiltinView {
10009        name: "referential_constraints",
10010        schema: INFORMATION_SCHEMA,
10011        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10012        desc: RelationDesc::builder()
10013            .with_column("constraint_catalog", ScalarType::String.nullable(false))
10014            .with_column("constraint_schema", ScalarType::String.nullable(false))
10015            .with_column("constraint_name", ScalarType::String.nullable(false))
10016            .with_column(
10017                "unique_constraint_catalog",
10018                ScalarType::String.nullable(false),
10019            )
10020            .with_column(
10021                "unique_constraint_schema",
10022                ScalarType::String.nullable(false),
10023            )
10024            .with_column("unique_constraint_name", ScalarType::String.nullable(false))
10025            .with_column("match_option", ScalarType::String.nullable(false))
10026            .with_column("update_rule", ScalarType::String.nullable(false))
10027            .with_column("delete_rule", ScalarType::String.nullable(false))
10028            .with_key(vec![])
10029            .finish(),
10030        column_comments: BTreeMap::new(),
10031        sql: "SELECT
10032    NULL::text AS constraint_catalog,
10033    NULL::text AS constraint_schema,
10034    NULL::text AS constraint_name,
10035    NULL::text AS unique_constraint_catalog,
10036    NULL::text AS unique_constraint_schema,
10037    NULL::text AS unique_constraint_name,
10038    NULL::text AS match_option,
10039    NULL::text AS update_rule,
10040    NULL::text AS delete_rule
10041WHERE false",
10042        access: vec![PUBLIC_SELECT],
10043    });
10044
10045pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10046    name: "routines",
10047    schema: INFORMATION_SCHEMA,
10048    oid: oid::VIEW_ROUTINES_OID,
10049    desc: RelationDesc::builder()
10050        .with_column("routine_catalog", ScalarType::String.nullable(false))
10051        .with_column("routine_schema", ScalarType::String.nullable(false))
10052        .with_column("routine_name", ScalarType::String.nullable(false))
10053        .with_column("routine_type", ScalarType::String.nullable(false))
10054        .with_column("routine_definition", ScalarType::String.nullable(true))
10055        .finish(),
10056    column_comments: BTreeMap::new(),
10057    sql: "SELECT
10058    current_database() as routine_catalog,
10059    s.name AS routine_schema,
10060    f.name AS routine_name,
10061    'FUNCTION' AS routine_type,
10062    NULL::text AS routine_definition
10063FROM mz_catalog.mz_functions f
10064JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10065LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10066WHERE s.database_id IS NULL OR d.name = current_database()",
10067    access: vec![PUBLIC_SELECT],
10068});
10069
10070pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10071    name: "schemata",
10072    schema: INFORMATION_SCHEMA,
10073    oid: oid::VIEW_SCHEMATA_OID,
10074    desc: RelationDesc::builder()
10075        .with_column("catalog_name", ScalarType::String.nullable(false))
10076        .with_column("schema_name", ScalarType::String.nullable(false))
10077        .finish(),
10078    column_comments: BTreeMap::new(),
10079    sql: "
10080SELECT
10081    current_database() as catalog_name,
10082    s.name AS schema_name
10083FROM mz_catalog.mz_schemas s
10084LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10085WHERE s.database_id IS NULL OR d.name = current_database()",
10086    access: vec![PUBLIC_SELECT],
10087});
10088
10089pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10090    name: "tables",
10091    schema: INFORMATION_SCHEMA,
10092    oid: oid::VIEW_TABLES_OID,
10093    desc: RelationDesc::builder()
10094        .with_column("table_catalog", ScalarType::String.nullable(false))
10095        .with_column("table_schema", ScalarType::String.nullable(false))
10096        .with_column("table_name", ScalarType::String.nullable(false))
10097        .with_column("table_type", ScalarType::String.nullable(false))
10098        .finish(),
10099    column_comments: BTreeMap::new(),
10100    sql: "SELECT
10101    current_database() as table_catalog,
10102    s.name AS table_schema,
10103    r.name AS table_name,
10104    CASE r.type
10105        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10106        WHEN 'table' THEN 'BASE TABLE'
10107        ELSE pg_catalog.upper(r.type)
10108    END AS table_type
10109FROM mz_catalog.mz_relations r
10110JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10111LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10112WHERE s.database_id IS NULL OR d.name = current_database()",
10113    access: vec![PUBLIC_SELECT],
10114});
10115
10116pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10117    LazyLock::new(|| BuiltinView {
10118        name: "table_constraints",
10119        schema: INFORMATION_SCHEMA,
10120        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10121        desc: RelationDesc::builder()
10122            .with_column("constraint_catalog", ScalarType::String.nullable(false))
10123            .with_column("constraint_schema", ScalarType::String.nullable(false))
10124            .with_column("constraint_name", ScalarType::String.nullable(false))
10125            .with_column("table_catalog", ScalarType::String.nullable(false))
10126            .with_column("table_schema", ScalarType::String.nullable(false))
10127            .with_column("table_name", ScalarType::String.nullable(false))
10128            .with_column("constraint_type", ScalarType::String.nullable(false))
10129            .with_column("is_deferrable", ScalarType::String.nullable(false))
10130            .with_column("initially_deferred", ScalarType::String.nullable(false))
10131            .with_column("enforced", ScalarType::String.nullable(false))
10132            .with_column("nulls_distinct", ScalarType::String.nullable(false))
10133            .with_key(vec![])
10134            .finish(),
10135        column_comments: BTreeMap::new(),
10136        sql: "SELECT
10137    NULL::text AS constraint_catalog,
10138    NULL::text AS constraint_schema,
10139    NULL::text AS constraint_name,
10140    NULL::text AS table_catalog,
10141    NULL::text AS table_schema,
10142    NULL::text AS table_name,
10143    NULL::text AS constraint_type,
10144    NULL::text AS is_deferrable,
10145    NULL::text AS initially_deferred,
10146    NULL::text AS enforced,
10147    NULL::text AS nulls_distinct
10148WHERE false",
10149        access: vec![PUBLIC_SELECT],
10150    });
10151
10152pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10153    BuiltinView {
10154        name: "table_privileges",
10155        schema: INFORMATION_SCHEMA,
10156        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10157        desc: RelationDesc::builder()
10158            .with_column("grantor", ScalarType::String.nullable(false))
10159            .with_column("grantee", ScalarType::String.nullable(true))
10160            .with_column("table_catalog", ScalarType::String.nullable(true))
10161            .with_column("table_schema", ScalarType::String.nullable(false))
10162            .with_column("table_name", ScalarType::String.nullable(false))
10163            .with_column("privilege_type", ScalarType::String.nullable(true))
10164            .with_column("is_grantable", ScalarType::String.nullable(false))
10165            .with_column("with_hierarchy", ScalarType::String.nullable(false))
10166            .finish(),
10167        column_comments: BTreeMap::new(),
10168        sql: "
10169SELECT
10170    grantor,
10171    grantee,
10172    table_catalog,
10173    table_schema,
10174    table_name,
10175    privilege_type,
10176    is_grantable,
10177    CASE privilege_type
10178        WHEN 'SELECT' THEN 'YES'
10179        ELSE 'NO'
10180    END AS with_hierarchy
10181FROM
10182    (SELECT
10183        grantor.name AS grantor,
10184        CASE mz_internal.mz_aclitem_grantee(privileges)
10185            WHEN 'p' THEN 'PUBLIC'
10186            ELSE grantee.name
10187        END AS grantee,
10188        table_catalog,
10189        table_schema,
10190        table_name,
10191        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10192        -- ADMIN OPTION isn't implemented.
10193        'NO' AS is_grantable
10194    FROM
10195        (SELECT
10196            unnest(relations.privileges) AS privileges,
10197            CASE
10198                WHEN schemas.database_id IS NULL THEN current_database()
10199                ELSE databases.name
10200            END AS table_catalog,
10201            schemas.name AS table_schema,
10202            relations.name AS table_name
10203        FROM mz_catalog.mz_relations AS relations
10204        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10205        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10206        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10207    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10208    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10209WHERE
10210    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10211    -- to pg_has_role. Therefore we need to use a CASE statement.
10212    CASE
10213        WHEN grantee = 'PUBLIC' THEN true
10214        ELSE mz_catalog.mz_is_superuser()
10215            OR pg_has_role(current_role, grantee, 'USAGE')
10216            OR pg_has_role(current_role, grantor, 'USAGE')
10217    END",
10218        access: vec![PUBLIC_SELECT],
10219    }
10220});
10221
10222pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10223    name: "triggers",
10224    schema: INFORMATION_SCHEMA,
10225    oid: oid::VIEW_TRIGGERS_OID,
10226    desc: RelationDesc::builder()
10227        .with_column("trigger_catalog", ScalarType::String.nullable(false))
10228        .with_column("trigger_schema", ScalarType::String.nullable(false))
10229        .with_column("trigger_name", ScalarType::String.nullable(false))
10230        .with_column("event_manipulation", ScalarType::String.nullable(false))
10231        .with_column("event_object_catalog", ScalarType::String.nullable(false))
10232        .with_column("event_object_schema", ScalarType::String.nullable(false))
10233        .with_column("event_object_table", ScalarType::String.nullable(false))
10234        .with_column("action_order", ScalarType::Int32.nullable(false))
10235        .with_column("action_condition", ScalarType::String.nullable(false))
10236        .with_column("action_statement", ScalarType::String.nullable(false))
10237        .with_column("action_orientation", ScalarType::String.nullable(false))
10238        .with_column("action_timing", ScalarType::String.nullable(false))
10239        .with_column(
10240            "action_reference_old_table",
10241            ScalarType::String.nullable(false),
10242        )
10243        .with_column(
10244            "action_reference_new_table",
10245            ScalarType::String.nullable(false),
10246        )
10247        .with_key(vec![])
10248        .finish(),
10249    column_comments: BTreeMap::new(),
10250    sql: "SELECT
10251    NULL::text as trigger_catalog,
10252    NULL::text AS trigger_schema,
10253    NULL::text AS trigger_name,
10254    NULL::text AS event_manipulation,
10255    NULL::text AS event_object_catalog,
10256    NULL::text AS event_object_schema,
10257    NULL::text AS event_object_table,
10258    NULL::integer AS action_order,
10259    NULL::text AS action_condition,
10260    NULL::text AS action_statement,
10261    NULL::text AS action_orientation,
10262    NULL::text AS action_timing,
10263    NULL::text AS action_reference_old_table,
10264    NULL::text AS action_reference_new_table
10265WHERE FALSE",
10266    access: vec![PUBLIC_SELECT],
10267});
10268
10269pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10270    name: "views",
10271    schema: INFORMATION_SCHEMA,
10272    oid: oid::VIEW_VIEWS_OID,
10273    desc: RelationDesc::builder()
10274        .with_column("table_catalog", ScalarType::String.nullable(false))
10275        .with_column("table_schema", ScalarType::String.nullable(false))
10276        .with_column("table_name", ScalarType::String.nullable(false))
10277        .with_column("view_definition", ScalarType::String.nullable(false))
10278        .finish(),
10279    column_comments: BTreeMap::new(),
10280    sql: "SELECT
10281    current_database() as table_catalog,
10282    s.name AS table_schema,
10283    v.name AS table_name,
10284    v.definition AS view_definition
10285FROM mz_catalog.mz_views v
10286JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10287LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10288WHERE s.database_id IS NULL OR d.name = current_database()",
10289    access: vec![PUBLIC_SELECT],
10290});
10291
10292pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10293    LazyLock::new(|| BuiltinView {
10294        name: "character_sets",
10295        schema: INFORMATION_SCHEMA,
10296        oid: oid::VIEW_CHARACTER_SETS_OID,
10297        desc: RelationDesc::builder()
10298            .with_column("character_set_catalog", ScalarType::String.nullable(true))
10299            .with_column("character_set_schema", ScalarType::String.nullable(true))
10300            .with_column("character_set_name", ScalarType::String.nullable(false))
10301            .with_column("character_repertoire", ScalarType::String.nullable(false))
10302            .with_column("form_of_use", ScalarType::String.nullable(false))
10303            .with_column(
10304                "default_collate_catalog",
10305                ScalarType::String.nullable(false),
10306            )
10307            .with_column("default_collate_schema", ScalarType::String.nullable(false))
10308            .with_column("default_collate_name", ScalarType::String.nullable(false))
10309            .with_key(vec![])
10310            .finish(),
10311        column_comments: BTreeMap::new(),
10312        sql: "SELECT
10313    NULL as character_set_catalog,
10314    NULL as character_set_schema,
10315    'UTF8' as character_set_name,
10316    'UCS' as character_repertoire,
10317    'UTF8' as form_of_use,
10318    current_database() as default_collate_catalog,
10319    'pg_catalog' as default_collate_schema,
10320    'en_US.utf8' as default_collate_name",
10321        access: vec![PUBLIC_SELECT],
10322    });
10323
10324// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10325// codes a collation of 'C' for every database, so we could copy that here.
10326pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10327    name: "pg_collation",
10328    schema: PG_CATALOG_SCHEMA,
10329    oid: oid::VIEW_PG_COLLATION_OID,
10330    desc: RelationDesc::builder()
10331        .with_column("oid", ScalarType::Oid.nullable(false))
10332        .with_column("collname", ScalarType::String.nullable(false))
10333        .with_column("collnamespace", ScalarType::Oid.nullable(false))
10334        .with_column("collowner", ScalarType::Oid.nullable(false))
10335        .with_column("collprovider", ScalarType::PgLegacyChar.nullable(false))
10336        .with_column("collisdeterministic", ScalarType::Bool.nullable(false))
10337        .with_column("collencoding", ScalarType::Int32.nullable(false))
10338        .with_column("collcollate", ScalarType::String.nullable(false))
10339        .with_column("collctype", ScalarType::String.nullable(false))
10340        .with_column("collversion", ScalarType::String.nullable(false))
10341        .with_key(vec![])
10342        .finish(),
10343    column_comments: BTreeMap::new(),
10344    sql: "
10345SELECT
10346    NULL::pg_catalog.oid AS oid,
10347    NULL::pg_catalog.text AS collname,
10348    NULL::pg_catalog.oid AS collnamespace,
10349    NULL::pg_catalog.oid AS collowner,
10350    NULL::pg_catalog.\"char\" AS collprovider,
10351    NULL::pg_catalog.bool AS collisdeterministic,
10352    NULL::pg_catalog.int4 AS collencoding,
10353    NULL::pg_catalog.text AS collcollate,
10354    NULL::pg_catalog.text AS collctype,
10355    NULL::pg_catalog.text AS collversion
10356WHERE false",
10357    access: vec![PUBLIC_SELECT],
10358});
10359
10360// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10361pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10362    name: "pg_policy",
10363    schema: PG_CATALOG_SCHEMA,
10364    oid: oid::VIEW_PG_POLICY_OID,
10365    desc: RelationDesc::builder()
10366        .with_column("oid", ScalarType::Oid.nullable(false))
10367        .with_column("polname", ScalarType::String.nullable(false))
10368        .with_column("polrelid", ScalarType::Oid.nullable(false))
10369        .with_column("polcmd", ScalarType::PgLegacyChar.nullable(false))
10370        .with_column("polpermissive", ScalarType::Bool.nullable(false))
10371        .with_column(
10372            "polroles",
10373            ScalarType::Array(Box::new(ScalarType::Oid)).nullable(false),
10374        )
10375        .with_column("polqual", ScalarType::String.nullable(false))
10376        .with_column("polwithcheck", ScalarType::String.nullable(false))
10377        .with_key(vec![])
10378        .finish(),
10379    column_comments: BTreeMap::new(),
10380    sql: "
10381SELECT
10382    NULL::pg_catalog.oid AS oid,
10383    NULL::pg_catalog.text AS polname,
10384    NULL::pg_catalog.oid AS polrelid,
10385    NULL::pg_catalog.\"char\" AS polcmd,
10386    NULL::pg_catalog.bool AS polpermissive,
10387    NULL::pg_catalog.oid[] AS polroles,
10388    NULL::pg_catalog.text AS polqual,
10389    NULL::pg_catalog.text AS polwithcheck
10390WHERE false",
10391    access: vec![PUBLIC_SELECT],
10392});
10393
10394// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10395pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10396    name: "pg_inherits",
10397    schema: PG_CATALOG_SCHEMA,
10398    oid: oid::VIEW_PG_INHERITS_OID,
10399    desc: RelationDesc::builder()
10400        .with_column("inhrelid", ScalarType::Oid.nullable(false))
10401        .with_column("inhparent", ScalarType::Oid.nullable(false))
10402        .with_column("inhseqno", ScalarType::Int32.nullable(false))
10403        .with_column("inhdetachpending", ScalarType::Bool.nullable(false))
10404        .with_key(vec![])
10405        .finish(),
10406    column_comments: BTreeMap::new(),
10407    sql: "
10408SELECT
10409    NULL::pg_catalog.oid AS inhrelid,
10410    NULL::pg_catalog.oid AS inhparent,
10411    NULL::pg_catalog.int4 AS inhseqno,
10412    NULL::pg_catalog.bool AS inhdetachpending
10413WHERE false",
10414    access: vec![PUBLIC_SELECT],
10415});
10416
10417pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10418    name: "pg_locks",
10419    schema: PG_CATALOG_SCHEMA,
10420    oid: oid::VIEW_PG_LOCKS_OID,
10421    desc: RelationDesc::builder()
10422        .with_column("locktype", ScalarType::String.nullable(false))
10423        .with_column("database", ScalarType::Oid.nullable(false))
10424        .with_column("relation", ScalarType::Oid.nullable(false))
10425        .with_column("page", ScalarType::Int32.nullable(false))
10426        .with_column("tuple", ScalarType::Int16.nullable(false))
10427        .with_column("virtualxid", ScalarType::String.nullable(false))
10428        .with_column("transactionid", ScalarType::String.nullable(false))
10429        .with_column("classid", ScalarType::Oid.nullable(false))
10430        .with_column("objid", ScalarType::Oid.nullable(false))
10431        .with_column("objsubid", ScalarType::Int16.nullable(false))
10432        .with_column("virtualtransaction", ScalarType::String.nullable(false))
10433        .with_column("pid", ScalarType::Int32.nullable(false))
10434        .with_column("mode", ScalarType::String.nullable(false))
10435        .with_column("granted", ScalarType::Bool.nullable(false))
10436        .with_column("fastpath", ScalarType::Bool.nullable(false))
10437        .with_column(
10438            "waitstart",
10439            ScalarType::TimestampTz { precision: None }.nullable(false),
10440        )
10441        .with_key(vec![])
10442        .finish(),
10443    column_comments: BTreeMap::new(),
10444    sql: "
10445SELECT
10446-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10447    NULL::pg_catalog.text AS locktype,
10448    NULL::pg_catalog.oid AS database,
10449    NULL::pg_catalog.oid AS relation,
10450    NULL::pg_catalog.int4 AS page,
10451    NULL::pg_catalog.int2 AS tuple,
10452    NULL::pg_catalog.text AS virtualxid,
10453    NULL::pg_catalog.text AS transactionid,
10454    NULL::pg_catalog.oid AS classid,
10455    NULL::pg_catalog.oid AS objid,
10456    NULL::pg_catalog.int2 AS objsubid,
10457    NULL::pg_catalog.text AS virtualtransaction,
10458    NULL::pg_catalog.int4 AS pid,
10459    NULL::pg_catalog.text AS mode,
10460    NULL::pg_catalog.bool AS granted,
10461    NULL::pg_catalog.bool AS fastpath,
10462    NULL::pg_catalog.timestamptz AS waitstart
10463WHERE false",
10464    access: vec![PUBLIC_SELECT],
10465});
10466
10467pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10468    name: "pg_authid",
10469    schema: PG_CATALOG_SCHEMA,
10470    oid: oid::VIEW_PG_AUTHID_OID,
10471    desc: RelationDesc::builder()
10472        .with_column("oid", ScalarType::Oid.nullable(false))
10473        .with_column("rolname", ScalarType::String.nullable(false))
10474        .with_column("rolsuper", ScalarType::Bool.nullable(true))
10475        .with_column("rolinherit", ScalarType::Bool.nullable(false))
10476        .with_column("rolcreaterole", ScalarType::Bool.nullable(true))
10477        .with_column("rolcreatedb", ScalarType::Bool.nullable(true))
10478        .with_column("rolcanlogin", ScalarType::Bool.nullable(false))
10479        .with_column("rolreplication", ScalarType::Bool.nullable(false))
10480        .with_column("rolbypassrls", ScalarType::Bool.nullable(false))
10481        .with_column("rolconnlimit", ScalarType::Int32.nullable(false))
10482        .with_column("rolpassword", ScalarType::String.nullable(false))
10483        .with_column(
10484            "rolvaliduntil",
10485            ScalarType::TimestampTz { precision: None }.nullable(true),
10486        )
10487        .finish(),
10488    column_comments: BTreeMap::new(),
10489    sql: r#"
10490SELECT
10491    r.oid AS oid,
10492    r.name AS rolname,
10493    -- We determine superuser status each time a role logs in, so there's no way to accurately
10494    -- depict this in the catalog. Except for mz_system, which is always a superuser. For all other
10495    -- roles we hardcode NULL.
10496    CASE
10497        WHEN r.name = 'mz_system' THEN true
10498        ELSE NULL::pg_catalog.bool
10499    END AS rolsuper,
10500    inherit AS rolinherit,
10501    mz_catalog.has_system_privilege(r.oid, 'CREATEROLE') AS rolcreaterole,
10502    mz_catalog.has_system_privilege(r.oid, 'CREATEDB') AS rolcreatedb,
10503    -- We determine login status each time a role logs in, so there's no clean
10504    -- way to accurately determine this in the catalog. Instead we do something
10505    -- a little gross. For system roles, we hardcode the known roles that can
10506    -- log in. For user roles, we determine `rolcanlogin` based on whether the
10507    -- role name looks like an email address.
10508    --
10509    -- This works for the vast majority of cases in production. Roles that users
10510    -- log in to come from Frontegg and therefore *must* be valid email
10511    -- addresses, while roles that are created via `CREATE ROLE` (e.g.,
10512    -- `admin`, `prod_app`) almost certainly are not named to look like email
10513    -- addresses.
10514    --
10515    -- For the moment, we're comfortable with the edge cases here. If we discover
10516    -- that folks are regularly creating non-login roles with names that look
10517    -- like an email address (e.g., `admins@sysops.foocorp`), we can change
10518    -- course.
10519    (
10520        r.name IN ('mz_support', 'mz_system')
10521        -- This entire scheme is sloppy, so we intentionally use a simple
10522        -- regex to match email addresses, rather than one that perfectly
10523        -- matches the RFC on what constitutes a valid email address.
10524        OR r.name ~ '^[^@]+@[^@]+\.[^@]+$'
10525    ) AS rolcanlogin,
10526    -- MZ doesn't support replication in the same way Postgres does
10527    false AS rolreplication,
10528    -- MZ doesn't how row level security
10529    false AS rolbypassrls,
10530    -- MZ doesn't have a connection limit
10531    -1 AS rolconnlimit,
10532    '********'::pg_catalog.text AS rolpassword,
10533    -- MZ doesn't have role passwords
10534    NULL::pg_catalog.timestamptz AS rolvaliduntil
10535FROM mz_catalog.mz_roles r"#,
10536    access: vec![PUBLIC_SELECT],
10537});
10538
10539pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10540    name: "pg_aggregate",
10541    schema: PG_CATALOG_SCHEMA,
10542    oid: oid::VIEW_PG_AGGREGATE_OID,
10543    desc: RelationDesc::builder()
10544        .with_column("aggfnoid", ScalarType::Oid.nullable(false))
10545        .with_column("aggkind", ScalarType::String.nullable(false))
10546        .with_column("aggnumdirectargs", ScalarType::Int16.nullable(false))
10547        .with_column("aggtransfn", ScalarType::RegProc.nullable(true))
10548        .with_column("aggfinalfn", ScalarType::RegProc.nullable(false))
10549        .with_column("aggcombinefn", ScalarType::RegProc.nullable(false))
10550        .with_column("aggserialfn", ScalarType::RegProc.nullable(false))
10551        .with_column("aggdeserialfn", ScalarType::RegProc.nullable(false))
10552        .with_column("aggmtransfn", ScalarType::RegProc.nullable(false))
10553        .with_column("aggminvtransfn", ScalarType::RegProc.nullable(false))
10554        .with_column("aggmfinalfn", ScalarType::RegProc.nullable(false))
10555        .with_column("aggfinalextra", ScalarType::Bool.nullable(false))
10556        .with_column("aggmfinalextra", ScalarType::Bool.nullable(false))
10557        .with_column("aggfinalmodify", ScalarType::PgLegacyChar.nullable(true))
10558        .with_column("aggmfinalmodify", ScalarType::PgLegacyChar.nullable(true))
10559        .with_column("aggsortop", ScalarType::Oid.nullable(false))
10560        .with_column("aggtranstype", ScalarType::Oid.nullable(true))
10561        .with_column("aggtransspace", ScalarType::Int32.nullable(true))
10562        .with_column("aggmtranstype", ScalarType::Oid.nullable(false))
10563        .with_column("aggmtransspace", ScalarType::Int32.nullable(true))
10564        .with_column("agginitval", ScalarType::String.nullable(true))
10565        .with_column("aggminitval", ScalarType::String.nullable(true))
10566        .finish(),
10567    column_comments: BTreeMap::new(),
10568    sql: "SELECT
10569    a.oid as aggfnoid,
10570    -- Currently Materialize only support 'normal' aggregate functions.
10571    a.agg_kind as aggkind,
10572    a.agg_num_direct_args as aggnumdirectargs,
10573    -- Materialize doesn't support these fields.
10574    NULL::pg_catalog.regproc as aggtransfn,
10575    '0'::pg_catalog.regproc as aggfinalfn,
10576    '0'::pg_catalog.regproc as aggcombinefn,
10577    '0'::pg_catalog.regproc as aggserialfn,
10578    '0'::pg_catalog.regproc as aggdeserialfn,
10579    '0'::pg_catalog.regproc as aggmtransfn,
10580    '0'::pg_catalog.regproc as aggminvtransfn,
10581    '0'::pg_catalog.regproc as aggmfinalfn,
10582    false as aggfinalextra,
10583    false as aggmfinalextra,
10584    NULL::pg_catalog.\"char\" AS aggfinalmodify,
10585    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
10586    '0'::pg_catalog.oid as aggsortop,
10587    NULL::pg_catalog.oid as aggtranstype,
10588    NULL::pg_catalog.int4 as aggtransspace,
10589    '0'::pg_catalog.oid as aggmtranstype,
10590    NULL::pg_catalog.int4 as aggmtransspace,
10591    NULL::pg_catalog.text as agginitval,
10592    NULL::pg_catalog.text as aggminitval
10593FROM mz_internal.mz_aggregates a",
10594    access: vec![PUBLIC_SELECT],
10595});
10596
10597pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10598    name: "pg_trigger",
10599    schema: PG_CATALOG_SCHEMA,
10600    oid: oid::VIEW_PG_TRIGGER_OID,
10601    desc: RelationDesc::builder()
10602        .with_column("oid", ScalarType::Oid.nullable(false))
10603        .with_column("tgrelid", ScalarType::Oid.nullable(false))
10604        .with_column("tgparentid", ScalarType::Oid.nullable(false))
10605        .with_column("tgname", ScalarType::String.nullable(false))
10606        .with_column("tgfoid", ScalarType::Oid.nullable(false))
10607        .with_column("tgtype", ScalarType::Int16.nullable(false))
10608        .with_column("tgenabled", ScalarType::PgLegacyChar.nullable(false))
10609        .with_column("tgisinternal", ScalarType::Bool.nullable(false))
10610        .with_column("tgconstrrelid", ScalarType::Oid.nullable(false))
10611        .with_column("tgconstrindid", ScalarType::Oid.nullable(false))
10612        .with_column("tgconstraint", ScalarType::Oid.nullable(false))
10613        .with_column("tgdeferrable", ScalarType::Bool.nullable(false))
10614        .with_column("tginitdeferred", ScalarType::Bool.nullable(false))
10615        .with_column("tgnargs", ScalarType::Int16.nullable(false))
10616        .with_column("tgattr", ScalarType::Int2Vector.nullable(false))
10617        .with_column("tgargs", ScalarType::Bytes.nullable(false))
10618        .with_column("tgqual", ScalarType::String.nullable(false))
10619        .with_column("tgoldtable", ScalarType::String.nullable(false))
10620        .with_column("tgnewtable", ScalarType::String.nullable(false))
10621        .with_key(vec![])
10622        .finish(),
10623    column_comments: BTreeMap::new(),
10624    sql: "SELECT
10625    -- MZ doesn't support triggers so all of these fields are NULL.
10626    NULL::pg_catalog.oid AS oid,
10627    NULL::pg_catalog.oid AS tgrelid,
10628    NULL::pg_catalog.oid AS tgparentid,
10629    NULL::pg_catalog.text AS tgname,
10630    NULL::pg_catalog.oid AS tgfoid,
10631    NULL::pg_catalog.int2 AS tgtype,
10632    NULL::pg_catalog.\"char\" AS tgenabled,
10633    NULL::pg_catalog.bool AS tgisinternal,
10634    NULL::pg_catalog.oid AS tgconstrrelid,
10635    NULL::pg_catalog.oid AS tgconstrindid,
10636    NULL::pg_catalog.oid AS tgconstraint,
10637    NULL::pg_catalog.bool AS tgdeferrable,
10638    NULL::pg_catalog.bool AS tginitdeferred,
10639    NULL::pg_catalog.int2 AS tgnargs,
10640    NULL::pg_catalog.int2vector AS tgattr,
10641    NULL::pg_catalog.bytea AS tgargs,
10642    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
10643    -- uses text as a placeholder, so we'll follow their lead here.
10644    NULL::pg_catalog.text AS tgqual,
10645    NULL::pg_catalog.text AS tgoldtable,
10646    NULL::pg_catalog.text AS tgnewtable
10647WHERE false
10648    ",
10649    access: vec![PUBLIC_SELECT],
10650});
10651
10652pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10653    name: "pg_rewrite",
10654    schema: PG_CATALOG_SCHEMA,
10655    oid: oid::VIEW_PG_REWRITE_OID,
10656    desc: RelationDesc::builder()
10657        .with_column("oid", ScalarType::Oid.nullable(false))
10658        .with_column("rulename", ScalarType::String.nullable(false))
10659        .with_column("ev_class", ScalarType::Oid.nullable(false))
10660        .with_column("ev_type", ScalarType::PgLegacyChar.nullable(false))
10661        .with_column("ev_enabled", ScalarType::PgLegacyChar.nullable(false))
10662        .with_column("is_instead", ScalarType::Bool.nullable(false))
10663        .with_column("ev_qual", ScalarType::String.nullable(false))
10664        .with_column("ev_action", ScalarType::String.nullable(false))
10665        .with_key(vec![])
10666        .finish(),
10667    column_comments: BTreeMap::new(),
10668    sql: "SELECT
10669    -- MZ doesn't support rewrite rules so all of these fields are NULL.
10670    NULL::pg_catalog.oid AS oid,
10671    NULL::pg_catalog.text AS rulename,
10672    NULL::pg_catalog.oid AS ev_class,
10673    NULL::pg_catalog.\"char\" AS ev_type,
10674    NULL::pg_catalog.\"char\" AS ev_enabled,
10675    NULL::pg_catalog.bool AS is_instead,
10676    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
10677    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
10678    NULL::pg_catalog.text AS ev_qual,
10679    NULL::pg_catalog.text AS ev_action
10680WHERE false
10681    ",
10682    access: vec![PUBLIC_SELECT],
10683});
10684
10685pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10686    name: "pg_extension",
10687    schema: PG_CATALOG_SCHEMA,
10688    oid: oid::VIEW_PG_EXTENSION_OID,
10689    desc: RelationDesc::builder()
10690        .with_column("oid", ScalarType::Oid.nullable(false))
10691        .with_column("extname", ScalarType::String.nullable(false))
10692        .with_column("extowner", ScalarType::Oid.nullable(false))
10693        .with_column("extnamespace", ScalarType::Oid.nullable(false))
10694        .with_column("extrelocatable", ScalarType::Bool.nullable(false))
10695        .with_column("extversion", ScalarType::String.nullable(false))
10696        .with_column(
10697            "extconfig",
10698            ScalarType::Array(Box::new(ScalarType::Oid)).nullable(false),
10699        )
10700        .with_column(
10701            "extcondition",
10702            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
10703        )
10704        .with_key(vec![])
10705        .finish(),
10706    column_comments: BTreeMap::new(),
10707    sql: "SELECT
10708    -- MZ doesn't support extensions so all of these fields are NULL.
10709    NULL::pg_catalog.oid AS oid,
10710    NULL::pg_catalog.text AS extname,
10711    NULL::pg_catalog.oid AS extowner,
10712    NULL::pg_catalog.oid AS extnamespace,
10713    NULL::pg_catalog.bool AS extrelocatable,
10714    NULL::pg_catalog.text AS extversion,
10715    NULL::pg_catalog.oid[] AS extconfig,
10716    NULL::pg_catalog.text[] AS extcondition
10717WHERE false
10718    ",
10719    access: vec![PUBLIC_SELECT],
10720});
10721
10722pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10723    name: "mz_show_all_objects",
10724    schema: MZ_INTERNAL_SCHEMA,
10725    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
10726    desc: RelationDesc::builder()
10727        .with_column("schema_id", ScalarType::String.nullable(false))
10728        .with_column("name", ScalarType::String.nullable(false))
10729        .with_column("type", ScalarType::String.nullable(false))
10730        .with_column("comment", ScalarType::String.nullable(false))
10731        .finish(),
10732    column_comments: BTreeMap::new(),
10733    sql: "WITH comments AS (
10734        SELECT id, object_type, comment
10735        FROM mz_internal.mz_comments
10736        WHERE object_sub_id IS NULL
10737    )
10738    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
10739    FROM mz_catalog.mz_objects AS objs
10740    LEFT JOIN comments ON objs.id = comments.id
10741    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
10742    access: vec![PUBLIC_SELECT],
10743});
10744
10745pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
10746    BuiltinView {
10747    name: "mz_show_clusters",
10748    schema: MZ_INTERNAL_SCHEMA,
10749    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
10750    desc: RelationDesc::builder()
10751        .with_column("name", ScalarType::String.nullable(false))
10752        .with_column("replicas", ScalarType::String.nullable(true))
10753        .with_column("comment", ScalarType::String.nullable(false))
10754        .finish(),
10755    column_comments: BTreeMap::new(),
10756    sql: "
10757    WITH clusters AS (
10758        SELECT
10759            mc.id,
10760            mc.name,
10761            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
10762        FROM mz_catalog.mz_clusters mc
10763        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
10764        ON mc.id = mcr.cluster_id
10765        GROUP BY mc.id, mc.name
10766    ),
10767    comments AS (
10768        SELECT id, comment
10769        FROM mz_internal.mz_comments
10770        WHERE object_type = 'cluster' AND object_sub_id IS NULL
10771    )
10772    SELECT name, replicas, COALESCE(comment, '') as comment
10773    FROM clusters
10774    LEFT JOIN comments ON clusters.id = comments.id",
10775    access: vec![PUBLIC_SELECT],
10776}
10777});
10778
10779pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10780    name: "mz_show_secrets",
10781    schema: MZ_INTERNAL_SCHEMA,
10782    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
10783    desc: RelationDesc::builder()
10784        .with_column("schema_id", ScalarType::String.nullable(false))
10785        .with_column("name", ScalarType::String.nullable(false))
10786        .with_column("comment", ScalarType::String.nullable(false))
10787        .finish(),
10788    column_comments: BTreeMap::new(),
10789    sql: "WITH comments AS (
10790        SELECT id, comment
10791        FROM mz_internal.mz_comments
10792        WHERE object_type = 'secret' AND object_sub_id IS NULL
10793    )
10794    SELECT schema_id, name, COALESCE(comment, '') as comment
10795    FROM mz_catalog.mz_secrets secrets
10796    LEFT JOIN comments ON secrets.id = comments.id",
10797    access: vec![PUBLIC_SELECT],
10798});
10799
10800pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10801    name: "mz_show_columns",
10802    schema: MZ_INTERNAL_SCHEMA,
10803    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
10804    desc: RelationDesc::builder()
10805        .with_column("id", ScalarType::String.nullable(false))
10806        .with_column("name", ScalarType::String.nullable(false))
10807        .with_column("nullable", ScalarType::Bool.nullable(false))
10808        .with_column("type", ScalarType::String.nullable(false))
10809        .with_column("position", ScalarType::UInt64.nullable(false))
10810        .with_column("comment", ScalarType::String.nullable(false))
10811        .finish(),
10812    column_comments: BTreeMap::new(),
10813    sql: "
10814    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
10815    FROM mz_catalog.mz_columns columns
10816    LEFT JOIN mz_internal.mz_comments comments
10817    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
10818    access: vec![PUBLIC_SELECT],
10819});
10820
10821pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10822    name: "mz_show_databases",
10823    schema: MZ_INTERNAL_SCHEMA,
10824    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
10825    desc: RelationDesc::builder()
10826        .with_column("name", ScalarType::String.nullable(false))
10827        .with_column("comment", ScalarType::String.nullable(false))
10828        .finish(),
10829    column_comments: BTreeMap::new(),
10830    sql: "WITH comments AS (
10831        SELECT id, comment
10832        FROM mz_internal.mz_comments
10833        WHERE object_type = 'database' AND object_sub_id IS NULL
10834    )
10835    SELECT name, COALESCE(comment, '') as comment
10836    FROM mz_catalog.mz_databases databases
10837    LEFT JOIN comments ON databases.id = comments.id",
10838    access: vec![PUBLIC_SELECT],
10839});
10840
10841pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10842    name: "mz_show_schemas",
10843    schema: MZ_INTERNAL_SCHEMA,
10844    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
10845    desc: RelationDesc::builder()
10846        .with_column("database_id", ScalarType::String.nullable(true))
10847        .with_column("name", ScalarType::String.nullable(false))
10848        .with_column("comment", ScalarType::String.nullable(false))
10849        .finish(),
10850    column_comments: BTreeMap::new(),
10851    sql: "WITH comments AS (
10852        SELECT id, comment
10853        FROM mz_internal.mz_comments
10854        WHERE object_type = 'schema' AND object_sub_id IS NULL
10855    )
10856    SELECT database_id, name, COALESCE(comment, '') as comment
10857    FROM mz_catalog.mz_schemas schemas
10858    LEFT JOIN comments ON schemas.id = comments.id",
10859    access: vec![PUBLIC_SELECT],
10860});
10861
10862pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10863    name: "mz_show_roles",
10864    schema: MZ_INTERNAL_SCHEMA,
10865    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
10866    desc: RelationDesc::builder()
10867        .with_column("name", ScalarType::String.nullable(false))
10868        .with_column("comment", ScalarType::String.nullable(false))
10869        .finish(),
10870    column_comments: BTreeMap::new(),
10871    sql: "WITH comments AS (
10872        SELECT id, comment
10873        FROM mz_internal.mz_comments
10874        WHERE object_type = 'role' AND object_sub_id IS NULL
10875    )
10876    SELECT name, COALESCE(comment, '') as comment
10877    FROM mz_catalog.mz_roles roles
10878    LEFT JOIN comments ON roles.id = comments.id
10879    WHERE roles.id NOT LIKE 's%'
10880      AND roles.id NOT LIKE 'g%'",
10881    access: vec![PUBLIC_SELECT],
10882});
10883
10884pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10885    name: "mz_show_tables",
10886    schema: MZ_INTERNAL_SCHEMA,
10887    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
10888    desc: RelationDesc::builder()
10889        .with_column("schema_id", ScalarType::String.nullable(false))
10890        .with_column("name", ScalarType::String.nullable(false))
10891        .with_column("comment", ScalarType::String.nullable(false))
10892        .with_column("source_id", ScalarType::String.nullable(true))
10893        .finish(),
10894    column_comments: BTreeMap::new(),
10895    sql: "WITH comments AS (
10896        SELECT id, comment
10897        FROM mz_internal.mz_comments
10898        WHERE object_type = 'table' AND object_sub_id IS NULL
10899    )
10900    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
10901    FROM mz_catalog.mz_tables tables
10902    LEFT JOIN comments ON tables.id = comments.id",
10903    access: vec![PUBLIC_SELECT],
10904});
10905
10906pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10907    name: "mz_show_views",
10908    schema: MZ_INTERNAL_SCHEMA,
10909    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
10910    desc: RelationDesc::builder()
10911        .with_column("schema_id", ScalarType::String.nullable(false))
10912        .with_column("name", ScalarType::String.nullable(false))
10913        .with_column("comment", ScalarType::String.nullable(false))
10914        .finish(),
10915    column_comments: BTreeMap::new(),
10916    sql: "WITH comments AS (
10917        SELECT id, comment
10918        FROM mz_internal.mz_comments
10919        WHERE object_type = 'view' AND object_sub_id IS NULL
10920    )
10921    SELECT schema_id, name, COALESCE(comment, '') as comment
10922    FROM mz_catalog.mz_views views
10923    LEFT JOIN comments ON views.id = comments.id",
10924    access: vec![PUBLIC_SELECT],
10925});
10926
10927pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10928    name: "mz_show_types",
10929    schema: MZ_INTERNAL_SCHEMA,
10930    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
10931    desc: RelationDesc::builder()
10932        .with_column("schema_id", ScalarType::String.nullable(false))
10933        .with_column("name", ScalarType::String.nullable(false))
10934        .with_column("comment", ScalarType::String.nullable(false))
10935        .finish(),
10936    column_comments: BTreeMap::new(),
10937    sql: "WITH comments AS (
10938        SELECT id, comment
10939        FROM mz_internal.mz_comments
10940        WHERE object_type = 'type' AND object_sub_id IS NULL
10941    )
10942    SELECT schema_id, name, COALESCE(comment, '') as comment
10943    FROM mz_catalog.mz_types types
10944    LEFT JOIN comments ON types.id = comments.id",
10945    access: vec![PUBLIC_SELECT],
10946});
10947
10948pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10949    name: "mz_show_connections",
10950    schema: MZ_INTERNAL_SCHEMA,
10951    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
10952    desc: RelationDesc::builder()
10953        .with_column("schema_id", ScalarType::String.nullable(false))
10954        .with_column("name", ScalarType::String.nullable(false))
10955        .with_column("type", ScalarType::String.nullable(false))
10956        .with_column("comment", ScalarType::String.nullable(false))
10957        .finish(),
10958    column_comments: BTreeMap::new(),
10959    sql: "WITH comments AS (
10960        SELECT id, comment
10961        FROM mz_internal.mz_comments
10962        WHERE object_type = 'connection' AND object_sub_id IS NULL
10963    )
10964    SELECT schema_id, name, type, COALESCE(comment, '') as comment
10965    FROM mz_catalog.mz_connections connections
10966    LEFT JOIN comments ON connections.id = comments.id",
10967    access: vec![PUBLIC_SELECT],
10968});
10969
10970pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10971    name: "mz_show_sources",
10972    schema: MZ_INTERNAL_SCHEMA,
10973    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
10974    desc: RelationDesc::builder()
10975        .with_column("id", ScalarType::String.nullable(false))
10976        .with_column("name", ScalarType::String.nullable(false))
10977        .with_column("type", ScalarType::String.nullable(false))
10978        .with_column("cluster", ScalarType::String.nullable(true))
10979        .with_column("schema_id", ScalarType::String.nullable(false))
10980        .with_column("cluster_id", ScalarType::String.nullable(true))
10981        .with_column("comment", ScalarType::String.nullable(false))
10982        .finish(),
10983    column_comments: BTreeMap::new(),
10984    sql: "
10985WITH comments AS (
10986    SELECT id, comment
10987    FROM mz_internal.mz_comments
10988    WHERE object_type = 'source' AND object_sub_id IS NULL
10989)
10990SELECT
10991    sources.id,
10992    sources.name,
10993    sources.type,
10994    clusters.name AS cluster,
10995    schema_id,
10996    cluster_id,
10997    COALESCE(comments.comment, '') as comment
10998FROM
10999    mz_catalog.mz_sources AS sources
11000        LEFT JOIN
11001            mz_catalog.mz_clusters AS clusters
11002            ON clusters.id = sources.cluster_id
11003        LEFT JOIN comments ON sources.id = comments.id",
11004    access: vec![PUBLIC_SELECT],
11005});
11006
11007pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11008    name: "mz_show_sinks",
11009    schema: MZ_INTERNAL_SCHEMA,
11010    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11011    desc: RelationDesc::builder()
11012        .with_column("id", ScalarType::String.nullable(false))
11013        .with_column("name", ScalarType::String.nullable(false))
11014        .with_column("type", ScalarType::String.nullable(false))
11015        .with_column("cluster", ScalarType::String.nullable(false))
11016        .with_column("schema_id", ScalarType::String.nullable(false))
11017        .with_column("cluster_id", ScalarType::String.nullable(false))
11018        .with_column("comment", ScalarType::String.nullable(false))
11019        .finish(),
11020    column_comments: BTreeMap::new(),
11021    sql: "
11022WITH comments AS (
11023    SELECT id, comment
11024    FROM mz_internal.mz_comments
11025    WHERE object_type = 'sink' AND object_sub_id IS NULL
11026)
11027SELECT
11028    sinks.id,
11029    sinks.name,
11030    sinks.type,
11031    clusters.name AS cluster,
11032    schema_id,
11033    cluster_id,
11034    COALESCE(comments.comment, '') as comment
11035FROM
11036    mz_catalog.mz_sinks AS sinks
11037    JOIN
11038        mz_catalog.mz_clusters AS clusters
11039        ON clusters.id = sinks.cluster_id
11040    LEFT JOIN comments ON sinks.id = comments.id",
11041    access: vec![PUBLIC_SELECT],
11042});
11043
11044pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11045    name: "mz_show_materialized_views",
11046    schema: MZ_INTERNAL_SCHEMA,
11047    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11048    desc: RelationDesc::builder()
11049        .with_column("id", ScalarType::String.nullable(false))
11050        .with_column("name", ScalarType::String.nullable(false))
11051        .with_column("cluster", ScalarType::String.nullable(false))
11052        .with_column("schema_id", ScalarType::String.nullable(false))
11053        .with_column("cluster_id", ScalarType::String.nullable(false))
11054        .with_column("comment", ScalarType::String.nullable(false))
11055        .finish(),
11056    column_comments: BTreeMap::new(),
11057    sql: "
11058WITH comments AS (
11059    SELECT id, comment
11060    FROM mz_internal.mz_comments
11061    WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11062)
11063SELECT
11064    mviews.id as id,
11065    mviews.name,
11066    clusters.name AS cluster,
11067    schema_id,
11068    cluster_id,
11069    COALESCE(comments.comment, '') as comment
11070FROM
11071    mz_catalog.mz_materialized_views AS mviews
11072    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11073    LEFT JOIN comments ON mviews.id = comments.id",
11074    access: vec![PUBLIC_SELECT],
11075});
11076
11077pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11078    name: "mz_show_indexes",
11079    schema: MZ_INTERNAL_SCHEMA,
11080    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11081    desc: RelationDesc::builder()
11082        .with_column("id", ScalarType::String.nullable(false))
11083        .with_column("name", ScalarType::String.nullable(false))
11084        .with_column("on", ScalarType::String.nullable(false))
11085        .with_column("cluster", ScalarType::String.nullable(false))
11086        .with_column(
11087            "key",
11088            ScalarType::Array(Box::new(ScalarType::String)).nullable(false),
11089        )
11090        .with_column("on_id", ScalarType::String.nullable(false))
11091        .with_column("schema_id", ScalarType::String.nullable(false))
11092        .with_column("cluster_id", ScalarType::String.nullable(false))
11093        .with_column("comment", ScalarType::String.nullable(false))
11094        .finish(),
11095    column_comments: BTreeMap::new(),
11096    sql: "
11097WITH comments AS (
11098    SELECT id, comment
11099    FROM mz_internal.mz_comments
11100    WHERE object_type = 'index' AND object_sub_id IS NULL
11101)
11102SELECT
11103    idxs.id AS id,
11104    idxs.name AS name,
11105    objs.name AS on,
11106    clusters.name AS cluster,
11107    COALESCE(keys.key, '{}'::_text) AS key,
11108    idxs.on_id AS on_id,
11109    objs.schema_id AS schema_id,
11110    clusters.id AS cluster_id,
11111    COALESCE(comments.comment, '') as comment
11112FROM
11113    mz_catalog.mz_indexes AS idxs
11114    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11115    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11116    LEFT JOIN
11117        (SELECT
11118            idxs.id,
11119            ARRAY_AGG(
11120                CASE
11121                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11122                    ELSE idx_cols.on_expression
11123                END
11124                ORDER BY idx_cols.index_position ASC
11125            ) AS key
11126        FROM
11127            mz_catalog.mz_indexes AS idxs
11128            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11129            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11130                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11131        GROUP BY idxs.id) AS keys
11132    ON idxs.id = keys.id
11133    LEFT JOIN comments ON idxs.id = comments.id",
11134    access: vec![PUBLIC_SELECT],
11135});
11136
11137pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11138    name: "mz_show_cluster_replicas",
11139    schema: MZ_INTERNAL_SCHEMA,
11140    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11141    desc: RelationDesc::builder()
11142        .with_column("cluster", ScalarType::String.nullable(false))
11143        .with_column("replica", ScalarType::String.nullable(false))
11144        .with_column("replica_id", ScalarType::String.nullable(false))
11145        .with_column("size", ScalarType::String.nullable(true))
11146        .with_column("ready", ScalarType::Bool.nullable(false))
11147        .with_column("comment", ScalarType::String.nullable(false))
11148        .finish(),
11149    column_comments: BTreeMap::new(),
11150    sql: r#"SELECT
11151    mz_catalog.mz_clusters.name AS cluster,
11152    mz_catalog.mz_cluster_replicas.name AS replica,
11153    mz_catalog.mz_cluster_replicas.id as replica_id,
11154    mz_catalog.mz_cluster_replicas.size AS size,
11155    coalesce(statuses.ready, FALSE) AS ready,
11156    coalesce(comments.comment, '') as comment
11157FROM
11158    mz_catalog.mz_cluster_replicas
11159        JOIN mz_catalog.mz_clusters
11160            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11161        LEFT JOIN
11162            (
11163                SELECT
11164                    replica_id,
11165                    bool_and(hydrated) AS ready
11166                FROM mz_internal.mz_hydration_statuses
11167                WHERE replica_id is not null
11168                GROUP BY replica_id
11169            ) AS statuses
11170            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11171        LEFT JOIN mz_internal.mz_comments comments
11172            ON mz_catalog.mz_cluster_replicas.id = comments.id
11173WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11174ORDER BY 1, 2"#,
11175    access: vec![PUBLIC_SELECT],
11176});
11177
11178pub static MZ_SHOW_CONTINUAL_TASKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11179    name: "mz_show_continual_tasks",
11180    schema: MZ_INTERNAL_SCHEMA,
11181    oid: oid::VIEW_MZ_SHOW_CONTINUAL_TASKS_OID,
11182    desc: RelationDesc::builder()
11183        .with_column("id", ScalarType::String.nullable(false))
11184        .with_column("name", ScalarType::String.nullable(false))
11185        .with_column("cluster", ScalarType::String.nullable(false))
11186        .with_column("schema_id", ScalarType::String.nullable(false))
11187        .with_column("cluster_id", ScalarType::String.nullable(false))
11188        .with_column("comment", ScalarType::String.nullable(false))
11189        .finish(),
11190    column_comments: BTreeMap::new(),
11191    sql: "
11192WITH comments AS (
11193    SELECT id, comment
11194    FROM mz_internal.mz_comments
11195    WHERE object_type = 'continual-task' AND object_sub_id IS NULL
11196)
11197SELECT
11198    cts.id as id,
11199    cts.name,
11200    clusters.name AS cluster,
11201    schema_id,
11202    cluster_id,
11203    COALESCE(comments.comment, '') as comment
11204FROM
11205    mz_internal.mz_continual_tasks AS cts
11206    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = cts.cluster_id
11207    LEFT JOIN comments ON cts.id = comments.id",
11208    access: vec![PUBLIC_SELECT],
11209});
11210
11211pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11212    name: "mz_show_role_members",
11213    schema: MZ_INTERNAL_SCHEMA,
11214    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11215    desc: RelationDesc::builder()
11216        .with_column("role", ScalarType::String.nullable(false))
11217        .with_column("member", ScalarType::String.nullable(false))
11218        .with_column("grantor", ScalarType::String.nullable(false))
11219        .finish(),
11220    column_comments: BTreeMap::from_iter([
11221        ("role", "The role that `member` is a member of."),
11222        ("member", "The role that is a member of `role`."),
11223        (
11224            "grantor",
11225            "The role that granted membership of `member` to `role`.",
11226        ),
11227    ]),
11228    sql: r#"SELECT
11229    r1.name AS role,
11230    r2.name AS member,
11231    r3.name AS grantor
11232FROM mz_catalog.mz_role_members rm
11233JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11234JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11235JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11236ORDER BY role"#,
11237    access: vec![PUBLIC_SELECT],
11238});
11239
11240pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11241    name: "mz_show_my_role_members",
11242    schema: MZ_INTERNAL_SCHEMA,
11243    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11244    desc: RelationDesc::builder()
11245        .with_column("role", ScalarType::String.nullable(false))
11246        .with_column("member", ScalarType::String.nullable(false))
11247        .with_column("grantor", ScalarType::String.nullable(false))
11248        .finish(),
11249    column_comments: BTreeMap::from_iter([
11250        ("role", "The role that `member` is a member of."),
11251        ("member", "The role that is a member of `role`."),
11252        (
11253            "grantor",
11254            "The role that granted membership of `member` to `role`.",
11255        ),
11256    ]),
11257    sql: r#"SELECT role, member, grantor
11258FROM mz_internal.mz_show_role_members
11259WHERE pg_has_role(member, 'USAGE')"#,
11260    access: vec![PUBLIC_SELECT],
11261});
11262
11263pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11264    name: "mz_show_system_privileges",
11265    schema: MZ_INTERNAL_SCHEMA,
11266    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11267    desc: RelationDesc::builder()
11268        .with_column("grantor", ScalarType::String.nullable(true))
11269        .with_column("grantee", ScalarType::String.nullable(true))
11270        .with_column("privilege_type", ScalarType::String.nullable(false))
11271        .finish(),
11272    column_comments: BTreeMap::from_iter([
11273        ("grantor", "The role that granted the privilege."),
11274        ("grantee", "The role that the privilege was granted to."),
11275        ("privilege_type", "They type of privilege granted."),
11276    ]),
11277    sql: r#"SELECT
11278    grantor.name AS grantor,
11279    CASE privileges.grantee
11280        WHEN 'p' THEN 'PUBLIC'
11281        ELSE grantee.name
11282    END AS grantee,
11283    privileges.privilege_type AS privilege_type
11284FROM
11285    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11286    FROM mz_catalog.mz_system_privileges) AS privileges
11287LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11288LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11289WHERE privileges.grantee NOT LIKE 's%'"#,
11290    access: vec![PUBLIC_SELECT],
11291});
11292
11293pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11294    name: "mz_show_my_system_privileges",
11295    schema: MZ_INTERNAL_SCHEMA,
11296    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11297    desc: RelationDesc::builder()
11298        .with_column("grantor", ScalarType::String.nullable(true))
11299        .with_column("grantee", ScalarType::String.nullable(true))
11300        .with_column("privilege_type", ScalarType::String.nullable(false))
11301        .finish(),
11302    column_comments: BTreeMap::from_iter([
11303        ("grantor", "The role that granted the privilege."),
11304        ("grantee", "The role that the privilege was granted to."),
11305        ("privilege_type", "They type of privilege granted."),
11306    ]),
11307    sql: r#"SELECT grantor, grantee, privilege_type
11308FROM mz_internal.mz_show_system_privileges
11309WHERE
11310    CASE
11311        WHEN grantee = 'PUBLIC' THEN true
11312        ELSE pg_has_role(grantee, 'USAGE')
11313    END"#,
11314    access: vec![PUBLIC_SELECT],
11315});
11316
11317pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11318    name: "mz_show_cluster_privileges",
11319    schema: MZ_INTERNAL_SCHEMA,
11320    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11321    desc: RelationDesc::builder()
11322        .with_column("grantor", ScalarType::String.nullable(true))
11323        .with_column("grantee", ScalarType::String.nullable(true))
11324        .with_column("name", ScalarType::String.nullable(false))
11325        .with_column("privilege_type", ScalarType::String.nullable(false))
11326        .finish(),
11327    column_comments: BTreeMap::from_iter([
11328        ("grantor", "The role that granted the privilege."),
11329        ("grantee", "The role that the privilege was granted to."),
11330        ("name", "The name of the cluster."),
11331        ("privilege_type", "They type of privilege granted."),
11332    ]),
11333    sql: r#"SELECT
11334    grantor.name AS grantor,
11335    CASE privileges.grantee
11336        WHEN 'p' THEN 'PUBLIC'
11337        ELSE grantee.name
11338    END AS grantee,
11339    privileges.name AS name,
11340    privileges.privilege_type AS privilege_type
11341FROM
11342    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11343    FROM mz_catalog.mz_clusters
11344    WHERE id NOT LIKE 's%') AS privileges
11345LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11346LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11347WHERE privileges.grantee NOT LIKE 's%'"#,
11348    access: vec![PUBLIC_SELECT],
11349});
11350
11351pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11352    name: "mz_show_my_cluster_privileges",
11353    schema: MZ_INTERNAL_SCHEMA,
11354    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11355    desc: RelationDesc::builder()
11356        .with_column("grantor", ScalarType::String.nullable(true))
11357        .with_column("grantee", ScalarType::String.nullable(true))
11358        .with_column("name", ScalarType::String.nullable(false))
11359        .with_column("privilege_type", ScalarType::String.nullable(false))
11360        .finish(),
11361    column_comments: BTreeMap::from_iter([
11362        ("grantor", "The role that granted the privilege."),
11363        ("grantee", "The role that the privilege was granted to."),
11364        ("name", "The name of the cluster."),
11365        ("privilege_type", "They type of privilege granted."),
11366    ]),
11367    sql: r#"SELECT grantor, grantee, name, privilege_type
11368FROM mz_internal.mz_show_cluster_privileges
11369WHERE
11370    CASE
11371        WHEN grantee = 'PUBLIC' THEN true
11372        ELSE pg_has_role(grantee, 'USAGE')
11373    END"#,
11374    access: vec![PUBLIC_SELECT],
11375});
11376
11377pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11378    name: "mz_show_database_privileges",
11379    schema: MZ_INTERNAL_SCHEMA,
11380    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
11381    desc: RelationDesc::builder()
11382        .with_column("grantor", ScalarType::String.nullable(true))
11383        .with_column("grantee", ScalarType::String.nullable(true))
11384        .with_column("name", ScalarType::String.nullable(false))
11385        .with_column("privilege_type", ScalarType::String.nullable(false))
11386        .finish(),
11387    column_comments: BTreeMap::from_iter([
11388        ("grantor", "The role that granted the privilege."),
11389        ("grantee", "The role that the privilege was granted to."),
11390        ("name", "The name of the database."),
11391        ("privilege_type", "They type of privilege granted."),
11392    ]),
11393    sql: r#"SELECT
11394    grantor.name AS grantor,
11395    CASE privileges.grantee
11396        WHEN 'p' THEN 'PUBLIC'
11397        ELSE grantee.name
11398    END AS grantee,
11399    privileges.name AS name,
11400    privileges.privilege_type AS privilege_type
11401FROM
11402    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11403    FROM mz_catalog.mz_databases
11404    WHERE id NOT LIKE 's%') AS privileges
11405LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11406LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11407WHERE privileges.grantee NOT LIKE 's%'"#,
11408    access: vec![PUBLIC_SELECT],
11409});
11410
11411pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11412    name: "mz_show_my_database_privileges",
11413    schema: MZ_INTERNAL_SCHEMA,
11414    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
11415    desc: RelationDesc::builder()
11416        .with_column("grantor", ScalarType::String.nullable(true))
11417        .with_column("grantee", ScalarType::String.nullable(true))
11418        .with_column("name", ScalarType::String.nullable(false))
11419        .with_column("privilege_type", ScalarType::String.nullable(false))
11420        .finish(),
11421    column_comments: BTreeMap::from_iter([
11422        ("grantor", "The role that granted the privilege."),
11423        ("grantee", "The role that the privilege was granted to."),
11424        ("name", "The name of the cluster."),
11425        ("privilege_type", "They type of privilege granted."),
11426    ]),
11427    sql: r#"SELECT grantor, grantee, name, privilege_type
11428FROM mz_internal.mz_show_database_privileges
11429WHERE
11430    CASE
11431        WHEN grantee = 'PUBLIC' THEN true
11432        ELSE pg_has_role(grantee, 'USAGE')
11433    END"#,
11434    access: vec![PUBLIC_SELECT],
11435});
11436
11437pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11438    name: "mz_show_schema_privileges",
11439    schema: MZ_INTERNAL_SCHEMA,
11440    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
11441    desc: RelationDesc::builder()
11442        .with_column("grantor", ScalarType::String.nullable(true))
11443        .with_column("grantee", ScalarType::String.nullable(true))
11444        .with_column("database", ScalarType::String.nullable(true))
11445        .with_column("name", ScalarType::String.nullable(false))
11446        .with_column("privilege_type", ScalarType::String.nullable(false))
11447        .finish(),
11448    column_comments: BTreeMap::from_iter([
11449        ("grantor", "The role that granted the privilege."),
11450        ("grantee", "The role that the privilege was granted to."),
11451        (
11452            "database",
11453            "The name of the database containing the schema.",
11454        ),
11455        ("name", "The name of the schema."),
11456        ("privilege_type", "They type of privilege granted."),
11457    ]),
11458    sql: r#"SELECT
11459    grantor.name AS grantor,
11460    CASE privileges.grantee
11461        WHEN 'p' THEN 'PUBLIC'
11462        ELSE grantee.name
11463    END AS grantee,
11464    databases.name AS database,
11465    privileges.name AS name,
11466    privileges.privilege_type AS privilege_type
11467FROM
11468    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
11469    FROM mz_catalog.mz_schemas
11470    WHERE id NOT LIKE 's%') AS privileges
11471LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11472LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11473LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
11474WHERE privileges.grantee NOT LIKE 's%'"#,
11475    access: vec![PUBLIC_SELECT],
11476});
11477
11478pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11479    name: "mz_show_my_schema_privileges",
11480    schema: MZ_INTERNAL_SCHEMA,
11481    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
11482    desc: RelationDesc::builder()
11483        .with_column("grantor", ScalarType::String.nullable(true))
11484        .with_column("grantee", ScalarType::String.nullable(true))
11485        .with_column("database", ScalarType::String.nullable(true))
11486        .with_column("name", ScalarType::String.nullable(false))
11487        .with_column("privilege_type", ScalarType::String.nullable(false))
11488        .finish(),
11489    column_comments: BTreeMap::from_iter([
11490        ("grantor", "The role that granted the privilege."),
11491        ("grantee", "The role that the privilege was granted to."),
11492        (
11493            "database",
11494            "The name of the database containing the schema.",
11495        ),
11496        ("name", "The name of the schema."),
11497        ("privilege_type", "They type of privilege granted."),
11498    ]),
11499    sql: r#"SELECT grantor, grantee, database, name, privilege_type
11500FROM mz_internal.mz_show_schema_privileges
11501WHERE
11502    CASE
11503        WHEN grantee = 'PUBLIC' THEN true
11504        ELSE pg_has_role(grantee, 'USAGE')
11505    END"#,
11506    access: vec![PUBLIC_SELECT],
11507});
11508
11509pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11510    name: "mz_show_object_privileges",
11511    schema: MZ_INTERNAL_SCHEMA,
11512    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
11513    desc: RelationDesc::builder()
11514        .with_column("grantor", ScalarType::String.nullable(true))
11515        .with_column("grantee", ScalarType::String.nullable(true))
11516        .with_column("database", ScalarType::String.nullable(true))
11517        .with_column("schema", ScalarType::String.nullable(true))
11518        .with_column("name", ScalarType::String.nullable(false))
11519        .with_column("object_type", ScalarType::String.nullable(false))
11520        .with_column("privilege_type", ScalarType::String.nullable(false))
11521        .finish(),
11522    column_comments: BTreeMap::from_iter([
11523        ("grantor", "The role that granted the privilege."),
11524        ("grantee", "The role that the privilege was granted to."),
11525        (
11526            "database",
11527            "The name of the database containing the object.",
11528        ),
11529        ("schema", "The name of the schema containing the object."),
11530        ("name", "The name of the object."),
11531        (
11532            "object_type",
11533            "The type of object the privilege is granted on.",
11534        ),
11535        ("privilege_type", "They type of privilege granted."),
11536    ]),
11537    sql: r#"SELECT
11538    grantor.name AS grantor,
11539    CASE privileges.grantee
11540            WHEN 'p' THEN 'PUBLIC'
11541            ELSE grantee.name
11542        END AS grantee,
11543    databases.name AS database,
11544    schemas.name AS schema,
11545    privileges.name AS name,
11546    privileges.type AS object_type,
11547    privileges.privilege_type AS privilege_type
11548FROM
11549    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
11550    FROM mz_catalog.mz_objects
11551    WHERE id NOT LIKE 's%') AS privileges
11552LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11553LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11554LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
11555LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
11556WHERE privileges.grantee NOT LIKE 's%'"#,
11557    access: vec![PUBLIC_SELECT],
11558});
11559
11560pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11561    name: "mz_show_my_object_privileges",
11562    schema: MZ_INTERNAL_SCHEMA,
11563    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
11564    desc: RelationDesc::builder()
11565        .with_column("grantor", ScalarType::String.nullable(true))
11566        .with_column("grantee", ScalarType::String.nullable(true))
11567        .with_column("database", ScalarType::String.nullable(true))
11568        .with_column("schema", ScalarType::String.nullable(true))
11569        .with_column("name", ScalarType::String.nullable(false))
11570        .with_column("object_type", ScalarType::String.nullable(false))
11571        .with_column("privilege_type", ScalarType::String.nullable(false))
11572        .finish(),
11573    column_comments: BTreeMap::from_iter([
11574        ("grantor", "The role that granted the privilege."),
11575        ("grantee", "The role that the privilege was granted to."),
11576        (
11577            "database",
11578            "The name of the database containing the object.",
11579        ),
11580        ("schema", "The name of the schema containing the object."),
11581        ("name", "The name of the object."),
11582        (
11583            "object_type",
11584            "The type of object the privilege is granted on.",
11585        ),
11586        ("privilege_type", "They type of privilege granted."),
11587    ]),
11588    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11589FROM mz_internal.mz_show_object_privileges
11590WHERE
11591    CASE
11592        WHEN grantee = 'PUBLIC' THEN true
11593        ELSE pg_has_role(grantee, 'USAGE')
11594    END"#,
11595    access: vec![PUBLIC_SELECT],
11596});
11597
11598pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11599    name: "mz_show_all_privileges",
11600    schema: MZ_INTERNAL_SCHEMA,
11601    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
11602    desc: RelationDesc::builder()
11603        .with_column("grantor", ScalarType::String.nullable(true))
11604        .with_column("grantee", ScalarType::String.nullable(true))
11605        .with_column("database", ScalarType::String.nullable(true))
11606        .with_column("schema", ScalarType::String.nullable(true))
11607        .with_column("name", ScalarType::String.nullable(true))
11608        .with_column("object_type", ScalarType::String.nullable(false))
11609        .with_column("privilege_type", ScalarType::String.nullable(false))
11610        .finish(),
11611    column_comments: BTreeMap::from_iter([
11612        ("grantor", "The role that granted the privilege."),
11613        ("grantee", "The role that the privilege was granted to."),
11614        (
11615            "database",
11616            "The name of the database containing the object.",
11617        ),
11618        ("schema", "The name of the schema containing the object."),
11619        ("name", "The name of the privilege target."),
11620        (
11621            "object_type",
11622            "The type of object the privilege is granted on.",
11623        ),
11624        ("privilege_type", "They type of privilege granted."),
11625    ]),
11626    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
11627FROM mz_internal.mz_show_system_privileges
11628UNION ALL
11629SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
11630FROM mz_internal.mz_show_cluster_privileges
11631UNION ALL
11632SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
11633FROM mz_internal.mz_show_database_privileges
11634UNION ALL
11635SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
11636FROM mz_internal.mz_show_schema_privileges
11637UNION ALL
11638SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11639FROM mz_internal.mz_show_object_privileges"#,
11640    access: vec![PUBLIC_SELECT],
11641});
11642
11643pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11644    name: "mz_show_all_my_privileges",
11645    schema: MZ_INTERNAL_SCHEMA,
11646    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
11647    desc: RelationDesc::builder()
11648        .with_column("grantor", ScalarType::String.nullable(true))
11649        .with_column("grantee", ScalarType::String.nullable(true))
11650        .with_column("database", ScalarType::String.nullable(true))
11651        .with_column("schema", ScalarType::String.nullable(true))
11652        .with_column("name", ScalarType::String.nullable(true))
11653        .with_column("object_type", ScalarType::String.nullable(false))
11654        .with_column("privilege_type", ScalarType::String.nullable(false))
11655        .finish(),
11656    column_comments: BTreeMap::from_iter([
11657        ("grantor", "The role that granted the privilege."),
11658        ("grantee", "The role that the privilege was granted to."),
11659        (
11660            "database",
11661            "The name of the database containing the object.",
11662        ),
11663        ("schema", "The name of the schema containing the object."),
11664        ("name", "The name of the privilege target."),
11665        (
11666            "object_type",
11667            "The type of object the privilege is granted on.",
11668        ),
11669        ("privilege_type", "They type of privilege granted."),
11670    ]),
11671    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11672FROM mz_internal.mz_show_all_privileges
11673WHERE
11674    CASE
11675        WHEN grantee = 'PUBLIC' THEN true
11676        ELSE pg_has_role(grantee, 'USAGE')
11677    END"#,
11678    access: vec![PUBLIC_SELECT],
11679});
11680
11681pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11682    name: "mz_show_default_privileges",
11683    schema: MZ_INTERNAL_SCHEMA,
11684    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
11685    desc: RelationDesc::builder()
11686        .with_column("object_owner", ScalarType::String.nullable(true))
11687        .with_column("database", ScalarType::String.nullable(true))
11688        .with_column("schema", ScalarType::String.nullable(true))
11689        .with_column("object_type", ScalarType::String.nullable(false))
11690        .with_column("grantee", ScalarType::String.nullable(true))
11691        .with_column("privilege_type", ScalarType::String.nullable(true))
11692        .finish(),
11693    column_comments: BTreeMap::from_iter([
11694        (
11695            "object_owner",
11696            "Privileges described in this row will be granted on objects created by `object_owner`.",
11697        ),
11698        (
11699            "database",
11700            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11701        ),
11702        (
11703            "schema",
11704            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11705        ),
11706        (
11707            "object_type",
11708            "Privileges described in this row will be granted only on objects of type `object_type`.",
11709        ),
11710        (
11711            "grantee",
11712            "Privileges described in this row will be granted to `grantee`.",
11713        ),
11714        ("privilege_type", "They type of privilege to be granted."),
11715    ]),
11716    sql: r#"SELECT
11717    CASE defaults.role_id
11718        WHEN 'p' THEN 'PUBLIC'
11719        ELSE object_owner.name
11720    END AS object_owner,
11721    databases.name AS database,
11722    schemas.name AS schema,
11723    object_type,
11724    CASE defaults.grantee
11725        WHEN 'p' THEN 'PUBLIC'
11726        ELSE grantee.name
11727    END AS grantee,
11728    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
11729FROM mz_catalog.mz_default_privileges defaults
11730LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
11731LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
11732LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
11733LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
11734WHERE defaults.grantee NOT LIKE 's%'
11735    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
11736    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
11737    access: vec![PUBLIC_SELECT],
11738});
11739
11740pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11741    name: "mz_show_my_default_privileges",
11742    schema: MZ_INTERNAL_SCHEMA,
11743    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
11744    desc: RelationDesc::builder()
11745        .with_column("object_owner", ScalarType::String.nullable(true))
11746        .with_column("database", ScalarType::String.nullable(true))
11747        .with_column("schema", ScalarType::String.nullable(true))
11748        .with_column("object_type", ScalarType::String.nullable(false))
11749        .with_column("grantee", ScalarType::String.nullable(true))
11750        .with_column("privilege_type", ScalarType::String.nullable(true))
11751        .finish(),
11752    column_comments: BTreeMap::from_iter([
11753        (
11754            "object_owner",
11755            "Privileges described in this row will be granted on objects created by `object_owner`.",
11756        ),
11757        (
11758            "database",
11759            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11760        ),
11761        (
11762            "schema",
11763            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11764        ),
11765        (
11766            "object_type",
11767            "Privileges described in this row will be granted only on objects of type `object_type`.",
11768        ),
11769        (
11770            "grantee",
11771            "Privileges described in this row will be granted to `grantee`.",
11772        ),
11773        ("privilege_type", "They type of privilege to be granted."),
11774    ]),
11775    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
11776FROM mz_internal.mz_show_default_privileges
11777WHERE
11778    CASE
11779        WHEN grantee = 'PUBLIC' THEN true
11780        ELSE pg_has_role(grantee, 'USAGE')
11781    END"#,
11782    access: vec![PUBLIC_SELECT],
11783});
11784
11785pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11786    name: "mz_show_network_policies",
11787    schema: MZ_INTERNAL_SCHEMA,
11788    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
11789    desc: RelationDesc::builder()
11790        .with_column("name", ScalarType::String.nullable(false))
11791        .with_column("rules", ScalarType::String.nullable(true))
11792        .with_column("comment", ScalarType::String.nullable(false))
11793        .finish(),
11794    column_comments: BTreeMap::new(),
11795    sql: "
11796WITH comments AS (
11797    SELECT id, comment
11798    FROM mz_internal.mz_comments
11799    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
11800)
11801SELECT
11802    policy.name,
11803    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
11804    COALESCE(comment, '') as comment
11805FROM
11806    mz_internal.mz_network_policies as policy
11807LEFT JOIN
11808    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
11809LEFT JOIN
11810    comments ON policy.id = comments.id
11811WHERE
11812    policy.id NOT LIKE 's%'
11813AND
11814    policy.id NOT LIKE 'g%'
11815GROUP BY policy.name, comments.comment;",
11816    access: vec![PUBLIC_SELECT],
11817});
11818
11819pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11820    name: "mz_cluster_replica_history",
11821    schema: MZ_INTERNAL_SCHEMA,
11822    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
11823    desc: RelationDesc::builder()
11824        .with_column("replica_id", ScalarType::String.nullable(true))
11825        .with_column("size", ScalarType::String.nullable(true))
11826        .with_column("cluster_id", ScalarType::String.nullable(true))
11827        .with_column("cluster_name", ScalarType::String.nullable(true))
11828        .with_column("replica_name", ScalarType::String.nullable(true))
11829        .with_column(
11830            "created_at",
11831            ScalarType::TimestampTz { precision: None }.nullable(false),
11832        )
11833        .with_column(
11834            "dropped_at",
11835            ScalarType::TimestampTz { precision: None }.nullable(true),
11836        )
11837        .with_column(
11838            "credits_per_hour",
11839            ScalarType::Numeric { max_scale: None }.nullable(true),
11840        )
11841        .finish(),
11842    column_comments: BTreeMap::from_iter([
11843        ("replica_id", "The ID of a cluster replica."),
11844        (
11845            "size",
11846            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
11847        ),
11848        (
11849            "cluster_id",
11850            "The ID of the cluster associated with the replica.",
11851        ),
11852        (
11853            "cluster_name",
11854            "The name of the cluster associated with the replica.",
11855        ),
11856        ("replica_name", "The name of the replica."),
11857        ("created_at", "The time at which the replica was created."),
11858        (
11859            "dropped_at",
11860            "The time at which the replica was dropped, or `NULL` if it still exists.",
11861        ),
11862        (
11863            "credits_per_hour",
11864            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
11865        ),
11866    ]),
11867    sql: r#"
11868        WITH
11869            creates AS
11870            (
11871                SELECT
11872                    details ->> 'logical_size' AS size,
11873                    details ->> 'replica_id' AS replica_id,
11874                    details ->> 'replica_name' AS replica_name,
11875                    details ->> 'cluster_name' AS cluster_name,
11876                    details ->> 'cluster_id' AS cluster_id,
11877                    occurred_at
11878                FROM mz_catalog.mz_audit_events
11879                WHERE
11880                    object_type = 'cluster-replica' AND event_type = 'create'
11881                        AND
11882                    details ->> 'replica_id' IS NOT NULL
11883                        AND
11884                    details ->> 'cluster_id' !~~ 's%'
11885            ),
11886            drops AS
11887            (
11888                SELECT details ->> 'replica_id' AS replica_id, occurred_at
11889                FROM mz_catalog.mz_audit_events
11890                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
11891            )
11892        SELECT
11893            creates.replica_id,
11894            creates.size,
11895            creates.cluster_id,
11896            creates.cluster_name,
11897            creates.replica_name,
11898            creates.occurred_at AS created_at,
11899            drops.occurred_at AS dropped_at,
11900            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
11901        FROM
11902            creates
11903                LEFT JOIN drops ON creates.replica_id = drops.replica_id
11904                LEFT JOIN
11905                    mz_catalog.mz_cluster_replica_sizes
11906                    ON mz_cluster_replica_sizes.size = creates.size"#,
11907    access: vec![PUBLIC_SELECT],
11908});
11909
11910pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11911    name: "mz_cluster_replica_name_history",
11912    schema: MZ_INTERNAL_SCHEMA,
11913    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
11914    desc: RelationDesc::builder()
11915        .with_column(
11916            "occurred_at",
11917            ScalarType::TimestampTz { precision: None }.nullable(true),
11918        )
11919        .with_column("id", ScalarType::String.nullable(true))
11920        .with_column("previous_name", ScalarType::String.nullable(true))
11921        .with_column("new_name", ScalarType::String.nullable(true))
11922        .finish(),
11923    column_comments: BTreeMap::from_iter([
11924        (
11925            "occurred_at",
11926            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
11927        ),
11928        ("id", "The ID of the cluster replica."),
11929        (
11930            "previous_name",
11931            "The previous name of the cluster replica. `NULL` if there was no previous name.",
11932        ),
11933        ("new_name", "The new name of the cluster replica."),
11934    ]),
11935    sql: r#"WITH user_replica_alter_history AS (
11936  SELECT occurred_at,
11937    audit_events.details->>'replica_id' AS id,
11938    audit_events.details->>'old_name' AS previous_name,
11939    audit_events.details->>'new_name' AS new_name
11940  FROM mz_catalog.mz_audit_events AS audit_events
11941  WHERE object_type = 'cluster-replica'
11942    AND audit_events.event_type = 'alter'
11943    AND audit_events.details->>'replica_id' like 'u%'
11944),
11945user_replica_create_history AS (
11946  SELECT occurred_at,
11947    audit_events.details->>'replica_id' AS id,
11948    NULL AS previous_name,
11949    audit_events.details->>'replica_name' AS new_name
11950  FROM mz_catalog.mz_audit_events AS audit_events
11951  WHERE object_type = 'cluster-replica'
11952    AND audit_events.event_type = 'create'
11953    AND audit_events.details->>'replica_id' like 'u%'
11954),
11955-- Because built in system cluster replicas don't have audit events, we need to manually add them
11956system_replicas AS (
11957  -- We assume that the system cluster replicas were created at the beginning of time
11958  SELECT NULL::timestamptz AS occurred_at,
11959    id,
11960    NULL AS previous_name,
11961    name AS new_name
11962  FROM mz_catalog.mz_cluster_replicas
11963  WHERE id LIKE 's%'
11964)
11965SELECT *
11966FROM user_replica_alter_history
11967UNION ALL
11968SELECT *
11969FROM user_replica_create_history
11970UNION ALL
11971SELECT *
11972FROM system_replicas"#,
11973    access: vec![PUBLIC_SELECT],
11974});
11975
11976pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11977    name: "mz_hydration_statuses",
11978    schema: MZ_INTERNAL_SCHEMA,
11979    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
11980    desc: RelationDesc::builder()
11981        .with_column("object_id", ScalarType::String.nullable(false))
11982        .with_column("replica_id", ScalarType::String.nullable(true))
11983        .with_column("hydrated", ScalarType::Bool.nullable(true))
11984        .finish(),
11985    column_comments: BTreeMap::from_iter([
11986        (
11987            "object_id",
11988            "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`.",
11989        ),
11990        ("replica_id", "The ID of a cluster replica."),
11991        ("hydrated", "Whether the object is hydrated on the replica."),
11992    ]),
11993    sql: r#"WITH
11994-- Joining against the linearizable catalog tables ensures that this view
11995-- always contains the set of installed objects, even when it depends
11996-- on introspection relations that may received delayed updates.
11997--
11998-- Note that this view only includes objects that are maintained by dataflows.
11999-- In particular, some source types (webhook, introspection, ...) are not and
12000-- are therefore omitted.
12001indexes AS (
12002    SELECT
12003        i.id AS object_id,
12004        h.replica_id,
12005        COALESCE(h.hydrated, false) AS hydrated
12006    FROM mz_catalog.mz_indexes i
12007    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12008        ON (h.object_id = i.id)
12009),
12010materialized_views AS (
12011    SELECT
12012        i.id AS object_id,
12013        h.replica_id,
12014        COALESCE(h.hydrated, false) AS hydrated
12015    FROM mz_catalog.mz_materialized_views i
12016    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12017        ON (h.object_id = i.id)
12018),
12019continual_tasks AS (
12020    SELECT
12021        i.id AS object_id,
12022        h.replica_id,
12023        COALESCE(h.hydrated, false) AS hydrated
12024    FROM mz_internal.mz_continual_tasks i
12025    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12026        ON (h.object_id = i.id)
12027),
12028-- Hydration is a dataflow concept and not all sources are maintained by
12029-- dataflows, so we need to find the ones that are. Generally, sources that
12030-- have a cluster ID are maintained by a dataflow running on that cluster.
12031-- Webhook sources are an exception to this rule.
12032sources_with_clusters AS (
12033    SELECT id, cluster_id
12034    FROM mz_catalog.mz_sources
12035    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12036),
12037sources AS (
12038    SELECT
12039        s.id AS object_id,
12040        r.id AS replica_id,
12041        ss.rehydration_latency IS NOT NULL AS hydrated
12042    FROM sources_with_clusters s
12043    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12044    JOIN mz_catalog.mz_cluster_replicas r
12045        ON (r.cluster_id = s.cluster_id)
12046),
12047-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12048-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12049-- There is likely still a possibility of FPs.
12050sinks AS (
12051    SELECT
12052        s.id AS object_id,
12053        r.id AS replica_id,
12054        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12055    FROM mz_catalog.mz_sinks s
12056    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12057    JOIN mz_catalog.mz_cluster_replicas r
12058        ON (r.cluster_id = s.cluster_id)
12059    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12060        ON (f.object_id = s.id AND f.replica_id = r.id)
12061)
12062SELECT * FROM indexes
12063UNION ALL
12064SELECT * FROM materialized_views
12065UNION ALL
12066SELECT * FROM continual_tasks
12067UNION ALL
12068SELECT * FROM sources
12069UNION ALL
12070SELECT * FROM sinks"#,
12071    access: vec![PUBLIC_SELECT],
12072});
12073
12074pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12075    name: "mz_materialization_dependencies",
12076    schema: MZ_INTERNAL_SCHEMA,
12077    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12078    desc: RelationDesc::builder()
12079        .with_column("object_id", ScalarType::String.nullable(false))
12080        .with_column("dependency_id", ScalarType::String.nullable(false))
12081        .finish(),
12082    column_comments: BTreeMap::from_iter([
12083        (
12084            "object_id",
12085            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12086        ),
12087        (
12088            "dependency_id",
12089            "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`.",
12090        ),
12091    ]),
12092    sql: "
12093SELECT object_id, dependency_id
12094FROM mz_internal.mz_compute_dependencies
12095UNION ALL
12096SELECT s.id, d.referenced_object_id AS dependency_id
12097FROM mz_internal.mz_object_dependencies d
12098JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12099JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12100    access: vec![PUBLIC_SELECT],
12101});
12102
12103pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12104    name: "mz_materialization_lag",
12105    schema: MZ_INTERNAL_SCHEMA,
12106    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12107    desc: RelationDesc::builder()
12108        .with_column("object_id", ScalarType::String.nullable(false))
12109        .with_column("local_lag", ScalarType::Interval.nullable(true))
12110        .with_column("global_lag", ScalarType::Interval.nullable(true))
12111        .with_column("slowest_local_input_id", ScalarType::String.nullable(false))
12112        .with_column(
12113            "slowest_global_input_id",
12114            ScalarType::String.nullable(false),
12115        )
12116        .finish(),
12117    column_comments: BTreeMap::from_iter([
12118        (
12119            "object_id",
12120            "The ID of the materialized view, index, or sink.",
12121        ),
12122        (
12123            "local_lag",
12124            "The amount of time the materialization lags behind its direct inputs.",
12125        ),
12126        (
12127            "global_lag",
12128            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12129        ),
12130        (
12131            "slowest_local_input_id",
12132            "The ID of the slowest direct input.",
12133        ),
12134        (
12135            "slowest_global_input_id",
12136            "The ID of the slowest root input.",
12137        ),
12138    ]),
12139    sql: "
12140WITH MUTUALLY RECURSIVE
12141    -- IDs of objects for which we want to know the lag.
12142    materializations (id text) AS (
12143        SELECT id FROM mz_catalog.mz_indexes
12144        UNION ALL
12145        SELECT id FROM mz_catalog.mz_materialized_views
12146        UNION ALL
12147        SELECT id FROM mz_internal.mz_continual_tasks
12148        UNION ALL
12149        SELECT id FROM mz_catalog.mz_sinks
12150    ),
12151    -- Direct dependencies of materializations.
12152    direct_dependencies (id text, dep_id text) AS (
12153        SELECT m.id, d.dependency_id
12154        FROM materializations m
12155        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12156    ),
12157    -- All transitive dependencies of materializations.
12158    transitive_dependencies (id text, dep_id text) AS (
12159        SELECT id, dep_id FROM direct_dependencies
12160        UNION
12161        SELECT td.id, dd.dep_id
12162        FROM transitive_dependencies td
12163        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12164    ),
12165    -- Root dependencies of materializations (sources and tables).
12166    root_dependencies (id text, dep_id text) AS (
12167        SELECT *
12168        FROM transitive_dependencies td
12169        WHERE NOT EXISTS (
12170            SELECT 1
12171            FROM direct_dependencies dd
12172            WHERE dd.id = td.dep_id
12173        )
12174    ),
12175    -- Write progress times of materializations.
12176    materialization_times (id text, time timestamptz) AS (
12177        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12178        FROM materializations m
12179        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12180    ),
12181    -- Write progress times of direct dependencies of materializations.
12182    input_times (id text, slowest_dep text, time timestamptz) AS (
12183        SELECT DISTINCT ON (d.id)
12184            d.id,
12185            d.dep_id,
12186            to_timestamp(f.write_frontier::text::double / 1000)
12187        FROM direct_dependencies d
12188        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12189        ORDER BY d.id, f.write_frontier ASC
12190    ),
12191    -- Write progress times of root dependencies of materializations.
12192    root_times (id text, slowest_dep text, time timestamptz) AS (
12193        SELECT DISTINCT ON (d.id)
12194            d.id,
12195            d.dep_id,
12196            to_timestamp(f.write_frontier::text::double / 1000)
12197        FROM root_dependencies d
12198        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12199        ORDER BY d.id, f.write_frontier ASC
12200    )
12201SELECT
12202    id AS object_id,
12203    -- Ensure that lag values are always NULL for materializations that have reached the empty
12204    -- frontier, as those have processed all their input data.
12205    -- Also make sure that lag values are never negative, even when input frontiers are before
12206    -- output frontiers (as can happen during hydration).
12207    CASE
12208        WHEN m.time IS NULL THEN INTERVAL '0'
12209        WHEN i.time IS NULL THEN NULL
12210        ELSE greatest(i.time - m.time, INTERVAL '0')
12211    END AS local_lag,
12212    CASE
12213        WHEN m.time IS NULL THEN INTERVAL '0'
12214        WHEN r.time IS NULL THEN NULL
12215        ELSE greatest(r.time - m.time, INTERVAL '0')
12216    END AS global_lag,
12217    i.slowest_dep AS slowest_local_input_id,
12218    r.slowest_dep AS slowest_global_input_id
12219FROM materialization_times m
12220JOIN input_times i USING (id)
12221JOIN root_times r USING (id)",
12222    access: vec![PUBLIC_SELECT],
12223});
12224
12225/**
12226 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12227 * It's specifically for the Console's environment overview page to speed up load times.
12228 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12229 */
12230pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12231    BuiltinView {
12232        name: "mz_console_cluster_utilization_overview",
12233        schema: MZ_INTERNAL_SCHEMA,
12234        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12235        desc: RelationDesc::builder()
12236            .with_column(
12237                "bucket_start",
12238                ScalarType::TimestampTz { precision: None }.nullable(false),
12239            )
12240            .with_column("replica_id", ScalarType::String.nullable(false))
12241            .with_column("memory_percent", ScalarType::Float64.nullable(true))
12242            .with_column(
12243                "max_memory_at",
12244                ScalarType::TimestampTz { precision: None }.nullable(false),
12245            )
12246            .with_column("disk_percent", ScalarType::Float64.nullable(true))
12247            .with_column(
12248                "max_disk_at",
12249                ScalarType::TimestampTz { precision: None }.nullable(false),
12250            )
12251            .with_column(
12252                "memory_and_disk_percent",
12253                ScalarType::Float64.nullable(true),
12254            )
12255            .with_column(
12256                "max_memory_and_disk_memory_percent",
12257                ScalarType::Float64.nullable(true),
12258            )
12259            .with_column(
12260                "max_memory_and_disk_disk_percent",
12261                ScalarType::Float64.nullable(true),
12262            )
12263            .with_column(
12264                "max_memory_and_disk_at",
12265                ScalarType::TimestampTz { precision: None }.nullable(false),
12266            )
12267            .with_column("max_cpu_percent", ScalarType::Float64.nullable(true))
12268            .with_column(
12269                "max_cpu_at",
12270                ScalarType::TimestampTz { precision: None }.nullable(false),
12271            )
12272            .with_column("offline_events", ScalarType::Jsonb.nullable(true))
12273            .with_column(
12274                "bucket_end",
12275                ScalarType::TimestampTz { precision: None }.nullable(false),
12276            )
12277            .with_column("name", ScalarType::String.nullable(true))
12278            .with_column("cluster_id", ScalarType::String.nullable(true))
12279            .with_column("size", ScalarType::String.nullable(true))
12280            .finish(),
12281        column_comments: BTreeMap::new(),
12282        sql: r#"WITH replica_history AS (
12283  SELECT replica_id,
12284    size,
12285    cluster_id
12286  FROM mz_internal.mz_cluster_replica_history
12287  UNION
12288  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12289  SELECT id AS replica_id,
12290    size,
12291    cluster_id
12292  FROM mz_catalog.mz_cluster_replicas
12293),
12294replica_metrics_history AS (
12295  SELECT
12296    m.occurred_at,
12297    m.replica_id,
12298    r.size,
12299    (SUM(m.cpu_nano_cores::float8) / s.cpu_nano_cores) / s.processes AS cpu_percent,
12300    (SUM(m.memory_bytes::float8) / s.memory_bytes) / s.processes AS memory_percent,
12301    (SUM(m.disk_bytes::float8) / s.disk_bytes) / s.processes AS disk_percent,
12302    SUM(m.disk_bytes::float8) AS disk_bytes,
12303    SUM(m.memory_bytes::float8) AS memory_bytes,
12304    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12305    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12306  FROM
12307    replica_history AS r
12308    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12309    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12310  GROUP BY
12311    m.occurred_at,
12312    m.replica_id,
12313    r.size,
12314    s.cpu_nano_cores,
12315    s.memory_bytes,
12316    s.disk_bytes,
12317    s.processes
12318),
12319replica_utilization_history_binned AS (
12320  SELECT m.occurred_at,
12321    m.replica_id,
12322    m.cpu_percent,
12323    m.memory_percent,
12324    m.memory_bytes,
12325    m.disk_percent,
12326    m.disk_bytes,
12327    m.total_disk_bytes,
12328    m.total_memory_bytes,
12329    m.size,
12330    date_bin(
12331      '8 HOURS',
12332      occurred_at,
12333      '1970-01-01'::timestamp
12334    ) AS bucket_start
12335  FROM replica_history AS r
12336    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12337  WHERE mz_now() <= date_bin(
12338      '8 HOURS',
12339      occurred_at,
12340      '1970-01-01'::timestamp
12341    ) + INTERVAL '14 DAYS'
12342),
12343-- For each (replica, bucket), take the (replica, bucket) with the highest memory
12344max_memory AS (
12345  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12346    replica_id,
12347    memory_percent,
12348    occurred_at
12349  FROM replica_utilization_history_binned
12350  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12351  ORDER BY bucket_start,
12352    replica_id,
12353    COALESCE(memory_bytes, 0) DESC
12354),
12355max_disk AS (
12356  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12357    replica_id,
12358    disk_percent,
12359    occurred_at
12360  FROM replica_utilization_history_binned
12361  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12362  ORDER BY bucket_start,
12363    replica_id,
12364    COALESCE(disk_bytes, 0) DESC
12365),
12366max_cpu AS (
12367  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12368    replica_id,
12369    cpu_percent,
12370    occurred_at
12371  FROM replica_utilization_history_binned
12372  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12373  ORDER BY bucket_start,
12374    replica_id,
12375    COALESCE(cpu_percent, 0) DESC
12376),
12377/*
12378 This is different
12379 from adding max_memory
12380 and max_disk per bucket because both
12381 values may not occur at the same time if the bucket interval is large.
12382 */
12383max_memory_and_disk AS (
12384  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12385    replica_id,
12386    memory_percent,
12387    disk_percent,
12388    memory_and_disk_percent,
12389    occurred_at
12390  FROM (
12391      SELECT *,
12392        CASE
12393          WHEN disk_bytes IS NULL
12394          AND memory_bytes IS NULL THEN NULL
12395          ELSE (
12396            (
12397              COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0)
12398            ) / total_memory_bytes
12399          ) / (
12400            (
12401              total_disk_bytes::numeric + total_memory_bytes::numeric
12402            ) / total_memory_bytes
12403          )
12404        END AS memory_and_disk_percent
12405      FROM replica_utilization_history_binned
12406    ) AS max_memory_and_disk_inner
12407  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12408  ORDER BY bucket_start,
12409    replica_id,
12410    COALESCE(memory_and_disk_percent, 0) DESC
12411),
12412-- For each (replica, bucket), get its offline events at that time
12413replica_offline_event_history AS (
12414  SELECT date_bin(
12415      '8 HOURS',
12416      occurred_at,
12417      '1970-01-01'::timestamp
12418    ) AS bucket_start,
12419    replica_id,
12420    jsonb_agg(
12421      jsonb_build_object(
12422        'replicaId',
12423        rsh.replica_id,
12424        'occurredAt',
12425        rsh.occurred_at,
12426        'status',
12427        rsh.status,
12428        'reason',
12429        rsh.reason
12430      )
12431    ) AS offline_events
12432  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
12433  WHERE process_id = '0'
12434    AND status = 'offline'
12435    AND mz_now() <= date_bin(
12436      '8 HOURS',
12437      occurred_at,
12438      '1970-01-01'::timestamp
12439    ) + INTERVAL '14 DAYS'
12440  GROUP BY bucket_start,
12441    replica_id
12442)
12443SELECT max_memory.bucket_start,
12444  max_memory.replica_id,
12445  max_memory.memory_percent,
12446  max_memory.occurred_at as max_memory_at,
12447  max_disk.disk_percent,
12448  max_disk.occurred_at as max_disk_at,
12449  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
12450  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
12451  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
12452  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
12453  max_cpu.cpu_percent as max_cpu_percent,
12454  max_cpu.occurred_at as max_cpu_at,
12455  replica_offline_event_history.offline_events,
12456  max_memory.bucket_start + INTERVAL '8 HOURS' as bucket_end,
12457  replica_name_history.new_name AS name,
12458  replica_history.cluster_id,
12459  replica_history.size
12460FROM max_memory
12461  JOIN max_disk ON max_memory.bucket_start = max_disk.bucket_start
12462  AND max_memory.replica_id = max_disk.replica_id
12463  JOIN max_cpu ON max_memory.bucket_start = max_cpu.bucket_start
12464  AND max_memory.replica_id = max_cpu.replica_id
12465  JOIN max_memory_and_disk ON max_memory.bucket_start = max_memory_and_disk.bucket_start
12466  AND max_memory.replica_id = max_memory_and_disk.replica_id
12467  JOIN replica_history ON max_memory.replica_id = replica_history.replica_id,
12468  LATERAL (
12469    SELECT new_name
12470    FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
12471    WHERE max_memory.replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
12472      AND max_memory.bucket_start + INTERVAL '8 HOURS' >= COALESCE(
12473        replica_name_history.occurred_at,
12474        '1970-01-01'::timestamp
12475      )
12476    ORDER BY replica_name_history.occurred_at DESC
12477    LIMIT '1'
12478  ) AS replica_name_history
12479  LEFT JOIN replica_offline_event_history ON max_memory.bucket_start = replica_offline_event_history.bucket_start
12480  AND max_memory.replica_id = replica_offline_event_history.replica_id"#,
12481        access: vec![PUBLIC_SELECT],
12482    }
12483});
12484
12485/**
12486 * Traces the blue/green deployment lineage in the audit log to determine all cluster
12487 * IDs that are logically the same cluster.
12488 * cluster_id: The ID of a cluster.
12489 * current_deployment_cluster_id: The cluster ID of the last cluster in
12490 *   cluster_id's blue/green lineage.
12491 * cluster_name: The name of the cluster.
12492 * The approach taken is as follows. First, find all extant clusters and add them
12493 * to the result set. Per cluster, we do the following:
12494 * 1. Find the most recent create or rename event. This moment represents when the
12495 *    cluster took on its final logical identity.
12496 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
12497 *    appended) that was dropped within one minute of that moment. That cluster is
12498 *    almost certainly the logical predecessor of the current cluster. Add the cluster
12499 *    to the result set.
12500 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
12501 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
12502 * but one that's likely to be pretty good one. If a name is reused after more
12503 * than one minute, that's a good sign that it wasn't an automatic blue/green
12504 * process, but someone turning on a new use case that happens to have the same
12505 * name as a previous but logically distinct use case.
12506 */
12507pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12508    name: "mz_cluster_deployment_lineage",
12509    schema: MZ_INTERNAL_SCHEMA,
12510    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
12511    desc: RelationDesc::builder()
12512        .with_column("cluster_id", ScalarType::String.nullable(true))
12513        .with_column(
12514            "current_deployment_cluster_id",
12515            ScalarType::String.nullable(false),
12516        )
12517        .with_column("cluster_name", ScalarType::String.nullable(false))
12518        .with_key(vec![0, 1, 2])
12519        .finish(),
12520    column_comments: BTreeMap::from_iter([
12521        (
12522            "cluster_id",
12523            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
12524        ),
12525        (
12526            "current_deployment_cluster_id",
12527            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
12528        ),
12529        ("cluster_name", "The name of the cluster"),
12530    ]),
12531    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
12532  cluster_id text,
12533  cluster_name text,
12534  event_type text,
12535  occurred_at timestamptz
12536) AS (
12537  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
12538    coalesce(details->>'name', details->>'new_name') AS cluster_name,
12539    event_type,
12540    occurred_at
12541  FROM mz_audit_events
12542  WHERE (
12543      event_type IN ('create', 'drop')
12544      OR (
12545        event_type = 'alter'
12546        AND details ? 'new_name'
12547      )
12548    )
12549    AND object_type = 'cluster'
12550    AND mz_now() < occurred_at + INTERVAL '30 days'
12551),
12552mz_cluster_deployment_lineage (
12553  cluster_id text,
12554  current_deployment_cluster_id text,
12555  cluster_name text
12556) AS (
12557  SELECT c.id,
12558    c.id,
12559    c.name
12560  FROM mz_clusters c
12561  WHERE c.id LIKE 'u%'
12562  UNION
12563  SELECT *
12564  FROM dropped_clusters
12565),
12566-- Closest create or rename event based on the current clusters in the result set
12567most_recent_create_or_rename (
12568  cluster_id text,
12569  current_deployment_cluster_id text,
12570  cluster_name text,
12571  occurred_at timestamptz
12572) AS (
12573  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
12574    c.current_deployment_cluster_id,
12575    e.cluster_name,
12576    e.occurred_at
12577  FROM mz_cluster_deployment_lineage c
12578    JOIN cluster_events e ON c.cluster_id = e.cluster_id
12579    AND c.cluster_name = e.cluster_name
12580  WHERE e.event_type <> 'drop'
12581  ORDER BY e.cluster_id,
12582    e.occurred_at DESC
12583),
12584-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
12585dropped_clusters (
12586  cluster_id text,
12587  current_deployment_cluster_id text,
12588  cluster_name text
12589) AS (
12590  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
12591    cr.current_deployment_cluster_id,
12592    cr.cluster_name
12593  FROM most_recent_create_or_rename cr
12594    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
12595    AND cr.occurred_at + interval '1 minute'
12596    AND (
12597      e.cluster_name = cr.cluster_name
12598      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
12599    )
12600  WHERE e.event_type = 'drop'
12601  ORDER BY cr.cluster_id,
12602    abs(
12603      extract(
12604        epoch
12605        FROM cr.occurred_at - e.occurred_at
12606      )
12607    )
12608)
12609SELECT *
12610FROM mz_cluster_deployment_lineage"#,
12611    access: vec![PUBLIC_SELECT],
12612});
12613
12614pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12615    name: "mz_show_databases_ind",
12616    schema: MZ_INTERNAL_SCHEMA,
12617    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
12618    sql: "IN CLUSTER mz_catalog_server
12619ON mz_internal.mz_show_databases (name)",
12620    is_retained_metrics_object: false,
12621};
12622
12623pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12624    name: "mz_show_schemas_ind",
12625    schema: MZ_INTERNAL_SCHEMA,
12626    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
12627    sql: "IN CLUSTER mz_catalog_server
12628ON mz_internal.mz_show_schemas (database_id)",
12629    is_retained_metrics_object: false,
12630};
12631
12632pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12633    name: "mz_show_connections_ind",
12634    schema: MZ_INTERNAL_SCHEMA,
12635    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
12636    sql: "IN CLUSTER mz_catalog_server
12637ON mz_internal.mz_show_connections (schema_id)",
12638    is_retained_metrics_object: false,
12639};
12640
12641pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
12642    name: "mz_show_tables_ind",
12643    schema: MZ_INTERNAL_SCHEMA,
12644    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
12645    sql: "IN CLUSTER mz_catalog_server
12646ON mz_internal.mz_show_tables (schema_id)",
12647    is_retained_metrics_object: false,
12648};
12649
12650pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12651    name: "mz_show_sources_ind",
12652    schema: MZ_INTERNAL_SCHEMA,
12653    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
12654    sql: "IN CLUSTER mz_catalog_server
12655ON mz_internal.mz_show_sources (schema_id)",
12656    is_retained_metrics_object: false,
12657};
12658
12659pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12660    name: "mz_show_views_ind",
12661    schema: MZ_INTERNAL_SCHEMA,
12662    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
12663    sql: "IN CLUSTER mz_catalog_server
12664ON mz_internal.mz_show_views (schema_id)",
12665    is_retained_metrics_object: false,
12666};
12667
12668pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12669    name: "mz_show_materialized_views_ind",
12670    schema: MZ_INTERNAL_SCHEMA,
12671    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
12672    sql: "IN CLUSTER mz_catalog_server
12673ON mz_internal.mz_show_materialized_views (schema_id)",
12674    is_retained_metrics_object: false,
12675};
12676
12677pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
12678    name: "mz_show_sinks_ind",
12679    schema: MZ_INTERNAL_SCHEMA,
12680    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
12681    sql: "IN CLUSTER mz_catalog_server
12682ON mz_internal.mz_show_sinks (schema_id)",
12683    is_retained_metrics_object: false,
12684};
12685
12686pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
12687    name: "mz_show_types_ind",
12688    schema: MZ_INTERNAL_SCHEMA,
12689    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
12690    sql: "IN CLUSTER mz_catalog_server
12691ON mz_internal.mz_show_types (schema_id)",
12692    is_retained_metrics_object: false,
12693};
12694
12695pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
12696    name: "mz_show_roles_ind",
12697    schema: MZ_INTERNAL_SCHEMA,
12698    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
12699    sql: "IN CLUSTER mz_catalog_server
12700ON mz_internal.mz_show_roles (name)",
12701    is_retained_metrics_object: false,
12702};
12703
12704pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12705    name: "mz_show_all_objects_ind",
12706    schema: MZ_INTERNAL_SCHEMA,
12707    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
12708    sql: "IN CLUSTER mz_catalog_server
12709ON mz_internal.mz_show_all_objects (schema_id)",
12710    is_retained_metrics_object: false,
12711};
12712
12713pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12714    name: "mz_show_indexes_ind",
12715    schema: MZ_INTERNAL_SCHEMA,
12716    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
12717    sql: "IN CLUSTER mz_catalog_server
12718ON mz_internal.mz_show_indexes (schema_id)",
12719    is_retained_metrics_object: false,
12720};
12721
12722pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12723    name: "mz_show_columns_ind",
12724    schema: MZ_INTERNAL_SCHEMA,
12725    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
12726    sql: "IN CLUSTER mz_catalog_server
12727ON mz_internal.mz_show_columns (id)",
12728    is_retained_metrics_object: false,
12729};
12730
12731pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12732    name: "mz_show_clusters_ind",
12733    schema: MZ_INTERNAL_SCHEMA,
12734    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
12735    sql: "IN CLUSTER mz_catalog_server
12736ON mz_internal.mz_show_clusters (name)",
12737    is_retained_metrics_object: false,
12738};
12739
12740pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
12741    name: "mz_show_cluster_replicas_ind",
12742    schema: MZ_INTERNAL_SCHEMA,
12743    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
12744    sql: "IN CLUSTER mz_catalog_server
12745ON mz_internal.mz_show_cluster_replicas (cluster)",
12746    is_retained_metrics_object: false,
12747};
12748
12749pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12750    name: "mz_show_secrets_ind",
12751    schema: MZ_INTERNAL_SCHEMA,
12752    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
12753    sql: "IN CLUSTER mz_catalog_server
12754ON mz_internal.mz_show_secrets (schema_id)",
12755    is_retained_metrics_object: false,
12756};
12757
12758pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12759    name: "mz_databases_ind",
12760    schema: MZ_CATALOG_SCHEMA,
12761    oid: oid::INDEX_MZ_DATABASES_IND_OID,
12762    sql: "IN CLUSTER mz_catalog_server
12763ON mz_catalog.mz_databases (name)",
12764    is_retained_metrics_object: false,
12765};
12766
12767pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12768    name: "mz_schemas_ind",
12769    schema: MZ_CATALOG_SCHEMA,
12770    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
12771    sql: "IN CLUSTER mz_catalog_server
12772ON mz_catalog.mz_schemas (database_id)",
12773    is_retained_metrics_object: false,
12774};
12775
12776pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12777    name: "mz_connections_ind",
12778    schema: MZ_CATALOG_SCHEMA,
12779    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
12780    sql: "IN CLUSTER mz_catalog_server
12781ON mz_catalog.mz_connections (schema_id)",
12782    is_retained_metrics_object: false,
12783};
12784
12785pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
12786    name: "mz_tables_ind",
12787    schema: MZ_CATALOG_SCHEMA,
12788    oid: oid::INDEX_MZ_TABLES_IND_OID,
12789    sql: "IN CLUSTER mz_catalog_server
12790ON mz_catalog.mz_tables (schema_id)",
12791    is_retained_metrics_object: false,
12792};
12793
12794pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
12795    name: "mz_types_ind",
12796    schema: MZ_CATALOG_SCHEMA,
12797    oid: oid::INDEX_MZ_TYPES_IND_OID,
12798    sql: "IN CLUSTER mz_catalog_server
12799ON mz_catalog.mz_types (schema_id)",
12800    is_retained_metrics_object: false,
12801};
12802
12803pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12804    name: "mz_objects_ind",
12805    schema: MZ_CATALOG_SCHEMA,
12806    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
12807    sql: "IN CLUSTER mz_catalog_server
12808ON mz_catalog.mz_objects (schema_id)",
12809    is_retained_metrics_object: false,
12810};
12811
12812pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12813    name: "mz_columns_ind",
12814    schema: MZ_CATALOG_SCHEMA,
12815    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
12816    sql: "IN CLUSTER mz_catalog_server
12817ON mz_catalog.mz_columns (name)",
12818    is_retained_metrics_object: false,
12819};
12820
12821pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12822    name: "mz_secrets_ind",
12823    schema: MZ_CATALOG_SCHEMA,
12824    oid: oid::INDEX_MZ_SECRETS_IND_OID,
12825    sql: "IN CLUSTER mz_catalog_server
12826ON mz_catalog.mz_secrets (name)",
12827    is_retained_metrics_object: false,
12828};
12829
12830pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12831    name: "mz_views_ind",
12832    schema: MZ_CATALOG_SCHEMA,
12833    oid: oid::INDEX_MZ_VIEWS_IND_OID,
12834    sql: "IN CLUSTER mz_catalog_server
12835ON mz_catalog.mz_views (schema_id)",
12836    is_retained_metrics_object: false,
12837};
12838
12839pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
12840    name: "mz_console_cluster_utilization_overview_ind",
12841    schema: MZ_INTERNAL_SCHEMA,
12842    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
12843    sql: "IN CLUSTER mz_catalog_server
12844ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
12845    is_retained_metrics_object: false,
12846};
12847
12848pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
12849    name: "mz_cluster_deployment_lineage_ind",
12850    schema: MZ_INTERNAL_SCHEMA,
12851    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
12852    sql: "IN CLUSTER mz_catalog_server
12853ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
12854    is_retained_metrics_object: false,
12855};
12856
12857pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12858    name: "mz_clusters_ind",
12859    schema: MZ_CATALOG_SCHEMA,
12860    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
12861    sql: "IN CLUSTER mz_catalog_server
12862ON mz_catalog.mz_clusters (id)",
12863    is_retained_metrics_object: false,
12864};
12865
12866pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12867    name: "mz_indexes_ind",
12868    schema: MZ_CATALOG_SCHEMA,
12869    oid: oid::INDEX_MZ_INDEXES_IND_OID,
12870    sql: "IN CLUSTER mz_catalog_server
12871ON mz_catalog.mz_indexes (id)",
12872    is_retained_metrics_object: false,
12873};
12874
12875pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
12876    name: "mz_roles_ind",
12877    schema: MZ_CATALOG_SCHEMA,
12878    oid: oid::INDEX_MZ_ROLES_IND_OID,
12879    sql: "IN CLUSTER mz_catalog_server
12880ON mz_catalog.mz_roles (id)",
12881    is_retained_metrics_object: false,
12882};
12883
12884pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12885    name: "mz_sources_ind",
12886    schema: MZ_CATALOG_SCHEMA,
12887    oid: oid::INDEX_MZ_SOURCES_IND_OID,
12888    sql: "IN CLUSTER mz_catalog_server
12889ON mz_catalog.mz_sources (id)",
12890    is_retained_metrics_object: true,
12891};
12892
12893pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
12894    name: "mz_sinks_ind",
12895    schema: MZ_CATALOG_SCHEMA,
12896    oid: oid::INDEX_MZ_SINKS_IND_OID,
12897    sql: "IN CLUSTER mz_catalog_server
12898ON mz_catalog.mz_sinks (id)",
12899    is_retained_metrics_object: true,
12900};
12901
12902pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12903    name: "mz_materialized_views_ind",
12904    schema: MZ_CATALOG_SCHEMA,
12905    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
12906    sql: "IN CLUSTER mz_catalog_server
12907ON mz_catalog.mz_materialized_views (id)",
12908    is_retained_metrics_object: false,
12909};
12910
12911pub const MZ_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
12912    name: "mz_continual_tasks_ind",
12913    schema: MZ_INTERNAL_SCHEMA,
12914    oid: oid::INDEX_MZ_CONTINUAL_TASKS_IND_OID,
12915    sql: "IN CLUSTER mz_catalog_server
12916ON mz_internal.mz_continual_tasks (id)",
12917    is_retained_metrics_object: false,
12918};
12919
12920pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12921    name: "mz_source_statuses_ind",
12922    schema: MZ_INTERNAL_SCHEMA,
12923    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
12924    sql: "IN CLUSTER mz_catalog_server
12925ON mz_internal.mz_source_statuses (id)",
12926    is_retained_metrics_object: false,
12927};
12928
12929pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12930    name: "mz_sink_statuses_ind",
12931    schema: MZ_INTERNAL_SCHEMA,
12932    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
12933    sql: "IN CLUSTER mz_catalog_server
12934ON mz_internal.mz_sink_statuses (id)",
12935    is_retained_metrics_object: false,
12936};
12937
12938pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
12939    name: "mz_source_status_history_ind",
12940    schema: MZ_INTERNAL_SCHEMA,
12941    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
12942    sql: "IN CLUSTER mz_catalog_server
12943ON mz_internal.mz_source_status_history (source_id)",
12944    is_retained_metrics_object: false,
12945};
12946
12947pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
12948    name: "mz_sink_status_history_ind",
12949    schema: MZ_INTERNAL_SCHEMA,
12950    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
12951    sql: "IN CLUSTER mz_catalog_server
12952ON mz_internal.mz_sink_status_history (sink_id)",
12953    is_retained_metrics_object: false,
12954};
12955
12956pub const MZ_SHOW_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
12957    name: "mz_show_continual_tasks_ind",
12958    schema: MZ_INTERNAL_SCHEMA,
12959    oid: oid::INDEX_MZ_SHOW_CONTINUAL_TASKS_OID,
12960    sql: "IN CLUSTER mz_catalog_server
12961ON mz_internal.mz_show_continual_tasks (id)",
12962    is_retained_metrics_object: false,
12963};
12964
12965// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
12966// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
12967// save index space, and we don't expect the sum to be > 2^63
12968// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
12969//
12970//
12971// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
12972// underlying relation.
12973//
12974// We append WITH_HISTORY because we want to build a separate view + index that doesn't
12975// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
12976// to hold all records/updates, which causes CPU and latency of querying it to spike.
12977pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
12978    LazyLock::new(|| BuiltinView {
12979        name: "mz_source_statistics_with_history",
12980        schema: MZ_INTERNAL_SCHEMA,
12981        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
12982        desc: RelationDesc::builder()
12983            .with_column("id", ScalarType::String.nullable(false))
12984            .with_column("messages_received", ScalarType::UInt64.nullable(false))
12985            .with_column("bytes_received", ScalarType::UInt64.nullable(false))
12986            .with_column("updates_staged", ScalarType::UInt64.nullable(false))
12987            .with_column("updates_committed", ScalarType::UInt64.nullable(false))
12988            .with_column("records_indexed", ScalarType::UInt64.nullable(false))
12989            .with_column("bytes_indexed", ScalarType::UInt64.nullable(false))
12990            .with_column("rehydration_latency", ScalarType::Interval.nullable(true))
12991            .with_column("snapshot_records_known", ScalarType::UInt64.nullable(true))
12992            .with_column("snapshot_records_staged", ScalarType::UInt64.nullable(true))
12993            .with_column("snapshot_committed", ScalarType::Bool.nullable(false))
12994            .with_column("offset_known", ScalarType::UInt64.nullable(true))
12995            .with_column("offset_committed", ScalarType::UInt64.nullable(true))
12996            .with_key(vec![0])
12997            .finish(),
12998        column_comments: BTreeMap::new(),
12999        sql: "
13000SELECT
13001    id,
13002    -- Counters
13003    SUM(messages_received)::uint8 AS messages_received,
13004    SUM(bytes_received)::uint8 AS bytes_received,
13005    SUM(updates_staged)::uint8 AS updates_staged,
13006    SUM(updates_committed)::uint8 AS updates_committed,
13007    -- Resetting Gauges
13008    SUM(records_indexed)::uint8 AS records_indexed,
13009    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13010    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13011    CASE
13012        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13013        ELSE MAX(rehydration_latency)::interval
13014    END AS rehydration_latency,
13015    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13016    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13017    bool_and(snapshot_committed) as snapshot_committed,
13018    -- Gauges
13019    SUM(offset_known)::uint8 AS offset_known,
13020    SUM(offset_committed)::uint8 AS offset_committed
13021FROM mz_internal.mz_source_statistics_raw
13022GROUP BY id",
13023        access: vec![PUBLIC_SELECT],
13024    });
13025
13026pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13027    name: "mz_source_statistics_with_history_ind",
13028    schema: MZ_INTERNAL_SCHEMA,
13029    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13030    sql: "IN CLUSTER mz_catalog_server
13031ON mz_internal.mz_source_statistics_with_history (id)",
13032    is_retained_metrics_object: true,
13033};
13034
13035// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13036// Used to query MZ_SOURCE_STATISTICS at the current time.
13037pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13038    BuiltinView {
13039        name: "mz_source_statistics",
13040        schema: MZ_INTERNAL_SCHEMA,
13041        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13042        // We need to add a redundant where clause for a new dataflow to be created.
13043        desc: RelationDesc::builder()
13044            .with_column("id", ScalarType::String.nullable(false))
13045            .with_column("messages_received", ScalarType::UInt64.nullable(false))
13046            .with_column("bytes_received", ScalarType::UInt64.nullable(false))
13047            .with_column("updates_staged", ScalarType::UInt64.nullable(false))
13048            .with_column("updates_committed", ScalarType::UInt64.nullable(false))
13049            .with_column("records_indexed", ScalarType::UInt64.nullable(false))
13050            .with_column("bytes_indexed", ScalarType::UInt64.nullable(false))
13051            .with_column("rehydration_latency", ScalarType::Interval.nullable(true))
13052            .with_column("snapshot_records_known", ScalarType::UInt64.nullable(true))
13053            .with_column("snapshot_records_staged", ScalarType::UInt64.nullable(true))
13054            .with_column("snapshot_committed", ScalarType::Bool.nullable(false))
13055            .with_column("offset_known", ScalarType::UInt64.nullable(true))
13056            .with_column("offset_committed", ScalarType::UInt64.nullable(true))
13057            .with_key(vec![0])
13058            .finish(),
13059        column_comments: BTreeMap::from_iter([
13060            (
13061                "id",
13062                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13063            ),
13064            (
13065                "messages_received",
13066                "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.",
13067            ),
13068            (
13069                "bytes_received",
13070                "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.",
13071            ),
13072            (
13073                "updates_staged",
13074                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13075            ),
13076            (
13077                "updates_committed",
13078                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13079            ),
13080            (
13081                "records_indexed",
13082                "The number of individual records indexed in the source envelope state.",
13083            ),
13084            (
13085                "bytes_indexed",
13086                "The number of bytes stored in the source's internal index, if any.",
13087            ),
13088            (
13089                "rehydration_latency",
13090                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13091            ),
13092            (
13093                "snapshot_records_known",
13094                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13095            ),
13096            (
13097                "snapshot_records_staged",
13098                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13099            ),
13100            (
13101                "snapshot_committed",
13102                "Whether the source has committed the initial snapshot for a source.",
13103            ),
13104            (
13105                "offset_known",
13106                "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.",
13107            ),
13108            (
13109                "offset_committed",
13110                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13111            ),
13112        ]),
13113        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13114        access: vec![PUBLIC_SELECT],
13115    }
13116});
13117
13118pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13119    name: "mz_source_statistics_ind",
13120    schema: MZ_INTERNAL_SCHEMA,
13121    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13122    sql: "IN CLUSTER mz_catalog_server
13123ON mz_internal.mz_source_statistics (id)",
13124    is_retained_metrics_object: false,
13125};
13126
13127pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13128    name: "mz_sink_statistics",
13129    schema: MZ_INTERNAL_SCHEMA,
13130    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13131    desc: RelationDesc::builder()
13132        .with_column("id", ScalarType::String.nullable(false))
13133        .with_column("messages_staged", ScalarType::UInt64.nullable(false))
13134        .with_column("messages_committed", ScalarType::UInt64.nullable(false))
13135        .with_column("bytes_staged", ScalarType::UInt64.nullable(false))
13136        .with_column("bytes_committed", ScalarType::UInt64.nullable(false))
13137        .with_key(vec![0])
13138        .finish(),
13139    column_comments: BTreeMap::from_iter([
13140        (
13141            "id",
13142            "The ID of the sink. Corresponds to `mz_catalog.mz_sources.id`.",
13143        ),
13144        (
13145            "messages_staged",
13146            "The number of messages staged but possibly not committed to the sink.",
13147        ),
13148        (
13149            "messages_committed",
13150            "The number of messages committed to the sink.",
13151        ),
13152        (
13153            "bytes_staged",
13154            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13155        ),
13156        (
13157            "bytes_committed",
13158            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13159        ),
13160    ]),
13161    sql: "
13162SELECT
13163    id,
13164    SUM(messages_staged)::uint8 AS messages_staged,
13165    SUM(messages_committed)::uint8 AS messages_committed,
13166    SUM(bytes_staged)::uint8 AS bytes_staged,
13167    SUM(bytes_committed)::uint8 AS bytes_committed
13168FROM mz_internal.mz_sink_statistics_raw
13169GROUP BY id",
13170    access: vec![PUBLIC_SELECT],
13171});
13172
13173pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13174    name: "mz_sink_statistics_ind",
13175    schema: MZ_INTERNAL_SCHEMA,
13176    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13177    sql: "IN CLUSTER mz_catalog_server
13178ON mz_internal.mz_sink_statistics (id)",
13179    is_retained_metrics_object: true,
13180};
13181
13182pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13183    name: "mz_cluster_replicas_ind",
13184    schema: MZ_CATALOG_SCHEMA,
13185    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13186    sql: "IN CLUSTER mz_catalog_server
13187ON mz_catalog.mz_cluster_replicas (id)",
13188    is_retained_metrics_object: true,
13189};
13190
13191pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13192    name: "mz_cluster_replica_sizes_ind",
13193    schema: MZ_CATALOG_SCHEMA,
13194    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13195    sql: "IN CLUSTER mz_catalog_server
13196ON mz_catalog.mz_cluster_replica_sizes (size)",
13197    is_retained_metrics_object: true,
13198};
13199
13200pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13201    name: "mz_cluster_replica_statuses_ind",
13202    schema: MZ_INTERNAL_SCHEMA,
13203    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13204    sql: "IN CLUSTER mz_catalog_server
13205ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13206    is_retained_metrics_object: true,
13207};
13208
13209pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13210    name: "mz_cluster_replica_status_history_ind",
13211    schema: MZ_INTERNAL_SCHEMA,
13212    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13213    sql: "IN CLUSTER mz_catalog_server
13214ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13215    is_retained_metrics_object: false,
13216};
13217
13218pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13219    name: "mz_cluster_replica_metrics_ind",
13220    schema: MZ_INTERNAL_SCHEMA,
13221    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13222    sql: "IN CLUSTER mz_catalog_server
13223ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13224    is_retained_metrics_object: true,
13225};
13226
13227pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13228    name: "mz_cluster_replica_metrics_history_ind",
13229    schema: MZ_INTERNAL_SCHEMA,
13230    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13231    sql: "IN CLUSTER mz_catalog_server
13232ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13233    is_retained_metrics_object: false,
13234};
13235
13236pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13237    name: "mz_cluster_replica_history_ind",
13238    schema: MZ_INTERNAL_SCHEMA,
13239    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13240    sql: "IN CLUSTER mz_catalog_server
13241ON mz_internal.mz_cluster_replica_history (dropped_at)",
13242    is_retained_metrics_object: true,
13243};
13244
13245pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13246    name: "mz_cluster_replica_name_history_ind",
13247    schema: MZ_INTERNAL_SCHEMA,
13248    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13249    sql: "IN CLUSTER mz_catalog_server
13250ON mz_internal.mz_cluster_replica_name_history (id)",
13251    is_retained_metrics_object: false,
13252};
13253
13254pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13255    name: "mz_object_lifetimes_ind",
13256    schema: MZ_INTERNAL_SCHEMA,
13257    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13258    sql: "IN CLUSTER mz_catalog_server
13259ON mz_internal.mz_object_lifetimes (id)",
13260    is_retained_metrics_object: false,
13261};
13262
13263pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13264    name: "mz_object_history_ind",
13265    schema: MZ_INTERNAL_SCHEMA,
13266    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13267    sql: "IN CLUSTER mz_catalog_server
13268ON mz_internal.mz_object_history (id)",
13269    is_retained_metrics_object: false,
13270};
13271
13272pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13273    name: "mz_object_dependencies_ind",
13274    schema: MZ_INTERNAL_SCHEMA,
13275    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
13276    sql: "IN CLUSTER mz_catalog_server
13277ON mz_internal.mz_object_dependencies (object_id)",
13278    is_retained_metrics_object: true,
13279};
13280
13281pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13282    name: "mz_compute_dependencies_ind",
13283    schema: MZ_INTERNAL_SCHEMA,
13284    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
13285    sql: "IN CLUSTER mz_catalog_server
13286ON mz_internal.mz_compute_dependencies (dependency_id)",
13287    is_retained_metrics_object: false,
13288};
13289
13290pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13291    name: "mz_object_transitive_dependencies_ind",
13292    schema: MZ_INTERNAL_SCHEMA,
13293    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
13294    sql: "IN CLUSTER mz_catalog_server
13295ON mz_internal.mz_object_transitive_dependencies (object_id)",
13296    is_retained_metrics_object: false,
13297};
13298
13299pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
13300    name: "mz_frontiers_ind",
13301    schema: MZ_INTERNAL_SCHEMA,
13302    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
13303    sql: "IN CLUSTER mz_catalog_server
13304ON mz_internal.mz_frontiers (object_id)",
13305    is_retained_metrics_object: false,
13306};
13307
13308pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13309    name: "mz_wallclock_global_lag_recent_history_ind",
13310    schema: MZ_INTERNAL_SCHEMA,
13311    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
13312    sql: "IN CLUSTER mz_catalog_server
13313ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
13314    is_retained_metrics_object: false,
13315};
13316
13317pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
13318    name: "mz_recent_activity_log_thinned_ind",
13319    schema: MZ_INTERNAL_SCHEMA,
13320    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
13321    sql: "IN CLUSTER mz_catalog_server
13322-- sql_hash because we plan to join
13323-- this against mz_internal.mz_sql_text
13324ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
13325    is_retained_metrics_object: false,
13326};
13327
13328pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13329    name: "mz_kafka_sources_ind",
13330    schema: MZ_CATALOG_SCHEMA,
13331    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
13332    sql: "IN CLUSTER mz_catalog_server
13333ON mz_catalog.mz_kafka_sources (id)",
13334    is_retained_metrics_object: true,
13335};
13336
13337pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13338    name: "mz_webhook_sources_ind",
13339    schema: MZ_INTERNAL_SCHEMA,
13340    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
13341    sql: "IN CLUSTER mz_catalog_server
13342ON mz_internal.mz_webhook_sources (id)",
13343    is_retained_metrics_object: true,
13344};
13345
13346pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
13347    name: "mz_comments_ind",
13348    schema: MZ_INTERNAL_SCHEMA,
13349    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
13350    sql: "IN CLUSTER mz_catalog_server
13351ON mz_internal.mz_comments (id)",
13352    is_retained_metrics_object: true,
13353};
13354
13355pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
13356    name: "mz_analytics",
13357    schema: MZ_INTERNAL_SCHEMA,
13358    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
13359    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
13360    access: &[MzAclItem {
13361        grantee: MZ_SYSTEM_ROLE_ID,
13362        grantor: MZ_ANALYTICS_ROLE_ID,
13363        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
13364    }],
13365    owner_id: &MZ_ANALYTICS_ROLE_ID,
13366    runtime_alterable: true,
13367};
13368
13369pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
13370    id: MZ_SYSTEM_ROLE_ID,
13371    name: SYSTEM_USER_NAME,
13372    oid: oid::ROLE_MZ_SYSTEM_OID,
13373    attributes: RoleAttributes::new().with_all(),
13374};
13375
13376pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
13377    id: MZ_SUPPORT_ROLE_ID,
13378    name: SUPPORT_USER_NAME,
13379    oid: oid::ROLE_MZ_SUPPORT_OID,
13380    attributes: RoleAttributes::new(),
13381};
13382
13383pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
13384    id: MZ_ANALYTICS_ROLE_ID,
13385    name: ANALYTICS_USER_NAME,
13386    oid: oid::ROLE_MZ_ANALYTICS_OID,
13387    attributes: RoleAttributes::new(),
13388};
13389
13390/// This role can `SELECT` from various query history objects,
13391/// e.g. `mz_prepared_statement_history`.
13392pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
13393    id: MZ_MONITOR_ROLE_ID,
13394    name: "mz_monitor",
13395    oid: oid::ROLE_MZ_MONITOR_OID,
13396    attributes: RoleAttributes::new(),
13397};
13398
13399/// This role is like [`MZ_MONITOR_ROLE`], but can only query
13400/// the redacted versions of the objects.
13401pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
13402    id: MZ_MONITOR_REDACTED_ROLE_ID,
13403    name: "mz_monitor_redacted",
13404    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
13405    attributes: RoleAttributes::new(),
13406};
13407
13408pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
13409    name: SYSTEM_USER_NAME,
13410    owner_id: &MZ_SYSTEM_ROLE_ID,
13411    privileges: &[
13412        MzAclItem {
13413            grantee: MZ_SUPPORT_ROLE_ID,
13414            grantor: MZ_SYSTEM_ROLE_ID,
13415            acl_mode: AclMode::USAGE,
13416        },
13417        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13418    ],
13419};
13420
13421pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13422    name: BUILTIN_CLUSTER_REPLICA_NAME,
13423    cluster_name: MZ_SYSTEM_CLUSTER.name,
13424};
13425
13426pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
13427    name: "mz_catalog_server",
13428    owner_id: &MZ_SYSTEM_ROLE_ID,
13429    privileges: &[
13430        MzAclItem {
13431            grantee: RoleId::Public,
13432            grantor: MZ_SYSTEM_ROLE_ID,
13433            acl_mode: AclMode::USAGE,
13434        },
13435        MzAclItem {
13436            grantee: MZ_SUPPORT_ROLE_ID,
13437            grantor: MZ_SYSTEM_ROLE_ID,
13438            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
13439        },
13440        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13441    ],
13442};
13443
13444pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13445    name: BUILTIN_CLUSTER_REPLICA_NAME,
13446    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
13447};
13448
13449pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
13450    name: "mz_probe",
13451    owner_id: &MZ_SYSTEM_ROLE_ID,
13452    privileges: &[
13453        MzAclItem {
13454            grantee: MZ_SUPPORT_ROLE_ID,
13455            grantor: MZ_SYSTEM_ROLE_ID,
13456            acl_mode: AclMode::USAGE,
13457        },
13458        MzAclItem {
13459            grantee: MZ_MONITOR_ROLE_ID,
13460            grantor: MZ_SYSTEM_ROLE_ID,
13461            acl_mode: AclMode::USAGE,
13462        },
13463        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13464    ],
13465};
13466pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13467    name: BUILTIN_CLUSTER_REPLICA_NAME,
13468    cluster_name: MZ_PROBE_CLUSTER.name,
13469};
13470
13471pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
13472    name: "mz_support",
13473    owner_id: &MZ_SUPPORT_ROLE_ID,
13474    privileges: &[
13475        MzAclItem {
13476            grantee: MZ_SYSTEM_ROLE_ID,
13477            grantor: MZ_SUPPORT_ROLE_ID,
13478            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13479        },
13480        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
13481    ],
13482};
13483
13484pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
13485    name: "mz_analytics",
13486    owner_id: &MZ_ANALYTICS_ROLE_ID,
13487    privileges: &[
13488        MzAclItem {
13489            grantee: MZ_SYSTEM_ROLE_ID,
13490            grantor: MZ_ANALYTICS_ROLE_ID,
13491            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13492        },
13493        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
13494    ],
13495};
13496
13497/// List of all builtin objects sorted topologically by dependency.
13498pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
13499    let mut builtins = vec![
13500        Builtin::Type(&TYPE_ANY),
13501        Builtin::Type(&TYPE_ANYARRAY),
13502        Builtin::Type(&TYPE_ANYELEMENT),
13503        Builtin::Type(&TYPE_ANYNONARRAY),
13504        Builtin::Type(&TYPE_ANYRANGE),
13505        Builtin::Type(&TYPE_BOOL),
13506        Builtin::Type(&TYPE_BOOL_ARRAY),
13507        Builtin::Type(&TYPE_BYTEA),
13508        Builtin::Type(&TYPE_BYTEA_ARRAY),
13509        Builtin::Type(&TYPE_BPCHAR),
13510        Builtin::Type(&TYPE_BPCHAR_ARRAY),
13511        Builtin::Type(&TYPE_CHAR),
13512        Builtin::Type(&TYPE_CHAR_ARRAY),
13513        Builtin::Type(&TYPE_DATE),
13514        Builtin::Type(&TYPE_DATE_ARRAY),
13515        Builtin::Type(&TYPE_FLOAT4),
13516        Builtin::Type(&TYPE_FLOAT4_ARRAY),
13517        Builtin::Type(&TYPE_FLOAT8),
13518        Builtin::Type(&TYPE_FLOAT8_ARRAY),
13519        Builtin::Type(&TYPE_INT4),
13520        Builtin::Type(&TYPE_INT4_ARRAY),
13521        Builtin::Type(&TYPE_INT8),
13522        Builtin::Type(&TYPE_INT8_ARRAY),
13523        Builtin::Type(&TYPE_INTERVAL),
13524        Builtin::Type(&TYPE_INTERVAL_ARRAY),
13525        Builtin::Type(&TYPE_JSONB),
13526        Builtin::Type(&TYPE_JSONB_ARRAY),
13527        Builtin::Type(&TYPE_LIST),
13528        Builtin::Type(&TYPE_MAP),
13529        Builtin::Type(&TYPE_NAME),
13530        Builtin::Type(&TYPE_NAME_ARRAY),
13531        Builtin::Type(&TYPE_NUMERIC),
13532        Builtin::Type(&TYPE_NUMERIC_ARRAY),
13533        Builtin::Type(&TYPE_OID),
13534        Builtin::Type(&TYPE_OID_ARRAY),
13535        Builtin::Type(&TYPE_RECORD),
13536        Builtin::Type(&TYPE_RECORD_ARRAY),
13537        Builtin::Type(&TYPE_REGCLASS),
13538        Builtin::Type(&TYPE_REGCLASS_ARRAY),
13539        Builtin::Type(&TYPE_REGPROC),
13540        Builtin::Type(&TYPE_REGPROC_ARRAY),
13541        Builtin::Type(&TYPE_REGTYPE),
13542        Builtin::Type(&TYPE_REGTYPE_ARRAY),
13543        Builtin::Type(&TYPE_INT2),
13544        Builtin::Type(&TYPE_INT2_ARRAY),
13545        Builtin::Type(&TYPE_TEXT),
13546        Builtin::Type(&TYPE_TEXT_ARRAY),
13547        Builtin::Type(&TYPE_TIME),
13548        Builtin::Type(&TYPE_TIME_ARRAY),
13549        Builtin::Type(&TYPE_TIMESTAMP),
13550        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
13551        Builtin::Type(&TYPE_TIMESTAMPTZ),
13552        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
13553        Builtin::Type(&TYPE_UUID),
13554        Builtin::Type(&TYPE_UUID_ARRAY),
13555        Builtin::Type(&TYPE_VARCHAR),
13556        Builtin::Type(&TYPE_VARCHAR_ARRAY),
13557        Builtin::Type(&TYPE_INT2_VECTOR),
13558        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
13559        Builtin::Type(&TYPE_ANYCOMPATIBLE),
13560        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
13561        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
13562        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
13563        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
13564        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
13565        Builtin::Type(&TYPE_UINT2),
13566        Builtin::Type(&TYPE_UINT2_ARRAY),
13567        Builtin::Type(&TYPE_UINT4),
13568        Builtin::Type(&TYPE_UINT4_ARRAY),
13569        Builtin::Type(&TYPE_UINT8),
13570        Builtin::Type(&TYPE_UINT8_ARRAY),
13571        Builtin::Type(&TYPE_MZ_TIMESTAMP),
13572        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
13573        Builtin::Type(&TYPE_INT4_RANGE),
13574        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
13575        Builtin::Type(&TYPE_INT8_RANGE),
13576        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
13577        Builtin::Type(&TYPE_DATE_RANGE),
13578        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
13579        Builtin::Type(&TYPE_NUM_RANGE),
13580        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
13581        Builtin::Type(&TYPE_TS_RANGE),
13582        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
13583        Builtin::Type(&TYPE_TSTZ_RANGE),
13584        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
13585        Builtin::Type(&TYPE_MZ_ACL_ITEM),
13586        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
13587        Builtin::Type(&TYPE_ACL_ITEM),
13588        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
13589        Builtin::Type(&TYPE_INTERNAL),
13590    ];
13591    for (schema, funcs) in &[
13592        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
13593        (
13594            INFORMATION_SCHEMA,
13595            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
13596        ),
13597        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
13598        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
13599        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
13600    ] {
13601        for (name, func) in funcs.iter() {
13602            builtins.push(Builtin::Func(BuiltinFunc {
13603                name,
13604                schema,
13605                inner: func,
13606            }));
13607        }
13608    }
13609    builtins.append(&mut vec![
13610        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
13611        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
13612        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
13613        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
13614        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
13615        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
13616        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
13617        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
13618        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
13619        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
13620        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
13621        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
13622        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
13623        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
13624        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
13625        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
13626        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
13627        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
13628        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
13629        Builtin::Log(&MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_RAW),
13630        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
13631        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
13632        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
13633        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
13634        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
13635        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
13636        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
13637        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
13638        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
13639        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
13640        Builtin::Table(&MZ_KAFKA_SINKS),
13641        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
13642        Builtin::Table(&MZ_KAFKA_SOURCES),
13643        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
13644        Builtin::Table(&MZ_DATABASES),
13645        Builtin::Table(&MZ_SCHEMAS),
13646        Builtin::Table(&MZ_COLUMNS),
13647        Builtin::Table(&MZ_INDEXES),
13648        Builtin::Table(&MZ_INDEX_COLUMNS),
13649        Builtin::Table(&MZ_TABLES),
13650        Builtin::Table(&MZ_SOURCES),
13651        Builtin::Table(&MZ_SOURCE_REFERENCES),
13652        Builtin::Table(&MZ_POSTGRES_SOURCES),
13653        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
13654        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
13655        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
13656        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
13657        Builtin::Table(&MZ_SINKS),
13658        Builtin::Table(&MZ_VIEWS),
13659        Builtin::Table(&MZ_MATERIALIZED_VIEWS),
13660        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
13661        Builtin::Table(&MZ_TYPES),
13662        Builtin::Table(&MZ_TYPE_PG_METADATA),
13663        Builtin::Table(&MZ_ARRAY_TYPES),
13664        Builtin::Table(&MZ_BASE_TYPES),
13665        Builtin::Table(&MZ_LIST_TYPES),
13666        Builtin::Table(&MZ_MAP_TYPES),
13667        Builtin::Table(&MZ_ROLES),
13668        Builtin::Table(&MZ_ROLE_MEMBERS),
13669        Builtin::Table(&MZ_ROLE_PARAMETERS),
13670        Builtin::Table(&MZ_PSEUDO_TYPES),
13671        Builtin::Table(&MZ_FUNCTIONS),
13672        Builtin::Table(&MZ_OPERATORS),
13673        Builtin::Table(&MZ_AGGREGATES),
13674        Builtin::Table(&MZ_CLUSTERS),
13675        Builtin::Table(&MZ_CLUSTER_WORKLOAD_CLASSES),
13676        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
13677        Builtin::Table(&MZ_SECRETS),
13678        Builtin::Table(&MZ_CONNECTIONS),
13679        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
13680        Builtin::Table(&MZ_CLUSTER_REPLICAS),
13681        Builtin::Table(&MZ_CLUSTER_REPLICA_METRICS),
13682        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
13683        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
13684        Builtin::Table(&MZ_CLUSTER_REPLICA_STATUSES),
13685        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
13686        Builtin::Table(&MZ_INTERNAL_CLUSTER_REPLICAS),
13687        Builtin::Table(&MZ_PENDING_CLUSTER_REPLICAS),
13688        Builtin::Table(&MZ_AUDIT_EVENTS),
13689        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
13690        Builtin::Table(&MZ_EGRESS_IPS),
13691        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
13692        Builtin::Table(&MZ_AWS_CONNECTIONS),
13693        Builtin::Table(&MZ_SUBSCRIPTIONS),
13694        Builtin::Table(&MZ_SESSIONS),
13695        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
13696        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
13697        Builtin::Table(&MZ_COMMENTS),
13698        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
13699        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
13700        Builtin::Table(&MZ_CONTINUAL_TASKS),
13701        Builtin::Table(&MZ_NETWORK_POLICIES),
13702        Builtin::Table(&MZ_NETWORK_POLICY_RULES),
13703        Builtin::View(&MZ_RELATIONS),
13704        Builtin::View(&MZ_OBJECT_OID_ALIAS),
13705        Builtin::View(&MZ_OBJECTS),
13706        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
13707        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
13708        Builtin::View(&MZ_OBJECT_HISTORY),
13709        Builtin::View(&MZ_OBJECT_LIFETIMES),
13710        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
13711        Builtin::View(&MZ_ARRANGEMENT_SHARING),
13712        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
13713        Builtin::View(&MZ_ARRANGEMENT_SIZES),
13714        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
13715        Builtin::View(&MZ_DATAFLOWS),
13716        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
13717        Builtin::View(&MZ_DATAFLOW_CHANNELS),
13718        Builtin::View(&MZ_DATAFLOW_OPERATORS),
13719        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
13720        Builtin::View(&MZ_MAPPABLE_OBJECTS),
13721        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
13722        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
13723        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
13724        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
13725        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
13726        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
13727        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
13728        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
13729        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
13730        Builtin::View(&MZ_COMPUTE_EXPORTS),
13731        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
13732        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
13733        Builtin::View(&MZ_COMPUTE_FRONTIERS),
13734        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
13735        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
13736        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
13737        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
13738        Builtin::View(&MZ_MESSAGE_COUNTS),
13739        Builtin::View(&MZ_ACTIVE_PEEKS),
13740        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
13741        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
13742        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
13743        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
13744        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
13745        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
13746        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
13747        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
13748        Builtin::View(&MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_PER_WORKER),
13749        Builtin::View(&MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM),
13750        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
13751        Builtin::View(&MZ_SCHEDULING_ELAPSED),
13752        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
13753        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
13754        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
13755        Builtin::View(&MZ_SHOW_COLUMNS),
13756        Builtin::View(&MZ_SHOW_CLUSTERS),
13757        Builtin::View(&MZ_SHOW_SECRETS),
13758        Builtin::View(&MZ_SHOW_DATABASES),
13759        Builtin::View(&MZ_SHOW_SCHEMAS),
13760        Builtin::View(&MZ_SHOW_TABLES),
13761        Builtin::View(&MZ_SHOW_VIEWS),
13762        Builtin::View(&MZ_SHOW_TYPES),
13763        Builtin::View(&MZ_SHOW_ROLES),
13764        Builtin::View(&MZ_SHOW_CONNECTIONS),
13765        Builtin::View(&MZ_SHOW_SOURCES),
13766        Builtin::View(&MZ_SHOW_SINKS),
13767        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
13768        Builtin::View(&MZ_SHOW_INDEXES),
13769        Builtin::View(&MZ_SHOW_CONTINUAL_TASKS),
13770        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
13771        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
13772        Builtin::View(&MZ_TIMEZONE_NAMES),
13773        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
13774        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
13775        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
13776        Builtin::View(&PG_NAMESPACE),
13777        Builtin::View(&PG_CLASS_ALL_DATABASES),
13778        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
13779        Builtin::View(&PG_CLASS),
13780        Builtin::View(&PG_DEPEND),
13781        Builtin::View(&PG_DATABASE),
13782        Builtin::View(&PG_INDEX),
13783        Builtin::View(&PG_TYPE_ALL_DATABASES),
13784        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
13785        Builtin::View(&PG_TYPE),
13786        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
13787        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
13788        Builtin::View(&PG_DESCRIPTION),
13789        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
13790        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
13791        Builtin::View(&PG_ATTRIBUTE),
13792        Builtin::View(&PG_PROC),
13793        Builtin::View(&PG_OPERATOR),
13794        Builtin::View(&PG_RANGE),
13795        Builtin::View(&PG_ENUM),
13796        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
13797        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
13798        Builtin::View(&PG_ATTRDEF),
13799        Builtin::View(&PG_SETTINGS),
13800        Builtin::View(&PG_AUTH_MEMBERS),
13801        Builtin::View(&PG_CONSTRAINT),
13802        Builtin::View(&PG_TABLES),
13803        Builtin::View(&PG_TABLESPACE),
13804        Builtin::View(&PG_ACCESS_METHODS),
13805        Builtin::View(&PG_LOCKS),
13806        Builtin::View(&PG_AUTHID),
13807        Builtin::View(&PG_ROLES),
13808        Builtin::View(&PG_USER),
13809        Builtin::View(&PG_VIEWS),
13810        Builtin::View(&PG_MATVIEWS),
13811        Builtin::View(&PG_COLLATION),
13812        Builtin::View(&PG_POLICY),
13813        Builtin::View(&PG_INHERITS),
13814        Builtin::View(&PG_AGGREGATE),
13815        Builtin::View(&PG_TRIGGER),
13816        Builtin::View(&PG_REWRITE),
13817        Builtin::View(&PG_EXTENSION),
13818        Builtin::View(&PG_EVENT_TRIGGER),
13819        Builtin::View(&PG_LANGUAGE),
13820        Builtin::View(&PG_SHDESCRIPTION),
13821        Builtin::View(&PG_INDEXES),
13822        Builtin::View(&PG_TIMEZONE_ABBREVS),
13823        Builtin::View(&PG_TIMEZONE_NAMES),
13824        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
13825        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
13826        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
13827        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
13828        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
13829        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
13830        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
13831        Builtin::View(&INFORMATION_SCHEMA_TABLES),
13832        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
13833        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
13834        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
13835        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
13836        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
13837        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
13838        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
13839        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
13840        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
13841        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
13842        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
13843        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
13844        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
13845        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
13846        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
13847        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
13848        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
13849        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
13850        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
13851        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
13852        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
13853        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
13854        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
13855        Builtin::View(&MZ_SINK_STATUSES),
13856        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
13857        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
13858        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
13859        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
13860        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
13861        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
13862        Builtin::Source(&MZ_SESSION_HISTORY),
13863        Builtin::Source(&MZ_SQL_TEXT),
13864        Builtin::View(&MZ_SQL_TEXT_REDACTED),
13865        Builtin::View(&MZ_RECENT_SQL_TEXT),
13866        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
13867        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
13868        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
13869        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
13870        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
13871        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
13872        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
13873        Builtin::View(&MZ_SOURCE_STATUSES),
13874        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
13875        Builtin::Source(&MZ_STORAGE_SHARDS),
13876        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
13877        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
13878        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
13879        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
13880        Builtin::View(&MZ_SOURCE_STATISTICS),
13881        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
13882        Builtin::View(&MZ_SINK_STATISTICS),
13883        Builtin::Index(&MZ_SINK_STATISTICS_IND),
13884        Builtin::View(&MZ_STORAGE_USAGE),
13885        Builtin::Source(&MZ_FRONTIERS),
13886        Builtin::View(&MZ_GLOBAL_FRONTIERS),
13887        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
13888        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
13889        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
13890        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
13891        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
13892        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
13893        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
13894        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
13895        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
13896        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
13897        Builtin::View(&MZ_MATERIALIZATION_LAG),
13898        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
13899        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
13900        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
13901        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
13902        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
13903        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
13904        Builtin::View(&MZ_LIR_MAPPING),
13905        Builtin::View(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
13906        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
13907        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
13908        Builtin::View(&MZ_HYDRATION_STATUSES),
13909        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
13910        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
13911        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
13912        Builtin::Index(&MZ_SHOW_DATABASES_IND),
13913        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
13914        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
13915        Builtin::Index(&MZ_SHOW_TABLES_IND),
13916        Builtin::Index(&MZ_SHOW_SOURCES_IND),
13917        Builtin::Index(&MZ_SHOW_VIEWS_IND),
13918        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
13919        Builtin::Index(&MZ_SHOW_SINKS_IND),
13920        Builtin::Index(&MZ_SHOW_TYPES_IND),
13921        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
13922        Builtin::Index(&MZ_SHOW_INDEXES_IND),
13923        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
13924        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
13925        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
13926        Builtin::Index(&MZ_SHOW_SECRETS_IND),
13927        Builtin::Index(&MZ_SHOW_ROLES_IND),
13928        Builtin::Index(&MZ_CLUSTERS_IND),
13929        Builtin::Index(&MZ_INDEXES_IND),
13930        Builtin::Index(&MZ_ROLES_IND),
13931        Builtin::Index(&MZ_SOURCES_IND),
13932        Builtin::Index(&MZ_SINKS_IND),
13933        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
13934        Builtin::Index(&MZ_CONTINUAL_TASKS_IND),
13935        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
13936        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
13937        Builtin::Index(&MZ_SINK_STATUSES_IND),
13938        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
13939        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
13940        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
13941        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
13942        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
13943        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
13944        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
13945        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
13946        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
13947        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
13948        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
13949        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
13950        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
13951        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
13952        Builtin::Index(&MZ_FRONTIERS_IND),
13953        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
13954        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
13955        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
13956        Builtin::Index(&MZ_COMMENTS_IND),
13957        Builtin::Index(&MZ_DATABASES_IND),
13958        Builtin::Index(&MZ_SCHEMAS_IND),
13959        Builtin::Index(&MZ_CONNECTIONS_IND),
13960        Builtin::Index(&MZ_TABLES_IND),
13961        Builtin::Index(&MZ_TYPES_IND),
13962        Builtin::Index(&MZ_OBJECTS_IND),
13963        Builtin::Index(&MZ_COLUMNS_IND),
13964        Builtin::Index(&MZ_SECRETS_IND),
13965        Builtin::Index(&MZ_VIEWS_IND),
13966        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
13967        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
13968        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
13969        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
13970        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
13971        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
13972        Builtin::Connection(&MZ_ANALYTICS),
13973        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT),
13974        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT),
13975        Builtin::ContinualTask(&MZ_WALLCLOCK_LAG_HISTORY_CT),
13976        Builtin::View(&MZ_INDEX_ADVICE),
13977    ]);
13978
13979    builtins.extend(notice::builtins());
13980
13981    builtins
13982});
13983pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
13984    &MZ_SYSTEM_ROLE,
13985    &MZ_SUPPORT_ROLE,
13986    &MZ_ANALYTICS_ROLE,
13987    &MZ_MONITOR_ROLE,
13988    &MZ_MONITOR_REDACTED,
13989];
13990pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
13991    &MZ_SYSTEM_CLUSTER,
13992    &MZ_CATALOG_SERVER_CLUSTER,
13993    &MZ_PROBE_CLUSTER,
13994    &MZ_SUPPORT_CLUSTER,
13995    &MZ_ANALYTICS_CLUSTER,
13996];
13997pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
13998    &MZ_SYSTEM_CLUSTER_REPLICA,
13999    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14000    &MZ_PROBE_CLUSTER_REPLICA,
14001];
14002
14003#[allow(non_snake_case)]
14004pub mod BUILTINS {
14005    use mz_sql::catalog::BuiltinsConfig;
14006
14007    use super::*;
14008
14009    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14010        BUILTINS_STATIC.iter().filter_map(|b| match b {
14011            Builtin::Log(log) => Some(*log),
14012            _ => None,
14013        })
14014    }
14015
14016    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14017        BUILTINS_STATIC.iter().filter_map(|b| match b {
14018            Builtin::Type(typ) => Some(*typ),
14019            _ => None,
14020        })
14021    }
14022
14023    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14024        BUILTINS_STATIC.iter().filter_map(|b| match b {
14025            Builtin::View(view) => Some(*view),
14026            _ => None,
14027        })
14028    }
14029
14030    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14031        BUILTINS_STATIC.iter().filter_map(|b| match b {
14032            Builtin::Func(func) => Some(func),
14033            _ => None,
14034        })
14035    }
14036
14037    pub fn iter(cfg: &BuiltinsConfig) -> impl Iterator<Item = &'static Builtin<NameReference>> {
14038        let include_continual_tasks = cfg.include_continual_tasks;
14039        BUILTINS_STATIC.iter().filter(move |x| match x {
14040            Builtin::ContinualTask(_) if !include_continual_tasks => false,
14041            _ => true,
14042        })
14043    }
14044}
14045
14046pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14047    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14048/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14049/// the builtin itself.
14050pub static BUILTIN_LOOKUP: LazyLock<
14051    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14052> = LazyLock::new(|| {
14053    // BUILTIN_LOOKUP is only ever used for lookups by key, it's not iterated,
14054    // so it's safe to include all of them, regardless of BuiltinConfig. We
14055    // enforce this statically by using the mz_ore HashMap which disallows
14056    // iteration.
14057    BUILTINS_STATIC
14058        .iter()
14059        .enumerate()
14060        .map(|(idx, builtin)| {
14061            (
14062                SystemObjectDescription {
14063                    schema_name: builtin.schema().to_string(),
14064                    object_type: builtin.catalog_item_type(),
14065                    object_name: builtin.name().to_string(),
14066                },
14067                (idx, builtin),
14068            )
14069        })
14070        .collect()
14071});
14072
14073#[mz_ore::test]
14074#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14075fn test_builtin_type_schema() {
14076    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14077
14078    for typ in BUILTINS::types() {
14079        if typ.oid < FIRST_MATERIALIZE_OID {
14080            assert_eq!(
14081                typ.schema, PG_CATALOG_SCHEMA,
14082                "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14083            );
14084        } else {
14085            // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the mz_catalog
14086            // schema.
14087            assert_eq!(
14088                typ.schema, MZ_CATALOG_SCHEMA,
14089                "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14090            );
14091        }
14092    }
14093}