Skip to main content

mz_catalog/
builtin.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Built-in catalog items.
11//!
12//! Builtins exist in the `mz_catalog` ambient schema. They are automatically
13//! installed into the catalog when it is opened. Their definitions are not
14//! persisted in the catalog, but hardcoded in this module. This makes it easy
15//! to add new builtins, or change the definition of existing builtins, in new
16//! versions of Materialize.
17//!
18//! Builtin's names, columns, and types are part of the stable API of
19//! Materialize. Be careful to maintain backwards compatibility when changing
20//! definitions of existing builtins!
21//!
22//! More information about builtin system tables and types can be found in
23//! <https://materialize.com/docs/sql/system-catalog/>.
24
25pub mod notice;
26
27use std::collections::BTreeMap;
28use std::hash::Hash;
29use std::string::ToString;
30use std::sync::LazyLock;
31
32use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
33use mz_ore::collections::HashMap;
34use mz_pgrepr::oid;
35use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
36use mz_repr::adt::numeric::NumericMaxScale;
37use mz_repr::namespaces::{
38    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_INTROSPECTION_SCHEMA,
39    MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA,
40};
41use mz_repr::role_id::RoleId;
42use mz_repr::{RelationDesc, SqlRelationType, SqlScalarType};
43use mz_sql::catalog::RoleAttributesRaw;
44use mz_sql::catalog::{
45    CatalogItemType, CatalogType, CatalogTypeDetails, CatalogTypePgMetadata, NameReference,
46    ObjectType, SystemObjectType, TypeReference,
47};
48use mz_sql::rbac;
49use mz_sql::session::user::{
50    ANALYTICS_USER_NAME, MZ_ANALYTICS_ROLE_ID, MZ_MONITOR_REDACTED_ROLE_ID, MZ_MONITOR_ROLE_ID,
51    MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID, SUPPORT_USER_NAME, SYSTEM_USER_NAME,
52};
53use mz_storage_client::controller::IntrospectionType;
54use mz_storage_client::healthcheck::WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC;
55use mz_storage_client::healthcheck::{
56    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_PREPARED_STATEMENT_HISTORY_DESC,
57    MZ_SESSION_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC, MZ_SOURCE_STATUS_HISTORY_DESC,
58    MZ_SQL_TEXT_DESC, MZ_STATEMENT_EXECUTION_HISTORY_DESC, REPLICA_METRICS_HISTORY_DESC,
59    REPLICA_STATUS_HISTORY_DESC, WALLCLOCK_LAG_HISTORY_DESC,
60};
61use mz_storage_client::statistics::{MZ_SINK_STATISTICS_RAW_DESC, MZ_SOURCE_STATISTICS_RAW_DESC};
62use serde::Serialize;
63
64use crate::durable::objects::SystemObjectDescription;
65
66pub const BUILTIN_PREFIXES: &[&str] = &["mz_", "pg_", "external_"];
67const BUILTIN_CLUSTER_REPLICA_NAME: &str = "r1";
68
69/// A sentinel used in place of a fingerprint that indicates that a builtin
70/// object is runtime alterable. Runtime alterable objects don't have meaningful
71/// fingerprints because they may have been intentionally changed by the user
72/// after creation.
73// NOTE(benesch): ideally we'd use a fingerprint type that used a sum type
74// rather than a loosely typed string to represent the runtime alterable
75// state like so:
76//
77//     enum Fingerprint {
78//         SqlText(String),
79//         RuntimeAlterable,
80//     }
81//
82// However, that would entail a complicated migration for the existing system object
83// mapping collection stored on disk.
84pub const RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL: &str = "<RUNTIME-ALTERABLE>";
85
86#[derive(Clone, Debug)]
87pub enum Builtin<T: 'static + TypeReference> {
88    Log(&'static BuiltinLog),
89    Table(&'static BuiltinTable),
90    View(&'static BuiltinView),
91    Type(&'static BuiltinType<T>),
92    Func(BuiltinFunc),
93    Source(&'static BuiltinSource),
94    ContinualTask(&'static BuiltinContinualTask),
95    Index(&'static BuiltinIndex),
96    Connection(&'static BuiltinConnection),
97}
98
99impl<T: TypeReference> Builtin<T> {
100    pub fn name(&self) -> &'static str {
101        match self {
102            Builtin::Log(log) => log.name,
103            Builtin::Table(table) => table.name,
104            Builtin::View(view) => view.name,
105            Builtin::Type(typ) => typ.name,
106            Builtin::Func(func) => func.name,
107            Builtin::Source(coll) => coll.name,
108            Builtin::ContinualTask(ct) => ct.name,
109            Builtin::Index(index) => index.name,
110            Builtin::Connection(connection) => connection.name,
111        }
112    }
113
114    pub fn schema(&self) -> &'static str {
115        match self {
116            Builtin::Log(log) => log.schema,
117            Builtin::Table(table) => table.schema,
118            Builtin::View(view) => view.schema,
119            Builtin::Type(typ) => typ.schema,
120            Builtin::Func(func) => func.schema,
121            Builtin::Source(coll) => coll.schema,
122            Builtin::ContinualTask(ct) => ct.schema,
123            Builtin::Index(index) => index.schema,
124            Builtin::Connection(connection) => connection.schema,
125        }
126    }
127
128    pub fn catalog_item_type(&self) -> CatalogItemType {
129        match self {
130            Builtin::Log(_) => CatalogItemType::Source,
131            Builtin::Source(_) => CatalogItemType::Source,
132            Builtin::ContinualTask(_) => CatalogItemType::ContinualTask,
133            Builtin::Table(_) => CatalogItemType::Table,
134            Builtin::View(_) => CatalogItemType::View,
135            Builtin::Type(_) => CatalogItemType::Type,
136            Builtin::Func(_) => CatalogItemType::Func,
137            Builtin::Index(_) => CatalogItemType::Index,
138            Builtin::Connection(_) => CatalogItemType::Connection,
139        }
140    }
141
142    /// Whether the object can be altered at runtime by its owner.
143    pub fn runtime_alterable(&self) -> bool {
144        match self {
145            Builtin::Connection(c) => c.runtime_alterable,
146            _ => false,
147        }
148    }
149}
150
151#[derive(Clone, Debug, Hash, Serialize)]
152pub struct BuiltinLog {
153    pub variant: LogVariant,
154    pub name: &'static str,
155    pub schema: &'static str,
156    pub oid: u32,
157    /// ACL items to apply to the object
158    pub access: Vec<MzAclItem>,
159}
160
161#[derive(Clone, Hash, Debug, PartialEq, Eq)]
162pub struct BuiltinTable {
163    pub name: &'static str,
164    pub schema: &'static str,
165    pub oid: u32,
166    pub desc: RelationDesc,
167    pub column_comments: BTreeMap<&'static str, &'static str>,
168    /// Whether the table's retention policy is controlled by
169    /// the system variable `METRICS_RETENTION`
170    pub is_retained_metrics_object: bool,
171    /// ACL items to apply to the object
172    pub access: Vec<MzAclItem>,
173}
174
175#[derive(Clone, Debug, Hash, Serialize)]
176pub struct BuiltinSource {
177    pub name: &'static str,
178    pub schema: &'static str,
179    pub oid: u32,
180    pub desc: RelationDesc,
181    pub column_comments: BTreeMap<&'static str, &'static str>,
182    pub data_source: IntrospectionType,
183    /// Whether the source's retention policy is controlled by
184    /// the system variable `METRICS_RETENTION`
185    pub is_retained_metrics_object: bool,
186    /// ACL items to apply to the object
187    pub access: Vec<MzAclItem>,
188}
189
190#[derive(Hash, Debug, PartialEq, Eq)]
191pub struct BuiltinContinualTask {
192    pub name: &'static str,
193    pub schema: &'static str,
194    pub oid: u32,
195    pub desc: RelationDesc,
196    pub sql: &'static str,
197    /// ACL items to apply to the object
198    pub access: Vec<MzAclItem>,
199}
200
201#[derive(Hash, Debug)]
202pub struct BuiltinView {
203    pub name: &'static str,
204    pub schema: &'static str,
205    pub oid: u32,
206    pub desc: RelationDesc,
207    pub column_comments: BTreeMap<&'static str, &'static str>,
208    pub sql: &'static str,
209    /// ACL items to apply to the object
210    pub access: Vec<MzAclItem>,
211}
212
213impl BuiltinView {
214    pub fn create_sql(&self) -> String {
215        format!("CREATE VIEW {}.{} AS {}", self.schema, self.name, self.sql)
216    }
217}
218
219#[derive(Debug)]
220pub struct BuiltinType<T: TypeReference> {
221    pub name: &'static str,
222    pub schema: &'static str,
223    pub oid: u32,
224    pub details: CatalogTypeDetails<T>,
225}
226
227#[derive(Clone, Debug)]
228pub struct BuiltinFunc {
229    pub schema: &'static str,
230    pub name: &'static str,
231    pub inner: &'static mz_sql::func::Func,
232}
233
234/// Note: When creating a built-in index, it's usually best to choose a key that has only one
235/// component. For example, if you created an index
236/// `ON mz_internal.mz_object_lifetimes (id, object_type)`, then this index couldn't be used for a
237/// lookup for `WHERE object_type = ...`, and neither for joins keyed on just `id`.
238/// See <https://materialize.com/docs/transform-data/optimization/#matching-multi-column-indexes-to-multi-column-where-clauses>
239#[derive(Debug)]
240pub struct BuiltinIndex {
241    pub name: &'static str,
242    pub schema: &'static str,
243    pub oid: u32,
244    /// SQL fragment for the index, following `CREATE INDEX [name]`
245    ///
246    /// Format: `IN CLUSTER [cluster_name] ON [table_name] ([column_exprs])`
247    pub sql: &'static str,
248    pub is_retained_metrics_object: bool,
249}
250
251impl BuiltinIndex {
252    pub fn create_sql(&self) -> String {
253        format!("CREATE INDEX {}\n{}", self.name, self.sql)
254    }
255}
256
257impl BuiltinContinualTask {
258    pub fn create_sql(&self) -> String {
259        format!(
260            "CREATE CONTINUAL TASK {}.{}\n{}",
261            self.schema, self.name, self.sql
262        )
263    }
264}
265
266#[derive(Hash, Debug)]
267pub struct BuiltinConnection {
268    pub name: &'static str,
269    pub schema: &'static str,
270    pub oid: u32,
271    pub sql: &'static str,
272    pub access: &'static [MzAclItem],
273    pub owner_id: &'static RoleId,
274    /// Whether the object can be altered at runtime by its owner.
275    ///
276    /// Note that when `runtime_alterable` is true, changing the `sql` in future
277    /// versions does not trigger a migration.
278    pub runtime_alterable: bool,
279}
280
281#[derive(Clone, Debug)]
282pub struct BuiltinRole {
283    pub id: RoleId,
284    /// Name of the builtin role.
285    ///
286    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
287    pub name: &'static str,
288    pub oid: u32,
289    pub attributes: RoleAttributesRaw,
290}
291
292#[derive(Clone, Debug)]
293pub struct BuiltinCluster {
294    /// Name of the cluster.
295    ///
296    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
297    pub name: &'static str,
298    pub privileges: &'static [MzAclItem],
299    pub owner_id: &'static RoleId,
300}
301
302#[derive(Clone, Debug, PartialEq, Eq)]
303pub struct BuiltinClusterReplica {
304    /// Name of the compute replica.
305    pub name: &'static str,
306    /// Name of the cluster that this replica belongs to.
307    pub cluster_name: &'static str,
308}
309
310/// Uniquely identifies the definition of a builtin object.
311pub trait Fingerprint {
312    fn fingerprint(&self) -> String;
313}
314
315impl<T: TypeReference> Fingerprint for &Builtin<T> {
316    fn fingerprint(&self) -> String {
317        match self {
318            Builtin::Log(log) => log.fingerprint(),
319            Builtin::Table(table) => table.fingerprint(),
320            Builtin::View(view) => view.fingerprint(),
321            Builtin::Type(typ) => typ.fingerprint(),
322            Builtin::Func(func) => func.fingerprint(),
323            Builtin::Source(coll) => coll.fingerprint(),
324            Builtin::ContinualTask(ct) => ct.fingerprint(),
325            Builtin::Index(index) => index.fingerprint(),
326            Builtin::Connection(connection) => connection.fingerprint(),
327        }
328    }
329}
330
331// Types and Funcs never change fingerprints so we just return constant 0
332impl<T: TypeReference> Fingerprint for &BuiltinType<T> {
333    fn fingerprint(&self) -> String {
334        "".to_string()
335    }
336}
337
338impl Fingerprint for &BuiltinFunc {
339    fn fingerprint(&self) -> String {
340        "".to_string()
341    }
342}
343
344impl Fingerprint for &BuiltinLog {
345    fn fingerprint(&self) -> String {
346        self.variant.desc().fingerprint()
347    }
348}
349
350impl Fingerprint for &BuiltinTable {
351    fn fingerprint(&self) -> String {
352        self.desc.fingerprint()
353    }
354}
355
356impl Fingerprint for &BuiltinView {
357    fn fingerprint(&self) -> String {
358        self.sql.to_string()
359    }
360}
361
362impl Fingerprint for &BuiltinSource {
363    fn fingerprint(&self) -> String {
364        self.desc.fingerprint()
365    }
366}
367
368impl Fingerprint for &BuiltinContinualTask {
369    fn fingerprint(&self) -> String {
370        self.create_sql()
371    }
372}
373
374impl Fingerprint for &BuiltinIndex {
375    fn fingerprint(&self) -> String {
376        self.create_sql()
377    }
378}
379
380impl Fingerprint for &BuiltinConnection {
381    fn fingerprint(&self) -> String {
382        self.sql.to_string()
383    }
384}
385
386impl Fingerprint for RelationDesc {
387    fn fingerprint(&self) -> String {
388        self.typ().fingerprint()
389    }
390}
391
392impl Fingerprint for SqlRelationType {
393    fn fingerprint(&self) -> String {
394        serde_json::to_string(self).expect("serialization cannot fail")
395    }
396}
397
398// Builtin definitions below. Ensure you add new builtins to the `BUILTINS` map.
399//
400// You SHOULD NOT delete a builtin. If you do, you will break any downstream
401// user objects that depended on the builtin.
402//
403// Builtins are loaded in dependency order, so a builtin must appear in `BUILTINS`
404// before any items it depends upon.
405//
406// WARNING: if you change the definition of an existing builtin item, you must
407// be careful to maintain backwards compatibility! Adding new columns is safe.
408// Removing a column, changing the name of a column, or changing the type of a
409// column is not safe, as persisted user views may depend upon that column.
410
411// The following types are the list of builtin data types available
412// in Materialize. This list is derived from the `pg_type` table in PostgreSQL.
413//
414// Builtin types cannot be created, updated, or deleted. Their OIDs
415// are static, unlike other objects, to match the type OIDs defined by Postgres.
416
417pub const TYPE_BOOL: BuiltinType<NameReference> = BuiltinType {
418    name: "bool",
419    schema: PG_CATALOG_SCHEMA,
420    oid: oid::TYPE_BOOL_OID,
421    details: CatalogTypeDetails {
422        typ: CatalogType::Bool,
423        array_id: None,
424        pg_metadata: Some(CatalogTypePgMetadata {
425            typinput_oid: 1242,
426            typreceive_oid: 2436,
427        }),
428    },
429};
430
431pub const TYPE_BYTEA: BuiltinType<NameReference> = BuiltinType {
432    name: "bytea",
433    schema: PG_CATALOG_SCHEMA,
434    oid: oid::TYPE_BYTEA_OID,
435    details: CatalogTypeDetails {
436        typ: CatalogType::Bytes,
437        array_id: None,
438        pg_metadata: Some(CatalogTypePgMetadata {
439            typinput_oid: 1244,
440            typreceive_oid: 2412,
441        }),
442    },
443};
444
445pub const TYPE_INT8: BuiltinType<NameReference> = BuiltinType {
446    name: "int8",
447    schema: PG_CATALOG_SCHEMA,
448    oid: oid::TYPE_INT8_OID,
449    details: CatalogTypeDetails {
450        typ: CatalogType::Int64,
451        array_id: None,
452        pg_metadata: Some(CatalogTypePgMetadata {
453            typinput_oid: 460,
454            typreceive_oid: 2408,
455        }),
456    },
457};
458
459pub const TYPE_INT4: BuiltinType<NameReference> = BuiltinType {
460    name: "int4",
461    schema: PG_CATALOG_SCHEMA,
462    oid: oid::TYPE_INT4_OID,
463    details: CatalogTypeDetails {
464        typ: CatalogType::Int32,
465        array_id: None,
466        pg_metadata: Some(CatalogTypePgMetadata {
467            typinput_oid: 42,
468            typreceive_oid: 2406,
469        }),
470    },
471};
472
473pub const TYPE_TEXT: BuiltinType<NameReference> = BuiltinType {
474    name: "text",
475    schema: PG_CATALOG_SCHEMA,
476    oid: oid::TYPE_TEXT_OID,
477    details: CatalogTypeDetails {
478        typ: CatalogType::String,
479        array_id: None,
480        pg_metadata: Some(CatalogTypePgMetadata {
481            typinput_oid: 46,
482            typreceive_oid: 2414,
483        }),
484    },
485};
486
487pub const TYPE_OID: BuiltinType<NameReference> = BuiltinType {
488    name: "oid",
489    schema: PG_CATALOG_SCHEMA,
490    oid: oid::TYPE_OID_OID,
491    details: CatalogTypeDetails {
492        typ: CatalogType::Oid,
493        array_id: None,
494        pg_metadata: Some(CatalogTypePgMetadata {
495            typinput_oid: 1798,
496            typreceive_oid: 2418,
497        }),
498    },
499};
500
501pub const TYPE_FLOAT4: BuiltinType<NameReference> = BuiltinType {
502    name: "float4",
503    schema: PG_CATALOG_SCHEMA,
504    oid: oid::TYPE_FLOAT4_OID,
505    details: CatalogTypeDetails {
506        typ: CatalogType::Float32,
507        array_id: None,
508        pg_metadata: Some(CatalogTypePgMetadata {
509            typinput_oid: 200,
510            typreceive_oid: 2424,
511        }),
512    },
513};
514
515pub const TYPE_FLOAT8: BuiltinType<NameReference> = BuiltinType {
516    name: "float8",
517    schema: PG_CATALOG_SCHEMA,
518    oid: oid::TYPE_FLOAT8_OID,
519    details: CatalogTypeDetails {
520        typ: CatalogType::Float64,
521        array_id: None,
522        pg_metadata: Some(CatalogTypePgMetadata {
523            typinput_oid: 214,
524            typreceive_oid: 2426,
525        }),
526    },
527};
528
529pub const TYPE_BOOL_ARRAY: BuiltinType<NameReference> = BuiltinType {
530    name: "_bool",
531    schema: PG_CATALOG_SCHEMA,
532    oid: oid::TYPE_BOOL_ARRAY_OID,
533    details: CatalogTypeDetails {
534        typ: CatalogType::Array {
535            element_reference: TYPE_BOOL.name,
536        },
537        array_id: None,
538        pg_metadata: Some(CatalogTypePgMetadata {
539            typinput_oid: 750,
540            typreceive_oid: 2400,
541        }),
542    },
543};
544
545pub const TYPE_BYTEA_ARRAY: BuiltinType<NameReference> = BuiltinType {
546    name: "_bytea",
547    schema: PG_CATALOG_SCHEMA,
548    oid: oid::TYPE_BYTEA_ARRAY_OID,
549    details: CatalogTypeDetails {
550        typ: CatalogType::Array {
551            element_reference: TYPE_BYTEA.name,
552        },
553        array_id: None,
554        pg_metadata: Some(CatalogTypePgMetadata {
555            typinput_oid: 750,
556            typreceive_oid: 2400,
557        }),
558    },
559};
560
561pub const TYPE_INT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
562    name: "_int4",
563    schema: PG_CATALOG_SCHEMA,
564    oid: oid::TYPE_INT4_ARRAY_OID,
565    details: CatalogTypeDetails {
566        typ: CatalogType::Array {
567            element_reference: TYPE_INT4.name,
568        },
569        array_id: None,
570        pg_metadata: Some(CatalogTypePgMetadata {
571            typinput_oid: 750,
572            typreceive_oid: 2400,
573        }),
574    },
575};
576
577pub const TYPE_TEXT_ARRAY: BuiltinType<NameReference> = BuiltinType {
578    name: "_text",
579    schema: PG_CATALOG_SCHEMA,
580    oid: oid::TYPE_TEXT_ARRAY_OID,
581    details: CatalogTypeDetails {
582        typ: CatalogType::Array {
583            element_reference: TYPE_TEXT.name,
584        },
585        array_id: None,
586        pg_metadata: Some(CatalogTypePgMetadata {
587            typinput_oid: 750,
588            typreceive_oid: 2400,
589        }),
590    },
591};
592
593pub const TYPE_INT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
594    name: "_int8",
595    schema: PG_CATALOG_SCHEMA,
596    oid: oid::TYPE_INT8_ARRAY_OID,
597    details: CatalogTypeDetails {
598        typ: CatalogType::Array {
599            element_reference: TYPE_INT8.name,
600        },
601        array_id: None,
602        pg_metadata: Some(CatalogTypePgMetadata {
603            typinput_oid: 750,
604            typreceive_oid: 2400,
605        }),
606    },
607};
608
609pub const TYPE_FLOAT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
610    name: "_float4",
611    schema: PG_CATALOG_SCHEMA,
612    oid: oid::TYPE_FLOAT4_ARRAY_OID,
613    details: CatalogTypeDetails {
614        typ: CatalogType::Array {
615            element_reference: TYPE_FLOAT4.name,
616        },
617        array_id: None,
618        pg_metadata: Some(CatalogTypePgMetadata {
619            typinput_oid: 750,
620            typreceive_oid: 2400,
621        }),
622    },
623};
624
625pub const TYPE_FLOAT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
626    name: "_float8",
627    schema: PG_CATALOG_SCHEMA,
628    oid: oid::TYPE_FLOAT8_ARRAY_OID,
629    details: CatalogTypeDetails {
630        typ: CatalogType::Array {
631            element_reference: TYPE_FLOAT8.name,
632        },
633        array_id: None,
634        pg_metadata: Some(CatalogTypePgMetadata {
635            typinput_oid: 750,
636            typreceive_oid: 2400,
637        }),
638    },
639};
640
641pub const TYPE_OID_ARRAY: BuiltinType<NameReference> = BuiltinType {
642    name: "_oid",
643    schema: PG_CATALOG_SCHEMA,
644    oid: oid::TYPE_OID_ARRAY_OID,
645    details: CatalogTypeDetails {
646        typ: CatalogType::Array {
647            element_reference: TYPE_OID.name,
648        },
649        array_id: None,
650        pg_metadata: Some(CatalogTypePgMetadata {
651            typinput_oid: 750,
652            typreceive_oid: 2400,
653        }),
654    },
655};
656
657pub const TYPE_DATE: BuiltinType<NameReference> = BuiltinType {
658    name: "date",
659    schema: PG_CATALOG_SCHEMA,
660    oid: oid::TYPE_DATE_OID,
661    details: CatalogTypeDetails {
662        typ: CatalogType::Date,
663        array_id: None,
664        pg_metadata: Some(CatalogTypePgMetadata {
665            typinput_oid: 1084,
666            typreceive_oid: 2468,
667        }),
668    },
669};
670
671pub const TYPE_TIME: BuiltinType<NameReference> = BuiltinType {
672    name: "time",
673    schema: PG_CATALOG_SCHEMA,
674    oid: oid::TYPE_TIME_OID,
675    details: CatalogTypeDetails {
676        typ: CatalogType::Time,
677        array_id: None,
678        pg_metadata: Some(CatalogTypePgMetadata {
679            typinput_oid: 1143,
680            typreceive_oid: 2470,
681        }),
682    },
683};
684
685pub const TYPE_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
686    name: "timestamp",
687    schema: PG_CATALOG_SCHEMA,
688    oid: oid::TYPE_TIMESTAMP_OID,
689    details: CatalogTypeDetails {
690        typ: CatalogType::Timestamp,
691        array_id: None,
692        pg_metadata: Some(CatalogTypePgMetadata {
693            typinput_oid: 1312,
694            typreceive_oid: 2474,
695        }),
696    },
697};
698
699pub const TYPE_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
700    name: "_timestamp",
701    schema: PG_CATALOG_SCHEMA,
702    oid: oid::TYPE_TIMESTAMP_ARRAY_OID,
703    details: CatalogTypeDetails {
704        typ: CatalogType::Array {
705            element_reference: TYPE_TIMESTAMP.name,
706        },
707        array_id: None,
708        pg_metadata: Some(CatalogTypePgMetadata {
709            typinput_oid: 750,
710            typreceive_oid: 2400,
711        }),
712    },
713};
714
715pub const TYPE_DATE_ARRAY: BuiltinType<NameReference> = BuiltinType {
716    name: "_date",
717    schema: PG_CATALOG_SCHEMA,
718    oid: oid::TYPE_DATE_ARRAY_OID,
719    details: CatalogTypeDetails {
720        typ: CatalogType::Array {
721            element_reference: TYPE_DATE.name,
722        },
723        array_id: None,
724        pg_metadata: Some(CatalogTypePgMetadata {
725            typinput_oid: 750,
726            typreceive_oid: 2400,
727        }),
728    },
729};
730
731pub const TYPE_TIME_ARRAY: BuiltinType<NameReference> = BuiltinType {
732    name: "_time",
733    schema: PG_CATALOG_SCHEMA,
734    oid: oid::TYPE_TIME_ARRAY_OID,
735    details: CatalogTypeDetails {
736        typ: CatalogType::Array {
737            element_reference: TYPE_TIME.name,
738        },
739        array_id: None,
740        pg_metadata: Some(CatalogTypePgMetadata {
741            typinput_oid: 750,
742            typreceive_oid: 2400,
743        }),
744    },
745};
746
747pub const TYPE_TIMESTAMPTZ: BuiltinType<NameReference> = BuiltinType {
748    name: "timestamptz",
749    schema: PG_CATALOG_SCHEMA,
750    oid: oid::TYPE_TIMESTAMPTZ_OID,
751    details: CatalogTypeDetails {
752        typ: CatalogType::TimestampTz,
753        array_id: None,
754        pg_metadata: Some(CatalogTypePgMetadata {
755            typinput_oid: 1150,
756            typreceive_oid: 2476,
757        }),
758    },
759};
760
761pub const TYPE_TIMESTAMPTZ_ARRAY: BuiltinType<NameReference> = BuiltinType {
762    name: "_timestamptz",
763    schema: PG_CATALOG_SCHEMA,
764    oid: oid::TYPE_TIMESTAMPTZ_ARRAY_OID,
765    details: CatalogTypeDetails {
766        typ: CatalogType::Array {
767            element_reference: TYPE_TIMESTAMPTZ.name,
768        },
769        array_id: None,
770        pg_metadata: Some(CatalogTypePgMetadata {
771            typinput_oid: 750,
772            typreceive_oid: 2400,
773        }),
774    },
775};
776
777pub const TYPE_INTERVAL: BuiltinType<NameReference> = BuiltinType {
778    name: "interval",
779    schema: PG_CATALOG_SCHEMA,
780    oid: oid::TYPE_INTERVAL_OID,
781    details: CatalogTypeDetails {
782        typ: CatalogType::Interval,
783        array_id: None,
784        pg_metadata: Some(CatalogTypePgMetadata {
785            typinput_oid: 1160,
786            typreceive_oid: 2478,
787        }),
788    },
789};
790
791pub const TYPE_INTERVAL_ARRAY: BuiltinType<NameReference> = BuiltinType {
792    name: "_interval",
793    schema: PG_CATALOG_SCHEMA,
794    oid: oid::TYPE_INTERVAL_ARRAY_OID,
795    details: CatalogTypeDetails {
796        typ: CatalogType::Array {
797            element_reference: TYPE_INTERVAL.name,
798        },
799        array_id: None,
800        pg_metadata: Some(CatalogTypePgMetadata {
801            typinput_oid: 750,
802            typreceive_oid: 2400,
803        }),
804    },
805};
806
807pub const TYPE_NAME: BuiltinType<NameReference> = BuiltinType {
808    name: "name",
809    schema: PG_CATALOG_SCHEMA,
810    oid: oid::TYPE_NAME_OID,
811    details: CatalogTypeDetails {
812        typ: CatalogType::PgLegacyName,
813        array_id: None,
814        pg_metadata: Some(CatalogTypePgMetadata {
815            typinput_oid: 34,
816            typreceive_oid: 2422,
817        }),
818    },
819};
820
821pub const TYPE_NAME_ARRAY: BuiltinType<NameReference> = BuiltinType {
822    name: "_name",
823    schema: PG_CATALOG_SCHEMA,
824    oid: oid::TYPE_NAME_ARRAY_OID,
825    details: CatalogTypeDetails {
826        typ: CatalogType::Array {
827            element_reference: TYPE_NAME.name,
828        },
829        array_id: None,
830        pg_metadata: Some(CatalogTypePgMetadata {
831            typinput_oid: 750,
832            typreceive_oid: 2400,
833        }),
834    },
835};
836
837pub const TYPE_NUMERIC: BuiltinType<NameReference> = BuiltinType {
838    name: "numeric",
839    schema: PG_CATALOG_SCHEMA,
840    oid: oid::TYPE_NUMERIC_OID,
841    details: CatalogTypeDetails {
842        typ: CatalogType::Numeric,
843        array_id: None,
844        pg_metadata: Some(CatalogTypePgMetadata {
845            typinput_oid: 1701,
846            typreceive_oid: 2460,
847        }),
848    },
849};
850
851pub const TYPE_NUMERIC_ARRAY: BuiltinType<NameReference> = BuiltinType {
852    name: "_numeric",
853    schema: PG_CATALOG_SCHEMA,
854    oid: oid::TYPE_NUMERIC_ARRAY_OID,
855    details: CatalogTypeDetails {
856        typ: CatalogType::Array {
857            element_reference: TYPE_NUMERIC.name,
858        },
859        array_id: None,
860        pg_metadata: Some(CatalogTypePgMetadata {
861            typinput_oid: 750,
862            typreceive_oid: 2400,
863        }),
864    },
865};
866
867pub const TYPE_RECORD: BuiltinType<NameReference> = BuiltinType {
868    name: "record",
869    schema: PG_CATALOG_SCHEMA,
870    oid: oid::TYPE_RECORD_OID,
871    details: CatalogTypeDetails {
872        typ: CatalogType::Pseudo,
873        array_id: None,
874        pg_metadata: Some(CatalogTypePgMetadata {
875            typinput_oid: 2290,
876            typreceive_oid: 2402,
877        }),
878    },
879};
880
881pub const TYPE_RECORD_ARRAY: BuiltinType<NameReference> = BuiltinType {
882    name: "_record",
883    schema: PG_CATALOG_SCHEMA,
884    oid: oid::TYPE_RECORD_ARRAY_OID,
885    details: CatalogTypeDetails {
886        typ: CatalogType::Array {
887            element_reference: TYPE_RECORD.name,
888        },
889        array_id: None,
890        pg_metadata: Some(CatalogTypePgMetadata {
891            typinput_oid: 750,
892            typreceive_oid: 2400,
893        }),
894    },
895};
896
897pub const TYPE_UUID: BuiltinType<NameReference> = BuiltinType {
898    name: "uuid",
899    schema: PG_CATALOG_SCHEMA,
900    oid: oid::TYPE_UUID_OID,
901    details: CatalogTypeDetails {
902        typ: CatalogType::Uuid,
903        array_id: None,
904        pg_metadata: Some(CatalogTypePgMetadata {
905            typinput_oid: 2952,
906            typreceive_oid: 2961,
907        }),
908    },
909};
910
911pub const TYPE_UUID_ARRAY: BuiltinType<NameReference> = BuiltinType {
912    name: "_uuid",
913    schema: PG_CATALOG_SCHEMA,
914    oid: oid::TYPE_UUID_ARRAY_OID,
915    details: CatalogTypeDetails {
916        typ: CatalogType::Array {
917            element_reference: TYPE_UUID.name,
918        },
919        array_id: None,
920        pg_metadata: Some(CatalogTypePgMetadata {
921            typinput_oid: 750,
922            typreceive_oid: 2400,
923        }),
924    },
925};
926
927pub const TYPE_JSONB: BuiltinType<NameReference> = BuiltinType {
928    name: "jsonb",
929    schema: PG_CATALOG_SCHEMA,
930    oid: oid::TYPE_JSONB_OID,
931    details: CatalogTypeDetails {
932        typ: CatalogType::Jsonb,
933        array_id: None,
934        pg_metadata: Some(CatalogTypePgMetadata {
935            typinput_oid: 3806,
936            typreceive_oid: 3805,
937        }),
938    },
939};
940
941pub const TYPE_JSONB_ARRAY: BuiltinType<NameReference> = BuiltinType {
942    name: "_jsonb",
943    schema: PG_CATALOG_SCHEMA,
944    oid: oid::TYPE_JSONB_ARRAY_OID,
945    details: CatalogTypeDetails {
946        typ: CatalogType::Array {
947            element_reference: TYPE_JSONB.name,
948        },
949        array_id: None,
950        pg_metadata: Some(CatalogTypePgMetadata {
951            typinput_oid: 750,
952            typreceive_oid: 2400,
953        }),
954    },
955};
956
957pub const TYPE_ANY: BuiltinType<NameReference> = BuiltinType {
958    name: "any",
959    schema: PG_CATALOG_SCHEMA,
960    oid: oid::TYPE_ANY_OID,
961    details: CatalogTypeDetails {
962        typ: CatalogType::Pseudo,
963        array_id: None,
964        pg_metadata: Some(CatalogTypePgMetadata {
965            typinput_oid: 2294,
966            typreceive_oid: 0,
967        }),
968    },
969};
970
971pub const TYPE_ANYARRAY: BuiltinType<NameReference> = BuiltinType {
972    name: "anyarray",
973    schema: PG_CATALOG_SCHEMA,
974    oid: oid::TYPE_ANYARRAY_OID,
975    details: CatalogTypeDetails {
976        typ: CatalogType::Pseudo,
977        array_id: None,
978        pg_metadata: Some(CatalogTypePgMetadata {
979            typinput_oid: 2296,
980            typreceive_oid: 2502,
981        }),
982    },
983};
984
985pub const TYPE_ANYELEMENT: BuiltinType<NameReference> = BuiltinType {
986    name: "anyelement",
987    schema: PG_CATALOG_SCHEMA,
988    oid: oid::TYPE_ANYELEMENT_OID,
989    details: CatalogTypeDetails {
990        typ: CatalogType::Pseudo,
991        array_id: None,
992        pg_metadata: Some(CatalogTypePgMetadata {
993            typinput_oid: 2312,
994            typreceive_oid: 0,
995        }),
996    },
997};
998
999pub const TYPE_ANYNONARRAY: BuiltinType<NameReference> = BuiltinType {
1000    name: "anynonarray",
1001    schema: PG_CATALOG_SCHEMA,
1002    oid: oid::TYPE_ANYNONARRAY_OID,
1003    details: CatalogTypeDetails {
1004        typ: CatalogType::Pseudo,
1005        array_id: None,
1006        pg_metadata: Some(CatalogTypePgMetadata {
1007            typinput_oid: 2777,
1008            typreceive_oid: 0,
1009        }),
1010    },
1011};
1012
1013pub const TYPE_ANYRANGE: BuiltinType<NameReference> = BuiltinType {
1014    name: "anyrange",
1015    schema: PG_CATALOG_SCHEMA,
1016    oid: oid::TYPE_ANYRANGE_OID,
1017    details: CatalogTypeDetails {
1018        typ: CatalogType::Pseudo,
1019        array_id: None,
1020        pg_metadata: Some(CatalogTypePgMetadata {
1021            typinput_oid: 3832,
1022            typreceive_oid: 0,
1023        }),
1024    },
1025};
1026
1027pub const TYPE_CHAR: BuiltinType<NameReference> = BuiltinType {
1028    name: "char",
1029    schema: PG_CATALOG_SCHEMA,
1030    oid: oid::TYPE_CHAR_OID,
1031    details: CatalogTypeDetails {
1032        typ: CatalogType::PgLegacyChar,
1033        array_id: None,
1034        pg_metadata: Some(CatalogTypePgMetadata {
1035            typinput_oid: 1245,
1036            typreceive_oid: 2434,
1037        }),
1038    },
1039};
1040
1041pub const TYPE_VARCHAR: BuiltinType<NameReference> = BuiltinType {
1042    name: "varchar",
1043    schema: PG_CATALOG_SCHEMA,
1044    oid: oid::TYPE_VARCHAR_OID,
1045    details: CatalogTypeDetails {
1046        typ: CatalogType::VarChar,
1047        array_id: None,
1048        pg_metadata: Some(CatalogTypePgMetadata {
1049            typinput_oid: 1046,
1050            typreceive_oid: 2432,
1051        }),
1052    },
1053};
1054
1055pub const TYPE_INT2: BuiltinType<NameReference> = BuiltinType {
1056    name: "int2",
1057    schema: PG_CATALOG_SCHEMA,
1058    oid: oid::TYPE_INT2_OID,
1059    details: CatalogTypeDetails {
1060        typ: CatalogType::Int16,
1061        array_id: None,
1062        pg_metadata: Some(CatalogTypePgMetadata {
1063            typinput_oid: 38,
1064            typreceive_oid: 2404,
1065        }),
1066    },
1067};
1068
1069pub const TYPE_INT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1070    name: "_int2",
1071    schema: PG_CATALOG_SCHEMA,
1072    oid: oid::TYPE_INT2_ARRAY_OID,
1073    details: CatalogTypeDetails {
1074        typ: CatalogType::Array {
1075            element_reference: TYPE_INT2.name,
1076        },
1077        array_id: None,
1078        pg_metadata: Some(CatalogTypePgMetadata {
1079            typinput_oid: 750,
1080            typreceive_oid: 2400,
1081        }),
1082    },
1083};
1084
1085pub const TYPE_BPCHAR: BuiltinType<NameReference> = BuiltinType {
1086    name: "bpchar",
1087    schema: PG_CATALOG_SCHEMA,
1088    oid: oid::TYPE_BPCHAR_OID,
1089    details: CatalogTypeDetails {
1090        typ: CatalogType::Char,
1091        array_id: None,
1092        pg_metadata: Some(CatalogTypePgMetadata {
1093            typinput_oid: 1044,
1094            typreceive_oid: 2430,
1095        }),
1096    },
1097};
1098
1099pub const TYPE_CHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1100    name: "_char",
1101    schema: PG_CATALOG_SCHEMA,
1102    oid: oid::TYPE_CHAR_ARRAY_OID,
1103    details: CatalogTypeDetails {
1104        typ: CatalogType::Array {
1105            element_reference: TYPE_CHAR.name,
1106        },
1107        array_id: None,
1108        pg_metadata: Some(CatalogTypePgMetadata {
1109            typinput_oid: 750,
1110            typreceive_oid: 2400,
1111        }),
1112    },
1113};
1114
1115pub const TYPE_VARCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1116    name: "_varchar",
1117    schema: PG_CATALOG_SCHEMA,
1118    oid: oid::TYPE_VARCHAR_ARRAY_OID,
1119    details: CatalogTypeDetails {
1120        typ: CatalogType::Array {
1121            element_reference: TYPE_VARCHAR.name,
1122        },
1123        array_id: None,
1124        pg_metadata: Some(CatalogTypePgMetadata {
1125            typinput_oid: 750,
1126            typreceive_oid: 2400,
1127        }),
1128    },
1129};
1130
1131pub const TYPE_BPCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1132    name: "_bpchar",
1133    schema: PG_CATALOG_SCHEMA,
1134    oid: oid::TYPE_BPCHAR_ARRAY_OID,
1135    details: CatalogTypeDetails {
1136        typ: CatalogType::Array {
1137            element_reference: TYPE_BPCHAR.name,
1138        },
1139        array_id: None,
1140        pg_metadata: Some(CatalogTypePgMetadata {
1141            typinput_oid: 750,
1142            typreceive_oid: 2400,
1143        }),
1144    },
1145};
1146
1147pub const TYPE_REGPROC: BuiltinType<NameReference> = BuiltinType {
1148    name: "regproc",
1149    schema: PG_CATALOG_SCHEMA,
1150    oid: oid::TYPE_REGPROC_OID,
1151    details: CatalogTypeDetails {
1152        typ: CatalogType::RegProc,
1153        array_id: None,
1154        pg_metadata: Some(CatalogTypePgMetadata {
1155            typinput_oid: 44,
1156            typreceive_oid: 2444,
1157        }),
1158    },
1159};
1160
1161pub const TYPE_REGPROC_ARRAY: BuiltinType<NameReference> = BuiltinType {
1162    name: "_regproc",
1163    schema: PG_CATALOG_SCHEMA,
1164    oid: oid::TYPE_REGPROC_ARRAY_OID,
1165    details: CatalogTypeDetails {
1166        typ: CatalogType::Array {
1167            element_reference: TYPE_REGPROC.name,
1168        },
1169        array_id: None,
1170        pg_metadata: Some(CatalogTypePgMetadata {
1171            typinput_oid: 750,
1172            typreceive_oid: 2400,
1173        }),
1174    },
1175};
1176
1177pub const TYPE_REGTYPE: BuiltinType<NameReference> = BuiltinType {
1178    name: "regtype",
1179    schema: PG_CATALOG_SCHEMA,
1180    oid: oid::TYPE_REGTYPE_OID,
1181    details: CatalogTypeDetails {
1182        typ: CatalogType::RegType,
1183        array_id: None,
1184        pg_metadata: Some(CatalogTypePgMetadata {
1185            typinput_oid: 2220,
1186            typreceive_oid: 2454,
1187        }),
1188    },
1189};
1190
1191pub const TYPE_REGTYPE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1192    name: "_regtype",
1193    schema: PG_CATALOG_SCHEMA,
1194    oid: oid::TYPE_REGTYPE_ARRAY_OID,
1195    details: CatalogTypeDetails {
1196        typ: CatalogType::Array {
1197            element_reference: TYPE_REGTYPE.name,
1198        },
1199        array_id: None,
1200        pg_metadata: Some(CatalogTypePgMetadata {
1201            typinput_oid: 750,
1202            typreceive_oid: 2400,
1203        }),
1204    },
1205};
1206
1207pub const TYPE_REGCLASS: BuiltinType<NameReference> = BuiltinType {
1208    name: "regclass",
1209    schema: PG_CATALOG_SCHEMA,
1210    oid: oid::TYPE_REGCLASS_OID,
1211    details: CatalogTypeDetails {
1212        typ: CatalogType::RegClass,
1213        array_id: None,
1214        pg_metadata: Some(CatalogTypePgMetadata {
1215            typinput_oid: 2218,
1216            typreceive_oid: 2452,
1217        }),
1218    },
1219};
1220
1221pub const TYPE_REGCLASS_ARRAY: BuiltinType<NameReference> = BuiltinType {
1222    name: "_regclass",
1223    schema: PG_CATALOG_SCHEMA,
1224    oid: oid::TYPE_REGCLASS_ARRAY_OID,
1225    details: CatalogTypeDetails {
1226        typ: CatalogType::Array {
1227            element_reference: TYPE_REGCLASS.name,
1228        },
1229        array_id: None,
1230        pg_metadata: Some(CatalogTypePgMetadata {
1231            typinput_oid: 750,
1232            typreceive_oid: 2400,
1233        }),
1234    },
1235};
1236
1237pub const TYPE_INT2_VECTOR: BuiltinType<NameReference> = BuiltinType {
1238    name: "int2vector",
1239    schema: PG_CATALOG_SCHEMA,
1240    oid: oid::TYPE_INT2_VECTOR_OID,
1241    details: CatalogTypeDetails {
1242        typ: CatalogType::Int2Vector,
1243        array_id: None,
1244        pg_metadata: Some(CatalogTypePgMetadata {
1245            typinput_oid: 40,
1246            typreceive_oid: 2410,
1247        }),
1248    },
1249};
1250
1251pub const TYPE_INT2_VECTOR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1252    name: "_int2vector",
1253    schema: PG_CATALOG_SCHEMA,
1254    oid: oid::TYPE_INT2_VECTOR_ARRAY_OID,
1255    details: CatalogTypeDetails {
1256        typ: CatalogType::Array {
1257            element_reference: TYPE_INT2_VECTOR.name,
1258        },
1259        array_id: None,
1260        pg_metadata: Some(CatalogTypePgMetadata {
1261            typinput_oid: 750,
1262            typreceive_oid: 2400,
1263        }),
1264    },
1265};
1266
1267pub const TYPE_ANYCOMPATIBLE: BuiltinType<NameReference> = BuiltinType {
1268    name: "anycompatible",
1269    schema: PG_CATALOG_SCHEMA,
1270    oid: oid::TYPE_ANYCOMPATIBLE_OID,
1271    details: CatalogTypeDetails {
1272        typ: CatalogType::Pseudo,
1273        array_id: None,
1274        pg_metadata: Some(CatalogTypePgMetadata {
1275            typinput_oid: 5086,
1276            typreceive_oid: 0,
1277        }),
1278    },
1279};
1280
1281pub const TYPE_ANYCOMPATIBLEARRAY: BuiltinType<NameReference> = BuiltinType {
1282    name: "anycompatiblearray",
1283    schema: PG_CATALOG_SCHEMA,
1284    oid: oid::TYPE_ANYCOMPATIBLEARRAY_OID,
1285    details: CatalogTypeDetails {
1286        typ: CatalogType::Pseudo,
1287        array_id: None,
1288        pg_metadata: Some(CatalogTypePgMetadata {
1289            typinput_oid: 5088,
1290            typreceive_oid: 5090,
1291        }),
1292    },
1293};
1294
1295pub const TYPE_ANYCOMPATIBLENONARRAY: BuiltinType<NameReference> = BuiltinType {
1296    name: "anycompatiblenonarray",
1297    schema: PG_CATALOG_SCHEMA,
1298    oid: oid::TYPE_ANYCOMPATIBLENONARRAY_OID,
1299    details: CatalogTypeDetails {
1300        typ: CatalogType::Pseudo,
1301        array_id: None,
1302        pg_metadata: Some(CatalogTypePgMetadata {
1303            typinput_oid: 5092,
1304            typreceive_oid: 0,
1305        }),
1306    },
1307};
1308
1309pub const TYPE_ANYCOMPATIBLERANGE: BuiltinType<NameReference> = BuiltinType {
1310    name: "anycompatiblerange",
1311    schema: PG_CATALOG_SCHEMA,
1312    oid: oid::TYPE_ANYCOMPATIBLERANGE_OID,
1313    details: CatalogTypeDetails {
1314        typ: CatalogType::Pseudo,
1315        array_id: None,
1316        pg_metadata: Some(CatalogTypePgMetadata {
1317            typinput_oid: 5094,
1318            typreceive_oid: 0,
1319        }),
1320    },
1321};
1322
1323pub const TYPE_LIST: BuiltinType<NameReference> = BuiltinType {
1324    name: "list",
1325    schema: MZ_CATALOG_SCHEMA,
1326    oid: mz_pgrepr::oid::TYPE_LIST_OID,
1327    details: CatalogTypeDetails {
1328        typ: CatalogType::Pseudo,
1329        array_id: None,
1330        pg_metadata: None,
1331    },
1332};
1333
1334pub const TYPE_MAP: BuiltinType<NameReference> = BuiltinType {
1335    name: "map",
1336    schema: MZ_CATALOG_SCHEMA,
1337    oid: mz_pgrepr::oid::TYPE_MAP_OID,
1338    details: CatalogTypeDetails {
1339        typ: CatalogType::Pseudo,
1340        array_id: None,
1341        pg_metadata: None,
1342    },
1343};
1344
1345pub const TYPE_ANYCOMPATIBLELIST: BuiltinType<NameReference> = BuiltinType {
1346    name: "anycompatiblelist",
1347    schema: MZ_CATALOG_SCHEMA,
1348    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLELIST_OID,
1349    details: CatalogTypeDetails {
1350        typ: CatalogType::Pseudo,
1351        array_id: None,
1352        pg_metadata: None,
1353    },
1354};
1355
1356pub const TYPE_ANYCOMPATIBLEMAP: BuiltinType<NameReference> = BuiltinType {
1357    name: "anycompatiblemap",
1358    schema: MZ_CATALOG_SCHEMA,
1359    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLEMAP_OID,
1360    details: CatalogTypeDetails {
1361        typ: CatalogType::Pseudo,
1362        array_id: None,
1363        pg_metadata: None,
1364    },
1365};
1366
1367pub const TYPE_UINT2: BuiltinType<NameReference> = BuiltinType {
1368    name: "uint2",
1369    schema: MZ_CATALOG_SCHEMA,
1370    oid: mz_pgrepr::oid::TYPE_UINT2_OID,
1371    details: CatalogTypeDetails {
1372        typ: CatalogType::UInt16,
1373        array_id: None,
1374        pg_metadata: None,
1375    },
1376};
1377
1378pub const TYPE_UINT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1379    name: "_uint2",
1380    schema: MZ_CATALOG_SCHEMA,
1381    oid: mz_pgrepr::oid::TYPE_UINT2_ARRAY_OID,
1382    details: CatalogTypeDetails {
1383        typ: CatalogType::Array {
1384            element_reference: TYPE_UINT2.name,
1385        },
1386        array_id: None,
1387        pg_metadata: None,
1388    },
1389};
1390
1391pub const TYPE_UINT4: BuiltinType<NameReference> = BuiltinType {
1392    name: "uint4",
1393    schema: MZ_CATALOG_SCHEMA,
1394    oid: mz_pgrepr::oid::TYPE_UINT4_OID,
1395    details: CatalogTypeDetails {
1396        typ: CatalogType::UInt32,
1397        array_id: None,
1398        pg_metadata: None,
1399    },
1400};
1401
1402pub const TYPE_UINT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
1403    name: "_uint4",
1404    schema: MZ_CATALOG_SCHEMA,
1405    oid: mz_pgrepr::oid::TYPE_UINT4_ARRAY_OID,
1406    details: CatalogTypeDetails {
1407        typ: CatalogType::Array {
1408            element_reference: TYPE_UINT4.name,
1409        },
1410        array_id: None,
1411        pg_metadata: None,
1412    },
1413};
1414
1415pub const TYPE_UINT8: BuiltinType<NameReference> = BuiltinType {
1416    name: "uint8",
1417    schema: MZ_CATALOG_SCHEMA,
1418    oid: mz_pgrepr::oid::TYPE_UINT8_OID,
1419    details: CatalogTypeDetails {
1420        typ: CatalogType::UInt64,
1421        array_id: None,
1422        pg_metadata: None,
1423    },
1424};
1425
1426pub const TYPE_UINT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
1427    name: "_uint8",
1428    schema: MZ_CATALOG_SCHEMA,
1429    oid: mz_pgrepr::oid::TYPE_UINT8_ARRAY_OID,
1430    details: CatalogTypeDetails {
1431        typ: CatalogType::Array {
1432            element_reference: TYPE_UINT8.name,
1433        },
1434        array_id: None,
1435        pg_metadata: None,
1436    },
1437};
1438
1439pub const TYPE_MZ_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
1440    name: "mz_timestamp",
1441    schema: MZ_CATALOG_SCHEMA,
1442    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_OID,
1443    details: CatalogTypeDetails {
1444        typ: CatalogType::MzTimestamp,
1445        array_id: None,
1446        pg_metadata: None,
1447    },
1448};
1449
1450pub const TYPE_MZ_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
1451    name: "_mz_timestamp",
1452    schema: MZ_CATALOG_SCHEMA,
1453    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_ARRAY_OID,
1454    details: CatalogTypeDetails {
1455        typ: CatalogType::Array {
1456            element_reference: TYPE_MZ_TIMESTAMP.name,
1457        },
1458        array_id: None,
1459        pg_metadata: None,
1460    },
1461};
1462
1463pub const TYPE_INT4_RANGE: BuiltinType<NameReference> = BuiltinType {
1464    name: "int4range",
1465    schema: PG_CATALOG_SCHEMA,
1466    oid: mz_pgrepr::oid::TYPE_INT4RANGE_OID,
1467    details: CatalogTypeDetails {
1468        typ: CatalogType::Range {
1469            element_reference: TYPE_INT4.name,
1470        },
1471        array_id: None,
1472        pg_metadata: Some(CatalogTypePgMetadata {
1473            typinput_oid: 3834,
1474            typreceive_oid: 3836,
1475        }),
1476    },
1477};
1478
1479pub const TYPE_INT4_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1480    name: "_int4range",
1481    schema: PG_CATALOG_SCHEMA,
1482    oid: mz_pgrepr::oid::TYPE_INT4RANGE_ARRAY_OID,
1483    details: CatalogTypeDetails {
1484        typ: CatalogType::Array {
1485            element_reference: TYPE_INT4_RANGE.name,
1486        },
1487        array_id: None,
1488        pg_metadata: Some(CatalogTypePgMetadata {
1489            typinput_oid: 750,
1490            typreceive_oid: 2400,
1491        }),
1492    },
1493};
1494
1495pub const TYPE_INT8_RANGE: BuiltinType<NameReference> = BuiltinType {
1496    name: "int8range",
1497    schema: PG_CATALOG_SCHEMA,
1498    oid: mz_pgrepr::oid::TYPE_INT8RANGE_OID,
1499    details: CatalogTypeDetails {
1500        typ: CatalogType::Range {
1501            element_reference: TYPE_INT8.name,
1502        },
1503        array_id: None,
1504        pg_metadata: Some(CatalogTypePgMetadata {
1505            typinput_oid: 3834,
1506            typreceive_oid: 3836,
1507        }),
1508    },
1509};
1510
1511pub const TYPE_INT8_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1512    name: "_int8range",
1513    schema: PG_CATALOG_SCHEMA,
1514    oid: mz_pgrepr::oid::TYPE_INT8RANGE_ARRAY_OID,
1515    details: CatalogTypeDetails {
1516        typ: CatalogType::Array {
1517            element_reference: TYPE_INT8_RANGE.name,
1518        },
1519        array_id: None,
1520        pg_metadata: Some(CatalogTypePgMetadata {
1521            typinput_oid: 750,
1522            typreceive_oid: 2400,
1523        }),
1524    },
1525};
1526
1527pub const TYPE_DATE_RANGE: BuiltinType<NameReference> = BuiltinType {
1528    name: "daterange",
1529    schema: PG_CATALOG_SCHEMA,
1530    oid: mz_pgrepr::oid::TYPE_DATERANGE_OID,
1531    details: CatalogTypeDetails {
1532        typ: CatalogType::Range {
1533            element_reference: TYPE_DATE.name,
1534        },
1535        array_id: None,
1536        pg_metadata: Some(CatalogTypePgMetadata {
1537            typinput_oid: 3834,
1538            typreceive_oid: 3836,
1539        }),
1540    },
1541};
1542
1543pub const TYPE_DATE_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1544    name: "_daterange",
1545    schema: PG_CATALOG_SCHEMA,
1546    oid: mz_pgrepr::oid::TYPE_DATERANGE_ARRAY_OID,
1547    details: CatalogTypeDetails {
1548        typ: CatalogType::Array {
1549            element_reference: TYPE_DATE_RANGE.name,
1550        },
1551        array_id: None,
1552        pg_metadata: Some(CatalogTypePgMetadata {
1553            typinput_oid: 750,
1554            typreceive_oid: 2400,
1555        }),
1556    },
1557};
1558
1559pub const TYPE_NUM_RANGE: BuiltinType<NameReference> = BuiltinType {
1560    name: "numrange",
1561    schema: PG_CATALOG_SCHEMA,
1562    oid: mz_pgrepr::oid::TYPE_NUMRANGE_OID,
1563    details: CatalogTypeDetails {
1564        typ: CatalogType::Range {
1565            element_reference: TYPE_NUMERIC.name,
1566        },
1567        array_id: None,
1568        pg_metadata: Some(CatalogTypePgMetadata {
1569            typinput_oid: 3834,
1570            typreceive_oid: 3836,
1571        }),
1572    },
1573};
1574
1575pub const TYPE_NUM_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1576    name: "_numrange",
1577    schema: PG_CATALOG_SCHEMA,
1578    oid: mz_pgrepr::oid::TYPE_NUMRANGE_ARRAY_OID,
1579    details: CatalogTypeDetails {
1580        typ: CatalogType::Array {
1581            element_reference: TYPE_NUM_RANGE.name,
1582        },
1583        array_id: None,
1584        pg_metadata: Some(CatalogTypePgMetadata {
1585            typinput_oid: 750,
1586            typreceive_oid: 2400,
1587        }),
1588    },
1589};
1590
1591pub const TYPE_TS_RANGE: BuiltinType<NameReference> = BuiltinType {
1592    name: "tsrange",
1593    schema: PG_CATALOG_SCHEMA,
1594    oid: mz_pgrepr::oid::TYPE_TSRANGE_OID,
1595    details: CatalogTypeDetails {
1596        typ: CatalogType::Range {
1597            element_reference: TYPE_TIMESTAMP.name,
1598        },
1599        array_id: None,
1600        pg_metadata: Some(CatalogTypePgMetadata {
1601            typinput_oid: 3834,
1602            typreceive_oid: 3836,
1603        }),
1604    },
1605};
1606
1607pub const TYPE_TS_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1608    name: "_tsrange",
1609    schema: PG_CATALOG_SCHEMA,
1610    oid: mz_pgrepr::oid::TYPE_TSRANGE_ARRAY_OID,
1611    details: CatalogTypeDetails {
1612        typ: CatalogType::Array {
1613            element_reference: TYPE_TS_RANGE.name,
1614        },
1615        array_id: None,
1616        pg_metadata: Some(CatalogTypePgMetadata {
1617            typinput_oid: 750,
1618            typreceive_oid: 2400,
1619        }),
1620    },
1621};
1622
1623pub const TYPE_TSTZ_RANGE: BuiltinType<NameReference> = BuiltinType {
1624    name: "tstzrange",
1625    schema: PG_CATALOG_SCHEMA,
1626    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_OID,
1627    details: CatalogTypeDetails {
1628        typ: CatalogType::Range {
1629            element_reference: TYPE_TIMESTAMPTZ.name,
1630        },
1631        array_id: None,
1632        pg_metadata: Some(CatalogTypePgMetadata {
1633            typinput_oid: 3834,
1634            typreceive_oid: 3836,
1635        }),
1636    },
1637};
1638
1639pub const TYPE_TSTZ_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1640    name: "_tstzrange",
1641    schema: PG_CATALOG_SCHEMA,
1642    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_ARRAY_OID,
1643    details: CatalogTypeDetails {
1644        typ: CatalogType::Array {
1645            element_reference: TYPE_TSTZ_RANGE.name,
1646        },
1647        array_id: None,
1648        pg_metadata: Some(CatalogTypePgMetadata {
1649            typinput_oid: 750,
1650            typreceive_oid: 2400,
1651        }),
1652    },
1653};
1654
1655pub const TYPE_MZ_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1656    name: "mz_aclitem",
1657    schema: MZ_CATALOG_SCHEMA,
1658    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_OID,
1659    details: CatalogTypeDetails {
1660        typ: CatalogType::MzAclItem,
1661        array_id: None,
1662        pg_metadata: None,
1663    },
1664};
1665
1666pub const TYPE_MZ_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1667    name: "_mz_aclitem",
1668    schema: MZ_CATALOG_SCHEMA,
1669    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_ARRAY_OID,
1670    details: CatalogTypeDetails {
1671        typ: CatalogType::Array {
1672            element_reference: TYPE_MZ_ACL_ITEM.name,
1673        },
1674        array_id: None,
1675        pg_metadata: Some(CatalogTypePgMetadata {
1676            typinput_oid: 750,
1677            typreceive_oid: 2400,
1678        }),
1679    },
1680};
1681
1682pub const TYPE_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1683    name: "aclitem",
1684    schema: PG_CATALOG_SCHEMA,
1685    oid: 1033,
1686    details: CatalogTypeDetails {
1687        typ: CatalogType::AclItem,
1688        array_id: None,
1689        pg_metadata: Some(CatalogTypePgMetadata {
1690            typinput_oid: 1031,
1691            typreceive_oid: 0,
1692        }),
1693    },
1694};
1695
1696pub const TYPE_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1697    name: "_aclitem",
1698    schema: PG_CATALOG_SCHEMA,
1699    oid: 1034,
1700    details: CatalogTypeDetails {
1701        typ: CatalogType::Array {
1702            element_reference: TYPE_ACL_ITEM.name,
1703        },
1704        array_id: None,
1705        pg_metadata: Some(CatalogTypePgMetadata {
1706            typinput_oid: 750,
1707            typreceive_oid: 2400,
1708        }),
1709    },
1710};
1711
1712pub const TYPE_INTERNAL: BuiltinType<NameReference> = BuiltinType {
1713    name: "internal",
1714    schema: PG_CATALOG_SCHEMA,
1715    oid: 2281,
1716    details: CatalogTypeDetails {
1717        typ: CatalogType::Pseudo,
1718        array_id: None,
1719        pg_metadata: Some(CatalogTypePgMetadata {
1720            typinput_oid: 2304,
1721            typreceive_oid: 0,
1722        }),
1723    },
1724};
1725
1726const PUBLIC_SELECT: MzAclItem = MzAclItem {
1727    grantee: RoleId::Public,
1728    grantor: MZ_SYSTEM_ROLE_ID,
1729    acl_mode: AclMode::SELECT,
1730};
1731
1732const SUPPORT_SELECT: MzAclItem = MzAclItem {
1733    grantee: MZ_SUPPORT_ROLE_ID,
1734    grantor: MZ_SYSTEM_ROLE_ID,
1735    acl_mode: AclMode::SELECT,
1736};
1737
1738const ANALYTICS_SELECT: MzAclItem = MzAclItem {
1739    grantee: MZ_ANALYTICS_ROLE_ID,
1740    grantor: MZ_SYSTEM_ROLE_ID,
1741    acl_mode: AclMode::SELECT,
1742};
1743
1744const MONITOR_SELECT: MzAclItem = MzAclItem {
1745    grantee: MZ_MONITOR_ROLE_ID,
1746    grantor: MZ_SYSTEM_ROLE_ID,
1747    acl_mode: AclMode::SELECT,
1748};
1749
1750const MONITOR_REDACTED_SELECT: MzAclItem = MzAclItem {
1751    grantee: MZ_MONITOR_REDACTED_ROLE_ID,
1752    grantor: MZ_SYSTEM_ROLE_ID,
1753    acl_mode: AclMode::SELECT,
1754};
1755
1756pub static MZ_DATAFLOW_OPERATORS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1757    name: "mz_dataflow_operators_per_worker",
1758    schema: MZ_INTROSPECTION_SCHEMA,
1759    oid: oid::LOG_MZ_DATAFLOW_OPERATORS_PER_WORKER_OID,
1760    variant: LogVariant::Timely(TimelyLog::Operates),
1761    access: vec![PUBLIC_SELECT],
1762});
1763
1764pub static MZ_DATAFLOW_ADDRESSES_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1765    name: "mz_dataflow_addresses_per_worker",
1766    schema: MZ_INTROSPECTION_SCHEMA,
1767    oid: oid::LOG_MZ_DATAFLOW_ADDRESSES_PER_WORKER_OID,
1768    variant: LogVariant::Timely(TimelyLog::Addresses),
1769    access: vec![PUBLIC_SELECT],
1770});
1771
1772pub static MZ_DATAFLOW_CHANNELS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1773    name: "mz_dataflow_channels_per_worker",
1774    schema: MZ_INTROSPECTION_SCHEMA,
1775    oid: oid::LOG_MZ_DATAFLOW_CHANNELS_PER_WORKER_OID,
1776    variant: LogVariant::Timely(TimelyLog::Channels),
1777    access: vec![PUBLIC_SELECT],
1778});
1779
1780pub static MZ_SCHEDULING_ELAPSED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1781    name: "mz_scheduling_elapsed_raw",
1782    schema: MZ_INTROSPECTION_SCHEMA,
1783    oid: oid::LOG_MZ_SCHEDULING_ELAPSED_RAW_OID,
1784    variant: LogVariant::Timely(TimelyLog::Elapsed),
1785    access: vec![PUBLIC_SELECT],
1786});
1787
1788pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1789    LazyLock::new(|| BuiltinLog {
1790        name: "mz_compute_operator_durations_histogram_raw",
1791        schema: MZ_INTROSPECTION_SCHEMA,
1792        oid: oid::LOG_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW_OID,
1793        variant: LogVariant::Timely(TimelyLog::Histogram),
1794        access: vec![PUBLIC_SELECT],
1795    });
1796
1797pub static MZ_SCHEDULING_PARKS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1798    name: "mz_scheduling_parks_histogram_raw",
1799    schema: MZ_INTROSPECTION_SCHEMA,
1800    oid: oid::LOG_MZ_SCHEDULING_PARKS_HISTOGRAM_RAW_OID,
1801    variant: LogVariant::Timely(TimelyLog::Parks),
1802    access: vec![PUBLIC_SELECT],
1803});
1804
1805pub static MZ_ARRANGEMENT_RECORDS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1806    name: "mz_arrangement_records_raw",
1807    schema: MZ_INTROSPECTION_SCHEMA,
1808    oid: oid::LOG_MZ_ARRANGEMENT_RECORDS_RAW_OID,
1809    variant: LogVariant::Differential(DifferentialLog::ArrangementRecords),
1810    access: vec![PUBLIC_SELECT],
1811});
1812
1813pub static MZ_ARRANGEMENT_BATCHES_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1814    name: "mz_arrangement_batches_raw",
1815    schema: MZ_INTROSPECTION_SCHEMA,
1816    oid: oid::LOG_MZ_ARRANGEMENT_BATCHES_RAW_OID,
1817    variant: LogVariant::Differential(DifferentialLog::ArrangementBatches),
1818    access: vec![PUBLIC_SELECT],
1819});
1820
1821pub static MZ_ARRANGEMENT_SHARING_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1822    name: "mz_arrangement_sharing_raw",
1823    schema: MZ_INTROSPECTION_SCHEMA,
1824    oid: oid::LOG_MZ_ARRANGEMENT_SHARING_RAW_OID,
1825    variant: LogVariant::Differential(DifferentialLog::Sharing),
1826    access: vec![PUBLIC_SELECT],
1827});
1828
1829pub static MZ_ARRANGEMENT_BATCHER_RECORDS_RAW: LazyLock<BuiltinLog> =
1830    LazyLock::new(|| BuiltinLog {
1831        name: "mz_arrangement_batcher_records_raw",
1832        schema: MZ_INTROSPECTION_SCHEMA,
1833        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_RECORDS_RAW_OID,
1834        variant: LogVariant::Differential(DifferentialLog::BatcherRecords),
1835        access: vec![PUBLIC_SELECT],
1836    });
1837
1838pub static MZ_ARRANGEMENT_BATCHER_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1839    name: "mz_arrangement_batcher_size_raw",
1840    schema: MZ_INTROSPECTION_SCHEMA,
1841    oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_SIZE_RAW_OID,
1842    variant: LogVariant::Differential(DifferentialLog::BatcherSize),
1843    access: vec![PUBLIC_SELECT],
1844});
1845
1846pub static MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW: LazyLock<BuiltinLog> =
1847    LazyLock::new(|| BuiltinLog {
1848        name: "mz_arrangement_batcher_capacity_raw",
1849        schema: MZ_INTROSPECTION_SCHEMA,
1850        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW_OID,
1851        variant: LogVariant::Differential(DifferentialLog::BatcherCapacity),
1852        access: vec![PUBLIC_SELECT],
1853    });
1854
1855pub static MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1856    LazyLock::new(|| BuiltinLog {
1857        name: "mz_arrangement_batcher_allocations_raw",
1858        schema: MZ_INTROSPECTION_SCHEMA,
1859        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW_OID,
1860        variant: LogVariant::Differential(DifferentialLog::BatcherAllocations),
1861        access: vec![PUBLIC_SELECT],
1862    });
1863
1864pub static MZ_COMPUTE_EXPORTS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1865    name: "mz_compute_exports_per_worker",
1866    schema: MZ_INTROSPECTION_SCHEMA,
1867    oid: oid::LOG_MZ_COMPUTE_EXPORTS_PER_WORKER_OID,
1868    variant: LogVariant::Compute(ComputeLog::DataflowCurrent),
1869    access: vec![PUBLIC_SELECT],
1870});
1871
1872pub static MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER: LazyLock<BuiltinLog> =
1873    LazyLock::new(|| BuiltinLog {
1874        name: "mz_compute_dataflow_global_ids_per_worker",
1875        schema: MZ_INTROSPECTION_SCHEMA,
1876        oid: oid::LOG_MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER_OID,
1877        variant: LogVariant::Compute(ComputeLog::DataflowGlobal),
1878        access: vec![PUBLIC_SELECT],
1879    });
1880
1881pub static MZ_COMPUTE_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1882    name: "mz_compute_frontiers_per_worker",
1883    schema: MZ_INTROSPECTION_SCHEMA,
1884    oid: oid::LOG_MZ_COMPUTE_FRONTIERS_PER_WORKER_OID,
1885    variant: LogVariant::Compute(ComputeLog::FrontierCurrent),
1886    access: vec![PUBLIC_SELECT],
1887});
1888
1889pub static MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> =
1890    LazyLock::new(|| BuiltinLog {
1891        name: "mz_compute_import_frontiers_per_worker",
1892        schema: MZ_INTROSPECTION_SCHEMA,
1893        oid: oid::LOG_MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER_OID,
1894        variant: LogVariant::Compute(ComputeLog::ImportFrontierCurrent),
1895        access: vec![PUBLIC_SELECT],
1896    });
1897
1898pub static MZ_COMPUTE_ERROR_COUNTS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1899    name: "mz_compute_error_counts_raw",
1900    schema: MZ_INTROSPECTION_SCHEMA,
1901    oid: oid::LOG_MZ_COMPUTE_ERROR_COUNTS_RAW_OID,
1902    variant: LogVariant::Compute(ComputeLog::ErrorCount),
1903    access: vec![PUBLIC_SELECT],
1904});
1905
1906pub static MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER: LazyLock<BuiltinLog> =
1907    LazyLock::new(|| BuiltinLog {
1908        name: "mz_compute_hydration_times_per_worker",
1909        schema: MZ_INTROSPECTION_SCHEMA,
1910        oid: oid::LOG_MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER_OID,
1911        variant: LogVariant::Compute(ComputeLog::HydrationTime),
1912        access: vec![PUBLIC_SELECT],
1913    });
1914
1915pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER: LazyLock<BuiltinLog> =
1916    LazyLock::new(|| BuiltinLog {
1917        name: "mz_compute_operator_hydration_statuses_per_worker",
1918        schema: MZ_INTROSPECTION_SCHEMA,
1919        oid: oid::LOG_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER_OID,
1920        variant: LogVariant::Compute(ComputeLog::OperatorHydrationStatus),
1921        access: vec![PUBLIC_SELECT],
1922    });
1923
1924pub static MZ_ACTIVE_PEEKS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1925    name: "mz_active_peeks_per_worker",
1926    schema: MZ_INTROSPECTION_SCHEMA,
1927    oid: oid::LOG_MZ_ACTIVE_PEEKS_PER_WORKER_OID,
1928    variant: LogVariant::Compute(ComputeLog::PeekCurrent),
1929    access: vec![PUBLIC_SELECT],
1930});
1931
1932pub static MZ_COMPUTE_LIR_MAPPING_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1933    name: "mz_compute_lir_mapping_per_worker",
1934    schema: MZ_INTROSPECTION_SCHEMA,
1935    oid: oid::LOG_MZ_COMPUTE_LIR_MAPPING_PER_WORKER_OID,
1936    variant: LogVariant::Compute(ComputeLog::LirMapping),
1937    access: vec![PUBLIC_SELECT],
1938});
1939
1940pub static MZ_PEEK_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1941    name: "mz_peek_durations_histogram_raw",
1942    schema: MZ_INTROSPECTION_SCHEMA,
1943    oid: oid::LOG_MZ_PEEK_DURATIONS_HISTOGRAM_RAW_OID,
1944    variant: LogVariant::Compute(ComputeLog::PeekDuration),
1945    access: vec![PUBLIC_SELECT],
1946});
1947
1948pub static MZ_ARRANGEMENT_HEAP_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1949    name: "mz_arrangement_heap_size_raw",
1950    schema: MZ_INTROSPECTION_SCHEMA,
1951    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_SIZE_RAW_OID,
1952    variant: LogVariant::Compute(ComputeLog::ArrangementHeapSize),
1953    access: vec![PUBLIC_SELECT],
1954});
1955
1956pub static MZ_ARRANGEMENT_HEAP_CAPACITY_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1957    name: "mz_arrangement_heap_capacity_raw",
1958    schema: MZ_INTROSPECTION_SCHEMA,
1959    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_CAPACITY_RAW_OID,
1960    variant: LogVariant::Compute(ComputeLog::ArrangementHeapCapacity),
1961    access: vec![PUBLIC_SELECT],
1962});
1963
1964pub static MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1965    LazyLock::new(|| BuiltinLog {
1966        name: "mz_arrangement_heap_allocations_raw",
1967        schema: MZ_INTROSPECTION_SCHEMA,
1968        oid: oid::LOG_MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW_OID,
1969        variant: LogVariant::Compute(ComputeLog::ArrangementHeapAllocations),
1970        access: vec![PUBLIC_SELECT],
1971    });
1972
1973pub static MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> =
1974    LazyLock::new(|| BuiltinLog {
1975        name: "mz_message_batch_counts_received_raw",
1976        schema: MZ_INTROSPECTION_SCHEMA,
1977        oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW_OID,
1978        variant: LogVariant::Timely(TimelyLog::BatchesReceived),
1979        access: vec![PUBLIC_SELECT],
1980    });
1981
1982pub static MZ_MESSAGE_BATCH_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1983    name: "mz_message_batch_counts_sent_raw",
1984    schema: MZ_INTROSPECTION_SCHEMA,
1985    oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_SENT_RAW_OID,
1986    variant: LogVariant::Timely(TimelyLog::BatchesSent),
1987    access: vec![PUBLIC_SELECT],
1988});
1989
1990pub static MZ_MESSAGE_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1991    name: "mz_message_counts_received_raw",
1992    schema: MZ_INTROSPECTION_SCHEMA,
1993    oid: oid::LOG_MZ_MESSAGE_COUNTS_RECEIVED_RAW_OID,
1994    variant: LogVariant::Timely(TimelyLog::MessagesReceived),
1995    access: vec![PUBLIC_SELECT],
1996});
1997
1998pub static MZ_MESSAGE_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1999    name: "mz_message_counts_sent_raw",
2000    schema: MZ_INTROSPECTION_SCHEMA,
2001    oid: oid::LOG_MZ_MESSAGE_COUNTS_SENT_RAW_OID,
2002    variant: LogVariant::Timely(TimelyLog::MessagesSent),
2003    access: vec![PUBLIC_SELECT],
2004});
2005
2006pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW: LazyLock<BuiltinLog> =
2007    LazyLock::new(|| BuiltinLog {
2008        name: "mz_dataflow_operator_reachability_raw",
2009        schema: MZ_INTROSPECTION_SCHEMA,
2010        oid: oid::LOG_MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW_OID,
2011        variant: LogVariant::Timely(TimelyLog::Reachability),
2012        access: vec![PUBLIC_SELECT],
2013    });
2014
2015pub static MZ_ICEBERG_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2016    name: "mz_iceberg_sinks",
2017    schema: MZ_CATALOG_SCHEMA,
2018    oid: oid::TABLE_MZ_ICEBERG_SINKS_OID,
2019    desc: RelationDesc::builder()
2020        .with_column("id", SqlScalarType::String.nullable(false))
2021        .with_column("namespace", SqlScalarType::String.nullable(false))
2022        .with_column("table", SqlScalarType::String.nullable(false))
2023        .finish(),
2024    column_comments: BTreeMap::from_iter([
2025        ("id", "The ID of the sink."),
2026        (
2027            "namespace",
2028            "The namespace of the Iceberg table into which the sink is writing.",
2029        ),
2030        ("table", "The Iceberg table into which the sink is writing."),
2031    ]),
2032    is_retained_metrics_object: false,
2033    access: vec![PUBLIC_SELECT],
2034});
2035
2036pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2037    name: "mz_kafka_sinks",
2038    schema: MZ_CATALOG_SCHEMA,
2039    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2040    desc: RelationDesc::builder()
2041        .with_column("id", SqlScalarType::String.nullable(false))
2042        .with_column("topic", SqlScalarType::String.nullable(false))
2043        .with_key(vec![0])
2044        .finish(),
2045    column_comments: BTreeMap::from_iter([
2046        ("id", "The ID of the sink."),
2047        (
2048            "topic",
2049            "The name of the Kafka topic into which the sink is writing.",
2050        ),
2051    ]),
2052    is_retained_metrics_object: false,
2053    access: vec![PUBLIC_SELECT],
2054});
2055pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2056    name: "mz_kafka_connections",
2057    schema: MZ_CATALOG_SCHEMA,
2058    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2059    desc: RelationDesc::builder()
2060        .with_column("id", SqlScalarType::String.nullable(false))
2061        .with_column(
2062            "brokers",
2063            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2064        )
2065        .with_column("sink_progress_topic", SqlScalarType::String.nullable(false))
2066        .finish(),
2067    column_comments: BTreeMap::from_iter([
2068        ("id", "The ID of the connection."),
2069        (
2070            "brokers",
2071            "The addresses of the Kafka brokers to connect to.",
2072        ),
2073        (
2074            "sink_progress_topic",
2075            "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.",
2076        ),
2077    ]),
2078    is_retained_metrics_object: false,
2079    access: vec![PUBLIC_SELECT],
2080});
2081pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2082    name: "mz_kafka_sources",
2083    schema: MZ_CATALOG_SCHEMA,
2084    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2085    desc: RelationDesc::builder()
2086        .with_column("id", SqlScalarType::String.nullable(false))
2087        .with_column("group_id_prefix", SqlScalarType::String.nullable(false))
2088        .with_column("topic", SqlScalarType::String.nullable(false))
2089        .finish(),
2090    column_comments: BTreeMap::from_iter([
2091        (
2092            "id",
2093            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2094        ),
2095        (
2096            "group_id_prefix",
2097            "The value of the `GROUP ID PREFIX` connection option.",
2098        ),
2099        (
2100            "topic",
2101            "The name of the Kafka topic the source is reading from.",
2102        ),
2103    ]),
2104    is_retained_metrics_object: false,
2105    access: vec![PUBLIC_SELECT],
2106});
2107pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2108    name: "mz_postgres_sources",
2109    schema: MZ_INTERNAL_SCHEMA,
2110    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2111    desc: RelationDesc::builder()
2112        .with_column("id", SqlScalarType::String.nullable(false))
2113        .with_column("replication_slot", SqlScalarType::String.nullable(false))
2114        .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
2115        .finish(),
2116    column_comments: BTreeMap::from_iter([
2117        (
2118            "id",
2119            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2120        ),
2121        (
2122            "replication_slot",
2123            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2124        ),
2125        (
2126            "timeline_id",
2127            "The PostgreSQL timeline ID determined on source creation.",
2128        ),
2129    ]),
2130    is_retained_metrics_object: false,
2131    access: vec![PUBLIC_SELECT],
2132});
2133pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2134    name: "mz_postgres_source_tables",
2135    schema: MZ_INTERNAL_SCHEMA,
2136    oid: oid::TABLE_MZ_POSTGRES_SOURCE_TABLES_OID,
2137    desc: RelationDesc::builder()
2138        .with_column("id", SqlScalarType::String.nullable(false))
2139        .with_column("schema_name", SqlScalarType::String.nullable(false))
2140        .with_column("table_name", SqlScalarType::String.nullable(false))
2141        .finish(),
2142    column_comments: BTreeMap::from_iter([
2143        (
2144            "id",
2145            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2146        ),
2147        (
2148            "schema_name",
2149            "The schema of the upstream table being ingested.",
2150        ),
2151        (
2152            "table_name",
2153            "The name of the upstream table being ingested.",
2154        ),
2155    ]),
2156    is_retained_metrics_object: true,
2157    access: vec![PUBLIC_SELECT],
2158});
2159pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2160    name: "mz_mysql_source_tables",
2161    schema: MZ_INTERNAL_SCHEMA,
2162    oid: oid::TABLE_MZ_MYSQL_SOURCE_TABLES_OID,
2163    desc: RelationDesc::builder()
2164        .with_column("id", SqlScalarType::String.nullable(false))
2165        .with_column("schema_name", SqlScalarType::String.nullable(false))
2166        .with_column("table_name", SqlScalarType::String.nullable(false))
2167        .finish(),
2168    column_comments: BTreeMap::from_iter([
2169        (
2170            "id",
2171            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2172        ),
2173        (
2174            "schema_name",
2175            "The schema (or, database) of the upstream table being ingested.",
2176        ),
2177        (
2178            "table_name",
2179            "The name of the upstream table being ingested.",
2180        ),
2181    ]),
2182    is_retained_metrics_object: true,
2183    access: vec![PUBLIC_SELECT],
2184});
2185pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2186    name: "mz_sql_server_source_tables",
2187    schema: MZ_INTERNAL_SCHEMA,
2188    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2189    desc: RelationDesc::builder()
2190        .with_column("id", SqlScalarType::String.nullable(false))
2191        .with_column("schema_name", SqlScalarType::String.nullable(false))
2192        .with_column("table_name", SqlScalarType::String.nullable(false))
2193        .finish(),
2194    column_comments: BTreeMap::from_iter([
2195        (
2196            "id",
2197            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2198        ),
2199        (
2200            "schema_name",
2201            "The schema of the upstream table being ingested.",
2202        ),
2203        (
2204            "table_name",
2205            "The name of the upstream table being ingested.",
2206        ),
2207    ]),
2208    is_retained_metrics_object: true,
2209    access: vec![PUBLIC_SELECT],
2210});
2211pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2212    name: "mz_kafka_source_tables",
2213    schema: MZ_INTERNAL_SCHEMA,
2214    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2215    desc: RelationDesc::builder()
2216        .with_column("id", SqlScalarType::String.nullable(false))
2217        .with_column("topic", SqlScalarType::String.nullable(false))
2218        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2219        .with_column("key_format", SqlScalarType::String.nullable(true))
2220        .with_column("value_format", SqlScalarType::String.nullable(true))
2221        .finish(),
2222    column_comments: BTreeMap::from_iter([
2223        (
2224            "id",
2225            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2226        ),
2227        ("topic", "The topic being ingested."),
2228        (
2229            "envelope_type",
2230            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2231        ),
2232        (
2233            "key_format",
2234            "The format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2235        ),
2236        (
2237            "value_format",
2238            "The format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2239        ),
2240    ]),
2241    is_retained_metrics_object: true,
2242    access: vec![PUBLIC_SELECT],
2243});
2244pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2245    name: "mz_object_dependencies",
2246    schema: MZ_INTERNAL_SCHEMA,
2247    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2248    desc: RelationDesc::builder()
2249        .with_column("object_id", SqlScalarType::String.nullable(false))
2250        .with_column(
2251            "referenced_object_id",
2252            SqlScalarType::String.nullable(false),
2253        )
2254        .finish(),
2255    column_comments: BTreeMap::from_iter([
2256        (
2257            "object_id",
2258            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2259        ),
2260        (
2261            "referenced_object_id",
2262            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2263        ),
2264    ]),
2265    is_retained_metrics_object: true,
2266    access: vec![PUBLIC_SELECT],
2267});
2268pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2269    name: "mz_compute_dependencies",
2270    schema: MZ_INTERNAL_SCHEMA,
2271    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2272    data_source: IntrospectionType::ComputeDependencies,
2273    desc: RelationDesc::builder()
2274        .with_column("object_id", SqlScalarType::String.nullable(false))
2275        .with_column("dependency_id", SqlScalarType::String.nullable(false))
2276        .finish(),
2277    column_comments: BTreeMap::from_iter([
2278        (
2279            "object_id",
2280            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2281        ),
2282        (
2283            "dependency_id",
2284            "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`.",
2285        ),
2286    ]),
2287    is_retained_metrics_object: false,
2288    access: vec![PUBLIC_SELECT],
2289});
2290
2291pub static MZ_DATABASES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2292    name: "mz_databases",
2293    schema: MZ_CATALOG_SCHEMA,
2294    oid: oid::TABLE_MZ_DATABASES_OID,
2295    desc: RelationDesc::builder()
2296        .with_column("id", SqlScalarType::String.nullable(false))
2297        .with_column("oid", SqlScalarType::Oid.nullable(false))
2298        .with_column("name", SqlScalarType::String.nullable(false))
2299        .with_column("owner_id", SqlScalarType::String.nullable(false))
2300        .with_column(
2301            "privileges",
2302            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2303        )
2304        .with_key(vec![0])
2305        .with_key(vec![1])
2306        .finish(),
2307    column_comments: BTreeMap::from_iter([
2308        ("id", "Materialize's unique ID for the database."),
2309        ("oid", "A PostgreSQL-compatible OID for the database."),
2310        ("name", "The name of the database."),
2311        (
2312            "owner_id",
2313            "The role ID of the owner of the database. Corresponds to `mz_roles.id`.",
2314        ),
2315        ("privileges", "The privileges belonging to the database."),
2316    ]),
2317    is_retained_metrics_object: false,
2318    access: vec![PUBLIC_SELECT],
2319});
2320pub static MZ_SCHEMAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2321    name: "mz_schemas",
2322    schema: MZ_CATALOG_SCHEMA,
2323    oid: oid::TABLE_MZ_SCHEMAS_OID,
2324    desc: RelationDesc::builder()
2325        .with_column("id", SqlScalarType::String.nullable(false))
2326        .with_column("oid", SqlScalarType::Oid.nullable(false))
2327        .with_column("database_id", SqlScalarType::String.nullable(true))
2328        .with_column("name", SqlScalarType::String.nullable(false))
2329        .with_column("owner_id", SqlScalarType::String.nullable(false))
2330        .with_column(
2331            "privileges",
2332            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2333        )
2334        .with_key(vec![0])
2335        .with_key(vec![1])
2336        .finish(),
2337    column_comments: BTreeMap::from_iter([
2338        ("id", "Materialize's unique ID for the schema."),
2339        ("oid", "A PostgreSQL-compatible oid for the schema."),
2340        (
2341            "database_id",
2342            "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2343        ),
2344        ("name", "The name of the schema."),
2345        (
2346            "owner_id",
2347            "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2348        ),
2349        ("privileges", "The privileges belonging to the schema."),
2350    ]),
2351    is_retained_metrics_object: false,
2352    access: vec![PUBLIC_SELECT],
2353});
2354pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2355    name: "mz_columns",
2356    schema: MZ_CATALOG_SCHEMA,
2357    oid: oid::TABLE_MZ_COLUMNS_OID,
2358    desc: RelationDesc::builder()
2359        .with_column("id", SqlScalarType::String.nullable(false)) // not a key
2360        .with_column("name", SqlScalarType::String.nullable(false))
2361        .with_column("position", SqlScalarType::UInt64.nullable(false))
2362        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2363        .with_column("type", SqlScalarType::String.nullable(false))
2364        .with_column("default", SqlScalarType::String.nullable(true))
2365        .with_column("type_oid", SqlScalarType::Oid.nullable(false))
2366        .with_column("type_mod", SqlScalarType::Int32.nullable(false))
2367        .finish(),
2368    column_comments: BTreeMap::from_iter([
2369        (
2370            "id",
2371            "The unique ID of the table, source, or view containing the column.",
2372        ),
2373        ("name", "The name of the column."),
2374        (
2375            "position",
2376            "The 1-indexed position of the column in its containing table, source, or view.",
2377        ),
2378        ("nullable", "Can the column contain a `NULL` value?"),
2379        ("type", "The data type of the column."),
2380        ("default", "The default expression of the column."),
2381        (
2382            "type_oid",
2383            "The OID of the type of the column (references `mz_types`).",
2384        ),
2385        ("type_mod", "The packed type identifier of the column."),
2386    ]),
2387    is_retained_metrics_object: false,
2388    access: vec![PUBLIC_SELECT],
2389});
2390pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2391    name: "mz_indexes",
2392    schema: MZ_CATALOG_SCHEMA,
2393    oid: oid::TABLE_MZ_INDEXES_OID,
2394    desc: RelationDesc::builder()
2395        .with_column("id", SqlScalarType::String.nullable(false))
2396        .with_column("oid", SqlScalarType::Oid.nullable(false))
2397        .with_column("name", SqlScalarType::String.nullable(false))
2398        .with_column("on_id", SqlScalarType::String.nullable(false))
2399        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2400        .with_column("owner_id", SqlScalarType::String.nullable(false))
2401        .with_column("create_sql", SqlScalarType::String.nullable(false))
2402        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2403        .with_key(vec![0])
2404        .with_key(vec![1])
2405        .finish(),
2406    column_comments: BTreeMap::from_iter([
2407        ("id", "Materialize's unique ID for the index."),
2408        ("oid", "A PostgreSQL-compatible OID for the index."),
2409        ("name", "The name of the index."),
2410        (
2411            "on_id",
2412            "The ID of the relation on which the index is built.",
2413        ),
2414        (
2415            "cluster_id",
2416            "The ID of the cluster in which the index is built.",
2417        ),
2418        (
2419            "owner_id",
2420            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2421        ),
2422        ("create_sql", "The `CREATE` SQL statement for the index."),
2423        (
2424            "redacted_create_sql",
2425            "The redacted `CREATE` SQL statement for the index.",
2426        ),
2427    ]),
2428    is_retained_metrics_object: false,
2429    access: vec![PUBLIC_SELECT],
2430});
2431pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2432    name: "mz_index_columns",
2433    schema: MZ_CATALOG_SCHEMA,
2434    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2435    desc: RelationDesc::builder()
2436        .with_column("index_id", SqlScalarType::String.nullable(false))
2437        .with_column("index_position", SqlScalarType::UInt64.nullable(false))
2438        .with_column("on_position", SqlScalarType::UInt64.nullable(true))
2439        .with_column("on_expression", SqlScalarType::String.nullable(true))
2440        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2441        .finish(),
2442    column_comments: BTreeMap::from_iter([
2443        (
2444            "index_id",
2445            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2446        ),
2447        (
2448            "index_position",
2449            "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.)",
2450        ),
2451        (
2452            "on_position",
2453            "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.",
2454        ),
2455        (
2456            "on_expression",
2457            "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.",
2458        ),
2459        (
2460            "nullable",
2461            "Can this column of the index evaluate to `NULL`?",
2462        ),
2463    ]),
2464    is_retained_metrics_object: false,
2465    access: vec![PUBLIC_SELECT],
2466});
2467pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2468    name: "mz_tables",
2469    schema: MZ_CATALOG_SCHEMA,
2470    oid: oid::TABLE_MZ_TABLES_OID,
2471    desc: RelationDesc::builder()
2472        .with_column("id", SqlScalarType::String.nullable(false))
2473        .with_column("oid", SqlScalarType::Oid.nullable(false))
2474        .with_column("schema_id", SqlScalarType::String.nullable(false))
2475        .with_column("name", SqlScalarType::String.nullable(false))
2476        .with_column("owner_id", SqlScalarType::String.nullable(false))
2477        .with_column(
2478            "privileges",
2479            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2480        )
2481        .with_column("create_sql", SqlScalarType::String.nullable(true))
2482        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2483        .with_column("source_id", SqlScalarType::String.nullable(true))
2484        .with_key(vec![0])
2485        .with_key(vec![1])
2486        .finish(),
2487    column_comments: BTreeMap::from_iter([
2488        ("id", "Materialize's unique ID for the table."),
2489        ("oid", "A PostgreSQL-compatible OID for the table."),
2490        (
2491            "schema_id",
2492            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2493        ),
2494        ("name", "The name of the table."),
2495        (
2496            "owner_id",
2497            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2498        ),
2499        ("privileges", "The privileges belonging to the table."),
2500        ("create_sql", "The `CREATE` SQL statement for the table."),
2501        (
2502            "redacted_create_sql",
2503            "The redacted `CREATE` SQL statement for the table.",
2504        ),
2505        (
2506            "source_id",
2507            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2508        ),
2509    ]),
2510    is_retained_metrics_object: true,
2511    access: vec![PUBLIC_SELECT],
2512});
2513pub static MZ_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2514    name: "mz_connections",
2515    schema: MZ_CATALOG_SCHEMA,
2516    oid: oid::TABLE_MZ_CONNECTIONS_OID,
2517    desc: RelationDesc::builder()
2518        .with_column("id", SqlScalarType::String.nullable(false))
2519        .with_column("oid", SqlScalarType::Oid.nullable(false))
2520        .with_column("schema_id", SqlScalarType::String.nullable(false))
2521        .with_column("name", SqlScalarType::String.nullable(false))
2522        .with_column("type", SqlScalarType::String.nullable(false))
2523        .with_column("owner_id", SqlScalarType::String.nullable(false))
2524        .with_column(
2525            "privileges",
2526            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2527        )
2528        .with_column("create_sql", SqlScalarType::String.nullable(false))
2529        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2530        .with_key(vec![0])
2531        .with_key(vec![1])
2532        .finish(),
2533    column_comments: BTreeMap::from_iter([
2534        ("id", "The unique ID of the connection."),
2535        ("oid", "A PostgreSQL-compatible OID for the connection."),
2536        (
2537            "schema_id",
2538            "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2539        ),
2540        ("name", "The name of the connection."),
2541        (
2542            "type",
2543            "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2544        ),
2545        (
2546            "owner_id",
2547            "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2548        ),
2549        ("privileges", "The privileges belonging to the connection."),
2550        (
2551            "create_sql",
2552            "The `CREATE` SQL statement for the connection.",
2553        ),
2554        (
2555            "redacted_create_sql",
2556            "The redacted `CREATE` SQL statement for the connection.",
2557        ),
2558    ]),
2559    is_retained_metrics_object: false,
2560    access: vec![PUBLIC_SELECT],
2561});
2562pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2563    name: "mz_ssh_tunnel_connections",
2564    schema: MZ_CATALOG_SCHEMA,
2565    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2566    desc: RelationDesc::builder()
2567        .with_column("id", SqlScalarType::String.nullable(false))
2568        .with_column("public_key_1", SqlScalarType::String.nullable(false))
2569        .with_column("public_key_2", SqlScalarType::String.nullable(false))
2570        .finish(),
2571    column_comments: BTreeMap::from_iter([
2572        ("id", "The ID of the connection."),
2573        (
2574            "public_key_1",
2575            "The first public key associated with the SSH tunnel.",
2576        ),
2577        (
2578            "public_key_2",
2579            "The second public key associated with the SSH tunnel.",
2580        ),
2581    ]),
2582    is_retained_metrics_object: false,
2583    access: vec![PUBLIC_SELECT],
2584});
2585pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2586    name: "mz_sources",
2587    schema: MZ_CATALOG_SCHEMA,
2588    oid: oid::TABLE_MZ_SOURCES_OID,
2589    desc: RelationDesc::builder()
2590        .with_column("id", SqlScalarType::String.nullable(false))
2591        .with_column("oid", SqlScalarType::Oid.nullable(false))
2592        .with_column("schema_id", SqlScalarType::String.nullable(false))
2593        .with_column("name", SqlScalarType::String.nullable(false))
2594        .with_column("type", SqlScalarType::String.nullable(false))
2595        .with_column("connection_id", SqlScalarType::String.nullable(true))
2596        .with_column("size", SqlScalarType::String.nullable(true))
2597        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2598        .with_column("key_format", SqlScalarType::String.nullable(true))
2599        .with_column("value_format", SqlScalarType::String.nullable(true))
2600        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2601        .with_column("owner_id", SqlScalarType::String.nullable(false))
2602        .with_column(
2603            "privileges",
2604            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2605        )
2606        .with_column("create_sql", SqlScalarType::String.nullable(true))
2607        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2608        .with_key(vec![0])
2609        .with_key(vec![1])
2610        .finish(),
2611    column_comments: BTreeMap::from_iter([
2612        ("id", "Materialize's unique ID for the source."),
2613        ("oid", "A PostgreSQL-compatible OID for the source."),
2614        (
2615            "schema_id",
2616            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2617        ),
2618        ("name", "The name of the source."),
2619        (
2620            "type",
2621            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2622        ),
2623        (
2624            "connection_id",
2625            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2626        ),
2627        ("size", "*Deprecated* The size of the source."),
2628        (
2629            "envelope_type",
2630            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2631        ),
2632        (
2633            "key_format",
2634            "For Kafka sources, the format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2635        ),
2636        (
2637            "value_format",
2638            "For Kafka sources, the format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2639        ),
2640        (
2641            "cluster_id",
2642            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2643        ),
2644        (
2645            "owner_id",
2646            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2647        ),
2648        ("privileges", "The privileges granted on the source."),
2649        ("create_sql", "The `CREATE` SQL statement for the source."),
2650        (
2651            "redacted_create_sql",
2652            "The redacted `CREATE` SQL statement for the source.",
2653        ),
2654    ]),
2655    is_retained_metrics_object: true,
2656    access: vec![PUBLIC_SELECT],
2657});
2658pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2659    BuiltinTable {
2660        name: "mz_sinks",
2661        schema: MZ_CATALOG_SCHEMA,
2662        oid: oid::TABLE_MZ_SINKS_OID,
2663        desc: RelationDesc::builder()
2664            .with_column("id", SqlScalarType::String.nullable(false))
2665            .with_column("oid", SqlScalarType::Oid.nullable(false))
2666            .with_column("schema_id", SqlScalarType::String.nullable(false))
2667            .with_column("name", SqlScalarType::String.nullable(false))
2668            .with_column("type", SqlScalarType::String.nullable(false))
2669            .with_column("connection_id", SqlScalarType::String.nullable(true))
2670            .with_column("size", SqlScalarType::String.nullable(true))
2671            .with_column("envelope_type", SqlScalarType::String.nullable(true))
2672            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2673            // below. This should be removed in the future.
2674            .with_column("format", SqlScalarType::String.nullable(true))
2675            .with_column("key_format", SqlScalarType::String.nullable(true))
2676            .with_column("value_format", SqlScalarType::String.nullable(true))
2677            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2678            .with_column("owner_id", SqlScalarType::String.nullable(false))
2679            .with_column("create_sql", SqlScalarType::String.nullable(false))
2680            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2681            .with_key(vec![0])
2682            .with_key(vec![1])
2683            .finish(),
2684        column_comments: BTreeMap::from_iter([
2685            ("id", "Materialize's unique ID for the sink."),
2686            ("oid", "A PostgreSQL-compatible OID for the sink."),
2687            (
2688                "schema_id",
2689                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2690            ),
2691            ("name", "The name of the sink."),
2692            ("type", "The type of the sink: `kafka`."),
2693            (
2694                "connection_id",
2695                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2696            ),
2697            ("size", "The size of the sink."),
2698            (
2699                "envelope_type",
2700                "The envelope of the sink: `upsert`, or `debezium`.",
2701            ),
2702            (
2703                "format",
2704                "*Deprecated* The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2705            ),
2706            (
2707                "key_format",
2708                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2709            ),
2710            (
2711                "value_format",
2712                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2713            ),
2714            (
2715                "cluster_id",
2716                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2717            ),
2718            (
2719                "owner_id",
2720                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2721            ),
2722            ("create_sql", "The `CREATE` SQL statement for the sink."),
2723            (
2724                "redacted_create_sql",
2725                "The redacted `CREATE` SQL statement for the sink.",
2726            ),
2727        ]),
2728        is_retained_metrics_object: true,
2729        access: vec![PUBLIC_SELECT],
2730    }
2731});
2732pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2733    name: "mz_views",
2734    schema: MZ_CATALOG_SCHEMA,
2735    oid: oid::TABLE_MZ_VIEWS_OID,
2736    desc: RelationDesc::builder()
2737        .with_column("id", SqlScalarType::String.nullable(false))
2738        .with_column("oid", SqlScalarType::Oid.nullable(false))
2739        .with_column("schema_id", SqlScalarType::String.nullable(false))
2740        .with_column("name", SqlScalarType::String.nullable(false))
2741        .with_column("definition", SqlScalarType::String.nullable(false))
2742        .with_column("owner_id", SqlScalarType::String.nullable(false))
2743        .with_column(
2744            "privileges",
2745            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2746        )
2747        .with_column("create_sql", SqlScalarType::String.nullable(false))
2748        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2749        .with_key(vec![0])
2750        .with_key(vec![1])
2751        .finish(),
2752    column_comments: BTreeMap::from_iter([
2753        ("id", "Materialize's unique ID for the view."),
2754        ("oid", "A PostgreSQL-compatible OID for the view."),
2755        (
2756            "schema_id",
2757            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2758        ),
2759        ("name", "The name of the view."),
2760        ("definition", "The view definition (a `SELECT` query)."),
2761        (
2762            "owner_id",
2763            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2764        ),
2765        ("privileges", "The privileges belonging to the view."),
2766        ("create_sql", "The `CREATE` SQL statement for the view."),
2767        (
2768            "redacted_create_sql",
2769            "The redacted `CREATE` SQL statement for the view.",
2770        ),
2771    ]),
2772    is_retained_metrics_object: false,
2773    access: vec![PUBLIC_SELECT],
2774});
2775pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2776    name: "mz_materialized_views",
2777    schema: MZ_CATALOG_SCHEMA,
2778    oid: oid::TABLE_MZ_MATERIALIZED_VIEWS_OID,
2779    desc: RelationDesc::builder()
2780        .with_column("id", SqlScalarType::String.nullable(false))
2781        .with_column("oid", SqlScalarType::Oid.nullable(false))
2782        .with_column("schema_id", SqlScalarType::String.nullable(false))
2783        .with_column("name", SqlScalarType::String.nullable(false))
2784        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2785        .with_column("definition", SqlScalarType::String.nullable(false))
2786        .with_column("owner_id", SqlScalarType::String.nullable(false))
2787        .with_column(
2788            "privileges",
2789            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2790        )
2791        .with_column("create_sql", SqlScalarType::String.nullable(false))
2792        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2793        .with_key(vec![0])
2794        .with_key(vec![1])
2795        .finish(),
2796    column_comments: BTreeMap::from_iter([
2797        ("id", "Materialize's unique ID for the materialized view."),
2798        (
2799            "oid",
2800            "A PostgreSQL-compatible OID for the materialized view.",
2801        ),
2802        (
2803            "schema_id",
2804            "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2805        ),
2806        ("name", "The name of the materialized view."),
2807        (
2808            "cluster_id",
2809            "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2810        ),
2811        (
2812            "definition",
2813            "The materialized view definition (a `SELECT` query).",
2814        ),
2815        (
2816            "owner_id",
2817            "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2818        ),
2819        (
2820            "privileges",
2821            "The privileges belonging to the materialized view.",
2822        ),
2823        (
2824            "create_sql",
2825            "The `CREATE` SQL statement for the materialized view.",
2826        ),
2827        (
2828            "redacted_create_sql",
2829            "The redacted `CREATE` SQL statement for the materialized view.",
2830        ),
2831    ]),
2832    is_retained_metrics_object: false,
2833    access: vec![PUBLIC_SELECT],
2834});
2835pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
2836    BuiltinTable {
2837        name: "mz_materialized_view_refresh_strategies",
2838        schema: MZ_INTERNAL_SCHEMA,
2839        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
2840        desc: RelationDesc::builder()
2841            .with_column(
2842                "materialized_view_id",
2843                SqlScalarType::String.nullable(false),
2844            )
2845            .with_column("type", SqlScalarType::String.nullable(false))
2846            .with_column("interval", SqlScalarType::Interval.nullable(true))
2847            .with_column(
2848                "aligned_to",
2849                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2850            )
2851            .with_column(
2852                "at",
2853                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2854            )
2855            .finish(),
2856        column_comments: BTreeMap::from_iter([
2857            (
2858                "materialized_view_id",
2859                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
2860            ),
2861            (
2862                "type",
2863                "`at`, `every`, or `on-commit`. Default: `on-commit`",
2864            ),
2865            (
2866                "interval",
2867                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2868            ),
2869            (
2870                "aligned_to",
2871                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2872            ),
2873            (
2874                "at",
2875                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
2876            ),
2877        ]),
2878        is_retained_metrics_object: false,
2879        access: vec![PUBLIC_SELECT],
2880    }
2881});
2882pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2883    name: "mz_types",
2884    schema: MZ_CATALOG_SCHEMA,
2885    oid: oid::TABLE_MZ_TYPES_OID,
2886    desc: RelationDesc::builder()
2887        .with_column("id", SqlScalarType::String.nullable(false))
2888        .with_column("oid", SqlScalarType::Oid.nullable(false))
2889        .with_column("schema_id", SqlScalarType::String.nullable(false))
2890        .with_column("name", SqlScalarType::String.nullable(false))
2891        .with_column("category", SqlScalarType::String.nullable(false))
2892        .with_column("owner_id", SqlScalarType::String.nullable(false))
2893        .with_column(
2894            "privileges",
2895            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2896        )
2897        .with_column("create_sql", SqlScalarType::String.nullable(true))
2898        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2899        .with_key(vec![0])
2900        .with_key(vec![1])
2901        .finish(),
2902    column_comments: BTreeMap::from_iter([
2903        ("id", "Materialize's unique ID for the type."),
2904        ("oid", "A PostgreSQL-compatible OID for the type."),
2905        (
2906            "schema_id",
2907            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
2908        ),
2909        ("name", "The name of the type."),
2910        ("category", "The category of the type."),
2911        (
2912            "owner_id",
2913            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
2914        ),
2915        ("privileges", "The privileges belonging to the type."),
2916        ("create_sql", "The `CREATE` SQL statement for the type."),
2917        (
2918            "redacted_create_sql",
2919            "The redacted `CREATE` SQL statement for the type.",
2920        ),
2921    ]),
2922    is_retained_metrics_object: false,
2923    access: vec![PUBLIC_SELECT],
2924});
2925pub static MZ_CONTINUAL_TASKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2926    name: "mz_continual_tasks",
2927    schema: MZ_INTERNAL_SCHEMA,
2928    oid: oid::TABLE_MZ_CONTINUAL_TASKS_OID,
2929    desc: RelationDesc::builder()
2930        .with_column("id", SqlScalarType::String.nullable(false))
2931        .with_column("oid", SqlScalarType::Oid.nullable(false))
2932        .with_column("schema_id", SqlScalarType::String.nullable(false))
2933        .with_column("name", SqlScalarType::String.nullable(false))
2934        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2935        .with_column("definition", SqlScalarType::String.nullable(false))
2936        .with_column("owner_id", SqlScalarType::String.nullable(false))
2937        .with_column(
2938            "privileges",
2939            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2940        )
2941        .with_column("create_sql", SqlScalarType::String.nullable(false))
2942        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2943        .with_key(vec![0])
2944        .with_key(vec![1])
2945        .finish(),
2946    column_comments: BTreeMap::new(),
2947    is_retained_metrics_object: false,
2948    access: vec![PUBLIC_SELECT],
2949});
2950pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2951    name: "mz_network_policies",
2952    schema: MZ_INTERNAL_SCHEMA,
2953    oid: oid::TABLE_MZ_NETWORK_POLICIES_OID,
2954    desc: RelationDesc::builder()
2955        .with_column("id", SqlScalarType::String.nullable(false))
2956        .with_column("name", SqlScalarType::String.nullable(false))
2957        .with_column("owner_id", SqlScalarType::String.nullable(false))
2958        .with_column(
2959            "privileges",
2960            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2961        )
2962        .with_column("oid", SqlScalarType::Oid.nullable(false))
2963        .finish(),
2964    column_comments: BTreeMap::from_iter([
2965        ("id", "The ID of the network policy."),
2966        ("name", "The name of the network policy."),
2967        (
2968            "owner_id",
2969            "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
2970        ),
2971        (
2972            "privileges",
2973            "The privileges belonging to the network policy.",
2974        ),
2975        ("oid", "A PostgreSQL-compatible OID for the network policy."),
2976    ]),
2977    is_retained_metrics_object: false,
2978    access: vec![PUBLIC_SELECT],
2979});
2980pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2981    name: "mz_network_policy_rules",
2982    schema: MZ_INTERNAL_SCHEMA,
2983    oid: oid::TABLE_MZ_NETWORK_POLICY_RULES_OID,
2984    desc: RelationDesc::builder()
2985        .with_column("name", SqlScalarType::String.nullable(false))
2986        .with_column("policy_id", SqlScalarType::String.nullable(false))
2987        .with_column("action", SqlScalarType::String.nullable(false))
2988        .with_column("address", SqlScalarType::String.nullable(false))
2989        .with_column("direction", SqlScalarType::String.nullable(false))
2990        .finish(),
2991    column_comments: BTreeMap::from_iter([
2992        (
2993            "name",
2994            "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
2995        ),
2996        (
2997            "policy_id",
2998            "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
2999        ),
3000        (
3001            "action",
3002            "The action of the rule. `allow` is the only supported action.",
3003        ),
3004        ("address", "The address the rule will take action on."),
3005        (
3006            "direction",
3007            "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3008        ),
3009    ]),
3010    is_retained_metrics_object: false,
3011    access: vec![PUBLIC_SELECT],
3012});
3013/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3014/// in the `mz_types` table as part of our public, stable API.
3015pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3016    name: "mz_type_pg_metadata",
3017    schema: MZ_INTERNAL_SCHEMA,
3018    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3019    desc: RelationDesc::builder()
3020        .with_column("id", SqlScalarType::String.nullable(false))
3021        .with_column("typinput", SqlScalarType::Oid.nullable(false))
3022        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
3023        .finish(),
3024    column_comments: BTreeMap::new(),
3025    is_retained_metrics_object: false,
3026    access: vec![PUBLIC_SELECT],
3027});
3028pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3029    name: "mz_array_types",
3030    schema: MZ_CATALOG_SCHEMA,
3031    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3032    desc: RelationDesc::builder()
3033        .with_column("id", SqlScalarType::String.nullable(false))
3034        .with_column("element_id", SqlScalarType::String.nullable(false))
3035        .finish(),
3036    column_comments: BTreeMap::from_iter([
3037        ("id", "The ID of the array type."),
3038        ("element_id", "The ID of the array's element type."),
3039    ]),
3040    is_retained_metrics_object: false,
3041    access: vec![PUBLIC_SELECT],
3042});
3043pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3044    name: "mz_base_types",
3045    schema: MZ_CATALOG_SCHEMA,
3046    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3047    desc: RelationDesc::builder()
3048        .with_column("id", SqlScalarType::String.nullable(false))
3049        .finish(),
3050    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3051    is_retained_metrics_object: false,
3052    access: vec![PUBLIC_SELECT],
3053});
3054pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3055    name: "mz_list_types",
3056    schema: MZ_CATALOG_SCHEMA,
3057    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3058    desc: RelationDesc::builder()
3059        .with_column("id", SqlScalarType::String.nullable(false))
3060        .with_column("element_id", SqlScalarType::String.nullable(false))
3061        .with_column(
3062            "element_modifiers",
3063            SqlScalarType::List {
3064                element_type: Box::new(SqlScalarType::Int64),
3065                custom_id: None,
3066            }
3067            .nullable(true),
3068        )
3069        .finish(),
3070    column_comments: BTreeMap::from_iter([
3071        ("id", "The ID of the list type."),
3072        ("element_id", "The IID of the list's element type."),
3073        (
3074            "element_modifiers",
3075            "The element type modifiers, or `NULL` if none.",
3076        ),
3077    ]),
3078    is_retained_metrics_object: false,
3079    access: vec![PUBLIC_SELECT],
3080});
3081pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3082    name: "mz_map_types",
3083    schema: MZ_CATALOG_SCHEMA,
3084    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3085    desc: RelationDesc::builder()
3086        .with_column("id", SqlScalarType::String.nullable(false))
3087        .with_column("key_id", SqlScalarType::String.nullable(false))
3088        .with_column("value_id", SqlScalarType::String.nullable(false))
3089        .with_column(
3090            "key_modifiers",
3091            SqlScalarType::List {
3092                element_type: Box::new(SqlScalarType::Int64),
3093                custom_id: None,
3094            }
3095            .nullable(true),
3096        )
3097        .with_column(
3098            "value_modifiers",
3099            SqlScalarType::List {
3100                element_type: Box::new(SqlScalarType::Int64),
3101                custom_id: None,
3102            }
3103            .nullable(true),
3104        )
3105        .finish(),
3106    column_comments: BTreeMap::from_iter([
3107        ("id", "The ID of the map type."),
3108        ("key_id", "The ID of the map's key type."),
3109        ("value_id", "The ID of the map's value type."),
3110        (
3111            "key_modifiers",
3112            "The key type modifiers, or `NULL` if none.",
3113        ),
3114        (
3115            "value_modifiers",
3116            "The value type modifiers, or `NULL` if none.",
3117        ),
3118    ]),
3119    is_retained_metrics_object: false,
3120    access: vec![PUBLIC_SELECT],
3121});
3122pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3123    name: "mz_roles",
3124    schema: MZ_CATALOG_SCHEMA,
3125    oid: oid::TABLE_MZ_ROLES_OID,
3126    desc: RelationDesc::builder()
3127        .with_column("id", SqlScalarType::String.nullable(false))
3128        .with_column("oid", SqlScalarType::Oid.nullable(false))
3129        .with_column("name", SqlScalarType::String.nullable(false))
3130        .with_column("inherit", SqlScalarType::Bool.nullable(false))
3131        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(true))
3132        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
3133        .with_key(vec![0])
3134        .with_key(vec![1])
3135        .finish(),
3136    column_comments: BTreeMap::from_iter([
3137        ("id", "Materialize's unique ID for the role."),
3138        ("oid", "A PostgreSQL-compatible OID for the role."),
3139        ("name", "The name of the role."),
3140        (
3141            "inherit",
3142            "Indicates whether the role has inheritance of privileges.",
3143        ),
3144        ("rolcanlogin", "Indicates whether the role can log in."),
3145        ("rolsuper", "Indicates whether the role is a superuser."),
3146    ]),
3147    is_retained_metrics_object: false,
3148    access: vec![PUBLIC_SELECT],
3149});
3150pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3151    name: "mz_role_members",
3152    schema: MZ_CATALOG_SCHEMA,
3153    oid: oid::TABLE_MZ_ROLE_MEMBERS_OID,
3154    desc: RelationDesc::builder()
3155        .with_column("role_id", SqlScalarType::String.nullable(false))
3156        .with_column("member", SqlScalarType::String.nullable(false))
3157        .with_column("grantor", SqlScalarType::String.nullable(false))
3158        .finish(),
3159    column_comments: BTreeMap::from_iter([
3160        (
3161            "role_id",
3162            "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3163        ),
3164        (
3165            "member",
3166            "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3167        ),
3168        (
3169            "grantor",
3170            "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3171        ),
3172    ]),
3173    is_retained_metrics_object: false,
3174    access: vec![PUBLIC_SELECT],
3175});
3176pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3177    name: "mz_role_parameters",
3178    schema: MZ_CATALOG_SCHEMA,
3179    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3180    desc: RelationDesc::builder()
3181        .with_column("role_id", SqlScalarType::String.nullable(false))
3182        .with_column("parameter_name", SqlScalarType::String.nullable(false))
3183        .with_column("parameter_value", SqlScalarType::String.nullable(false))
3184        .finish(),
3185    column_comments: BTreeMap::from_iter([
3186        (
3187            "role_id",
3188            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3189        ),
3190        (
3191            "parameter_name",
3192            "The configuration parameter name. One of the supported configuration parameters.",
3193        ),
3194        (
3195            "parameter_value",
3196            "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.",
3197        ),
3198    ]),
3199    is_retained_metrics_object: false,
3200    access: vec![PUBLIC_SELECT],
3201});
3202pub static MZ_ROLE_AUTH: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3203    name: "mz_role_auth",
3204    schema: MZ_CATALOG_SCHEMA,
3205    oid: oid::TABLE_MZ_ROLE_AUTH_OID,
3206    desc: RelationDesc::builder()
3207        .with_column("role_id", SqlScalarType::String.nullable(false))
3208        .with_column("role_oid", SqlScalarType::Oid.nullable(false))
3209        .with_column("password_hash", SqlScalarType::String.nullable(true))
3210        .with_column(
3211            "updated_at",
3212            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3213        )
3214        .finish(),
3215    column_comments: BTreeMap::from_iter([
3216        (
3217            "role_id",
3218            "The ID of the role. Corresponds to `mz_roles.id`.",
3219        ),
3220        ("role_oid", "A PostgreSQL-compatible OID for the role."),
3221        (
3222            "password_hash",
3223            "The hashed password for the role, if any. Uses the `SCRAM-SHA-256` algorithm.",
3224        ),
3225        (
3226            "updated_at",
3227            "The time at which the password was last updated.",
3228        ),
3229    ]),
3230    is_retained_metrics_object: false,
3231    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
3232});
3233pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3234    name: "mz_pseudo_types",
3235    schema: MZ_CATALOG_SCHEMA,
3236    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3237    desc: RelationDesc::builder()
3238        .with_column("id", SqlScalarType::String.nullable(false))
3239        .finish(),
3240    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3241    is_retained_metrics_object: false,
3242    access: vec![PUBLIC_SELECT],
3243});
3244pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3245    BuiltinTable {
3246        name: "mz_functions",
3247        schema: MZ_CATALOG_SCHEMA,
3248        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3249        desc: RelationDesc::builder()
3250            .with_column("id", SqlScalarType::String.nullable(false)) // not a key!
3251            .with_column("oid", SqlScalarType::Oid.nullable(false))
3252            .with_column("schema_id", SqlScalarType::String.nullable(false))
3253            .with_column("name", SqlScalarType::String.nullable(false))
3254            .with_column(
3255                "argument_type_ids",
3256                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3257            )
3258            .with_column(
3259                "variadic_argument_type_id",
3260                SqlScalarType::String.nullable(true),
3261            )
3262            .with_column("return_type_id", SqlScalarType::String.nullable(true))
3263            .with_column("returns_set", SqlScalarType::Bool.nullable(false))
3264            .with_column("owner_id", SqlScalarType::String.nullable(false))
3265            .finish(),
3266        column_comments: BTreeMap::from_iter([
3267            ("id", "Materialize's unique ID for the function."),
3268            ("oid", "A PostgreSQL-compatible OID for the function."),
3269            (
3270                "schema_id",
3271                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3272            ),
3273            ("name", "The name of the function."),
3274            (
3275                "argument_type_ids",
3276                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3277            ),
3278            (
3279                "variadic_argument_type_id",
3280                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3281            ),
3282            (
3283                "return_type_id",
3284                "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`].",
3285            ),
3286            (
3287                "returns_set",
3288                "Whether the function returns a set, i.e. the function is a table function.",
3289            ),
3290            (
3291                "owner_id",
3292                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3293            ),
3294        ]),
3295        is_retained_metrics_object: false,
3296        access: vec![PUBLIC_SELECT],
3297    }
3298});
3299pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3300    name: "mz_operators",
3301    schema: MZ_CATALOG_SCHEMA,
3302    oid: oid::TABLE_MZ_OPERATORS_OID,
3303    desc: RelationDesc::builder()
3304        .with_column("oid", SqlScalarType::Oid.nullable(false))
3305        .with_column("name", SqlScalarType::String.nullable(false))
3306        .with_column(
3307            "argument_type_ids",
3308            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3309        )
3310        .with_column("return_type_id", SqlScalarType::String.nullable(true))
3311        .finish(),
3312    column_comments: BTreeMap::new(),
3313    is_retained_metrics_object: false,
3314    access: vec![PUBLIC_SELECT],
3315});
3316pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3317    name: "mz_aggregates",
3318    schema: MZ_INTERNAL_SCHEMA,
3319    oid: oid::TABLE_MZ_AGGREGATES_OID,
3320    desc: RelationDesc::builder()
3321        .with_column("oid", SqlScalarType::Oid.nullable(false))
3322        .with_column("agg_kind", SqlScalarType::String.nullable(false))
3323        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
3324        .finish(),
3325    column_comments: BTreeMap::new(),
3326    is_retained_metrics_object: false,
3327    access: vec![PUBLIC_SELECT],
3328});
3329
3330pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3331    name: "mz_clusters",
3332    schema: MZ_CATALOG_SCHEMA,
3333    oid: oid::TABLE_MZ_CLUSTERS_OID,
3334    desc: RelationDesc::builder()
3335        .with_column("id", SqlScalarType::String.nullable(false))
3336        .with_column("name", SqlScalarType::String.nullable(false))
3337        .with_column("owner_id", SqlScalarType::String.nullable(false))
3338        .with_column(
3339            "privileges",
3340            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3341        )
3342        .with_column("managed", SqlScalarType::Bool.nullable(false))
3343        .with_column("size", SqlScalarType::String.nullable(true))
3344        .with_column("replication_factor", SqlScalarType::UInt32.nullable(true))
3345        .with_column("disk", SqlScalarType::Bool.nullable(true))
3346        .with_column(
3347            "availability_zones",
3348            SqlScalarType::List {
3349                element_type: Box::new(SqlScalarType::String),
3350                custom_id: None,
3351            }
3352            .nullable(true),
3353        )
3354        .with_column(
3355            "introspection_debugging",
3356            SqlScalarType::Bool.nullable(true),
3357        )
3358        .with_column(
3359            "introspection_interval",
3360            SqlScalarType::Interval.nullable(true),
3361        )
3362        .with_key(vec![0])
3363        .finish(),
3364    column_comments: BTreeMap::from_iter([
3365        ("id", "Materialize's unique ID for the cluster."),
3366        ("name", "The name of the cluster."),
3367        (
3368            "owner_id",
3369            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3370        ),
3371        ("privileges", "The privileges belonging to the cluster."),
3372        (
3373            "managed",
3374            "Whether the cluster is a managed cluster with automatically managed replicas.",
3375        ),
3376        (
3377            "size",
3378            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3379        ),
3380        (
3381            "replication_factor",
3382            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3383        ),
3384        (
3385            "disk",
3386            "**Unstable** If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3387        ),
3388        (
3389            "availability_zones",
3390            "**Unstable** If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3391        ),
3392        (
3393            "introspection_debugging",
3394            "Whether introspection of the gathering of the introspection data is enabled.",
3395        ),
3396        (
3397            "introspection_interval",
3398            "The interval at which to collect introspection data.",
3399        ),
3400    ]),
3401    is_retained_metrics_object: false,
3402    access: vec![PUBLIC_SELECT],
3403});
3404
3405pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3406    name: "mz_cluster_workload_classes",
3407    schema: MZ_INTERNAL_SCHEMA,
3408    oid: oid::TABLE_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3409    desc: RelationDesc::builder()
3410        .with_column("id", SqlScalarType::String.nullable(false))
3411        .with_column("workload_class", SqlScalarType::String.nullable(true))
3412        .with_key(vec![0])
3413        .finish(),
3414    column_comments: BTreeMap::new(),
3415    is_retained_metrics_object: false,
3416    access: vec![PUBLIC_SELECT],
3417});
3418
3419pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3420    name: "mz_cluster_workload_classes_ind",
3421    schema: MZ_INTERNAL_SCHEMA,
3422    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3423    sql: "IN CLUSTER mz_catalog_server
3424ON mz_internal.mz_cluster_workload_classes (id)",
3425    is_retained_metrics_object: false,
3426};
3427
3428pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3429    name: "mz_cluster_schedules",
3430    schema: MZ_INTERNAL_SCHEMA,
3431    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3432    desc: RelationDesc::builder()
3433        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3434        .with_column("type", SqlScalarType::String.nullable(false))
3435        .with_column(
3436            "refresh_hydration_time_estimate",
3437            SqlScalarType::Interval.nullable(true),
3438        )
3439        .finish(),
3440    column_comments: BTreeMap::from_iter([
3441        (
3442            "cluster_id",
3443            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3444        ),
3445        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3446        (
3447            "refresh_hydration_time_estimate",
3448            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3449        ),
3450    ]),
3451    is_retained_metrics_object: false,
3452    access: vec![PUBLIC_SELECT],
3453});
3454
3455pub static MZ_SECRETS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3456    name: "mz_secrets",
3457    schema: MZ_CATALOG_SCHEMA,
3458    oid: oid::TABLE_MZ_SECRETS_OID,
3459    desc: RelationDesc::builder()
3460        .with_column("id", SqlScalarType::String.nullable(false))
3461        .with_column("oid", SqlScalarType::Oid.nullable(false))
3462        .with_column("schema_id", SqlScalarType::String.nullable(false))
3463        .with_column("name", SqlScalarType::String.nullable(false))
3464        .with_column("owner_id", SqlScalarType::String.nullable(false))
3465        .with_column(
3466            "privileges",
3467            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3468        )
3469        .finish(),
3470    column_comments: BTreeMap::from_iter([
3471        ("id", "The unique ID of the secret."),
3472        ("oid", "A PostgreSQL-compatible oid for the secret."),
3473        (
3474            "schema_id",
3475            "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3476        ),
3477        ("name", "The name of the secret."),
3478        (
3479            "owner_id",
3480            "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3481        ),
3482        ("privileges", "The privileges belonging to the secret."),
3483    ]),
3484    is_retained_metrics_object: false,
3485    access: vec![PUBLIC_SELECT],
3486});
3487
3488pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3489    name: "mz_cluster_replicas",
3490    schema: MZ_CATALOG_SCHEMA,
3491    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3492    desc: RelationDesc::builder()
3493        .with_column("id", SqlScalarType::String.nullable(false))
3494        .with_column("name", SqlScalarType::String.nullable(false))
3495        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3496        .with_column("size", SqlScalarType::String.nullable(true))
3497        // `NULL` for un-orchestrated clusters and for replicas where the user
3498        // hasn't specified them.
3499        .with_column("availability_zone", SqlScalarType::String.nullable(true))
3500        .with_column("owner_id", SqlScalarType::String.nullable(false))
3501        .with_column("disk", SqlScalarType::Bool.nullable(true))
3502        .finish(),
3503    column_comments: BTreeMap::from_iter([
3504        ("id", "Materialize's unique ID for the cluster replica."),
3505        ("name", "The name of the cluster replica."),
3506        (
3507            "cluster_id",
3508            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3509        ),
3510        (
3511            "size",
3512            "The cluster replica's size, selected during creation.",
3513        ),
3514        (
3515            "availability_zone",
3516            "The availability zone in which the cluster is running.",
3517        ),
3518        (
3519            "owner_id",
3520            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3521        ),
3522        ("disk", "If the replica has a local disk."),
3523    ]),
3524    is_retained_metrics_object: true,
3525    access: vec![PUBLIC_SELECT],
3526});
3527
3528pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3529    name: "mz_internal_cluster_replicas",
3530    schema: MZ_INTERNAL_SCHEMA,
3531    oid: oid::TABLE_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3532    desc: RelationDesc::builder()
3533        .with_column("id", SqlScalarType::String.nullable(false))
3534        .finish(),
3535    column_comments: BTreeMap::from_iter([(
3536        "id",
3537        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3538    )]),
3539    is_retained_metrics_object: false,
3540    access: vec![PUBLIC_SELECT],
3541});
3542
3543pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3544    name: "mz_pending_cluster_replicas",
3545    schema: MZ_INTERNAL_SCHEMA,
3546    oid: oid::TABLE_MZ_PENDING_CLUSTER_REPLICAS_OID,
3547    desc: RelationDesc::builder()
3548        .with_column("id", SqlScalarType::String.nullable(false))
3549        .finish(),
3550    column_comments: BTreeMap::from_iter([(
3551        "id",
3552        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3553    )]),
3554    is_retained_metrics_object: false,
3555    access: vec![PUBLIC_SELECT],
3556});
3557
3558pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3559    BuiltinSource {
3560        name: "mz_cluster_replica_status_history",
3561        schema: MZ_INTERNAL_SCHEMA,
3562        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3563        data_source: IntrospectionType::ReplicaStatusHistory,
3564        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3565        column_comments: BTreeMap::from_iter([
3566            ("replica_id", "The ID of a cluster replica."),
3567            ("process_id", "The ID of a process within the replica."),
3568            (
3569                "status",
3570                "The status of the cluster replica: `online` or `offline`.",
3571            ),
3572            (
3573                "reason",
3574                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3575            ),
3576            (
3577                "occurred_at",
3578                "Wall-clock timestamp at which the event occurred.",
3579            ),
3580        ]),
3581        is_retained_metrics_object: false,
3582        access: vec![PUBLIC_SELECT],
3583    }
3584});
3585
3586pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
3587    || {
3588        BuiltinContinualTask {
3589            name: "mz_cluster_replica_status_history_ct",
3590            schema: MZ_INTERNAL_SCHEMA,
3591            oid: oid::CT_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3592            desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3593            sql: "
3594IN CLUSTER mz_catalog_server
3595ON INPUT mz_internal.mz_cluster_replica_status_history AS (
3596    DELETE FROM mz_internal.mz_cluster_replica_status_history_ct WHERE occurred_at + '30d' < mz_now();
3597    INSERT INTO mz_internal.mz_cluster_replica_status_history_ct SELECT * FROM mz_internal.mz_cluster_replica_status_history;
3598)",
3599            access: vec![PUBLIC_SELECT],
3600        }
3601    },
3602);
3603
3604pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3605    name: "mz_cluster_replica_statuses",
3606    schema: MZ_INTERNAL_SCHEMA,
3607    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
3608    desc: RelationDesc::builder()
3609        .with_column("replica_id", SqlScalarType::String.nullable(false))
3610        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3611        .with_column("status", SqlScalarType::String.nullable(false))
3612        .with_column("reason", SqlScalarType::String.nullable(true))
3613        .with_column(
3614            "updated_at",
3615            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3616        )
3617        .with_key(vec![0, 1])
3618        .finish(),
3619    column_comments: BTreeMap::from_iter([
3620        (
3621            "replica_id",
3622            "Materialize's unique ID for the cluster replica.",
3623        ),
3624        (
3625            "process_id",
3626            "The ID of the process within the cluster replica.",
3627        ),
3628        (
3629            "status",
3630            "The status of the cluster replica: `online` or `offline`.",
3631        ),
3632        (
3633            "reason",
3634            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3635        ),
3636        (
3637            "updated_at",
3638            "The time at which the status was last updated.",
3639        ),
3640    ]),
3641    sql: "
3642SELECT
3643    DISTINCT ON (replica_id, process_id)
3644    replica_id,
3645    process_id,
3646    status,
3647    reason,
3648    occurred_at as updated_at
3649FROM mz_internal.mz_cluster_replica_status_history
3650JOIN mz_cluster_replicas r ON r.id = replica_id
3651ORDER BY replica_id, process_id, occurred_at DESC",
3652    access: vec![PUBLIC_SELECT],
3653});
3654
3655pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3656    name: "mz_cluster_replica_sizes",
3657    schema: MZ_CATALOG_SCHEMA,
3658    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3659    desc: RelationDesc::builder()
3660        .with_column("size", SqlScalarType::String.nullable(false))
3661        .with_column("processes", SqlScalarType::UInt64.nullable(false))
3662        .with_column("workers", SqlScalarType::UInt64.nullable(false))
3663        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(false))
3664        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(false))
3665        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3666        .with_column(
3667            "credits_per_hour",
3668            SqlScalarType::Numeric { max_scale: None }.nullable(false),
3669        )
3670        .finish(),
3671    column_comments: BTreeMap::from_iter([
3672        ("size", "The human-readable replica size."),
3673        ("processes", "The number of processes in the replica."),
3674        (
3675            "workers",
3676            "The number of Timely Dataflow workers per process.",
3677        ),
3678        (
3679            "cpu_nano_cores",
3680            "The CPU allocation per process, in billionths of a vCPU core.",
3681        ),
3682        (
3683            "memory_bytes",
3684            "The RAM allocation per process, in billionths of a vCPU core.",
3685        ),
3686        ("disk_bytes", "The disk allocation per process."),
3687        (
3688            "credits_per_hour",
3689            "The number of compute credits consumed per hour.",
3690        ),
3691    ]),
3692    is_retained_metrics_object: true,
3693    access: vec![PUBLIC_SELECT],
3694});
3695
3696pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3697    name: "mz_audit_events",
3698    schema: MZ_CATALOG_SCHEMA,
3699    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
3700    desc: RelationDesc::builder()
3701        .with_column("id", SqlScalarType::UInt64.nullable(false))
3702        .with_column("event_type", SqlScalarType::String.nullable(false))
3703        .with_column("object_type", SqlScalarType::String.nullable(false))
3704        .with_column("details", SqlScalarType::Jsonb.nullable(false))
3705        .with_column("user", SqlScalarType::String.nullable(true))
3706        .with_column(
3707            "occurred_at",
3708            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3709        )
3710        .with_key(vec![0])
3711        .finish(),
3712    column_comments: BTreeMap::from_iter([
3713        (
3714            "id",
3715            "Materialize's unique, monotonically increasing ID for the event.",
3716        ),
3717        (
3718            "event_type",
3719            "The type of the event: `create`, `drop`, or `alter`.",
3720        ),
3721        (
3722            "object_type",
3723            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
3724        ),
3725        (
3726            "details",
3727            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
3728        ),
3729        (
3730            "user",
3731            "The user who triggered the event, or `NULL` if triggered by the system.",
3732        ),
3733        (
3734            "occurred_at",
3735            "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.",
3736        ),
3737    ]),
3738    is_retained_metrics_object: false,
3739    access: vec![PUBLIC_SELECT],
3740});
3741
3742pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3743    name: "mz_source_status_history",
3744    schema: MZ_INTERNAL_SCHEMA,
3745    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
3746    data_source: IntrospectionType::SourceStatusHistory,
3747    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
3748    column_comments: BTreeMap::from_iter([
3749        (
3750            "occurred_at",
3751            "Wall-clock timestamp of the source status change.",
3752        ),
3753        (
3754            "source_id",
3755            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
3756        ),
3757        (
3758            "status",
3759            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
3760        ),
3761        (
3762            "error",
3763            "If the source is in an error state, the error message.",
3764        ),
3765        (
3766            "details",
3767            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
3768        ),
3769        (
3770            "replica_id",
3771            "The ID of the replica that an instance of a source is running on.",
3772        ),
3773    ]),
3774    is_retained_metrics_object: false,
3775    access: vec![PUBLIC_SELECT],
3776});
3777
3778pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
3779    || BuiltinSource {
3780        name: "mz_aws_privatelink_connection_status_history",
3781        schema: MZ_INTERNAL_SCHEMA,
3782        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
3783        data_source: IntrospectionType::PrivatelinkConnectionStatusHistory,
3784        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
3785        column_comments: BTreeMap::from_iter([
3786            ("occurred_at", "Wall-clock timestamp of the status change."),
3787            (
3788                "connection_id",
3789                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
3790            ),
3791            (
3792                "status",
3793                "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`.",
3794            ),
3795        ]),
3796        is_retained_metrics_object: false,
3797        access: vec![PUBLIC_SELECT],
3798    },
3799);
3800
3801pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| {
3802    BuiltinView {
3803        name: "mz_aws_privatelink_connection_statuses",
3804        schema: MZ_INTERNAL_SCHEMA,
3805        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
3806        desc: RelationDesc::builder()
3807            .with_column("id", SqlScalarType::String.nullable(false))
3808            .with_column("name", SqlScalarType::String.nullable(false))
3809            .with_column(
3810                "last_status_change_at",
3811                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3812            )
3813            .with_column("status", SqlScalarType::String.nullable(true))
3814            .with_key(vec![0])
3815            .finish(),
3816        column_comments: BTreeMap::from_iter([
3817            (
3818                "id",
3819                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
3820            ),
3821            ("name", "The name of the connection."),
3822            (
3823                "last_status_change_at",
3824                "Wall-clock timestamp of the connection status change.",
3825            ),
3826            (
3827                "status",
3828                "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`.",
3829            ),
3830        ]),
3831        sql: "
3832    WITH statuses_w_last_status AS (
3833        SELECT
3834            connection_id,
3835            occurred_at,
3836            status,
3837            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
3838        FROM mz_internal.mz_aws_privatelink_connection_status_history
3839    ),
3840    latest_events AS (
3841        -- Only take the most recent transition for each ID
3842        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
3843        FROM statuses_w_last_status
3844        -- Only keep first status transitions
3845        WHERE status <> last_status OR last_status IS NULL
3846        ORDER BY connection_id, occurred_at DESC
3847    )
3848    SELECT
3849        conns.id,
3850        name,
3851        occurred_at as last_status_change_at,
3852        status
3853    FROM latest_events
3854    JOIN mz_catalog.mz_connections AS conns
3855    ON conns.id = latest_events.connection_id",
3856        access: vec![PUBLIC_SELECT],
3857    }
3858});
3859
3860pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
3861    LazyLock::new(|| BuiltinSource {
3862        name: "mz_statement_execution_history",
3863        schema: MZ_INTERNAL_SCHEMA,
3864        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
3865        data_source: IntrospectionType::StatementExecutionHistory,
3866        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
3867        column_comments: BTreeMap::new(),
3868        is_retained_metrics_object: false,
3869        access: vec![MONITOR_SELECT],
3870    });
3871
3872pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
3873    BuiltinView {
3874    name: "mz_statement_execution_history_redacted",
3875    schema: MZ_INTERNAL_SCHEMA,
3876    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
3877    // everything but `params` and `error_message`
3878    desc: RelationDesc::builder()
3879        .with_column("id", SqlScalarType::Uuid.nullable(false))
3880        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
3881        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
3882        .with_column("cluster_id", SqlScalarType::String.nullable(true))
3883        .with_column("application_name", SqlScalarType::String.nullable(false))
3884        .with_column("cluster_name", SqlScalarType::String.nullable(true))
3885        .with_column("database_name", SqlScalarType::String.nullable(false))
3886        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
3887        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
3888        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
3889        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
3890        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
3891        .with_column("mz_version", SqlScalarType::String.nullable(false))
3892        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
3893        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
3894        .with_column("finished_status", SqlScalarType::String.nullable(true))
3895        .with_column("result_size", SqlScalarType::Int64.nullable(true))
3896        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
3897        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
3898        .finish(),
3899    column_comments: BTreeMap::new(),
3900    sql: "
3901SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
3902cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
3903transient_index_id, mz_version, began_at, finished_at, finished_status,
3904result_size, rows_returned, execution_strategy
3905FROM mz_internal.mz_statement_execution_history",
3906    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
3907}
3908});
3909
3910pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
3911    LazyLock::new(|| BuiltinSource {
3912        name: "mz_prepared_statement_history",
3913        schema: MZ_INTERNAL_SCHEMA,
3914        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
3915        data_source: IntrospectionType::PreparedStatementHistory,
3916        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
3917        column_comments: BTreeMap::new(),
3918        is_retained_metrics_object: false,
3919        access: vec![
3920            SUPPORT_SELECT,
3921            ANALYTICS_SELECT,
3922            MONITOR_REDACTED_SELECT,
3923            MONITOR_SELECT,
3924        ],
3925    });
3926
3927pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3928    name: "mz_sql_text",
3929    schema: MZ_INTERNAL_SCHEMA,
3930    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
3931    desc: MZ_SQL_TEXT_DESC.clone(),
3932    data_source: IntrospectionType::SqlText,
3933    column_comments: BTreeMap::new(),
3934    is_retained_metrics_object: false,
3935    access: vec![MONITOR_SELECT],
3936});
3937
3938pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3939    name: "mz_sql_text_redacted",
3940    schema: MZ_INTERNAL_SCHEMA,
3941    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
3942    desc: RelationDesc::builder()
3943        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3944        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3945        .finish(),
3946    column_comments: BTreeMap::new(),
3947    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
3948    access: vec![
3949        MONITOR_SELECT,
3950        MONITOR_REDACTED_SELECT,
3951        SUPPORT_SELECT,
3952        ANALYTICS_SELECT,
3953    ],
3954});
3955
3956pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
3957    BuiltinView {
3958        name: "mz_recent_sql_text",
3959        schema: MZ_INTERNAL_SCHEMA,
3960        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
3961        // This should always be 1 day more than the interval in
3962        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
3963        // is rounded down to the nearest day.  Thus something that actually happened three days ago
3964        // could have a `prepared day` anywhere from 3 to 4 days back.
3965        desc: RelationDesc::builder()
3966            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3967            .with_column("sql", SqlScalarType::String.nullable(false))
3968            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3969            .with_key(vec![0, 1, 2])
3970            .finish(),
3971        column_comments: BTreeMap::new(),
3972        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
3973        access: vec![MONITOR_SELECT],
3974    }
3975});
3976
3977pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3978    name: "mz_recent_sql_text_redacted",
3979    schema: MZ_INTERNAL_SCHEMA,
3980    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
3981    desc: RelationDesc::builder()
3982        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3983        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3984        .finish(),
3985    column_comments: BTreeMap::new(),
3986    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
3987    access: vec![
3988        MONITOR_SELECT,
3989        MONITOR_REDACTED_SELECT,
3990        SUPPORT_SELECT,
3991        ANALYTICS_SELECT,
3992    ],
3993});
3994
3995pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
3996    name: "mz_recent_sql_text_ind",
3997    schema: MZ_INTERNAL_SCHEMA,
3998    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
3999    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4000    is_retained_metrics_object: false,
4001});
4002
4003pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4004    name: "mz_session_history",
4005    schema: MZ_INTERNAL_SCHEMA,
4006    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4007    data_source: IntrospectionType::SessionHistory,
4008    desc: MZ_SESSION_HISTORY_DESC.clone(),
4009    column_comments: BTreeMap::from_iter([
4010        (
4011            "session_id",
4012            "The globally unique ID of the session. Corresponds to `mz_sessions.id`.",
4013        ),
4014        (
4015            "connected_at",
4016            "The time at which the session was established.",
4017        ),
4018        (
4019            "initial_application_name",
4020            "The `application_name` session metadata field.",
4021        ),
4022        (
4023            "authenticated_user",
4024            "The name of the user for which the session was established.",
4025        ),
4026    ]),
4027    is_retained_metrics_object: false,
4028    access: vec![PUBLIC_SELECT],
4029});
4030
4031pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4032    BuiltinView {
4033        name: "mz_activity_log_thinned",
4034        schema: MZ_INTERNAL_SCHEMA,
4035        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
4036        desc: RelationDesc::builder()
4037            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4038            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4039            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4040            .with_column("application_name", SqlScalarType::String.nullable(false))
4041            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4042            .with_column("database_name", SqlScalarType::String.nullable(false))
4043            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4044            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4045            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4046            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4047            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4048            .with_column("mz_version", SqlScalarType::String.nullable(false))
4049            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4050            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4051            .with_column("finished_status", SqlScalarType::String.nullable(true))
4052            .with_column("error_message", SqlScalarType::String.nullable(true))
4053            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4054            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4055            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4056            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4057            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4058            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4059            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4060            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4061            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4062            .with_column("statement_type", SqlScalarType::String.nullable(true))
4063            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4064            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4065            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4066            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4067            .finish(),
4068        column_comments: BTreeMap::new(),
4069        sql: "
4070SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
4071transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
4072error_message, result_size, rows_returned, execution_strategy, transaction_id,
4073mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
4074mpsh.session_id, prepared_at, statement_type, throttled_count,
4075connected_at, initial_application_name, authenticated_user
4076FROM mz_internal.mz_statement_execution_history mseh,
4077     mz_internal.mz_prepared_statement_history mpsh,
4078     mz_internal.mz_session_history msh
4079WHERE mseh.prepared_statement_id = mpsh.id
4080AND mpsh.session_id = msh.session_id",
4081        access: vec![MONITOR_SELECT],
4082    }
4083});
4084
4085pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4086    BuiltinView {
4087        name: "mz_recent_activity_log_thinned",
4088        schema: MZ_INTERNAL_SCHEMA,
4089        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
4090        desc: RelationDesc::builder()
4091            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4092            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4093            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4094            .with_column("application_name", SqlScalarType::String.nullable(false))
4095            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4096            .with_column("database_name", SqlScalarType::String.nullable(false))
4097            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4098            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4099            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4100            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4101            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4102            .with_column("mz_version", SqlScalarType::String.nullable(false))
4103            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4104            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4105            .with_column("finished_status", SqlScalarType::String.nullable(true))
4106            .with_column("error_message", SqlScalarType::String.nullable(true))
4107            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4108            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4109            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4110            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4111            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4112            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4113            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4114            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4115            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4116            .with_column("statement_type", SqlScalarType::String.nullable(true))
4117            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4118            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4119            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4120            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4121            .finish(),
4122        column_comments: BTreeMap::new(),
4123        // We use a temporal window of 2 days rather than 1 day for `mz_session_history`'s `connected_at` since a statement execution at
4124        // the edge of the 1 day temporal window could've been executed in a session that was established an hour before the 1 day window.
4125        sql:
4126        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
4127AND began_at + INTERVAL '1 day' > mz_now() AND connected_at + INTERVAL '2 days' > mz_now()",
4128        access: vec![MONITOR_SELECT],
4129    }
4130});
4131
4132pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4133    name: "mz_recent_activity_log",
4134    schema: MZ_INTERNAL_SCHEMA,
4135    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
4136    desc: RelationDesc::builder()
4137        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4138        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4139        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4140        .with_column("application_name", SqlScalarType::String.nullable(false))
4141        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4142        .with_column("database_name", SqlScalarType::String.nullable(false))
4143        .with_column(
4144            "search_path",
4145            SqlScalarType::List {
4146                element_type: Box::new(SqlScalarType::String),
4147                custom_id: None,
4148            }
4149            .nullable(false),
4150        )
4151        .with_column(
4152            "transaction_isolation",
4153            SqlScalarType::String.nullable(false),
4154        )
4155        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4156        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4157        .with_column(
4158            "params",
4159            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
4160        )
4161        .with_column("mz_version", SqlScalarType::String.nullable(false))
4162        .with_column(
4163            "began_at",
4164            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4165        )
4166        .with_column(
4167            "finished_at",
4168            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4169        )
4170        .with_column("finished_status", SqlScalarType::String.nullable(true))
4171        .with_column("error_message", SqlScalarType::String.nullable(true))
4172        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4173        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4174        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4175        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4176        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4177        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4178        .with_column(
4179            "prepared_statement_name",
4180            SqlScalarType::String.nullable(false),
4181        )
4182        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4183        .with_column(
4184            "prepared_at",
4185            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4186        )
4187        .with_column("statement_type", SqlScalarType::String.nullable(true))
4188        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4189        .with_column(
4190            "connected_at",
4191            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4192        )
4193        .with_column(
4194            "initial_application_name",
4195            SqlScalarType::String.nullable(false),
4196        )
4197        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4198        .with_column("sql", SqlScalarType::String.nullable(false))
4199        .finish(),
4200    column_comments: BTreeMap::from_iter([
4201        (
4202            "execution_id",
4203            "An ID that is unique for each executed statement.",
4204        ),
4205        (
4206            "sample_rate",
4207            "The actual rate at which the statement was sampled.",
4208        ),
4209        (
4210            "cluster_id",
4211            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
4212        ),
4213        (
4214            "application_name",
4215            "The value of the `application_name` configuration parameter at execution time.",
4216        ),
4217        (
4218            "cluster_name",
4219            "The name of the cluster with ID `cluster_id` at execution time.",
4220        ),
4221        (
4222            "database_name",
4223            "The value of the `database` configuration parameter at execution time.",
4224        ),
4225        (
4226            "search_path",
4227            "The value of the `search_path` configuration parameter at execution time.",
4228        ),
4229        (
4230            "transaction_isolation",
4231            "The value of the `transaction_isolation` configuration parameter at execution time.",
4232        ),
4233        (
4234            "execution_timestamp",
4235            "The logical timestamp at which execution was scheduled.",
4236        ),
4237        (
4238            "transient_index_id",
4239            "The internal index of the compute dataflow created for the query, if any.",
4240        ),
4241        (
4242            "params",
4243            "The parameters with which the statement was executed.",
4244        ),
4245        (
4246            "mz_version",
4247            "The version of Materialize that was running when the statement was executed.",
4248        ),
4249        (
4250            "began_at",
4251            "The wall-clock time at which the statement began executing.",
4252        ),
4253        (
4254            "finished_at",
4255            "The wall-clock time at which the statement finished executing.",
4256        ),
4257        (
4258            "finished_status",
4259            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). `aborted` means that Materialize exited before the statement finished executing.",
4260        ),
4261        (
4262            "error_message",
4263            "The error message, if the statement failed.",
4264        ),
4265        (
4266            "result_size",
4267            "The size in bytes of the result, for statements that return rows.",
4268        ),
4269        (
4270            "rows_returned",
4271            "The number of rows returned, for statements that return rows.",
4272        ),
4273        (
4274            "execution_strategy",
4275            "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.",
4276        ),
4277        (
4278            "transaction_id",
4279            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
4280        ),
4281        (
4282            "prepared_statement_id",
4283            "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`).",
4284        ),
4285        (
4286            "sql_hash",
4287            "An opaque value uniquely identifying the text of the query.",
4288        ),
4289        (
4290            "prepared_statement_name",
4291            "The name given by the client library to the prepared statement.",
4292        ),
4293        (
4294            "session_id",
4295            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
4296        ),
4297        (
4298            "prepared_at",
4299            "The time at which the statement was prepared.",
4300        ),
4301        (
4302            "statement_type",
4303            "The _type_ of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
4304        ),
4305        (
4306            "throttled_count",
4307            "The number of statement executions that were dropped due to throttling before the current one was seen. If you have a very high volume of queries and need to log them without throttling, contact our team.",
4308        ),
4309        (
4310            "connected_at",
4311            "The time at which the session was established.",
4312        ),
4313        (
4314            "initial_application_name",
4315            "The initial value of `application_name` at the beginning of the session.",
4316        ),
4317        (
4318            "authenticated_user",
4319            "The name of the user for which the session was established.",
4320        ),
4321        ("sql", "The SQL text of the statement."),
4322    ]),
4323    sql: "SELECT mralt.*, mrst.sql
4324FROM mz_internal.mz_recent_activity_log_thinned mralt,
4325     mz_internal.mz_recent_sql_text mrst
4326WHERE mralt.sql_hash = mrst.sql_hash",
4327    access: vec![MONITOR_SELECT],
4328});
4329
4330pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4331    BuiltinView {
4332    name: "mz_recent_activity_log_redacted",
4333    schema: MZ_INTERNAL_SCHEMA,
4334    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
4335    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
4336    desc: RelationDesc::builder()
4337        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4338        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4339        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4340        .with_column("application_name", SqlScalarType::String.nullable(false))
4341        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4342        .with_column("database_name", SqlScalarType::String.nullable(false))
4343        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4344        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4345        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4346        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4347        .with_column("mz_version", SqlScalarType::String.nullable(false))
4348        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4349        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4350        .with_column("finished_status", SqlScalarType::String.nullable(true))
4351        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4352        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4353        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4354        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4355        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4356        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4357        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4358        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4359        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4360        .with_column("statement_type", SqlScalarType::String.nullable(true))
4361        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4362        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4363        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4364        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4365        .finish(),
4366    column_comments: BTreeMap::new(),
4367    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4368    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4369    mralt.transient_index_id, mralt.mz_version, mralt.began_at, mralt.finished_at,
4370    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4371    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4372    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4373    mralt.initial_application_name, mralt.authenticated_user,
4374    mrst.redacted_sql
4375FROM mz_internal.mz_recent_activity_log_thinned mralt,
4376     mz_internal.mz_recent_sql_text mrst
4377WHERE mralt.sql_hash = mrst.sql_hash",
4378    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4379}
4380});
4381
4382pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4383    BuiltinSource {
4384        name: "mz_statement_lifecycle_history",
4385        schema: MZ_INTERNAL_SCHEMA,
4386        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4387        desc: RelationDesc::builder()
4388            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
4389            .with_column("event_type", SqlScalarType::String.nullable(false))
4390            .with_column(
4391                "occurred_at",
4392                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4393            )
4394            .finish(),
4395        data_source: IntrospectionType::StatementLifecycleHistory,
4396        column_comments: BTreeMap::from_iter([
4397            (
4398                "statement_id",
4399                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4400            ),
4401            (
4402                "event_type",
4403                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4404            ),
4405            ("occurred_at", "The time at which the event took place."),
4406        ]),
4407        is_retained_metrics_object: false,
4408        // TODO[btv]: Maybe this should be public instead of
4409        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4410        // change, we probably don't need to worry about it now.
4411        access: vec![
4412            SUPPORT_SELECT,
4413            ANALYTICS_SELECT,
4414            MONITOR_REDACTED_SELECT,
4415            MONITOR_SELECT,
4416        ],
4417    }
4418});
4419
4420pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4421    name: "mz_source_statuses",
4422    schema: MZ_INTERNAL_SCHEMA,
4423    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4424    desc: RelationDesc::builder()
4425        .with_column("id", SqlScalarType::String.nullable(false))
4426        .with_column("name", SqlScalarType::String.nullable(false))
4427        .with_column("type", SqlScalarType::String.nullable(false))
4428        .with_column(
4429            "last_status_change_at",
4430            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4431        )
4432        .with_column("status", SqlScalarType::String.nullable(false))
4433        .with_column("error", SqlScalarType::String.nullable(true))
4434        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4435        .finish(),
4436    column_comments: BTreeMap::from_iter([
4437        (
4438            "id",
4439            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4440        ),
4441        ("name", "The name of the source."),
4442        ("type", "The type of the source."),
4443        (
4444            "last_status_change_at",
4445            "Wall-clock timestamp of the source status change.",
4446        ),
4447        (
4448            "status",
4449            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4450        ),
4451        (
4452            "error",
4453            "If the source is in an error state, the error message.",
4454        ),
4455        (
4456            "details",
4457            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4458        ),
4459    ]),
4460    sql: "
4461    WITH
4462    -- The status history contains per-replica events and source-global events.
4463    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4464    -- we can treat them uniformly below.
4465    uniform_status_history AS
4466    (
4467        SELECT
4468            s.source_id,
4469            COALESCE(s.replica_id, '<source>') as replica_id,
4470            s.occurred_at,
4471            s.status,
4472            s.error,
4473            s.details
4474        FROM mz_internal.mz_source_status_history s
4475    ),
4476    -- For getting the latest events, we first determine the latest per-replica
4477    -- events here and then apply precedence rules below.
4478    latest_per_replica_events AS
4479    (
4480        SELECT DISTINCT ON (source_id, replica_id)
4481            occurred_at, source_id, replica_id, status, error, details
4482        FROM uniform_status_history
4483        ORDER BY source_id, replica_id, occurred_at DESC
4484    ),
4485    -- We have a precedence list that determines the overall status in case
4486    -- there is differing per-replica (including source-global) statuses. If
4487    -- there is no 'dropped' status, and any replica reports 'running', the
4488    -- overall status is 'running' even if there might be some replica that has
4489    -- errors or is paused.
4490    latest_events AS
4491    (
4492       SELECT DISTINCT ON (source_id)
4493            source_id,
4494            occurred_at,
4495            status,
4496            error,
4497            details
4498        FROM latest_per_replica_events
4499        ORDER BY source_id, CASE status
4500                    WHEN 'dropped' THEN 1
4501                    WHEN 'running' THEN 2
4502                    WHEN 'stalled' THEN 3
4503                    WHEN 'starting' THEN 4
4504                    WHEN 'paused' THEN 5
4505                    WHEN 'ceased' THEN 6
4506                    ELSE 7  -- For any other status values
4507                END
4508    ),
4509    -- Determine which sources are subsources and which are parent sources
4510    subsources AS
4511    (
4512        SELECT subsources.id AS self, sources.id AS parent
4513        FROM
4514            mz_catalog.mz_sources AS subsources
4515                JOIN
4516                    mz_internal.mz_object_dependencies AS deps
4517                    ON subsources.id = deps.object_id
4518                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4519    ),
4520    -- Determine which sources are source tables
4521    tables AS
4522    (
4523        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4524        FROM mz_catalog.mz_tables AS tables
4525        WHERE tables.source_id IS NOT NULL
4526    ),
4527    -- Determine which collection's ID to use for the status
4528    id_of_status_to_use AS
4529    (
4530        SELECT
4531            self_events.source_id,
4532            -- If self not errored, but parent is, use parent; else self
4533            CASE
4534                WHEN
4535                    self_events.status <> 'ceased' AND
4536                    parent_events.status = 'stalled'
4537                THEN parent_events.source_id
4538                ELSE self_events.source_id
4539            END AS id_to_use
4540        FROM
4541            latest_events AS self_events
4542                LEFT JOIN subsources ON self_events.source_id = subsources.self
4543                LEFT JOIN tables ON self_events.source_id = tables.self
4544                LEFT JOIN
4545                    latest_events AS parent_events
4546                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4547    ),
4548    -- Swap out events for the ID of the event we plan to use instead
4549    latest_events_to_use AS
4550    (
4551        SELECT occurred_at, s.source_id, status, error, details
4552        FROM
4553            id_of_status_to_use AS s
4554                JOIN latest_events AS e ON e.source_id = s.id_to_use
4555    ),
4556    combined AS (
4557        SELECT
4558            mz_sources.id,
4559            mz_sources.name,
4560            mz_sources.type,
4561            occurred_at,
4562            status,
4563            error,
4564            details
4565        FROM
4566            mz_catalog.mz_sources
4567            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4568        UNION ALL
4569        SELECT
4570            tables.self AS id,
4571            tables.name,
4572            'table' AS type,
4573            occurred_at,
4574            status,
4575            error,
4576            details
4577        FROM
4578            tables
4579            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4580    )
4581SELECT
4582    id,
4583    name,
4584    type,
4585    occurred_at AS last_status_change_at,
4586    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4587    CASE
4588        WHEN
4589            type = 'webhook' OR
4590            type = 'progress'
4591        THEN 'running'
4592        ELSE COALESCE(status, 'created')
4593    END AS status,
4594    error,
4595    details
4596FROM combined
4597WHERE id NOT LIKE 's%';",
4598    access: vec![PUBLIC_SELECT],
4599});
4600
4601pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4602    name: "mz_sink_status_history",
4603    schema: MZ_INTERNAL_SCHEMA,
4604    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4605    data_source: IntrospectionType::SinkStatusHistory,
4606    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4607    column_comments: BTreeMap::from_iter([
4608        (
4609            "occurred_at",
4610            "Wall-clock timestamp of the sink status change.",
4611        ),
4612        (
4613            "sink_id",
4614            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4615        ),
4616        (
4617            "status",
4618            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4619        ),
4620        (
4621            "error",
4622            "If the sink is in an error state, the error message.",
4623        ),
4624        (
4625            "details",
4626            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4627        ),
4628        (
4629            "replica_id",
4630            "The ID of the replica that an instance of a sink is running on.",
4631        ),
4632    ]),
4633    is_retained_metrics_object: false,
4634    access: vec![PUBLIC_SELECT],
4635});
4636
4637pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4638    name: "mz_sink_statuses",
4639    schema: MZ_INTERNAL_SCHEMA,
4640    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4641    desc: RelationDesc::builder()
4642        .with_column("id", SqlScalarType::String.nullable(false))
4643        .with_column("name", SqlScalarType::String.nullable(false))
4644        .with_column("type", SqlScalarType::String.nullable(false))
4645        .with_column(
4646            "last_status_change_at",
4647            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4648        )
4649        .with_column("status", SqlScalarType::String.nullable(false))
4650        .with_column("error", SqlScalarType::String.nullable(true))
4651        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4652        .finish(),
4653    column_comments: BTreeMap::from_iter([
4654        (
4655            "id",
4656            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4657        ),
4658        ("name", "The name of the sink."),
4659        ("type", "The type of the sink."),
4660        (
4661            "last_status_change_at",
4662            "Wall-clock timestamp of the sink status change.",
4663        ),
4664        (
4665            "status",
4666            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4667        ),
4668        (
4669            "error",
4670            "If the sink is in an error state, the error message.",
4671        ),
4672        (
4673            "details",
4674            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4675        ),
4676    ]),
4677    sql: "
4678WITH
4679-- The status history contains per-replica events and sink-global events.
4680-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
4681-- we can treat them uniformly below.
4682uniform_status_history AS
4683(
4684    SELECT
4685        s.sink_id,
4686        COALESCE(s.replica_id, '<sink>') as replica_id,
4687        s.occurred_at,
4688        s.status,
4689        s.error,
4690        s.details
4691    FROM mz_internal.mz_sink_status_history s
4692),
4693-- For getting the latest events, we first determine the latest per-replica
4694-- events here and then apply precedence rules below.
4695latest_per_replica_events AS
4696(
4697    SELECT DISTINCT ON (sink_id, replica_id)
4698        occurred_at, sink_id, replica_id, status, error, details
4699    FROM uniform_status_history
4700    ORDER BY sink_id, replica_id, occurred_at DESC
4701),
4702-- We have a precedence list that determines the overall status in case
4703-- there is differing per-replica (including sink-global) statuses. If
4704-- there is no 'dropped' status, and any replica reports 'running', the
4705-- overall status is 'running' even if there might be some replica that has
4706-- errors or is paused.
4707latest_events AS
4708(
4709    SELECT DISTINCT ON (sink_id)
4710        sink_id,
4711        occurred_at,
4712        status,
4713        error,
4714        details
4715    FROM latest_per_replica_events
4716    ORDER BY sink_id, CASE status
4717                WHEN 'dropped' THEN 1
4718                WHEN 'running' THEN 2
4719                WHEN 'stalled' THEN 3
4720                WHEN 'starting' THEN 4
4721                WHEN 'paused' THEN 5
4722                WHEN 'ceased' THEN 6
4723                ELSE 7  -- For any other status values
4724            END
4725)
4726SELECT
4727    mz_sinks.id,
4728    name,
4729    mz_sinks.type,
4730    occurred_at as last_status_change_at,
4731    coalesce(status, 'created') as status,
4732    error,
4733    details
4734FROM mz_catalog.mz_sinks
4735LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
4736WHERE
4737    -- This is a convenient way to filter out system sinks, like the status_history table itself.
4738    mz_sinks.id NOT LIKE 's%'",
4739    access: vec![PUBLIC_SELECT],
4740});
4741
4742pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
4743    LazyLock::new(|| SystemObjectDescription {
4744        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
4745        object_type: CatalogItemType::Table,
4746        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
4747    });
4748
4749pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4750    name: "mz_storage_usage_by_shard",
4751    schema: MZ_INTERNAL_SCHEMA,
4752    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
4753    desc: RelationDesc::builder()
4754        .with_column("id", SqlScalarType::UInt64.nullable(false))
4755        .with_column("shard_id", SqlScalarType::String.nullable(true))
4756        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
4757        .with_column(
4758            "collection_timestamp",
4759            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4760        )
4761        .finish(),
4762    column_comments: BTreeMap::new(),
4763    is_retained_metrics_object: false,
4764    access: vec![PUBLIC_SELECT],
4765});
4766
4767pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4768    name: "mz_egress_ips",
4769    schema: MZ_CATALOG_SCHEMA,
4770    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
4771    desc: RelationDesc::builder()
4772        .with_column("egress_ip", SqlScalarType::String.nullable(false))
4773        .with_column("prefix_length", SqlScalarType::Int32.nullable(false))
4774        .with_column("cidr", SqlScalarType::String.nullable(false))
4775        .finish(),
4776    column_comments: BTreeMap::from_iter([
4777        ("egress_ip", "The start of the range of IP addresses."),
4778        (
4779            "prefix_length",
4780            "The number of leading bits in the CIDR netmask.",
4781        ),
4782        ("cidr", "The CIDR representation."),
4783    ]),
4784    is_retained_metrics_object: false,
4785    access: vec![PUBLIC_SELECT],
4786});
4787
4788pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
4789    LazyLock::new(|| BuiltinTable {
4790        name: "mz_aws_privatelink_connections",
4791        schema: MZ_CATALOG_SCHEMA,
4792        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
4793        desc: RelationDesc::builder()
4794            .with_column("id", SqlScalarType::String.nullable(false))
4795            .with_column("principal", SqlScalarType::String.nullable(false))
4796            .finish(),
4797        column_comments: BTreeMap::from_iter([
4798            ("id", "The ID of the connection."),
4799            (
4800                "principal",
4801                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
4802            ),
4803        ]),
4804        is_retained_metrics_object: false,
4805        access: vec![PUBLIC_SELECT],
4806    });
4807
4808pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4809    name: "mz_aws_connections",
4810    schema: MZ_INTERNAL_SCHEMA,
4811    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
4812    desc: RelationDesc::builder()
4813        .with_column("id", SqlScalarType::String.nullable(false))
4814        .with_column("endpoint", SqlScalarType::String.nullable(true))
4815        .with_column("region", SqlScalarType::String.nullable(true))
4816        .with_column("access_key_id", SqlScalarType::String.nullable(true))
4817        .with_column(
4818            "access_key_id_secret_id",
4819            SqlScalarType::String.nullable(true),
4820        )
4821        .with_column(
4822            "secret_access_key_secret_id",
4823            SqlScalarType::String.nullable(true),
4824        )
4825        .with_column("session_token", SqlScalarType::String.nullable(true))
4826        .with_column(
4827            "session_token_secret_id",
4828            SqlScalarType::String.nullable(true),
4829        )
4830        .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
4831        .with_column(
4832            "assume_role_session_name",
4833            SqlScalarType::String.nullable(true),
4834        )
4835        .with_column("principal", SqlScalarType::String.nullable(true))
4836        .with_column("external_id", SqlScalarType::String.nullable(true))
4837        .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
4838        .finish(),
4839    column_comments: BTreeMap::from_iter([
4840        ("id", "The ID of the connection."),
4841        ("endpoint", "The value of the `ENDPOINT` option, if set."),
4842        ("region", "The value of the `REGION` option, if set."),
4843        (
4844            "access_key_id",
4845            "The value of the `ACCESS KEY ID` option, if provided in line.",
4846        ),
4847        (
4848            "access_key_id_secret_id",
4849            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
4850        ),
4851        (
4852            "secret_access_key_secret_id",
4853            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
4854        ),
4855        (
4856            "session_token",
4857            "The value of the `SESSION TOKEN` option, if provided in line.",
4858        ),
4859        (
4860            "session_token_secret_id",
4861            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
4862        ),
4863        (
4864            "assume_role_arn",
4865            "The value of the `ASSUME ROLE ARN` option, if set.",
4866        ),
4867        (
4868            "assume_role_session_name",
4869            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
4870        ),
4871        (
4872            "principal",
4873            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4874        ),
4875        (
4876            "external_id",
4877            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4878        ),
4879        (
4880            "example_trust_policy",
4881            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
4882        ),
4883    ]),
4884    is_retained_metrics_object: false,
4885    access: vec![PUBLIC_SELECT],
4886});
4887
4888pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
4889    LazyLock::new(|| BuiltinSource {
4890        name: "mz_cluster_replica_metrics_history",
4891        schema: MZ_INTERNAL_SCHEMA,
4892        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4893        data_source: IntrospectionType::ReplicaMetricsHistory,
4894        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4895        column_comments: BTreeMap::from_iter([
4896            ("replica_id", "The ID of a cluster replica."),
4897            ("process_id", "The ID of a process within the replica."),
4898            (
4899                "cpu_nano_cores",
4900                "Approximate CPU usage, in billionths of a vCPU core.",
4901            ),
4902            ("memory_bytes", "Approximate memory usage, in bytes."),
4903            ("disk_bytes", "Approximate disk usage, in bytes."),
4904            (
4905                "occurred_at",
4906                "Wall-clock timestamp at which the event occurred.",
4907            ),
4908            (
4909                "heap_bytes",
4910                "Approximate heap (RAM + swap) usage, in bytes.",
4911            ),
4912            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
4913        ]),
4914        is_retained_metrics_object: false,
4915        access: vec![PUBLIC_SELECT],
4916    });
4917
4918pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
4919    || {
4920        BuiltinContinualTask {
4921            name: "mz_cluster_replica_metrics_history_ct",
4922            schema: MZ_INTERNAL_SCHEMA,
4923            oid: oid::CT_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4924            desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4925            sql: "
4926IN CLUSTER mz_catalog_server
4927ON INPUT mz_internal.mz_cluster_replica_metrics_history AS (
4928    DELETE FROM mz_internal.mz_cluster_replica_metrics_history_ct WHERE occurred_at + '30d' < mz_now();
4929    INSERT INTO mz_internal.mz_cluster_replica_metrics_history_ct SELECT * FROM mz_internal.mz_cluster_replica_metrics_history;
4930)",
4931            access: vec![PUBLIC_SELECT],
4932        }
4933    },
4934);
4935
4936pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4937    name: "mz_cluster_replica_metrics",
4938    schema: MZ_INTERNAL_SCHEMA,
4939    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
4940    desc: RelationDesc::builder()
4941        .with_column("replica_id", SqlScalarType::String.nullable(false))
4942        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
4943        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
4944        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
4945        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
4946        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
4947        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
4948        .with_key(vec![0, 1])
4949        .finish(),
4950    column_comments: BTreeMap::from_iter([
4951        ("replica_id", "The ID of a cluster replica."),
4952        ("process_id", "The ID of a process within the replica."),
4953        (
4954            "cpu_nano_cores",
4955            "Approximate CPU usage, in billionths of a vCPU core.",
4956        ),
4957        ("memory_bytes", "Approximate RAM usage, in bytes."),
4958        ("disk_bytes", "Approximate disk usage, in bytes."),
4959        (
4960            "heap_bytes",
4961            "Approximate heap (RAM + swap) usage, in bytes.",
4962        ),
4963        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
4964    ]),
4965    sql: "
4966SELECT
4967    DISTINCT ON (replica_id, process_id)
4968    replica_id,
4969    process_id,
4970    cpu_nano_cores,
4971    memory_bytes,
4972    disk_bytes,
4973    heap_bytes,
4974    heap_limit
4975FROM mz_internal.mz_cluster_replica_metrics_history
4976JOIN mz_cluster_replicas r ON r.id = replica_id
4977ORDER BY replica_id, process_id, occurred_at DESC",
4978    access: vec![PUBLIC_SELECT],
4979});
4980
4981pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
4982    LazyLock::new(|| BuiltinSource {
4983        name: "mz_cluster_replica_frontiers",
4984        schema: MZ_CATALOG_SCHEMA,
4985        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
4986        data_source: IntrospectionType::ReplicaFrontiers,
4987        desc: RelationDesc::builder()
4988            .with_column("object_id", SqlScalarType::String.nullable(false))
4989            .with_column("replica_id", SqlScalarType::String.nullable(false))
4990            .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
4991            .finish(),
4992        column_comments: BTreeMap::from_iter([
4993            (
4994                "object_id",
4995                "The ID of the source, sink, index, materialized view, or subscription.",
4996            ),
4997            ("replica_id", "The ID of a cluster replica."),
4998            (
4999                "write_frontier",
5000                "The next timestamp at which the output may change.",
5001            ),
5002        ]),
5003        is_retained_metrics_object: false,
5004        access: vec![PUBLIC_SELECT],
5005    });
5006
5007pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
5008    LazyLock::new(|| BuiltinIndex {
5009        name: "mz_cluster_replica_frontiers_ind",
5010        schema: MZ_CATALOG_SCHEMA,
5011        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
5012        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
5013        is_retained_metrics_object: false,
5014    });
5015
5016pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5017    name: "mz_frontiers",
5018    schema: MZ_INTERNAL_SCHEMA,
5019    oid: oid::SOURCE_MZ_FRONTIERS_OID,
5020    data_source: IntrospectionType::Frontiers,
5021    desc: RelationDesc::builder()
5022        .with_column("object_id", SqlScalarType::String.nullable(false))
5023        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
5024        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5025        .finish(),
5026    column_comments: BTreeMap::from_iter([
5027        (
5028            "object_id",
5029            "The ID of the source, sink, table, index, materialized view, or subscription.",
5030        ),
5031        (
5032            "read_frontier",
5033            "The earliest timestamp at which the output is still readable.",
5034        ),
5035        (
5036            "write_frontier",
5037            "The next timestamp at which the output may change.",
5038        ),
5039    ]),
5040    is_retained_metrics_object: false,
5041    access: vec![PUBLIC_SELECT],
5042});
5043
5044/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
5045pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5046    name: "mz_global_frontiers",
5047    schema: MZ_INTERNAL_SCHEMA,
5048    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5049    desc: RelationDesc::builder()
5050        .with_column("object_id", SqlScalarType::String.nullable(false))
5051        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
5052        .finish(),
5053    column_comments: BTreeMap::new(),
5054    sql: "
5055SELECT object_id, write_frontier AS time
5056FROM mz_internal.mz_frontiers
5057WHERE write_frontier IS NOT NULL",
5058    access: vec![PUBLIC_SELECT],
5059});
5060
5061pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5062    name: "mz_wallclock_lag_history",
5063    schema: MZ_INTERNAL_SCHEMA,
5064    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5065    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5066    data_source: IntrospectionType::WallclockLagHistory,
5067    column_comments: BTreeMap::from_iter([
5068        (
5069            "object_id",
5070            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5071        ),
5072        (
5073            "replica_id",
5074            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5075        ),
5076        (
5077            "lag",
5078            "The amount of time the object's write frontier lags behind wallclock time.",
5079        ),
5080        (
5081            "occurred_at",
5082            "Wall-clock timestamp at which the event occurred.",
5083        ),
5084    ]),
5085    is_retained_metrics_object: false,
5086    access: vec![PUBLIC_SELECT],
5087});
5088
5089pub static MZ_WALLCLOCK_LAG_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(|| {
5090    BuiltinContinualTask {
5091    name: "mz_wallclock_lag_history_ct",
5092    schema: MZ_INTERNAL_SCHEMA,
5093    oid: oid::CT_MZ_WALLCLOCK_LAG_HISTORY_OID,
5094    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5095    sql: "
5096IN CLUSTER mz_catalog_server
5097ON INPUT mz_internal.mz_wallclock_lag_history AS (
5098    DELETE FROM mz_internal.mz_wallclock_lag_history_ct WHERE occurred_at + '30d' < mz_now();
5099    INSERT INTO mz_internal.mz_wallclock_lag_history_ct SELECT * FROM mz_internal.mz_wallclock_lag_history;
5100)",
5101            access: vec![PUBLIC_SELECT],
5102        }
5103});
5104
5105pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5106    name: "mz_wallclock_global_lag_history",
5107    schema: MZ_INTERNAL_SCHEMA,
5108    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5109    desc: RelationDesc::builder()
5110        .with_column("object_id", SqlScalarType::String.nullable(false))
5111        .with_column("lag", SqlScalarType::Interval.nullable(true))
5112        .with_column(
5113            "occurred_at",
5114            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5115        )
5116        .with_key(vec![0, 2])
5117        .finish(),
5118    column_comments: BTreeMap::new(),
5119    sql: "
5120WITH times_binned AS (
5121    SELECT
5122        object_id,
5123        lag,
5124        date_trunc('minute', occurred_at) AS occurred_at
5125    FROM mz_internal.mz_wallclock_lag_history
5126)
5127SELECT
5128    object_id,
5129    min(lag) AS lag,
5130    occurred_at
5131FROM times_binned
5132GROUP BY object_id, occurred_at
5133OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5134    access: vec![PUBLIC_SELECT],
5135});
5136
5137pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> =
5138    LazyLock::new(|| BuiltinView {
5139        name: "mz_wallclock_global_lag_recent_history",
5140        schema: MZ_INTERNAL_SCHEMA,
5141        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5142        desc: RelationDesc::builder()
5143            .with_column("object_id", SqlScalarType::String.nullable(false))
5144            .with_column("lag", SqlScalarType::Interval.nullable(true))
5145            .with_column(
5146                "occurred_at",
5147                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5148            )
5149            .with_key(vec![0, 2])
5150            .finish(),
5151        column_comments: BTreeMap::new(),
5152        sql: "
5153SELECT object_id, lag, occurred_at
5154FROM mz_internal.mz_wallclock_global_lag_history
5155WHERE occurred_at + '1 day' > mz_now()",
5156        access: vec![PUBLIC_SELECT],
5157    });
5158
5159pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5160    name: "mz_wallclock_global_lag",
5161    schema: MZ_INTERNAL_SCHEMA,
5162    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5163    desc: RelationDesc::builder()
5164        .with_column("object_id", SqlScalarType::String.nullable(false))
5165        .with_column("lag", SqlScalarType::Interval.nullable(true))
5166        .with_key(vec![0])
5167        .finish(),
5168    column_comments: BTreeMap::from_iter([
5169        (
5170            "object_id",
5171            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5172        ),
5173        (
5174            "lag",
5175            "The amount of time the object's write frontier lags behind wallclock time.",
5176        ),
5177    ]),
5178    sql: "
5179SELECT DISTINCT ON (object_id) object_id, lag
5180FROM mz_internal.mz_wallclock_global_lag_recent_history
5181WHERE occurred_at + '5 minutes' > mz_now()
5182ORDER BY object_id, occurred_at DESC",
5183    access: vec![PUBLIC_SELECT],
5184});
5185
5186pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5187    LazyLock::new(|| BuiltinSource {
5188        name: "mz_wallclock_global_lag_histogram_raw",
5189        schema: MZ_INTERNAL_SCHEMA,
5190        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5191        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5192        column_comments: BTreeMap::new(),
5193        data_source: IntrospectionType::WallclockLagHistogram,
5194        is_retained_metrics_object: false,
5195        access: vec![PUBLIC_SELECT],
5196    });
5197
5198pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5199    LazyLock::new(|| BuiltinView {
5200        name: "mz_wallclock_global_lag_histogram",
5201        schema: MZ_INTERNAL_SCHEMA,
5202        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5203        desc: RelationDesc::builder()
5204            .with_column(
5205                "period_start",
5206                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5207            )
5208            .with_column(
5209                "period_end",
5210                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5211            )
5212            .with_column("object_id", SqlScalarType::String.nullable(false))
5213            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
5214            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
5215            .with_column("count", SqlScalarType::Int64.nullable(false))
5216            .with_key(vec![0, 1, 2, 3, 4])
5217            .finish(),
5218        column_comments: BTreeMap::new(),
5219        sql: "
5220SELECT *, count(*) AS count
5221FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5222GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5223        access: vec![PUBLIC_SELECT],
5224    });
5225
5226pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5227    BuiltinSource {
5228        name: "mz_materialized_view_refreshes",
5229        schema: MZ_INTERNAL_SCHEMA,
5230        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5231        data_source: IntrospectionType::ComputeMaterializedViewRefreshes,
5232        desc: RelationDesc::builder()
5233            .with_column(
5234                "materialized_view_id",
5235                SqlScalarType::String.nullable(false),
5236            )
5237            .with_column(
5238                "last_completed_refresh",
5239                SqlScalarType::MzTimestamp.nullable(true),
5240            )
5241            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
5242            .finish(),
5243        column_comments: BTreeMap::from_iter([
5244            (
5245                "materialized_view_id",
5246                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5247            ),
5248            (
5249                "last_completed_refresh",
5250                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5251            ),
5252            (
5253                "next_refresh",
5254                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5255            ),
5256        ]),
5257        is_retained_metrics_object: false,
5258        access: vec![PUBLIC_SELECT],
5259    }
5260});
5261
5262pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5263    name: "mz_subscriptions",
5264    schema: MZ_INTERNAL_SCHEMA,
5265    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5266    desc: RelationDesc::builder()
5267        .with_column("id", SqlScalarType::String.nullable(false))
5268        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
5269        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5270        .with_column(
5271            "created_at",
5272            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5273        )
5274        .with_column(
5275            "referenced_object_ids",
5276            SqlScalarType::List {
5277                element_type: Box::new(SqlScalarType::String),
5278                custom_id: None,
5279            }
5280            .nullable(false),
5281        )
5282        .finish(),
5283    column_comments: BTreeMap::from_iter([
5284        ("id", "The ID of the subscription."),
5285        (
5286            "session_id",
5287            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5288        ),
5289        (
5290            "cluster_id",
5291            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5292        ),
5293        (
5294            "created_at",
5295            "The time at which the subscription was created.",
5296        ),
5297        (
5298            "referenced_object_ids",
5299            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5300        ),
5301    ]),
5302    is_retained_metrics_object: false,
5303    access: vec![PUBLIC_SELECT],
5304});
5305
5306pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5307    name: "mz_sessions",
5308    schema: MZ_INTERNAL_SCHEMA,
5309    oid: oid::TABLE_MZ_SESSIONS_OID,
5310    desc: RelationDesc::builder()
5311        .with_column("id", SqlScalarType::Uuid.nullable(false))
5312        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
5313        .with_column("role_id", SqlScalarType::String.nullable(false))
5314        .with_column("client_ip", SqlScalarType::String.nullable(true))
5315        .with_column(
5316            "connected_at",
5317            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5318        )
5319        .finish(),
5320    column_comments: BTreeMap::from_iter([
5321        ("id", "The globally unique ID of the session."),
5322        (
5323            "connection_id",
5324            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5325        ),
5326        (
5327            "role_id",
5328            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5329        ),
5330        (
5331            "client_ip",
5332            "The IP address of the client that initiated the session.",
5333        ),
5334        (
5335            "connected_at",
5336            "The time at which the session connected to the system.",
5337        ),
5338    ]),
5339    is_retained_metrics_object: false,
5340    access: vec![PUBLIC_SELECT],
5341});
5342
5343pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5344    name: "mz_default_privileges",
5345    schema: MZ_CATALOG_SCHEMA,
5346    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5347    desc: RelationDesc::builder()
5348        .with_column("role_id", SqlScalarType::String.nullable(false))
5349        .with_column("database_id", SqlScalarType::String.nullable(true))
5350        .with_column("schema_id", SqlScalarType::String.nullable(true))
5351        .with_column("object_type", SqlScalarType::String.nullable(false))
5352        .with_column("grantee", SqlScalarType::String.nullable(false))
5353        .with_column("privileges", SqlScalarType::String.nullable(false))
5354        .finish(),
5355    column_comments: BTreeMap::from_iter([
5356        (
5357            "role_id",
5358            "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.",
5359        ),
5360        (
5361            "database_id",
5362            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5363        ),
5364        (
5365            "schema_id",
5366            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5367        ),
5368        (
5369            "object_type",
5370            "Privileges described in this row will be granted only on objects of type `object_type`.",
5371        ),
5372        (
5373            "grantee",
5374            "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.",
5375        ),
5376        ("privileges", "The set of privileges that will be granted."),
5377    ]),
5378    is_retained_metrics_object: false,
5379    access: vec![PUBLIC_SELECT],
5380});
5381
5382pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5383    name: "mz_system_privileges",
5384    schema: MZ_CATALOG_SCHEMA,
5385    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5386    desc: RelationDesc::builder()
5387        .with_column("privileges", SqlScalarType::MzAclItem.nullable(false))
5388        .finish(),
5389    column_comments: BTreeMap::from_iter([(
5390        "privileges",
5391        "The privileges belonging to the system.",
5392    )]),
5393    is_retained_metrics_object: false,
5394    access: vec![PUBLIC_SELECT],
5395});
5396
5397pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5398    name: "mz_comments",
5399    schema: MZ_INTERNAL_SCHEMA,
5400    oid: oid::TABLE_MZ_COMMENTS_OID,
5401    desc: RelationDesc::builder()
5402        .with_column("id", SqlScalarType::String.nullable(false))
5403        .with_column("object_type", SqlScalarType::String.nullable(false))
5404        .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
5405        .with_column("comment", SqlScalarType::String.nullable(false))
5406        .finish(),
5407    column_comments: BTreeMap::from_iter([
5408        (
5409            "id",
5410            "The ID of the object. Corresponds to `mz_objects.id`.",
5411        ),
5412        (
5413            "object_type",
5414            "The type of object the comment is associated with.",
5415        ),
5416        (
5417            "object_sub_id",
5418            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5419        ),
5420        ("comment", "The comment itself."),
5421    ]),
5422    is_retained_metrics_object: false,
5423    access: vec![PUBLIC_SELECT],
5424});
5425
5426pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5427    name: "mz_source_references",
5428    schema: MZ_INTERNAL_SCHEMA,
5429    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5430    desc: RelationDesc::builder()
5431        .with_column("source_id", SqlScalarType::String.nullable(false))
5432        .with_column("namespace", SqlScalarType::String.nullable(true))
5433        .with_column("name", SqlScalarType::String.nullable(false))
5434        .with_column(
5435            "updated_at",
5436            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5437        )
5438        .with_column(
5439            "columns",
5440            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5441        )
5442        .finish(),
5443    column_comments: BTreeMap::new(),
5444    is_retained_metrics_object: false,
5445    access: vec![PUBLIC_SELECT],
5446});
5447
5448pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5449    name: "mz_webhook_sources",
5450    schema: MZ_INTERNAL_SCHEMA,
5451    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5452    desc: RelationDesc::builder()
5453        .with_column("id", SqlScalarType::String.nullable(false))
5454        .with_column("name", SqlScalarType::String.nullable(false))
5455        .with_column("url", SqlScalarType::String.nullable(false))
5456        .finish(),
5457    column_comments: BTreeMap::from_iter([
5458        (
5459            "id",
5460            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5461        ),
5462        ("name", "The name of the webhook source."),
5463        (
5464            "url",
5465            "The URL which can be used to send events to the source.",
5466        ),
5467    ]),
5468    is_retained_metrics_object: false,
5469    access: vec![PUBLIC_SELECT],
5470});
5471
5472pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5473    BuiltinTable {
5474        name: "mz_history_retention_strategies",
5475        schema: MZ_INTERNAL_SCHEMA,
5476        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5477        desc: RelationDesc::builder()
5478            .with_column("id", SqlScalarType::String.nullable(false))
5479            .with_column("strategy", SqlScalarType::String.nullable(false))
5480            .with_column("value", SqlScalarType::Jsonb.nullable(false))
5481            .finish(),
5482        column_comments: BTreeMap::from_iter([
5483            ("id", "The ID of the object."),
5484            (
5485                "strategy",
5486                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5487            ),
5488            (
5489                "value",
5490                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5491            ),
5492        ]),
5493        is_retained_metrics_object: false,
5494        access: vec![PUBLIC_SELECT],
5495    }
5496});
5497
5498pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5499    name: "mz_license_keys",
5500    schema: MZ_INTERNAL_SCHEMA,
5501    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
5502    desc: RelationDesc::builder()
5503        .with_column("id", SqlScalarType::String.nullable(false))
5504        .with_column("organization", SqlScalarType::String.nullable(false))
5505        .with_column("environment_id", SqlScalarType::String.nullable(false))
5506        .with_column(
5507            "expiration",
5508            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5509        )
5510        .with_column(
5511            "not_before",
5512            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5513        )
5514        .finish(),
5515    column_comments: BTreeMap::from_iter([
5516        ("id", "The identifier of the license key."),
5517        (
5518            "organization",
5519            "The name of the organization that this license key was issued to.",
5520        ),
5521        (
5522            "environment_id",
5523            "The environment ID that this license key was issued for.",
5524        ),
5525        (
5526            "expiration",
5527            "The date and time when this license key expires.",
5528        ),
5529        (
5530            "not_before",
5531            "The start of the validity period for this license key.",
5532        ),
5533    ]),
5534    is_retained_metrics_object: false,
5535    access: vec![PUBLIC_SELECT],
5536});
5537
5538pub static MZ_REPLACEMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5539    name: "mz_replacements",
5540    schema: MZ_INTERNAL_SCHEMA,
5541    oid: oid::TABLE_MZ_REPLACEMENTS_OID,
5542    desc: RelationDesc::builder()
5543        .with_column("id", SqlScalarType::String.nullable(false))
5544        .with_column("target_id", SqlScalarType::String.nullable(false))
5545        .finish(),
5546    column_comments: BTreeMap::from_iter([
5547        (
5548            "id",
5549            "The ID of the replacement object. Corresponds to `mz_objects.id`.",
5550        ),
5551        (
5552            "target_id",
5553            "The ID of the replacement target. Corresponds to `mz_objects.id`.",
5554        ),
5555    ]),
5556    is_retained_metrics_object: false,
5557    access: vec![PUBLIC_SELECT],
5558});
5559
5560// These will be replaced with per-replica tables once source/sink multiplexing on
5561// a single cluster is supported.
5562pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5563    name: "mz_source_statistics_raw",
5564    schema: MZ_INTERNAL_SCHEMA,
5565    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5566    data_source: IntrospectionType::StorageSourceStatistics,
5567    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5568    column_comments: BTreeMap::new(),
5569    is_retained_metrics_object: true,
5570    access: vec![PUBLIC_SELECT],
5571});
5572pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5573    name: "mz_sink_statistics_raw",
5574    schema: MZ_INTERNAL_SCHEMA,
5575    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5576    data_source: IntrospectionType::StorageSinkStatistics,
5577    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5578    column_comments: BTreeMap::new(),
5579    is_retained_metrics_object: true,
5580    access: vec![PUBLIC_SELECT],
5581});
5582
5583pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5584    name: "mz_storage_shards",
5585    schema: MZ_INTERNAL_SCHEMA,
5586    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5587    data_source: IntrospectionType::ShardMapping,
5588    desc: RelationDesc::builder()
5589        .with_column("object_id", SqlScalarType::String.nullable(false))
5590        .with_column("shard_id", SqlScalarType::String.nullable(false))
5591        .finish(),
5592    column_comments: BTreeMap::new(),
5593    is_retained_metrics_object: false,
5594    access: vec![PUBLIC_SELECT],
5595});
5596
5597pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5598    name: "mz_storage_usage",
5599    schema: MZ_CATALOG_SCHEMA,
5600    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5601    desc: RelationDesc::builder()
5602        .with_column("object_id", SqlScalarType::String.nullable(false))
5603        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5604        .with_column(
5605            "collection_timestamp",
5606            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5607        )
5608        .with_key(vec![0, 2])
5609        .finish(),
5610    column_comments: BTreeMap::from_iter([
5611        (
5612            "object_id",
5613            "The ID of the table, source, or materialized view.",
5614        ),
5615        (
5616            "size_bytes",
5617            "The number of storage bytes used by the object.",
5618        ),
5619        (
5620            "collection_timestamp",
5621            "The time at which storage usage of the object was assessed.",
5622        ),
5623    ]),
5624    sql: "
5625SELECT
5626    object_id,
5627    sum(size_bytes)::uint8 AS size_bytes,
5628    collection_timestamp
5629FROM
5630    mz_internal.mz_storage_shards
5631    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5632GROUP BY object_id, collection_timestamp",
5633    access: vec![PUBLIC_SELECT],
5634});
5635
5636pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5637    BuiltinView {
5638    name: "mz_recent_storage_usage",
5639    schema: MZ_CATALOG_SCHEMA,
5640    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
5641    desc: RelationDesc::builder()
5642        .with_column("object_id", SqlScalarType::String.nullable(false))
5643        .with_column("size_bytes", SqlScalarType::UInt64.nullable(true))
5644        .with_key(vec![0])
5645        .finish(),
5646    column_comments: BTreeMap::from_iter([
5647        ("object_id", "The ID of the table, source, or materialized view."),
5648        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
5649    ]),
5650    sql: "
5651WITH
5652
5653recent_storage_usage_by_shard AS (
5654    SELECT shard_id, size_bytes, collection_timestamp
5655    FROM mz_internal.mz_storage_usage_by_shard
5656    -- Restricting to the last 6 hours makes it feasible to index the view.
5657    WHERE collection_timestamp + '6 hours' >= mz_now()
5658),
5659
5660most_recent_collection_timestamp_by_shard AS (
5661    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
5662    FROM recent_storage_usage_by_shard
5663    GROUP BY shard_id
5664)
5665
5666SELECT
5667    object_id,
5668    sum(size_bytes)::uint8 AS size_bytes
5669FROM
5670    mz_internal.mz_storage_shards
5671    LEFT JOIN most_recent_collection_timestamp_by_shard
5672        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
5673    LEFT JOIN recent_storage_usage_by_shard
5674        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
5675        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
5676GROUP BY object_id",
5677    access: vec![PUBLIC_SELECT],
5678}
5679});
5680
5681pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
5682    name: "mz_recent_storage_usage_ind",
5683    schema: MZ_CATALOG_SCHEMA,
5684    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
5685    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
5686    is_retained_metrics_object: false,
5687});
5688
5689pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
5690    BuiltinView {
5691        name: "mz_relations",
5692        schema: MZ_CATALOG_SCHEMA,
5693        oid: oid::VIEW_MZ_RELATIONS_OID,
5694        desc: RelationDesc::builder()
5695            .with_column("id", SqlScalarType::String.nullable(false))
5696            .with_column("oid", SqlScalarType::Oid.nullable(false))
5697            .with_column("schema_id", SqlScalarType::String.nullable(false))
5698            .with_column("name", SqlScalarType::String.nullable(false))
5699            .with_column("type", SqlScalarType::String.nullable(false))
5700            .with_column("owner_id", SqlScalarType::String.nullable(false))
5701            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5702            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false))
5703            .finish(),
5704        column_comments: BTreeMap::from_iter([
5705            ("id", "Materialize's unique ID for the relation."),
5706            ("oid", "A PostgreSQL-compatible OID for the relation."),
5707            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
5708            ("name", "The name of the relation."),
5709            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
5710            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
5711            ("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."),
5712            ("privileges", "The privileges belonging to the relation."),
5713        ]),
5714        sql: "
5715      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
5716UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
5717UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
5718UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views
5719UNION ALL SELECT id, oid, schema_id, name, 'continual-task', owner_id, cluster_id, privileges FROM mz_internal.mz_continual_tasks",
5720        access: vec![PUBLIC_SELECT],
5721    }
5722});
5723
5724pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5725    name: "mz_objects_id_namespace_types",
5726    schema: MZ_INTERNAL_SCHEMA,
5727    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
5728    desc: RelationDesc::builder()
5729        .with_column("object_type", SqlScalarType::String.nullable(false))
5730        .with_key(vec![0])
5731        .finish(),
5732    column_comments: BTreeMap::new(),
5733    sql: r#"SELECT *
5734    FROM (
5735        VALUES
5736            ('table'),
5737            ('view'),
5738            ('materialized-view'),
5739            ('source'),
5740            ('sink'),
5741            ('index'),
5742            ('connection'),
5743            ('type'),
5744            ('function'),
5745            ('secret')
5746    )
5747    AS _ (object_type)"#,
5748    access: vec![PUBLIC_SELECT],
5749});
5750
5751pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5752    name: "mz_object_oid_alias",
5753    schema: MZ_INTERNAL_SCHEMA,
5754    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
5755    desc: RelationDesc::builder()
5756        .with_column("object_type", SqlScalarType::String.nullable(false))
5757        .with_column("oid_alias", SqlScalarType::String.nullable(false))
5758        .with_key(vec![0])
5759        .finish(),
5760    column_comments: BTreeMap::new(),
5761    sql: "SELECT object_type, oid_alias
5762    FROM (
5763        VALUES
5764            (
5765                'table'::pg_catalog.text,
5766                'regclass'::pg_catalog.text
5767            ),
5768            ('source', 'regclass'),
5769            ('view', 'regclass'),
5770            ('materialized-view', 'regclass'),
5771            ('index', 'regclass'),
5772            ('type', 'regtype'),
5773            ('function', 'regproc')
5774    )
5775    AS _ (object_type, oid_alias);",
5776    access: vec![PUBLIC_SELECT],
5777});
5778
5779pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
5780    BuiltinView {
5781        name: "mz_objects",
5782        schema: MZ_CATALOG_SCHEMA,
5783        oid: oid::VIEW_MZ_OBJECTS_OID,
5784        desc: RelationDesc::builder()
5785            .with_column("id", SqlScalarType::String.nullable(false))
5786            .with_column("oid", SqlScalarType::Oid.nullable(false))
5787            .with_column("schema_id", SqlScalarType::String.nullable(false))
5788            .with_column("name", SqlScalarType::String.nullable(false))
5789            .with_column("type", SqlScalarType::String.nullable(false))
5790            .with_column("owner_id", SqlScalarType::String.nullable(false))
5791            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5792            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(true))
5793            .finish(),
5794        column_comments: BTreeMap::from_iter([
5795            ("id", "Materialize's unique ID for the object."),
5796            ("oid", "A PostgreSQL-compatible OID for the object."),
5797            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
5798            ("name", "The name of the object."),
5799            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
5800            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
5801            ("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."),
5802            ("privileges", "The privileges belonging to the object."),
5803        ]),
5804        sql:
5805        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
5806UNION ALL
5807    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
5808UNION ALL
5809    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[]
5810    FROM mz_catalog.mz_indexes
5811    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
5812UNION ALL
5813    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
5814UNION ALL
5815    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
5816UNION ALL
5817    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
5818UNION ALL
5819    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
5820        access: vec![PUBLIC_SELECT],
5821    }
5822});
5823
5824pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5825    name: "mz_object_fully_qualified_names",
5826    schema: MZ_INTERNAL_SCHEMA,
5827    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
5828    desc: RelationDesc::builder()
5829        .with_column("id", SqlScalarType::String.nullable(false))
5830        .with_column("name", SqlScalarType::String.nullable(false))
5831        .with_column("object_type", SqlScalarType::String.nullable(false))
5832        .with_column("schema_id", SqlScalarType::String.nullable(false))
5833        .with_column("schema_name", SqlScalarType::String.nullable(false))
5834        .with_column("database_id", SqlScalarType::String.nullable(true))
5835        .with_column("database_name", SqlScalarType::String.nullable(true))
5836        .with_column("cluster_id", SqlScalarType::String.nullable(true))
5837        .finish(),
5838    column_comments: BTreeMap::from_iter([
5839        ("id", "Materialize's unique ID for the object."),
5840        ("name", "The name of the object."),
5841        (
5842            "object_type",
5843            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5844        ),
5845        (
5846            "schema_id",
5847            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
5848        ),
5849        (
5850            "schema_name",
5851            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
5852        ),
5853        (
5854            "database_id",
5855            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
5856        ),
5857        (
5858            "database_name",
5859            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
5860        ),
5861        (
5862            "cluster_id",
5863            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
5864        ),
5865    ]),
5866    sql: "
5867    SELECT o.id,
5868        o.name,
5869        o.type as object_type,
5870        sc.id as schema_id,
5871        sc.name as schema_name,
5872        db.id as database_id,
5873        db.name as database_name,
5874        o.cluster_id
5875    FROM mz_catalog.mz_objects o
5876    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
5877    -- LEFT JOIN accounts for objects in the ambient database.
5878    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
5879    access: vec![PUBLIC_SELECT],
5880});
5881
5882pub static MZ_OBJECT_GLOBAL_IDS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5883    name: "mz_object_global_ids",
5884    schema: MZ_INTERNAL_SCHEMA,
5885    oid: oid::VIEW_MZ_OBJECT_GLOBAL_IDS_OID,
5886    desc: RelationDesc::builder()
5887        .with_column("id", SqlScalarType::String.nullable(false))
5888        .with_column("global_id", SqlScalarType::String.nullable(false))
5889        .finish(),
5890    column_comments: BTreeMap::from_iter([
5891        (
5892            "id",
5893            "The ID of the object. Corresponds to `mz_objects.id`.",
5894        ),
5895        ("global_id", "The global ID of the object."),
5896    ]),
5897    is_retained_metrics_object: false,
5898    access: vec![PUBLIC_SELECT],
5899});
5900
5901// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
5902pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5903    name: "mz_object_lifetimes",
5904    schema: MZ_INTERNAL_SCHEMA,
5905    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
5906    desc: RelationDesc::builder()
5907        .with_column("id", SqlScalarType::String.nullable(true))
5908        .with_column("previous_id", SqlScalarType::String.nullable(true))
5909        .with_column("object_type", SqlScalarType::String.nullable(false))
5910        .with_column("event_type", SqlScalarType::String.nullable(false))
5911        .with_column(
5912            "occurred_at",
5913            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5914        )
5915        .finish(),
5916    column_comments: BTreeMap::from_iter([
5917        ("id", "Materialize's unique ID for the object."),
5918        ("previous_id", "The object's previous ID, if one exists."),
5919        (
5920            "object_type",
5921            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5922        ),
5923        (
5924            "event_type",
5925            "The lifetime event, either `create` or `drop`.",
5926        ),
5927        (
5928            "occurred_at",
5929            "Wall-clock timestamp of when the event occurred.",
5930        ),
5931    ]),
5932    sql: "
5933    SELECT
5934        CASE
5935            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
5936            ELSE a.details ->> 'id'
5937        END id,
5938        a.details ->> 'previous_id' as previous_id,
5939        a.object_type,
5940        a.event_type,
5941        a.occurred_at
5942    FROM mz_catalog.mz_audit_events a
5943    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
5944    access: vec![PUBLIC_SELECT],
5945});
5946
5947pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5948    name: "mz_object_history",
5949    schema: MZ_INTERNAL_SCHEMA,
5950    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
5951    desc: RelationDesc::builder()
5952        .with_column("id", SqlScalarType::String.nullable(true))
5953        .with_column("cluster_id", SqlScalarType::String.nullable(true))
5954        .with_column("object_type", SqlScalarType::String.nullable(false))
5955        .with_column(
5956            "created_at",
5957            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5958        )
5959        .with_column(
5960            "dropped_at",
5961            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5962        )
5963        .finish(),
5964    column_comments: BTreeMap::from_iter([
5965        ("id", "Materialize's unique ID for the object."),
5966        (
5967            "cluster_id",
5968            "The object's cluster ID. `NULL` if the object has no associated cluster.",
5969        ),
5970        (
5971            "object_type",
5972            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5973        ),
5974        (
5975            "created_at",
5976            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
5977        ),
5978        (
5979            "dropped_at",
5980            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
5981        ),
5982    ]),
5983    sql: r#"
5984    WITH
5985        creates AS
5986        (
5987            SELECT
5988                details ->> 'id' AS id,
5989                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
5990                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
5991                object_type,
5992                occurred_at
5993            FROM
5994                mz_catalog.mz_audit_events AS events
5995                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
5996            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
5997        ),
5998        drops AS
5999        (
6000            SELECT details ->> 'id' AS id, occurred_at
6001            FROM mz_catalog.mz_audit_events
6002            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6003        ),
6004        user_object_history AS
6005        (
6006            SELECT
6007                creates.id,
6008                creates.cluster_id,
6009                creates.object_type,
6010                creates.occurred_at AS created_at,
6011                drops.occurred_at AS dropped_at
6012            FROM creates LEFT JOIN drops ON creates.id = drops.id
6013            WHERE creates.id LIKE 'u%'
6014        ),
6015        -- We need to union built in objects since they aren't in the audit log
6016        built_in_objects AS
6017        (
6018            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
6019            SELECT DISTINCT ON (objects.id)
6020                objects.id,
6021                objects.cluster_id,
6022                objects.type AS object_type,
6023                NULL::timestamptz AS created_at,
6024                NULL::timestamptz AS dropped_at
6025            FROM mz_catalog.mz_objects AS objects
6026            WHERE objects.id LIKE 's%'
6027        )
6028    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
6029    access: vec![PUBLIC_SELECT],
6030});
6031
6032pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6033    name: "mz_dataflows_per_worker",
6034    schema: MZ_INTROSPECTION_SCHEMA,
6035    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
6036    desc: RelationDesc::builder()
6037        .with_column("id", SqlScalarType::UInt64.nullable(true))
6038        .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6039        .with_column("name", SqlScalarType::String.nullable(false))
6040        .finish(),
6041    column_comments: BTreeMap::new(),
6042    sql: "SELECT
6043    addrs.address[1] AS id,
6044    ops.worker_id,
6045    ops.name
6046FROM
6047    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6048    mz_introspection.mz_dataflow_operators_per_worker ops
6049WHERE
6050    addrs.id = ops.id AND
6051    addrs.worker_id = ops.worker_id AND
6052    mz_catalog.list_length(addrs.address) = 1",
6053    access: vec![PUBLIC_SELECT],
6054});
6055
6056pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6057    name: "mz_dataflows",
6058    schema: MZ_INTROSPECTION_SCHEMA,
6059    oid: oid::VIEW_MZ_DATAFLOWS_OID,
6060    desc: RelationDesc::builder()
6061        .with_column("id", SqlScalarType::UInt64.nullable(true))
6062        .with_column("name", SqlScalarType::String.nullable(false))
6063        .finish(),
6064    column_comments: BTreeMap::from_iter([
6065        ("id", "The ID of the dataflow."),
6066        ("name", "The internal name of the dataflow."),
6067    ]),
6068    sql: "
6069SELECT id, name
6070FROM mz_introspection.mz_dataflows_per_worker
6071WHERE worker_id = 0",
6072    access: vec![PUBLIC_SELECT],
6073});
6074
6075pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6076    name: "mz_dataflow_addresses",
6077    schema: MZ_INTROSPECTION_SCHEMA,
6078    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
6079    desc: RelationDesc::builder()
6080        .with_column("id", SqlScalarType::UInt64.nullable(false))
6081        .with_column(
6082            "address",
6083            SqlScalarType::List {
6084                element_type: Box::new(SqlScalarType::UInt64),
6085                custom_id: None,
6086            }
6087            .nullable(false),
6088        )
6089        .finish(),
6090    column_comments: BTreeMap::from_iter([
6091        (
6092            "id",
6093            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
6094        ),
6095        (
6096            "address",
6097            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
6098        ),
6099    ]),
6100    sql: "
6101SELECT id, address
6102FROM mz_introspection.mz_dataflow_addresses_per_worker
6103WHERE worker_id = 0",
6104    access: vec![PUBLIC_SELECT],
6105});
6106
6107pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6108    name: "mz_dataflow_channels",
6109    schema: MZ_INTROSPECTION_SCHEMA,
6110    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
6111    desc: RelationDesc::builder()
6112        .with_column("id", SqlScalarType::UInt64.nullable(false))
6113        .with_column("from_index", SqlScalarType::UInt64.nullable(false))
6114        .with_column("from_port", SqlScalarType::UInt64.nullable(false))
6115        .with_column("to_index", SqlScalarType::UInt64.nullable(false))
6116        .with_column("to_port", SqlScalarType::UInt64.nullable(false))
6117        .with_column("type", SqlScalarType::String.nullable(false))
6118        .finish(),
6119    column_comments: BTreeMap::from_iter([
6120        ("id", "The ID of the channel."),
6121        (
6122            "from_index",
6123            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
6124        ),
6125        ("from_port", "The source operator's output port."),
6126        (
6127            "to_index",
6128            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
6129        ),
6130        ("to_port", "The target operator's input port."),
6131        ("type", "The container type of the channel."),
6132    ]),
6133    sql: "
6134SELECT id, from_index, from_port, to_index, to_port, type
6135FROM mz_introspection.mz_dataflow_channels_per_worker
6136WHERE worker_id = 0",
6137    access: vec![PUBLIC_SELECT],
6138});
6139
6140pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6141    name: "mz_dataflow_operators",
6142    schema: MZ_INTROSPECTION_SCHEMA,
6143    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6144    desc: RelationDesc::builder()
6145        .with_column("id", SqlScalarType::UInt64.nullable(false))
6146        .with_column("name", SqlScalarType::String.nullable(false))
6147        .finish(),
6148    column_comments: BTreeMap::from_iter([
6149        ("id", "The ID of the operator."),
6150        ("name", "The internal name of the operator."),
6151    ]),
6152    sql: "
6153SELECT id, name
6154FROM mz_introspection.mz_dataflow_operators_per_worker
6155WHERE worker_id = 0",
6156    access: vec![PUBLIC_SELECT],
6157});
6158
6159pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6160    name: "mz_dataflow_global_ids",
6161    schema: MZ_INTROSPECTION_SCHEMA,
6162    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6163    desc: RelationDesc::builder()
6164        .with_column("id", SqlScalarType::UInt64.nullable(false))
6165        .with_column("global_id", SqlScalarType::String.nullable(false))
6166        .finish(),
6167    column_comments: BTreeMap::from_iter([
6168        ("id", "The dataflow ID."),
6169        ("global_id", "A global ID associated with that dataflow."),
6170    ]),
6171    sql: "
6172SELECT id, global_id
6173FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6174WHERE worker_id = 0",
6175    access: vec![PUBLIC_SELECT],
6176});
6177
6178pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6179    BuiltinView {
6180    name: "mz_mappable_objects",
6181    schema: MZ_INTROSPECTION_SCHEMA,
6182    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6183    desc: RelationDesc::builder()
6184        .with_column("name", SqlScalarType::String.nullable(false))
6185        .with_column("global_id", SqlScalarType::String.nullable(false))
6186        .finish(),
6187    column_comments: BTreeMap::from_iter([
6188        ("name", "The name of the object."),
6189        ("global_id", "The global ID of the object."),
6190    ]),
6191    sql: "
6192SELECT COALESCE(quote_ident(md.name) || '.', '') || quote_ident(ms.name) || '.' || quote_ident(mo.name) AS name, mgi.global_id AS global_id
6193FROM      mz_catalog.mz_objects mo
6194          JOIN mz_introspection.mz_compute_exports mce ON (mo.id = mce.export_id)
6195          JOIN mz_catalog.mz_schemas ms ON (mo.schema_id = ms.id)
6196          JOIN mz_introspection.mz_dataflow_global_ids mgi ON (mce.dataflow_id = mgi.id)
6197     LEFT JOIN mz_catalog.mz_databases md ON (ms.database_id = md.id);",
6198    access: vec![PUBLIC_SELECT],
6199}
6200});
6201
6202pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6203    name: "mz_lir_mapping",
6204    schema: MZ_INTROSPECTION_SCHEMA,
6205    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6206    desc: RelationDesc::builder()
6207        .with_column("global_id", SqlScalarType::String.nullable(false))
6208        .with_column("lir_id", SqlScalarType::UInt64.nullable(false))
6209        .with_column("operator", SqlScalarType::String.nullable(false))
6210        .with_column("parent_lir_id", SqlScalarType::UInt64.nullable(true))
6211        .with_column("nesting", SqlScalarType::UInt16.nullable(false))
6212        .with_column("operator_id_start", SqlScalarType::UInt64.nullable(false))
6213        .with_column("operator_id_end", SqlScalarType::UInt64.nullable(false))
6214        .finish(),
6215    column_comments: BTreeMap::from_iter([
6216        ("global_id", "The global ID."),
6217        ("lir_id", "The LIR node ID."),
6218        (
6219            "operator",
6220            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6221        ),
6222        (
6223            "parent_lir_id",
6224            "The parent of this LIR node. May be `NULL`.",
6225        ),
6226        ("nesting", "The nesting level of this LIR node."),
6227        (
6228            "operator_id_start",
6229            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6230        ),
6231        (
6232            "operator_id_end",
6233            "The first dataflow operator ID _after_ this LIR operator (exclusive).",
6234        ),
6235    ]),
6236    sql: "
6237SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6238FROM mz_introspection.mz_compute_lir_mapping_per_worker
6239WHERE worker_id = 0",
6240    access: vec![PUBLIC_SELECT],
6241});
6242
6243pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6244    LazyLock::new(|| BuiltinView {
6245        name: "mz_dataflow_operator_dataflows_per_worker",
6246        schema: MZ_INTROSPECTION_SCHEMA,
6247        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6248        desc: RelationDesc::builder()
6249            .with_column("id", SqlScalarType::UInt64.nullable(false))
6250            .with_column("name", SqlScalarType::String.nullable(false))
6251            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6252            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6253            .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6254            .finish(),
6255        column_comments: BTreeMap::new(),
6256        sql: "SELECT
6257    ops.id,
6258    ops.name,
6259    ops.worker_id,
6260    dfs.id as dataflow_id,
6261    dfs.name as dataflow_name
6262FROM
6263    mz_introspection.mz_dataflow_operators_per_worker ops,
6264    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6265    mz_introspection.mz_dataflows_per_worker dfs
6266WHERE
6267    ops.id = addrs.id AND
6268    ops.worker_id = addrs.worker_id AND
6269    dfs.id = addrs.address[1] AND
6270    dfs.worker_id = addrs.worker_id",
6271        access: vec![PUBLIC_SELECT],
6272    });
6273
6274pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6275    name: "mz_dataflow_operator_dataflows",
6276    schema: MZ_INTROSPECTION_SCHEMA,
6277    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6278    desc: RelationDesc::builder()
6279        .with_column("id", SqlScalarType::UInt64.nullable(false))
6280        .with_column("name", SqlScalarType::String.nullable(false))
6281        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6282        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6283        .finish(),
6284    column_comments: BTreeMap::from_iter([
6285        (
6286            "id",
6287            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6288        ),
6289        ("name", "The internal name of the operator."),
6290        (
6291            "dataflow_id",
6292            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6293        ),
6294        (
6295            "dataflow_name",
6296            "The internal name of the dataflow hosting the operator.",
6297        ),
6298    ]),
6299    sql: "
6300SELECT id, name, dataflow_id, dataflow_name
6301FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6302WHERE worker_id = 0",
6303    access: vec![PUBLIC_SELECT],
6304});
6305
6306pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6307    BuiltinView {
6308        name: "mz_object_transitive_dependencies",
6309        schema: MZ_INTERNAL_SCHEMA,
6310        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6311        desc: RelationDesc::builder()
6312            .with_column("object_id", SqlScalarType::String.nullable(false))
6313            .with_column(
6314                "referenced_object_id",
6315                SqlScalarType::String.nullable(false),
6316            )
6317            .with_key(vec![0, 1])
6318            .finish(),
6319        column_comments: BTreeMap::from_iter([
6320            (
6321                "object_id",
6322                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6323            ),
6324            (
6325                "referenced_object_id",
6326                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6327            ),
6328        ]),
6329        sql: "
6330WITH MUTUALLY RECURSIVE
6331  reach(object_id text, referenced_object_id text) AS (
6332    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6333    UNION
6334    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6335  )
6336SELECT object_id, referenced_object_id FROM reach;",
6337        access: vec![PUBLIC_SELECT],
6338    }
6339});
6340
6341pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6342    name: "mz_compute_exports",
6343    schema: MZ_INTROSPECTION_SCHEMA,
6344    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6345    desc: RelationDesc::builder()
6346        .with_column("export_id", SqlScalarType::String.nullable(false))
6347        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6348        .finish(),
6349    column_comments: BTreeMap::from_iter([
6350        (
6351            "export_id",
6352            "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`.",
6353        ),
6354        (
6355            "dataflow_id",
6356            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6357        ),
6358    ]),
6359    sql: "
6360SELECT export_id, dataflow_id
6361FROM mz_introspection.mz_compute_exports_per_worker
6362WHERE worker_id = 0",
6363    access: vec![PUBLIC_SELECT],
6364});
6365
6366pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6367    name: "mz_compute_frontiers",
6368    schema: MZ_INTROSPECTION_SCHEMA,
6369    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6370    desc: RelationDesc::builder()
6371        .with_column("export_id", SqlScalarType::String.nullable(false))
6372        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6373        .with_key(vec![0])
6374        .finish(),
6375    column_comments: BTreeMap::from_iter([
6376        (
6377            "export_id",
6378            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6379        ),
6380        (
6381            "time",
6382            "The next timestamp at which the dataflow output may change.",
6383        ),
6384    ]),
6385    sql: "SELECT
6386    export_id, pg_catalog.min(time) AS time
6387FROM mz_introspection.mz_compute_frontiers_per_worker
6388GROUP BY export_id",
6389    access: vec![PUBLIC_SELECT],
6390});
6391
6392pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6393    LazyLock::new(|| BuiltinView {
6394        name: "mz_dataflow_channel_operators_per_worker",
6395        schema: MZ_INTROSPECTION_SCHEMA,
6396        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6397        desc: RelationDesc::builder()
6398            .with_column("id", SqlScalarType::UInt64.nullable(false))
6399            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6400            .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6401            .with_column(
6402                "from_operator_address",
6403                SqlScalarType::List {
6404                    element_type: Box::new(SqlScalarType::UInt64),
6405                    custom_id: None,
6406                }
6407                .nullable(true),
6408            )
6409            .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6410            .with_column(
6411                "to_operator_address",
6412                SqlScalarType::List {
6413                    element_type: Box::new(SqlScalarType::UInt64),
6414                    custom_id: None,
6415                }
6416                .nullable(true),
6417            )
6418            .with_column("type", SqlScalarType::String.nullable(false))
6419            .finish(),
6420        column_comments: BTreeMap::new(),
6421        sql: "
6422WITH
6423channel_addresses(id, worker_id, address, from_index, to_index, type) AS (
6424     SELECT id, worker_id, address, from_index, to_index, type
6425     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6426     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6427     USING (id, worker_id)
6428),
6429channel_operator_addresses(id, worker_id, from_address, to_address, type) AS (
6430     SELECT id, worker_id,
6431            address || from_index AS from_address,
6432            address || to_index AS to_address,
6433            type
6434     FROM channel_addresses
6435),
6436operator_addresses(id, worker_id, address) AS (
6437     SELECT id, worker_id, address
6438     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6439     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6440     USING (id, worker_id)
6441)
6442SELECT coa.id,
6443       coa.worker_id,
6444       from_ops.id AS from_operator_id,
6445       coa.from_address AS from_operator_address,
6446       to_ops.id AS to_operator_id,
6447       coa.to_address AS to_operator_address,
6448       coa.type
6449FROM channel_operator_addresses coa
6450     LEFT OUTER JOIN operator_addresses from_ops
6451          ON coa.from_address = from_ops.address AND
6452             coa.worker_id = from_ops.worker_id
6453     LEFT OUTER JOIN operator_addresses to_ops
6454          ON coa.to_address = to_ops.address AND
6455             coa.worker_id = to_ops.worker_id
6456",
6457        access: vec![PUBLIC_SELECT],
6458    });
6459
6460pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6461    name: "mz_dataflow_channel_operators",
6462    schema: MZ_INTROSPECTION_SCHEMA,
6463    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6464    desc: RelationDesc::builder()
6465        .with_column("id", SqlScalarType::UInt64.nullable(false))
6466        .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6467        .with_column(
6468            "from_operator_address",
6469            SqlScalarType::List {
6470                element_type: Box::new(SqlScalarType::UInt64),
6471                custom_id: None,
6472            }
6473            .nullable(true),
6474        )
6475        .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6476        .with_column(
6477            "to_operator_address",
6478            SqlScalarType::List {
6479                element_type: Box::new(SqlScalarType::UInt64),
6480                custom_id: None,
6481            }
6482            .nullable(true),
6483        )
6484        .with_column("type", SqlScalarType::String.nullable(false))
6485        .finish(),
6486    column_comments: BTreeMap::from_iter([
6487        (
6488            "id",
6489            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6490        ),
6491        (
6492            "from_operator_id",
6493            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6494        ),
6495        (
6496            "from_operator_address",
6497            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6498        ),
6499        (
6500            "to_operator_id",
6501            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6502        ),
6503        (
6504            "to_operator_address",
6505            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6506        ),
6507        ("type", "The container type of the channel."),
6508    ]),
6509    sql: "
6510SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address, type
6511FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6512WHERE worker_id = 0",
6513    access: vec![PUBLIC_SELECT],
6514});
6515
6516pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6517    name: "mz_compute_import_frontiers",
6518    schema: MZ_INTROSPECTION_SCHEMA,
6519    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6520    desc: RelationDesc::builder()
6521        .with_column("export_id", SqlScalarType::String.nullable(false))
6522        .with_column("import_id", SqlScalarType::String.nullable(false))
6523        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6524        .with_key(vec![0, 1])
6525        .finish(),
6526    column_comments: BTreeMap::from_iter([
6527        (
6528            "export_id",
6529            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6530        ),
6531        (
6532            "import_id",
6533            "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`.",
6534        ),
6535        (
6536            "time",
6537            "The next timestamp at which the dataflow input may change.",
6538        ),
6539    ]),
6540    sql: "SELECT
6541    export_id, import_id, pg_catalog.min(time) AS time
6542FROM mz_introspection.mz_compute_import_frontiers_per_worker
6543GROUP BY export_id, import_id",
6544    access: vec![PUBLIC_SELECT],
6545});
6546
6547pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6548    LazyLock::new(|| BuiltinView {
6549        name: "mz_records_per_dataflow_operator_per_worker",
6550        schema: MZ_INTROSPECTION_SCHEMA,
6551        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6552        desc: RelationDesc::builder()
6553            .with_column("id", SqlScalarType::UInt64.nullable(false))
6554            .with_column("name", SqlScalarType::String.nullable(false))
6555            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6556            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6557            .with_column("records", SqlScalarType::Int64.nullable(true))
6558            .with_column("batches", SqlScalarType::Int64.nullable(true))
6559            .with_column("size", SqlScalarType::Int64.nullable(true))
6560            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6561            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6562            .finish(),
6563        column_comments: BTreeMap::new(),
6564        sql: "
6565SELECT
6566    dod.id,
6567    dod.name,
6568    dod.worker_id,
6569    dod.dataflow_id,
6570    ar_size.records AS records,
6571    ar_size.batches AS batches,
6572    ar_size.size AS size,
6573    ar_size.capacity AS capacity,
6574    ar_size.allocations AS allocations
6575FROM
6576    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6577    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6578        dod.id = ar_size.operator_id AND
6579        dod.worker_id = ar_size.worker_id",
6580        access: vec![PUBLIC_SELECT],
6581    });
6582
6583pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6584    LazyLock::new(|| BuiltinView {
6585        name: "mz_records_per_dataflow_operator",
6586        schema: MZ_INTROSPECTION_SCHEMA,
6587        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6588        desc: RelationDesc::builder()
6589            .with_column("id", SqlScalarType::UInt64.nullable(false))
6590            .with_column("name", SqlScalarType::String.nullable(false))
6591            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6592            .with_column("records", SqlScalarType::Int64.nullable(true))
6593            .with_column("batches", SqlScalarType::Int64.nullable(true))
6594            .with_column("size", SqlScalarType::Int64.nullable(true))
6595            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6596            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6597            .with_key(vec![0, 1, 2])
6598            .finish(),
6599        column_comments: BTreeMap::from_iter([
6600            (
6601                "id",
6602                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6603            ),
6604            ("name", "The internal name of the operator."),
6605            (
6606                "dataflow_id",
6607                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6608            ),
6609            ("records", "The number of records in the operator."),
6610            ("batches", "The number of batches in the dataflow."),
6611            ("size", "The utilized size in bytes of the arrangement."),
6612            (
6613                "capacity",
6614                "The capacity in bytes of the arrangement. Can be larger than the size.",
6615            ),
6616            (
6617                "allocations",
6618                "The number of separate memory allocations backing the arrangement.",
6619            ),
6620        ]),
6621        sql: "
6622SELECT
6623    id,
6624    name,
6625    dataflow_id,
6626    SUM(records)::int8 AS records,
6627    SUM(batches)::int8 AS batches,
6628    SUM(size)::int8 AS size,
6629    SUM(capacity)::int8 AS capacity,
6630    SUM(allocations)::int8 AS allocations
6631FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
6632GROUP BY id, name, dataflow_id",
6633        access: vec![PUBLIC_SELECT],
6634    });
6635
6636pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
6637    LazyLock::new(|| BuiltinView {
6638        name: "mz_records_per_dataflow_per_worker",
6639        schema: MZ_INTROSPECTION_SCHEMA,
6640        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
6641        desc: RelationDesc::builder()
6642            .with_column("id", SqlScalarType::UInt64.nullable(false))
6643            .with_column("name", SqlScalarType::String.nullable(false))
6644            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6645            .with_column("records", SqlScalarType::Int64.nullable(true))
6646            .with_column("batches", SqlScalarType::Int64.nullable(true))
6647            .with_column("size", SqlScalarType::Int64.nullable(true))
6648            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6649            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6650            .with_key(vec![0, 1, 2])
6651            .finish(),
6652        column_comments: BTreeMap::new(),
6653        sql: "
6654SELECT
6655    rdo.dataflow_id as id,
6656    dfs.name,
6657    rdo.worker_id,
6658    SUM(rdo.records)::int8 as records,
6659    SUM(rdo.batches)::int8 as batches,
6660    SUM(rdo.size)::int8 as size,
6661    SUM(rdo.capacity)::int8 as capacity,
6662    SUM(rdo.allocations)::int8 as allocations
6663FROM
6664    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
6665    mz_introspection.mz_dataflows_per_worker dfs
6666WHERE
6667    rdo.dataflow_id = dfs.id AND
6668    rdo.worker_id = dfs.worker_id
6669GROUP BY
6670    rdo.dataflow_id,
6671    dfs.name,
6672    rdo.worker_id",
6673        access: vec![PUBLIC_SELECT],
6674    });
6675
6676pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6677    name: "mz_records_per_dataflow",
6678    schema: MZ_INTROSPECTION_SCHEMA,
6679    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
6680    desc: RelationDesc::builder()
6681        .with_column("id", SqlScalarType::UInt64.nullable(false))
6682        .with_column("name", SqlScalarType::String.nullable(false))
6683        .with_column("records", SqlScalarType::Int64.nullable(true))
6684        .with_column("batches", SqlScalarType::Int64.nullable(true))
6685        .with_column("size", SqlScalarType::Int64.nullable(true))
6686        .with_column("capacity", SqlScalarType::Int64.nullable(true))
6687        .with_column("allocations", SqlScalarType::Int64.nullable(true))
6688        .with_key(vec![0, 1])
6689        .finish(),
6690    column_comments: BTreeMap::from_iter([
6691        (
6692            "id",
6693            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6694        ),
6695        ("name", "The internal name of the dataflow."),
6696        ("records", "The number of records in the dataflow."),
6697        ("batches", "The number of batches in the dataflow."),
6698        ("size", "The utilized size in bytes of the arrangements."),
6699        (
6700            "capacity",
6701            "The capacity in bytes of the arrangements. Can be larger than the size.",
6702        ),
6703        (
6704            "allocations",
6705            "The number of separate memory allocations backing the arrangements.",
6706        ),
6707    ]),
6708    sql: "
6709SELECT
6710    id,
6711    name,
6712    SUM(records)::int8 as records,
6713    SUM(batches)::int8 as batches,
6714    SUM(size)::int8 as size,
6715    SUM(capacity)::int8 as capacity,
6716    SUM(allocations)::int8 as allocations
6717FROM
6718    mz_introspection.mz_records_per_dataflow_per_worker
6719GROUP BY
6720    id,
6721    name",
6722    access: vec![PUBLIC_SELECT],
6723});
6724
6725/// Peeled version of `PG_NAMESPACE`:
6726/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6727///   in order to make this view indexable.
6728/// - This has the database name as an extra column, so that downstream views can check it against
6729///  `current_database()`.
6730pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6731    name: "pg_namespace_all_databases",
6732    schema: MZ_INTERNAL_SCHEMA,
6733    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
6734    desc: RelationDesc::builder()
6735        .with_column("oid", SqlScalarType::Oid.nullable(false))
6736        .with_column("nspname", SqlScalarType::String.nullable(false))
6737        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6738        .with_column(
6739            "nspacl",
6740            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6741        )
6742        .with_column("database_name", SqlScalarType::String.nullable(true))
6743        .finish(),
6744    column_comments: BTreeMap::new(),
6745    sql: "
6746SELECT
6747    s.oid AS oid,
6748    s.name AS nspname,
6749    role_owner.oid AS nspowner,
6750    NULL::pg_catalog.text[] AS nspacl,
6751    d.name as database_name
6752FROM mz_catalog.mz_schemas s
6753LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
6754JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
6755    access: vec![PUBLIC_SELECT],
6756});
6757
6758pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6759    name: "pg_namespace_all_databases_ind",
6760    schema: MZ_INTERNAL_SCHEMA,
6761    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
6762    sql: "IN CLUSTER mz_catalog_server
6763ON mz_internal.pg_namespace_all_databases (nspname)",
6764    is_retained_metrics_object: false,
6765};
6766
6767pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6768    name: "pg_namespace",
6769    schema: PG_CATALOG_SCHEMA,
6770    oid: oid::VIEW_PG_NAMESPACE_OID,
6771    desc: RelationDesc::builder()
6772        .with_column("oid", SqlScalarType::Oid.nullable(false))
6773        .with_column("nspname", SqlScalarType::String.nullable(false))
6774        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6775        .with_column(
6776            "nspacl",
6777            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6778        )
6779        .finish(),
6780    column_comments: BTreeMap::new(),
6781    sql: "
6782SELECT
6783    oid, nspname, nspowner, nspacl
6784FROM mz_internal.pg_namespace_all_databases
6785WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
6786    access: vec![PUBLIC_SELECT],
6787});
6788
6789/// Peeled version of `PG_CLASS`:
6790/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6791///   in order to make this view indexable.
6792/// - This has the database name as an extra column, so that downstream views can check it against
6793///  `current_database()`.
6794pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
6795    BuiltinView {
6796        name: "pg_class_all_databases",
6797        schema: MZ_INTERNAL_SCHEMA,
6798        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
6799        desc: RelationDesc::builder()
6800            .with_column("oid", SqlScalarType::Oid.nullable(false))
6801            .with_column("relname", SqlScalarType::String.nullable(false))
6802            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
6803            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
6804            .with_column("relowner", SqlScalarType::Oid.nullable(false))
6805            .with_column("relam", SqlScalarType::Oid.nullable(false))
6806            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
6807            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
6808            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
6809            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
6810            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
6811            .with_column("relkind", SqlScalarType::String.nullable(true))
6812            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
6813            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
6814            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
6815            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
6816            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
6817            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
6818            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
6819            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
6820            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
6821            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
6822            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
6823            .with_column("database_name", SqlScalarType::String.nullable(true))
6824            .finish(),
6825        column_comments: BTreeMap::new(),
6826        sql: "
6827SELECT
6828    class_objects.oid,
6829    class_objects.name AS relname,
6830    mz_schemas.oid AS relnamespace,
6831    -- MZ doesn't support typed tables so reloftype is filled with 0
6832    0::pg_catalog.oid AS reloftype,
6833    role_owner.oid AS relowner,
6834    0::pg_catalog.oid AS relam,
6835    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
6836    0::pg_catalog.oid AS reltablespace,
6837    -- MZ doesn't support (estimated) row counts currently.
6838    -- Postgres defines a value of -1 as unknown.
6839    -1::float4 as reltuples,
6840    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
6841    0::pg_catalog.oid AS reltoastrelid,
6842    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
6843    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
6844    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
6845    -- TODO(jkosh44): update this column when issue is resolved.
6846    'p'::pg_catalog.\"char\" AS relpersistence,
6847    CASE
6848        WHEN class_objects.type = 'table' THEN 'r'
6849        WHEN class_objects.type = 'source' THEN 'r'
6850        WHEN class_objects.type = 'index' THEN 'i'
6851        WHEN class_objects.type = 'view' THEN 'v'
6852        WHEN class_objects.type = 'materialized-view' THEN 'm'
6853    END relkind,
6854    COALESCE(
6855        (
6856            SELECT count(*)::pg_catalog.int2
6857            FROM mz_catalog.mz_columns
6858            WHERE mz_columns.id = class_objects.id
6859        ),
6860        0::pg_catalog.int2
6861    ) AS relnatts,
6862    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
6863    0::pg_catalog.int2 AS relchecks,
6864    -- MZ doesn't support creating rules so relhasrules is filled with false
6865    false AS relhasrules,
6866    -- MZ doesn't support creating triggers so relhastriggers is filled with false
6867    false AS relhastriggers,
6868    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
6869    false AS relhassubclass,
6870    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
6871    false AS relrowsecurity,
6872    false AS relforcerowsecurity,
6873    -- MZ doesn't support replication so relreplident is filled with 'd' for default
6874    'd'::pg_catalog.\"char\" AS relreplident,
6875    -- MZ doesn't support table partitioning so relispartition is filled with false
6876    false AS relispartition,
6877    -- PG removed relhasoids in v12 so it's filled with false
6878    false AS relhasoids,
6879    -- MZ doesn't support options for relations
6880    NULL::pg_catalog.text[] as reloptions,
6881    d.name as database_name
6882FROM (
6883    -- pg_class catalogs relations and indexes
6884    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
6885    UNION ALL
6886        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
6887        FROM mz_catalog.mz_indexes
6888        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6889) AS class_objects
6890JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6891LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6892JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
6893        access: vec![PUBLIC_SELECT],
6894    }
6895});
6896
6897pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6898    name: "pg_class_all_databases_ind",
6899    schema: MZ_INTERNAL_SCHEMA,
6900    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
6901    sql: "IN CLUSTER mz_catalog_server
6902ON mz_internal.pg_class_all_databases (relname)",
6903    is_retained_metrics_object: false,
6904};
6905
6906pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| {
6907    BuiltinView {
6908    name: "pg_class",
6909    schema: PG_CATALOG_SCHEMA,
6910    oid: oid::VIEW_PG_CLASS_OID,
6911    desc: RelationDesc::builder()
6912        .with_column("oid", SqlScalarType::Oid.nullable(false))
6913        .with_column("relname", SqlScalarType::String.nullable(false))
6914        .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
6915        .with_column("reloftype", SqlScalarType::Oid.nullable(false))
6916        .with_column("relowner", SqlScalarType::Oid.nullable(false))
6917        .with_column("relam", SqlScalarType::Oid.nullable(false))
6918        .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
6919        .with_column("reltuples", SqlScalarType::Float32.nullable(false))
6920        .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
6921        .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
6922        .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
6923        .with_column("relkind", SqlScalarType::String.nullable(true))
6924        .with_column("relnatts", SqlScalarType::Int16.nullable(false))
6925        .with_column("relchecks", SqlScalarType::Int16.nullable(false))
6926        .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
6927        .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
6928        .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
6929        .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
6930        .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
6931        .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
6932        .with_column("relispartition", SqlScalarType::Bool.nullable(false))
6933        .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
6934        .with_column(
6935            "reloptions",
6936            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6937        )
6938        .finish(),
6939    column_comments: BTreeMap::new(),
6940    sql: "
6941SELECT
6942    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
6943    relhasindex, relpersistence, relkind, relnatts, relchecks, relhasrules, relhastriggers, relhassubclass,
6944    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
6945FROM mz_internal.pg_class_all_databases
6946WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
6947",
6948    access: vec![PUBLIC_SELECT],
6949}
6950});
6951
6952pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6953    name: "pg_depend",
6954    schema: PG_CATALOG_SCHEMA,
6955    oid: oid::VIEW_PG_DEPEND_OID,
6956    desc: RelationDesc::builder()
6957        .with_column("classid", SqlScalarType::Oid.nullable(true))
6958        .with_column("objid", SqlScalarType::Oid.nullable(false))
6959        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
6960        .with_column("refclassid", SqlScalarType::Oid.nullable(true))
6961        .with_column("refobjid", SqlScalarType::Oid.nullable(false))
6962        .with_column("refobjsubid", SqlScalarType::Int32.nullable(false))
6963        .with_column("deptype", SqlScalarType::PgLegacyChar.nullable(false))
6964        .finish(),
6965    column_comments: BTreeMap::new(),
6966    sql: "
6967WITH class_objects AS (
6968    SELECT
6969        CASE
6970            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6971            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6972            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
6973            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
6974        END classid,
6975        id,
6976        oid,
6977        schema_id
6978    FROM mz_catalog.mz_relations
6979    UNION ALL
6980    SELECT
6981        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
6982        i.id,
6983        i.oid,
6984        r.schema_id
6985    FROM mz_catalog.mz_indexes i
6986    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
6987),
6988
6989current_objects AS (
6990    SELECT class_objects.*
6991    FROM class_objects
6992    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6993    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6994    -- This filter is tricky, as it filters out not just objects outside the
6995    -- database, but *dependencies* on objects outside this database. It's not
6996    -- clear that this is the right choice, but because PostgreSQL doesn't
6997    -- support cross-database references, it's not clear that the other choice
6998    -- is better.
6999    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7000)
7001
7002SELECT
7003    objects.classid::pg_catalog.oid,
7004    objects.oid::pg_catalog.oid AS objid,
7005    0::pg_catalog.int4 AS objsubid,
7006    dependents.classid::pg_catalog.oid AS refclassid,
7007    dependents.oid::pg_catalog.oid AS refobjid,
7008    0::pg_catalog.int4 AS refobjsubid,
7009    'n'::pg_catalog.char AS deptype
7010FROM mz_internal.mz_object_dependencies
7011JOIN current_objects objects ON object_id = objects.id
7012JOIN current_objects dependents ON referenced_object_id = dependents.id",
7013    access: vec![PUBLIC_SELECT],
7014});
7015
7016pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7017    name: "pg_database",
7018    schema: PG_CATALOG_SCHEMA,
7019    oid: oid::VIEW_PG_DATABASE_OID,
7020    desc: RelationDesc::builder()
7021        .with_column("oid", SqlScalarType::Oid.nullable(false))
7022        .with_column("datname", SqlScalarType::String.nullable(false))
7023        .with_column("datdba", SqlScalarType::Oid.nullable(false))
7024        .with_column("encoding", SqlScalarType::Int32.nullable(false))
7025        .with_column("datistemplate", SqlScalarType::Bool.nullable(false))
7026        .with_column("datallowconn", SqlScalarType::Bool.nullable(false))
7027        .with_column("datcollate", SqlScalarType::String.nullable(false))
7028        .with_column("datctype", SqlScalarType::String.nullable(false))
7029        .with_column(
7030            "datacl",
7031            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7032        )
7033        .with_key(vec![0])
7034        .finish(),
7035    column_comments: BTreeMap::new(),
7036    sql: "SELECT
7037    d.oid as oid,
7038    d.name as datname,
7039    role_owner.oid as datdba,
7040    6 as encoding,
7041    -- Materialize doesn't support database cloning.
7042    FALSE AS datistemplate,
7043    TRUE AS datallowconn,
7044    'C' as datcollate,
7045    'C' as datctype,
7046    NULL::pg_catalog.text[] as datacl
7047FROM mz_catalog.mz_databases d
7048JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
7049    access: vec![PUBLIC_SELECT],
7050});
7051
7052pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
7053    BuiltinView {
7054        name: "pg_index",
7055        schema: PG_CATALOG_SCHEMA,
7056        oid: oid::VIEW_PG_INDEX_OID,
7057        desc: RelationDesc::builder()
7058            .with_column("indexrelid", SqlScalarType::Oid.nullable(false))
7059            .with_column("indrelid", SqlScalarType::Oid.nullable(false))
7060            .with_column("indnatts", SqlScalarType::Int16.nullable(false))
7061            .with_column("indisunique", SqlScalarType::Bool.nullable(false))
7062            .with_column("indisprimary", SqlScalarType::Bool.nullable(false))
7063            .with_column("indimmediate", SqlScalarType::Bool.nullable(false))
7064            .with_column("indisclustered", SqlScalarType::Bool.nullable(false))
7065            .with_column("indisvalid", SqlScalarType::Bool.nullable(false))
7066            .with_column("indisreplident", SqlScalarType::Bool.nullable(false))
7067            .with_column("indkey", SqlScalarType::Int2Vector.nullable(false))
7068            .with_column("indoption", SqlScalarType::Int2Vector.nullable(false))
7069            .with_column("indexprs", SqlScalarType::String.nullable(true))
7070            .with_column("indpred", SqlScalarType::String.nullable(true))
7071            .with_key(vec![0, 1])
7072            .finish(),
7073        column_comments: BTreeMap::new(),
7074        sql: "SELECT
7075    mz_indexes.oid AS indexrelid,
7076    mz_relations.oid AS indrelid,
7077    COALESCE(
7078        (
7079            SELECT count(*)::pg_catalog.int2
7080            FROM mz_catalog.mz_columns
7081            JOIN mz_catalog.mz_relations mri ON mz_columns.id = mri.id
7082            WHERE mri.oid = mz_catalog.mz_relations.oid
7083        ),
7084        0::pg_catalog.int2
7085    ) AS indnatts,
7086    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7087    false::pg_catalog.bool AS indisunique,
7088    false::pg_catalog.bool AS indisprimary,
7089    -- MZ doesn't support unique indexes so indimmediate is filled with false
7090    false::pg_catalog.bool AS indimmediate,
7091    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7092    false::pg_catalog.bool AS indisclustered,
7093    -- MZ never creates invalid indexes so indisvalid is filled with true
7094    true::pg_catalog.bool AS indisvalid,
7095    -- MZ doesn't support replication so indisreplident is filled with false
7096    false::pg_catalog.bool AS indisreplident,
7097    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7098    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,
7099    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7100    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7101    -- Index expressions are returned in MZ format
7102    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7103    WHEN NULL THEN NULL
7104    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7105    END AS indexprs,
7106    -- MZ doesn't support indexes with predicates
7107    NULL::pg_catalog.text AS indpred
7108FROM mz_catalog.mz_indexes
7109JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7110JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7111JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7112LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7113WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7114GROUP BY mz_indexes.oid, mz_relations.oid",
7115        access: vec![PUBLIC_SELECT],
7116    }
7117});
7118
7119pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7120    name: "pg_indexes",
7121    schema: PG_CATALOG_SCHEMA,
7122    oid: oid::VIEW_PG_INDEXES_OID,
7123    desc: RelationDesc::builder()
7124        .with_column("table_catalog", SqlScalarType::String.nullable(false))
7125        .with_column("schemaname", SqlScalarType::String.nullable(false))
7126        .with_column("tablename", SqlScalarType::String.nullable(false))
7127        .with_column("indexname", SqlScalarType::String.nullable(false))
7128        .with_column("tablespace", SqlScalarType::String.nullable(true))
7129        .with_column("indexdef", SqlScalarType::String.nullable(true))
7130        .finish(),
7131    column_comments: BTreeMap::new(),
7132    sql: "SELECT
7133    current_database() as table_catalog,
7134    s.name AS schemaname,
7135    r.name AS tablename,
7136    i.name AS indexname,
7137    NULL::text AS tablespace,
7138    -- TODO(jkosh44) Fill in with actual index definition.
7139    NULL::text AS indexdef
7140FROM mz_catalog.mz_indexes i
7141JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7142JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7143LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7144WHERE s.database_id IS NULL OR d.name = current_database()",
7145    access: vec![PUBLIC_SELECT],
7146});
7147
7148/// Peeled version of `PG_DESCRIPTION`:
7149/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7150///   in order to make this view indexable.
7151/// - This has 2 extra columns for the database names, so that downstream views can check them
7152///   against `current_database()`.
7153pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7154    BuiltinView {
7155        name: "pg_description_all_databases",
7156        schema: MZ_INTERNAL_SCHEMA,
7157        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7158        desc: RelationDesc::builder()
7159            .with_column("objoid", SqlScalarType::Oid.nullable(false))
7160            .with_column("classoid", SqlScalarType::Oid.nullable(true))
7161            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7162            .with_column("description", SqlScalarType::String.nullable(false))
7163            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
7164            .with_column("class_database_name", SqlScalarType::String.nullable(true))
7165            .finish(),
7166        column_comments: BTreeMap::new(),
7167        sql: "
7168(
7169    -- Gather all of the class oid's for objects that can have comments.
7170    WITH pg_classoids AS (
7171        SELECT oid, database_name as oid_database_name,
7172          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7173          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7174        FROM mz_internal.pg_class_all_databases
7175        UNION ALL
7176        SELECT oid, database_name as oid_database_name,
7177          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7178          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7179        FROM mz_internal.pg_type_all_databases
7180        UNION ALL
7181        SELECT oid, database_name as oid_database_name,
7182          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7183          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7184        FROM mz_internal.pg_namespace_all_databases
7185    ),
7186
7187    -- Gather all of the MZ ids for objects that can have comments.
7188    mz_objects AS (
7189        SELECT id, oid, type FROM mz_catalog.mz_objects
7190        UNION ALL
7191        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7192    )
7193    SELECT
7194        pg_classoids.oid AS objoid,
7195        pg_classoids.classoid as classoid,
7196        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7197        cmt.comment AS description,
7198        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7199        oid_database_name,
7200        class_database_name
7201    FROM
7202        pg_classoids
7203    JOIN
7204        mz_objects ON pg_classoids.oid = mz_objects.oid
7205    JOIN
7206        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7207)",
7208        access: vec![PUBLIC_SELECT],
7209    }
7210});
7211
7212pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7213    name: "pg_description_all_databases_ind",
7214    schema: MZ_INTERNAL_SCHEMA,
7215    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7216    sql: "IN CLUSTER mz_catalog_server
7217ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7218    is_retained_metrics_object: false,
7219};
7220
7221/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7222/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7223/// which is required for this view.
7224pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7225    name: "pg_description",
7226    schema: PG_CATALOG_SCHEMA,
7227    oid: oid::VIEW_PG_DESCRIPTION_OID,
7228    desc: RelationDesc::builder()
7229        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7230        .with_column("classoid", SqlScalarType::Oid.nullable(true))
7231        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7232        .with_column("description", SqlScalarType::String.nullable(false))
7233        .finish(),
7234    column_comments: BTreeMap::new(),
7235    sql: "
7236SELECT
7237    objoid,
7238    classoid,
7239    objsubid,
7240    description
7241FROM
7242    mz_internal.pg_description_all_databases
7243WHERE
7244    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7245    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7246    access: vec![PUBLIC_SELECT],
7247});
7248
7249/// Peeled version of `PG_TYPE`:
7250/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7251///   in order to make this view indexable.
7252/// - This has the database name as an extra column, so that downstream views can check it against
7253///  `current_database()`.
7254pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7255    BuiltinView {
7256        name: "pg_type_all_databases",
7257        schema: MZ_INTERNAL_SCHEMA,
7258        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7259        desc: RelationDesc::builder()
7260            .with_column("oid", SqlScalarType::Oid.nullable(false))
7261            .with_column("typname", SqlScalarType::String.nullable(false))
7262            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7263            .with_column("typowner", SqlScalarType::Oid.nullable(false))
7264            .with_column("typlen", SqlScalarType::Int16.nullable(true))
7265            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7266            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7267            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7268            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7269            .with_column("typelem", SqlScalarType::Oid.nullable(false))
7270            .with_column("typarray", SqlScalarType::Oid.nullable(false))
7271            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7272            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7273            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7274            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7275            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7276            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7277            .with_column("typdefault", SqlScalarType::String.nullable(true))
7278            .with_column("database_name", SqlScalarType::String.nullable(true))
7279            .finish(),
7280        column_comments: BTreeMap::new(),
7281        sql: "
7282SELECT
7283    mz_types.oid,
7284    mz_types.name AS typname,
7285    mz_schemas.oid AS typnamespace,
7286    role_owner.oid AS typowner,
7287    NULL::pg_catalog.int2 AS typlen,
7288    -- 'a' is used internally to denote an array type, but in postgres they show up
7289    -- as 'b'.
7290    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7291    (CASE category
7292        WHEN 'array' THEN 'A'
7293        WHEN 'bit-string' THEN 'V'
7294        WHEN 'boolean' THEN 'B'
7295        WHEN 'composite' THEN 'C'
7296        WHEN 'date-time' THEN 'D'
7297        WHEN 'enum' THEN 'E'
7298        WHEN 'geometric' THEN 'G'
7299        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7300        WHEN 'network-address' THEN 'I'
7301        WHEN 'numeric' THEN 'N'
7302        WHEN 'pseudo' THEN 'P'
7303        WHEN 'string' THEN 'S'
7304        WHEN 'timespan' THEN 'T'
7305        WHEN 'user-defined' THEN 'U'
7306        WHEN 'unknown' THEN 'X'
7307    END)::pg_catalog.char AS typcategory,
7308    -- In pg only the 'box' type is not ','.
7309    ','::pg_catalog.char AS typdelim,
7310    0::pg_catalog.oid AS typrelid,
7311    coalesce(
7312        (
7313            SELECT t.oid
7314            FROM mz_catalog.mz_array_types a
7315            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7316            WHERE a.id = mz_types.id
7317        ),
7318        (
7319            SELECT t.oid
7320            FROM mz_catalog.mz_list_types l
7321            JOIN mz_catalog.mz_types t ON l.element_id = t.id
7322            WHERE l.id = mz_types.id
7323        ),
7324        0
7325    ) AS typelem,
7326    coalesce(
7327        (
7328            SELECT
7329                t.oid
7330            FROM
7331                mz_catalog.mz_array_types AS a
7332                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7333            WHERE
7334                a.element_id = mz_types.id
7335        ),
7336        0
7337    )
7338        AS typarray,
7339    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7340    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7341    false::pg_catalog.bool AS typnotnull,
7342    0::pg_catalog.oid AS typbasetype,
7343    -1::pg_catalog.int4 AS typtypmod,
7344    -- MZ doesn't support COLLATE so typcollation is filled with 0
7345    0::pg_catalog.oid AS typcollation,
7346    NULL::pg_catalog.text AS typdefault,
7347    d.name as database_name
7348FROM
7349    mz_catalog.mz_types
7350    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7351    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7352    JOIN (
7353            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7354            -- converted to the correct value above.
7355            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7356            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7357            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7358            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7359            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7360        )
7361            AS t ON mz_types.id = t.id
7362    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7363    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7364        access: vec![PUBLIC_SELECT],
7365    }
7366});
7367
7368pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7369    name: "pg_type_all_databases_ind",
7370    schema: MZ_INTERNAL_SCHEMA,
7371    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7372    sql: "IN CLUSTER mz_catalog_server
7373ON mz_internal.pg_type_all_databases (oid)",
7374    is_retained_metrics_object: false,
7375};
7376
7377pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7378    name: "pg_type",
7379    schema: PG_CATALOG_SCHEMA,
7380    oid: oid::VIEW_PG_TYPE_OID,
7381    desc: RelationDesc::builder()
7382        .with_column("oid", SqlScalarType::Oid.nullable(false))
7383        .with_column("typname", SqlScalarType::String.nullable(false))
7384        .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7385        .with_column("typowner", SqlScalarType::Oid.nullable(false))
7386        .with_column("typlen", SqlScalarType::Int16.nullable(true))
7387        .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7388        .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7389        .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7390        .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7391        .with_column("typelem", SqlScalarType::Oid.nullable(false))
7392        .with_column("typarray", SqlScalarType::Oid.nullable(false))
7393        .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7394        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7395        .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7396        .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7397        .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7398        .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7399        .with_column("typdefault", SqlScalarType::String.nullable(true))
7400        .finish(),
7401    column_comments: BTreeMap::new(),
7402    sql: "SELECT
7403    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7404    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7405FROM mz_internal.pg_type_all_databases
7406WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7407    access: vec![PUBLIC_SELECT],
7408});
7409
7410/// Peeled version of `PG_ATTRIBUTE`:
7411/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7412///   in order to make this view indexable.
7413/// - This has 2 extra columns for the database names, so that downstream views can check them
7414///   against `current_database()`.
7415pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7416    BuiltinView {
7417        name: "pg_attribute_all_databases",
7418        schema: MZ_INTERNAL_SCHEMA,
7419        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7420        desc: RelationDesc::builder()
7421            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7422            .with_column("attname", SqlScalarType::String.nullable(false))
7423            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7424            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7425            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7426            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7427            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7428            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7429            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7430            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7431            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7432            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7433            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7434            .with_column("database_name", SqlScalarType::String.nullable(true))
7435            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
7436            .finish(),
7437        column_comments: BTreeMap::new(),
7438        sql: "
7439SELECT
7440    class_objects.oid as attrelid,
7441    mz_columns.name as attname,
7442    mz_columns.type_oid AS atttypid,
7443    pg_type_all_databases.typlen AS attlen,
7444    position::int8::int2 as attnum,
7445    mz_columns.type_mod as atttypmod,
7446    -- dummy value, just to make go-jet's workaround work for now. Discussion:
7447    -- https://github.com/MaterializeInc/materialize/pull/34649#issuecomment-3714291409
7448    0::int2 as attndims,
7449    NOT nullable as attnotnull,
7450    mz_columns.default IS NOT NULL as atthasdef,
7451    ''::pg_catalog.\"char\" as attidentity,
7452    -- MZ doesn't support generated columns so attgenerated is filled with ''
7453    ''::pg_catalog.\"char\" as attgenerated,
7454    FALSE as attisdropped,
7455    -- MZ doesn't support COLLATE so attcollation is filled with 0
7456    0::pg_catalog.oid as attcollation,
7457    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7458    d.name as database_name,
7459    pg_type_all_databases.database_name as pg_type_database_name
7460FROM (
7461    -- pg_attribute catalogs columns on relations and indexes
7462    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7463    UNION ALL
7464        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7465        FROM mz_catalog.mz_indexes
7466        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7467) AS class_objects
7468JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7469JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7470JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7471LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7472        // Since this depends on pg_type, its id must be higher due to initialization
7473        // ordering.
7474        access: vec![PUBLIC_SELECT],
7475    }
7476});
7477
7478pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7479    name: "pg_attribute_all_databases_ind",
7480    schema: MZ_INTERNAL_SCHEMA,
7481    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7482    sql: "IN CLUSTER mz_catalog_server
7483ON mz_internal.pg_attribute_all_databases (
7484    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7485    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7486)",
7487    is_retained_metrics_object: false,
7488};
7489
7490/// <https://www.postgresql.org/docs/current/catalog-pg-attribute.html>
7491pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7492    BuiltinView {
7493        name: "pg_attribute",
7494        schema: PG_CATALOG_SCHEMA,
7495        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7496        desc: RelationDesc::builder()
7497            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7498            .with_column("attname", SqlScalarType::String.nullable(false))
7499            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7500            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7501            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7502            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7503            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7504            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7505            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7506            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7507            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7508            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7509            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7510            .finish(),
7511        column_comments: BTreeMap::new(),
7512        sql: "
7513SELECT
7514    attrelid, attname, atttypid, attlen, attnum, atttypmod, attndims, attnotnull, atthasdef,
7515    attidentity, attgenerated, attisdropped, attcollation
7516FROM mz_internal.pg_attribute_all_databases
7517WHERE
7518  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7519  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7520        // Since this depends on pg_type, its id must be higher due to initialization
7521        // ordering.
7522        access: vec![PUBLIC_SELECT],
7523    }
7524});
7525
7526pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7527    name: "pg_proc",
7528    schema: PG_CATALOG_SCHEMA,
7529    oid: oid::VIEW_PG_PROC_OID,
7530    desc: RelationDesc::builder()
7531        .with_column("oid", SqlScalarType::Oid.nullable(false))
7532        .with_column("proname", SqlScalarType::String.nullable(false))
7533        .with_column("pronamespace", SqlScalarType::Oid.nullable(false))
7534        .with_column("proowner", SqlScalarType::Oid.nullable(false))
7535        .with_column("proargdefaults", SqlScalarType::String.nullable(true))
7536        .with_column("prorettype", SqlScalarType::Oid.nullable(false))
7537        .finish(),
7538    column_comments: BTreeMap::new(),
7539    sql: "SELECT
7540    mz_functions.oid,
7541    mz_functions.name AS proname,
7542    mz_schemas.oid AS pronamespace,
7543    role_owner.oid AS proowner,
7544    NULL::pg_catalog.text AS proargdefaults,
7545    ret_type.oid AS prorettype
7546FROM mz_catalog.mz_functions
7547JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7548LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7549JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7550JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7551WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7552    access: vec![PUBLIC_SELECT],
7553});
7554
7555pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7556    name: "pg_operator",
7557    schema: PG_CATALOG_SCHEMA,
7558    oid: oid::VIEW_PG_OPERATOR_OID,
7559    desc: RelationDesc::builder()
7560        .with_column("oid", SqlScalarType::Oid.nullable(false))
7561        .with_column("oprname", SqlScalarType::String.nullable(false))
7562        .with_column("oprresult", SqlScalarType::Oid.nullable(false))
7563        .with_column("oprleft", SqlScalarType::Oid.nullable(false))
7564        .with_column("oprright", SqlScalarType::Oid.nullable(false))
7565        .with_key(vec![0, 1, 2, 3, 4])
7566        .finish(),
7567    column_comments: BTreeMap::new(),
7568    sql: "SELECT
7569    mz_operators.oid,
7570    mz_operators.name AS oprname,
7571    ret_type.oid AS oprresult,
7572    left_type.oid as oprleft,
7573    right_type.oid as oprright
7574FROM mz_catalog.mz_operators
7575JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7576JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7577JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7578WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7579UNION SELECT
7580    mz_operators.oid,
7581    mz_operators.name AS oprname,
7582    ret_type.oid AS oprresult,
7583    0 as oprleft,
7584    right_type.oid as oprright
7585FROM mz_catalog.mz_operators
7586JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7587JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7588WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7589    access: vec![PUBLIC_SELECT],
7590});
7591
7592pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7593    name: "pg_range",
7594    schema: PG_CATALOG_SCHEMA,
7595    oid: oid::VIEW_PG_RANGE_OID,
7596    desc: RelationDesc::builder()
7597        .with_column("rngtypid", SqlScalarType::Oid.nullable(false))
7598        .with_column("rngsubtype", SqlScalarType::Oid.nullable(false))
7599        .with_key(vec![])
7600        .finish(),
7601    column_comments: BTreeMap::new(),
7602    sql: "SELECT
7603    NULL::pg_catalog.oid AS rngtypid,
7604    NULL::pg_catalog.oid AS rngsubtype
7605WHERE false",
7606    access: vec![PUBLIC_SELECT],
7607});
7608
7609pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7610    name: "pg_enum",
7611    schema: PG_CATALOG_SCHEMA,
7612    oid: oid::VIEW_PG_ENUM_OID,
7613    desc: RelationDesc::builder()
7614        .with_column("oid", SqlScalarType::Oid.nullable(false))
7615        .with_column("enumtypid", SqlScalarType::Oid.nullable(false))
7616        .with_column("enumsortorder", SqlScalarType::Float32.nullable(false))
7617        .with_column("enumlabel", SqlScalarType::String.nullable(false))
7618        .with_key(vec![])
7619        .finish(),
7620    column_comments: BTreeMap::new(),
7621    sql: "SELECT
7622    NULL::pg_catalog.oid AS oid,
7623    NULL::pg_catalog.oid AS enumtypid,
7624    NULL::pg_catalog.float4 AS enumsortorder,
7625    NULL::pg_catalog.text AS enumlabel
7626WHERE false",
7627    access: vec![PUBLIC_SELECT],
7628});
7629
7630/// Peeled version of `PG_ATTRDEF`:
7631/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7632///   in order to make this view indexable.
7633pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7634    name: "pg_attrdef_all_databases",
7635    schema: MZ_INTERNAL_SCHEMA,
7636    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
7637    desc: RelationDesc::builder()
7638        .with_column("oid", SqlScalarType::Oid.nullable(true))
7639        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7640        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7641        .with_column("adbin", SqlScalarType::String.nullable(false))
7642        .with_column("adsrc", SqlScalarType::String.nullable(false))
7643        .finish(),
7644    column_comments: BTreeMap::new(),
7645    sql: "
7646SELECT
7647    NULL::pg_catalog.oid AS oid,
7648    mz_objects.oid AS adrelid,
7649    mz_columns.position::int8 AS adnum,
7650    mz_columns.default AS adbin,
7651    mz_columns.default AS adsrc
7652FROM mz_catalog.mz_columns
7653    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
7654WHERE default IS NOT NULL",
7655    access: vec![PUBLIC_SELECT],
7656});
7657
7658pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7659    name: "pg_attrdef_all_databases_ind",
7660    schema: MZ_INTERNAL_SCHEMA,
7661    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
7662    sql: "IN CLUSTER mz_catalog_server
7663ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
7664    is_retained_metrics_object: false,
7665};
7666
7667pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7668    name: "pg_attrdef",
7669    schema: PG_CATALOG_SCHEMA,
7670    oid: oid::VIEW_PG_ATTRDEF_OID,
7671    desc: RelationDesc::builder()
7672        .with_column("oid", SqlScalarType::Oid.nullable(true))
7673        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7674        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7675        .with_column("adbin", SqlScalarType::String.nullable(false))
7676        .with_column("adsrc", SqlScalarType::String.nullable(false))
7677        .finish(),
7678    column_comments: BTreeMap::new(),
7679    sql: "
7680SELECT
7681    pg_attrdef_all_databases.oid as oid,
7682    adrelid,
7683    adnum,
7684    adbin,
7685    adsrc
7686FROM mz_internal.pg_attrdef_all_databases
7687    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
7688    access: vec![PUBLIC_SELECT],
7689});
7690
7691pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7692    name: "pg_settings",
7693    schema: PG_CATALOG_SCHEMA,
7694    oid: oid::VIEW_PG_SETTINGS_OID,
7695    desc: RelationDesc::builder()
7696        .with_column("name", SqlScalarType::String.nullable(false))
7697        .with_column("setting", SqlScalarType::String.nullable(false))
7698        .with_key(vec![])
7699        .finish(),
7700    column_comments: BTreeMap::new(),
7701    sql: "SELECT
7702    name, setting
7703FROM (VALUES
7704    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
7705) AS _ (name, setting)",
7706    access: vec![PUBLIC_SELECT],
7707});
7708
7709pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7710    name: "pg_auth_members",
7711    schema: PG_CATALOG_SCHEMA,
7712    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
7713    desc: RelationDesc::builder()
7714        .with_column("roleid", SqlScalarType::Oid.nullable(false))
7715        .with_column("member", SqlScalarType::Oid.nullable(false))
7716        .with_column("grantor", SqlScalarType::Oid.nullable(false))
7717        .with_column("admin_option", SqlScalarType::Bool.nullable(false))
7718        .finish(),
7719    column_comments: BTreeMap::new(),
7720    sql: "SELECT
7721    role.oid AS roleid,
7722    member.oid AS member,
7723    grantor.oid AS grantor,
7724    -- Materialize hasn't implemented admin_option.
7725    false as admin_option
7726FROM mz_catalog.mz_role_members membership
7727JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
7728JOIN mz_catalog.mz_roles member ON membership.member = member.id
7729JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
7730    access: vec![PUBLIC_SELECT],
7731});
7732
7733pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7734    name: "pg_event_trigger",
7735    schema: PG_CATALOG_SCHEMA,
7736    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
7737    desc: RelationDesc::builder()
7738        .with_column("oid", SqlScalarType::Oid.nullable(false))
7739        .with_column("evtname", SqlScalarType::String.nullable(false))
7740        .with_column("evtevent", SqlScalarType::String.nullable(false))
7741        .with_column("evtowner", SqlScalarType::Oid.nullable(false))
7742        .with_column("evtfoid", SqlScalarType::Oid.nullable(false))
7743        .with_column("evtenabled", SqlScalarType::PgLegacyChar.nullable(false))
7744        .with_column(
7745            "evttags",
7746            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7747        )
7748        .with_key(vec![])
7749        .finish(),
7750    column_comments: BTreeMap::new(),
7751    sql: "SELECT
7752        NULL::pg_catalog.oid AS oid,
7753        NULL::pg_catalog.text AS evtname,
7754        NULL::pg_catalog.text AS evtevent,
7755        NULL::pg_catalog.oid AS evtowner,
7756        NULL::pg_catalog.oid AS evtfoid,
7757        NULL::pg_catalog.char AS evtenabled,
7758        NULL::pg_catalog.text[] AS evttags
7759    WHERE false",
7760    access: vec![PUBLIC_SELECT],
7761});
7762
7763pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7764    name: "pg_language",
7765    schema: PG_CATALOG_SCHEMA,
7766    oid: oid::VIEW_PG_LANGUAGE_OID,
7767    desc: RelationDesc::builder()
7768        .with_column("oid", SqlScalarType::Oid.nullable(false))
7769        .with_column("lanname", SqlScalarType::String.nullable(false))
7770        .with_column("lanowner", SqlScalarType::Oid.nullable(false))
7771        .with_column("lanispl", SqlScalarType::Bool.nullable(false))
7772        .with_column("lanpltrusted", SqlScalarType::Bool.nullable(false))
7773        .with_column("lanplcallfoid", SqlScalarType::Oid.nullable(false))
7774        .with_column("laninline", SqlScalarType::Oid.nullable(false))
7775        .with_column("lanvalidator", SqlScalarType::Oid.nullable(false))
7776        .with_column(
7777            "lanacl",
7778            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7779        )
7780        .with_key(vec![])
7781        .finish(),
7782    column_comments: BTreeMap::new(),
7783    sql: "SELECT
7784        NULL::pg_catalog.oid  AS oid,
7785        NULL::pg_catalog.text AS lanname,
7786        NULL::pg_catalog.oid  AS lanowner,
7787        NULL::pg_catalog.bool AS lanispl,
7788        NULL::pg_catalog.bool AS lanpltrusted,
7789        NULL::pg_catalog.oid  AS lanplcallfoid,
7790        NULL::pg_catalog.oid  AS laninline,
7791        NULL::pg_catalog.oid  AS lanvalidator,
7792        NULL::pg_catalog.text[] AS lanacl
7793    WHERE false",
7794    access: vec![PUBLIC_SELECT],
7795});
7796
7797pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7798    name: "pg_shdescription",
7799    schema: PG_CATALOG_SCHEMA,
7800    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
7801    desc: RelationDesc::builder()
7802        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7803        .with_column("classoid", SqlScalarType::Oid.nullable(false))
7804        .with_column("description", SqlScalarType::String.nullable(false))
7805        .with_key(vec![])
7806        .finish(),
7807    column_comments: BTreeMap::new(),
7808    sql: "SELECT
7809        NULL::pg_catalog.oid AS objoid,
7810        NULL::pg_catalog.oid AS classoid,
7811        NULL::pg_catalog.text AS description
7812    WHERE false",
7813    access: vec![PUBLIC_SELECT],
7814});
7815
7816pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
7817    BuiltinView {
7818        name: "pg_timezone_abbrevs",
7819        schema: PG_CATALOG_SCHEMA,
7820        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
7821        desc: RelationDesc::builder()
7822            .with_column("abbrev", SqlScalarType::String.nullable(false))
7823            .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7824            .with_column("is_dst", SqlScalarType::Bool.nullable(true))
7825            .with_key(vec![0])
7826            .finish(),
7827        column_comments: BTreeMap::new(),
7828        sql: "SELECT
7829    abbreviation AS abbrev,
7830    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
7831        AS utc_offset,
7832    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
7833        AS is_dst
7834FROM mz_catalog.mz_timezone_abbreviations",
7835        access: vec![PUBLIC_SELECT],
7836    }
7837});
7838
7839pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7840    name: "pg_timezone_names",
7841    schema: PG_CATALOG_SCHEMA,
7842    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
7843    desc: RelationDesc::builder()
7844        .with_column("name", SqlScalarType::String.nullable(false))
7845        .with_column("abbrev", SqlScalarType::String.nullable(true))
7846        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7847        .with_column("is_dst", SqlScalarType::Bool.nullable(true))
7848        .with_key(vec![0])
7849        .finish(),
7850    column_comments: BTreeMap::new(),
7851    sql: "SELECT
7852    name,
7853    timezone_offset(name, now()).abbrev AS abbrev,
7854    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
7855        AS utc_offset,
7856    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
7857        AS is_dst
7858FROM mz_catalog.mz_timezone_names",
7859    access: vec![PUBLIC_SELECT],
7860});
7861
7862pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7863    name: "mz_timezone_abbreviations",
7864    schema: MZ_CATALOG_SCHEMA,
7865    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
7866    desc: RelationDesc::builder()
7867        .with_column("abbreviation", SqlScalarType::String.nullable(false))
7868        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7869        .with_column("dst", SqlScalarType::Bool.nullable(true))
7870        .with_column("timezone_name", SqlScalarType::String.nullable(true))
7871        .with_key(vec![0])
7872        .finish(),
7873    column_comments: BTreeMap::from_iter([
7874        ("abbreviation", "The timezone abbreviation."),
7875        (
7876            "utc_offset",
7877            "The UTC offset of the timezone or `NULL` if fixed.",
7878        ),
7879        (
7880            "dst",
7881            "Whether the timezone is in daylight savings or `NULL` if fixed.",
7882        ),
7883        (
7884            "timezone_name",
7885            "The full name of the non-fixed timezone or `NULL` if not fixed.",
7886        ),
7887    ]),
7888    sql: format!(
7889        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
7890        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
7891    )
7892    .leak(),
7893    access: vec![PUBLIC_SELECT],
7894});
7895
7896pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7897    name: "mz_timezone_names",
7898    schema: MZ_CATALOG_SCHEMA,
7899    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
7900    desc: RelationDesc::builder()
7901        .with_column("name", SqlScalarType::String.nullable(false))
7902        .with_key(vec![0])
7903        .finish(),
7904    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
7905    sql: format!(
7906        "SELECT * FROM ({}) _ (name)",
7907        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
7908    )
7909    .leak(),
7910    access: vec![PUBLIC_SELECT],
7911});
7912
7913pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7914    LazyLock::new(|| BuiltinView {
7915        name: "mz_peek_durations_histogram_per_worker",
7916        schema: MZ_INTROSPECTION_SCHEMA,
7917        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
7918        desc: RelationDesc::builder()
7919            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7920            .with_column("type", SqlScalarType::String.nullable(false))
7921            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7922            .with_column("count", SqlScalarType::Int64.nullable(false))
7923            .with_key(vec![0, 1, 2])
7924            .finish(),
7925        column_comments: BTreeMap::new(),
7926        sql: "SELECT
7927    worker_id, type, duration_ns, pg_catalog.count(*) AS count
7928FROM
7929    mz_introspection.mz_peek_durations_histogram_raw
7930GROUP BY
7931    worker_id, type, duration_ns",
7932        access: vec![PUBLIC_SELECT],
7933    });
7934
7935pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7936    name: "mz_peek_durations_histogram",
7937    schema: MZ_INTROSPECTION_SCHEMA,
7938    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
7939    desc: RelationDesc::builder()
7940        .with_column("type", SqlScalarType::String.nullable(false))
7941        .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7942        .with_column(
7943            "count",
7944            SqlScalarType::Numeric {
7945                max_scale: Some(NumericMaxScale::ZERO),
7946            }
7947            .nullable(false),
7948        )
7949        .with_key(vec![0, 1])
7950        .finish(),
7951    column_comments: BTreeMap::from_iter([
7952        ("type", "The peek variant: `index` or `persist`."),
7953        (
7954            "duration_ns",
7955            "The upper bound of the bucket in nanoseconds.",
7956        ),
7957        (
7958            "count",
7959            "The (noncumulative) count of peeks in this bucket.",
7960        ),
7961    ]),
7962    sql: "
7963SELECT
7964    type, duration_ns,
7965    pg_catalog.sum(count) AS count
7966FROM mz_introspection.mz_peek_durations_histogram_per_worker
7967GROUP BY type, duration_ns",
7968    access: vec![PUBLIC_SELECT],
7969});
7970
7971pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
7972    LazyLock::new(|| BuiltinView {
7973        name: "mz_scheduling_elapsed_per_worker",
7974        schema: MZ_INTROSPECTION_SCHEMA,
7975        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
7976        desc: RelationDesc::builder()
7977            .with_column("id", SqlScalarType::UInt64.nullable(false))
7978            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7979            .with_column("elapsed_ns", SqlScalarType::Int64.nullable(false))
7980            .with_key(vec![0, 1])
7981            .finish(),
7982        column_comments: BTreeMap::new(),
7983        sql: "SELECT
7984    id, worker_id, pg_catalog.count(*) AS elapsed_ns
7985FROM
7986    mz_introspection.mz_scheduling_elapsed_raw
7987GROUP BY
7988    id, worker_id",
7989        access: vec![PUBLIC_SELECT],
7990    });
7991
7992pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7993    name: "mz_scheduling_elapsed",
7994    schema: MZ_INTROSPECTION_SCHEMA,
7995    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
7996    desc: RelationDesc::builder()
7997        .with_column("id", SqlScalarType::UInt64.nullable(false))
7998        .with_column(
7999            "elapsed_ns",
8000            SqlScalarType::Numeric {
8001                max_scale: Some(NumericMaxScale::ZERO),
8002            }
8003            .nullable(false),
8004        )
8005        .with_key(vec![0])
8006        .finish(),
8007    column_comments: BTreeMap::from_iter([
8008        (
8009            "id",
8010            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8011        ),
8012        (
8013            "elapsed_ns",
8014            "The total elapsed time spent in the operator in nanoseconds.",
8015        ),
8016    ]),
8017    sql: "
8018SELECT
8019    id,
8020    pg_catalog.sum(elapsed_ns) AS elapsed_ns
8021FROM mz_introspection.mz_scheduling_elapsed_per_worker
8022GROUP BY id",
8023    access: vec![PUBLIC_SELECT],
8024});
8025
8026pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8027    LazyLock::new(|| BuiltinView {
8028        name: "mz_compute_operator_durations_histogram_per_worker",
8029        schema: MZ_INTROSPECTION_SCHEMA,
8030        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8031        desc: RelationDesc::builder()
8032            .with_column("id", SqlScalarType::UInt64.nullable(false))
8033            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8034            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8035            .with_column("count", SqlScalarType::Int64.nullable(false))
8036            .with_key(vec![0, 1, 2])
8037            .finish(),
8038        column_comments: BTreeMap::new(),
8039        sql: "SELECT
8040    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8041FROM
8042    mz_introspection.mz_compute_operator_durations_histogram_raw
8043GROUP BY
8044    id, worker_id, duration_ns",
8045        access: vec![PUBLIC_SELECT],
8046    });
8047
8048pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8049    LazyLock::new(|| BuiltinView {
8050        name: "mz_compute_operator_durations_histogram",
8051        schema: MZ_INTROSPECTION_SCHEMA,
8052        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8053        desc: RelationDesc::builder()
8054            .with_column("id", SqlScalarType::UInt64.nullable(false))
8055            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8056            .with_column(
8057                "count",
8058                SqlScalarType::Numeric {
8059                    max_scale: Some(NumericMaxScale::ZERO),
8060                }
8061                .nullable(false),
8062            )
8063            .with_key(vec![0, 1])
8064            .finish(),
8065        column_comments: BTreeMap::from_iter([
8066            (
8067                "id",
8068                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8069            ),
8070            (
8071                "duration_ns",
8072                "The upper bound of the duration bucket in nanoseconds.",
8073            ),
8074            (
8075                "count",
8076                "The (noncumulative) count of invocations in the bucket.",
8077            ),
8078        ]),
8079        sql: "
8080SELECT
8081    id,
8082    duration_ns,
8083    pg_catalog.sum(count) AS count
8084FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8085GROUP BY id, duration_ns",
8086        access: vec![PUBLIC_SELECT],
8087    });
8088
8089pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8090    LazyLock::new(|| BuiltinView {
8091        name: "mz_scheduling_parks_histogram_per_worker",
8092        schema: MZ_INTROSPECTION_SCHEMA,
8093        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8094        desc: RelationDesc::builder()
8095            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8096            .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8097            .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8098            .with_column("count", SqlScalarType::Int64.nullable(false))
8099            .with_key(vec![0, 1, 2])
8100            .finish(),
8101        column_comments: BTreeMap::new(),
8102        sql: "SELECT
8103    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8104FROM
8105    mz_introspection.mz_scheduling_parks_histogram_raw
8106GROUP BY
8107    worker_id, slept_for_ns, requested_ns",
8108        access: vec![PUBLIC_SELECT],
8109    });
8110
8111pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8112    name: "mz_scheduling_parks_histogram",
8113    schema: MZ_INTROSPECTION_SCHEMA,
8114    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8115    desc: RelationDesc::builder()
8116        .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8117        .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8118        .with_column(
8119            "count",
8120            SqlScalarType::Numeric {
8121                max_scale: Some(NumericMaxScale::ZERO),
8122            }
8123            .nullable(false),
8124        )
8125        .with_key(vec![0, 1])
8126        .finish(),
8127    column_comments: BTreeMap::from_iter([
8128        (
8129            "slept_for_ns",
8130            "The actual length of the park event in nanoseconds.",
8131        ),
8132        (
8133            "requested_ns",
8134            "The requested length of the park event in nanoseconds.",
8135        ),
8136        (
8137            "count",
8138            "The (noncumulative) count of park events in this bucket.",
8139        ),
8140    ]),
8141    sql: "
8142SELECT
8143    slept_for_ns,
8144    requested_ns,
8145    pg_catalog.sum(count) AS count
8146FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8147GROUP BY slept_for_ns, requested_ns",
8148    access: vec![PUBLIC_SELECT],
8149});
8150
8151pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8152    LazyLock::new(|| BuiltinView {
8153        name: "mz_compute_error_counts_per_worker",
8154        schema: MZ_INTROSPECTION_SCHEMA,
8155        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8156        desc: RelationDesc::builder()
8157            .with_column("export_id", SqlScalarType::String.nullable(false))
8158            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8159            .with_column("count", SqlScalarType::Int64.nullable(false))
8160            .with_key(vec![0, 1, 2])
8161            .finish(),
8162        column_comments: BTreeMap::new(),
8163        sql: "
8164WITH MUTUALLY RECURSIVE
8165    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8166    -- For these we don't log error counts separately, so we need to forward the error counts from
8167    -- their dependencies instead.
8168    index_reuses(reuse_id text, index_id text) AS (
8169        SELECT d.object_id, d.dependency_id
8170        FROM mz_internal.mz_compute_dependencies d
8171        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8172        WHERE NOT EXISTS (
8173            SELECT 1 FROM mz_introspection.mz_dataflows
8174            WHERE id = e.dataflow_id
8175        )
8176    ),
8177    -- Error counts that were directly logged on compute exports.
8178    direct_errors(export_id text, worker_id uint8, count int8) AS (
8179        SELECT export_id, worker_id, count
8180        FROM mz_introspection.mz_compute_error_counts_raw
8181    ),
8182    -- Error counts propagated to index reused.
8183    all_errors(export_id text, worker_id uint8, count int8) AS (
8184        SELECT * FROM direct_errors
8185        UNION
8186        SELECT r.reuse_id, e.worker_id, e.count
8187        FROM all_errors e
8188        JOIN index_reuses r ON (r.index_id = e.export_id)
8189    )
8190SELECT * FROM all_errors",
8191        access: vec![PUBLIC_SELECT],
8192    });
8193
8194pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8195    name: "mz_compute_error_counts",
8196    schema: MZ_INTROSPECTION_SCHEMA,
8197    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8198    desc: RelationDesc::builder()
8199        .with_column("export_id", SqlScalarType::String.nullable(false))
8200        .with_column(
8201            "count",
8202            SqlScalarType::Numeric {
8203                max_scale: Some(NumericMaxScale::ZERO),
8204            }
8205            .nullable(false),
8206        )
8207        .with_key(vec![0])
8208        .finish(),
8209    column_comments: BTreeMap::from_iter([
8210        (
8211            "export_id",
8212            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8213        ),
8214        (
8215            "count",
8216            "The count of errors present in this dataflow export.",
8217        ),
8218    ]),
8219    sql: "
8220SELECT
8221    export_id,
8222    pg_catalog.sum(count) AS count
8223FROM mz_introspection.mz_compute_error_counts_per_worker
8224GROUP BY export_id
8225HAVING pg_catalog.sum(count) != 0",
8226    access: vec![PUBLIC_SELECT],
8227});
8228
8229pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8230    LazyLock::new(|| BuiltinSource {
8231        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8232        // naming conflict because the resolver stumbles over the source with the same name in
8233        // `mz_introspection` due to the automatic schema translation.
8234        name: "mz_compute_error_counts_raw_unified",
8235        schema: MZ_INTERNAL_SCHEMA,
8236        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8237        desc: RelationDesc::builder()
8238            .with_column("replica_id", SqlScalarType::String.nullable(false))
8239            .with_column("object_id", SqlScalarType::String.nullable(false))
8240            .with_column(
8241                "count",
8242                SqlScalarType::Numeric { max_scale: None }.nullable(false),
8243            )
8244            .finish(),
8245        data_source: IntrospectionType::ComputeErrorCounts,
8246        column_comments: BTreeMap::new(),
8247        is_retained_metrics_object: false,
8248        access: vec![PUBLIC_SELECT],
8249    });
8250
8251pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8252    name: "mz_compute_hydration_times",
8253    schema: MZ_INTERNAL_SCHEMA,
8254    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8255    desc: RelationDesc::builder()
8256        .with_column("replica_id", SqlScalarType::String.nullable(false))
8257        .with_column("object_id", SqlScalarType::String.nullable(false))
8258        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
8259        .finish(),
8260    data_source: IntrospectionType::ComputeHydrationTimes,
8261    column_comments: BTreeMap::new(),
8262    is_retained_metrics_object: true,
8263    access: vec![PUBLIC_SELECT],
8264});
8265
8266pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8267    LazyLock::new(|| BuiltinIndex {
8268        name: "mz_compute_hydration_times_ind",
8269        schema: MZ_INTERNAL_SCHEMA,
8270        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8271        sql: "IN CLUSTER mz_catalog_server
8272    ON mz_internal.mz_compute_hydration_times (replica_id)",
8273        is_retained_metrics_object: true,
8274    });
8275
8276pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8277    name: "mz_compute_hydration_statuses",
8278    schema: MZ_INTERNAL_SCHEMA,
8279    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8280    desc: RelationDesc::builder()
8281        .with_column("object_id", SqlScalarType::String.nullable(false))
8282        .with_column("replica_id", SqlScalarType::String.nullable(false))
8283        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8284        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
8285        .finish(),
8286    column_comments: BTreeMap::from_iter([
8287        (
8288            "object_id",
8289            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8290        ),
8291        ("replica_id", "The ID of a cluster replica."),
8292        (
8293            "hydrated",
8294            "Whether the compute object is hydrated on the replica.",
8295        ),
8296        (
8297            "hydration_time",
8298            "The amount of time it took for the replica to hydrate the compute object.",
8299        ),
8300    ]),
8301    sql: "
8302WITH
8303    dataflows AS (
8304        SELECT
8305            object_id,
8306            replica_id,
8307            time_ns IS NOT NULL AS hydrated,
8308            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8309        FROM mz_internal.mz_compute_hydration_times
8310    ),
8311    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8312    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8313    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8314    -- blue-green readiness query does), so we include them as 'hydrated'.
8315    complete_mvs AS (
8316        SELECT
8317            mv.id,
8318            f.replica_id,
8319            true AS hydrated,
8320            NULL::interval AS hydration_time
8321        FROM mz_materialized_views mv
8322        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8323        WHERE f.write_frontier IS NULL
8324    ),
8325    -- Ditto CTs
8326    complete_cts AS (
8327        SELECT
8328            ct.id,
8329            f.replica_id,
8330            true AS hydrated,
8331            NULL::interval AS hydration_time
8332        FROM mz_internal.mz_continual_tasks ct
8333        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = ct.id
8334        WHERE f.write_frontier IS NULL
8335    )
8336SELECT * FROM dataflows
8337UNION ALL
8338SELECT * FROM complete_mvs
8339UNION ALL
8340SELECT * FROM complete_cts",
8341    access: vec![PUBLIC_SELECT],
8342});
8343
8344pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
8345    BuiltinSource {
8346        name: "mz_compute_operator_hydration_statuses",
8347        schema: MZ_INTERNAL_SCHEMA,
8348        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8349        desc: RelationDesc::builder()
8350            .with_column("replica_id", SqlScalarType::String.nullable(false))
8351            .with_column("object_id", SqlScalarType::String.nullable(false))
8352            .with_column(
8353                "physical_plan_node_id",
8354                SqlScalarType::UInt64.nullable(false),
8355            )
8356            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8357            .with_key(vec![0, 1, 2])
8358            .finish(),
8359        data_source: IntrospectionType::ComputeOperatorHydrationStatus,
8360        column_comments: BTreeMap::from_iter([
8361            ("replica_id", "The ID of a cluster replica."),
8362            (
8363                "object_id",
8364                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8365            ),
8366            (
8367                "physical_plan_node_id",
8368                "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)`.",
8369            ),
8370            ("hydrated", "Whether the node is hydrated on the replica."),
8371        ]),
8372        is_retained_metrics_object: false,
8373        access: vec![PUBLIC_SELECT],
8374    }
8375});
8376
8377pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8378    name: "mz_message_counts_per_worker",
8379    schema: MZ_INTROSPECTION_SCHEMA,
8380    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8381    desc: RelationDesc::builder()
8382        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8383        .with_column("from_worker_id", SqlScalarType::UInt64.nullable(false))
8384        .with_column("to_worker_id", SqlScalarType::UInt64.nullable(false))
8385        .with_column("sent", SqlScalarType::Int64.nullable(false))
8386        .with_column("received", SqlScalarType::Int64.nullable(false))
8387        .with_column("batch_sent", SqlScalarType::Int64.nullable(false))
8388        .with_column("batch_received", SqlScalarType::Int64.nullable(false))
8389        .with_key(vec![0, 1, 2])
8390        .finish(),
8391    column_comments: BTreeMap::new(),
8392    sql: "
8393WITH batch_sent_cte AS (
8394    SELECT
8395        channel_id,
8396        from_worker_id,
8397        to_worker_id,
8398        pg_catalog.count(*) AS sent
8399    FROM
8400        mz_introspection.mz_message_batch_counts_sent_raw
8401    GROUP BY
8402        channel_id, from_worker_id, to_worker_id
8403),
8404batch_received_cte AS (
8405    SELECT
8406        channel_id,
8407        from_worker_id,
8408        to_worker_id,
8409        pg_catalog.count(*) AS received
8410    FROM
8411        mz_introspection.mz_message_batch_counts_received_raw
8412    GROUP BY
8413        channel_id, from_worker_id, to_worker_id
8414),
8415sent_cte AS (
8416    SELECT
8417        channel_id,
8418        from_worker_id,
8419        to_worker_id,
8420        pg_catalog.count(*) AS sent
8421    FROM
8422        mz_introspection.mz_message_counts_sent_raw
8423    GROUP BY
8424        channel_id, from_worker_id, to_worker_id
8425),
8426received_cte AS (
8427    SELECT
8428        channel_id,
8429        from_worker_id,
8430        to_worker_id,
8431        pg_catalog.count(*) AS received
8432    FROM
8433        mz_introspection.mz_message_counts_received_raw
8434    GROUP BY
8435        channel_id, from_worker_id, to_worker_id
8436)
8437SELECT
8438    sent_cte.channel_id,
8439    sent_cte.from_worker_id,
8440    sent_cte.to_worker_id,
8441    sent_cte.sent,
8442    received_cte.received,
8443    batch_sent_cte.sent AS batch_sent,
8444    batch_received_cte.received AS batch_received
8445FROM sent_cte
8446JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8447JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8448JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8449    access: vec![PUBLIC_SELECT],
8450});
8451
8452pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8453    name: "mz_message_counts",
8454    schema: MZ_INTROSPECTION_SCHEMA,
8455    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8456    desc: RelationDesc::builder()
8457        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8458        .with_column(
8459            "sent",
8460            SqlScalarType::Numeric {
8461                max_scale: Some(NumericMaxScale::ZERO),
8462            }
8463            .nullable(false),
8464        )
8465        .with_column(
8466            "received",
8467            SqlScalarType::Numeric {
8468                max_scale: Some(NumericMaxScale::ZERO),
8469            }
8470            .nullable(false),
8471        )
8472        .with_column(
8473            "batch_sent",
8474            SqlScalarType::Numeric {
8475                max_scale: Some(NumericMaxScale::ZERO),
8476            }
8477            .nullable(false),
8478        )
8479        .with_column(
8480            "batch_received",
8481            SqlScalarType::Numeric {
8482                max_scale: Some(NumericMaxScale::ZERO),
8483            }
8484            .nullable(false),
8485        )
8486        .with_key(vec![0])
8487        .finish(),
8488    column_comments: BTreeMap::from_iter([
8489        (
8490            "channel_id",
8491            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8492        ),
8493        ("sent", "The number of messages sent."),
8494        ("received", "The number of messages received."),
8495        ("batch_sent", "The number of batches sent."),
8496        ("batch_received", "The number of batches received."),
8497    ]),
8498    sql: "
8499SELECT
8500    channel_id,
8501    pg_catalog.sum(sent) AS sent,
8502    pg_catalog.sum(received) AS received,
8503    pg_catalog.sum(batch_sent) AS batch_sent,
8504    pg_catalog.sum(batch_received) AS batch_received
8505FROM mz_introspection.mz_message_counts_per_worker
8506GROUP BY channel_id",
8507    access: vec![PUBLIC_SELECT],
8508});
8509
8510pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8511    name: "mz_active_peeks",
8512    schema: MZ_INTROSPECTION_SCHEMA,
8513    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8514    desc: RelationDesc::builder()
8515        .with_column("id", SqlScalarType::Uuid.nullable(false))
8516        .with_column("object_id", SqlScalarType::String.nullable(false))
8517        .with_column("type", SqlScalarType::String.nullable(false))
8518        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
8519        .finish(),
8520    column_comments: BTreeMap::from_iter([
8521        ("id", "The ID of the peek request."),
8522        (
8523            "object_id",
8524            "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`.",
8525        ),
8526        (
8527            "type",
8528            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8529        ),
8530        ("time", "The timestamp the peek has requested."),
8531    ]),
8532    sql: "
8533SELECT id, object_id, type, time
8534FROM mz_introspection.mz_active_peeks_per_worker
8535WHERE worker_id = 0",
8536    access: vec![PUBLIC_SELECT],
8537});
8538
8539pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8540    LazyLock::new(|| BuiltinView {
8541        name: "mz_dataflow_operator_reachability_per_worker",
8542        schema: MZ_INTROSPECTION_SCHEMA,
8543        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8544        desc: RelationDesc::builder()
8545            .with_column("id", SqlScalarType::UInt64.nullable(false))
8546            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8547            .with_column("port", SqlScalarType::UInt64.nullable(false))
8548            .with_column("update_type", SqlScalarType::String.nullable(false))
8549            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8550            .with_column("count", SqlScalarType::Int64.nullable(false))
8551            .with_key(vec![0, 1, 2, 3, 4])
8552            .finish(),
8553        column_comments: BTreeMap::new(),
8554        sql: "SELECT
8555    addr2.id,
8556    reachability.worker_id,
8557    port,
8558    update_type,
8559    time,
8560    pg_catalog.count(*) as count
8561FROM
8562    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8563    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8564    mz_introspection.mz_dataflow_addresses_per_worker addr2
8565WHERE
8566    addr2.address =
8567    CASE
8568        WHEN source = 0 THEN addr1.address
8569        ELSE addr1.address || reachability.source
8570    END
8571    AND addr1.id = reachability.id
8572    AND addr1.worker_id = reachability.worker_id
8573    AND addr2.worker_id = reachability.worker_id
8574GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8575        access: vec![PUBLIC_SELECT],
8576    });
8577
8578pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8579    LazyLock::new(|| BuiltinView {
8580        name: "mz_dataflow_operator_reachability",
8581        schema: MZ_INTROSPECTION_SCHEMA,
8582        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8583        desc: RelationDesc::builder()
8584            .with_column("id", SqlScalarType::UInt64.nullable(false))
8585            .with_column("port", SqlScalarType::UInt64.nullable(false))
8586            .with_column("update_type", SqlScalarType::String.nullable(false))
8587            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8588            .with_column(
8589                "count",
8590                SqlScalarType::Numeric {
8591                    max_scale: Some(NumericMaxScale::ZERO),
8592                }
8593                .nullable(false),
8594            )
8595            .with_key(vec![0, 1, 2, 3])
8596            .finish(),
8597        column_comments: BTreeMap::new(),
8598        sql: "
8599SELECT
8600    id,
8601    port,
8602    update_type,
8603    time,
8604    pg_catalog.sum(count) as count
8605FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8606GROUP BY id, port, update_type, time",
8607        access: vec![PUBLIC_SELECT],
8608    });
8609
8610pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8611    BuiltinView {
8612        name: "mz_arrangement_sizes_per_worker",
8613        schema: MZ_INTROSPECTION_SCHEMA,
8614        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8615        desc: RelationDesc::builder()
8616            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8617            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8618            .with_column("records", SqlScalarType::Int64.nullable(true))
8619            .with_column("batches", SqlScalarType::Int64.nullable(true))
8620            .with_column("size", SqlScalarType::Int64.nullable(true))
8621            .with_column("capacity", SqlScalarType::Int64.nullable(true))
8622            .with_column("allocations", SqlScalarType::Int64.nullable(true))
8623            .finish(),
8624        column_comments: BTreeMap::new(),
8625        sql: "
8626WITH operators_per_worker_cte AS (
8627    SELECT
8628        id AS operator_id,
8629        worker_id
8630    FROM
8631        mz_introspection.mz_dataflow_operators_per_worker
8632),
8633batches_cte AS (
8634    SELECT
8635        operator_id,
8636        worker_id,
8637        COUNT(*) AS batches
8638    FROM
8639        mz_introspection.mz_arrangement_batches_raw
8640    GROUP BY
8641        operator_id, worker_id
8642),
8643records_cte AS (
8644    SELECT
8645        operator_id,
8646        worker_id,
8647        COUNT(*) AS records
8648    FROM
8649        mz_introspection.mz_arrangement_records_raw
8650    GROUP BY
8651        operator_id, worker_id
8652),
8653heap_size_cte AS (
8654    SELECT
8655        operator_id,
8656        worker_id,
8657        COUNT(*) AS size
8658    FROM
8659        mz_introspection.mz_arrangement_heap_size_raw
8660    GROUP BY
8661        operator_id, worker_id
8662),
8663heap_capacity_cte AS (
8664    SELECT
8665        operator_id,
8666        worker_id,
8667        COUNT(*) AS capacity
8668    FROM
8669        mz_introspection.mz_arrangement_heap_capacity_raw
8670    GROUP BY
8671        operator_id, worker_id
8672),
8673heap_allocations_cte AS (
8674    SELECT
8675        operator_id,
8676        worker_id,
8677        COUNT(*) AS allocations
8678    FROM
8679        mz_introspection.mz_arrangement_heap_allocations_raw
8680    GROUP BY
8681        operator_id, worker_id
8682),
8683batcher_records_cte AS (
8684    SELECT
8685        operator_id,
8686        worker_id,
8687        COUNT(*) AS records
8688    FROM
8689        mz_introspection.mz_arrangement_batcher_records_raw
8690    GROUP BY
8691        operator_id, worker_id
8692),
8693batcher_size_cte AS (
8694    SELECT
8695        operator_id,
8696        worker_id,
8697        COUNT(*) AS size
8698    FROM
8699        mz_introspection.mz_arrangement_batcher_size_raw
8700    GROUP BY
8701        operator_id, worker_id
8702),
8703batcher_capacity_cte AS (
8704    SELECT
8705        operator_id,
8706        worker_id,
8707        COUNT(*) AS capacity
8708    FROM
8709        mz_introspection.mz_arrangement_batcher_capacity_raw
8710    GROUP BY
8711        operator_id, worker_id
8712),
8713batcher_allocations_cte AS (
8714    SELECT
8715        operator_id,
8716        worker_id,
8717        COUNT(*) AS allocations
8718    FROM
8719        mz_introspection.mz_arrangement_batcher_allocations_raw
8720    GROUP BY
8721        operator_id, worker_id
8722),
8723combined AS (
8724    SELECT
8725        opw.operator_id,
8726        opw.worker_id,
8727        CASE
8728            WHEN records_cte.records IS NULL AND batcher_records_cte.records IS NULL THEN NULL
8729            ELSE COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0)
8730        END AS records,
8731        batches_cte.batches AS batches,
8732        CASE
8733            WHEN heap_size_cte.size IS NULL AND batcher_size_cte.size IS NULL THEN NULL
8734            ELSE COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0)
8735        END AS size,
8736        CASE
8737            WHEN heap_capacity_cte.capacity IS NULL AND batcher_capacity_cte.capacity IS NULL THEN NULL
8738            ELSE COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0)
8739        END AS capacity,
8740        CASE
8741            WHEN heap_allocations_cte.allocations IS NULL AND batcher_allocations_cte.allocations IS NULL THEN NULL
8742            ELSE COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0)
8743        END AS allocations
8744    FROM
8745                    operators_per_worker_cte opw
8746    LEFT OUTER JOIN batches_cte USING (operator_id, worker_id)
8747    LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
8748    LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
8749    LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
8750    LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
8751    LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
8752    LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
8753    LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
8754    LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)
8755)
8756SELECT
8757    operator_id, worker_id, records, batches, size, capacity, allocations
8758FROM combined
8759WHERE
8760       records     IS NOT NULL
8761    OR batches     IS NOT NULL
8762    OR size        IS NOT NULL
8763    OR capacity    IS NOT NULL
8764    OR allocations IS NOT NULL
8765",
8766        access: vec![PUBLIC_SELECT],
8767    }
8768});
8769
8770pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8771    name: "mz_arrangement_sizes",
8772    schema: MZ_INTROSPECTION_SCHEMA,
8773    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
8774    desc: RelationDesc::builder()
8775        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8776        .with_column("records", SqlScalarType::Int64.nullable(true))
8777        .with_column("batches", SqlScalarType::Int64.nullable(true))
8778        .with_column("size", SqlScalarType::Int64.nullable(true))
8779        .with_column("capacity", SqlScalarType::Int64.nullable(true))
8780        .with_column("allocations", SqlScalarType::Int64.nullable(true))
8781        .with_key(vec![0])
8782        .finish(),
8783    column_comments: BTreeMap::from_iter([
8784        (
8785            "operator_id",
8786            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8787        ),
8788        ("records", "The number of records in the arrangement."),
8789        ("batches", "The number of batches in the arrangement."),
8790        ("size", "The utilized size in bytes of the arrangement."),
8791        (
8792            "capacity",
8793            "The capacity in bytes of the arrangement. Can be larger than the size.",
8794        ),
8795        (
8796            "allocations",
8797            "The number of separate memory allocations backing the arrangement.",
8798        ),
8799    ]),
8800    sql: "
8801SELECT
8802    operator_id,
8803    SUM(records)::int8 AS records,
8804    SUM(batches)::int8 AS batches,
8805    SUM(size)::int8 AS size,
8806    SUM(capacity)::int8 AS capacity,
8807    SUM(allocations)::int8 AS allocations
8808FROM mz_introspection.mz_arrangement_sizes_per_worker
8809GROUP BY operator_id",
8810    access: vec![PUBLIC_SELECT],
8811});
8812
8813pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
8814    LazyLock::new(|| BuiltinView {
8815        name: "mz_arrangement_sharing_per_worker",
8816        schema: MZ_INTROSPECTION_SCHEMA,
8817        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
8818        desc: RelationDesc::builder()
8819            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8820            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8821            .with_column("count", SqlScalarType::Int64.nullable(false))
8822            .with_key(vec![0, 1])
8823            .finish(),
8824        column_comments: BTreeMap::new(),
8825        sql: "
8826SELECT
8827    operator_id,
8828    worker_id,
8829    pg_catalog.count(*) AS count
8830FROM mz_introspection.mz_arrangement_sharing_raw
8831GROUP BY operator_id, worker_id",
8832        access: vec![PUBLIC_SELECT],
8833    });
8834
8835pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8836    name: "mz_arrangement_sharing",
8837    schema: MZ_INTROSPECTION_SCHEMA,
8838    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
8839    desc: RelationDesc::builder()
8840        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8841        .with_column("count", SqlScalarType::Int64.nullable(false))
8842        .finish(),
8843    column_comments: BTreeMap::from_iter([
8844        (
8845            "operator_id",
8846            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8847        ),
8848        (
8849            "count",
8850            "The number of operators that share the arrangement.",
8851        ),
8852    ]),
8853    sql: "
8854SELECT operator_id, count
8855FROM mz_introspection.mz_arrangement_sharing_per_worker
8856WHERE worker_id = 0",
8857    access: vec![PUBLIC_SELECT],
8858});
8859
8860pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8861    name: "mz_cluster_replica_utilization",
8862    schema: MZ_INTERNAL_SCHEMA,
8863    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
8864    desc: RelationDesc::builder()
8865        .with_column("replica_id", SqlScalarType::String.nullable(false))
8866        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
8867        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8868        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8869        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8870        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8871        .finish(),
8872    column_comments: BTreeMap::from_iter([
8873        ("replica_id", "The ID of a cluster replica."),
8874        ("process_id", "The ID of a process within the replica."),
8875        (
8876            "cpu_percent",
8877            "Approximate CPU usage, in percent of the total allocation.",
8878        ),
8879        (
8880            "memory_percent",
8881            "Approximate RAM usage, in percent of the total allocation.",
8882        ),
8883        (
8884            "disk_percent",
8885            "Approximate disk usage, in percent of the total allocation.",
8886        ),
8887        (
8888            "heap_percent",
8889            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
8890        ),
8891    ]),
8892    sql: "
8893SELECT
8894    r.id AS replica_id,
8895    m.process_id,
8896    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
8897    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
8898    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
8899    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent
8900FROM
8901    mz_catalog.mz_cluster_replicas AS r
8902        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8903        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
8904    access: vec![PUBLIC_SELECT],
8905});
8906
8907pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
8908    LazyLock::new(|| BuiltinView {
8909        name: "mz_cluster_replica_utilization_history",
8910        schema: MZ_INTERNAL_SCHEMA,
8911        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
8912        desc: RelationDesc::builder()
8913            .with_column("replica_id", SqlScalarType::String.nullable(false))
8914            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
8915            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8916            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8917            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8918            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8919            .with_column(
8920                "occurred_at",
8921                SqlScalarType::TimestampTz { precision: None }.nullable(false),
8922            )
8923            .finish(),
8924        column_comments: BTreeMap::from_iter([
8925            ("replica_id", "The ID of a cluster replica."),
8926            ("process_id", "The ID of a process within the replica."),
8927            (
8928                "cpu_percent",
8929                "Approximate CPU usage, in percent of the total allocation.",
8930            ),
8931            (
8932                "memory_percent",
8933                "Approximate RAM usage, in percent of the total allocation.",
8934            ),
8935            (
8936                "disk_percent",
8937                "Approximate disk usage, in percent of the total allocation.",
8938            ),
8939            (
8940                "heap_percent",
8941                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
8942            ),
8943            (
8944                "occurred_at",
8945                "Wall-clock timestamp at which the event occurred.",
8946            ),
8947        ]),
8948        sql: "
8949SELECT
8950    r.id AS replica_id,
8951    m.process_id,
8952    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
8953    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
8954    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
8955    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
8956    m.occurred_at
8957FROM
8958    mz_catalog.mz_cluster_replicas AS r
8959        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8960        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
8961        access: vec![PUBLIC_SELECT],
8962    });
8963
8964pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
8965    LazyLock::new(|| BuiltinView {
8966        name: "mz_dataflow_operator_parents_per_worker",
8967        schema: MZ_INTROSPECTION_SCHEMA,
8968        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
8969        desc: RelationDesc::builder()
8970            .with_column("id", SqlScalarType::UInt64.nullable(false))
8971            .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
8972            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8973            .finish(),
8974        column_comments: BTreeMap::new(),
8975        sql: "
8976WITH operator_addrs AS(
8977    SELECT
8978        id, address, worker_id
8979    FROM mz_introspection.mz_dataflow_addresses_per_worker
8980        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
8981            USING (id, worker_id)
8982),
8983parent_addrs AS (
8984    SELECT
8985        id,
8986        address[1:list_length(address) - 1] AS parent_address,
8987        worker_id
8988    FROM operator_addrs
8989)
8990SELECT pa.id, oa.id AS parent_id, pa.worker_id
8991FROM parent_addrs AS pa
8992    INNER JOIN operator_addrs AS oa
8993        ON pa.parent_address = oa.address
8994        AND pa.worker_id = oa.worker_id",
8995        access: vec![PUBLIC_SELECT],
8996    });
8997
8998pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8999    name: "mz_dataflow_operator_parents",
9000    schema: MZ_INTROSPECTION_SCHEMA,
9001    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
9002    desc: RelationDesc::builder()
9003        .with_column("id", SqlScalarType::UInt64.nullable(false))
9004        .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9005        .finish(),
9006    column_comments: BTreeMap::from_iter([
9007        (
9008            "id",
9009            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
9010        ),
9011        (
9012            "parent_id",
9013            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
9014        ),
9015    ]),
9016    sql: "
9017SELECT id, parent_id
9018FROM mz_introspection.mz_dataflow_operator_parents_per_worker
9019WHERE worker_id = 0",
9020    access: vec![PUBLIC_SELECT],
9021});
9022
9023pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9024    name: "mz_dataflow_arrangement_sizes",
9025    schema: MZ_INTROSPECTION_SCHEMA,
9026    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
9027    desc: RelationDesc::builder()
9028        .with_column("id", SqlScalarType::UInt64.nullable(false))
9029        .with_column("name", SqlScalarType::String.nullable(false))
9030        .with_column("records", SqlScalarType::Int64.nullable(true))
9031        .with_column("batches", SqlScalarType::Int64.nullable(true))
9032        .with_column("size", SqlScalarType::Int64.nullable(true))
9033        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9034        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9035        .with_key(vec![0, 1])
9036        .finish(),
9037    column_comments: BTreeMap::from_iter([
9038        (
9039            "id",
9040            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9041        ),
9042        ("name", "The name of the [dataflow]."),
9043        (
9044            "records",
9045            "The number of records in all arrangements in the dataflow.",
9046        ),
9047        (
9048            "batches",
9049            "The number of batches in all arrangements in the dataflow.",
9050        ),
9051        ("size", "The utilized size in bytes of the arrangements."),
9052        (
9053            "capacity",
9054            "The capacity in bytes of the arrangements. Can be larger than the size.",
9055        ),
9056        (
9057            "allocations",
9058            "The number of separate memory allocations backing the arrangements.",
9059        ),
9060    ]),
9061    sql: "
9062SELECT
9063    mdod.dataflow_id AS id,
9064    mdod.dataflow_name AS name,
9065    SUM(mas.records)::int8 AS records,
9066    SUM(mas.batches)::int8 AS batches,
9067    SUM(mas.size)::int8 AS size,
9068    SUM(mas.capacity)::int8 AS capacity,
9069    SUM(mas.allocations)::int8 AS allocations
9070FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9071LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9072    ON mdod.id = mas.operator_id
9073GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9074    access: vec![PUBLIC_SELECT],
9075});
9076
9077pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9078    name: "mz_expected_group_size_advice",
9079    schema: MZ_INTROSPECTION_SCHEMA,
9080    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9081    desc: RelationDesc::builder()
9082        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
9083        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
9084        .with_column("region_id", SqlScalarType::UInt64.nullable(false))
9085        .with_column("region_name", SqlScalarType::String.nullable(false))
9086        .with_column("levels", SqlScalarType::Int64.nullable(false))
9087        .with_column("to_cut", SqlScalarType::Int64.nullable(false))
9088        .with_column(
9089            "savings",
9090            SqlScalarType::Numeric {
9091                max_scale: Some(NumericMaxScale::ZERO),
9092            }
9093            .nullable(true),
9094        )
9095        .with_column("hint", SqlScalarType::Float64.nullable(false))
9096        .finish(),
9097    column_comments: BTreeMap::from_iter([
9098        (
9099            "dataflow_id",
9100            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9101        ),
9102        (
9103            "dataflow_name",
9104            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9105        ),
9106        (
9107            "region_id",
9108            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9109        ),
9110        (
9111            "region_name",
9112            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9113        ),
9114        (
9115            "levels",
9116            "The number of levels in the hierarchical scheme implemented by the region.",
9117        ),
9118        (
9119            "to_cut",
9120            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9121        ),
9122        (
9123            "savings",
9124            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9125        ),
9126        (
9127            "hint",
9128            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9129        ),
9130    ]),
9131    sql: "
9132        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9133        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9134        -- of arrangements must be built. For each dataflow and region corresponding to one
9135        -- such pattern, we look for how many levels can be eliminated without hitting a level
9136        -- that actually substantially filters the input. The advice is constructed so that
9137        -- setting the hint for the affected region will eliminate these redundant levels of
9138        -- the hierarchical rendering.
9139        --
9140        -- A number of helper CTEs are used for the view definition. The first one, operators,
9141        -- looks for operator names that comprise arrangements of inputs to each level of a
9142        -- min/max/top-k hierarchy.
9143        WITH operators AS (
9144            SELECT
9145                dod.dataflow_id,
9146                dor.id AS region_id,
9147                dod.id,
9148                ars.records,
9149                ars.size
9150            FROM
9151                mz_introspection.mz_dataflow_operator_dataflows dod
9152                JOIN mz_introspection.mz_dataflow_addresses doa
9153                    ON dod.id = doa.id
9154                JOIN mz_introspection.mz_dataflow_addresses dra
9155                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9156                JOIN mz_introspection.mz_dataflow_operators dor
9157                    ON dor.id = dra.id
9158                JOIN mz_introspection.mz_arrangement_sizes ars
9159                    ON ars.operator_id = dod.id
9160            WHERE
9161                dod.name = 'Arranged TopK input'
9162                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9163                OR dod.name = 'Arrange ReduceMinsMaxes'
9164            ),
9165        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9166        -- identified in operators above.
9167        levels AS (
9168            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9169            FROM operators o
9170            GROUP BY o.dataflow_id, o.region_id
9171        ),
9172        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9173        -- operator. This operator is crucially important, as it records the number of records
9174        -- that was given as input to the gadget as a whole.
9175        pivot AS (
9176            SELECT
9177                o1.dataflow_id,
9178                o1.region_id,
9179                o1.id,
9180                o1.records
9181            FROM operators o1
9182            WHERE
9183                o1.id = (
9184                    SELECT MIN(o2.id)
9185                    FROM operators o2
9186                    WHERE
9187                        o2.dataflow_id = o1.dataflow_id
9188                        AND o2.region_id = o1.region_id
9189                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9190                )
9191        ),
9192        -- The fourth CTE, candidates, will look for operators where the number of records
9193        -- maintained is not significantly different from the number at the pivot (excluding
9194        -- the pivot itself). These are the candidates for being cut from the dataflow region
9195        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9196        -- load generator data, to give some room for small deviations in number of records.
9197        -- The intuition for allowing for this deviation is that we are looking for a strongly
9198        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9199        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9200        -- among groups where the min/max/top-k computation is (partially) applied. If the
9201        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9202        -- groups might be empty or contain only one row. Each subsequent level will have a number
9203        -- of groups that is reduced exponentially. So at some point, we will find the level where
9204        -- we actually start having a few rows per group. That's where we will see the row counts
9205        -- significantly drop off.
9206        candidates AS (
9207            SELECT
9208                o.dataflow_id,
9209                o.region_id,
9210                o.id,
9211                o.records,
9212                o.size
9213            FROM
9214                operators o
9215                JOIN pivot p
9216                    ON o.dataflow_id = p.dataflow_id
9217                        AND o.region_id = p.region_id
9218                        AND o.id <> p.id
9219            WHERE o.records >= p.records * (1 - 0.15)
9220        ),
9221        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9222        -- candidate levels that should be cut. We only return here dataflow regions where at
9223        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9224        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9225        -- cutting the height of the hierarchy further. This is because we will have way less
9226        -- groups in the next level, so there should be even further reduction happening or there
9227        -- is some substantial skew in the data. But if the latter is the case, then we should not
9228        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9229        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9230        -- compute a conservative estimate of the memory savings in bytes that will result from
9231        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9232        -- input arrangements for each level to be cut. These arrangements should dominate the
9233        -- size of each level that can be cut, since the reduction gadget internal to the level
9234        -- does not remove much data at these levels.
9235        cuts AS (
9236            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9237            FROM candidates c
9238            GROUP BY c.dataflow_id, c.region_id
9239            HAVING COUNT(*) > 0
9240        )
9241        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9242        -- levels and the number of candidates to be cut. The hint is computed taking into account
9243        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9244        -- currently equal to 16.
9245        SELECT
9246            dod.dataflow_id,
9247            dod.dataflow_name,
9248            dod.id AS region_id,
9249            dod.name AS region_name,
9250            l.levels,
9251            c.to_cut,
9252            c.savings,
9253            pow(16, l.levels - c.to_cut) - 1 AS hint
9254        FROM cuts c
9255            JOIN levels l
9256                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9257            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9258                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9259    access: vec![PUBLIC_SELECT],
9260});
9261
9262pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9263    BuiltinView {
9264        name: "mz_index_advice",
9265        schema: MZ_INTERNAL_SCHEMA,
9266        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9267        desc: RelationDesc::builder()
9268            .with_column("object_id", SqlScalarType::String.nullable(true))
9269            .with_column("hint", SqlScalarType::String.nullable(false))
9270            .with_column("details", SqlScalarType::String.nullable(false))
9271            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
9272            .finish(),
9273        column_comments: BTreeMap::from_iter([
9274            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9275            ("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."),
9276            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9277            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9278        ]),
9279        sql: "
9280-- To avoid confusion with sources and sinks in the materialize sense,
9281-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9282-- when referring to the object dependency graph.
9283--
9284-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9285-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9286-- that are not depended on by other maintained objects and have a justification why they must
9287-- be maintained (e.g. a materialized view that is depended on by a sink).
9288-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9289-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9290-- downstream objects, that node is marked to be converted into a maintained object and this
9291-- node is then propagated further up. Once completed, the list of objects that are marked as
9292-- maintained is checked against all objects to generate appropriate recommendations.
9293--
9294-- Note that the recommendations only incorporate dependencies between objects.
9295-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9296-- a sink if an index is added in between the sink and the filter. For very selective filters,
9297-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9298-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9299-- dependencies.
9300WITH MUTUALLY RECURSIVE
9301    -- for all objects, understand if they have an index on them and on which cluster they are running
9302    -- this avoids having different cases for views with an index and materialized views later on
9303    objects(id text, type text, cluster_id text, indexes text list) AS (
9304        -- views and materialized views without an index
9305        SELECT
9306            o.id,
9307            o.type,
9308            o.cluster_id,
9309            '{}'::text list AS indexes
9310        FROM mz_catalog.mz_objects o
9311        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9312            SELECT FROM mz_internal.mz_object_dependencies d
9313            JOIN mz_catalog.mz_objects AS i
9314                ON (i.id = d.object_id AND i.type = 'index')
9315            WHERE (o.id = d.referenced_object_id)
9316        )
9317
9318        UNION ALL
9319
9320        -- views and materialized views with an index
9321        SELECT
9322            o.id,
9323            o.type,
9324            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9325            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9326            list_agg(i.id) AS indexes
9327        FROM mz_catalog.mz_objects o
9328        JOIN mz_internal.mz_object_dependencies AS d
9329            ON (o.id = d.referenced_object_id)
9330        JOIN mz_catalog.mz_objects AS i
9331            ON (i.id = d.object_id AND i.type = 'index')
9332        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9333        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9334    ),
9335
9336    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9337    maintained_leafs(id text, justification text) AS (
9338        -- materialized views that are connected to a sink
9339        SELECT
9340            m.id,
9341            s.id AS justification
9342        FROM objects AS m
9343        JOIN mz_internal.mz_object_dependencies AS d
9344            ON (m.id = d.referenced_object_id)
9345        JOIN mz_catalog.mz_objects AS s
9346            ON (s.id = d.object_id AND s.type = 'sink')
9347        WHERE m.type = 'materialized-view'
9348
9349        UNION ALL
9350
9351        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9352        SELECT
9353            v.id,
9354            unnest(v.indexes) AS justification
9355        FROM objects AS v
9356        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9357            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9358            INNER JOIN mz_catalog.mz_objects AS child
9359                ON (d.object_id = child.id)
9360            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]
9361        )
9362    ),
9363
9364    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9365    agg_maintained_children(id text, maintained_children text list) AS (
9366        SELECT
9367            parent_id AS id,
9368            list_agg(maintained_child) AS maintained_leafs
9369        FROM (
9370            SELECT DISTINCT
9371                d.referenced_object_id AS parent_id,
9372                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9373                unnest(child.maintained_children) AS maintained_child
9374            FROM propagate_dependencies AS child
9375            INNER JOIN mz_internal.mz_object_dependencies AS d
9376                ON (child.id = d.object_id)
9377        )
9378        GROUP BY parent_id
9379    ),
9380
9381    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9382    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9383    -- 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
9384    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9385        -- base case: start with the leafs
9386        SELECT DISTINCT
9387            id,
9388            LIST[id] AS maintained_children,
9389            list_agg(justification) AS justification
9390        FROM maintained_leafs
9391        GROUP BY id
9392
9393        UNION
9394
9395        -- recursive case: if there is a child with the same dependencies as the parent,
9396        -- the parent is only reused by a single child
9397        SELECT
9398            parent.id,
9399            child.maintained_children,
9400            NULL::text list AS justification
9401        FROM agg_maintained_children AS parent
9402        INNER JOIN mz_internal.mz_object_dependencies AS d
9403            ON (parent.id = d.referenced_object_id)
9404        INNER JOIN propagate_dependencies AS child
9405            ON (d.object_id = child.id)
9406        WHERE parent.maintained_children = child.maintained_children
9407
9408        UNION
9409
9410        -- recursive case: if there is NO child with the same dependencies as the parent,
9411        -- different children are reusing the parent so maintaining the object is justified by itself
9412        SELECT DISTINCT
9413            parent.id,
9414            LIST[parent.id] AS maintained_children,
9415            parent.maintained_children AS justification
9416        FROM agg_maintained_children AS parent
9417        WHERE NOT EXISTS (
9418            SELECT FROM mz_internal.mz_object_dependencies AS d
9419            INNER JOIN propagate_dependencies AS child
9420                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9421            WHERE parent.maintained_children = child.maintained_children
9422        )
9423    ),
9424
9425    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9426        SELECT
9427            p.id,
9428            o.type,
9429            o.cluster_id,
9430            p.maintained_children,
9431            p.justification,
9432            o.indexes
9433        FROM propagate_dependencies p
9434        JOIN objects AS o
9435            ON (p.id = o.id)
9436    ),
9437
9438    hints(id text, hint text, details text, justification text list) AS (
9439        -- materialized views that are not required
9440        SELECT
9441            id,
9442            'convert to a view' AS hint,
9443            'no dependencies from sinks nor from objects on different clusters' AS details,
9444            justification
9445        FROM objects_with_justification
9446        WHERE type = 'materialized-view' AND justification IS NULL
9447
9448        UNION ALL
9449
9450        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9451        SELECT
9452            id,
9453            'keep' AS hint,
9454            'dependencies from sinks or objects on different clusters: ' AS details,
9455            justification
9456        FROM objects_with_justification AS m
9457        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9458            SELECT FROM unnest(justification) AS dependency
9459            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9460
9461            UNION ALL
9462
9463            SELECT FROM unnest(justification) AS dependency
9464            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9465            WHERE d.cluster_id != m.cluster_id
9466        )
9467
9468        UNION ALL
9469
9470        -- 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
9471        SELECT
9472            id,
9473            'convert to a view with an index' AS hint,
9474            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9475            justification
9476        FROM objects_with_justification AS m
9477        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
9478            SELECT FROM unnest(justification) AS dependency
9479            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9480
9481            UNION ALL
9482
9483            SELECT FROM unnest(justification) AS dependency
9484            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9485            WHERE d.cluster_id != m.cluster_id
9486        )
9487
9488        UNION ALL
9489
9490        -- views that have indexes on different clusters should be a materialized view
9491        SELECT
9492            o.id,
9493            'convert to materialized view' AS hint,
9494            'dependencies on multiple clusters: ' AS details,
9495            o.justification
9496        FROM objects_with_justification o,
9497            LATERAL unnest(o.justification) j
9498        LEFT JOIN mz_catalog.mz_objects AS m
9499            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9500        WHERE o.type = 'view' AND o.justification IS NOT NULL
9501        GROUP BY o.id, o.justification
9502        HAVING count(DISTINCT m.cluster_id) >= 2
9503
9504        UNION ALL
9505
9506        -- views without an index that should be maintained
9507        SELECT
9508            id,
9509            'add index' AS hint,
9510            'multiple downstream dependencies: ' AS details,
9511            justification
9512        FROM objects_with_justification
9513        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9514
9515        UNION ALL
9516
9517        -- index inside the dependency graph (not a leaf)
9518        SELECT
9519            unnest(indexes) AS id,
9520            'drop unless queried directly' AS hint,
9521            'fewer than two downstream dependencies: ' AS details,
9522            maintained_children AS justification
9523        FROM objects_with_justification
9524        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9525
9526        UNION ALL
9527
9528        -- index on a leaf of the dependency graph
9529        SELECT
9530            unnest(indexes) AS id,
9531            'drop unless queried directly' AS hint,
9532            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9533            NULL::text list AS justification
9534        FROM objects_with_justification
9535        -- indexes can only be part of justification for leaf nodes
9536        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9537
9538        UNION ALL
9539
9540        -- index on a source
9541        SELECT
9542            unnest(indexes) AS id,
9543            'drop unless queried directly' AS hint,
9544            'sources do not transform data and can expose data directly' AS details,
9545            NULL::text list AS justification
9546        FROM objects_with_justification
9547        -- indexes can only be part of justification for leaf nodes
9548        WHERE type = 'source' AND NOT indexes = '{}'::text list
9549
9550        UNION ALL
9551
9552        -- indexes on views inside the dependency graph
9553        SELECT
9554            unnest(indexes) AS id,
9555            'keep' AS hint,
9556            'multiple downstream dependencies: ' AS details,
9557            justification
9558        FROM objects_with_justification
9559        -- indexes can only be part of justification for leaf nodes
9560        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9561    ),
9562
9563    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9564        SELECT
9565            h.id,
9566            h.hint,
9567            h.details || list_agg(o.name)::text AS details,
9568            h.justification
9569        FROM hints AS h,
9570            LATERAL unnest(h.justification) j
9571        JOIN mz_catalog.mz_objects AS o
9572            ON (o.id = j)
9573        GROUP BY h.id, h.hint, h.details, h.justification
9574
9575        UNION ALL
9576
9577        SELECT
9578            id,
9579            hint,
9580            details,
9581            justification
9582        FROM hints
9583        WHERE justification IS NULL
9584    )
9585
9586SELECT
9587    h.id AS object_id,
9588    h.hint AS hint,
9589    h.details,
9590    h.justification AS referenced_object_ids
9591FROM hints_resolved_ids AS h",
9592        access: vec![PUBLIC_SELECT],
9593    }
9594});
9595
9596// NOTE: If you add real data to this implementation, then please update
9597// the related `pg_` function implementations (like `pg_get_constraintdef`)
9598pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9599    name: "pg_constraint",
9600    schema: PG_CATALOG_SCHEMA,
9601    oid: oid::VIEW_PG_CONSTRAINT_OID,
9602    desc: RelationDesc::builder()
9603        .with_column("oid", SqlScalarType::Oid.nullable(false))
9604        .with_column("conname", SqlScalarType::String.nullable(false))
9605        .with_column("connamespace", SqlScalarType::Oid.nullable(false))
9606        .with_column("contype", SqlScalarType::PgLegacyChar.nullable(false))
9607        .with_column("condeferrable", SqlScalarType::Bool.nullable(false))
9608        .with_column("condeferred", SqlScalarType::Bool.nullable(false))
9609        .with_column("convalidated", SqlScalarType::Bool.nullable(false))
9610        .with_column("conrelid", SqlScalarType::Oid.nullable(false))
9611        .with_column("contypid", SqlScalarType::Oid.nullable(false))
9612        .with_column("conindid", SqlScalarType::Oid.nullable(false))
9613        .with_column("conparentid", SqlScalarType::Oid.nullable(false))
9614        .with_column("confrelid", SqlScalarType::Oid.nullable(false))
9615        .with_column("confupdtype", SqlScalarType::PgLegacyChar.nullable(false))
9616        .with_column("confdeltype", SqlScalarType::PgLegacyChar.nullable(false))
9617        .with_column("confmatchtype", SqlScalarType::PgLegacyChar.nullable(false))
9618        .with_column("conislocal", SqlScalarType::Bool.nullable(false))
9619        .with_column("coninhcount", SqlScalarType::Int32.nullable(false))
9620        .with_column("connoinherit", SqlScalarType::Bool.nullable(false))
9621        .with_column(
9622            "conkey",
9623            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9624        )
9625        .with_column(
9626            "confkey",
9627            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9628        )
9629        .with_column(
9630            "conpfeqop",
9631            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9632        )
9633        .with_column(
9634            "conppeqop",
9635            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9636        )
9637        .with_column(
9638            "conffeqop",
9639            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9640        )
9641        .with_column(
9642            "conexclop",
9643            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9644        )
9645        .with_column("conbin", SqlScalarType::String.nullable(false))
9646        .with_key(vec![])
9647        .finish(),
9648    column_comments: BTreeMap::new(),
9649    sql: "SELECT
9650    NULL::pg_catalog.oid as oid,
9651    NULL::pg_catalog.text as conname,
9652    NULL::pg_catalog.oid as connamespace,
9653    NULL::pg_catalog.\"char\" as contype,
9654    NULL::pg_catalog.bool as condeferrable,
9655    NULL::pg_catalog.bool as condeferred,
9656    NULL::pg_catalog.bool as convalidated,
9657    NULL::pg_catalog.oid as conrelid,
9658    NULL::pg_catalog.oid as contypid,
9659    NULL::pg_catalog.oid as conindid,
9660    NULL::pg_catalog.oid as conparentid,
9661    NULL::pg_catalog.oid as confrelid,
9662    NULL::pg_catalog.\"char\" as confupdtype,
9663    NULL::pg_catalog.\"char\" as confdeltype,
9664    NULL::pg_catalog.\"char\" as confmatchtype,
9665    NULL::pg_catalog.bool as conislocal,
9666    NULL::pg_catalog.int4 as coninhcount,
9667    NULL::pg_catalog.bool as connoinherit,
9668    NULL::pg_catalog.int2[] as conkey,
9669    NULL::pg_catalog.int2[] as confkey,
9670    NULL::pg_catalog.oid[] as conpfeqop,
9671    NULL::pg_catalog.oid[] as conppeqop,
9672    NULL::pg_catalog.oid[] as conffeqop,
9673    NULL::pg_catalog.oid[] as conexclop,
9674    NULL::pg_catalog.text as conbin
9675WHERE false",
9676    access: vec![PUBLIC_SELECT],
9677});
9678
9679pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9680    name: "pg_tables",
9681    schema: PG_CATALOG_SCHEMA,
9682    oid: oid::VIEW_PG_TABLES_OID,
9683    desc: RelationDesc::builder()
9684        .with_column("schemaname", SqlScalarType::String.nullable(true))
9685        .with_column("tablename", SqlScalarType::String.nullable(false))
9686        .with_column("tableowner", SqlScalarType::String.nullable(false))
9687        .finish(),
9688    column_comments: BTreeMap::new(),
9689    sql: "
9690SELECT n.nspname AS schemaname,
9691    c.relname AS tablename,
9692    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
9693FROM pg_catalog.pg_class c
9694LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
9695WHERE c.relkind IN ('r', 'p')",
9696    access: vec![PUBLIC_SELECT],
9697});
9698
9699pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9700    name: "pg_tablespace",
9701    schema: PG_CATALOG_SCHEMA,
9702    oid: oid::VIEW_PG_TABLESPACE_OID,
9703    desc: RelationDesc::builder()
9704        .with_column("oid", SqlScalarType::Oid.nullable(false))
9705        .with_column("spcname", SqlScalarType::String.nullable(false))
9706        .with_column("spcowner", SqlScalarType::Oid.nullable(true))
9707        .with_column(
9708            "spcacl",
9709            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9710        )
9711        .with_column(
9712            "spcoptions",
9713            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9714        )
9715        .with_key(vec![])
9716        .finish(),
9717    column_comments: BTreeMap::new(),
9718    sql: "
9719    SELECT oid, spcname, spcowner, spcacl, spcoptions
9720    FROM (
9721        VALUES (
9722            --These are the same defaults CockroachDB uses.
9723            0::pg_catalog.oid,
9724            'pg_default'::pg_catalog.text,
9725            NULL::pg_catalog.oid,
9726            NULL::pg_catalog.text[],
9727            NULL::pg_catalog.text[]
9728        )
9729    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
9730",
9731    access: vec![PUBLIC_SELECT],
9732});
9733
9734pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9735    name: "pg_am",
9736    schema: PG_CATALOG_SCHEMA,
9737    oid: oid::VIEW_PG_AM_OID,
9738    desc: RelationDesc::builder()
9739        .with_column("oid", SqlScalarType::Oid.nullable(false))
9740        .with_column("amname", SqlScalarType::String.nullable(false))
9741        .with_column("amhandler", SqlScalarType::RegProc.nullable(false))
9742        .with_column("amtype", SqlScalarType::PgLegacyChar.nullable(false))
9743        .with_key(vec![])
9744        .finish(),
9745    column_comments: BTreeMap::new(),
9746    sql: "
9747SELECT NULL::pg_catalog.oid AS oid,
9748    NULL::pg_catalog.text AS amname,
9749    NULL::pg_catalog.regproc AS amhandler,
9750    NULL::pg_catalog.\"char\" AS amtype
9751WHERE false",
9752    access: vec![PUBLIC_SELECT],
9753});
9754
9755pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9756    name: "pg_roles",
9757    schema: PG_CATALOG_SCHEMA,
9758    oid: oid::VIEW_PG_ROLES_OID,
9759    desc: RelationDesc::builder()
9760        .with_column("rolname", SqlScalarType::String.nullable(false))
9761        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
9762        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
9763        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
9764        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
9765        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
9766        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
9767        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
9768        .with_column("rolpassword", SqlScalarType::String.nullable(false))
9769        .with_column(
9770            "rolvaliduntil",
9771            SqlScalarType::TimestampTz { precision: None }.nullable(true),
9772        )
9773        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
9774        .with_column(
9775            "rolconfig",
9776            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9777        )
9778        .with_column("oid", SqlScalarType::Oid.nullable(false))
9779        .finish(),
9780    column_comments: BTreeMap::new(),
9781    sql: "SELECT
9782    rolname,
9783    rolsuper,
9784    rolinherit,
9785    rolcreaterole,
9786    rolcreatedb,
9787    COALESCE(rolcanlogin, false) AS rolcanlogin,
9788    rolreplication,
9789    rolconnlimit,
9790    '********' as rolpassword,
9791    rolvaliduntil,
9792    rolbypassrls,
9793    (
9794        SELECT array_agg(parameter_name || '=' || parameter_value)
9795        FROM mz_catalog.mz_role_parameters rp
9796        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9797        WHERE ai.oid = r.oid
9798    ) AS rolconfig,
9799    oid
9800FROM pg_catalog.pg_authid ai",
9801    access: vec![PUBLIC_SELECT],
9802});
9803
9804pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9805    name: "pg_user",
9806    schema: PG_CATALOG_SCHEMA,
9807    oid: oid::VIEW_PG_USER_OID,
9808    desc: RelationDesc::builder()
9809        .with_column("usename", SqlScalarType::String.nullable(false))
9810        .with_column("usesysid", SqlScalarType::Oid.nullable(false))
9811        .with_column("usecreatedb", SqlScalarType::Bool.nullable(true))
9812        .with_column("usesuper", SqlScalarType::Bool.nullable(true))
9813        .with_column("userepl", SqlScalarType::Bool.nullable(false))
9814        .with_column("usebypassrls", SqlScalarType::Bool.nullable(false))
9815        .with_column("passwd", SqlScalarType::String.nullable(true))
9816        .with_column(
9817            "valuntil",
9818            SqlScalarType::TimestampTz { precision: None }.nullable(true),
9819        )
9820        .with_column(
9821            "useconfig",
9822            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9823        )
9824        .finish(),
9825    column_comments: BTreeMap::new(),
9826    sql: "
9827SELECT
9828    rolname as usename,
9829    ai.oid as usesysid,
9830    rolcreatedb AS usecreatedb,
9831    rolsuper AS usesuper,
9832    rolreplication AS userepl,
9833    rolbypassrls AS usebypassrls,
9834    rolpassword as passwd,
9835    rolvaliduntil as valuntil,
9836    (
9837        SELECT array_agg(parameter_name || '=' || parameter_value)
9838        FROM mz_catalog.mz_role_parameters rp
9839        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9840        WHERE ai.oid = r.oid
9841    ) AS useconfig
9842FROM pg_catalog.pg_authid ai
9843WHERE rolcanlogin",
9844    access: vec![PUBLIC_SELECT],
9845});
9846
9847pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9848    name: "pg_views",
9849    schema: PG_CATALOG_SCHEMA,
9850    oid: oid::VIEW_PG_VIEWS_OID,
9851    desc: RelationDesc::builder()
9852        .with_column("schemaname", SqlScalarType::String.nullable(true))
9853        .with_column("viewname", SqlScalarType::String.nullable(false))
9854        .with_column("viewowner", SqlScalarType::Oid.nullable(false))
9855        .with_column("definition", SqlScalarType::String.nullable(false))
9856        .finish(),
9857    column_comments: BTreeMap::new(),
9858    sql: "SELECT
9859    s.name AS schemaname,
9860    v.name AS viewname,
9861    role_owner.oid AS viewowner,
9862    v.definition AS definition
9863FROM mz_catalog.mz_views v
9864LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
9865LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9866JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
9867WHERE s.database_id IS NULL OR d.name = current_database()",
9868    access: vec![PUBLIC_SELECT],
9869});
9870
9871pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9872    name: "pg_matviews",
9873    schema: PG_CATALOG_SCHEMA,
9874    oid: oid::VIEW_PG_MATVIEWS_OID,
9875    desc: RelationDesc::builder()
9876        .with_column("schemaname", SqlScalarType::String.nullable(true))
9877        .with_column("matviewname", SqlScalarType::String.nullable(false))
9878        .with_column("matviewowner", SqlScalarType::Oid.nullable(false))
9879        .with_column("definition", SqlScalarType::String.nullable(false))
9880        .finish(),
9881    column_comments: BTreeMap::new(),
9882    sql: "SELECT
9883    s.name AS schemaname,
9884    m.name AS matviewname,
9885    role_owner.oid AS matviewowner,
9886    m.definition AS definition
9887FROM mz_catalog.mz_materialized_views m
9888LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
9889LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9890JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
9891WHERE s.database_id IS NULL OR d.name = current_database()",
9892    access: vec![PUBLIC_SELECT],
9893});
9894
9895pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
9896    LazyLock::new(|| BuiltinView {
9897        name: "applicable_roles",
9898        schema: INFORMATION_SCHEMA,
9899        oid: oid::VIEW_APPLICABLE_ROLES_OID,
9900        desc: RelationDesc::builder()
9901            .with_column("grantee", SqlScalarType::String.nullable(false))
9902            .with_column("role_name", SqlScalarType::String.nullable(false))
9903            .with_column("is_grantable", SqlScalarType::String.nullable(false))
9904            .finish(),
9905        column_comments: BTreeMap::new(),
9906        sql: "
9907SELECT
9908    member.name AS grantee,
9909    role.name AS role_name,
9910    -- ADMIN OPTION isn't implemented.
9911    'NO' AS is_grantable
9912FROM mz_catalog.mz_role_members membership
9913JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
9914JOIN mz_catalog.mz_roles member ON membership.member = member.id
9915WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
9916        access: vec![PUBLIC_SELECT],
9917    });
9918
9919pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9920    name: "columns",
9921    schema: INFORMATION_SCHEMA,
9922    oid: oid::VIEW_COLUMNS_OID,
9923    desc: RelationDesc::builder()
9924        .with_column("table_catalog", SqlScalarType::String.nullable(false))
9925        .with_column("table_schema", SqlScalarType::String.nullable(false))
9926        .with_column("table_name", SqlScalarType::String.nullable(false))
9927        .with_column("column_name", SqlScalarType::String.nullable(false))
9928        .with_column("ordinal_position", SqlScalarType::Int64.nullable(false))
9929        .with_column("column_default", SqlScalarType::String.nullable(true))
9930        .with_column("is_nullable", SqlScalarType::String.nullable(false))
9931        .with_column("data_type", SqlScalarType::String.nullable(false))
9932        .with_column(
9933            "character_maximum_length",
9934            SqlScalarType::Int32.nullable(true),
9935        )
9936        .with_column("numeric_precision", SqlScalarType::Int32.nullable(true))
9937        .with_column("numeric_scale", SqlScalarType::Int32.nullable(true))
9938        .finish(),
9939    column_comments: BTreeMap::new(),
9940    sql: "
9941SELECT
9942    current_database() as table_catalog,
9943    s.name AS table_schema,
9944    o.name AS table_name,
9945    c.name AS column_name,
9946    c.position::int8 AS ordinal_position,
9947    c.default AS column_default,
9948    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
9949    c.type AS data_type,
9950    NULL::pg_catalog.int4 AS character_maximum_length,
9951    NULL::pg_catalog.int4 AS numeric_precision,
9952    NULL::pg_catalog.int4 AS numeric_scale
9953FROM mz_catalog.mz_columns c
9954JOIN mz_catalog.mz_objects o ON o.id = c.id
9955JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
9956LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9957WHERE s.database_id IS NULL OR d.name = current_database()",
9958    access: vec![PUBLIC_SELECT],
9959});
9960
9961pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
9962    LazyLock::new(|| BuiltinView {
9963        name: "enabled_roles",
9964        schema: INFORMATION_SCHEMA,
9965        oid: oid::VIEW_ENABLED_ROLES_OID,
9966        desc: RelationDesc::builder()
9967            .with_column("role_name", SqlScalarType::String.nullable(false))
9968            .finish(),
9969        column_comments: BTreeMap::new(),
9970        sql: "
9971SELECT name AS role_name
9972FROM mz_catalog.mz_roles
9973WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
9974        access: vec![PUBLIC_SELECT],
9975    });
9976
9977pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
9978    BuiltinView {
9979        name: "role_table_grants",
9980        schema: INFORMATION_SCHEMA,
9981        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
9982        desc: RelationDesc::builder()
9983            .with_column("grantor", SqlScalarType::String.nullable(false))
9984            .with_column("grantee", SqlScalarType::String.nullable(true))
9985            .with_column("table_catalog", SqlScalarType::String.nullable(true))
9986            .with_column("table_schema", SqlScalarType::String.nullable(false))
9987            .with_column("table_name", SqlScalarType::String.nullable(false))
9988            .with_column("privilege_type", SqlScalarType::String.nullable(true))
9989            .with_column("is_grantable", SqlScalarType::String.nullable(false))
9990            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
9991            .finish(),
9992        column_comments: BTreeMap::new(),
9993        sql: "
9994SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
9995FROM information_schema.table_privileges
9996WHERE
9997    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
9998    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
9999        access: vec![PUBLIC_SELECT],
10000    }
10001});
10002
10003pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
10004    LazyLock::new(|| BuiltinView {
10005        name: "key_column_usage",
10006        schema: INFORMATION_SCHEMA,
10007        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
10008        desc: RelationDesc::builder()
10009            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10010            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10011            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10012            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10013            .with_column("table_schema", SqlScalarType::String.nullable(false))
10014            .with_column("table_name", SqlScalarType::String.nullable(false))
10015            .with_column("column_name", SqlScalarType::String.nullable(false))
10016            .with_column("ordinal_position", SqlScalarType::Int32.nullable(false))
10017            .with_column(
10018                "position_in_unique_constraint",
10019                SqlScalarType::Int32.nullable(false),
10020            )
10021            .with_key(vec![])
10022            .finish(),
10023        column_comments: BTreeMap::new(),
10024        sql: "SELECT
10025    NULL::text AS constraint_catalog,
10026    NULL::text AS constraint_schema,
10027    NULL::text AS constraint_name,
10028    NULL::text AS table_catalog,
10029    NULL::text AS table_schema,
10030    NULL::text AS table_name,
10031    NULL::text AS column_name,
10032    NULL::integer AS ordinal_position,
10033    NULL::integer AS position_in_unique_constraint
10034WHERE false",
10035        access: vec![PUBLIC_SELECT],
10036    });
10037
10038pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10039    LazyLock::new(|| BuiltinView {
10040        name: "referential_constraints",
10041        schema: INFORMATION_SCHEMA,
10042        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10043        desc: RelationDesc::builder()
10044            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10045            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10046            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10047            .with_column(
10048                "unique_constraint_catalog",
10049                SqlScalarType::String.nullable(false),
10050            )
10051            .with_column(
10052                "unique_constraint_schema",
10053                SqlScalarType::String.nullable(false),
10054            )
10055            .with_column(
10056                "unique_constraint_name",
10057                SqlScalarType::String.nullable(false),
10058            )
10059            .with_column("match_option", SqlScalarType::String.nullable(false))
10060            .with_column("update_rule", SqlScalarType::String.nullable(false))
10061            .with_column("delete_rule", SqlScalarType::String.nullable(false))
10062            .with_key(vec![])
10063            .finish(),
10064        column_comments: BTreeMap::new(),
10065        sql: "SELECT
10066    NULL::text AS constraint_catalog,
10067    NULL::text AS constraint_schema,
10068    NULL::text AS constraint_name,
10069    NULL::text AS unique_constraint_catalog,
10070    NULL::text AS unique_constraint_schema,
10071    NULL::text AS unique_constraint_name,
10072    NULL::text AS match_option,
10073    NULL::text AS update_rule,
10074    NULL::text AS delete_rule
10075WHERE false",
10076        access: vec![PUBLIC_SELECT],
10077    });
10078
10079pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10080    name: "routines",
10081    schema: INFORMATION_SCHEMA,
10082    oid: oid::VIEW_ROUTINES_OID,
10083    desc: RelationDesc::builder()
10084        .with_column("routine_catalog", SqlScalarType::String.nullable(false))
10085        .with_column("routine_schema", SqlScalarType::String.nullable(false))
10086        .with_column("routine_name", SqlScalarType::String.nullable(false))
10087        .with_column("routine_type", SqlScalarType::String.nullable(false))
10088        .with_column("routine_definition", SqlScalarType::String.nullable(true))
10089        .finish(),
10090    column_comments: BTreeMap::new(),
10091    sql: "SELECT
10092    current_database() as routine_catalog,
10093    s.name AS routine_schema,
10094    f.name AS routine_name,
10095    'FUNCTION' AS routine_type,
10096    NULL::text AS routine_definition
10097FROM mz_catalog.mz_functions f
10098JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10099LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10100WHERE s.database_id IS NULL OR d.name = current_database()",
10101    access: vec![PUBLIC_SELECT],
10102});
10103
10104pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10105    name: "schemata",
10106    schema: INFORMATION_SCHEMA,
10107    oid: oid::VIEW_SCHEMATA_OID,
10108    desc: RelationDesc::builder()
10109        .with_column("catalog_name", SqlScalarType::String.nullable(false))
10110        .with_column("schema_name", SqlScalarType::String.nullable(false))
10111        .finish(),
10112    column_comments: BTreeMap::new(),
10113    sql: "
10114SELECT
10115    current_database() as catalog_name,
10116    s.name AS schema_name
10117FROM mz_catalog.mz_schemas s
10118LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10119WHERE s.database_id IS NULL OR d.name = current_database()",
10120    access: vec![PUBLIC_SELECT],
10121});
10122
10123pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10124    name: "tables",
10125    schema: INFORMATION_SCHEMA,
10126    oid: oid::VIEW_TABLES_OID,
10127    desc: RelationDesc::builder()
10128        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10129        .with_column("table_schema", SqlScalarType::String.nullable(false))
10130        .with_column("table_name", SqlScalarType::String.nullable(false))
10131        .with_column("table_type", SqlScalarType::String.nullable(false))
10132        .finish(),
10133    column_comments: BTreeMap::new(),
10134    sql: "SELECT
10135    current_database() as table_catalog,
10136    s.name AS table_schema,
10137    r.name AS table_name,
10138    CASE r.type
10139        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10140        WHEN 'table' THEN 'BASE TABLE'
10141        ELSE pg_catalog.upper(r.type)
10142    END AS table_type
10143FROM mz_catalog.mz_relations r
10144JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10145LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10146WHERE s.database_id IS NULL OR d.name = current_database()",
10147    access: vec![PUBLIC_SELECT],
10148});
10149
10150pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10151    LazyLock::new(|| BuiltinView {
10152        name: "table_constraints",
10153        schema: INFORMATION_SCHEMA,
10154        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10155        desc: RelationDesc::builder()
10156            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10157            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10158            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10159            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10160            .with_column("table_schema", SqlScalarType::String.nullable(false))
10161            .with_column("table_name", SqlScalarType::String.nullable(false))
10162            .with_column("constraint_type", SqlScalarType::String.nullable(false))
10163            .with_column("is_deferrable", SqlScalarType::String.nullable(false))
10164            .with_column("initially_deferred", SqlScalarType::String.nullable(false))
10165            .with_column("enforced", SqlScalarType::String.nullable(false))
10166            .with_column("nulls_distinct", SqlScalarType::String.nullable(false))
10167            .with_key(vec![])
10168            .finish(),
10169        column_comments: BTreeMap::new(),
10170        sql: "SELECT
10171    NULL::text AS constraint_catalog,
10172    NULL::text AS constraint_schema,
10173    NULL::text AS constraint_name,
10174    NULL::text AS table_catalog,
10175    NULL::text AS table_schema,
10176    NULL::text AS table_name,
10177    NULL::text AS constraint_type,
10178    NULL::text AS is_deferrable,
10179    NULL::text AS initially_deferred,
10180    NULL::text AS enforced,
10181    NULL::text AS nulls_distinct
10182WHERE false",
10183        access: vec![PUBLIC_SELECT],
10184    });
10185
10186pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10187    BuiltinView {
10188        name: "table_privileges",
10189        schema: INFORMATION_SCHEMA,
10190        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10191        desc: RelationDesc::builder()
10192            .with_column("grantor", SqlScalarType::String.nullable(false))
10193            .with_column("grantee", SqlScalarType::String.nullable(true))
10194            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10195            .with_column("table_schema", SqlScalarType::String.nullable(false))
10196            .with_column("table_name", SqlScalarType::String.nullable(false))
10197            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10198            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10199            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10200            .finish(),
10201        column_comments: BTreeMap::new(),
10202        sql: "
10203SELECT
10204    grantor,
10205    grantee,
10206    table_catalog,
10207    table_schema,
10208    table_name,
10209    privilege_type,
10210    is_grantable,
10211    CASE privilege_type
10212        WHEN 'SELECT' THEN 'YES'
10213        ELSE 'NO'
10214    END AS with_hierarchy
10215FROM
10216    (SELECT
10217        grantor.name AS grantor,
10218        CASE mz_internal.mz_aclitem_grantee(privileges)
10219            WHEN 'p' THEN 'PUBLIC'
10220            ELSE grantee.name
10221        END AS grantee,
10222        table_catalog,
10223        table_schema,
10224        table_name,
10225        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10226        -- ADMIN OPTION isn't implemented.
10227        'NO' AS is_grantable
10228    FROM
10229        (SELECT
10230            unnest(relations.privileges) AS privileges,
10231            CASE
10232                WHEN schemas.database_id IS NULL THEN current_database()
10233                ELSE databases.name
10234            END AS table_catalog,
10235            schemas.name AS table_schema,
10236            relations.name AS table_name
10237        FROM mz_catalog.mz_relations AS relations
10238        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10239        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10240        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10241    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10242    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10243WHERE
10244    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10245    -- to pg_has_role. Therefore we need to use a CASE statement.
10246    CASE
10247        WHEN grantee = 'PUBLIC' THEN true
10248        ELSE mz_catalog.mz_is_superuser()
10249            OR pg_has_role(current_role, grantee, 'USAGE')
10250            OR pg_has_role(current_role, grantor, 'USAGE')
10251    END",
10252        access: vec![PUBLIC_SELECT],
10253    }
10254});
10255
10256pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10257    name: "triggers",
10258    schema: INFORMATION_SCHEMA,
10259    oid: oid::VIEW_TRIGGERS_OID,
10260    desc: RelationDesc::builder()
10261        .with_column("trigger_catalog", SqlScalarType::String.nullable(false))
10262        .with_column("trigger_schema", SqlScalarType::String.nullable(false))
10263        .with_column("trigger_name", SqlScalarType::String.nullable(false))
10264        .with_column("event_manipulation", SqlScalarType::String.nullable(false))
10265        .with_column(
10266            "event_object_catalog",
10267            SqlScalarType::String.nullable(false),
10268        )
10269        .with_column("event_object_schema", SqlScalarType::String.nullable(false))
10270        .with_column("event_object_table", SqlScalarType::String.nullable(false))
10271        .with_column("action_order", SqlScalarType::Int32.nullable(false))
10272        .with_column("action_condition", SqlScalarType::String.nullable(false))
10273        .with_column("action_statement", SqlScalarType::String.nullable(false))
10274        .with_column("action_orientation", SqlScalarType::String.nullable(false))
10275        .with_column("action_timing", SqlScalarType::String.nullable(false))
10276        .with_column(
10277            "action_reference_old_table",
10278            SqlScalarType::String.nullable(false),
10279        )
10280        .with_column(
10281            "action_reference_new_table",
10282            SqlScalarType::String.nullable(false),
10283        )
10284        .with_key(vec![])
10285        .finish(),
10286    column_comments: BTreeMap::new(),
10287    sql: "SELECT
10288    NULL::text as trigger_catalog,
10289    NULL::text AS trigger_schema,
10290    NULL::text AS trigger_name,
10291    NULL::text AS event_manipulation,
10292    NULL::text AS event_object_catalog,
10293    NULL::text AS event_object_schema,
10294    NULL::text AS event_object_table,
10295    NULL::integer AS action_order,
10296    NULL::text AS action_condition,
10297    NULL::text AS action_statement,
10298    NULL::text AS action_orientation,
10299    NULL::text AS action_timing,
10300    NULL::text AS action_reference_old_table,
10301    NULL::text AS action_reference_new_table
10302WHERE FALSE",
10303    access: vec![PUBLIC_SELECT],
10304});
10305
10306pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10307    name: "views",
10308    schema: INFORMATION_SCHEMA,
10309    oid: oid::VIEW_VIEWS_OID,
10310    desc: RelationDesc::builder()
10311        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10312        .with_column("table_schema", SqlScalarType::String.nullable(false))
10313        .with_column("table_name", SqlScalarType::String.nullable(false))
10314        .with_column("view_definition", SqlScalarType::String.nullable(false))
10315        .finish(),
10316    column_comments: BTreeMap::new(),
10317    sql: "SELECT
10318    current_database() as table_catalog,
10319    s.name AS table_schema,
10320    v.name AS table_name,
10321    v.definition AS view_definition
10322FROM mz_catalog.mz_views v
10323JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10324LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10325WHERE s.database_id IS NULL OR d.name = current_database()",
10326    access: vec![PUBLIC_SELECT],
10327});
10328
10329pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10330    LazyLock::new(|| BuiltinView {
10331        name: "character_sets",
10332        schema: INFORMATION_SCHEMA,
10333        oid: oid::VIEW_CHARACTER_SETS_OID,
10334        desc: RelationDesc::builder()
10335            .with_column(
10336                "character_set_catalog",
10337                SqlScalarType::String.nullable(true),
10338            )
10339            .with_column("character_set_schema", SqlScalarType::String.nullable(true))
10340            .with_column("character_set_name", SqlScalarType::String.nullable(false))
10341            .with_column(
10342                "character_repertoire",
10343                SqlScalarType::String.nullable(false),
10344            )
10345            .with_column("form_of_use", SqlScalarType::String.nullable(false))
10346            .with_column(
10347                "default_collate_catalog",
10348                SqlScalarType::String.nullable(false),
10349            )
10350            .with_column(
10351                "default_collate_schema",
10352                SqlScalarType::String.nullable(false),
10353            )
10354            .with_column(
10355                "default_collate_name",
10356                SqlScalarType::String.nullable(false),
10357            )
10358            .with_key(vec![])
10359            .finish(),
10360        column_comments: BTreeMap::new(),
10361        sql: "SELECT
10362    NULL as character_set_catalog,
10363    NULL as character_set_schema,
10364    'UTF8' as character_set_name,
10365    'UCS' as character_repertoire,
10366    'UTF8' as form_of_use,
10367    current_database() as default_collate_catalog,
10368    'pg_catalog' as default_collate_schema,
10369    'en_US.utf8' as default_collate_name",
10370        access: vec![PUBLIC_SELECT],
10371    });
10372
10373// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10374// codes a collation of 'C' for every database, so we could copy that here.
10375pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10376    name: "pg_collation",
10377    schema: PG_CATALOG_SCHEMA,
10378    oid: oid::VIEW_PG_COLLATION_OID,
10379    desc: RelationDesc::builder()
10380        .with_column("oid", SqlScalarType::Oid.nullable(false))
10381        .with_column("collname", SqlScalarType::String.nullable(false))
10382        .with_column("collnamespace", SqlScalarType::Oid.nullable(false))
10383        .with_column("collowner", SqlScalarType::Oid.nullable(false))
10384        .with_column("collprovider", SqlScalarType::PgLegacyChar.nullable(false))
10385        .with_column("collisdeterministic", SqlScalarType::Bool.nullable(false))
10386        .with_column("collencoding", SqlScalarType::Int32.nullable(false))
10387        .with_column("collcollate", SqlScalarType::String.nullable(false))
10388        .with_column("collctype", SqlScalarType::String.nullable(false))
10389        .with_column("collversion", SqlScalarType::String.nullable(false))
10390        .with_key(vec![])
10391        .finish(),
10392    column_comments: BTreeMap::new(),
10393    sql: "
10394SELECT
10395    NULL::pg_catalog.oid AS oid,
10396    NULL::pg_catalog.text AS collname,
10397    NULL::pg_catalog.oid AS collnamespace,
10398    NULL::pg_catalog.oid AS collowner,
10399    NULL::pg_catalog.\"char\" AS collprovider,
10400    NULL::pg_catalog.bool AS collisdeterministic,
10401    NULL::pg_catalog.int4 AS collencoding,
10402    NULL::pg_catalog.text AS collcollate,
10403    NULL::pg_catalog.text AS collctype,
10404    NULL::pg_catalog.text AS collversion
10405WHERE false",
10406    access: vec![PUBLIC_SELECT],
10407});
10408
10409// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10410pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10411    name: "pg_policy",
10412    schema: PG_CATALOG_SCHEMA,
10413    oid: oid::VIEW_PG_POLICY_OID,
10414    desc: RelationDesc::builder()
10415        .with_column("oid", SqlScalarType::Oid.nullable(false))
10416        .with_column("polname", SqlScalarType::String.nullable(false))
10417        .with_column("polrelid", SqlScalarType::Oid.nullable(false))
10418        .with_column("polcmd", SqlScalarType::PgLegacyChar.nullable(false))
10419        .with_column("polpermissive", SqlScalarType::Bool.nullable(false))
10420        .with_column(
10421            "polroles",
10422            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10423        )
10424        .with_column("polqual", SqlScalarType::String.nullable(false))
10425        .with_column("polwithcheck", SqlScalarType::String.nullable(false))
10426        .with_key(vec![])
10427        .finish(),
10428    column_comments: BTreeMap::new(),
10429    sql: "
10430SELECT
10431    NULL::pg_catalog.oid AS oid,
10432    NULL::pg_catalog.text AS polname,
10433    NULL::pg_catalog.oid AS polrelid,
10434    NULL::pg_catalog.\"char\" AS polcmd,
10435    NULL::pg_catalog.bool AS polpermissive,
10436    NULL::pg_catalog.oid[] AS polroles,
10437    NULL::pg_catalog.text AS polqual,
10438    NULL::pg_catalog.text AS polwithcheck
10439WHERE false",
10440    access: vec![PUBLIC_SELECT],
10441});
10442
10443// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10444pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10445    name: "pg_inherits",
10446    schema: PG_CATALOG_SCHEMA,
10447    oid: oid::VIEW_PG_INHERITS_OID,
10448    desc: RelationDesc::builder()
10449        .with_column("inhrelid", SqlScalarType::Oid.nullable(false))
10450        .with_column("inhparent", SqlScalarType::Oid.nullable(false))
10451        .with_column("inhseqno", SqlScalarType::Int32.nullable(false))
10452        .with_column("inhdetachpending", SqlScalarType::Bool.nullable(false))
10453        .with_key(vec![])
10454        .finish(),
10455    column_comments: BTreeMap::new(),
10456    sql: "
10457SELECT
10458    NULL::pg_catalog.oid AS inhrelid,
10459    NULL::pg_catalog.oid AS inhparent,
10460    NULL::pg_catalog.int4 AS inhseqno,
10461    NULL::pg_catalog.bool AS inhdetachpending
10462WHERE false",
10463    access: vec![PUBLIC_SELECT],
10464});
10465
10466pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10467    name: "pg_locks",
10468    schema: PG_CATALOG_SCHEMA,
10469    oid: oid::VIEW_PG_LOCKS_OID,
10470    desc: RelationDesc::builder()
10471        .with_column("locktype", SqlScalarType::String.nullable(false))
10472        .with_column("database", SqlScalarType::Oid.nullable(false))
10473        .with_column("relation", SqlScalarType::Oid.nullable(false))
10474        .with_column("page", SqlScalarType::Int32.nullable(false))
10475        .with_column("tuple", SqlScalarType::Int16.nullable(false))
10476        .with_column("virtualxid", SqlScalarType::String.nullable(false))
10477        .with_column("transactionid", SqlScalarType::String.nullable(false))
10478        .with_column("classid", SqlScalarType::Oid.nullable(false))
10479        .with_column("objid", SqlScalarType::Oid.nullable(false))
10480        .with_column("objsubid", SqlScalarType::Int16.nullable(false))
10481        .with_column("virtualtransaction", SqlScalarType::String.nullable(false))
10482        .with_column("pid", SqlScalarType::Int32.nullable(false))
10483        .with_column("mode", SqlScalarType::String.nullable(false))
10484        .with_column("granted", SqlScalarType::Bool.nullable(false))
10485        .with_column("fastpath", SqlScalarType::Bool.nullable(false))
10486        .with_column(
10487            "waitstart",
10488            SqlScalarType::TimestampTz { precision: None }.nullable(false),
10489        )
10490        .with_key(vec![])
10491        .finish(),
10492    column_comments: BTreeMap::new(),
10493    sql: "
10494SELECT
10495-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10496    NULL::pg_catalog.text AS locktype,
10497    NULL::pg_catalog.oid AS database,
10498    NULL::pg_catalog.oid AS relation,
10499    NULL::pg_catalog.int4 AS page,
10500    NULL::pg_catalog.int2 AS tuple,
10501    NULL::pg_catalog.text AS virtualxid,
10502    NULL::pg_catalog.text AS transactionid,
10503    NULL::pg_catalog.oid AS classid,
10504    NULL::pg_catalog.oid AS objid,
10505    NULL::pg_catalog.int2 AS objsubid,
10506    NULL::pg_catalog.text AS virtualtransaction,
10507    NULL::pg_catalog.int4 AS pid,
10508    NULL::pg_catalog.text AS mode,
10509    NULL::pg_catalog.bool AS granted,
10510    NULL::pg_catalog.bool AS fastpath,
10511    NULL::pg_catalog.timestamptz AS waitstart
10512WHERE false",
10513    access: vec![PUBLIC_SELECT],
10514});
10515
10516/// Peeled version of `PG_AUTHID`: Excludes the columns rolcreaterole and rolcreatedb, to make this
10517/// view indexable.
10518pub static PG_AUTHID_CORE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10519    name: "pg_authid_core",
10520    schema: MZ_INTERNAL_SCHEMA,
10521    oid: oid::VIEW_PG_AUTHID_CORE_OID,
10522    desc: RelationDesc::builder()
10523        .with_column("oid", SqlScalarType::Oid.nullable(false))
10524        .with_column("rolname", SqlScalarType::String.nullable(false))
10525        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10526        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10527        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10528        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10529        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10530        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10531        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10532        .with_column(
10533            "rolvaliduntil",
10534            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10535        )
10536        .finish(),
10537    column_comments: BTreeMap::new(),
10538    sql: r#"
10539SELECT
10540    r.oid AS oid,
10541    r.name AS rolname,
10542    rolsuper,
10543    inherit AS rolinherit,
10544    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
10545    -- MZ doesn't support replication in the same way Postgres does
10546    false AS rolreplication,
10547    -- MZ doesn't how row level security
10548    false AS rolbypassrls,
10549    -- MZ doesn't have a connection limit
10550    -1 AS rolconnlimit,
10551    a.password_hash AS rolpassword,
10552    NULL::pg_catalog.timestamptz AS rolvaliduntil
10553FROM mz_catalog.mz_roles r
10554LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
10555    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10556});
10557
10558pub const PG_AUTHID_CORE_IND: BuiltinIndex = BuiltinIndex {
10559    name: "pg_authid_core_ind",
10560    schema: MZ_INTERNAL_SCHEMA,
10561    oid: oid::INDEX_PG_AUTHID_CORE_IND_OID,
10562    sql: "IN CLUSTER mz_catalog_server
10563ON mz_internal.pg_authid_core (rolname)",
10564    is_retained_metrics_object: false,
10565};
10566
10567pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10568    name: "pg_authid",
10569    schema: PG_CATALOG_SCHEMA,
10570    oid: oid::VIEW_PG_AUTHID_OID,
10571    desc: RelationDesc::builder()
10572        .with_column("oid", SqlScalarType::Oid.nullable(false))
10573        .with_column("rolname", SqlScalarType::String.nullable(false))
10574        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10575        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10576        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10577        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10578        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10579        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10580        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10581        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10582        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10583        .with_column(
10584            "rolvaliduntil",
10585            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10586        )
10587        .finish(),
10588    column_comments: BTreeMap::new(),
10589    // The `has_system_privilege` invocations for `rolcreaterole` and `rolcreatedb` get expanded
10590    // into very complex subqueries. If we put them into the SELECT clause directly, decorrelation
10591    // produces a very complex plan that the optimizer has a hard time dealing with. In particular,
10592    // the optimizer fails to reduce a query like `SELECT oid FROM pg_authid` to a simple lookup on
10593    // the `pg_authid_core` index and instead produces a large plan that contains a bunch of
10594    // expensive joins and arrangements.
10595    //
10596    // The proper fix is likely to implement `has_system_privileges` in Rust, but for now we work
10597    // around the issue by manually decorrelating `rolcreaterole` and `rolcreatedb`. Note that to
10598    // get the desired behavior we need to make sure that the join with `extra` doesn't change the
10599    // cardinality of `pg_authid_core` (otherwise it can never be optimized away). We ensure this
10600    // by:
10601    //  * using a `LEFT JOIN`, so the optimizer knows that left elements are never filtered
10602    //  * applying a `DISTINCT ON` to the CTE, so the optimizer knows that left elements are never
10603    //    duplicated
10604    sql: r#"
10605WITH extra AS (
10606    SELECT
10607        DISTINCT ON (oid)
10608        oid,
10609        mz_catalog.has_system_privilege(oid, 'CREATEROLE') AS rolcreaterole,
10610        mz_catalog.has_system_privilege(oid, 'CREATEDB') AS rolcreatedb
10611    FROM mz_internal.pg_authid_core
10612)
10613SELECT
10614    oid,
10615    rolname,
10616    rolsuper,
10617    rolinherit,
10618    extra.rolcreaterole,
10619    extra.rolcreatedb,
10620    rolcanlogin,
10621    rolreplication,
10622    rolbypassrls,
10623    rolconnlimit,
10624    rolpassword,
10625    rolvaliduntil
10626FROM mz_internal.pg_authid_core
10627LEFT JOIN extra USING (oid)"#,
10628    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10629});
10630
10631pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10632    name: "pg_aggregate",
10633    schema: PG_CATALOG_SCHEMA,
10634    oid: oid::VIEW_PG_AGGREGATE_OID,
10635    desc: RelationDesc::builder()
10636        .with_column("aggfnoid", SqlScalarType::Oid.nullable(false))
10637        .with_column("aggkind", SqlScalarType::String.nullable(false))
10638        .with_column("aggnumdirectargs", SqlScalarType::Int16.nullable(false))
10639        .with_column("aggtransfn", SqlScalarType::RegProc.nullable(true))
10640        .with_column("aggfinalfn", SqlScalarType::RegProc.nullable(false))
10641        .with_column("aggcombinefn", SqlScalarType::RegProc.nullable(false))
10642        .with_column("aggserialfn", SqlScalarType::RegProc.nullable(false))
10643        .with_column("aggdeserialfn", SqlScalarType::RegProc.nullable(false))
10644        .with_column("aggmtransfn", SqlScalarType::RegProc.nullable(false))
10645        .with_column("aggminvtransfn", SqlScalarType::RegProc.nullable(false))
10646        .with_column("aggmfinalfn", SqlScalarType::RegProc.nullable(false))
10647        .with_column("aggfinalextra", SqlScalarType::Bool.nullable(false))
10648        .with_column("aggmfinalextra", SqlScalarType::Bool.nullable(false))
10649        .with_column("aggfinalmodify", SqlScalarType::PgLegacyChar.nullable(true))
10650        .with_column(
10651            "aggmfinalmodify",
10652            SqlScalarType::PgLegacyChar.nullable(true),
10653        )
10654        .with_column("aggsortop", SqlScalarType::Oid.nullable(false))
10655        .with_column("aggtranstype", SqlScalarType::Oid.nullable(true))
10656        .with_column("aggtransspace", SqlScalarType::Int32.nullable(true))
10657        .with_column("aggmtranstype", SqlScalarType::Oid.nullable(false))
10658        .with_column("aggmtransspace", SqlScalarType::Int32.nullable(true))
10659        .with_column("agginitval", SqlScalarType::String.nullable(true))
10660        .with_column("aggminitval", SqlScalarType::String.nullable(true))
10661        .finish(),
10662    column_comments: BTreeMap::new(),
10663    sql: "SELECT
10664    a.oid as aggfnoid,
10665    -- Currently Materialize only support 'normal' aggregate functions.
10666    a.agg_kind as aggkind,
10667    a.agg_num_direct_args as aggnumdirectargs,
10668    -- Materialize doesn't support these fields.
10669    NULL::pg_catalog.regproc as aggtransfn,
10670    '0'::pg_catalog.regproc as aggfinalfn,
10671    '0'::pg_catalog.regproc as aggcombinefn,
10672    '0'::pg_catalog.regproc as aggserialfn,
10673    '0'::pg_catalog.regproc as aggdeserialfn,
10674    '0'::pg_catalog.regproc as aggmtransfn,
10675    '0'::pg_catalog.regproc as aggminvtransfn,
10676    '0'::pg_catalog.regproc as aggmfinalfn,
10677    false as aggfinalextra,
10678    false as aggmfinalextra,
10679    NULL::pg_catalog.\"char\" AS aggfinalmodify,
10680    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
10681    '0'::pg_catalog.oid as aggsortop,
10682    NULL::pg_catalog.oid as aggtranstype,
10683    NULL::pg_catalog.int4 as aggtransspace,
10684    '0'::pg_catalog.oid as aggmtranstype,
10685    NULL::pg_catalog.int4 as aggmtransspace,
10686    NULL::pg_catalog.text as agginitval,
10687    NULL::pg_catalog.text as aggminitval
10688FROM mz_internal.mz_aggregates a",
10689    access: vec![PUBLIC_SELECT],
10690});
10691
10692pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10693    name: "pg_trigger",
10694    schema: PG_CATALOG_SCHEMA,
10695    oid: oid::VIEW_PG_TRIGGER_OID,
10696    desc: RelationDesc::builder()
10697        .with_column("oid", SqlScalarType::Oid.nullable(false))
10698        .with_column("tgrelid", SqlScalarType::Oid.nullable(false))
10699        .with_column("tgparentid", SqlScalarType::Oid.nullable(false))
10700        .with_column("tgname", SqlScalarType::String.nullable(false))
10701        .with_column("tgfoid", SqlScalarType::Oid.nullable(false))
10702        .with_column("tgtype", SqlScalarType::Int16.nullable(false))
10703        .with_column("tgenabled", SqlScalarType::PgLegacyChar.nullable(false))
10704        .with_column("tgisinternal", SqlScalarType::Bool.nullable(false))
10705        .with_column("tgconstrrelid", SqlScalarType::Oid.nullable(false))
10706        .with_column("tgconstrindid", SqlScalarType::Oid.nullable(false))
10707        .with_column("tgconstraint", SqlScalarType::Oid.nullable(false))
10708        .with_column("tgdeferrable", SqlScalarType::Bool.nullable(false))
10709        .with_column("tginitdeferred", SqlScalarType::Bool.nullable(false))
10710        .with_column("tgnargs", SqlScalarType::Int16.nullable(false))
10711        .with_column("tgattr", SqlScalarType::Int2Vector.nullable(false))
10712        .with_column("tgargs", SqlScalarType::Bytes.nullable(false))
10713        .with_column("tgqual", SqlScalarType::String.nullable(false))
10714        .with_column("tgoldtable", SqlScalarType::String.nullable(false))
10715        .with_column("tgnewtable", SqlScalarType::String.nullable(false))
10716        .with_key(vec![])
10717        .finish(),
10718    column_comments: BTreeMap::new(),
10719    sql: "SELECT
10720    -- MZ doesn't support triggers so all of these fields are NULL.
10721    NULL::pg_catalog.oid AS oid,
10722    NULL::pg_catalog.oid AS tgrelid,
10723    NULL::pg_catalog.oid AS tgparentid,
10724    NULL::pg_catalog.text AS tgname,
10725    NULL::pg_catalog.oid AS tgfoid,
10726    NULL::pg_catalog.int2 AS tgtype,
10727    NULL::pg_catalog.\"char\" AS tgenabled,
10728    NULL::pg_catalog.bool AS tgisinternal,
10729    NULL::pg_catalog.oid AS tgconstrrelid,
10730    NULL::pg_catalog.oid AS tgconstrindid,
10731    NULL::pg_catalog.oid AS tgconstraint,
10732    NULL::pg_catalog.bool AS tgdeferrable,
10733    NULL::pg_catalog.bool AS tginitdeferred,
10734    NULL::pg_catalog.int2 AS tgnargs,
10735    NULL::pg_catalog.int2vector AS tgattr,
10736    NULL::pg_catalog.bytea AS tgargs,
10737    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
10738    -- uses text as a placeholder, so we'll follow their lead here.
10739    NULL::pg_catalog.text AS tgqual,
10740    NULL::pg_catalog.text AS tgoldtable,
10741    NULL::pg_catalog.text AS tgnewtable
10742WHERE false
10743    ",
10744    access: vec![PUBLIC_SELECT],
10745});
10746
10747pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10748    name: "pg_rewrite",
10749    schema: PG_CATALOG_SCHEMA,
10750    oid: oid::VIEW_PG_REWRITE_OID,
10751    desc: RelationDesc::builder()
10752        .with_column("oid", SqlScalarType::Oid.nullable(false))
10753        .with_column("rulename", SqlScalarType::String.nullable(false))
10754        .with_column("ev_class", SqlScalarType::Oid.nullable(false))
10755        .with_column("ev_type", SqlScalarType::PgLegacyChar.nullable(false))
10756        .with_column("ev_enabled", SqlScalarType::PgLegacyChar.nullable(false))
10757        .with_column("is_instead", SqlScalarType::Bool.nullable(false))
10758        .with_column("ev_qual", SqlScalarType::String.nullable(false))
10759        .with_column("ev_action", SqlScalarType::String.nullable(false))
10760        .with_key(vec![])
10761        .finish(),
10762    column_comments: BTreeMap::new(),
10763    sql: "SELECT
10764    -- MZ doesn't support rewrite rules so all of these fields are NULL.
10765    NULL::pg_catalog.oid AS oid,
10766    NULL::pg_catalog.text AS rulename,
10767    NULL::pg_catalog.oid AS ev_class,
10768    NULL::pg_catalog.\"char\" AS ev_type,
10769    NULL::pg_catalog.\"char\" AS ev_enabled,
10770    NULL::pg_catalog.bool AS is_instead,
10771    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
10772    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
10773    NULL::pg_catalog.text AS ev_qual,
10774    NULL::pg_catalog.text AS ev_action
10775WHERE false
10776    ",
10777    access: vec![PUBLIC_SELECT],
10778});
10779
10780pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10781    name: "pg_extension",
10782    schema: PG_CATALOG_SCHEMA,
10783    oid: oid::VIEW_PG_EXTENSION_OID,
10784    desc: RelationDesc::builder()
10785        .with_column("oid", SqlScalarType::Oid.nullable(false))
10786        .with_column("extname", SqlScalarType::String.nullable(false))
10787        .with_column("extowner", SqlScalarType::Oid.nullable(false))
10788        .with_column("extnamespace", SqlScalarType::Oid.nullable(false))
10789        .with_column("extrelocatable", SqlScalarType::Bool.nullable(false))
10790        .with_column("extversion", SqlScalarType::String.nullable(false))
10791        .with_column(
10792            "extconfig",
10793            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10794        )
10795        .with_column(
10796            "extcondition",
10797            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
10798        )
10799        .with_key(vec![])
10800        .finish(),
10801    column_comments: BTreeMap::new(),
10802    sql: "SELECT
10803    -- MZ doesn't support extensions so all of these fields are NULL.
10804    NULL::pg_catalog.oid AS oid,
10805    NULL::pg_catalog.text AS extname,
10806    NULL::pg_catalog.oid AS extowner,
10807    NULL::pg_catalog.oid AS extnamespace,
10808    NULL::pg_catalog.bool AS extrelocatable,
10809    NULL::pg_catalog.text AS extversion,
10810    NULL::pg_catalog.oid[] AS extconfig,
10811    NULL::pg_catalog.text[] AS extcondition
10812WHERE false
10813    ",
10814    access: vec![PUBLIC_SELECT],
10815});
10816
10817pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10818    name: "mz_show_all_objects",
10819    schema: MZ_INTERNAL_SCHEMA,
10820    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
10821    desc: RelationDesc::builder()
10822        .with_column("schema_id", SqlScalarType::String.nullable(false))
10823        .with_column("name", SqlScalarType::String.nullable(false))
10824        .with_column("type", SqlScalarType::String.nullable(false))
10825        .with_column("comment", SqlScalarType::String.nullable(false))
10826        .finish(),
10827    column_comments: BTreeMap::new(),
10828    sql: "WITH comments AS (
10829        SELECT id, object_type, comment
10830        FROM mz_internal.mz_comments
10831        WHERE object_sub_id IS NULL
10832    )
10833    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
10834    FROM mz_catalog.mz_objects AS objs
10835    LEFT JOIN comments ON objs.id = comments.id
10836    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
10837    access: vec![PUBLIC_SELECT],
10838});
10839
10840pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
10841    BuiltinView {
10842    name: "mz_show_clusters",
10843    schema: MZ_INTERNAL_SCHEMA,
10844    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
10845    desc: RelationDesc::builder()
10846        .with_column("name", SqlScalarType::String.nullable(false))
10847        .with_column("replicas", SqlScalarType::String.nullable(true))
10848        .with_column("comment", SqlScalarType::String.nullable(false))
10849        .finish(),
10850    column_comments: BTreeMap::new(),
10851    sql: "
10852    WITH clusters AS (
10853        SELECT
10854            mc.id,
10855            mc.name,
10856            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
10857        FROM mz_catalog.mz_clusters mc
10858        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
10859        ON mc.id = mcr.cluster_id
10860        GROUP BY mc.id, mc.name
10861    ),
10862    comments AS (
10863        SELECT id, comment
10864        FROM mz_internal.mz_comments
10865        WHERE object_type = 'cluster' AND object_sub_id IS NULL
10866    )
10867    SELECT name, replicas, COALESCE(comment, '') as comment
10868    FROM clusters
10869    LEFT JOIN comments ON clusters.id = comments.id",
10870    access: vec![PUBLIC_SELECT],
10871}
10872});
10873
10874pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10875    name: "mz_show_secrets",
10876    schema: MZ_INTERNAL_SCHEMA,
10877    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
10878    desc: RelationDesc::builder()
10879        .with_column("schema_id", SqlScalarType::String.nullable(false))
10880        .with_column("name", SqlScalarType::String.nullable(false))
10881        .with_column("comment", SqlScalarType::String.nullable(false))
10882        .finish(),
10883    column_comments: BTreeMap::new(),
10884    sql: "WITH comments AS (
10885        SELECT id, comment
10886        FROM mz_internal.mz_comments
10887        WHERE object_type = 'secret' AND object_sub_id IS NULL
10888    )
10889    SELECT schema_id, name, COALESCE(comment, '') as comment
10890    FROM mz_catalog.mz_secrets secrets
10891    LEFT JOIN comments ON secrets.id = comments.id",
10892    access: vec![PUBLIC_SELECT],
10893});
10894
10895pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10896    name: "mz_show_columns",
10897    schema: MZ_INTERNAL_SCHEMA,
10898    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
10899    desc: RelationDesc::builder()
10900        .with_column("id", SqlScalarType::String.nullable(false))
10901        .with_column("name", SqlScalarType::String.nullable(false))
10902        .with_column("nullable", SqlScalarType::Bool.nullable(false))
10903        .with_column("type", SqlScalarType::String.nullable(false))
10904        .with_column("position", SqlScalarType::UInt64.nullable(false))
10905        .with_column("comment", SqlScalarType::String.nullable(false))
10906        .finish(),
10907    column_comments: BTreeMap::new(),
10908    sql: "
10909    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
10910    FROM mz_catalog.mz_columns columns
10911    LEFT JOIN mz_internal.mz_comments comments
10912    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
10913    access: vec![PUBLIC_SELECT],
10914});
10915
10916pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10917    name: "mz_show_databases",
10918    schema: MZ_INTERNAL_SCHEMA,
10919    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
10920    desc: RelationDesc::builder()
10921        .with_column("name", SqlScalarType::String.nullable(false))
10922        .with_column("comment", SqlScalarType::String.nullable(false))
10923        .finish(),
10924    column_comments: BTreeMap::new(),
10925    sql: "WITH comments AS (
10926        SELECT id, comment
10927        FROM mz_internal.mz_comments
10928        WHERE object_type = 'database' AND object_sub_id IS NULL
10929    )
10930    SELECT name, COALESCE(comment, '') as comment
10931    FROM mz_catalog.mz_databases databases
10932    LEFT JOIN comments ON databases.id = comments.id",
10933    access: vec![PUBLIC_SELECT],
10934});
10935
10936pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10937    name: "mz_show_schemas",
10938    schema: MZ_INTERNAL_SCHEMA,
10939    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
10940    desc: RelationDesc::builder()
10941        .with_column("database_id", SqlScalarType::String.nullable(true))
10942        .with_column("name", SqlScalarType::String.nullable(false))
10943        .with_column("comment", SqlScalarType::String.nullable(false))
10944        .finish(),
10945    column_comments: BTreeMap::new(),
10946    sql: "WITH comments AS (
10947        SELECT id, comment
10948        FROM mz_internal.mz_comments
10949        WHERE object_type = 'schema' AND object_sub_id IS NULL
10950    )
10951    SELECT database_id, name, COALESCE(comment, '') as comment
10952    FROM mz_catalog.mz_schemas schemas
10953    LEFT JOIN comments ON schemas.id = comments.id",
10954    access: vec![PUBLIC_SELECT],
10955});
10956
10957pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10958    name: "mz_show_roles",
10959    schema: MZ_INTERNAL_SCHEMA,
10960    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
10961    desc: RelationDesc::builder()
10962        .with_column("name", SqlScalarType::String.nullable(false))
10963        .with_column("comment", SqlScalarType::String.nullable(false))
10964        .finish(),
10965    column_comments: BTreeMap::new(),
10966    sql: "WITH comments AS (
10967        SELECT id, comment
10968        FROM mz_internal.mz_comments
10969        WHERE object_type = 'role' AND object_sub_id IS NULL
10970    )
10971    SELECT name, COALESCE(comment, '') as comment
10972    FROM mz_catalog.mz_roles roles
10973    LEFT JOIN comments ON roles.id = comments.id
10974    WHERE roles.id NOT LIKE 's%'
10975      AND roles.id NOT LIKE 'g%'",
10976    access: vec![PUBLIC_SELECT],
10977});
10978
10979pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10980    name: "mz_show_tables",
10981    schema: MZ_INTERNAL_SCHEMA,
10982    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
10983    desc: RelationDesc::builder()
10984        .with_column("schema_id", SqlScalarType::String.nullable(false))
10985        .with_column("name", SqlScalarType::String.nullable(false))
10986        .with_column("comment", SqlScalarType::String.nullable(false))
10987        .with_column("source_id", SqlScalarType::String.nullable(true))
10988        .finish(),
10989    column_comments: BTreeMap::new(),
10990    sql: "WITH comments AS (
10991        SELECT id, comment
10992        FROM mz_internal.mz_comments
10993        WHERE object_type = 'table' AND object_sub_id IS NULL
10994    )
10995    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
10996    FROM mz_catalog.mz_tables tables
10997    LEFT JOIN comments ON tables.id = comments.id",
10998    access: vec![PUBLIC_SELECT],
10999});
11000
11001pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11002    name: "mz_show_views",
11003    schema: MZ_INTERNAL_SCHEMA,
11004    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
11005    desc: RelationDesc::builder()
11006        .with_column("schema_id", SqlScalarType::String.nullable(false))
11007        .with_column("name", SqlScalarType::String.nullable(false))
11008        .with_column("comment", SqlScalarType::String.nullable(false))
11009        .finish(),
11010    column_comments: BTreeMap::new(),
11011    sql: "WITH comments AS (
11012        SELECT id, comment
11013        FROM mz_internal.mz_comments
11014        WHERE object_type = 'view' AND object_sub_id IS NULL
11015    )
11016    SELECT schema_id, name, COALESCE(comment, '') as comment
11017    FROM mz_catalog.mz_views views
11018    LEFT JOIN comments ON views.id = comments.id",
11019    access: vec![PUBLIC_SELECT],
11020});
11021
11022pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11023    name: "mz_show_types",
11024    schema: MZ_INTERNAL_SCHEMA,
11025    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
11026    desc: RelationDesc::builder()
11027        .with_column("schema_id", SqlScalarType::String.nullable(false))
11028        .with_column("name", SqlScalarType::String.nullable(false))
11029        .with_column("comment", SqlScalarType::String.nullable(false))
11030        .finish(),
11031    column_comments: BTreeMap::new(),
11032    sql: "WITH comments AS (
11033        SELECT id, comment
11034        FROM mz_internal.mz_comments
11035        WHERE object_type = 'type' AND object_sub_id IS NULL
11036    )
11037    SELECT schema_id, name, COALESCE(comment, '') as comment
11038    FROM mz_catalog.mz_types types
11039    LEFT JOIN comments ON types.id = comments.id",
11040    access: vec![PUBLIC_SELECT],
11041});
11042
11043pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11044    name: "mz_show_connections",
11045    schema: MZ_INTERNAL_SCHEMA,
11046    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
11047    desc: RelationDesc::builder()
11048        .with_column("schema_id", SqlScalarType::String.nullable(false))
11049        .with_column("name", SqlScalarType::String.nullable(false))
11050        .with_column("type", SqlScalarType::String.nullable(false))
11051        .with_column("comment", SqlScalarType::String.nullable(false))
11052        .finish(),
11053    column_comments: BTreeMap::new(),
11054    sql: "WITH comments AS (
11055        SELECT id, comment
11056        FROM mz_internal.mz_comments
11057        WHERE object_type = 'connection' AND object_sub_id IS NULL
11058    )
11059    SELECT schema_id, name, type, COALESCE(comment, '') as comment
11060    FROM mz_catalog.mz_connections connections
11061    LEFT JOIN comments ON connections.id = comments.id",
11062    access: vec![PUBLIC_SELECT],
11063});
11064
11065pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11066    name: "mz_show_sources",
11067    schema: MZ_INTERNAL_SCHEMA,
11068    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
11069    desc: RelationDesc::builder()
11070        .with_column("id", SqlScalarType::String.nullable(false))
11071        .with_column("name", SqlScalarType::String.nullable(false))
11072        .with_column("type", SqlScalarType::String.nullable(false))
11073        .with_column("cluster", SqlScalarType::String.nullable(true))
11074        .with_column("schema_id", SqlScalarType::String.nullable(false))
11075        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11076        .with_column("comment", SqlScalarType::String.nullable(false))
11077        .finish(),
11078    column_comments: BTreeMap::new(),
11079    sql: "
11080WITH comments AS (
11081    SELECT id, comment
11082    FROM mz_internal.mz_comments
11083    WHERE object_type = 'source' AND object_sub_id IS NULL
11084)
11085SELECT
11086    sources.id,
11087    sources.name,
11088    sources.type,
11089    clusters.name AS cluster,
11090    schema_id,
11091    cluster_id,
11092    COALESCE(comments.comment, '') as comment
11093FROM
11094    mz_catalog.mz_sources AS sources
11095        LEFT JOIN
11096            mz_catalog.mz_clusters AS clusters
11097            ON clusters.id = sources.cluster_id
11098        LEFT JOIN comments ON sources.id = comments.id",
11099    access: vec![PUBLIC_SELECT],
11100});
11101
11102pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11103    name: "mz_show_sinks",
11104    schema: MZ_INTERNAL_SCHEMA,
11105    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11106    desc: RelationDesc::builder()
11107        .with_column("id", SqlScalarType::String.nullable(false))
11108        .with_column("name", SqlScalarType::String.nullable(false))
11109        .with_column("type", SqlScalarType::String.nullable(false))
11110        .with_column("cluster", SqlScalarType::String.nullable(false))
11111        .with_column("schema_id", SqlScalarType::String.nullable(false))
11112        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11113        .with_column("comment", SqlScalarType::String.nullable(false))
11114        .finish(),
11115    column_comments: BTreeMap::new(),
11116    sql: "
11117WITH comments AS (
11118    SELECT id, comment
11119    FROM mz_internal.mz_comments
11120    WHERE object_type = 'sink' AND object_sub_id IS NULL
11121)
11122SELECT
11123    sinks.id,
11124    sinks.name,
11125    sinks.type,
11126    clusters.name AS cluster,
11127    schema_id,
11128    cluster_id,
11129    COALESCE(comments.comment, '') as comment
11130FROM
11131    mz_catalog.mz_sinks AS sinks
11132    JOIN
11133        mz_catalog.mz_clusters AS clusters
11134        ON clusters.id = sinks.cluster_id
11135    LEFT JOIN comments ON sinks.id = comments.id",
11136    access: vec![PUBLIC_SELECT],
11137});
11138
11139pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11140    name: "mz_show_materialized_views",
11141    schema: MZ_INTERNAL_SCHEMA,
11142    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11143    desc: RelationDesc::builder()
11144        .with_column("id", SqlScalarType::String.nullable(false))
11145        .with_column("name", SqlScalarType::String.nullable(false))
11146        .with_column("cluster", SqlScalarType::String.nullable(false))
11147        .with_column("schema_id", SqlScalarType::String.nullable(false))
11148        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11149        .with_column("comment", SqlScalarType::String.nullable(false))
11150        .finish(),
11151    column_comments: BTreeMap::new(),
11152    sql: "
11153WITH
11154    comments AS (
11155        SELECT id, comment
11156        FROM mz_internal.mz_comments
11157        WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11158    )
11159SELECT
11160    mviews.id as id,
11161    mviews.name,
11162    clusters.name AS cluster,
11163    schema_id,
11164    cluster_id,
11165    COALESCE(comments.comment, '') as comment
11166FROM
11167    mz_catalog.mz_materialized_views AS mviews
11168    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11169    LEFT JOIN comments ON mviews.id = comments.id",
11170    access: vec![PUBLIC_SELECT],
11171});
11172
11173pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11174    name: "mz_show_indexes",
11175    schema: MZ_INTERNAL_SCHEMA,
11176    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11177    desc: RelationDesc::builder()
11178        .with_column("id", SqlScalarType::String.nullable(false))
11179        .with_column("name", SqlScalarType::String.nullable(false))
11180        .with_column("on", SqlScalarType::String.nullable(false))
11181        .with_column("cluster", SqlScalarType::String.nullable(false))
11182        .with_column(
11183            "key",
11184            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11185        )
11186        .with_column("on_id", SqlScalarType::String.nullable(false))
11187        .with_column("schema_id", SqlScalarType::String.nullable(false))
11188        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11189        .with_column("comment", SqlScalarType::String.nullable(false))
11190        .finish(),
11191    column_comments: BTreeMap::new(),
11192    sql: "
11193WITH comments AS (
11194    SELECT id, comment
11195    FROM mz_internal.mz_comments
11196    WHERE object_type = 'index' AND object_sub_id IS NULL
11197)
11198SELECT
11199    idxs.id AS id,
11200    idxs.name AS name,
11201    objs.name AS on,
11202    clusters.name AS cluster,
11203    COALESCE(keys.key, '{}'::_text) AS key,
11204    idxs.on_id AS on_id,
11205    objs.schema_id AS schema_id,
11206    clusters.id AS cluster_id,
11207    COALESCE(comments.comment, '') as comment
11208FROM
11209    mz_catalog.mz_indexes AS idxs
11210    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11211    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11212    LEFT JOIN
11213        (SELECT
11214            idxs.id,
11215            ARRAY_AGG(
11216                CASE
11217                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11218                    ELSE idx_cols.on_expression
11219                END
11220                ORDER BY idx_cols.index_position ASC
11221            ) AS key
11222        FROM
11223            mz_catalog.mz_indexes AS idxs
11224            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11225            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11226                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11227        GROUP BY idxs.id) AS keys
11228    ON idxs.id = keys.id
11229    LEFT JOIN comments ON idxs.id = comments.id",
11230    access: vec![PUBLIC_SELECT],
11231});
11232
11233pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11234    name: "mz_show_cluster_replicas",
11235    schema: MZ_INTERNAL_SCHEMA,
11236    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11237    desc: RelationDesc::builder()
11238        .with_column("cluster", SqlScalarType::String.nullable(false))
11239        .with_column("replica", SqlScalarType::String.nullable(false))
11240        .with_column("replica_id", SqlScalarType::String.nullable(false))
11241        .with_column("size", SqlScalarType::String.nullable(true))
11242        .with_column("ready", SqlScalarType::Bool.nullable(false))
11243        .with_column("comment", SqlScalarType::String.nullable(false))
11244        .finish(),
11245    column_comments: BTreeMap::new(),
11246    sql: r#"SELECT
11247    mz_catalog.mz_clusters.name AS cluster,
11248    mz_catalog.mz_cluster_replicas.name AS replica,
11249    mz_catalog.mz_cluster_replicas.id as replica_id,
11250    mz_catalog.mz_cluster_replicas.size AS size,
11251    coalesce(statuses.ready, FALSE) AS ready,
11252    coalesce(comments.comment, '') as comment
11253FROM
11254    mz_catalog.mz_cluster_replicas
11255        JOIN mz_catalog.mz_clusters
11256            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11257        LEFT JOIN
11258            (
11259                SELECT
11260                    replica_id,
11261                    bool_and(hydrated) AS ready
11262                FROM mz_internal.mz_hydration_statuses
11263                WHERE replica_id is not null
11264                GROUP BY replica_id
11265            ) AS statuses
11266            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11267        LEFT JOIN mz_internal.mz_comments comments
11268            ON mz_catalog.mz_cluster_replicas.id = comments.id
11269WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11270ORDER BY 1, 2"#,
11271    access: vec![PUBLIC_SELECT],
11272});
11273
11274pub static MZ_SHOW_CONTINUAL_TASKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11275    name: "mz_show_continual_tasks",
11276    schema: MZ_INTERNAL_SCHEMA,
11277    oid: oid::VIEW_MZ_SHOW_CONTINUAL_TASKS_OID,
11278    desc: RelationDesc::builder()
11279        .with_column("id", SqlScalarType::String.nullable(false))
11280        .with_column("name", SqlScalarType::String.nullable(false))
11281        .with_column("cluster", SqlScalarType::String.nullable(false))
11282        .with_column("schema_id", SqlScalarType::String.nullable(false))
11283        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11284        .with_column("comment", SqlScalarType::String.nullable(false))
11285        .finish(),
11286    column_comments: BTreeMap::new(),
11287    sql: "
11288WITH comments AS (
11289    SELECT id, comment
11290    FROM mz_internal.mz_comments
11291    WHERE object_type = 'continual-task' AND object_sub_id IS NULL
11292)
11293SELECT
11294    cts.id as id,
11295    cts.name,
11296    clusters.name AS cluster,
11297    schema_id,
11298    cluster_id,
11299    COALESCE(comments.comment, '') as comment
11300FROM
11301    mz_internal.mz_continual_tasks AS cts
11302    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = cts.cluster_id
11303    LEFT JOIN comments ON cts.id = comments.id",
11304    access: vec![PUBLIC_SELECT],
11305});
11306
11307pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11308    name: "mz_show_role_members",
11309    schema: MZ_INTERNAL_SCHEMA,
11310    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11311    desc: RelationDesc::builder()
11312        .with_column("role", SqlScalarType::String.nullable(false))
11313        .with_column("member", SqlScalarType::String.nullable(false))
11314        .with_column("grantor", SqlScalarType::String.nullable(false))
11315        .finish(),
11316    column_comments: BTreeMap::from_iter([
11317        ("role", "The role that `member` is a member of."),
11318        ("member", "The role that is a member of `role`."),
11319        (
11320            "grantor",
11321            "The role that granted membership of `member` to `role`.",
11322        ),
11323    ]),
11324    sql: r#"SELECT
11325    r1.name AS role,
11326    r2.name AS member,
11327    r3.name AS grantor
11328FROM mz_catalog.mz_role_members rm
11329JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11330JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11331JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11332ORDER BY role"#,
11333    access: vec![PUBLIC_SELECT],
11334});
11335
11336pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11337    name: "mz_show_my_role_members",
11338    schema: MZ_INTERNAL_SCHEMA,
11339    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11340    desc: RelationDesc::builder()
11341        .with_column("role", SqlScalarType::String.nullable(false))
11342        .with_column("member", SqlScalarType::String.nullable(false))
11343        .with_column("grantor", SqlScalarType::String.nullable(false))
11344        .finish(),
11345    column_comments: BTreeMap::from_iter([
11346        ("role", "The role that `member` is a member of."),
11347        ("member", "The role that is a member of `role`."),
11348        (
11349            "grantor",
11350            "The role that granted membership of `member` to `role`.",
11351        ),
11352    ]),
11353    sql: r#"SELECT role, member, grantor
11354FROM mz_internal.mz_show_role_members
11355WHERE pg_has_role(member, 'USAGE')"#,
11356    access: vec![PUBLIC_SELECT],
11357});
11358
11359pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11360    name: "mz_show_system_privileges",
11361    schema: MZ_INTERNAL_SCHEMA,
11362    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11363    desc: RelationDesc::builder()
11364        .with_column("grantor", SqlScalarType::String.nullable(true))
11365        .with_column("grantee", SqlScalarType::String.nullable(true))
11366        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11367        .finish(),
11368    column_comments: BTreeMap::from_iter([
11369        ("grantor", "The role that granted the privilege."),
11370        ("grantee", "The role that the privilege was granted to."),
11371        ("privilege_type", "They type of privilege granted."),
11372    ]),
11373    sql: r#"SELECT
11374    grantor.name AS grantor,
11375    CASE privileges.grantee
11376        WHEN 'p' THEN 'PUBLIC'
11377        ELSE grantee.name
11378    END AS grantee,
11379    privileges.privilege_type AS privilege_type
11380FROM
11381    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11382    FROM mz_catalog.mz_system_privileges) AS privileges
11383LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11384LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11385WHERE privileges.grantee NOT LIKE 's%'"#,
11386    access: vec![PUBLIC_SELECT],
11387});
11388
11389pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11390    name: "mz_show_my_system_privileges",
11391    schema: MZ_INTERNAL_SCHEMA,
11392    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11393    desc: RelationDesc::builder()
11394        .with_column("grantor", SqlScalarType::String.nullable(true))
11395        .with_column("grantee", SqlScalarType::String.nullable(true))
11396        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11397        .finish(),
11398    column_comments: BTreeMap::from_iter([
11399        ("grantor", "The role that granted the privilege."),
11400        ("grantee", "The role that the privilege was granted to."),
11401        ("privilege_type", "They type of privilege granted."),
11402    ]),
11403    sql: r#"SELECT grantor, grantee, privilege_type
11404FROM mz_internal.mz_show_system_privileges
11405WHERE
11406    CASE
11407        WHEN grantee = 'PUBLIC' THEN true
11408        ELSE pg_has_role(grantee, 'USAGE')
11409    END"#,
11410    access: vec![PUBLIC_SELECT],
11411});
11412
11413pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11414    name: "mz_show_cluster_privileges",
11415    schema: MZ_INTERNAL_SCHEMA,
11416    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11417    desc: RelationDesc::builder()
11418        .with_column("grantor", SqlScalarType::String.nullable(true))
11419        .with_column("grantee", SqlScalarType::String.nullable(true))
11420        .with_column("name", SqlScalarType::String.nullable(false))
11421        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11422        .finish(),
11423    column_comments: BTreeMap::from_iter([
11424        ("grantor", "The role that granted the privilege."),
11425        ("grantee", "The role that the privilege was granted to."),
11426        ("name", "The name of the cluster."),
11427        ("privilege_type", "They type of privilege granted."),
11428    ]),
11429    sql: r#"SELECT
11430    grantor.name AS grantor,
11431    CASE privileges.grantee
11432        WHEN 'p' THEN 'PUBLIC'
11433        ELSE grantee.name
11434    END AS grantee,
11435    privileges.name AS name,
11436    privileges.privilege_type AS privilege_type
11437FROM
11438    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11439    FROM mz_catalog.mz_clusters
11440    WHERE id NOT LIKE 's%') AS privileges
11441LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11442LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11443WHERE privileges.grantee NOT LIKE 's%'"#,
11444    access: vec![PUBLIC_SELECT],
11445});
11446
11447pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11448    name: "mz_show_my_cluster_privileges",
11449    schema: MZ_INTERNAL_SCHEMA,
11450    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11451    desc: RelationDesc::builder()
11452        .with_column("grantor", SqlScalarType::String.nullable(true))
11453        .with_column("grantee", SqlScalarType::String.nullable(true))
11454        .with_column("name", SqlScalarType::String.nullable(false))
11455        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11456        .finish(),
11457    column_comments: BTreeMap::from_iter([
11458        ("grantor", "The role that granted the privilege."),
11459        ("grantee", "The role that the privilege was granted to."),
11460        ("name", "The name of the cluster."),
11461        ("privilege_type", "They type of privilege granted."),
11462    ]),
11463    sql: r#"SELECT grantor, grantee, name, privilege_type
11464FROM mz_internal.mz_show_cluster_privileges
11465WHERE
11466    CASE
11467        WHEN grantee = 'PUBLIC' THEN true
11468        ELSE pg_has_role(grantee, 'USAGE')
11469    END"#,
11470    access: vec![PUBLIC_SELECT],
11471});
11472
11473pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11474    name: "mz_show_database_privileges",
11475    schema: MZ_INTERNAL_SCHEMA,
11476    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
11477    desc: RelationDesc::builder()
11478        .with_column("grantor", SqlScalarType::String.nullable(true))
11479        .with_column("grantee", SqlScalarType::String.nullable(true))
11480        .with_column("name", SqlScalarType::String.nullable(false))
11481        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11482        .finish(),
11483    column_comments: BTreeMap::from_iter([
11484        ("grantor", "The role that granted the privilege."),
11485        ("grantee", "The role that the privilege was granted to."),
11486        ("name", "The name of the database."),
11487        ("privilege_type", "They type of privilege granted."),
11488    ]),
11489    sql: r#"SELECT
11490    grantor.name AS grantor,
11491    CASE privileges.grantee
11492        WHEN 'p' THEN 'PUBLIC'
11493        ELSE grantee.name
11494    END AS grantee,
11495    privileges.name AS name,
11496    privileges.privilege_type AS privilege_type
11497FROM
11498    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11499    FROM mz_catalog.mz_databases
11500    WHERE id NOT LIKE 's%') AS privileges
11501LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11502LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11503WHERE privileges.grantee NOT LIKE 's%'"#,
11504    access: vec![PUBLIC_SELECT],
11505});
11506
11507pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11508    name: "mz_show_my_database_privileges",
11509    schema: MZ_INTERNAL_SCHEMA,
11510    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
11511    desc: RelationDesc::builder()
11512        .with_column("grantor", SqlScalarType::String.nullable(true))
11513        .with_column("grantee", SqlScalarType::String.nullable(true))
11514        .with_column("name", SqlScalarType::String.nullable(false))
11515        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11516        .finish(),
11517    column_comments: BTreeMap::from_iter([
11518        ("grantor", "The role that granted the privilege."),
11519        ("grantee", "The role that the privilege was granted to."),
11520        ("name", "The name of the cluster."),
11521        ("privilege_type", "They type of privilege granted."),
11522    ]),
11523    sql: r#"SELECT grantor, grantee, name, privilege_type
11524FROM mz_internal.mz_show_database_privileges
11525WHERE
11526    CASE
11527        WHEN grantee = 'PUBLIC' THEN true
11528        ELSE pg_has_role(grantee, 'USAGE')
11529    END"#,
11530    access: vec![PUBLIC_SELECT],
11531});
11532
11533pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11534    name: "mz_show_schema_privileges",
11535    schema: MZ_INTERNAL_SCHEMA,
11536    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
11537    desc: RelationDesc::builder()
11538        .with_column("grantor", SqlScalarType::String.nullable(true))
11539        .with_column("grantee", SqlScalarType::String.nullable(true))
11540        .with_column("database", SqlScalarType::String.nullable(true))
11541        .with_column("name", SqlScalarType::String.nullable(false))
11542        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11543        .finish(),
11544    column_comments: BTreeMap::from_iter([
11545        ("grantor", "The role that granted the privilege."),
11546        ("grantee", "The role that the privilege was granted to."),
11547        (
11548            "database",
11549            "The name of the database containing the schema.",
11550        ),
11551        ("name", "The name of the schema."),
11552        ("privilege_type", "They type of privilege granted."),
11553    ]),
11554    sql: r#"SELECT
11555    grantor.name AS grantor,
11556    CASE privileges.grantee
11557        WHEN 'p' THEN 'PUBLIC'
11558        ELSE grantee.name
11559    END AS grantee,
11560    databases.name AS database,
11561    privileges.name AS name,
11562    privileges.privilege_type AS privilege_type
11563FROM
11564    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
11565    FROM mz_catalog.mz_schemas
11566    WHERE id NOT LIKE 's%') AS privileges
11567LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11568LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11569LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
11570WHERE privileges.grantee NOT LIKE 's%'"#,
11571    access: vec![PUBLIC_SELECT],
11572});
11573
11574pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11575    name: "mz_show_my_schema_privileges",
11576    schema: MZ_INTERNAL_SCHEMA,
11577    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
11578    desc: RelationDesc::builder()
11579        .with_column("grantor", SqlScalarType::String.nullable(true))
11580        .with_column("grantee", SqlScalarType::String.nullable(true))
11581        .with_column("database", SqlScalarType::String.nullable(true))
11582        .with_column("name", SqlScalarType::String.nullable(false))
11583        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11584        .finish(),
11585    column_comments: BTreeMap::from_iter([
11586        ("grantor", "The role that granted the privilege."),
11587        ("grantee", "The role that the privilege was granted to."),
11588        (
11589            "database",
11590            "The name of the database containing the schema.",
11591        ),
11592        ("name", "The name of the schema."),
11593        ("privilege_type", "They type of privilege granted."),
11594    ]),
11595    sql: r#"SELECT grantor, grantee, database, name, privilege_type
11596FROM mz_internal.mz_show_schema_privileges
11597WHERE
11598    CASE
11599        WHEN grantee = 'PUBLIC' THEN true
11600        ELSE pg_has_role(grantee, 'USAGE')
11601    END"#,
11602    access: vec![PUBLIC_SELECT],
11603});
11604
11605pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11606    name: "mz_show_object_privileges",
11607    schema: MZ_INTERNAL_SCHEMA,
11608    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
11609    desc: RelationDesc::builder()
11610        .with_column("grantor", SqlScalarType::String.nullable(true))
11611        .with_column("grantee", SqlScalarType::String.nullable(true))
11612        .with_column("database", SqlScalarType::String.nullable(true))
11613        .with_column("schema", SqlScalarType::String.nullable(true))
11614        .with_column("name", SqlScalarType::String.nullable(false))
11615        .with_column("object_type", SqlScalarType::String.nullable(false))
11616        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11617        .finish(),
11618    column_comments: BTreeMap::from_iter([
11619        ("grantor", "The role that granted the privilege."),
11620        ("grantee", "The role that the privilege was granted to."),
11621        (
11622            "database",
11623            "The name of the database containing the object.",
11624        ),
11625        ("schema", "The name of the schema containing the object."),
11626        ("name", "The name of the object."),
11627        (
11628            "object_type",
11629            "The type of object the privilege is granted on.",
11630        ),
11631        ("privilege_type", "They type of privilege granted."),
11632    ]),
11633    sql: r#"SELECT
11634    grantor.name AS grantor,
11635    CASE privileges.grantee
11636            WHEN 'p' THEN 'PUBLIC'
11637            ELSE grantee.name
11638        END AS grantee,
11639    databases.name AS database,
11640    schemas.name AS schema,
11641    privileges.name AS name,
11642    privileges.type AS object_type,
11643    privileges.privilege_type AS privilege_type
11644FROM
11645    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
11646    FROM mz_catalog.mz_objects
11647    WHERE id NOT LIKE 's%') AS privileges
11648LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11649LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11650LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
11651LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
11652WHERE privileges.grantee NOT LIKE 's%'"#,
11653    access: vec![PUBLIC_SELECT],
11654});
11655
11656pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11657    name: "mz_show_my_object_privileges",
11658    schema: MZ_INTERNAL_SCHEMA,
11659    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
11660    desc: RelationDesc::builder()
11661        .with_column("grantor", SqlScalarType::String.nullable(true))
11662        .with_column("grantee", SqlScalarType::String.nullable(true))
11663        .with_column("database", SqlScalarType::String.nullable(true))
11664        .with_column("schema", SqlScalarType::String.nullable(true))
11665        .with_column("name", SqlScalarType::String.nullable(false))
11666        .with_column("object_type", SqlScalarType::String.nullable(false))
11667        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11668        .finish(),
11669    column_comments: BTreeMap::from_iter([
11670        ("grantor", "The role that granted the privilege."),
11671        ("grantee", "The role that the privilege was granted to."),
11672        (
11673            "database",
11674            "The name of the database containing the object.",
11675        ),
11676        ("schema", "The name of the schema containing the object."),
11677        ("name", "The name of the object."),
11678        (
11679            "object_type",
11680            "The type of object the privilege is granted on.",
11681        ),
11682        ("privilege_type", "They type of privilege granted."),
11683    ]),
11684    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11685FROM mz_internal.mz_show_object_privileges
11686WHERE
11687    CASE
11688        WHEN grantee = 'PUBLIC' THEN true
11689        ELSE pg_has_role(grantee, 'USAGE')
11690    END"#,
11691    access: vec![PUBLIC_SELECT],
11692});
11693
11694pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11695    name: "mz_show_all_privileges",
11696    schema: MZ_INTERNAL_SCHEMA,
11697    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
11698    desc: RelationDesc::builder()
11699        .with_column("grantor", SqlScalarType::String.nullable(true))
11700        .with_column("grantee", SqlScalarType::String.nullable(true))
11701        .with_column("database", SqlScalarType::String.nullable(true))
11702        .with_column("schema", SqlScalarType::String.nullable(true))
11703        .with_column("name", SqlScalarType::String.nullable(true))
11704        .with_column("object_type", SqlScalarType::String.nullable(false))
11705        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11706        .finish(),
11707    column_comments: BTreeMap::from_iter([
11708        ("grantor", "The role that granted the privilege."),
11709        ("grantee", "The role that the privilege was granted to."),
11710        (
11711            "database",
11712            "The name of the database containing the object.",
11713        ),
11714        ("schema", "The name of the schema containing the object."),
11715        ("name", "The name of the privilege target."),
11716        (
11717            "object_type",
11718            "The type of object the privilege is granted on.",
11719        ),
11720        ("privilege_type", "They type of privilege granted."),
11721    ]),
11722    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
11723FROM mz_internal.mz_show_system_privileges
11724UNION ALL
11725SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
11726FROM mz_internal.mz_show_cluster_privileges
11727UNION ALL
11728SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
11729FROM mz_internal.mz_show_database_privileges
11730UNION ALL
11731SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
11732FROM mz_internal.mz_show_schema_privileges
11733UNION ALL
11734SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11735FROM mz_internal.mz_show_object_privileges"#,
11736    access: vec![PUBLIC_SELECT],
11737});
11738
11739pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11740    name: "mz_show_all_my_privileges",
11741    schema: MZ_INTERNAL_SCHEMA,
11742    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
11743    desc: RelationDesc::builder()
11744        .with_column("grantor", SqlScalarType::String.nullable(true))
11745        .with_column("grantee", SqlScalarType::String.nullable(true))
11746        .with_column("database", SqlScalarType::String.nullable(true))
11747        .with_column("schema", SqlScalarType::String.nullable(true))
11748        .with_column("name", SqlScalarType::String.nullable(true))
11749        .with_column("object_type", SqlScalarType::String.nullable(false))
11750        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11751        .finish(),
11752    column_comments: BTreeMap::from_iter([
11753        ("grantor", "The role that granted the privilege."),
11754        ("grantee", "The role that the privilege was granted to."),
11755        (
11756            "database",
11757            "The name of the database containing the object.",
11758        ),
11759        ("schema", "The name of the schema containing the object."),
11760        ("name", "The name of the privilege target."),
11761        (
11762            "object_type",
11763            "The type of object the privilege is granted on.",
11764        ),
11765        ("privilege_type", "They type of privilege granted."),
11766    ]),
11767    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11768FROM mz_internal.mz_show_all_privileges
11769WHERE
11770    CASE
11771        WHEN grantee = 'PUBLIC' THEN true
11772        ELSE pg_has_role(grantee, 'USAGE')
11773    END"#,
11774    access: vec![PUBLIC_SELECT],
11775});
11776
11777pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11778    name: "mz_show_default_privileges",
11779    schema: MZ_INTERNAL_SCHEMA,
11780    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
11781    desc: RelationDesc::builder()
11782        .with_column("object_owner", SqlScalarType::String.nullable(true))
11783        .with_column("database", SqlScalarType::String.nullable(true))
11784        .with_column("schema", SqlScalarType::String.nullable(true))
11785        .with_column("object_type", SqlScalarType::String.nullable(false))
11786        .with_column("grantee", SqlScalarType::String.nullable(true))
11787        .with_column("privilege_type", SqlScalarType::String.nullable(true))
11788        .finish(),
11789    column_comments: BTreeMap::from_iter([
11790        (
11791            "object_owner",
11792            "Privileges described in this row will be granted on objects created by `object_owner`.",
11793        ),
11794        (
11795            "database",
11796            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11797        ),
11798        (
11799            "schema",
11800            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11801        ),
11802        (
11803            "object_type",
11804            "Privileges described in this row will be granted only on objects of type `object_type`.",
11805        ),
11806        (
11807            "grantee",
11808            "Privileges described in this row will be granted to `grantee`.",
11809        ),
11810        ("privilege_type", "They type of privilege to be granted."),
11811    ]),
11812    sql: r#"SELECT
11813    CASE defaults.role_id
11814        WHEN 'p' THEN 'PUBLIC'
11815        ELSE object_owner.name
11816    END AS object_owner,
11817    databases.name AS database,
11818    schemas.name AS schema,
11819    object_type,
11820    CASE defaults.grantee
11821        WHEN 'p' THEN 'PUBLIC'
11822        ELSE grantee.name
11823    END AS grantee,
11824    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
11825FROM mz_catalog.mz_default_privileges defaults
11826LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
11827LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
11828LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
11829LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
11830WHERE defaults.grantee NOT LIKE 's%'
11831    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
11832    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
11833    access: vec![PUBLIC_SELECT],
11834});
11835
11836pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11837    name: "mz_show_my_default_privileges",
11838    schema: MZ_INTERNAL_SCHEMA,
11839    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
11840    desc: RelationDesc::builder()
11841        .with_column("object_owner", SqlScalarType::String.nullable(true))
11842        .with_column("database", SqlScalarType::String.nullable(true))
11843        .with_column("schema", SqlScalarType::String.nullable(true))
11844        .with_column("object_type", SqlScalarType::String.nullable(false))
11845        .with_column("grantee", SqlScalarType::String.nullable(true))
11846        .with_column("privilege_type", SqlScalarType::String.nullable(true))
11847        .finish(),
11848    column_comments: BTreeMap::from_iter([
11849        (
11850            "object_owner",
11851            "Privileges described in this row will be granted on objects created by `object_owner`.",
11852        ),
11853        (
11854            "database",
11855            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11856        ),
11857        (
11858            "schema",
11859            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11860        ),
11861        (
11862            "object_type",
11863            "Privileges described in this row will be granted only on objects of type `object_type`.",
11864        ),
11865        (
11866            "grantee",
11867            "Privileges described in this row will be granted to `grantee`.",
11868        ),
11869        ("privilege_type", "They type of privilege to be granted."),
11870    ]),
11871    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
11872FROM mz_internal.mz_show_default_privileges
11873WHERE
11874    CASE
11875        WHEN grantee = 'PUBLIC' THEN true
11876        ELSE pg_has_role(grantee, 'USAGE')
11877    END"#,
11878    access: vec![PUBLIC_SELECT],
11879});
11880
11881pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11882    name: "mz_show_network_policies",
11883    schema: MZ_INTERNAL_SCHEMA,
11884    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
11885    desc: RelationDesc::builder()
11886        .with_column("name", SqlScalarType::String.nullable(false))
11887        .with_column("rules", SqlScalarType::String.nullable(true))
11888        .with_column("comment", SqlScalarType::String.nullable(false))
11889        .finish(),
11890    column_comments: BTreeMap::new(),
11891    sql: "
11892WITH comments AS (
11893    SELECT id, comment
11894    FROM mz_internal.mz_comments
11895    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
11896)
11897SELECT
11898    policy.name,
11899    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
11900    COALESCE(comment, '') as comment
11901FROM
11902    mz_internal.mz_network_policies as policy
11903LEFT JOIN
11904    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
11905LEFT JOIN
11906    comments ON policy.id = comments.id
11907WHERE
11908    policy.id NOT LIKE 's%'
11909AND
11910    policy.id NOT LIKE 'g%'
11911GROUP BY policy.name, comments.comment;",
11912    access: vec![PUBLIC_SELECT],
11913});
11914
11915pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11916    name: "mz_cluster_replica_history",
11917    schema: MZ_INTERNAL_SCHEMA,
11918    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
11919    desc: RelationDesc::builder()
11920        .with_column("replica_id", SqlScalarType::String.nullable(true))
11921        .with_column("size", SqlScalarType::String.nullable(true))
11922        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11923        .with_column("cluster_name", SqlScalarType::String.nullable(true))
11924        .with_column("replica_name", SqlScalarType::String.nullable(true))
11925        .with_column(
11926            "created_at",
11927            SqlScalarType::TimestampTz { precision: None }.nullable(false),
11928        )
11929        .with_column(
11930            "dropped_at",
11931            SqlScalarType::TimestampTz { precision: None }.nullable(true),
11932        )
11933        .with_column(
11934            "credits_per_hour",
11935            SqlScalarType::Numeric { max_scale: None }.nullable(true),
11936        )
11937        .finish(),
11938    column_comments: BTreeMap::from_iter([
11939        ("replica_id", "The ID of a cluster replica."),
11940        (
11941            "size",
11942            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
11943        ),
11944        (
11945            "cluster_id",
11946            "The ID of the cluster associated with the replica.",
11947        ),
11948        (
11949            "cluster_name",
11950            "The name of the cluster associated with the replica.",
11951        ),
11952        ("replica_name", "The name of the replica."),
11953        ("created_at", "The time at which the replica was created."),
11954        (
11955            "dropped_at",
11956            "The time at which the replica was dropped, or `NULL` if it still exists.",
11957        ),
11958        (
11959            "credits_per_hour",
11960            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
11961        ),
11962    ]),
11963    sql: r#"
11964        WITH
11965            creates AS
11966            (
11967                SELECT
11968                    details ->> 'logical_size' AS size,
11969                    details ->> 'replica_id' AS replica_id,
11970                    details ->> 'replica_name' AS replica_name,
11971                    details ->> 'cluster_name' AS cluster_name,
11972                    details ->> 'cluster_id' AS cluster_id,
11973                    occurred_at
11974                FROM mz_catalog.mz_audit_events
11975                WHERE
11976                    object_type = 'cluster-replica' AND event_type = 'create'
11977                        AND
11978                    details ->> 'replica_id' IS NOT NULL
11979                        AND
11980                    details ->> 'cluster_id' !~~ 's%'
11981            ),
11982            drops AS
11983            (
11984                SELECT details ->> 'replica_id' AS replica_id, occurred_at
11985                FROM mz_catalog.mz_audit_events
11986                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
11987            )
11988        SELECT
11989            creates.replica_id,
11990            creates.size,
11991            creates.cluster_id,
11992            creates.cluster_name,
11993            creates.replica_name,
11994            creates.occurred_at AS created_at,
11995            drops.occurred_at AS dropped_at,
11996            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
11997        FROM
11998            creates
11999                LEFT JOIN drops ON creates.replica_id = drops.replica_id
12000                LEFT JOIN
12001                    mz_catalog.mz_cluster_replica_sizes
12002                    ON mz_cluster_replica_sizes.size = creates.size"#,
12003    access: vec![PUBLIC_SELECT],
12004});
12005
12006pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12007    name: "mz_cluster_replica_name_history",
12008    schema: MZ_INTERNAL_SCHEMA,
12009    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
12010    desc: RelationDesc::builder()
12011        .with_column(
12012            "occurred_at",
12013            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12014        )
12015        .with_column("id", SqlScalarType::String.nullable(true))
12016        .with_column("previous_name", SqlScalarType::String.nullable(true))
12017        .with_column("new_name", SqlScalarType::String.nullable(true))
12018        .finish(),
12019    column_comments: BTreeMap::from_iter([
12020        (
12021            "occurred_at",
12022            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
12023        ),
12024        ("id", "The ID of the cluster replica."),
12025        (
12026            "previous_name",
12027            "The previous name of the cluster replica. `NULL` if there was no previous name.",
12028        ),
12029        ("new_name", "The new name of the cluster replica."),
12030    ]),
12031    sql: r#"WITH user_replica_alter_history AS (
12032  SELECT occurred_at,
12033    audit_events.details->>'replica_id' AS id,
12034    audit_events.details->>'old_name' AS previous_name,
12035    audit_events.details->>'new_name' AS new_name
12036  FROM mz_catalog.mz_audit_events AS audit_events
12037  WHERE object_type = 'cluster-replica'
12038    AND audit_events.event_type = 'alter'
12039    AND audit_events.details->>'replica_id' like 'u%'
12040),
12041user_replica_create_history AS (
12042  SELECT occurred_at,
12043    audit_events.details->>'replica_id' AS id,
12044    NULL AS previous_name,
12045    audit_events.details->>'replica_name' AS new_name
12046  FROM mz_catalog.mz_audit_events AS audit_events
12047  WHERE object_type = 'cluster-replica'
12048    AND audit_events.event_type = 'create'
12049    AND audit_events.details->>'replica_id' like 'u%'
12050),
12051-- Because built in system cluster replicas don't have audit events, we need to manually add them
12052system_replicas AS (
12053  -- We assume that the system cluster replicas were created at the beginning of time
12054  SELECT NULL::timestamptz AS occurred_at,
12055    id,
12056    NULL AS previous_name,
12057    name AS new_name
12058  FROM mz_catalog.mz_cluster_replicas
12059  WHERE id LIKE 's%'
12060)
12061SELECT *
12062FROM user_replica_alter_history
12063UNION ALL
12064SELECT *
12065FROM user_replica_create_history
12066UNION ALL
12067SELECT *
12068FROM system_replicas"#,
12069    access: vec![PUBLIC_SELECT],
12070});
12071
12072pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12073    name: "mz_hydration_statuses",
12074    schema: MZ_INTERNAL_SCHEMA,
12075    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
12076    desc: RelationDesc::builder()
12077        .with_column("object_id", SqlScalarType::String.nullable(false))
12078        .with_column("replica_id", SqlScalarType::String.nullable(true))
12079        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
12080        .finish(),
12081    column_comments: BTreeMap::from_iter([
12082        (
12083            "object_id",
12084            "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`.",
12085        ),
12086        ("replica_id", "The ID of a cluster replica."),
12087        ("hydrated", "Whether the object is hydrated on the replica."),
12088    ]),
12089    sql: r#"WITH
12090-- Joining against the linearizable catalog tables ensures that this view
12091-- always contains the set of installed objects, even when it depends
12092-- on introspection relations that may received delayed updates.
12093--
12094-- Note that this view only includes objects that are maintained by dataflows.
12095-- In particular, some source types (webhook, introspection, ...) are not and
12096-- are therefore omitted.
12097indexes AS (
12098    SELECT
12099        i.id AS object_id,
12100        h.replica_id,
12101        COALESCE(h.hydrated, false) AS hydrated
12102    FROM mz_catalog.mz_indexes i
12103    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12104        ON (h.object_id = i.id)
12105),
12106materialized_views AS (
12107    SELECT
12108        i.id AS object_id,
12109        h.replica_id,
12110        COALESCE(h.hydrated, false) AS hydrated
12111    FROM mz_catalog.mz_materialized_views i
12112    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12113        ON (h.object_id = i.id)
12114),
12115continual_tasks AS (
12116    SELECT
12117        i.id AS object_id,
12118        h.replica_id,
12119        COALESCE(h.hydrated, false) AS hydrated
12120    FROM mz_internal.mz_continual_tasks i
12121    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12122        ON (h.object_id = i.id)
12123),
12124-- Hydration is a dataflow concept and not all sources are maintained by
12125-- dataflows, so we need to find the ones that are. Generally, sources that
12126-- have a cluster ID are maintained by a dataflow running on that cluster.
12127-- Webhook sources are an exception to this rule.
12128sources_with_clusters AS (
12129    SELECT id, cluster_id
12130    FROM mz_catalog.mz_sources
12131    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12132),
12133sources AS (
12134    SELECT
12135        s.id AS object_id,
12136        ss.replica_id AS replica_id,
12137        ss.rehydration_latency IS NOT NULL AS hydrated
12138    FROM sources_with_clusters s
12139    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12140),
12141-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12142-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12143-- There is likely still a possibility of FPs.
12144sinks AS (
12145    SELECT
12146        s.id AS object_id,
12147        r.id AS replica_id,
12148        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12149    FROM mz_catalog.mz_sinks s
12150    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12151    JOIN mz_catalog.mz_cluster_replicas r
12152        ON (r.cluster_id = s.cluster_id)
12153    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12154        ON (f.object_id = s.id AND f.replica_id = r.id)
12155)
12156SELECT * FROM indexes
12157UNION ALL
12158SELECT * FROM materialized_views
12159UNION ALL
12160SELECT * FROM continual_tasks
12161UNION ALL
12162SELECT * FROM sources
12163UNION ALL
12164SELECT * FROM sinks"#,
12165    access: vec![PUBLIC_SELECT],
12166});
12167
12168pub const MZ_HYDRATION_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12169    name: "mz_hydration_statuses_ind",
12170    schema: MZ_INTERNAL_SCHEMA,
12171    oid: oid::INDEX_MZ_HYDRATION_STATUSES_IND_OID,
12172    sql: "IN CLUSTER mz_catalog_server
12173ON mz_internal.mz_hydration_statuses (object_id, replica_id)",
12174    is_retained_metrics_object: false,
12175};
12176
12177pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12178    name: "mz_materialization_dependencies",
12179    schema: MZ_INTERNAL_SCHEMA,
12180    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12181    desc: RelationDesc::builder()
12182        .with_column("object_id", SqlScalarType::String.nullable(false))
12183        .with_column("dependency_id", SqlScalarType::String.nullable(false))
12184        .finish(),
12185    column_comments: BTreeMap::from_iter([
12186        (
12187            "object_id",
12188            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12189        ),
12190        (
12191            "dependency_id",
12192            "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`.",
12193        ),
12194    ]),
12195    sql: "
12196SELECT object_id, dependency_id
12197FROM mz_internal.mz_compute_dependencies
12198UNION ALL
12199SELECT s.id, d.referenced_object_id AS dependency_id
12200FROM mz_internal.mz_object_dependencies d
12201JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12202JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12203    access: vec![PUBLIC_SELECT],
12204});
12205
12206pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12207    name: "mz_materialization_lag",
12208    schema: MZ_INTERNAL_SCHEMA,
12209    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12210    desc: RelationDesc::builder()
12211        .with_column("object_id", SqlScalarType::String.nullable(false))
12212        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
12213        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
12214        .with_column(
12215            "slowest_local_input_id",
12216            SqlScalarType::String.nullable(false),
12217        )
12218        .with_column(
12219            "slowest_global_input_id",
12220            SqlScalarType::String.nullable(false),
12221        )
12222        .finish(),
12223    column_comments: BTreeMap::from_iter([
12224        (
12225            "object_id",
12226            "The ID of the materialized view, index, or sink.",
12227        ),
12228        (
12229            "local_lag",
12230            "The amount of time the materialization lags behind its direct inputs.",
12231        ),
12232        (
12233            "global_lag",
12234            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12235        ),
12236        (
12237            "slowest_local_input_id",
12238            "The ID of the slowest direct input.",
12239        ),
12240        (
12241            "slowest_global_input_id",
12242            "The ID of the slowest root input.",
12243        ),
12244    ]),
12245    sql: "
12246WITH MUTUALLY RECURSIVE
12247    -- IDs of objects for which we want to know the lag.
12248    materializations (id text) AS (
12249        SELECT id FROM mz_catalog.mz_indexes
12250        UNION ALL
12251        SELECT id FROM mz_catalog.mz_materialized_views
12252        UNION ALL
12253        SELECT id FROM mz_internal.mz_continual_tasks
12254        UNION ALL
12255        SELECT id FROM mz_catalog.mz_sinks
12256    ),
12257    -- Direct dependencies of materializations.
12258    direct_dependencies (id text, dep_id text) AS (
12259        SELECT m.id, d.dependency_id
12260        FROM materializations m
12261        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12262    ),
12263    -- All transitive dependencies of materializations.
12264    transitive_dependencies (id text, dep_id text) AS (
12265        SELECT id, dep_id FROM direct_dependencies
12266        UNION
12267        SELECT td.id, dd.dep_id
12268        FROM transitive_dependencies td
12269        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12270    ),
12271    -- Root dependencies of materializations (sources and tables).
12272    root_dependencies (id text, dep_id text) AS (
12273        SELECT *
12274        FROM transitive_dependencies td
12275        WHERE NOT EXISTS (
12276            SELECT 1
12277            FROM direct_dependencies dd
12278            WHERE dd.id = td.dep_id
12279        )
12280    ),
12281    -- Write progress times of materializations.
12282    materialization_times (id text, time timestamptz) AS (
12283        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12284        FROM materializations m
12285        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12286    ),
12287    -- Write progress times of direct dependencies of materializations.
12288    input_times (id text, slowest_dep text, time timestamptz) AS (
12289        SELECT DISTINCT ON (d.id)
12290            d.id,
12291            d.dep_id,
12292            to_timestamp(f.write_frontier::text::double / 1000)
12293        FROM direct_dependencies d
12294        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12295        ORDER BY d.id, f.write_frontier ASC
12296    ),
12297    -- Write progress times of root dependencies of materializations.
12298    root_times (id text, slowest_dep text, time timestamptz) AS (
12299        SELECT DISTINCT ON (d.id)
12300            d.id,
12301            d.dep_id,
12302            to_timestamp(f.write_frontier::text::double / 1000)
12303        FROM root_dependencies d
12304        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12305        ORDER BY d.id, f.write_frontier ASC
12306    )
12307SELECT
12308    id AS object_id,
12309    -- Ensure that lag values are always NULL for materializations that have reached the empty
12310    -- frontier, as those have processed all their input data.
12311    -- Also make sure that lag values are never negative, even when input frontiers are before
12312    -- output frontiers (as can happen during hydration).
12313    CASE
12314        WHEN m.time IS NULL THEN INTERVAL '0'
12315        WHEN i.time IS NULL THEN NULL
12316        ELSE greatest(i.time - m.time, INTERVAL '0')
12317    END AS local_lag,
12318    CASE
12319        WHEN m.time IS NULL THEN INTERVAL '0'
12320        WHEN r.time IS NULL THEN NULL
12321        ELSE greatest(r.time - m.time, INTERVAL '0')
12322    END AS global_lag,
12323    i.slowest_dep AS slowest_local_input_id,
12324    r.slowest_dep AS slowest_global_input_id
12325FROM materialization_times m
12326JOIN input_times i USING (id)
12327JOIN root_times r USING (id)",
12328    access: vec![PUBLIC_SELECT],
12329});
12330
12331/**
12332 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12333 * It's specifically for the Console's environment overview page to speed up load times.
12334 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12335 */
12336pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12337    BuiltinView {
12338        name: "mz_console_cluster_utilization_overview",
12339        schema: MZ_INTERNAL_SCHEMA,
12340        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12341        desc: RelationDesc::builder()
12342            .with_column(
12343                "bucket_start",
12344                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12345            )
12346            .with_column("replica_id", SqlScalarType::String.nullable(false))
12347            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
12348            .with_column(
12349                "max_memory_at",
12350                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12351            )
12352            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
12353            .with_column(
12354                "max_disk_at",
12355                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12356            )
12357            .with_column(
12358                "memory_and_disk_percent",
12359                SqlScalarType::Float64.nullable(true),
12360            )
12361            .with_column(
12362                "max_memory_and_disk_memory_percent",
12363                SqlScalarType::Float64.nullable(true),
12364            )
12365            .with_column(
12366                "max_memory_and_disk_disk_percent",
12367                SqlScalarType::Float64.nullable(true),
12368            )
12369            .with_column(
12370                "max_memory_and_disk_at",
12371                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12372            )
12373            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
12374            .with_column(
12375                "max_heap_at",
12376                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12377            )
12378            .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
12379            .with_column(
12380                "max_cpu_at",
12381                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12382            )
12383            .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
12384            .with_column(
12385                "bucket_end",
12386                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12387            )
12388            .with_column("name", SqlScalarType::String.nullable(true))
12389            .with_column("cluster_id", SqlScalarType::String.nullable(true))
12390            .with_column("size", SqlScalarType::String.nullable(true))
12391            .finish(),
12392        column_comments: BTreeMap::new(),
12393        sql: r#"WITH replica_history AS (
12394  SELECT replica_id,
12395    size,
12396    cluster_id
12397  FROM mz_internal.mz_cluster_replica_history
12398  UNION
12399  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12400  SELECT id AS replica_id,
12401    size,
12402    cluster_id
12403  FROM mz_catalog.mz_cluster_replicas
12404),
12405replica_metrics_history AS (
12406  SELECT
12407    m.occurred_at,
12408    m.replica_id,
12409    r.size,
12410    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0)) / NULLIF(s.processes, 0) AS cpu_percent,
12411    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0)) / NULLIF(s.processes, 0) AS memory_percent,
12412    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0)) / NULLIF(s.processes, 0) AS disk_percent,
12413    (SUM(m.heap_bytes::float8) / NULLIF(m.heap_limit, 0)) / NULLIF(s.processes, 0) AS heap_percent,
12414    SUM(m.disk_bytes::float8) AS disk_bytes,
12415    SUM(m.memory_bytes::float8) AS memory_bytes,
12416    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12417    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12418  FROM
12419    replica_history AS r
12420    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12421    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12422  GROUP BY
12423    m.occurred_at,
12424    m.replica_id,
12425    r.size,
12426    s.cpu_nano_cores,
12427    s.memory_bytes,
12428    s.disk_bytes,
12429    m.heap_limit,
12430    s.processes
12431),
12432replica_utilization_history_binned AS (
12433  SELECT m.occurred_at,
12434    m.replica_id,
12435    m.cpu_percent,
12436    m.memory_percent,
12437    m.memory_bytes,
12438    m.disk_percent,
12439    m.disk_bytes,
12440    m.heap_percent,
12441    m.total_disk_bytes,
12442    m.total_memory_bytes,
12443    m.size,
12444    date_bin(
12445      '8 HOURS',
12446      occurred_at,
12447      '1970-01-01'::timestamp
12448    ) AS bucket_start
12449  FROM replica_history AS r
12450    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12451  WHERE mz_now() <= date_bin(
12452      '8 HOURS',
12453      occurred_at,
12454      '1970-01-01'::timestamp
12455    ) + INTERVAL '14 DAYS'
12456),
12457-- For each (replica, bucket), take the (replica, bucket) with the highest memory
12458max_memory AS (
12459  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12460    replica_id,
12461    memory_percent,
12462    occurred_at
12463  FROM replica_utilization_history_binned
12464  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12465  ORDER BY bucket_start,
12466    replica_id,
12467    COALESCE(memory_bytes, 0) DESC
12468),
12469max_disk AS (
12470  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12471    replica_id,
12472    disk_percent,
12473    occurred_at
12474  FROM replica_utilization_history_binned
12475  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12476  ORDER BY bucket_start,
12477    replica_id,
12478    COALESCE(disk_bytes, 0) DESC
12479),
12480max_cpu AS (
12481  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12482    replica_id,
12483    cpu_percent,
12484    occurred_at
12485  FROM replica_utilization_history_binned
12486  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12487  ORDER BY bucket_start,
12488    replica_id,
12489    COALESCE(cpu_percent, 0) DESC
12490),
12491/*
12492 This is different
12493 from adding max_memory
12494 and max_disk per bucket because both
12495 values may not occur at the same time if the bucket interval is large.
12496 */
12497max_memory_and_disk AS (
12498  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12499    replica_id,
12500    memory_percent,
12501    disk_percent,
12502    memory_and_disk_percent,
12503    occurred_at
12504  FROM (
12505      SELECT *,
12506        CASE
12507          WHEN disk_bytes IS NULL
12508          AND memory_bytes IS NULL THEN NULL
12509          ELSE (COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0))
12510               / (total_disk_bytes::numeric + total_memory_bytes::numeric)
12511        END AS memory_and_disk_percent
12512      FROM replica_utilization_history_binned
12513    ) AS max_memory_and_disk_inner
12514  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12515  ORDER BY bucket_start,
12516    replica_id,
12517    COALESCE(memory_and_disk_percent, 0) DESC
12518),
12519max_heap AS (
12520  SELECT DISTINCT ON (bucket_start, replica_id)
12521    bucket_start,
12522    replica_id,
12523    heap_percent,
12524    occurred_at
12525  FROM replica_utilization_history_binned
12526  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12527  ORDER BY bucket_start, replica_id, COALESCE(heap_percent, 0) DESC
12528),
12529-- For each (replica, bucket), get its offline events at that time
12530replica_offline_event_history AS (
12531  SELECT date_bin(
12532      '8 HOURS',
12533      occurred_at,
12534      '1970-01-01'::timestamp
12535    ) AS bucket_start,
12536    replica_id,
12537    jsonb_agg(
12538      jsonb_build_object(
12539        'replicaId',
12540        rsh.replica_id,
12541        'occurredAt',
12542        rsh.occurred_at,
12543        'status',
12544        rsh.status,
12545        'reason',
12546        rsh.reason
12547      )
12548    ) AS offline_events
12549  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
12550  WHERE process_id = '0'
12551    AND status = 'offline'
12552    AND mz_now() <= date_bin(
12553      '8 HOURS',
12554      occurred_at,
12555      '1970-01-01'::timestamp
12556    ) + INTERVAL '14 DAYS'
12557  GROUP BY bucket_start,
12558    replica_id
12559)
12560SELECT
12561  bucket_start,
12562  replica_id,
12563  max_memory.memory_percent,
12564  max_memory.occurred_at as max_memory_at,
12565  max_disk.disk_percent,
12566  max_disk.occurred_at as max_disk_at,
12567  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
12568  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
12569  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
12570  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
12571  max_heap.heap_percent,
12572  max_heap.occurred_at as max_heap_at,
12573  max_cpu.cpu_percent as max_cpu_percent,
12574  max_cpu.occurred_at as max_cpu_at,
12575  replica_offline_event_history.offline_events,
12576  bucket_start + INTERVAL '8 HOURS' as bucket_end,
12577  replica_name_history.new_name AS name,
12578  replica_history.cluster_id,
12579  replica_history.size
12580FROM max_memory
12581JOIN max_disk USING (bucket_start, replica_id)
12582JOIN max_cpu USING (bucket_start, replica_id)
12583JOIN max_memory_and_disk USING (bucket_start, replica_id)
12584JOIN max_heap USING (bucket_start, replica_id)
12585JOIN replica_history USING (replica_id)
12586CROSS JOIN LATERAL (
12587  SELECT new_name
12588  FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
12589  WHERE replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
12590    AND bucket_start + INTERVAL '8 HOURS' >= COALESCE(
12591      replica_name_history.occurred_at,
12592      '1970-01-01'::timestamp
12593    )
12594  ORDER BY replica_name_history.occurred_at DESC
12595  LIMIT '1'
12596) AS replica_name_history
12597LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
12598        access: vec![PUBLIC_SELECT],
12599    }
12600});
12601
12602/**
12603 * Traces the blue/green deployment lineage in the audit log to determine all cluster
12604 * IDs that are logically the same cluster.
12605 * cluster_id: The ID of a cluster.
12606 * current_deployment_cluster_id: The cluster ID of the last cluster in
12607 *   cluster_id's blue/green lineage.
12608 * cluster_name: The name of the cluster.
12609 * The approach taken is as follows. First, find all extant clusters and add them
12610 * to the result set. Per cluster, we do the following:
12611 * 1. Find the most recent create or rename event. This moment represents when the
12612 *    cluster took on its final logical identity.
12613 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
12614 *    appended) that was dropped within one minute of that moment. That cluster is
12615 *    almost certainly the logical predecessor of the current cluster. Add the cluster
12616 *    to the result set.
12617 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
12618 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
12619 * but one that's likely to be pretty good one. If a name is reused after more
12620 * than one minute, that's a good sign that it wasn't an automatic blue/green
12621 * process, but someone turning on a new use case that happens to have the same
12622 * name as a previous but logically distinct use case.
12623 */
12624pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12625    name: "mz_cluster_deployment_lineage",
12626    schema: MZ_INTERNAL_SCHEMA,
12627    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
12628    desc: RelationDesc::builder()
12629        .with_column("cluster_id", SqlScalarType::String.nullable(true))
12630        .with_column(
12631            "current_deployment_cluster_id",
12632            SqlScalarType::String.nullable(false),
12633        )
12634        .with_column("cluster_name", SqlScalarType::String.nullable(false))
12635        .with_key(vec![0, 1, 2])
12636        .finish(),
12637    column_comments: BTreeMap::from_iter([
12638        (
12639            "cluster_id",
12640            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
12641        ),
12642        (
12643            "current_deployment_cluster_id",
12644            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
12645        ),
12646        ("cluster_name", "The name of the cluster"),
12647    ]),
12648    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
12649  cluster_id text,
12650  cluster_name text,
12651  event_type text,
12652  occurred_at timestamptz
12653) AS (
12654  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
12655    coalesce(details->>'name', details->>'new_name') AS cluster_name,
12656    event_type,
12657    occurred_at
12658  FROM mz_audit_events
12659  WHERE (
12660      event_type IN ('create', 'drop')
12661      OR (
12662        event_type = 'alter'
12663        AND details ? 'new_name'
12664      )
12665    )
12666    AND object_type = 'cluster'
12667    AND mz_now() < occurred_at + INTERVAL '30 days'
12668),
12669mz_cluster_deployment_lineage (
12670  cluster_id text,
12671  current_deployment_cluster_id text,
12672  cluster_name text
12673) AS (
12674  SELECT c.id,
12675    c.id,
12676    c.name
12677  FROM mz_clusters c
12678  WHERE c.id LIKE 'u%'
12679  UNION
12680  SELECT *
12681  FROM dropped_clusters
12682),
12683-- Closest create or rename event based on the current clusters in the result set
12684most_recent_create_or_rename (
12685  cluster_id text,
12686  current_deployment_cluster_id text,
12687  cluster_name text,
12688  occurred_at timestamptz
12689) AS (
12690  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
12691    c.current_deployment_cluster_id,
12692    e.cluster_name,
12693    e.occurred_at
12694  FROM mz_cluster_deployment_lineage c
12695    JOIN cluster_events e ON c.cluster_id = e.cluster_id
12696    AND c.cluster_name = e.cluster_name
12697  WHERE e.event_type <> 'drop'
12698  ORDER BY e.cluster_id,
12699    e.occurred_at DESC
12700),
12701-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
12702dropped_clusters (
12703  cluster_id text,
12704  current_deployment_cluster_id text,
12705  cluster_name text
12706) AS (
12707  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
12708    cr.current_deployment_cluster_id,
12709    cr.cluster_name
12710  FROM most_recent_create_or_rename cr
12711    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
12712    AND cr.occurred_at + interval '1 minute'
12713    AND (
12714      e.cluster_name = cr.cluster_name
12715      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
12716    )
12717  WHERE e.event_type = 'drop'
12718  ORDER BY cr.cluster_id,
12719    abs(
12720      extract(
12721        epoch
12722        FROM cr.occurred_at - e.occurred_at
12723      )
12724    )
12725)
12726SELECT *
12727FROM mz_cluster_deployment_lineage"#,
12728    access: vec![PUBLIC_SELECT],
12729});
12730
12731pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12732    name: "mz_show_databases_ind",
12733    schema: MZ_INTERNAL_SCHEMA,
12734    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
12735    sql: "IN CLUSTER mz_catalog_server
12736ON mz_internal.mz_show_databases (name)",
12737    is_retained_metrics_object: false,
12738};
12739
12740pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12741    name: "mz_show_schemas_ind",
12742    schema: MZ_INTERNAL_SCHEMA,
12743    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
12744    sql: "IN CLUSTER mz_catalog_server
12745ON mz_internal.mz_show_schemas (database_id)",
12746    is_retained_metrics_object: false,
12747};
12748
12749pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12750    name: "mz_show_connections_ind",
12751    schema: MZ_INTERNAL_SCHEMA,
12752    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
12753    sql: "IN CLUSTER mz_catalog_server
12754ON mz_internal.mz_show_connections (schema_id)",
12755    is_retained_metrics_object: false,
12756};
12757
12758pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
12759    name: "mz_show_tables_ind",
12760    schema: MZ_INTERNAL_SCHEMA,
12761    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
12762    sql: "IN CLUSTER mz_catalog_server
12763ON mz_internal.mz_show_tables (schema_id)",
12764    is_retained_metrics_object: false,
12765};
12766
12767pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12768    name: "mz_show_sources_ind",
12769    schema: MZ_INTERNAL_SCHEMA,
12770    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
12771    sql: "IN CLUSTER mz_catalog_server
12772ON mz_internal.mz_show_sources (schema_id)",
12773    is_retained_metrics_object: false,
12774};
12775
12776pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12777    name: "mz_show_views_ind",
12778    schema: MZ_INTERNAL_SCHEMA,
12779    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
12780    sql: "IN CLUSTER mz_catalog_server
12781ON mz_internal.mz_show_views (schema_id)",
12782    is_retained_metrics_object: false,
12783};
12784
12785pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12786    name: "mz_show_materialized_views_ind",
12787    schema: MZ_INTERNAL_SCHEMA,
12788    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
12789    sql: "IN CLUSTER mz_catalog_server
12790ON mz_internal.mz_show_materialized_views (schema_id)",
12791    is_retained_metrics_object: false,
12792};
12793
12794pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
12795    name: "mz_show_sinks_ind",
12796    schema: MZ_INTERNAL_SCHEMA,
12797    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
12798    sql: "IN CLUSTER mz_catalog_server
12799ON mz_internal.mz_show_sinks (schema_id)",
12800    is_retained_metrics_object: false,
12801};
12802
12803pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
12804    name: "mz_show_types_ind",
12805    schema: MZ_INTERNAL_SCHEMA,
12806    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
12807    sql: "IN CLUSTER mz_catalog_server
12808ON mz_internal.mz_show_types (schema_id)",
12809    is_retained_metrics_object: false,
12810};
12811
12812pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
12813    name: "mz_show_roles_ind",
12814    schema: MZ_INTERNAL_SCHEMA,
12815    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
12816    sql: "IN CLUSTER mz_catalog_server
12817ON mz_internal.mz_show_roles (name)",
12818    is_retained_metrics_object: false,
12819};
12820
12821pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12822    name: "mz_show_all_objects_ind",
12823    schema: MZ_INTERNAL_SCHEMA,
12824    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
12825    sql: "IN CLUSTER mz_catalog_server
12826ON mz_internal.mz_show_all_objects (schema_id)",
12827    is_retained_metrics_object: false,
12828};
12829
12830pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12831    name: "mz_show_indexes_ind",
12832    schema: MZ_INTERNAL_SCHEMA,
12833    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
12834    sql: "IN CLUSTER mz_catalog_server
12835ON mz_internal.mz_show_indexes (schema_id)",
12836    is_retained_metrics_object: false,
12837};
12838
12839pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12840    name: "mz_show_columns_ind",
12841    schema: MZ_INTERNAL_SCHEMA,
12842    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
12843    sql: "IN CLUSTER mz_catalog_server
12844ON mz_internal.mz_show_columns (id)",
12845    is_retained_metrics_object: false,
12846};
12847
12848pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12849    name: "mz_show_clusters_ind",
12850    schema: MZ_INTERNAL_SCHEMA,
12851    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
12852    sql: "IN CLUSTER mz_catalog_server
12853ON mz_internal.mz_show_clusters (name)",
12854    is_retained_metrics_object: false,
12855};
12856
12857pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
12858    name: "mz_show_cluster_replicas_ind",
12859    schema: MZ_INTERNAL_SCHEMA,
12860    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
12861    sql: "IN CLUSTER mz_catalog_server
12862ON mz_internal.mz_show_cluster_replicas (cluster)",
12863    is_retained_metrics_object: false,
12864};
12865
12866pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12867    name: "mz_show_secrets_ind",
12868    schema: MZ_INTERNAL_SCHEMA,
12869    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
12870    sql: "IN CLUSTER mz_catalog_server
12871ON mz_internal.mz_show_secrets (schema_id)",
12872    is_retained_metrics_object: false,
12873};
12874
12875pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12876    name: "mz_databases_ind",
12877    schema: MZ_CATALOG_SCHEMA,
12878    oid: oid::INDEX_MZ_DATABASES_IND_OID,
12879    sql: "IN CLUSTER mz_catalog_server
12880ON mz_catalog.mz_databases (name)",
12881    is_retained_metrics_object: false,
12882};
12883
12884pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12885    name: "mz_schemas_ind",
12886    schema: MZ_CATALOG_SCHEMA,
12887    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
12888    sql: "IN CLUSTER mz_catalog_server
12889ON mz_catalog.mz_schemas (database_id)",
12890    is_retained_metrics_object: false,
12891};
12892
12893pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12894    name: "mz_connections_ind",
12895    schema: MZ_CATALOG_SCHEMA,
12896    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
12897    sql: "IN CLUSTER mz_catalog_server
12898ON mz_catalog.mz_connections (schema_id)",
12899    is_retained_metrics_object: false,
12900};
12901
12902pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
12903    name: "mz_tables_ind",
12904    schema: MZ_CATALOG_SCHEMA,
12905    oid: oid::INDEX_MZ_TABLES_IND_OID,
12906    sql: "IN CLUSTER mz_catalog_server
12907ON mz_catalog.mz_tables (schema_id)",
12908    is_retained_metrics_object: false,
12909};
12910
12911pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
12912    name: "mz_types_ind",
12913    schema: MZ_CATALOG_SCHEMA,
12914    oid: oid::INDEX_MZ_TYPES_IND_OID,
12915    sql: "IN CLUSTER mz_catalog_server
12916ON mz_catalog.mz_types (schema_id)",
12917    is_retained_metrics_object: false,
12918};
12919
12920pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12921    name: "mz_objects_ind",
12922    schema: MZ_CATALOG_SCHEMA,
12923    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
12924    sql: "IN CLUSTER mz_catalog_server
12925ON mz_catalog.mz_objects (schema_id)",
12926    is_retained_metrics_object: false,
12927};
12928
12929pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12930    name: "mz_columns_ind",
12931    schema: MZ_CATALOG_SCHEMA,
12932    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
12933    sql: "IN CLUSTER mz_catalog_server
12934ON mz_catalog.mz_columns (name)",
12935    is_retained_metrics_object: false,
12936};
12937
12938pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12939    name: "mz_secrets_ind",
12940    schema: MZ_CATALOG_SCHEMA,
12941    oid: oid::INDEX_MZ_SECRETS_IND_OID,
12942    sql: "IN CLUSTER mz_catalog_server
12943ON mz_catalog.mz_secrets (name)",
12944    is_retained_metrics_object: false,
12945};
12946
12947pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12948    name: "mz_views_ind",
12949    schema: MZ_CATALOG_SCHEMA,
12950    oid: oid::INDEX_MZ_VIEWS_IND_OID,
12951    sql: "IN CLUSTER mz_catalog_server
12952ON mz_catalog.mz_views (schema_id)",
12953    is_retained_metrics_object: false,
12954};
12955
12956pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
12957    name: "mz_console_cluster_utilization_overview_ind",
12958    schema: MZ_INTERNAL_SCHEMA,
12959    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
12960    sql: "IN CLUSTER mz_catalog_server
12961ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
12962    is_retained_metrics_object: false,
12963};
12964
12965pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
12966    name: "mz_cluster_deployment_lineage_ind",
12967    schema: MZ_INTERNAL_SCHEMA,
12968    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
12969    sql: "IN CLUSTER mz_catalog_server
12970ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
12971    is_retained_metrics_object: false,
12972};
12973
12974pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12975    name: "mz_clusters_ind",
12976    schema: MZ_CATALOG_SCHEMA,
12977    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
12978    sql: "IN CLUSTER mz_catalog_server
12979ON mz_catalog.mz_clusters (id)",
12980    is_retained_metrics_object: false,
12981};
12982
12983pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12984    name: "mz_indexes_ind",
12985    schema: MZ_CATALOG_SCHEMA,
12986    oid: oid::INDEX_MZ_INDEXES_IND_OID,
12987    sql: "IN CLUSTER mz_catalog_server
12988ON mz_catalog.mz_indexes (id)",
12989    is_retained_metrics_object: false,
12990};
12991
12992pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
12993    name: "mz_roles_ind",
12994    schema: MZ_CATALOG_SCHEMA,
12995    oid: oid::INDEX_MZ_ROLES_IND_OID,
12996    sql: "IN CLUSTER mz_catalog_server
12997ON mz_catalog.mz_roles (id)",
12998    is_retained_metrics_object: false,
12999};
13000
13001pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13002    name: "mz_sources_ind",
13003    schema: MZ_CATALOG_SCHEMA,
13004    oid: oid::INDEX_MZ_SOURCES_IND_OID,
13005    sql: "IN CLUSTER mz_catalog_server
13006ON mz_catalog.mz_sources (id)",
13007    is_retained_metrics_object: true,
13008};
13009
13010pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
13011    name: "mz_sinks_ind",
13012    schema: MZ_CATALOG_SCHEMA,
13013    oid: oid::INDEX_MZ_SINKS_IND_OID,
13014    sql: "IN CLUSTER mz_catalog_server
13015ON mz_catalog.mz_sinks (id)",
13016    is_retained_metrics_object: true,
13017};
13018
13019pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13020    name: "mz_materialized_views_ind",
13021    schema: MZ_CATALOG_SCHEMA,
13022    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
13023    sql: "IN CLUSTER mz_catalog_server
13024ON mz_catalog.mz_materialized_views (id)",
13025    is_retained_metrics_object: false,
13026};
13027
13028pub const MZ_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13029    name: "mz_continual_tasks_ind",
13030    schema: MZ_INTERNAL_SCHEMA,
13031    oid: oid::INDEX_MZ_CONTINUAL_TASKS_IND_OID,
13032    sql: "IN CLUSTER mz_catalog_server
13033ON mz_internal.mz_continual_tasks (id)",
13034    is_retained_metrics_object: false,
13035};
13036
13037pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13038    name: "mz_source_statuses_ind",
13039    schema: MZ_INTERNAL_SCHEMA,
13040    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
13041    sql: "IN CLUSTER mz_catalog_server
13042ON mz_internal.mz_source_statuses (id)",
13043    is_retained_metrics_object: false,
13044};
13045
13046pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13047    name: "mz_sink_statuses_ind",
13048    schema: MZ_INTERNAL_SCHEMA,
13049    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
13050    sql: "IN CLUSTER mz_catalog_server
13051ON mz_internal.mz_sink_statuses (id)",
13052    is_retained_metrics_object: false,
13053};
13054
13055pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13056    name: "mz_source_status_history_ind",
13057    schema: MZ_INTERNAL_SCHEMA,
13058    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
13059    sql: "IN CLUSTER mz_catalog_server
13060ON mz_internal.mz_source_status_history (source_id)",
13061    is_retained_metrics_object: false,
13062};
13063
13064pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13065    name: "mz_sink_status_history_ind",
13066    schema: MZ_INTERNAL_SCHEMA,
13067    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
13068    sql: "IN CLUSTER mz_catalog_server
13069ON mz_internal.mz_sink_status_history (sink_id)",
13070    is_retained_metrics_object: false,
13071};
13072
13073pub const MZ_SHOW_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13074    name: "mz_show_continual_tasks_ind",
13075    schema: MZ_INTERNAL_SCHEMA,
13076    oid: oid::INDEX_MZ_SHOW_CONTINUAL_TASKS_OID,
13077    sql: "IN CLUSTER mz_catalog_server
13078ON mz_internal.mz_show_continual_tasks (id)",
13079    is_retained_metrics_object: false,
13080};
13081
13082// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
13083// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
13084// save index space, and we don't expect the sum to be > 2^63
13085// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
13086//
13087//
13088// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
13089// underlying relation.
13090//
13091// We append WITH_HISTORY because we want to build a separate view + index that doesn't
13092// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
13093// to hold all records/updates, which causes CPU and latency of querying it to spike.
13094pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
13095    LazyLock::new(|| BuiltinView {
13096        name: "mz_source_statistics_with_history",
13097        schema: MZ_INTERNAL_SCHEMA,
13098        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
13099        desc: RelationDesc::builder()
13100            .with_column("id", SqlScalarType::String.nullable(false))
13101            .with_column("replica_id", SqlScalarType::String.nullable(true))
13102            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13103            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13104            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13105            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13106            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13107            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13108            .with_column(
13109                "rehydration_latency",
13110                SqlScalarType::Interval.nullable(true),
13111            )
13112            .with_column(
13113                "snapshot_records_known",
13114                SqlScalarType::UInt64.nullable(true),
13115            )
13116            .with_column(
13117                "snapshot_records_staged",
13118                SqlScalarType::UInt64.nullable(true),
13119            )
13120            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13121            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13122            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13123            .with_key(vec![0, 1])
13124            .finish(),
13125        column_comments: BTreeMap::new(),
13126        sql: "
13127WITH
13128    -- For each subsource, statistics are reported as its parent source
13129    subsource_to_parent AS
13130    (
13131        SELECT subsource.id AS id, parent.id AS report_id
13132        FROM mz_catalog.mz_sources AS subsource
13133            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
13134            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
13135        WHERE subsource.type = 'subsource'
13136    ),
13137    -- For each table from source, statistics are reported as its parent source
13138    table_to_parent AS
13139    (
13140        SELECT id, source_id AS report_id
13141        FROM mz_catalog.mz_tables
13142        WHERE source_id IS NOT NULL
13143    ),
13144    -- For each source and subsource, statistics are reported as itself
13145    source_refl AS
13146    (
13147        SELECT id, id AS report_id
13148        FROM mz_catalog.mz_sources
13149        WHERE type NOT IN ('progress', 'log')
13150    ),
13151    -- For each table from source, statistics are reported as itself
13152    table_refl AS
13153    (
13154        SELECT id, id AS report_id
13155        FROM mz_catalog.mz_tables
13156        WHERE source_id IS NOT NULL
13157    ),
13158    report_paths AS
13159    (
13160        SELECT id, report_id FROM subsource_to_parent
13161        UNION ALL SELECT id, report_id FROM table_to_parent
13162        UNION ALL SELECT id, report_id FROM source_refl
13163        UNION ALL SELECT id, report_id FROM table_refl
13164    )
13165SELECT
13166    report_paths.report_id AS id,
13167    replica_id,
13168    -- Counters
13169    SUM(messages_received)::uint8 AS messages_received,
13170    SUM(bytes_received)::uint8 AS bytes_received,
13171    SUM(updates_staged)::uint8 AS updates_staged,
13172    SUM(updates_committed)::uint8 AS updates_committed,
13173    -- Resetting Gauges
13174    SUM(records_indexed)::uint8 AS records_indexed,
13175    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13176    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13177    CASE
13178        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13179        ELSE MAX(rehydration_latency)::interval
13180    END AS rehydration_latency,
13181    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13182    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13183    bool_and(snapshot_committed) as snapshot_committed,
13184    -- Gauges
13185    MAX(offset_known)::uint8 AS offset_known,
13186    MIN(offset_committed)::uint8 AS offset_committed
13187FROM mz_internal.mz_source_statistics_raw
13188    JOIN report_paths USING (id)
13189GROUP BY report_paths.report_id, replica_id",
13190        access: vec![PUBLIC_SELECT],
13191    });
13192
13193pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13194    name: "mz_source_statistics_with_history_ind",
13195    schema: MZ_INTERNAL_SCHEMA,
13196    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13197    sql: "IN CLUSTER mz_catalog_server
13198ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
13199    is_retained_metrics_object: true,
13200};
13201
13202// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13203// Used to query MZ_SOURCE_STATISTICS at the current time.
13204pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13205    BuiltinView {
13206        name: "mz_source_statistics",
13207        schema: MZ_INTERNAL_SCHEMA,
13208        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13209        // We need to add a redundant where clause for a new dataflow to be created.
13210        desc: RelationDesc::builder()
13211            .with_column("id", SqlScalarType::String.nullable(false))
13212            .with_column("replica_id", SqlScalarType::String.nullable(true))
13213            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13214            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13215            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13216            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13217            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13218            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13219            .with_column(
13220                "rehydration_latency",
13221                SqlScalarType::Interval.nullable(true),
13222            )
13223            .with_column(
13224                "snapshot_records_known",
13225                SqlScalarType::UInt64.nullable(true),
13226            )
13227            .with_column(
13228                "snapshot_records_staged",
13229                SqlScalarType::UInt64.nullable(true),
13230            )
13231            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13232            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13233            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13234            .with_key(vec![0, 1])
13235            .finish(),
13236        column_comments: BTreeMap::from_iter([
13237            (
13238                "id",
13239                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13240            ),
13241            (
13242                "replica_id",
13243                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13244            ),
13245            (
13246                "messages_received",
13247                "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.",
13248            ),
13249            (
13250                "bytes_received",
13251                "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.",
13252            ),
13253            (
13254                "updates_staged",
13255                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13256            ),
13257            (
13258                "updates_committed",
13259                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13260            ),
13261            (
13262                "records_indexed",
13263                "The number of individual records indexed in the source envelope state.",
13264            ),
13265            (
13266                "bytes_indexed",
13267                "The number of bytes stored in the source's internal index, if any.",
13268            ),
13269            (
13270                "rehydration_latency",
13271                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13272            ),
13273            (
13274                "snapshot_records_known",
13275                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13276            ),
13277            (
13278                "snapshot_records_staged",
13279                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13280            ),
13281            (
13282                "snapshot_committed",
13283                "Whether the source has committed the initial snapshot for a source.",
13284            ),
13285            (
13286                "offset_known",
13287                "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.",
13288            ),
13289            (
13290                "offset_committed",
13291                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13292            ),
13293        ]),
13294        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13295        access: vec![PUBLIC_SELECT],
13296    }
13297});
13298
13299pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13300    name: "mz_source_statistics_ind",
13301    schema: MZ_INTERNAL_SCHEMA,
13302    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13303    sql: "IN CLUSTER mz_catalog_server
13304ON mz_internal.mz_source_statistics (id, replica_id)",
13305    is_retained_metrics_object: false,
13306};
13307
13308pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13309    name: "mz_sink_statistics",
13310    schema: MZ_INTERNAL_SCHEMA,
13311    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13312    desc: RelationDesc::builder()
13313        .with_column("id", SqlScalarType::String.nullable(false))
13314        .with_column("replica_id", SqlScalarType::String.nullable(true))
13315        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
13316        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
13317        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
13318        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
13319        .with_key(vec![0, 1])
13320        .finish(),
13321    column_comments: BTreeMap::from_iter([
13322        (
13323            "id",
13324            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
13325        ),
13326        (
13327            "replica_id",
13328            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13329        ),
13330        (
13331            "messages_staged",
13332            "The number of messages staged but possibly not committed to the sink.",
13333        ),
13334        (
13335            "messages_committed",
13336            "The number of messages committed to the sink.",
13337        ),
13338        (
13339            "bytes_staged",
13340            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13341        ),
13342        (
13343            "bytes_committed",
13344            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13345        ),
13346    ]),
13347    sql: "
13348SELECT
13349    id,
13350    replica_id,
13351    SUM(messages_staged)::uint8 AS messages_staged,
13352    SUM(messages_committed)::uint8 AS messages_committed,
13353    SUM(bytes_staged)::uint8 AS bytes_staged,
13354    SUM(bytes_committed)::uint8 AS bytes_committed
13355FROM mz_internal.mz_sink_statistics_raw
13356GROUP BY id, replica_id",
13357    access: vec![PUBLIC_SELECT],
13358});
13359
13360pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13361    name: "mz_sink_statistics_ind",
13362    schema: MZ_INTERNAL_SCHEMA,
13363    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13364    sql: "IN CLUSTER mz_catalog_server
13365ON mz_internal.mz_sink_statistics (id, replica_id)",
13366    is_retained_metrics_object: true,
13367};
13368
13369pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13370    name: "mz_cluster_replicas_ind",
13371    schema: MZ_CATALOG_SCHEMA,
13372    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13373    sql: "IN CLUSTER mz_catalog_server
13374ON mz_catalog.mz_cluster_replicas (id)",
13375    is_retained_metrics_object: true,
13376};
13377
13378pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13379    name: "mz_cluster_replica_sizes_ind",
13380    schema: MZ_CATALOG_SCHEMA,
13381    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13382    sql: "IN CLUSTER mz_catalog_server
13383ON mz_catalog.mz_cluster_replica_sizes (size)",
13384    is_retained_metrics_object: true,
13385};
13386
13387pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13388    name: "mz_cluster_replica_statuses_ind",
13389    schema: MZ_INTERNAL_SCHEMA,
13390    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13391    sql: "IN CLUSTER mz_catalog_server
13392ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13393    is_retained_metrics_object: false,
13394};
13395
13396pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13397    name: "mz_cluster_replica_status_history_ind",
13398    schema: MZ_INTERNAL_SCHEMA,
13399    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13400    sql: "IN CLUSTER mz_catalog_server
13401ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13402    is_retained_metrics_object: false,
13403};
13404
13405pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13406    name: "mz_cluster_replica_metrics_ind",
13407    schema: MZ_INTERNAL_SCHEMA,
13408    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13409    sql: "IN CLUSTER mz_catalog_server
13410ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13411    is_retained_metrics_object: false,
13412};
13413
13414pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13415    name: "mz_cluster_replica_metrics_history_ind",
13416    schema: MZ_INTERNAL_SCHEMA,
13417    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13418    sql: "IN CLUSTER mz_catalog_server
13419ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13420    is_retained_metrics_object: false,
13421};
13422
13423pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13424    name: "mz_cluster_replica_history_ind",
13425    schema: MZ_INTERNAL_SCHEMA,
13426    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13427    sql: "IN CLUSTER mz_catalog_server
13428ON mz_internal.mz_cluster_replica_history (dropped_at)",
13429    is_retained_metrics_object: true,
13430};
13431
13432pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13433    name: "mz_cluster_replica_name_history_ind",
13434    schema: MZ_INTERNAL_SCHEMA,
13435    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13436    sql: "IN CLUSTER mz_catalog_server
13437ON mz_internal.mz_cluster_replica_name_history (id)",
13438    is_retained_metrics_object: false,
13439};
13440
13441pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13442    name: "mz_object_lifetimes_ind",
13443    schema: MZ_INTERNAL_SCHEMA,
13444    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13445    sql: "IN CLUSTER mz_catalog_server
13446ON mz_internal.mz_object_lifetimes (id)",
13447    is_retained_metrics_object: false,
13448};
13449
13450pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13451    name: "mz_object_history_ind",
13452    schema: MZ_INTERNAL_SCHEMA,
13453    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13454    sql: "IN CLUSTER mz_catalog_server
13455ON mz_internal.mz_object_history (id)",
13456    is_retained_metrics_object: false,
13457};
13458
13459pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13460    name: "mz_object_dependencies_ind",
13461    schema: MZ_INTERNAL_SCHEMA,
13462    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
13463    sql: "IN CLUSTER mz_catalog_server
13464ON mz_internal.mz_object_dependencies (object_id)",
13465    is_retained_metrics_object: true,
13466};
13467
13468pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13469    name: "mz_compute_dependencies_ind",
13470    schema: MZ_INTERNAL_SCHEMA,
13471    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
13472    sql: "IN CLUSTER mz_catalog_server
13473ON mz_internal.mz_compute_dependencies (dependency_id)",
13474    is_retained_metrics_object: false,
13475};
13476
13477pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13478    name: "mz_object_transitive_dependencies_ind",
13479    schema: MZ_INTERNAL_SCHEMA,
13480    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
13481    sql: "IN CLUSTER mz_catalog_server
13482ON mz_internal.mz_object_transitive_dependencies (object_id)",
13483    is_retained_metrics_object: false,
13484};
13485
13486pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
13487    name: "mz_frontiers_ind",
13488    schema: MZ_INTERNAL_SCHEMA,
13489    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
13490    sql: "IN CLUSTER mz_catalog_server
13491ON mz_internal.mz_frontiers (object_id)",
13492    is_retained_metrics_object: false,
13493};
13494
13495pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13496    name: "mz_wallclock_global_lag_recent_history_ind",
13497    schema: MZ_INTERNAL_SCHEMA,
13498    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
13499    sql: "IN CLUSTER mz_catalog_server
13500ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
13501    is_retained_metrics_object: false,
13502};
13503
13504pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
13505    name: "mz_recent_activity_log_thinned_ind",
13506    schema: MZ_INTERNAL_SCHEMA,
13507    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
13508    sql: "IN CLUSTER mz_catalog_server
13509-- sql_hash because we plan to join
13510-- this against mz_internal.mz_sql_text
13511ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
13512    is_retained_metrics_object: false,
13513};
13514
13515pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13516    name: "mz_kafka_sources_ind",
13517    schema: MZ_CATALOG_SCHEMA,
13518    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
13519    sql: "IN CLUSTER mz_catalog_server
13520ON mz_catalog.mz_kafka_sources (id)",
13521    is_retained_metrics_object: true,
13522};
13523
13524pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13525    name: "mz_webhook_sources_ind",
13526    schema: MZ_INTERNAL_SCHEMA,
13527    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
13528    sql: "IN CLUSTER mz_catalog_server
13529ON mz_internal.mz_webhook_sources (id)",
13530    is_retained_metrics_object: true,
13531};
13532
13533pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
13534    name: "mz_comments_ind",
13535    schema: MZ_INTERNAL_SCHEMA,
13536    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
13537    sql: "IN CLUSTER mz_catalog_server
13538ON mz_internal.mz_comments (id)",
13539    is_retained_metrics_object: true,
13540};
13541
13542pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
13543    name: "mz_analytics",
13544    schema: MZ_INTERNAL_SCHEMA,
13545    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
13546    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
13547    access: &[MzAclItem {
13548        grantee: MZ_SYSTEM_ROLE_ID,
13549        grantor: MZ_ANALYTICS_ROLE_ID,
13550        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
13551    }],
13552    owner_id: &MZ_ANALYTICS_ROLE_ID,
13553    runtime_alterable: true,
13554};
13555
13556pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
13557    id: MZ_SYSTEM_ROLE_ID,
13558    name: SYSTEM_USER_NAME,
13559    oid: oid::ROLE_MZ_SYSTEM_OID,
13560    attributes: RoleAttributesRaw::new().with_all(),
13561};
13562
13563pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
13564    id: MZ_SUPPORT_ROLE_ID,
13565    name: SUPPORT_USER_NAME,
13566    oid: oid::ROLE_MZ_SUPPORT_OID,
13567    attributes: RoleAttributesRaw::new(),
13568};
13569
13570pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
13571    id: MZ_ANALYTICS_ROLE_ID,
13572    name: ANALYTICS_USER_NAME,
13573    oid: oid::ROLE_MZ_ANALYTICS_OID,
13574    attributes: RoleAttributesRaw::new(),
13575};
13576
13577/// This role can `SELECT` from various query history objects,
13578/// e.g. `mz_prepared_statement_history`.
13579pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
13580    id: MZ_MONITOR_ROLE_ID,
13581    name: "mz_monitor",
13582    oid: oid::ROLE_MZ_MONITOR_OID,
13583    attributes: RoleAttributesRaw::new(),
13584};
13585
13586/// This role is like [`MZ_MONITOR_ROLE`], but can only query
13587/// the redacted versions of the objects.
13588pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
13589    id: MZ_MONITOR_REDACTED_ROLE_ID,
13590    name: "mz_monitor_redacted",
13591    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
13592    attributes: RoleAttributesRaw::new(),
13593};
13594
13595pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
13596    name: SYSTEM_USER_NAME,
13597    owner_id: &MZ_SYSTEM_ROLE_ID,
13598    privileges: &[
13599        MzAclItem {
13600            grantee: MZ_SUPPORT_ROLE_ID,
13601            grantor: MZ_SYSTEM_ROLE_ID,
13602            acl_mode: AclMode::USAGE,
13603        },
13604        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13605    ],
13606};
13607
13608pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13609    name: BUILTIN_CLUSTER_REPLICA_NAME,
13610    cluster_name: MZ_SYSTEM_CLUSTER.name,
13611};
13612
13613pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
13614    name: "mz_catalog_server",
13615    owner_id: &MZ_SYSTEM_ROLE_ID,
13616    privileges: &[
13617        MzAclItem {
13618            grantee: RoleId::Public,
13619            grantor: MZ_SYSTEM_ROLE_ID,
13620            acl_mode: AclMode::USAGE,
13621        },
13622        MzAclItem {
13623            grantee: MZ_SUPPORT_ROLE_ID,
13624            grantor: MZ_SYSTEM_ROLE_ID,
13625            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
13626        },
13627        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13628    ],
13629};
13630
13631pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13632    name: BUILTIN_CLUSTER_REPLICA_NAME,
13633    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
13634};
13635
13636pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
13637    name: "mz_probe",
13638    owner_id: &MZ_SYSTEM_ROLE_ID,
13639    privileges: &[
13640        MzAclItem {
13641            grantee: MZ_SUPPORT_ROLE_ID,
13642            grantor: MZ_SYSTEM_ROLE_ID,
13643            acl_mode: AclMode::USAGE,
13644        },
13645        MzAclItem {
13646            grantee: MZ_MONITOR_ROLE_ID,
13647            grantor: MZ_SYSTEM_ROLE_ID,
13648            acl_mode: AclMode::USAGE,
13649        },
13650        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13651    ],
13652};
13653pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13654    name: BUILTIN_CLUSTER_REPLICA_NAME,
13655    cluster_name: MZ_PROBE_CLUSTER.name,
13656};
13657
13658pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
13659    name: "mz_support",
13660    owner_id: &MZ_SUPPORT_ROLE_ID,
13661    privileges: &[
13662        MzAclItem {
13663            grantee: MZ_SYSTEM_ROLE_ID,
13664            grantor: MZ_SUPPORT_ROLE_ID,
13665            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13666        },
13667        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
13668    ],
13669};
13670
13671pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
13672    name: "mz_analytics",
13673    owner_id: &MZ_ANALYTICS_ROLE_ID,
13674    privileges: &[
13675        MzAclItem {
13676            grantee: MZ_SYSTEM_ROLE_ID,
13677            grantor: MZ_ANALYTICS_ROLE_ID,
13678            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13679        },
13680        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
13681    ],
13682};
13683
13684/// List of all builtin objects sorted topologically by dependency.
13685pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
13686    let mut builtins = vec![
13687        Builtin::Type(&TYPE_ANY),
13688        Builtin::Type(&TYPE_ANYARRAY),
13689        Builtin::Type(&TYPE_ANYELEMENT),
13690        Builtin::Type(&TYPE_ANYNONARRAY),
13691        Builtin::Type(&TYPE_ANYRANGE),
13692        Builtin::Type(&TYPE_BOOL),
13693        Builtin::Type(&TYPE_BOOL_ARRAY),
13694        Builtin::Type(&TYPE_BYTEA),
13695        Builtin::Type(&TYPE_BYTEA_ARRAY),
13696        Builtin::Type(&TYPE_BPCHAR),
13697        Builtin::Type(&TYPE_BPCHAR_ARRAY),
13698        Builtin::Type(&TYPE_CHAR),
13699        Builtin::Type(&TYPE_CHAR_ARRAY),
13700        Builtin::Type(&TYPE_DATE),
13701        Builtin::Type(&TYPE_DATE_ARRAY),
13702        Builtin::Type(&TYPE_FLOAT4),
13703        Builtin::Type(&TYPE_FLOAT4_ARRAY),
13704        Builtin::Type(&TYPE_FLOAT8),
13705        Builtin::Type(&TYPE_FLOAT8_ARRAY),
13706        Builtin::Type(&TYPE_INT4),
13707        Builtin::Type(&TYPE_INT4_ARRAY),
13708        Builtin::Type(&TYPE_INT8),
13709        Builtin::Type(&TYPE_INT8_ARRAY),
13710        Builtin::Type(&TYPE_INTERVAL),
13711        Builtin::Type(&TYPE_INTERVAL_ARRAY),
13712        Builtin::Type(&TYPE_JSONB),
13713        Builtin::Type(&TYPE_JSONB_ARRAY),
13714        Builtin::Type(&TYPE_LIST),
13715        Builtin::Type(&TYPE_MAP),
13716        Builtin::Type(&TYPE_NAME),
13717        Builtin::Type(&TYPE_NAME_ARRAY),
13718        Builtin::Type(&TYPE_NUMERIC),
13719        Builtin::Type(&TYPE_NUMERIC_ARRAY),
13720        Builtin::Type(&TYPE_OID),
13721        Builtin::Type(&TYPE_OID_ARRAY),
13722        Builtin::Type(&TYPE_RECORD),
13723        Builtin::Type(&TYPE_RECORD_ARRAY),
13724        Builtin::Type(&TYPE_REGCLASS),
13725        Builtin::Type(&TYPE_REGCLASS_ARRAY),
13726        Builtin::Type(&TYPE_REGPROC),
13727        Builtin::Type(&TYPE_REGPROC_ARRAY),
13728        Builtin::Type(&TYPE_REGTYPE),
13729        Builtin::Type(&TYPE_REGTYPE_ARRAY),
13730        Builtin::Type(&TYPE_INT2),
13731        Builtin::Type(&TYPE_INT2_ARRAY),
13732        Builtin::Type(&TYPE_TEXT),
13733        Builtin::Type(&TYPE_TEXT_ARRAY),
13734        Builtin::Type(&TYPE_TIME),
13735        Builtin::Type(&TYPE_TIME_ARRAY),
13736        Builtin::Type(&TYPE_TIMESTAMP),
13737        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
13738        Builtin::Type(&TYPE_TIMESTAMPTZ),
13739        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
13740        Builtin::Type(&TYPE_UUID),
13741        Builtin::Type(&TYPE_UUID_ARRAY),
13742        Builtin::Type(&TYPE_VARCHAR),
13743        Builtin::Type(&TYPE_VARCHAR_ARRAY),
13744        Builtin::Type(&TYPE_INT2_VECTOR),
13745        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
13746        Builtin::Type(&TYPE_ANYCOMPATIBLE),
13747        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
13748        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
13749        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
13750        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
13751        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
13752        Builtin::Type(&TYPE_UINT2),
13753        Builtin::Type(&TYPE_UINT2_ARRAY),
13754        Builtin::Type(&TYPE_UINT4),
13755        Builtin::Type(&TYPE_UINT4_ARRAY),
13756        Builtin::Type(&TYPE_UINT8),
13757        Builtin::Type(&TYPE_UINT8_ARRAY),
13758        Builtin::Type(&TYPE_MZ_TIMESTAMP),
13759        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
13760        Builtin::Type(&TYPE_INT4_RANGE),
13761        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
13762        Builtin::Type(&TYPE_INT8_RANGE),
13763        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
13764        Builtin::Type(&TYPE_DATE_RANGE),
13765        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
13766        Builtin::Type(&TYPE_NUM_RANGE),
13767        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
13768        Builtin::Type(&TYPE_TS_RANGE),
13769        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
13770        Builtin::Type(&TYPE_TSTZ_RANGE),
13771        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
13772        Builtin::Type(&TYPE_MZ_ACL_ITEM),
13773        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
13774        Builtin::Type(&TYPE_ACL_ITEM),
13775        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
13776        Builtin::Type(&TYPE_INTERNAL),
13777    ];
13778    for (schema, funcs) in &[
13779        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
13780        (
13781            INFORMATION_SCHEMA,
13782            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
13783        ),
13784        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
13785        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
13786        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
13787    ] {
13788        for (name, func) in funcs.iter() {
13789            builtins.push(Builtin::Func(BuiltinFunc {
13790                name,
13791                schema,
13792                inner: func,
13793            }));
13794        }
13795    }
13796    builtins.append(&mut vec![
13797        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
13798        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
13799        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
13800        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
13801        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
13802        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
13803        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
13804        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
13805        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
13806        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
13807        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
13808        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
13809        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
13810        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
13811        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
13812        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
13813        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
13814        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
13815        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
13816        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
13817        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
13818        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
13819        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
13820        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
13821        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
13822        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
13823        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
13824        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
13825        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
13826        Builtin::Log(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
13827        Builtin::Table(&MZ_KAFKA_SINKS),
13828        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
13829        Builtin::Table(&MZ_KAFKA_SOURCES),
13830        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
13831        Builtin::Table(&MZ_ICEBERG_SINKS),
13832        Builtin::Table(&MZ_DATABASES),
13833        Builtin::Table(&MZ_SCHEMAS),
13834        Builtin::Table(&MZ_COLUMNS),
13835        Builtin::Table(&MZ_INDEXES),
13836        Builtin::Table(&MZ_INDEX_COLUMNS),
13837        Builtin::Table(&MZ_TABLES),
13838        Builtin::Table(&MZ_SOURCES),
13839        Builtin::Table(&MZ_SOURCE_REFERENCES),
13840        Builtin::Table(&MZ_POSTGRES_SOURCES),
13841        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
13842        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
13843        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
13844        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
13845        Builtin::Table(&MZ_SINKS),
13846        Builtin::Table(&MZ_VIEWS),
13847        Builtin::Table(&MZ_MATERIALIZED_VIEWS),
13848        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
13849        Builtin::Table(&MZ_TYPES),
13850        Builtin::Table(&MZ_TYPE_PG_METADATA),
13851        Builtin::Table(&MZ_ARRAY_TYPES),
13852        Builtin::Table(&MZ_BASE_TYPES),
13853        Builtin::Table(&MZ_LIST_TYPES),
13854        Builtin::Table(&MZ_MAP_TYPES),
13855        Builtin::Table(&MZ_ROLES),
13856        Builtin::Table(&MZ_ROLE_AUTH),
13857        Builtin::Table(&MZ_ROLE_MEMBERS),
13858        Builtin::Table(&MZ_ROLE_PARAMETERS),
13859        Builtin::Table(&MZ_PSEUDO_TYPES),
13860        Builtin::Table(&MZ_FUNCTIONS),
13861        Builtin::Table(&MZ_OPERATORS),
13862        Builtin::Table(&MZ_AGGREGATES),
13863        Builtin::Table(&MZ_CLUSTERS),
13864        Builtin::Table(&MZ_CLUSTER_WORKLOAD_CLASSES),
13865        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
13866        Builtin::Table(&MZ_SECRETS),
13867        Builtin::Table(&MZ_CONNECTIONS),
13868        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
13869        Builtin::Table(&MZ_CLUSTER_REPLICAS),
13870        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
13871        Builtin::View(&MZ_CLUSTER_REPLICA_METRICS),
13872        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
13873        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
13874        Builtin::View(&MZ_CLUSTER_REPLICA_STATUSES),
13875        Builtin::Table(&MZ_INTERNAL_CLUSTER_REPLICAS),
13876        Builtin::Table(&MZ_PENDING_CLUSTER_REPLICAS),
13877        Builtin::Table(&MZ_AUDIT_EVENTS),
13878        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
13879        Builtin::Table(&MZ_EGRESS_IPS),
13880        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
13881        Builtin::Table(&MZ_AWS_CONNECTIONS),
13882        Builtin::Table(&MZ_SUBSCRIPTIONS),
13883        Builtin::Table(&MZ_SESSIONS),
13884        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
13885        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
13886        Builtin::Table(&MZ_COMMENTS),
13887        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
13888        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
13889        Builtin::Table(&MZ_CONTINUAL_TASKS),
13890        Builtin::Table(&MZ_NETWORK_POLICIES),
13891        Builtin::Table(&MZ_NETWORK_POLICY_RULES),
13892        Builtin::Table(&MZ_LICENSE_KEYS),
13893        Builtin::Table(&MZ_REPLACEMENTS),
13894        Builtin::View(&MZ_RELATIONS),
13895        Builtin::View(&MZ_OBJECT_OID_ALIAS),
13896        Builtin::View(&MZ_OBJECTS),
13897        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
13898        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
13899        Builtin::View(&MZ_OBJECT_HISTORY),
13900        Builtin::View(&MZ_OBJECT_LIFETIMES),
13901        Builtin::Table(&MZ_OBJECT_GLOBAL_IDS),
13902        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
13903        Builtin::View(&MZ_ARRANGEMENT_SHARING),
13904        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
13905        Builtin::View(&MZ_ARRANGEMENT_SIZES),
13906        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
13907        Builtin::View(&MZ_DATAFLOWS),
13908        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
13909        Builtin::View(&MZ_DATAFLOW_CHANNELS),
13910        Builtin::View(&MZ_DATAFLOW_OPERATORS),
13911        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
13912        Builtin::View(&MZ_MAPPABLE_OBJECTS),
13913        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
13914        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
13915        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
13916        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
13917        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
13918        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
13919        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
13920        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
13921        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
13922        Builtin::View(&MZ_COMPUTE_EXPORTS),
13923        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
13924        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
13925        Builtin::View(&MZ_COMPUTE_FRONTIERS),
13926        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
13927        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
13928        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
13929        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
13930        Builtin::View(&MZ_MESSAGE_COUNTS),
13931        Builtin::View(&MZ_ACTIVE_PEEKS),
13932        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
13933        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
13934        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
13935        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
13936        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
13937        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
13938        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
13939        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
13940        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
13941        Builtin::View(&MZ_SCHEDULING_ELAPSED),
13942        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
13943        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
13944        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
13945        Builtin::View(&MZ_SHOW_COLUMNS),
13946        Builtin::View(&MZ_SHOW_CLUSTERS),
13947        Builtin::View(&MZ_SHOW_SECRETS),
13948        Builtin::View(&MZ_SHOW_DATABASES),
13949        Builtin::View(&MZ_SHOW_SCHEMAS),
13950        Builtin::View(&MZ_SHOW_TABLES),
13951        Builtin::View(&MZ_SHOW_VIEWS),
13952        Builtin::View(&MZ_SHOW_TYPES),
13953        Builtin::View(&MZ_SHOW_ROLES),
13954        Builtin::View(&MZ_SHOW_CONNECTIONS),
13955        Builtin::View(&MZ_SHOW_SOURCES),
13956        Builtin::View(&MZ_SHOW_SINKS),
13957        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
13958        Builtin::View(&MZ_SHOW_INDEXES),
13959        Builtin::View(&MZ_SHOW_CONTINUAL_TASKS),
13960        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
13961        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
13962        Builtin::View(&MZ_TIMEZONE_NAMES),
13963        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
13964        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
13965        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
13966        Builtin::View(&PG_NAMESPACE),
13967        Builtin::View(&PG_CLASS_ALL_DATABASES),
13968        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
13969        Builtin::View(&PG_CLASS),
13970        Builtin::View(&PG_DEPEND),
13971        Builtin::View(&PG_DATABASE),
13972        Builtin::View(&PG_INDEX),
13973        Builtin::View(&PG_TYPE_ALL_DATABASES),
13974        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
13975        Builtin::View(&PG_TYPE),
13976        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
13977        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
13978        Builtin::View(&PG_DESCRIPTION),
13979        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
13980        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
13981        Builtin::View(&PG_ATTRIBUTE),
13982        Builtin::View(&PG_PROC),
13983        Builtin::View(&PG_OPERATOR),
13984        Builtin::View(&PG_RANGE),
13985        Builtin::View(&PG_ENUM),
13986        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
13987        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
13988        Builtin::View(&PG_ATTRDEF),
13989        Builtin::View(&PG_SETTINGS),
13990        Builtin::View(&PG_AUTH_MEMBERS),
13991        Builtin::View(&PG_CONSTRAINT),
13992        Builtin::View(&PG_TABLES),
13993        Builtin::View(&PG_TABLESPACE),
13994        Builtin::View(&PG_ACCESS_METHODS),
13995        Builtin::View(&PG_LOCKS),
13996        Builtin::View(&PG_AUTHID_CORE),
13997        Builtin::Index(&PG_AUTHID_CORE_IND),
13998        Builtin::View(&PG_AUTHID),
13999        Builtin::View(&PG_ROLES),
14000        Builtin::View(&PG_USER),
14001        Builtin::View(&PG_VIEWS),
14002        Builtin::View(&PG_MATVIEWS),
14003        Builtin::View(&PG_COLLATION),
14004        Builtin::View(&PG_POLICY),
14005        Builtin::View(&PG_INHERITS),
14006        Builtin::View(&PG_AGGREGATE),
14007        Builtin::View(&PG_TRIGGER),
14008        Builtin::View(&PG_REWRITE),
14009        Builtin::View(&PG_EXTENSION),
14010        Builtin::View(&PG_EVENT_TRIGGER),
14011        Builtin::View(&PG_LANGUAGE),
14012        Builtin::View(&PG_SHDESCRIPTION),
14013        Builtin::View(&PG_INDEXES),
14014        Builtin::View(&PG_TIMEZONE_ABBREVS),
14015        Builtin::View(&PG_TIMEZONE_NAMES),
14016        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
14017        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
14018        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
14019        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
14020        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
14021        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
14022        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
14023        Builtin::View(&INFORMATION_SCHEMA_TABLES),
14024        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
14025        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
14026        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
14027        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
14028        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
14029        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
14030        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
14031        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
14032        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
14033        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
14034        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
14035        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
14036        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
14037        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
14038        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
14039        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
14040        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
14041        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
14042        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
14043        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
14044        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
14045        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
14046        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
14047        Builtin::View(&MZ_SINK_STATUSES),
14048        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
14049        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
14050        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
14051        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
14052        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
14053        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
14054        Builtin::Source(&MZ_SESSION_HISTORY),
14055        Builtin::Source(&MZ_SQL_TEXT),
14056        Builtin::View(&MZ_SQL_TEXT_REDACTED),
14057        Builtin::View(&MZ_RECENT_SQL_TEXT),
14058        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
14059        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
14060        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
14061        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
14062        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
14063        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
14064        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
14065        Builtin::View(&MZ_SOURCE_STATUSES),
14066        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
14067        Builtin::Source(&MZ_STORAGE_SHARDS),
14068        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
14069        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
14070        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
14071        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
14072        Builtin::View(&MZ_SOURCE_STATISTICS),
14073        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
14074        Builtin::View(&MZ_SINK_STATISTICS),
14075        Builtin::Index(&MZ_SINK_STATISTICS_IND),
14076        Builtin::View(&MZ_STORAGE_USAGE),
14077        Builtin::Source(&MZ_FRONTIERS),
14078        Builtin::View(&MZ_GLOBAL_FRONTIERS),
14079        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
14080        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
14081        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
14082        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
14083        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
14084        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
14085        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
14086        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
14087        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
14088        Builtin::View(&MZ_MATERIALIZATION_LAG),
14089        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
14090        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
14091        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
14092        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
14093        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
14094        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
14095        Builtin::View(&MZ_LIR_MAPPING),
14096        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
14097        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
14098        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
14099        Builtin::View(&MZ_HYDRATION_STATUSES),
14100        Builtin::Index(&MZ_HYDRATION_STATUSES_IND),
14101        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
14102        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
14103        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
14104        Builtin::Index(&MZ_SHOW_DATABASES_IND),
14105        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
14106        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
14107        Builtin::Index(&MZ_SHOW_TABLES_IND),
14108        Builtin::Index(&MZ_SHOW_SOURCES_IND),
14109        Builtin::Index(&MZ_SHOW_VIEWS_IND),
14110        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
14111        Builtin::Index(&MZ_SHOW_SINKS_IND),
14112        Builtin::Index(&MZ_SHOW_TYPES_IND),
14113        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
14114        Builtin::Index(&MZ_SHOW_INDEXES_IND),
14115        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
14116        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
14117        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
14118        Builtin::Index(&MZ_SHOW_SECRETS_IND),
14119        Builtin::Index(&MZ_SHOW_ROLES_IND),
14120        Builtin::Index(&MZ_CLUSTERS_IND),
14121        Builtin::Index(&MZ_INDEXES_IND),
14122        Builtin::Index(&MZ_ROLES_IND),
14123        Builtin::Index(&MZ_SOURCES_IND),
14124        Builtin::Index(&MZ_SINKS_IND),
14125        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
14126        Builtin::Index(&MZ_CONTINUAL_TASKS_IND),
14127        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
14128        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
14129        Builtin::Index(&MZ_SINK_STATUSES_IND),
14130        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
14131        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
14132        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
14133        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
14134        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
14135        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
14136        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
14137        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
14138        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
14139        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
14140        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
14141        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
14142        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
14143        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
14144        Builtin::Index(&MZ_FRONTIERS_IND),
14145        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
14146        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
14147        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
14148        Builtin::Index(&MZ_COMMENTS_IND),
14149        Builtin::Index(&MZ_DATABASES_IND),
14150        Builtin::Index(&MZ_SCHEMAS_IND),
14151        Builtin::Index(&MZ_CONNECTIONS_IND),
14152        Builtin::Index(&MZ_TABLES_IND),
14153        Builtin::Index(&MZ_TYPES_IND),
14154        Builtin::Index(&MZ_OBJECTS_IND),
14155        Builtin::Index(&MZ_COLUMNS_IND),
14156        Builtin::Index(&MZ_SECRETS_IND),
14157        Builtin::Index(&MZ_VIEWS_IND),
14158        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
14159        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
14160        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
14161        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
14162        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
14163        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
14164        Builtin::Connection(&MZ_ANALYTICS),
14165        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT),
14166        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT),
14167        Builtin::ContinualTask(&MZ_WALLCLOCK_LAG_HISTORY_CT),
14168        Builtin::View(&MZ_INDEX_ADVICE),
14169    ]);
14170
14171    builtins.extend(notice::builtins());
14172
14173    builtins
14174});
14175pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
14176    &MZ_SYSTEM_ROLE,
14177    &MZ_SUPPORT_ROLE,
14178    &MZ_ANALYTICS_ROLE,
14179    &MZ_MONITOR_ROLE,
14180    &MZ_MONITOR_REDACTED,
14181];
14182pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
14183    &MZ_SYSTEM_CLUSTER,
14184    &MZ_CATALOG_SERVER_CLUSTER,
14185    &MZ_PROBE_CLUSTER,
14186    &MZ_SUPPORT_CLUSTER,
14187    &MZ_ANALYTICS_CLUSTER,
14188];
14189pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
14190    &MZ_SYSTEM_CLUSTER_REPLICA,
14191    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14192    &MZ_PROBE_CLUSTER_REPLICA,
14193];
14194
14195#[allow(non_snake_case)]
14196pub mod BUILTINS {
14197    use mz_sql::catalog::BuiltinsConfig;
14198
14199    use super::*;
14200
14201    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14202        BUILTINS_STATIC.iter().filter_map(|b| match b {
14203            Builtin::Log(log) => Some(*log),
14204            _ => None,
14205        })
14206    }
14207
14208    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14209        BUILTINS_STATIC.iter().filter_map(|b| match b {
14210            Builtin::Type(typ) => Some(*typ),
14211            _ => None,
14212        })
14213    }
14214
14215    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14216        BUILTINS_STATIC.iter().filter_map(|b| match b {
14217            Builtin::View(view) => Some(*view),
14218            _ => None,
14219        })
14220    }
14221
14222    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14223        BUILTINS_STATIC.iter().filter_map(|b| match b {
14224            Builtin::Func(func) => Some(func),
14225            _ => None,
14226        })
14227    }
14228
14229    pub fn iter(cfg: &BuiltinsConfig) -> impl Iterator<Item = &'static Builtin<NameReference>> {
14230        let include_continual_tasks = cfg.include_continual_tasks;
14231        BUILTINS_STATIC.iter().filter(move |x| match x {
14232            Builtin::ContinualTask(_) if !include_continual_tasks => false,
14233            _ => true,
14234        })
14235    }
14236}
14237
14238pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14239    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14240/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14241/// the builtin itself.
14242pub static BUILTIN_LOOKUP: LazyLock<
14243    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14244> = LazyLock::new(|| {
14245    // BUILTIN_LOOKUP is only ever used for lookups by key, it's not iterated,
14246    // so it's safe to include all of them, regardless of BuiltinConfig. We
14247    // enforce this statically by using the mz_ore HashMap which disallows
14248    // iteration.
14249    BUILTINS_STATIC
14250        .iter()
14251        .enumerate()
14252        .map(|(idx, builtin)| {
14253            (
14254                SystemObjectDescription {
14255                    schema_name: builtin.schema().to_string(),
14256                    object_type: builtin.catalog_item_type(),
14257                    object_name: builtin.name().to_string(),
14258                },
14259                (idx, builtin),
14260            )
14261        })
14262        .collect()
14263});
14264
14265#[mz_ore::test]
14266#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14267fn test_builtin_type_schema() {
14268    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14269
14270    for typ in BUILTINS::types() {
14271        if typ.oid < FIRST_MATERIALIZE_OID {
14272            assert_eq!(
14273                typ.schema, PG_CATALOG_SCHEMA,
14274                "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14275            );
14276        } else {
14277            // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the mz_catalog
14278            // schema.
14279            assert_eq!(
14280                typ.schema, MZ_CATALOG_SCHEMA,
14281                "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14282            );
14283        }
14284    }
14285}