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        ("namespace", "The namespace of the sink."),
2027        ("table", "The table the sink is writing to."),
2028    ]),
2029    is_retained_metrics_object: false,
2030    access: vec![PUBLIC_SELECT],
2031});
2032
2033pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2034    name: "mz_kafka_sinks",
2035    schema: MZ_CATALOG_SCHEMA,
2036    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2037    desc: RelationDesc::builder()
2038        .with_column("id", SqlScalarType::String.nullable(false))
2039        .with_column("topic", SqlScalarType::String.nullable(false))
2040        .with_key(vec![0])
2041        .finish(),
2042    column_comments: BTreeMap::from_iter([
2043        ("id", "The ID of the sink."),
2044        (
2045            "topic",
2046            "The name of the Kafka topic into which the sink is writing.",
2047        ),
2048    ]),
2049    is_retained_metrics_object: false,
2050    access: vec![PUBLIC_SELECT],
2051});
2052pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2053    name: "mz_kafka_connections",
2054    schema: MZ_CATALOG_SCHEMA,
2055    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2056    desc: RelationDesc::builder()
2057        .with_column("id", SqlScalarType::String.nullable(false))
2058        .with_column(
2059            "brokers",
2060            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2061        )
2062        .with_column("sink_progress_topic", SqlScalarType::String.nullable(false))
2063        .finish(),
2064    column_comments: BTreeMap::from_iter([
2065        ("id", "The ID of the connection."),
2066        (
2067            "brokers",
2068            "The addresses of the Kafka brokers to connect to.",
2069        ),
2070        (
2071            "sink_progress_topic",
2072            "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.",
2073        ),
2074    ]),
2075    is_retained_metrics_object: false,
2076    access: vec![PUBLIC_SELECT],
2077});
2078pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2079    name: "mz_kafka_sources",
2080    schema: MZ_CATALOG_SCHEMA,
2081    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2082    desc: RelationDesc::builder()
2083        .with_column("id", SqlScalarType::String.nullable(false))
2084        .with_column("group_id_prefix", SqlScalarType::String.nullable(false))
2085        .with_column("topic", SqlScalarType::String.nullable(false))
2086        .finish(),
2087    column_comments: BTreeMap::from_iter([
2088        (
2089            "id",
2090            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2091        ),
2092        (
2093            "group_id_prefix",
2094            "The value of the `GROUP ID PREFIX` connection option.",
2095        ),
2096        (
2097            "topic",
2098            "The name of the Kafka topic the source is reading from.",
2099        ),
2100    ]),
2101    is_retained_metrics_object: false,
2102    access: vec![PUBLIC_SELECT],
2103});
2104pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2105    name: "mz_postgres_sources",
2106    schema: MZ_INTERNAL_SCHEMA,
2107    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2108    desc: RelationDesc::builder()
2109        .with_column("id", SqlScalarType::String.nullable(false))
2110        .with_column("replication_slot", SqlScalarType::String.nullable(false))
2111        .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
2112        .finish(),
2113    column_comments: BTreeMap::from_iter([
2114        (
2115            "id",
2116            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2117        ),
2118        (
2119            "replication_slot",
2120            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2121        ),
2122        (
2123            "timeline_id",
2124            "The PostgreSQL timeline ID determined on source creation.",
2125        ),
2126    ]),
2127    is_retained_metrics_object: false,
2128    access: vec![PUBLIC_SELECT],
2129});
2130pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2131    name: "mz_postgres_source_tables",
2132    schema: MZ_INTERNAL_SCHEMA,
2133    oid: oid::TABLE_MZ_POSTGRES_SOURCE_TABLES_OID,
2134    desc: RelationDesc::builder()
2135        .with_column("id", SqlScalarType::String.nullable(false))
2136        .with_column("schema_name", SqlScalarType::String.nullable(false))
2137        .with_column("table_name", SqlScalarType::String.nullable(false))
2138        .finish(),
2139    column_comments: BTreeMap::from_iter([
2140        (
2141            "id",
2142            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2143        ),
2144        (
2145            "schema_name",
2146            "The schema of the upstream table being ingested.",
2147        ),
2148        (
2149            "table_name",
2150            "The name of the upstream table being ingested.",
2151        ),
2152    ]),
2153    is_retained_metrics_object: true,
2154    access: vec![PUBLIC_SELECT],
2155});
2156pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2157    name: "mz_mysql_source_tables",
2158    schema: MZ_INTERNAL_SCHEMA,
2159    oid: oid::TABLE_MZ_MYSQL_SOURCE_TABLES_OID,
2160    desc: RelationDesc::builder()
2161        .with_column("id", SqlScalarType::String.nullable(false))
2162        .with_column("schema_name", SqlScalarType::String.nullable(false))
2163        .with_column("table_name", SqlScalarType::String.nullable(false))
2164        .finish(),
2165    column_comments: BTreeMap::from_iter([
2166        (
2167            "id",
2168            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2169        ),
2170        (
2171            "schema_name",
2172            "The schema (or, database) of the upstream table being ingested.",
2173        ),
2174        (
2175            "table_name",
2176            "The name of the upstream table being ingested.",
2177        ),
2178    ]),
2179    is_retained_metrics_object: true,
2180    access: vec![PUBLIC_SELECT],
2181});
2182pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2183    name: "mz_sql_server_source_tables",
2184    schema: MZ_INTERNAL_SCHEMA,
2185    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2186    desc: RelationDesc::builder()
2187        .with_column("id", SqlScalarType::String.nullable(false))
2188        .with_column("schema_name", SqlScalarType::String.nullable(false))
2189        .with_column("table_name", SqlScalarType::String.nullable(false))
2190        .finish(),
2191    column_comments: BTreeMap::from_iter([
2192        (
2193            "id",
2194            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2195        ),
2196        (
2197            "schema_name",
2198            "The schema (or, database) of the upstream table being ingested.",
2199        ),
2200        (
2201            "table_name",
2202            "The name of the upstream table being ingested.",
2203        ),
2204    ]),
2205    is_retained_metrics_object: true,
2206    access: vec![PUBLIC_SELECT],
2207});
2208pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2209    name: "mz_kafka_source_tables",
2210    schema: MZ_INTERNAL_SCHEMA,
2211    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2212    desc: RelationDesc::builder()
2213        .with_column("id", SqlScalarType::String.nullable(false))
2214        .with_column("topic", SqlScalarType::String.nullable(false))
2215        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2216        .with_column("key_format", SqlScalarType::String.nullable(true))
2217        .with_column("value_format", SqlScalarType::String.nullable(true))
2218        .finish(),
2219    column_comments: BTreeMap::from_iter([
2220        (
2221            "id",
2222            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2223        ),
2224        ("topic", "The topic being ingested."),
2225        (
2226            "envelope_type",
2227            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2228        ),
2229        (
2230            "key_format",
2231            "The format of the Kafka message key: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2232        ),
2233        (
2234            "value_format",
2235            "The format of the Kafka message value: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2236        ),
2237    ]),
2238    is_retained_metrics_object: true,
2239    access: vec![PUBLIC_SELECT],
2240});
2241pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2242    name: "mz_object_dependencies",
2243    schema: MZ_INTERNAL_SCHEMA,
2244    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2245    desc: RelationDesc::builder()
2246        .with_column("object_id", SqlScalarType::String.nullable(false))
2247        .with_column(
2248            "referenced_object_id",
2249            SqlScalarType::String.nullable(false),
2250        )
2251        .finish(),
2252    column_comments: BTreeMap::from_iter([
2253        (
2254            "object_id",
2255            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2256        ),
2257        (
2258            "referenced_object_id",
2259            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2260        ),
2261    ]),
2262    is_retained_metrics_object: true,
2263    access: vec![PUBLIC_SELECT],
2264});
2265pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2266    name: "mz_compute_dependencies",
2267    schema: MZ_INTERNAL_SCHEMA,
2268    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2269    data_source: IntrospectionType::ComputeDependencies,
2270    desc: RelationDesc::builder()
2271        .with_column("object_id", SqlScalarType::String.nullable(false))
2272        .with_column("dependency_id", SqlScalarType::String.nullable(false))
2273        .finish(),
2274    column_comments: BTreeMap::from_iter([
2275        (
2276            "object_id",
2277            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2278        ),
2279        (
2280            "dependency_id",
2281            "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`.",
2282        ),
2283    ]),
2284    is_retained_metrics_object: false,
2285    access: vec![PUBLIC_SELECT],
2286});
2287
2288pub static MZ_DATABASES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2289    name: "mz_databases",
2290    schema: MZ_CATALOG_SCHEMA,
2291    oid: oid::TABLE_MZ_DATABASES_OID,
2292    desc: RelationDesc::builder()
2293        .with_column("id", SqlScalarType::String.nullable(false))
2294        .with_column("oid", SqlScalarType::Oid.nullable(false))
2295        .with_column("name", SqlScalarType::String.nullable(false))
2296        .with_column("owner_id", SqlScalarType::String.nullable(false))
2297        .with_column(
2298            "privileges",
2299            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2300        )
2301        .with_key(vec![0])
2302        .with_key(vec![1])
2303        .finish(),
2304    column_comments: BTreeMap::from_iter([
2305        ("id", "Materialize's unique ID for the database."),
2306        (
2307            "oid",
2308            "A [PostgreSQL-compatible OID][`oid`] for the database.",
2309        ),
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        (
2340            "oid",
2341            "A [PostgreSQL-compatible oid][`oid`] for the schema.",
2342        ),
2343        (
2344            "database_id",
2345            "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2346        ),
2347        ("name", "The name of the schema."),
2348        (
2349            "owner_id",
2350            "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2351        ),
2352        ("privileges", "The privileges belonging to the schema."),
2353    ]),
2354    is_retained_metrics_object: false,
2355    access: vec![PUBLIC_SELECT],
2356});
2357pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2358    name: "mz_columns",
2359    schema: MZ_CATALOG_SCHEMA,
2360    oid: oid::TABLE_MZ_COLUMNS_OID,
2361    desc: RelationDesc::builder()
2362        .with_column("id", SqlScalarType::String.nullable(false)) // not a key
2363        .with_column("name", SqlScalarType::String.nullable(false))
2364        .with_column("position", SqlScalarType::UInt64.nullable(false))
2365        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2366        .with_column("type", SqlScalarType::String.nullable(false))
2367        .with_column("default", SqlScalarType::String.nullable(true))
2368        .with_column("type_oid", SqlScalarType::Oid.nullable(false))
2369        .with_column("type_mod", SqlScalarType::Int32.nullable(false))
2370        .finish(),
2371    column_comments: BTreeMap::from_iter([
2372        (
2373            "id",
2374            "The unique ID of the table, source, or view containing the column.",
2375        ),
2376        ("name", "The name of the column."),
2377        (
2378            "position",
2379            "The 1-indexed position of the column in its containing table, source, or view.",
2380        ),
2381        ("nullable", "Can the column contain a `NULL` value?"),
2382        ("type", "The data type of the column."),
2383        ("default", "The default expression of the column."),
2384        (
2385            "type_oid",
2386            "The OID of the type of the column (references `mz_types`).",
2387        ),
2388        ("type_mod", "The packed type identifier of the column."),
2389    ]),
2390    is_retained_metrics_object: false,
2391    access: vec![PUBLIC_SELECT],
2392});
2393pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2394    name: "mz_indexes",
2395    schema: MZ_CATALOG_SCHEMA,
2396    oid: oid::TABLE_MZ_INDEXES_OID,
2397    desc: RelationDesc::builder()
2398        .with_column("id", SqlScalarType::String.nullable(false))
2399        .with_column("oid", SqlScalarType::Oid.nullable(false))
2400        .with_column("name", SqlScalarType::String.nullable(false))
2401        .with_column("on_id", SqlScalarType::String.nullable(false))
2402        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2403        .with_column("owner_id", SqlScalarType::String.nullable(false))
2404        .with_column("create_sql", SqlScalarType::String.nullable(false))
2405        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2406        .with_key(vec![0])
2407        .with_key(vec![1])
2408        .finish(),
2409    column_comments: BTreeMap::from_iter([
2410        ("id", "Materialize's unique ID for the index."),
2411        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the index."),
2412        ("name", "The name of the index."),
2413        (
2414            "on_id",
2415            "The ID of the relation on which the index is built.",
2416        ),
2417        (
2418            "cluster_id",
2419            "The ID of the cluster in which the index is built.",
2420        ),
2421        (
2422            "owner_id",
2423            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2424        ),
2425        ("create_sql", "The `CREATE` SQL statement for the index."),
2426        (
2427            "redacted_create_sql",
2428            "The redacted `CREATE` SQL statement for the index.",
2429        ),
2430    ]),
2431    is_retained_metrics_object: false,
2432    access: vec![PUBLIC_SELECT],
2433});
2434pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2435    name: "mz_index_columns",
2436    schema: MZ_CATALOG_SCHEMA,
2437    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2438    desc: RelationDesc::builder()
2439        .with_column("index_id", SqlScalarType::String.nullable(false))
2440        .with_column("index_position", SqlScalarType::UInt64.nullable(false))
2441        .with_column("on_position", SqlScalarType::UInt64.nullable(true))
2442        .with_column("on_expression", SqlScalarType::String.nullable(true))
2443        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2444        .finish(),
2445    column_comments: BTreeMap::from_iter([
2446        (
2447            "index_id",
2448            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2449        ),
2450        (
2451            "index_position",
2452            "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.)",
2453        ),
2454        (
2455            "on_position",
2456            "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.",
2457        ),
2458        (
2459            "on_expression",
2460            "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.",
2461        ),
2462        (
2463            "nullable",
2464            "Can this column of the index evaluate to `NULL`?",
2465        ),
2466    ]),
2467    is_retained_metrics_object: false,
2468    access: vec![PUBLIC_SELECT],
2469});
2470pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2471    name: "mz_tables",
2472    schema: MZ_CATALOG_SCHEMA,
2473    oid: oid::TABLE_MZ_TABLES_OID,
2474    desc: RelationDesc::builder()
2475        .with_column("id", SqlScalarType::String.nullable(false))
2476        .with_column("oid", SqlScalarType::Oid.nullable(false))
2477        .with_column("schema_id", SqlScalarType::String.nullable(false))
2478        .with_column("name", SqlScalarType::String.nullable(false))
2479        .with_column("owner_id", SqlScalarType::String.nullable(false))
2480        .with_column(
2481            "privileges",
2482            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2483        )
2484        .with_column("create_sql", SqlScalarType::String.nullable(true))
2485        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2486        .with_column("source_id", SqlScalarType::String.nullable(true))
2487        .with_key(vec![0])
2488        .with_key(vec![1])
2489        .finish(),
2490    column_comments: BTreeMap::from_iter([
2491        ("id", "Materialize's unique ID for the table."),
2492        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the table."),
2493        (
2494            "schema_id",
2495            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2496        ),
2497        ("name", "The name of the table."),
2498        (
2499            "owner_id",
2500            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2501        ),
2502        ("privileges", "The privileges belonging to the table."),
2503        ("create_sql", "The `CREATE` SQL statement for the table."),
2504        (
2505            "redacted_create_sql",
2506            "The redacted `CREATE` SQL statement for the table.",
2507        ),
2508        (
2509            "source_id",
2510            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2511        ),
2512    ]),
2513    is_retained_metrics_object: true,
2514    access: vec![PUBLIC_SELECT],
2515});
2516pub static MZ_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2517    name: "mz_connections",
2518    schema: MZ_CATALOG_SCHEMA,
2519    oid: oid::TABLE_MZ_CONNECTIONS_OID,
2520    desc: RelationDesc::builder()
2521        .with_column("id", SqlScalarType::String.nullable(false))
2522        .with_column("oid", SqlScalarType::Oid.nullable(false))
2523        .with_column("schema_id", SqlScalarType::String.nullable(false))
2524        .with_column("name", SqlScalarType::String.nullable(false))
2525        .with_column("type", SqlScalarType::String.nullable(false))
2526        .with_column("owner_id", SqlScalarType::String.nullable(false))
2527        .with_column(
2528            "privileges",
2529            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2530        )
2531        .with_column("create_sql", SqlScalarType::String.nullable(false))
2532        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2533        .with_key(vec![0])
2534        .with_key(vec![1])
2535        .finish(),
2536    column_comments: BTreeMap::from_iter([
2537        ("id", "The unique ID of the connection."),
2538        (
2539            "oid",
2540            "A [PostgreSQL-compatible OID][`oid`] for the connection.",
2541        ),
2542        (
2543            "schema_id",
2544            "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2545        ),
2546        ("name", "The name of the connection."),
2547        (
2548            "type",
2549            "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2550        ),
2551        (
2552            "owner_id",
2553            "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2554        ),
2555        ("privileges", "The privileges belonging to the connection."),
2556        (
2557            "create_sql",
2558            "The `CREATE` SQL statement for the connection.",
2559        ),
2560        (
2561            "redacted_create_sql",
2562            "The redacted `CREATE` SQL statement for the connection.",
2563        ),
2564    ]),
2565    is_retained_metrics_object: false,
2566    access: vec![PUBLIC_SELECT],
2567});
2568pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2569    name: "mz_ssh_tunnel_connections",
2570    schema: MZ_CATALOG_SCHEMA,
2571    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2572    desc: RelationDesc::builder()
2573        .with_column("id", SqlScalarType::String.nullable(false))
2574        .with_column("public_key_1", SqlScalarType::String.nullable(false))
2575        .with_column("public_key_2", SqlScalarType::String.nullable(false))
2576        .finish(),
2577    column_comments: BTreeMap::from_iter([
2578        ("id", "The ID of the connection."),
2579        (
2580            "public_key_1",
2581            "The first public key associated with the SSH tunnel.",
2582        ),
2583        (
2584            "public_key_2",
2585            "The second public key associated with the SSH tunnel.",
2586        ),
2587    ]),
2588    is_retained_metrics_object: false,
2589    access: vec![PUBLIC_SELECT],
2590});
2591pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2592    name: "mz_sources",
2593    schema: MZ_CATALOG_SCHEMA,
2594    oid: oid::TABLE_MZ_SOURCES_OID,
2595    desc: RelationDesc::builder()
2596        .with_column("id", SqlScalarType::String.nullable(false))
2597        .with_column("oid", SqlScalarType::Oid.nullable(false))
2598        .with_column("schema_id", SqlScalarType::String.nullable(false))
2599        .with_column("name", SqlScalarType::String.nullable(false))
2600        .with_column("type", SqlScalarType::String.nullable(false))
2601        .with_column("connection_id", SqlScalarType::String.nullable(true))
2602        .with_column("size", SqlScalarType::String.nullable(true))
2603        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2604        .with_column("key_format", SqlScalarType::String.nullable(true))
2605        .with_column("value_format", SqlScalarType::String.nullable(true))
2606        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2607        .with_column("owner_id", SqlScalarType::String.nullable(false))
2608        .with_column(
2609            "privileges",
2610            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2611        )
2612        .with_column("create_sql", SqlScalarType::String.nullable(true))
2613        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2614        .with_key(vec![0])
2615        .with_key(vec![1])
2616        .finish(),
2617    column_comments: BTreeMap::from_iter([
2618        ("id", "Materialize's unique ID for the source."),
2619        (
2620            "oid",
2621            "A [PostgreSQL-compatible OID][`oid`] for the source.",
2622        ),
2623        (
2624            "schema_id",
2625            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2626        ),
2627        ("name", "The name of the source."),
2628        (
2629            "type",
2630            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2631        ),
2632        (
2633            "connection_id",
2634            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2635        ),
2636        ("size", "Deprecated The size of the source."),
2637        (
2638            "envelope_type",
2639            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2640        ),
2641        (
2642            "key_format",
2643            "For Kafka sources, the format of the Kafka message key: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2644        ),
2645        (
2646            "value_format",
2647            "For Kafka sources, the format of the Kafka message value: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2648        ),
2649        (
2650            "cluster_id",
2651            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2652        ),
2653        (
2654            "owner_id",
2655            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2656        ),
2657        ("privileges", "The privileges granted on the source."),
2658        ("create_sql", "The `CREATE` SQL statement for the source."),
2659        (
2660            "redacted_create_sql",
2661            "The redacted `CREATE` SQL statement for the source.",
2662        ),
2663    ]),
2664    is_retained_metrics_object: true,
2665    access: vec![PUBLIC_SELECT],
2666});
2667pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2668    BuiltinTable {
2669        name: "mz_sinks",
2670        schema: MZ_CATALOG_SCHEMA,
2671        oid: oid::TABLE_MZ_SINKS_OID,
2672        desc: RelationDesc::builder()
2673            .with_column("id", SqlScalarType::String.nullable(false))
2674            .with_column("oid", SqlScalarType::Oid.nullable(false))
2675            .with_column("schema_id", SqlScalarType::String.nullable(false))
2676            .with_column("name", SqlScalarType::String.nullable(false))
2677            .with_column("type", SqlScalarType::String.nullable(false))
2678            .with_column("connection_id", SqlScalarType::String.nullable(true))
2679            .with_column("size", SqlScalarType::String.nullable(true))
2680            .with_column("envelope_type", SqlScalarType::String.nullable(true))
2681            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2682            // below. This should be removed in the future.
2683            .with_column("format", SqlScalarType::String.nullable(true))
2684            .with_column("key_format", SqlScalarType::String.nullable(true))
2685            .with_column("value_format", SqlScalarType::String.nullable(true))
2686            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2687            .with_column("owner_id", SqlScalarType::String.nullable(false))
2688            .with_column("create_sql", SqlScalarType::String.nullable(false))
2689            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2690            .with_key(vec![0])
2691            .with_key(vec![1])
2692            .finish(),
2693        column_comments: BTreeMap::from_iter([
2694            ("id", "Materialize's unique ID for the sink."),
2695            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the sink."),
2696            (
2697                "schema_id",
2698                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2699            ),
2700            ("name", "The name of the sink."),
2701            ("type", "The type of the sink: `kafka`."),
2702            (
2703                "connection_id",
2704                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2705            ),
2706            ("size", "The size of the sink."),
2707            (
2708                "envelope_type",
2709                "The envelope of the sink: `upsert`, or `debezium`.",
2710            ),
2711            (
2712                "format",
2713                "Deprecated The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2714            ),
2715            (
2716                "key_format",
2717                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2718            ),
2719            (
2720                "value_format",
2721                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2722            ),
2723            (
2724                "cluster_id",
2725                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2726            ),
2727            (
2728                "owner_id",
2729                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2730            ),
2731            ("create_sql", "The `CREATE` SQL statement for the sink."),
2732            (
2733                "redacted_create_sql",
2734                "The redacted `CREATE` SQL statement for the sink.",
2735            ),
2736        ]),
2737        is_retained_metrics_object: true,
2738        access: vec![PUBLIC_SELECT],
2739    }
2740});
2741pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2742    name: "mz_views",
2743    schema: MZ_CATALOG_SCHEMA,
2744    oid: oid::TABLE_MZ_VIEWS_OID,
2745    desc: RelationDesc::builder()
2746        .with_column("id", SqlScalarType::String.nullable(false))
2747        .with_column("oid", SqlScalarType::Oid.nullable(false))
2748        .with_column("schema_id", SqlScalarType::String.nullable(false))
2749        .with_column("name", SqlScalarType::String.nullable(false))
2750        .with_column("definition", SqlScalarType::String.nullable(false))
2751        .with_column("owner_id", SqlScalarType::String.nullable(false))
2752        .with_column(
2753            "privileges",
2754            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2755        )
2756        .with_column("create_sql", SqlScalarType::String.nullable(false))
2757        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2758        .with_key(vec![0])
2759        .with_key(vec![1])
2760        .finish(),
2761    column_comments: BTreeMap::from_iter([
2762        ("id", "Materialize's unique ID for the view."),
2763        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the view."),
2764        (
2765            "schema_id",
2766            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2767        ),
2768        ("name", "The name of the view."),
2769        ("definition", "The view definition (a `SELECT` query)."),
2770        (
2771            "owner_id",
2772            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2773        ),
2774        ("privileges", "The privileges belonging to the view."),
2775        ("create_sql", "The `CREATE` SQL statement for the view."),
2776        (
2777            "redacted_create_sql",
2778            "The redacted `CREATE` SQL statement for the view.",
2779        ),
2780    ]),
2781    is_retained_metrics_object: false,
2782    access: vec![PUBLIC_SELECT],
2783});
2784pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2785    name: "mz_materialized_views",
2786    schema: MZ_CATALOG_SCHEMA,
2787    oid: oid::TABLE_MZ_MATERIALIZED_VIEWS_OID,
2788    desc: RelationDesc::builder()
2789        .with_column("id", SqlScalarType::String.nullable(false))
2790        .with_column("oid", SqlScalarType::Oid.nullable(false))
2791        .with_column("schema_id", SqlScalarType::String.nullable(false))
2792        .with_column("name", SqlScalarType::String.nullable(false))
2793        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2794        .with_column("definition", SqlScalarType::String.nullable(false))
2795        .with_column("owner_id", SqlScalarType::String.nullable(false))
2796        .with_column(
2797            "privileges",
2798            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2799        )
2800        .with_column("create_sql", SqlScalarType::String.nullable(false))
2801        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2802        .with_key(vec![0])
2803        .with_key(vec![1])
2804        .finish(),
2805    column_comments: BTreeMap::from_iter([
2806        ("id", "Materialize's unique ID for the materialized view."),
2807        (
2808            "oid",
2809            "A [PostgreSQL-compatible OID][`oid`] for the materialized view.",
2810        ),
2811        (
2812            "schema_id",
2813            "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2814        ),
2815        ("name", "The name of the materialized view."),
2816        (
2817            "cluster_id",
2818            "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2819        ),
2820        (
2821            "definition",
2822            "The materialized view definition (a `SELECT` query).",
2823        ),
2824        (
2825            "owner_id",
2826            "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2827        ),
2828        (
2829            "privileges",
2830            "The privileges belonging to the materialized view.",
2831        ),
2832        (
2833            "create_sql",
2834            "The `CREATE` SQL statement for the materialized view.",
2835        ),
2836        (
2837            "redacted_create_sql",
2838            "The redacted `CREATE` SQL statement for the materialized view.",
2839        ),
2840    ]),
2841    is_retained_metrics_object: false,
2842    access: vec![PUBLIC_SELECT],
2843});
2844pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
2845    BuiltinTable {
2846        name: "mz_materialized_view_refresh_strategies",
2847        schema: MZ_INTERNAL_SCHEMA,
2848        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
2849        desc: RelationDesc::builder()
2850            .with_column(
2851                "materialized_view_id",
2852                SqlScalarType::String.nullable(false),
2853            )
2854            .with_column("type", SqlScalarType::String.nullable(false))
2855            .with_column("interval", SqlScalarType::Interval.nullable(true))
2856            .with_column(
2857                "aligned_to",
2858                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2859            )
2860            .with_column(
2861                "at",
2862                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2863            )
2864            .finish(),
2865        column_comments: BTreeMap::from_iter([
2866            (
2867                "materialized_view_id",
2868                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
2869            ),
2870            (
2871                "type",
2872                "`at`, `every`, or `on-commit`. Default: `on-commit`",
2873            ),
2874            (
2875                "interval",
2876                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2877            ),
2878            (
2879                "aligned_to",
2880                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2881            ),
2882            (
2883                "at",
2884                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
2885            ),
2886        ]),
2887        is_retained_metrics_object: false,
2888        access: vec![PUBLIC_SELECT],
2889    }
2890});
2891pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2892    name: "mz_types",
2893    schema: MZ_CATALOG_SCHEMA,
2894    oid: oid::TABLE_MZ_TYPES_OID,
2895    desc: RelationDesc::builder()
2896        .with_column("id", SqlScalarType::String.nullable(false))
2897        .with_column("oid", SqlScalarType::Oid.nullable(false))
2898        .with_column("schema_id", SqlScalarType::String.nullable(false))
2899        .with_column("name", SqlScalarType::String.nullable(false))
2900        .with_column("category", SqlScalarType::String.nullable(false))
2901        .with_column("owner_id", SqlScalarType::String.nullable(false))
2902        .with_column(
2903            "privileges",
2904            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2905        )
2906        .with_column("create_sql", SqlScalarType::String.nullable(true))
2907        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2908        .with_key(vec![0])
2909        .with_key(vec![1])
2910        .finish(),
2911    column_comments: BTreeMap::from_iter([
2912        ("id", "Materialize's unique ID for the type."),
2913        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the type."),
2914        (
2915            "schema_id",
2916            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
2917        ),
2918        ("name", "The name of the type."),
2919        ("category", "The category of the type."),
2920        (
2921            "owner_id",
2922            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
2923        ),
2924        ("privileges", "The privileges belonging to the type."),
2925        ("create_sql", "The `CREATE` SQL statement for the type."),
2926        (
2927            "redacted_create_sql",
2928            "The redacted `CREATE` SQL statement for the type.",
2929        ),
2930    ]),
2931    is_retained_metrics_object: false,
2932    access: vec![PUBLIC_SELECT],
2933});
2934pub static MZ_CONTINUAL_TASKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2935    name: "mz_continual_tasks",
2936    schema: MZ_INTERNAL_SCHEMA,
2937    oid: oid::TABLE_MZ_CONTINUAL_TASKS_OID,
2938    desc: RelationDesc::builder()
2939        .with_column("id", SqlScalarType::String.nullable(false))
2940        .with_column("oid", SqlScalarType::Oid.nullable(false))
2941        .with_column("schema_id", SqlScalarType::String.nullable(false))
2942        .with_column("name", SqlScalarType::String.nullable(false))
2943        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2944        .with_column("definition", SqlScalarType::String.nullable(false))
2945        .with_column("owner_id", SqlScalarType::String.nullable(false))
2946        .with_column(
2947            "privileges",
2948            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2949        )
2950        .with_column("create_sql", SqlScalarType::String.nullable(false))
2951        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2952        .with_key(vec![0])
2953        .with_key(vec![1])
2954        .finish(),
2955    column_comments: BTreeMap::new(),
2956    is_retained_metrics_object: false,
2957    access: vec![PUBLIC_SELECT],
2958});
2959pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2960    name: "mz_network_policies",
2961    schema: MZ_INTERNAL_SCHEMA,
2962    oid: oid::TABLE_MZ_NETWORK_POLICIES_OID,
2963    desc: RelationDesc::builder()
2964        .with_column("id", SqlScalarType::String.nullable(false))
2965        .with_column("name", SqlScalarType::String.nullable(false))
2966        .with_column("owner_id", SqlScalarType::String.nullable(false))
2967        .with_column(
2968            "privileges",
2969            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2970        )
2971        .with_column("oid", SqlScalarType::Oid.nullable(false))
2972        .finish(),
2973    column_comments: BTreeMap::from_iter([
2974        ("id", "The ID of the network policy."),
2975        ("name", "The name of the network policy."),
2976        (
2977            "owner_id",
2978            "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
2979        ),
2980        (
2981            "privileges",
2982            "The privileges belonging to the network policy.",
2983        ),
2984        (
2985            "oid",
2986            "A [PostgreSQL-compatible OID][`oid`] for the network policy.",
2987        ),
2988    ]),
2989    is_retained_metrics_object: false,
2990    access: vec![PUBLIC_SELECT],
2991});
2992pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2993    name: "mz_network_policy_rules",
2994    schema: MZ_INTERNAL_SCHEMA,
2995    oid: oid::TABLE_MZ_NETWORK_POLICY_RULES_OID,
2996    desc: RelationDesc::builder()
2997        .with_column("name", SqlScalarType::String.nullable(false))
2998        .with_column("policy_id", SqlScalarType::String.nullable(false))
2999        .with_column("action", SqlScalarType::String.nullable(false))
3000        .with_column("address", SqlScalarType::String.nullable(false))
3001        .with_column("direction", SqlScalarType::String.nullable(false))
3002        .finish(),
3003    column_comments: BTreeMap::from_iter([
3004        (
3005            "name",
3006            "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
3007        ),
3008        (
3009            "policy_id",
3010            "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
3011        ),
3012        (
3013            "action",
3014            "The action of the rule. `allow` is the only supported action.",
3015        ),
3016        ("address", "The address the rule will take action on."),
3017        (
3018            "direction",
3019            "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3020        ),
3021    ]),
3022    is_retained_metrics_object: false,
3023    access: vec![PUBLIC_SELECT],
3024});
3025/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3026/// in the `mz_types` table as part of our public, stable API.
3027pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3028    name: "mz_type_pg_metadata",
3029    schema: MZ_INTERNAL_SCHEMA,
3030    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3031    desc: RelationDesc::builder()
3032        .with_column("id", SqlScalarType::String.nullable(false))
3033        .with_column("typinput", SqlScalarType::Oid.nullable(false))
3034        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
3035        .finish(),
3036    column_comments: BTreeMap::new(),
3037    is_retained_metrics_object: false,
3038    access: vec![PUBLIC_SELECT],
3039});
3040pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3041    name: "mz_array_types",
3042    schema: MZ_CATALOG_SCHEMA,
3043    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3044    desc: RelationDesc::builder()
3045        .with_column("id", SqlScalarType::String.nullable(false))
3046        .with_column("element_id", SqlScalarType::String.nullable(false))
3047        .finish(),
3048    column_comments: BTreeMap::from_iter([
3049        ("id", "The ID of the array type."),
3050        ("element_id", "The ID of the array's element type."),
3051    ]),
3052    is_retained_metrics_object: false,
3053    access: vec![PUBLIC_SELECT],
3054});
3055pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3056    name: "mz_base_types",
3057    schema: MZ_CATALOG_SCHEMA,
3058    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3059    desc: RelationDesc::builder()
3060        .with_column("id", SqlScalarType::String.nullable(false))
3061        .finish(),
3062    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3063    is_retained_metrics_object: false,
3064    access: vec![PUBLIC_SELECT],
3065});
3066pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3067    name: "mz_list_types",
3068    schema: MZ_CATALOG_SCHEMA,
3069    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3070    desc: RelationDesc::builder()
3071        .with_column("id", SqlScalarType::String.nullable(false))
3072        .with_column("element_id", SqlScalarType::String.nullable(false))
3073        .with_column(
3074            "element_modifiers",
3075            SqlScalarType::List {
3076                element_type: Box::new(SqlScalarType::Int64),
3077                custom_id: None,
3078            }
3079            .nullable(true),
3080        )
3081        .finish(),
3082    column_comments: BTreeMap::from_iter([
3083        ("id", "The ID of the list type."),
3084        ("element_id", "The IID of the list's element type."),
3085        (
3086            "element_modifiers",
3087            "The element type modifiers, or `NULL` if none.",
3088        ),
3089    ]),
3090    is_retained_metrics_object: false,
3091    access: vec![PUBLIC_SELECT],
3092});
3093pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3094    name: "mz_map_types",
3095    schema: MZ_CATALOG_SCHEMA,
3096    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3097    desc: RelationDesc::builder()
3098        .with_column("id", SqlScalarType::String.nullable(false))
3099        .with_column("key_id", SqlScalarType::String.nullable(false))
3100        .with_column("value_id", SqlScalarType::String.nullable(false))
3101        .with_column(
3102            "key_modifiers",
3103            SqlScalarType::List {
3104                element_type: Box::new(SqlScalarType::Int64),
3105                custom_id: None,
3106            }
3107            .nullable(true),
3108        )
3109        .with_column(
3110            "value_modifiers",
3111            SqlScalarType::List {
3112                element_type: Box::new(SqlScalarType::Int64),
3113                custom_id: None,
3114            }
3115            .nullable(true),
3116        )
3117        .finish(),
3118    column_comments: BTreeMap::from_iter([
3119        ("id", "The ID of the map type."),
3120        ("key_id", "The ID of the map's key type."),
3121        ("value_id", "The ID of the map's value type."),
3122        (
3123            "key_modifiers",
3124            "The key type modifiers, or `NULL` if none.",
3125        ),
3126        (
3127            "value_modifiers",
3128            "The value type modifiers, or `NULL` if none.",
3129        ),
3130    ]),
3131    is_retained_metrics_object: false,
3132    access: vec![PUBLIC_SELECT],
3133});
3134pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3135    name: "mz_roles",
3136    schema: MZ_CATALOG_SCHEMA,
3137    oid: oid::TABLE_MZ_ROLES_OID,
3138    desc: RelationDesc::builder()
3139        .with_column("id", SqlScalarType::String.nullable(false))
3140        .with_column("oid", SqlScalarType::Oid.nullable(false))
3141        .with_column("name", SqlScalarType::String.nullable(false))
3142        .with_column("inherit", SqlScalarType::Bool.nullable(false))
3143        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(true))
3144        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
3145        .with_key(vec![0])
3146        .with_key(vec![1])
3147        .finish(),
3148    column_comments: BTreeMap::from_iter([
3149        ("id", "Materialize's unique ID for the role."),
3150        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the role."),
3151        ("name", "The name of the role."),
3152        (
3153            "inherit",
3154            "Indicates whether the role has inheritance of privileges.",
3155        ),
3156        (
3157            "rolcanlogin",
3158            "Indicates whether the role can log in (i.e., is a user).",
3159        ),
3160        ("rolsuper", "Indicates whether the role is a superuser."),
3161    ]),
3162    is_retained_metrics_object: false,
3163    access: vec![PUBLIC_SELECT],
3164});
3165pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3166    name: "mz_role_members",
3167    schema: MZ_CATALOG_SCHEMA,
3168    oid: oid::TABLE_MZ_ROLE_MEMBERS_OID,
3169    desc: RelationDesc::builder()
3170        .with_column("role_id", SqlScalarType::String.nullable(false))
3171        .with_column("member", SqlScalarType::String.nullable(false))
3172        .with_column("grantor", SqlScalarType::String.nullable(false))
3173        .finish(),
3174    column_comments: BTreeMap::from_iter([
3175        (
3176            "role_id",
3177            "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3178        ),
3179        (
3180            "member",
3181            "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3182        ),
3183        (
3184            "grantor",
3185            "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3186        ),
3187    ]),
3188    is_retained_metrics_object: false,
3189    access: vec![PUBLIC_SELECT],
3190});
3191pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3192    name: "mz_role_parameters",
3193    schema: MZ_CATALOG_SCHEMA,
3194    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3195    desc: RelationDesc::builder()
3196        .with_column("role_id", SqlScalarType::String.nullable(false))
3197        .with_column("parameter_name", SqlScalarType::String.nullable(false))
3198        .with_column("parameter_value", SqlScalarType::String.nullable(false))
3199        .finish(),
3200    column_comments: BTreeMap::from_iter([
3201        (
3202            "role_id",
3203            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3204        ),
3205        (
3206            "parameter_name",
3207            "The configuration parameter name. One of the supported configuration parameters.",
3208        ),
3209        (
3210            "parameter_value",
3211            "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.",
3212        ),
3213    ]),
3214    is_retained_metrics_object: false,
3215    access: vec![PUBLIC_SELECT],
3216});
3217pub static MZ_ROLE_AUTH: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3218    name: "mz_role_auth",
3219    schema: MZ_CATALOG_SCHEMA,
3220    oid: oid::TABLE_MZ_ROLE_AUTH_OID,
3221    desc: RelationDesc::builder()
3222        .with_column("role_id", SqlScalarType::String.nullable(false))
3223        .with_column("role_oid", SqlScalarType::Oid.nullable(false))
3224        .with_column("password_hash", SqlScalarType::String.nullable(true))
3225        .with_column(
3226            "updated_at",
3227            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3228        )
3229        .finish(),
3230    column_comments: BTreeMap::from_iter([
3231        (
3232            "role_id",
3233            "The ID of the role. Corresponds to `mz_roles.id`.",
3234        ),
3235        (
3236            "role_oid",
3237            "The OID of the role whose configuration parameter default is set. Corresponds to `mz_roles.oid`.",
3238        ),
3239        ("password_hash", "The hashed password for the role"),
3240        (
3241            "updated_at",
3242            "The timestamp when the password was last updated.",
3243        ),
3244    ]),
3245    is_retained_metrics_object: false,
3246    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
3247});
3248pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3249    name: "mz_pseudo_types",
3250    schema: MZ_CATALOG_SCHEMA,
3251    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3252    desc: RelationDesc::builder()
3253        .with_column("id", SqlScalarType::String.nullable(false))
3254        .finish(),
3255    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3256    is_retained_metrics_object: false,
3257    access: vec![PUBLIC_SELECT],
3258});
3259pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3260    BuiltinTable {
3261        name: "mz_functions",
3262        schema: MZ_CATALOG_SCHEMA,
3263        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3264        desc: RelationDesc::builder()
3265            .with_column("id", SqlScalarType::String.nullable(false)) // not a key!
3266            .with_column("oid", SqlScalarType::Oid.nullable(false))
3267            .with_column("schema_id", SqlScalarType::String.nullable(false))
3268            .with_column("name", SqlScalarType::String.nullable(false))
3269            .with_column(
3270                "argument_type_ids",
3271                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3272            )
3273            .with_column(
3274                "variadic_argument_type_id",
3275                SqlScalarType::String.nullable(true),
3276            )
3277            .with_column("return_type_id", SqlScalarType::String.nullable(true))
3278            .with_column("returns_set", SqlScalarType::Bool.nullable(false))
3279            .with_column("owner_id", SqlScalarType::String.nullable(false))
3280            .finish(),
3281        column_comments: BTreeMap::from_iter([
3282            ("id", "Materialize's unique ID for the function."),
3283            (
3284                "oid",
3285                "A [PostgreSQL-compatible OID][`oid`] for the function.",
3286            ),
3287            (
3288                "schema_id",
3289                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3290            ),
3291            ("name", "The name of the function."),
3292            (
3293                "argument_type_ids",
3294                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3295            ),
3296            (
3297                "variadic_argument_type_id",
3298                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3299            ),
3300            (
3301                "return_type_id",
3302                "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`].",
3303            ),
3304            (
3305                "returns_set",
3306                "Whether the function returns a set, i.e. the function is a table function.",
3307            ),
3308            (
3309                "owner_id",
3310                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3311            ),
3312        ]),
3313        is_retained_metrics_object: false,
3314        access: vec![PUBLIC_SELECT],
3315    }
3316});
3317pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3318    name: "mz_operators",
3319    schema: MZ_CATALOG_SCHEMA,
3320    oid: oid::TABLE_MZ_OPERATORS_OID,
3321    desc: RelationDesc::builder()
3322        .with_column("oid", SqlScalarType::Oid.nullable(false))
3323        .with_column("name", SqlScalarType::String.nullable(false))
3324        .with_column(
3325            "argument_type_ids",
3326            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3327        )
3328        .with_column("return_type_id", SqlScalarType::String.nullable(true))
3329        .finish(),
3330    column_comments: BTreeMap::new(),
3331    is_retained_metrics_object: false,
3332    access: vec![PUBLIC_SELECT],
3333});
3334pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3335    name: "mz_aggregates",
3336    schema: MZ_INTERNAL_SCHEMA,
3337    oid: oid::TABLE_MZ_AGGREGATES_OID,
3338    desc: RelationDesc::builder()
3339        .with_column("oid", SqlScalarType::Oid.nullable(false))
3340        .with_column("agg_kind", SqlScalarType::String.nullable(false))
3341        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
3342        .finish(),
3343    column_comments: BTreeMap::new(),
3344    is_retained_metrics_object: false,
3345    access: vec![PUBLIC_SELECT],
3346});
3347
3348pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3349    name: "mz_clusters",
3350    schema: MZ_CATALOG_SCHEMA,
3351    oid: oid::TABLE_MZ_CLUSTERS_OID,
3352    desc: RelationDesc::builder()
3353        .with_column("id", SqlScalarType::String.nullable(false))
3354        .with_column("name", SqlScalarType::String.nullable(false))
3355        .with_column("owner_id", SqlScalarType::String.nullable(false))
3356        .with_column(
3357            "privileges",
3358            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3359        )
3360        .with_column("managed", SqlScalarType::Bool.nullable(false))
3361        .with_column("size", SqlScalarType::String.nullable(true))
3362        .with_column("replication_factor", SqlScalarType::UInt32.nullable(true))
3363        .with_column("disk", SqlScalarType::Bool.nullable(true))
3364        .with_column(
3365            "availability_zones",
3366            SqlScalarType::List {
3367                element_type: Box::new(SqlScalarType::String),
3368                custom_id: None,
3369            }
3370            .nullable(true),
3371        )
3372        .with_column(
3373            "introspection_debugging",
3374            SqlScalarType::Bool.nullable(true),
3375        )
3376        .with_column(
3377            "introspection_interval",
3378            SqlScalarType::Interval.nullable(true),
3379        )
3380        .with_key(vec![0])
3381        .finish(),
3382    column_comments: BTreeMap::from_iter([
3383        ("id", "Materialize's unique ID for the cluster."),
3384        ("name", "The name of the cluster."),
3385        (
3386            "owner_id",
3387            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3388        ),
3389        ("privileges", "The privileges belonging to the cluster."),
3390        (
3391            "managed",
3392            "Whether the cluster is a managed cluster with automatically managed replicas.",
3393        ),
3394        (
3395            "size",
3396            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3397        ),
3398        (
3399            "replication_factor",
3400            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3401        ),
3402        (
3403            "disk",
3404            "Unstable If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3405        ),
3406        (
3407            "availability_zones",
3408            "Unstable If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3409        ),
3410        (
3411            "introspection_debugging",
3412            "Whether introspection of the gathering of the introspection data is enabled.",
3413        ),
3414        (
3415            "introspection_interval",
3416            "The interval at which to collect introspection data.",
3417        ),
3418    ]),
3419    is_retained_metrics_object: false,
3420    access: vec![PUBLIC_SELECT],
3421});
3422
3423pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3424    name: "mz_cluster_workload_classes",
3425    schema: MZ_INTERNAL_SCHEMA,
3426    oid: oid::TABLE_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3427    desc: RelationDesc::builder()
3428        .with_column("id", SqlScalarType::String.nullable(false))
3429        .with_column("workload_class", SqlScalarType::String.nullable(true))
3430        .with_key(vec![0])
3431        .finish(),
3432    column_comments: BTreeMap::new(),
3433    is_retained_metrics_object: false,
3434    access: vec![PUBLIC_SELECT],
3435});
3436
3437pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3438    name: "mz_cluster_workload_classes_ind",
3439    schema: MZ_INTERNAL_SCHEMA,
3440    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3441    sql: "IN CLUSTER mz_catalog_server
3442ON mz_internal.mz_cluster_workload_classes (id)",
3443    is_retained_metrics_object: false,
3444};
3445
3446pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3447    name: "mz_cluster_schedules",
3448    schema: MZ_INTERNAL_SCHEMA,
3449    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3450    desc: RelationDesc::builder()
3451        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3452        .with_column("type", SqlScalarType::String.nullable(false))
3453        .with_column(
3454            "refresh_hydration_time_estimate",
3455            SqlScalarType::Interval.nullable(true),
3456        )
3457        .finish(),
3458    column_comments: BTreeMap::from_iter([
3459        (
3460            "cluster_id",
3461            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3462        ),
3463        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3464        (
3465            "refresh_hydration_time_estimate",
3466            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3467        ),
3468    ]),
3469    is_retained_metrics_object: false,
3470    access: vec![PUBLIC_SELECT],
3471});
3472
3473pub static MZ_SECRETS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3474    name: "mz_secrets",
3475    schema: MZ_CATALOG_SCHEMA,
3476    oid: oid::TABLE_MZ_SECRETS_OID,
3477    desc: RelationDesc::builder()
3478        .with_column("id", SqlScalarType::String.nullable(false))
3479        .with_column("oid", SqlScalarType::Oid.nullable(false))
3480        .with_column("schema_id", SqlScalarType::String.nullable(false))
3481        .with_column("name", SqlScalarType::String.nullable(false))
3482        .with_column("owner_id", SqlScalarType::String.nullable(false))
3483        .with_column(
3484            "privileges",
3485            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3486        )
3487        .finish(),
3488    column_comments: BTreeMap::from_iter([
3489        ("id", "The unique ID of the secret."),
3490        (
3491            "oid",
3492            "A [PostgreSQL-compatible oid][`oid`] for the secret.",
3493        ),
3494        (
3495            "schema_id",
3496            "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3497        ),
3498        ("name", "The name of the secret."),
3499        (
3500            "owner_id",
3501            "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3502        ),
3503        ("privileges", "The privileges belonging to the secret."),
3504    ]),
3505    is_retained_metrics_object: false,
3506    access: vec![PUBLIC_SELECT],
3507});
3508
3509pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3510    name: "mz_cluster_replicas",
3511    schema: MZ_CATALOG_SCHEMA,
3512    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3513    desc: RelationDesc::builder()
3514        .with_column("id", SqlScalarType::String.nullable(false))
3515        .with_column("name", SqlScalarType::String.nullable(false))
3516        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3517        .with_column("size", SqlScalarType::String.nullable(true))
3518        // `NULL` for un-orchestrated clusters and for replicas where the user
3519        // hasn't specified them.
3520        .with_column("availability_zone", SqlScalarType::String.nullable(true))
3521        .with_column("owner_id", SqlScalarType::String.nullable(false))
3522        .with_column("disk", SqlScalarType::Bool.nullable(true))
3523        .finish(),
3524    column_comments: BTreeMap::from_iter([
3525        ("id", "Materialize's unique ID for the cluster replica."),
3526        ("name", "The name of the cluster replica."),
3527        (
3528            "cluster_id",
3529            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3530        ),
3531        (
3532            "size",
3533            "The cluster replica's size, selected during creation.",
3534        ),
3535        (
3536            "availability_zone",
3537            "The availability zone in which the cluster is running.",
3538        ),
3539        (
3540            "owner_id",
3541            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3542        ),
3543        ("disk", "If the replica has a local disk."),
3544    ]),
3545    is_retained_metrics_object: true,
3546    access: vec![PUBLIC_SELECT],
3547});
3548
3549pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3550    name: "mz_internal_cluster_replicas",
3551    schema: MZ_INTERNAL_SCHEMA,
3552    oid: oid::TABLE_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3553    desc: RelationDesc::builder()
3554        .with_column("id", SqlScalarType::String.nullable(false))
3555        .finish(),
3556    column_comments: BTreeMap::from_iter([(
3557        "id",
3558        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3559    )]),
3560    is_retained_metrics_object: false,
3561    access: vec![PUBLIC_SELECT],
3562});
3563
3564pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3565    name: "mz_pending_cluster_replicas",
3566    schema: MZ_INTERNAL_SCHEMA,
3567    oid: oid::TABLE_MZ_PENDING_CLUSTER_REPLICAS_OID,
3568    desc: RelationDesc::builder()
3569        .with_column("id", SqlScalarType::String.nullable(false))
3570        .finish(),
3571    column_comments: BTreeMap::from_iter([(
3572        "id",
3573        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3574    )]),
3575    is_retained_metrics_object: false,
3576    access: vec![PUBLIC_SELECT],
3577});
3578
3579pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3580    BuiltinSource {
3581        name: "mz_cluster_replica_status_history",
3582        schema: MZ_INTERNAL_SCHEMA,
3583        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3584        data_source: IntrospectionType::ReplicaStatusHistory,
3585        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3586        column_comments: BTreeMap::from_iter([
3587            ("replica_id", "The ID of a cluster replica."),
3588            ("process_id", "The ID of a process within the replica."),
3589            (
3590                "status",
3591                "The status of the cluster replica: `online` or `offline`.",
3592            ),
3593            (
3594                "reason",
3595                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3596            ),
3597            (
3598                "occurred_at",
3599                "Wall-clock timestamp at which the event occurred.",
3600            ),
3601        ]),
3602        is_retained_metrics_object: false,
3603        access: vec![PUBLIC_SELECT],
3604    }
3605});
3606
3607pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
3608    || {
3609        BuiltinContinualTask {
3610            name: "mz_cluster_replica_status_history_ct",
3611            schema: MZ_INTERNAL_SCHEMA,
3612            oid: oid::CT_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3613            desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3614            sql: "
3615IN CLUSTER mz_catalog_server
3616ON INPUT mz_internal.mz_cluster_replica_status_history AS (
3617    DELETE FROM mz_internal.mz_cluster_replica_status_history_ct WHERE occurred_at + '30d' < mz_now();
3618    INSERT INTO mz_internal.mz_cluster_replica_status_history_ct SELECT * FROM mz_internal.mz_cluster_replica_status_history;
3619)",
3620            access: vec![PUBLIC_SELECT],
3621        }
3622    },
3623);
3624
3625pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3626    name: "mz_cluster_replica_statuses",
3627    schema: MZ_INTERNAL_SCHEMA,
3628    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
3629    desc: RelationDesc::builder()
3630        .with_column("replica_id", SqlScalarType::String.nullable(false))
3631        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3632        .with_column("status", SqlScalarType::String.nullable(false))
3633        .with_column("reason", SqlScalarType::String.nullable(true))
3634        .with_column(
3635            "updated_at",
3636            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3637        )
3638        .with_key(vec![0, 1])
3639        .finish(),
3640    column_comments: BTreeMap::from_iter([
3641        (
3642            "replica_id",
3643            "Materialize's unique ID for the cluster replica.",
3644        ),
3645        (
3646            "process_id",
3647            "The ID of the process within the cluster replica.",
3648        ),
3649        (
3650            "status",
3651            "The status of the cluster replica: `online` or `offline`.",
3652        ),
3653        (
3654            "reason",
3655            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3656        ),
3657        (
3658            "updated_at",
3659            "The time at which the status was last updated.",
3660        ),
3661    ]),
3662    sql: "
3663SELECT
3664    DISTINCT ON (replica_id, process_id)
3665    replica_id,
3666    process_id,
3667    status,
3668    reason,
3669    occurred_at as updated_at
3670FROM mz_internal.mz_cluster_replica_status_history
3671JOIN mz_cluster_replicas r ON r.id = replica_id
3672ORDER BY replica_id, process_id, occurred_at DESC",
3673    access: vec![PUBLIC_SELECT],
3674});
3675
3676pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3677    name: "mz_cluster_replica_sizes",
3678    schema: MZ_CATALOG_SCHEMA,
3679    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3680    desc: RelationDesc::builder()
3681        .with_column("size", SqlScalarType::String.nullable(false))
3682        .with_column("processes", SqlScalarType::UInt64.nullable(false))
3683        .with_column("workers", SqlScalarType::UInt64.nullable(false))
3684        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(false))
3685        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(false))
3686        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3687        .with_column(
3688            "credits_per_hour",
3689            SqlScalarType::Numeric { max_scale: None }.nullable(false),
3690        )
3691        .finish(),
3692    column_comments: BTreeMap::from_iter([
3693        ("size", "The human-readable replica size."),
3694        ("processes", "The number of processes in the replica."),
3695        (
3696            "workers",
3697            "The number of Timely Dataflow workers per process.",
3698        ),
3699        (
3700            "cpu_nano_cores",
3701            "The CPU allocation per process, in billionths of a vCPU core.",
3702        ),
3703        (
3704            "memory_bytes",
3705            "The RAM allocation per process, in billionths of a vCPU core.",
3706        ),
3707        ("disk_bytes", "The disk allocation per process."),
3708        (
3709            "credits_per_hour",
3710            "The number of compute credits consumed per hour.",
3711        ),
3712    ]),
3713    is_retained_metrics_object: true,
3714    access: vec![PUBLIC_SELECT],
3715});
3716
3717pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3718    name: "mz_audit_events",
3719    schema: MZ_CATALOG_SCHEMA,
3720    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
3721    desc: RelationDesc::builder()
3722        .with_column("id", SqlScalarType::UInt64.nullable(false))
3723        .with_column("event_type", SqlScalarType::String.nullable(false))
3724        .with_column("object_type", SqlScalarType::String.nullable(false))
3725        .with_column("details", SqlScalarType::Jsonb.nullable(false))
3726        .with_column("user", SqlScalarType::String.nullable(true))
3727        .with_column(
3728            "occurred_at",
3729            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3730        )
3731        .with_key(vec![0])
3732        .finish(),
3733    column_comments: BTreeMap::from_iter([
3734        (
3735            "id",
3736            "Materialize's unique, monotonically increasing ID for the event.",
3737        ),
3738        (
3739            "event_type",
3740            "The type of the event: `create`, `drop`, or `alter`.",
3741        ),
3742        (
3743            "object_type",
3744            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
3745        ),
3746        (
3747            "details",
3748            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
3749        ),
3750        (
3751            "user",
3752            "The user who triggered the event, or `NULL` if triggered by the system.",
3753        ),
3754        (
3755            "occurred_at",
3756            "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.",
3757        ),
3758    ]),
3759    is_retained_metrics_object: false,
3760    access: vec![PUBLIC_SELECT],
3761});
3762
3763pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3764    name: "mz_source_status_history",
3765    schema: MZ_INTERNAL_SCHEMA,
3766    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
3767    data_source: IntrospectionType::SourceStatusHistory,
3768    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
3769    column_comments: BTreeMap::from_iter([
3770        (
3771            "occurred_at",
3772            "Wall-clock timestamp of the source status change.",
3773        ),
3774        (
3775            "source_id",
3776            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
3777        ),
3778        (
3779            "status",
3780            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
3781        ),
3782        (
3783            "error",
3784            "If the source is in an error state, the error message.",
3785        ),
3786        (
3787            "details",
3788            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
3789        ),
3790        (
3791            "replica_id",
3792            "The ID of the replica that an instance of a source is running on.",
3793        ),
3794    ]),
3795    is_retained_metrics_object: false,
3796    access: vec![PUBLIC_SELECT],
3797});
3798
3799pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
3800    || BuiltinSource {
3801        name: "mz_aws_privatelink_connection_status_history",
3802        schema: MZ_INTERNAL_SCHEMA,
3803        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
3804        data_source: IntrospectionType::PrivatelinkConnectionStatusHistory,
3805        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
3806        column_comments: BTreeMap::from_iter([
3807            ("occurred_at", "Wall-clock timestamp of the status change."),
3808            (
3809                "connection_id",
3810                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
3811            ),
3812            (
3813                "status",
3814                "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`.",
3815            ),
3816        ]),
3817        is_retained_metrics_object: false,
3818        access: vec![PUBLIC_SELECT],
3819    },
3820);
3821
3822pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> =
3823    LazyLock::new(|| BuiltinView {
3824        name: "mz_aws_privatelink_connection_statuses",
3825        schema: MZ_INTERNAL_SCHEMA,
3826        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
3827        desc: RelationDesc::builder()
3828            .with_column("id", SqlScalarType::String.nullable(false))
3829            .with_column("name", SqlScalarType::String.nullable(false))
3830            .with_column(
3831                "last_status_change_at",
3832                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3833            )
3834            .with_column("status", SqlScalarType::String.nullable(true))
3835            .with_key(vec![0])
3836            .finish(),
3837        column_comments: BTreeMap::from_iter([
3838            (
3839                "id",
3840                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
3841            ),
3842            ("name", "The name of the connection."),
3843            (
3844                "last_status_change_at",
3845                "Wall-clock timestamp of the connection status change.",
3846            ),
3847            ("status", ""),
3848        ]),
3849        sql: "
3850    WITH statuses_w_last_status AS (
3851        SELECT
3852            connection_id,
3853            occurred_at,
3854            status,
3855            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
3856        FROM mz_internal.mz_aws_privatelink_connection_status_history
3857    ),
3858    latest_events AS (
3859        -- Only take the most recent transition for each ID
3860        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
3861        FROM statuses_w_last_status
3862        -- Only keep first status transitions
3863        WHERE status <> last_status OR last_status IS NULL
3864        ORDER BY connection_id, occurred_at DESC
3865    )
3866    SELECT
3867        conns.id,
3868        name,
3869        occurred_at as last_status_change_at,
3870        status
3871    FROM latest_events
3872    JOIN mz_catalog.mz_connections AS conns
3873    ON conns.id = latest_events.connection_id",
3874        access: vec![PUBLIC_SELECT],
3875    });
3876
3877pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
3878    LazyLock::new(|| BuiltinSource {
3879        name: "mz_statement_execution_history",
3880        schema: MZ_INTERNAL_SCHEMA,
3881        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
3882        data_source: IntrospectionType::StatementExecutionHistory,
3883        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
3884        column_comments: BTreeMap::new(),
3885        is_retained_metrics_object: false,
3886        access: vec![MONITOR_SELECT],
3887    });
3888
3889pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
3890    BuiltinView {
3891    name: "mz_statement_execution_history_redacted",
3892    schema: MZ_INTERNAL_SCHEMA,
3893    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
3894    // everything but `params` and `error_message`
3895    desc: RelationDesc::builder()
3896        .with_column("id", SqlScalarType::Uuid.nullable(false))
3897        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
3898        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
3899        .with_column("cluster_id", SqlScalarType::String.nullable(true))
3900        .with_column("application_name", SqlScalarType::String.nullable(false))
3901        .with_column("cluster_name", SqlScalarType::String.nullable(true))
3902        .with_column("database_name", SqlScalarType::String.nullable(false))
3903        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
3904        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
3905        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
3906        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
3907        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
3908        .with_column("mz_version", SqlScalarType::String.nullable(false))
3909        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
3910        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
3911        .with_column("finished_status", SqlScalarType::String.nullable(true))
3912        .with_column("result_size", SqlScalarType::Int64.nullable(true))
3913        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
3914        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
3915        .finish(),
3916    column_comments: BTreeMap::new(),
3917    sql: "
3918SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
3919cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
3920transient_index_id, mz_version, began_at, finished_at, finished_status,
3921result_size, rows_returned, execution_strategy
3922FROM mz_internal.mz_statement_execution_history",
3923    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
3924}
3925});
3926
3927pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
3928    LazyLock::new(|| BuiltinSource {
3929        name: "mz_prepared_statement_history",
3930        schema: MZ_INTERNAL_SCHEMA,
3931        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
3932        data_source: IntrospectionType::PreparedStatementHistory,
3933        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
3934        column_comments: BTreeMap::new(),
3935        is_retained_metrics_object: false,
3936        access: vec![
3937            SUPPORT_SELECT,
3938            ANALYTICS_SELECT,
3939            MONITOR_REDACTED_SELECT,
3940            MONITOR_SELECT,
3941        ],
3942    });
3943
3944pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3945    name: "mz_sql_text",
3946    schema: MZ_INTERNAL_SCHEMA,
3947    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
3948    desc: MZ_SQL_TEXT_DESC.clone(),
3949    data_source: IntrospectionType::SqlText,
3950    column_comments: BTreeMap::new(),
3951    is_retained_metrics_object: false,
3952    access: vec![MONITOR_SELECT],
3953});
3954
3955pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3956    name: "mz_sql_text_redacted",
3957    schema: MZ_INTERNAL_SCHEMA,
3958    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
3959    desc: RelationDesc::builder()
3960        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3961        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3962        .finish(),
3963    column_comments: BTreeMap::new(),
3964    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
3965    access: vec![
3966        MONITOR_SELECT,
3967        MONITOR_REDACTED_SELECT,
3968        SUPPORT_SELECT,
3969        ANALYTICS_SELECT,
3970    ],
3971});
3972
3973pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
3974    BuiltinView {
3975        name: "mz_recent_sql_text",
3976        schema: MZ_INTERNAL_SCHEMA,
3977        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
3978        // This should always be 1 day more than the interval in
3979        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
3980        // is rounded down to the nearest day.  Thus something that actually happened three days ago
3981        // could have a `prepared day` anywhere from 3 to 4 days back.
3982        desc: RelationDesc::builder()
3983            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3984            .with_column("sql", SqlScalarType::String.nullable(false))
3985            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3986            .with_key(vec![0, 1, 2])
3987            .finish(),
3988        column_comments: BTreeMap::new(),
3989        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
3990        access: vec![MONITOR_SELECT],
3991    }
3992});
3993
3994pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3995    name: "mz_recent_sql_text_redacted",
3996    schema: MZ_INTERNAL_SCHEMA,
3997    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
3998    desc: RelationDesc::builder()
3999        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4000        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4001        .finish(),
4002    column_comments: BTreeMap::new(),
4003    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
4004    access: vec![
4005        MONITOR_SELECT,
4006        MONITOR_REDACTED_SELECT,
4007        SUPPORT_SELECT,
4008        ANALYTICS_SELECT,
4009    ],
4010});
4011
4012pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
4013    name: "mz_recent_sql_text_ind",
4014    schema: MZ_INTERNAL_SCHEMA,
4015    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
4016    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4017    is_retained_metrics_object: false,
4018});
4019
4020pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4021    name: "mz_session_history",
4022    schema: MZ_INTERNAL_SCHEMA,
4023    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4024    data_source: IntrospectionType::SessionHistory,
4025    desc: MZ_SESSION_HISTORY_DESC.clone(),
4026    column_comments: BTreeMap::new(),
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 statements that were dropped due to throttling before the current one was seen. If you have a very high volume of queries and need to log them without throttling, contact our team.",
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("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4348        .with_column("mz_version", SqlScalarType::String.nullable(false))
4349        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4350        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4351        .with_column("finished_status", SqlScalarType::String.nullable(true))
4352        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4353        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4354        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4355        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4356        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4357        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4358        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4359        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4360        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4361        .with_column("statement_type", SqlScalarType::String.nullable(true))
4362        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4363        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4364        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4365        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4366        .finish(),
4367    column_comments: BTreeMap::new(),
4368    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4369    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4370    mralt.transient_index_id, mralt.params, mralt.mz_version, mralt.began_at, mralt.finished_at,
4371    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4372    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4373    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4374    mralt.initial_application_name, mralt.authenticated_user,
4375    mrst.redacted_sql
4376FROM mz_internal.mz_recent_activity_log_thinned mralt,
4377     mz_internal.mz_recent_sql_text mrst
4378WHERE mralt.sql_hash = mrst.sql_hash",
4379    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4380}
4381});
4382
4383pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4384    BuiltinSource {
4385        name: "mz_statement_lifecycle_history",
4386        schema: MZ_INTERNAL_SCHEMA,
4387        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4388        desc: RelationDesc::builder()
4389            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
4390            .with_column("event_type", SqlScalarType::String.nullable(false))
4391            .with_column(
4392                "occurred_at",
4393                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4394            )
4395            .finish(),
4396        data_source: IntrospectionType::StatementLifecycleHistory,
4397        column_comments: BTreeMap::from_iter([
4398            (
4399                "statement_id",
4400                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4401            ),
4402            (
4403                "event_type",
4404                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4405            ),
4406            ("occurred_at", "The time at which the event took place."),
4407        ]),
4408        is_retained_metrics_object: false,
4409        // TODO[btv]: Maybe this should be public instead of
4410        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4411        // change, we probably don't need to worry about it now.
4412        access: vec![
4413            SUPPORT_SELECT,
4414            ANALYTICS_SELECT,
4415            MONITOR_REDACTED_SELECT,
4416            MONITOR_SELECT,
4417        ],
4418    }
4419});
4420
4421pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4422    name: "mz_source_statuses",
4423    schema: MZ_INTERNAL_SCHEMA,
4424    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4425    desc: RelationDesc::builder()
4426        .with_column("id", SqlScalarType::String.nullable(false))
4427        .with_column("name", SqlScalarType::String.nullable(false))
4428        .with_column("type", SqlScalarType::String.nullable(false))
4429        .with_column(
4430            "last_status_change_at",
4431            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4432        )
4433        .with_column("status", SqlScalarType::String.nullable(false))
4434        .with_column("error", SqlScalarType::String.nullable(true))
4435        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4436        .finish(),
4437    column_comments: BTreeMap::from_iter([
4438        (
4439            "id",
4440            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4441        ),
4442        ("name", "The name of the source."),
4443        ("type", "The type of the source."),
4444        (
4445            "last_status_change_at",
4446            "Wall-clock timestamp of the source status change.",
4447        ),
4448        (
4449            "status",
4450            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4451        ),
4452        (
4453            "error",
4454            "If the source is in an error state, the error message.",
4455        ),
4456        (
4457            "details",
4458            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4459        ),
4460    ]),
4461    sql: "
4462    WITH
4463    -- The status history contains per-replica events and source-global events.
4464    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4465    -- we can treat them uniformly below.
4466    uniform_status_history AS
4467    (
4468        SELECT
4469            s.source_id,
4470            COALESCE(s.replica_id, '<source>') as replica_id,
4471            s.occurred_at,
4472            s.status,
4473            s.error,
4474            s.details
4475        FROM mz_internal.mz_source_status_history s
4476    ),
4477    -- For getting the latest events, we first determine the latest per-replica
4478    -- events here and then apply precedence rules below.
4479    latest_per_replica_events AS
4480    (
4481        SELECT DISTINCT ON (source_id, replica_id)
4482            occurred_at, source_id, replica_id, status, error, details
4483        FROM uniform_status_history
4484        ORDER BY source_id, replica_id, occurred_at DESC
4485    ),
4486    -- We have a precedence list that determines the overall status in case
4487    -- there is differing per-replica (including source-global) statuses. If
4488    -- there is no 'dropped' status, and any replica reports 'running', the
4489    -- overall status is 'running' even if there might be some replica that has
4490    -- errors or is paused.
4491    latest_events AS
4492    (
4493       SELECT DISTINCT ON (source_id)
4494            source_id,
4495            occurred_at,
4496            status,
4497            error,
4498            details
4499        FROM latest_per_replica_events
4500        ORDER BY source_id, CASE status
4501                    WHEN 'dropped' THEN 1
4502                    WHEN 'running' THEN 2
4503                    WHEN 'stalled' THEN 3
4504                    WHEN 'starting' THEN 4
4505                    WHEN 'paused' THEN 5
4506                    WHEN 'ceased' THEN 6
4507                    ELSE 7  -- For any other status values
4508                END
4509    ),
4510    -- Determine which sources are subsources and which are parent sources
4511    subsources AS
4512    (
4513        SELECT subsources.id AS self, sources.id AS parent
4514        FROM
4515            mz_catalog.mz_sources AS subsources
4516                JOIN
4517                    mz_internal.mz_object_dependencies AS deps
4518                    ON subsources.id = deps.object_id
4519                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4520    ),
4521    -- Determine which sources are source tables
4522    tables AS
4523    (
4524        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4525        FROM mz_catalog.mz_tables AS tables
4526        WHERE tables.source_id IS NOT NULL
4527    ),
4528    -- Determine which collection's ID to use for the status
4529    id_of_status_to_use AS
4530    (
4531        SELECT
4532            self_events.source_id,
4533            -- If self not errored, but parent is, use parent; else self
4534            CASE
4535                WHEN
4536                    self_events.status <> 'ceased' AND
4537                    parent_events.status = 'stalled'
4538                THEN parent_events.source_id
4539                ELSE self_events.source_id
4540            END AS id_to_use
4541        FROM
4542            latest_events AS self_events
4543                LEFT JOIN subsources ON self_events.source_id = subsources.self
4544                LEFT JOIN tables ON self_events.source_id = tables.self
4545                LEFT JOIN
4546                    latest_events AS parent_events
4547                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4548    ),
4549    -- Swap out events for the ID of the event we plan to use instead
4550    latest_events_to_use AS
4551    (
4552        SELECT occurred_at, s.source_id, status, error, details
4553        FROM
4554            id_of_status_to_use AS s
4555                JOIN latest_events AS e ON e.source_id = s.id_to_use
4556    ),
4557    combined AS (
4558        SELECT
4559            mz_sources.id,
4560            mz_sources.name,
4561            mz_sources.type,
4562            occurred_at,
4563            status,
4564            error,
4565            details
4566        FROM
4567            mz_catalog.mz_sources
4568            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4569        UNION ALL
4570        SELECT
4571            tables.self AS id,
4572            tables.name,
4573            'table' AS type,
4574            occurred_at,
4575            status,
4576            error,
4577            details
4578        FROM
4579            tables
4580            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4581    )
4582SELECT
4583    id,
4584    name,
4585    type,
4586    occurred_at AS last_status_change_at,
4587    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4588    CASE
4589        WHEN
4590            type = 'webhook' OR
4591            type = 'progress'
4592        THEN 'running'
4593        ELSE COALESCE(status, 'created')
4594    END AS status,
4595    error,
4596    details
4597FROM combined
4598WHERE id NOT LIKE 's%';",
4599    access: vec![PUBLIC_SELECT],
4600});
4601
4602pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4603    name: "mz_sink_status_history",
4604    schema: MZ_INTERNAL_SCHEMA,
4605    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4606    data_source: IntrospectionType::SinkStatusHistory,
4607    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4608    column_comments: BTreeMap::from_iter([
4609        (
4610            "occurred_at",
4611            "Wall-clock timestamp of the sink status change.",
4612        ),
4613        (
4614            "sink_id",
4615            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4616        ),
4617        (
4618            "status",
4619            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4620        ),
4621        (
4622            "error",
4623            "If the sink is in an error state, the error message.",
4624        ),
4625        (
4626            "details",
4627            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4628        ),
4629        (
4630            "replica_id",
4631            "The ID of the replica that an instance of a sink is running on.",
4632        ),
4633    ]),
4634    is_retained_metrics_object: false,
4635    access: vec![PUBLIC_SELECT],
4636});
4637
4638pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4639    name: "mz_sink_statuses",
4640    schema: MZ_INTERNAL_SCHEMA,
4641    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4642    desc: RelationDesc::builder()
4643        .with_column("id", SqlScalarType::String.nullable(false))
4644        .with_column("name", SqlScalarType::String.nullable(false))
4645        .with_column("type", SqlScalarType::String.nullable(false))
4646        .with_column(
4647            "last_status_change_at",
4648            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4649        )
4650        .with_column("status", SqlScalarType::String.nullable(false))
4651        .with_column("error", SqlScalarType::String.nullable(true))
4652        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4653        .finish(),
4654    column_comments: BTreeMap::from_iter([
4655        (
4656            "id",
4657            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4658        ),
4659        ("name", "The name of the sink."),
4660        ("type", "The type of the sink."),
4661        (
4662            "last_status_change_at",
4663            "Wall-clock timestamp of the sink status change.",
4664        ),
4665        (
4666            "status",
4667            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4668        ),
4669        (
4670            "error",
4671            "If the sink is in an error state, the error message.",
4672        ),
4673        (
4674            "details",
4675            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4676        ),
4677    ]),
4678    sql: "
4679WITH
4680-- The status history contains per-replica events and sink-global events.
4681-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
4682-- we can treat them uniformly below.
4683uniform_status_history AS
4684(
4685    SELECT
4686        s.sink_id,
4687        COALESCE(s.replica_id, '<sink>') as replica_id,
4688        s.occurred_at,
4689        s.status,
4690        s.error,
4691        s.details
4692    FROM mz_internal.mz_sink_status_history s
4693),
4694-- For getting the latest events, we first determine the latest per-replica
4695-- events here and then apply precedence rules below.
4696latest_per_replica_events AS
4697(
4698    SELECT DISTINCT ON (sink_id, replica_id)
4699        occurred_at, sink_id, replica_id, status, error, details
4700    FROM uniform_status_history
4701    ORDER BY sink_id, replica_id, occurred_at DESC
4702),
4703-- We have a precedence list that determines the overall status in case
4704-- there is differing per-replica (including sink-global) statuses. If
4705-- there is no 'dropped' status, and any replica reports 'running', the
4706-- overall status is 'running' even if there might be some replica that has
4707-- errors or is paused.
4708latest_events AS
4709(
4710    SELECT DISTINCT ON (sink_id)
4711        sink_id,
4712        occurred_at,
4713        status,
4714        error,
4715        details
4716    FROM latest_per_replica_events
4717    ORDER BY sink_id, CASE status
4718                WHEN 'dropped' THEN 1
4719                WHEN 'running' THEN 2
4720                WHEN 'stalled' THEN 3
4721                WHEN 'starting' THEN 4
4722                WHEN 'paused' THEN 5
4723                WHEN 'ceased' THEN 6
4724                ELSE 7  -- For any other status values
4725            END
4726)
4727SELECT
4728    mz_sinks.id,
4729    name,
4730    mz_sinks.type,
4731    occurred_at as last_status_change_at,
4732    coalesce(status, 'created') as status,
4733    error,
4734    details
4735FROM mz_catalog.mz_sinks
4736LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
4737WHERE
4738    -- This is a convenient way to filter out system sinks, like the status_history table itself.
4739    mz_sinks.id NOT LIKE 's%'",
4740    access: vec![PUBLIC_SELECT],
4741});
4742
4743pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
4744    LazyLock::new(|| SystemObjectDescription {
4745        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
4746        object_type: CatalogItemType::Table,
4747        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
4748    });
4749
4750pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4751    name: "mz_storage_usage_by_shard",
4752    schema: MZ_INTERNAL_SCHEMA,
4753    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
4754    desc: RelationDesc::builder()
4755        .with_column("id", SqlScalarType::UInt64.nullable(false))
4756        .with_column("shard_id", SqlScalarType::String.nullable(true))
4757        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
4758        .with_column(
4759            "collection_timestamp",
4760            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4761        )
4762        .finish(),
4763    column_comments: BTreeMap::new(),
4764    is_retained_metrics_object: false,
4765    access: vec![PUBLIC_SELECT],
4766});
4767
4768pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4769    name: "mz_egress_ips",
4770    schema: MZ_CATALOG_SCHEMA,
4771    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
4772    desc: RelationDesc::builder()
4773        .with_column("egress_ip", SqlScalarType::String.nullable(false))
4774        .with_column("prefix_length", SqlScalarType::Int32.nullable(false))
4775        .with_column("cidr", SqlScalarType::String.nullable(false))
4776        .finish(),
4777    column_comments: BTreeMap::from_iter([
4778        ("egress_ip", "The start of the range of IP addresses."),
4779        (
4780            "prefix_length",
4781            "The number of leading bits in the CIDR netmask.",
4782        ),
4783        ("cidr", "The CIDR representation."),
4784    ]),
4785    is_retained_metrics_object: false,
4786    access: vec![PUBLIC_SELECT],
4787});
4788
4789pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
4790    LazyLock::new(|| BuiltinTable {
4791        name: "mz_aws_privatelink_connections",
4792        schema: MZ_CATALOG_SCHEMA,
4793        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
4794        desc: RelationDesc::builder()
4795            .with_column("id", SqlScalarType::String.nullable(false))
4796            .with_column("principal", SqlScalarType::String.nullable(false))
4797            .finish(),
4798        column_comments: BTreeMap::from_iter([
4799            ("id", "The ID of the connection."),
4800            (
4801                "principal",
4802                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
4803            ),
4804        ]),
4805        is_retained_metrics_object: false,
4806        access: vec![PUBLIC_SELECT],
4807    });
4808
4809pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4810    name: "mz_aws_connections",
4811    schema: MZ_INTERNAL_SCHEMA,
4812    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
4813    desc: RelationDesc::builder()
4814        .with_column("id", SqlScalarType::String.nullable(false))
4815        .with_column("endpoint", SqlScalarType::String.nullable(true))
4816        .with_column("region", SqlScalarType::String.nullable(true))
4817        .with_column("access_key_id", SqlScalarType::String.nullable(true))
4818        .with_column(
4819            "access_key_id_secret_id",
4820            SqlScalarType::String.nullable(true),
4821        )
4822        .with_column(
4823            "secret_access_key_secret_id",
4824            SqlScalarType::String.nullable(true),
4825        )
4826        .with_column("session_token", SqlScalarType::String.nullable(true))
4827        .with_column(
4828            "session_token_secret_id",
4829            SqlScalarType::String.nullable(true),
4830        )
4831        .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
4832        .with_column(
4833            "assume_role_session_name",
4834            SqlScalarType::String.nullable(true),
4835        )
4836        .with_column("principal", SqlScalarType::String.nullable(true))
4837        .with_column("external_id", SqlScalarType::String.nullable(true))
4838        .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
4839        .finish(),
4840    column_comments: BTreeMap::from_iter([
4841        ("id", "The ID of the connection."),
4842        ("endpoint", "The value of the `ENDPOINT` option, if set."),
4843        ("region", "The value of the `REGION` option, if set."),
4844        (
4845            "access_key_id",
4846            "The value of the `ACCESS KEY ID` option, if provided in line.",
4847        ),
4848        (
4849            "access_key_id_secret_id",
4850            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
4851        ),
4852        (
4853            "secret_access_key_secret_id",
4854            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
4855        ),
4856        (
4857            "session_token",
4858            "The value of the `SESSION TOKEN` option, if provided in line.",
4859        ),
4860        (
4861            "session_token_secret_id",
4862            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
4863        ),
4864        (
4865            "assume_role_arn",
4866            "The value of the `ASSUME ROLE ARN` option, if set.",
4867        ),
4868        (
4869            "assume_role_session_name",
4870            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
4871        ),
4872        (
4873            "principal",
4874            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4875        ),
4876        (
4877            "external_id",
4878            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4879        ),
4880        (
4881            "example_trust_policy",
4882            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
4883        ),
4884    ]),
4885    is_retained_metrics_object: false,
4886    access: vec![PUBLIC_SELECT],
4887});
4888
4889pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
4890    LazyLock::new(|| BuiltinSource {
4891        name: "mz_cluster_replica_metrics_history",
4892        schema: MZ_INTERNAL_SCHEMA,
4893        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4894        data_source: IntrospectionType::ReplicaMetricsHistory,
4895        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4896        column_comments: BTreeMap::from_iter([
4897            ("replica_id", "The ID of a cluster replica."),
4898            ("process_id", "The ID of a process within the replica."),
4899            (
4900                "cpu_nano_cores",
4901                "Approximate CPU usage, in billionths of a vCPU core.",
4902            ),
4903            ("memory_bytes", "Approximate memory usage, in bytes."),
4904            ("disk_bytes", "Approximate disk usage, in bytes."),
4905            (
4906                "occurred_at",
4907                "Wall-clock timestamp at which the event occurred.",
4908            ),
4909            (
4910                "heap_bytes",
4911                "Approximate heap (RAM + swap) usage, in bytes.",
4912            ),
4913            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
4914        ]),
4915        is_retained_metrics_object: false,
4916        access: vec![PUBLIC_SELECT],
4917    });
4918
4919pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
4920    || {
4921        BuiltinContinualTask {
4922            name: "mz_cluster_replica_metrics_history_ct",
4923            schema: MZ_INTERNAL_SCHEMA,
4924            oid: oid::CT_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4925            desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4926            sql: "
4927IN CLUSTER mz_catalog_server
4928ON INPUT mz_internal.mz_cluster_replica_metrics_history AS (
4929    DELETE FROM mz_internal.mz_cluster_replica_metrics_history_ct WHERE occurred_at + '30d' < mz_now();
4930    INSERT INTO mz_internal.mz_cluster_replica_metrics_history_ct SELECT * FROM mz_internal.mz_cluster_replica_metrics_history;
4931)",
4932            access: vec![PUBLIC_SELECT],
4933        }
4934    },
4935);
4936
4937pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4938    name: "mz_cluster_replica_metrics",
4939    schema: MZ_INTERNAL_SCHEMA,
4940    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
4941    desc: RelationDesc::builder()
4942        .with_column("replica_id", SqlScalarType::String.nullable(false))
4943        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
4944        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
4945        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
4946        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
4947        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
4948        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
4949        .with_key(vec![0, 1])
4950        .finish(),
4951    column_comments: BTreeMap::from_iter([
4952        ("replica_id", "The ID of a cluster replica."),
4953        ("process_id", "The ID of a process within the replica."),
4954        (
4955            "cpu_nano_cores",
4956            "Approximate CPU usage, in billionths of a vCPU core.",
4957        ),
4958        ("memory_bytes", "Approximate RAM usage, in bytes."),
4959        ("disk_bytes", "Approximate disk usage, in bytes."),
4960        (
4961            "heap_bytes",
4962            "Approximate heap (RAM + swap) usage, in bytes.",
4963        ),
4964        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
4965    ]),
4966    sql: "
4967SELECT
4968    DISTINCT ON (replica_id, process_id)
4969    replica_id,
4970    process_id,
4971    cpu_nano_cores,
4972    memory_bytes,
4973    disk_bytes,
4974    heap_bytes,
4975    heap_limit
4976FROM mz_internal.mz_cluster_replica_metrics_history
4977JOIN mz_cluster_replicas r ON r.id = replica_id
4978ORDER BY replica_id, process_id, occurred_at DESC",
4979    access: vec![PUBLIC_SELECT],
4980});
4981
4982pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
4983    LazyLock::new(|| BuiltinSource {
4984        name: "mz_cluster_replica_frontiers",
4985        schema: MZ_CATALOG_SCHEMA,
4986        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
4987        data_source: IntrospectionType::ReplicaFrontiers,
4988        desc: RelationDesc::builder()
4989            .with_column("object_id", SqlScalarType::String.nullable(false))
4990            .with_column("replica_id", SqlScalarType::String.nullable(false))
4991            .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
4992            .finish(),
4993        column_comments: BTreeMap::from_iter([
4994            (
4995                "object_id",
4996                "The ID of the source, sink, index, materialized view, or subscription.",
4997            ),
4998            ("replica_id", "The ID of a cluster replica."),
4999            (
5000                "write_frontier",
5001                "The next timestamp at which the output may change.",
5002            ),
5003        ]),
5004        is_retained_metrics_object: false,
5005        access: vec![PUBLIC_SELECT],
5006    });
5007
5008pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
5009    LazyLock::new(|| BuiltinIndex {
5010        name: "mz_cluster_replica_frontiers_ind",
5011        schema: MZ_CATALOG_SCHEMA,
5012        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
5013        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
5014        is_retained_metrics_object: false,
5015    });
5016
5017pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5018    name: "mz_frontiers",
5019    schema: MZ_INTERNAL_SCHEMA,
5020    oid: oid::SOURCE_MZ_FRONTIERS_OID,
5021    data_source: IntrospectionType::Frontiers,
5022    desc: RelationDesc::builder()
5023        .with_column("object_id", SqlScalarType::String.nullable(false))
5024        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
5025        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5026        .finish(),
5027    column_comments: BTreeMap::from_iter([
5028        (
5029            "object_id",
5030            "The ID of the source, sink, table, index, materialized view, or subscription.",
5031        ),
5032        (
5033            "read_frontier",
5034            "The earliest timestamp at which the output is still readable.",
5035        ),
5036        (
5037            "write_frontier",
5038            "The next timestamp at which the output may change.",
5039        ),
5040    ]),
5041    is_retained_metrics_object: false,
5042    access: vec![PUBLIC_SELECT],
5043});
5044
5045/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
5046pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5047    name: "mz_global_frontiers",
5048    schema: MZ_INTERNAL_SCHEMA,
5049    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5050    desc: RelationDesc::builder()
5051        .with_column("object_id", SqlScalarType::String.nullable(false))
5052        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
5053        .finish(),
5054    column_comments: BTreeMap::new(),
5055    sql: "
5056SELECT object_id, write_frontier AS time
5057FROM mz_internal.mz_frontiers
5058WHERE write_frontier IS NOT NULL",
5059    access: vec![PUBLIC_SELECT],
5060});
5061
5062pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5063    name: "mz_wallclock_lag_history",
5064    schema: MZ_INTERNAL_SCHEMA,
5065    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5066    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5067    data_source: IntrospectionType::WallclockLagHistory,
5068    column_comments: BTreeMap::from_iter([
5069        (
5070            "object_id",
5071            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5072        ),
5073        (
5074            "replica_id",
5075            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5076        ),
5077        (
5078            "lag",
5079            "The amount of time the object's write frontier lags behind wallclock time.",
5080        ),
5081        (
5082            "occurred_at",
5083            "Wall-clock timestamp at which the event occurred.",
5084        ),
5085    ]),
5086    is_retained_metrics_object: false,
5087    access: vec![PUBLIC_SELECT],
5088});
5089
5090pub static MZ_WALLCLOCK_LAG_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(|| {
5091    BuiltinContinualTask {
5092    name: "mz_wallclock_lag_history_ct",
5093    schema: MZ_INTERNAL_SCHEMA,
5094    oid: oid::CT_MZ_WALLCLOCK_LAG_HISTORY_OID,
5095    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5096    sql: "
5097IN CLUSTER mz_catalog_server
5098ON INPUT mz_internal.mz_wallclock_lag_history AS (
5099    DELETE FROM mz_internal.mz_wallclock_lag_history_ct WHERE occurred_at + '30d' < mz_now();
5100    INSERT INTO mz_internal.mz_wallclock_lag_history_ct SELECT * FROM mz_internal.mz_wallclock_lag_history;
5101)",
5102            access: vec![PUBLIC_SELECT],
5103        }
5104});
5105
5106pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5107    name: "mz_wallclock_global_lag_history",
5108    schema: MZ_INTERNAL_SCHEMA,
5109    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5110    desc: RelationDesc::builder()
5111        .with_column("object_id", SqlScalarType::String.nullable(false))
5112        .with_column("lag", SqlScalarType::Interval.nullable(true))
5113        .with_column(
5114            "occurred_at",
5115            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5116        )
5117        .with_key(vec![0, 2])
5118        .finish(),
5119    column_comments: BTreeMap::new(),
5120    sql: "
5121WITH times_binned AS (
5122    SELECT
5123        object_id,
5124        lag,
5125        date_trunc('minute', occurred_at) AS occurred_at
5126    FROM mz_internal.mz_wallclock_lag_history
5127)
5128SELECT
5129    object_id,
5130    min(lag) AS lag,
5131    occurred_at
5132FROM times_binned
5133GROUP BY object_id, occurred_at
5134OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5135    access: vec![PUBLIC_SELECT],
5136});
5137
5138pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> =
5139    LazyLock::new(|| BuiltinView {
5140        name: "mz_wallclock_global_lag_recent_history",
5141        schema: MZ_INTERNAL_SCHEMA,
5142        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5143        desc: RelationDesc::builder()
5144            .with_column("object_id", SqlScalarType::String.nullable(false))
5145            .with_column("lag", SqlScalarType::Interval.nullable(true))
5146            .with_column(
5147                "occurred_at",
5148                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5149            )
5150            .with_key(vec![0, 2])
5151            .finish(),
5152        column_comments: BTreeMap::new(),
5153        sql: "
5154SELECT object_id, lag, occurred_at
5155FROM mz_internal.mz_wallclock_global_lag_history
5156WHERE occurred_at + '1 day' > mz_now()",
5157        access: vec![PUBLIC_SELECT],
5158    });
5159
5160pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5161    name: "mz_wallclock_global_lag",
5162    schema: MZ_INTERNAL_SCHEMA,
5163    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5164    desc: RelationDesc::builder()
5165        .with_column("object_id", SqlScalarType::String.nullable(false))
5166        .with_column("lag", SqlScalarType::Interval.nullable(true))
5167        .with_key(vec![0])
5168        .finish(),
5169    column_comments: BTreeMap::from_iter([
5170        (
5171            "object_id",
5172            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5173        ),
5174        (
5175            "lag",
5176            "The amount of time the object's write frontier lags behind wallclock time.",
5177        ),
5178    ]),
5179    sql: "
5180SELECT DISTINCT ON (object_id) object_id, lag
5181FROM mz_internal.mz_wallclock_global_lag_recent_history
5182WHERE occurred_at + '5 minutes' > mz_now()
5183ORDER BY object_id, occurred_at DESC",
5184    access: vec![PUBLIC_SELECT],
5185});
5186
5187pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5188    LazyLock::new(|| BuiltinSource {
5189        name: "mz_wallclock_global_lag_histogram_raw",
5190        schema: MZ_INTERNAL_SCHEMA,
5191        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5192        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5193        column_comments: BTreeMap::new(),
5194        data_source: IntrospectionType::WallclockLagHistogram,
5195        is_retained_metrics_object: false,
5196        access: vec![PUBLIC_SELECT],
5197    });
5198
5199pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5200    LazyLock::new(|| BuiltinView {
5201        name: "mz_wallclock_global_lag_histogram",
5202        schema: MZ_INTERNAL_SCHEMA,
5203        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5204        desc: RelationDesc::builder()
5205            .with_column(
5206                "period_start",
5207                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5208            )
5209            .with_column(
5210                "period_end",
5211                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5212            )
5213            .with_column("object_id", SqlScalarType::String.nullable(false))
5214            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
5215            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
5216            .with_column("count", SqlScalarType::Int64.nullable(false))
5217            .with_key(vec![0, 1, 2, 3, 4])
5218            .finish(),
5219        column_comments: BTreeMap::new(),
5220        sql: "
5221SELECT *, count(*) AS count
5222FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5223GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5224        access: vec![PUBLIC_SELECT],
5225    });
5226
5227pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5228    BuiltinSource {
5229        name: "mz_materialized_view_refreshes",
5230        schema: MZ_INTERNAL_SCHEMA,
5231        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5232        data_source: IntrospectionType::ComputeMaterializedViewRefreshes,
5233        desc: RelationDesc::builder()
5234            .with_column(
5235                "materialized_view_id",
5236                SqlScalarType::String.nullable(false),
5237            )
5238            .with_column(
5239                "last_completed_refresh",
5240                SqlScalarType::MzTimestamp.nullable(true),
5241            )
5242            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
5243            .finish(),
5244        column_comments: BTreeMap::from_iter([
5245            (
5246                "materialized_view_id",
5247                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5248            ),
5249            (
5250                "last_completed_refresh",
5251                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5252            ),
5253            (
5254                "next_refresh",
5255                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5256            ),
5257        ]),
5258        is_retained_metrics_object: false,
5259        access: vec![PUBLIC_SELECT],
5260    }
5261});
5262
5263pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5264    name: "mz_subscriptions",
5265    schema: MZ_INTERNAL_SCHEMA,
5266    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5267    desc: RelationDesc::builder()
5268        .with_column("id", SqlScalarType::String.nullable(false))
5269        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
5270        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5271        .with_column(
5272            "created_at",
5273            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5274        )
5275        .with_column(
5276            "referenced_object_ids",
5277            SqlScalarType::List {
5278                element_type: Box::new(SqlScalarType::String),
5279                custom_id: None,
5280            }
5281            .nullable(false),
5282        )
5283        .finish(),
5284    column_comments: BTreeMap::from_iter([
5285        ("id", "The ID of the subscription."),
5286        (
5287            "session_id",
5288            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5289        ),
5290        (
5291            "cluster_id",
5292            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5293        ),
5294        (
5295            "created_at",
5296            "The time at which the subscription was created.",
5297        ),
5298        (
5299            "referenced_object_ids",
5300            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5301        ),
5302    ]),
5303    is_retained_metrics_object: false,
5304    access: vec![PUBLIC_SELECT],
5305});
5306
5307pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5308    name: "mz_sessions",
5309    schema: MZ_INTERNAL_SCHEMA,
5310    oid: oid::TABLE_MZ_SESSIONS_OID,
5311    desc: RelationDesc::builder()
5312        .with_column("id", SqlScalarType::Uuid.nullable(false))
5313        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
5314        .with_column("role_id", SqlScalarType::String.nullable(false))
5315        .with_column("client_ip", SqlScalarType::String.nullable(true))
5316        .with_column(
5317            "connected_at",
5318            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5319        )
5320        .finish(),
5321    column_comments: BTreeMap::from_iter([
5322        ("id", "The globally unique ID of the session."),
5323        (
5324            "connection_id",
5325            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5326        ),
5327        (
5328            "role_id",
5329            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5330        ),
5331        (
5332            "client_ip",
5333            "The IP address of the client that initiated the session.",
5334        ),
5335        (
5336            "connected_at",
5337            "The time at which the session connected to the system.",
5338        ),
5339    ]),
5340    is_retained_metrics_object: false,
5341    access: vec![PUBLIC_SELECT],
5342});
5343
5344pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5345    name: "mz_default_privileges",
5346    schema: MZ_CATALOG_SCHEMA,
5347    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5348    desc: RelationDesc::builder()
5349        .with_column("role_id", SqlScalarType::String.nullable(false))
5350        .with_column("database_id", SqlScalarType::String.nullable(true))
5351        .with_column("schema_id", SqlScalarType::String.nullable(true))
5352        .with_column("object_type", SqlScalarType::String.nullable(false))
5353        .with_column("grantee", SqlScalarType::String.nullable(false))
5354        .with_column("privileges", SqlScalarType::String.nullable(false))
5355        .finish(),
5356    column_comments: BTreeMap::from_iter([
5357        (
5358            "role_id",
5359            "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.",
5360        ),
5361        (
5362            "database_id",
5363            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5364        ),
5365        (
5366            "schema_id",
5367            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5368        ),
5369        (
5370            "object_type",
5371            "Privileges described in this row will be granted only on objects of type `object_type`.",
5372        ),
5373        (
5374            "grantee",
5375            "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.",
5376        ),
5377        ("privileges", "The set of privileges that will be granted."),
5378    ]),
5379    is_retained_metrics_object: false,
5380    access: vec![PUBLIC_SELECT],
5381});
5382
5383pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5384    name: "mz_system_privileges",
5385    schema: MZ_CATALOG_SCHEMA,
5386    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5387    desc: RelationDesc::builder()
5388        .with_column("privileges", SqlScalarType::MzAclItem.nullable(false))
5389        .finish(),
5390    column_comments: BTreeMap::from_iter([(
5391        "privileges",
5392        "The privileges belonging to the system.",
5393    )]),
5394    is_retained_metrics_object: false,
5395    access: vec![PUBLIC_SELECT],
5396});
5397
5398pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5399    name: "mz_comments",
5400    schema: MZ_INTERNAL_SCHEMA,
5401    oid: oid::TABLE_MZ_COMMENTS_OID,
5402    desc: RelationDesc::builder()
5403        .with_column("id", SqlScalarType::String.nullable(false))
5404        .with_column("object_type", SqlScalarType::String.nullable(false))
5405        .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
5406        .with_column("comment", SqlScalarType::String.nullable(false))
5407        .finish(),
5408    column_comments: BTreeMap::from_iter([
5409        (
5410            "id",
5411            "The ID of the object. Corresponds to `mz_objects.id`.",
5412        ),
5413        (
5414            "object_type",
5415            "The type of object the comment is associated with.",
5416        ),
5417        (
5418            "object_sub_id",
5419            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5420        ),
5421        ("comment", "The comment itself."),
5422    ]),
5423    is_retained_metrics_object: false,
5424    access: vec![PUBLIC_SELECT],
5425});
5426
5427pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5428    name: "mz_source_references",
5429    schema: MZ_INTERNAL_SCHEMA,
5430    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5431    desc: RelationDesc::builder()
5432        .with_column("source_id", SqlScalarType::String.nullable(false))
5433        .with_column("namespace", SqlScalarType::String.nullable(true))
5434        .with_column("name", SqlScalarType::String.nullable(false))
5435        .with_column(
5436            "updated_at",
5437            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5438        )
5439        .with_column(
5440            "columns",
5441            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5442        )
5443        .finish(),
5444    column_comments: BTreeMap::new(),
5445    is_retained_metrics_object: false,
5446    access: vec![PUBLIC_SELECT],
5447});
5448
5449pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5450    name: "mz_webhook_sources",
5451    schema: MZ_INTERNAL_SCHEMA,
5452    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5453    desc: RelationDesc::builder()
5454        .with_column("id", SqlScalarType::String.nullable(false))
5455        .with_column("name", SqlScalarType::String.nullable(false))
5456        .with_column("url", SqlScalarType::String.nullable(false))
5457        .finish(),
5458    column_comments: BTreeMap::from_iter([
5459        (
5460            "id",
5461            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5462        ),
5463        ("name", "The name of the webhook source."),
5464        (
5465            "url",
5466            "The URL which can be used to send events to the source.",
5467        ),
5468    ]),
5469    is_retained_metrics_object: false,
5470    access: vec![PUBLIC_SELECT],
5471});
5472
5473pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5474    BuiltinTable {
5475        name: "mz_history_retention_strategies",
5476        schema: MZ_INTERNAL_SCHEMA,
5477        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5478        desc: RelationDesc::builder()
5479            .with_column("id", SqlScalarType::String.nullable(false))
5480            .with_column("strategy", SqlScalarType::String.nullable(false))
5481            .with_column("value", SqlScalarType::Jsonb.nullable(false))
5482            .finish(),
5483        column_comments: BTreeMap::from_iter([
5484            ("id", "The ID of the object."),
5485            (
5486                "strategy",
5487                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5488            ),
5489            (
5490                "value",
5491                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5492            ),
5493        ]),
5494        is_retained_metrics_object: false,
5495        access: vec![PUBLIC_SELECT],
5496    }
5497});
5498
5499pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5500    name: "mz_license_keys",
5501    schema: MZ_INTERNAL_SCHEMA,
5502    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
5503    desc: RelationDesc::builder()
5504        .with_column("id", SqlScalarType::String.nullable(false))
5505        .with_column("organization", SqlScalarType::String.nullable(false))
5506        .with_column("environment_id", SqlScalarType::String.nullable(false))
5507        .with_column(
5508            "expiration",
5509            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5510        )
5511        .with_column(
5512            "not_before",
5513            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5514        )
5515        .finish(),
5516    column_comments: BTreeMap::from_iter([
5517        ("id", "The identifier of the license key."),
5518        (
5519            "organization",
5520            "The name of the organization that this license key was issued to.",
5521        ),
5522        (
5523            "environment_id",
5524            "The environment ID that this license key was issued for.",
5525        ),
5526        (
5527            "expiration",
5528            "The date and time when this license key expires.",
5529        ),
5530        (
5531            "not_before",
5532            "The start of the validity period for this license key.",
5533        ),
5534    ]),
5535    is_retained_metrics_object: false,
5536    access: vec![PUBLIC_SELECT],
5537});
5538
5539pub static MZ_REPLACEMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5540    name: "mz_replacements",
5541    schema: MZ_INTERNAL_SCHEMA,
5542    oid: oid::TABLE_MZ_REPLACEMENTS_OID,
5543    desc: RelationDesc::builder()
5544        .with_column("id", SqlScalarType::String.nullable(false))
5545        .with_column("target_id", SqlScalarType::String.nullable(false))
5546        .finish(),
5547    column_comments: BTreeMap::from_iter([
5548        (
5549            "id",
5550            "The ID of the replacement object. Corresponds to `mz_objects.id`.",
5551        ),
5552        (
5553            "target_id",
5554            "The ID of the replacement target. Corresponds to `mz_objects.id`.",
5555        ),
5556    ]),
5557    is_retained_metrics_object: false,
5558    access: vec![PUBLIC_SELECT],
5559});
5560
5561// These will be replaced with per-replica tables once source/sink multiplexing on
5562// a single cluster is supported.
5563pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5564    name: "mz_source_statistics_raw",
5565    schema: MZ_INTERNAL_SCHEMA,
5566    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5567    data_source: IntrospectionType::StorageSourceStatistics,
5568    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5569    column_comments: BTreeMap::new(),
5570    is_retained_metrics_object: true,
5571    access: vec![PUBLIC_SELECT],
5572});
5573pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5574    name: "mz_sink_statistics_raw",
5575    schema: MZ_INTERNAL_SCHEMA,
5576    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5577    data_source: IntrospectionType::StorageSinkStatistics,
5578    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5579    column_comments: BTreeMap::new(),
5580    is_retained_metrics_object: true,
5581    access: vec![PUBLIC_SELECT],
5582});
5583
5584pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5585    name: "mz_storage_shards",
5586    schema: MZ_INTERNAL_SCHEMA,
5587    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5588    data_source: IntrospectionType::ShardMapping,
5589    desc: RelationDesc::builder()
5590        .with_column("object_id", SqlScalarType::String.nullable(false))
5591        .with_column("shard_id", SqlScalarType::String.nullable(false))
5592        .finish(),
5593    column_comments: BTreeMap::new(),
5594    is_retained_metrics_object: false,
5595    access: vec![PUBLIC_SELECT],
5596});
5597
5598pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5599    name: "mz_storage_usage",
5600    schema: MZ_CATALOG_SCHEMA,
5601    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5602    desc: RelationDesc::builder()
5603        .with_column("object_id", SqlScalarType::String.nullable(false))
5604        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5605        .with_column(
5606            "collection_timestamp",
5607            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5608        )
5609        .with_key(vec![0, 2])
5610        .finish(),
5611    column_comments: BTreeMap::from_iter([
5612        (
5613            "object_id",
5614            "The ID of the table, source, or materialized view.",
5615        ),
5616        (
5617            "size_bytes",
5618            "The number of storage bytes used by the object.",
5619        ),
5620        (
5621            "collection_timestamp",
5622            "The time at which storage usage of the object was assessed.",
5623        ),
5624    ]),
5625    sql: "
5626SELECT
5627    object_id,
5628    sum(size_bytes)::uint8 AS size_bytes,
5629    collection_timestamp
5630FROM
5631    mz_internal.mz_storage_shards
5632    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5633GROUP BY object_id, collection_timestamp",
5634    access: vec![PUBLIC_SELECT],
5635});
5636
5637pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5638    BuiltinView {
5639    name: "mz_recent_storage_usage",
5640    schema: MZ_CATALOG_SCHEMA,
5641    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
5642    desc: RelationDesc::builder()
5643        .with_column("object_id", SqlScalarType::String.nullable(false))
5644        .with_column("size_bytes", SqlScalarType::UInt64.nullable(true))
5645        .with_key(vec![0])
5646        .finish(),
5647    column_comments: BTreeMap::from_iter([
5648        ("object_id", "The ID of the table, source, or materialized view."),
5649        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
5650    ]),
5651    sql: "
5652WITH
5653
5654recent_storage_usage_by_shard AS (
5655    SELECT shard_id, size_bytes, collection_timestamp
5656    FROM mz_internal.mz_storage_usage_by_shard
5657    -- Restricting to the last 6 hours makes it feasible to index the view.
5658    WHERE collection_timestamp + '6 hours' >= mz_now()
5659),
5660
5661most_recent_collection_timestamp_by_shard AS (
5662    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
5663    FROM recent_storage_usage_by_shard
5664    GROUP BY shard_id
5665)
5666
5667SELECT
5668    object_id,
5669    sum(size_bytes)::uint8 AS size_bytes
5670FROM
5671    mz_internal.mz_storage_shards
5672    LEFT JOIN most_recent_collection_timestamp_by_shard
5673        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
5674    LEFT JOIN recent_storage_usage_by_shard
5675        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
5676        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
5677GROUP BY object_id",
5678    access: vec![PUBLIC_SELECT],
5679}
5680});
5681
5682pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
5683    name: "mz_recent_storage_usage_ind",
5684    schema: MZ_CATALOG_SCHEMA,
5685    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
5686    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
5687    is_retained_metrics_object: false,
5688});
5689
5690pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
5691    BuiltinView {
5692        name: "mz_relations",
5693        schema: MZ_CATALOG_SCHEMA,
5694        oid: oid::VIEW_MZ_RELATIONS_OID,
5695        desc: RelationDesc::builder()
5696            .with_column("id", SqlScalarType::String.nullable(false))
5697            .with_column("oid", SqlScalarType::Oid.nullable(false))
5698            .with_column("schema_id", SqlScalarType::String.nullable(false))
5699            .with_column("name", SqlScalarType::String.nullable(false))
5700            .with_column("type", SqlScalarType::String.nullable(false))
5701            .with_column("owner_id", SqlScalarType::String.nullable(false))
5702            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5703            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false))
5704            .finish(),
5705        column_comments: BTreeMap::from_iter([
5706            ("id", "Materialize's unique ID for the relation."),
5707            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the relation."),
5708            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
5709            ("name", "The name of the relation."),
5710            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
5711            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
5712            ("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."),
5713            ("privileges", "The privileges belonging to the relation."),
5714        ]),
5715        sql: "
5716      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
5717UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
5718UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
5719UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views
5720UNION ALL SELECT id, oid, schema_id, name, 'continual-task', owner_id, cluster_id, privileges FROM mz_internal.mz_continual_tasks",
5721        access: vec![PUBLIC_SELECT],
5722    }
5723});
5724
5725pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5726    name: "mz_objects_id_namespace_types",
5727    schema: MZ_INTERNAL_SCHEMA,
5728    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
5729    desc: RelationDesc::builder()
5730        .with_column("object_type", SqlScalarType::String.nullable(false))
5731        .with_key(vec![0])
5732        .finish(),
5733    column_comments: BTreeMap::new(),
5734    sql: r#"SELECT *
5735    FROM (
5736        VALUES
5737            ('table'),
5738            ('view'),
5739            ('materialized-view'),
5740            ('source'),
5741            ('sink'),
5742            ('index'),
5743            ('connection'),
5744            ('type'),
5745            ('function'),
5746            ('secret')
5747    )
5748    AS _ (object_type)"#,
5749    access: vec![PUBLIC_SELECT],
5750});
5751
5752pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5753    name: "mz_object_oid_alias",
5754    schema: MZ_INTERNAL_SCHEMA,
5755    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
5756    desc: RelationDesc::builder()
5757        .with_column("object_type", SqlScalarType::String.nullable(false))
5758        .with_column("oid_alias", SqlScalarType::String.nullable(false))
5759        .with_key(vec![0])
5760        .finish(),
5761    column_comments: BTreeMap::new(),
5762    sql: "SELECT object_type, oid_alias
5763    FROM (
5764        VALUES
5765            (
5766                'table'::pg_catalog.text,
5767                'regclass'::pg_catalog.text
5768            ),
5769            ('source', 'regclass'),
5770            ('view', 'regclass'),
5771            ('materialized-view', 'regclass'),
5772            ('index', 'regclass'),
5773            ('type', 'regtype'),
5774            ('function', 'regproc')
5775    )
5776    AS _ (object_type, oid_alias);",
5777    access: vec![PUBLIC_SELECT],
5778});
5779
5780pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
5781    BuiltinView {
5782        name: "mz_objects",
5783        schema: MZ_CATALOG_SCHEMA,
5784        oid: oid::VIEW_MZ_OBJECTS_OID,
5785        desc: RelationDesc::builder()
5786            .with_column("id", SqlScalarType::String.nullable(false))
5787            .with_column("oid", SqlScalarType::Oid.nullable(false))
5788            .with_column("schema_id", SqlScalarType::String.nullable(false))
5789            .with_column("name", SqlScalarType::String.nullable(false))
5790            .with_column("type", SqlScalarType::String.nullable(false))
5791            .with_column("owner_id", SqlScalarType::String.nullable(false))
5792            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5793            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(true))
5794            .finish(),
5795        column_comments: BTreeMap::from_iter([
5796            ("id", "Materialize's unique ID for the object."),
5797            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the object."),
5798            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
5799            ("name", "The name of the object."),
5800            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
5801            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
5802            ("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."),
5803            ("privileges", "The privileges belonging to the object."),
5804        ]),
5805        sql:
5806        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
5807UNION ALL
5808    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
5809UNION ALL
5810    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[]
5811    FROM mz_catalog.mz_indexes
5812    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
5813UNION ALL
5814    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
5815UNION ALL
5816    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
5817UNION ALL
5818    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
5819UNION ALL
5820    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
5821        access: vec![PUBLIC_SELECT],
5822    }
5823});
5824
5825pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5826    name: "mz_object_fully_qualified_names",
5827    schema: MZ_INTERNAL_SCHEMA,
5828    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
5829    desc: RelationDesc::builder()
5830        .with_column("id", SqlScalarType::String.nullable(false))
5831        .with_column("name", SqlScalarType::String.nullable(false))
5832        .with_column("object_type", SqlScalarType::String.nullable(false))
5833        .with_column("schema_id", SqlScalarType::String.nullable(false))
5834        .with_column("schema_name", SqlScalarType::String.nullable(false))
5835        .with_column("database_id", SqlScalarType::String.nullable(true))
5836        .with_column("database_name", SqlScalarType::String.nullable(true))
5837        .with_column("cluster_id", SqlScalarType::String.nullable(true))
5838        .finish(),
5839    column_comments: BTreeMap::from_iter([
5840        ("id", "Materialize's unique ID for the object."),
5841        ("name", "The name of the object."),
5842        (
5843            "object_type",
5844            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5845        ),
5846        (
5847            "schema_id",
5848            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
5849        ),
5850        (
5851            "schema_name",
5852            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
5853        ),
5854        (
5855            "database_id",
5856            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
5857        ),
5858        (
5859            "database_name",
5860            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
5861        ),
5862        (
5863            "cluster_id",
5864            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
5865        ),
5866    ]),
5867    sql: "
5868    SELECT o.id,
5869        o.name,
5870        o.type as object_type,
5871        sc.id as schema_id,
5872        sc.name as schema_name,
5873        db.id as database_id,
5874        db.name as database_name,
5875        o.cluster_id
5876    FROM mz_catalog.mz_objects o
5877    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
5878    -- LEFT JOIN accounts for objects in the ambient database.
5879    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
5880    access: vec![PUBLIC_SELECT],
5881});
5882
5883pub static MZ_OBJECT_GLOBAL_IDS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5884    name: "mz_object_global_ids",
5885    schema: MZ_INTERNAL_SCHEMA,
5886    oid: oid::VIEW_MZ_OBJECT_GLOBAL_IDS_OID,
5887    desc: RelationDesc::builder()
5888        .with_column("id", SqlScalarType::String.nullable(false))
5889        .with_column("global_id", SqlScalarType::String.nullable(false))
5890        .finish(),
5891    column_comments: BTreeMap::from_iter([
5892        ("id", "Materialize's unique catalog item ID for the object."),
5893        ("global_id", "A global ID for the object."),
5894    ]),
5895    is_retained_metrics_object: false,
5896    access: vec![PUBLIC_SELECT],
5897});
5898
5899// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
5900pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5901    name: "mz_object_lifetimes",
5902    schema: MZ_INTERNAL_SCHEMA,
5903    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
5904    desc: RelationDesc::builder()
5905        .with_column("id", SqlScalarType::String.nullable(true))
5906        .with_column("previous_id", SqlScalarType::String.nullable(true))
5907        .with_column("object_type", SqlScalarType::String.nullable(false))
5908        .with_column("event_type", SqlScalarType::String.nullable(false))
5909        .with_column(
5910            "occurred_at",
5911            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5912        )
5913        .finish(),
5914    column_comments: BTreeMap::from_iter([
5915        ("id", "Materialize's unique ID for the object."),
5916        ("previous_id", "The object's previous ID, if one exists."),
5917        (
5918            "object_type",
5919            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5920        ),
5921        (
5922            "event_type",
5923            "The lifetime event, either `create` or `drop`.",
5924        ),
5925        (
5926            "occurred_at",
5927            "Wall-clock timestamp of when the event occurred.",
5928        ),
5929    ]),
5930    sql: "
5931    SELECT
5932        CASE
5933            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
5934            ELSE a.details ->> 'id'
5935        END id,
5936        a.details ->> 'previous_id' as previous_id,
5937        a.object_type,
5938        a.event_type,
5939        a.occurred_at
5940    FROM mz_catalog.mz_audit_events a
5941    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
5942    access: vec![PUBLIC_SELECT],
5943});
5944
5945pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5946    name: "mz_object_history",
5947    schema: MZ_INTERNAL_SCHEMA,
5948    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
5949    desc: RelationDesc::builder()
5950        .with_column("id", SqlScalarType::String.nullable(true))
5951        .with_column("cluster_id", SqlScalarType::String.nullable(true))
5952        .with_column("object_type", SqlScalarType::String.nullable(false))
5953        .with_column(
5954            "created_at",
5955            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5956        )
5957        .with_column(
5958            "dropped_at",
5959            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5960        )
5961        .finish(),
5962    column_comments: BTreeMap::from_iter([
5963        ("id", "Materialize's unique ID for the object."),
5964        (
5965            "cluster_id",
5966            "The object's cluster ID. `NULL` if the object has no associated cluster.",
5967        ),
5968        (
5969            "object_type",
5970            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5971        ),
5972        (
5973            "created_at",
5974            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
5975        ),
5976        (
5977            "dropped_at",
5978            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
5979        ),
5980    ]),
5981    sql: r#"
5982    WITH
5983        creates AS
5984        (
5985            SELECT
5986                details ->> 'id' AS id,
5987                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
5988                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
5989                object_type,
5990                occurred_at
5991            FROM
5992                mz_catalog.mz_audit_events AS events
5993                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
5994            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
5995        ),
5996        drops AS
5997        (
5998            SELECT details ->> 'id' AS id, occurred_at
5999            FROM mz_catalog.mz_audit_events
6000            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6001        ),
6002        user_object_history AS
6003        (
6004            SELECT
6005                creates.id,
6006                creates.cluster_id,
6007                creates.object_type,
6008                creates.occurred_at AS created_at,
6009                drops.occurred_at AS dropped_at
6010            FROM creates LEFT JOIN drops ON creates.id = drops.id
6011            WHERE creates.id LIKE 'u%'
6012        ),
6013        -- We need to union built in objects since they aren't in the audit log
6014        built_in_objects AS
6015        (
6016            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
6017            SELECT DISTINCT ON (objects.id)
6018                objects.id,
6019                objects.cluster_id,
6020                objects.type AS object_type,
6021                NULL::timestamptz AS created_at,
6022                NULL::timestamptz AS dropped_at
6023            FROM mz_catalog.mz_objects AS objects
6024            WHERE objects.id LIKE 's%'
6025        )
6026    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
6027    access: vec![PUBLIC_SELECT],
6028});
6029
6030pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6031    name: "mz_dataflows_per_worker",
6032    schema: MZ_INTROSPECTION_SCHEMA,
6033    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
6034    desc: RelationDesc::builder()
6035        .with_column("id", SqlScalarType::UInt64.nullable(true))
6036        .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6037        .with_column("name", SqlScalarType::String.nullable(false))
6038        .finish(),
6039    column_comments: BTreeMap::new(),
6040    sql: "SELECT
6041    addrs.address[1] AS id,
6042    ops.worker_id,
6043    ops.name
6044FROM
6045    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6046    mz_introspection.mz_dataflow_operators_per_worker ops
6047WHERE
6048    addrs.id = ops.id AND
6049    addrs.worker_id = ops.worker_id AND
6050    mz_catalog.list_length(addrs.address) = 1",
6051    access: vec![PUBLIC_SELECT],
6052});
6053
6054pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6055    name: "mz_dataflows",
6056    schema: MZ_INTROSPECTION_SCHEMA,
6057    oid: oid::VIEW_MZ_DATAFLOWS_OID,
6058    desc: RelationDesc::builder()
6059        .with_column("id", SqlScalarType::UInt64.nullable(true))
6060        .with_column("name", SqlScalarType::String.nullable(false))
6061        .finish(),
6062    column_comments: BTreeMap::from_iter([
6063        ("id", "The ID of the dataflow."),
6064        ("name", "The internal name of the dataflow."),
6065    ]),
6066    sql: "
6067SELECT id, name
6068FROM mz_introspection.mz_dataflows_per_worker
6069WHERE worker_id = 0",
6070    access: vec![PUBLIC_SELECT],
6071});
6072
6073pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6074    name: "mz_dataflow_addresses",
6075    schema: MZ_INTROSPECTION_SCHEMA,
6076    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
6077    desc: RelationDesc::builder()
6078        .with_column("id", SqlScalarType::UInt64.nullable(false))
6079        .with_column(
6080            "address",
6081            SqlScalarType::List {
6082                element_type: Box::new(SqlScalarType::UInt64),
6083                custom_id: None,
6084            }
6085            .nullable(false),
6086        )
6087        .finish(),
6088    column_comments: BTreeMap::from_iter([
6089        (
6090            "id",
6091            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
6092        ),
6093        (
6094            "address",
6095            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
6096        ),
6097    ]),
6098    sql: "
6099SELECT id, address
6100FROM mz_introspection.mz_dataflow_addresses_per_worker
6101WHERE worker_id = 0",
6102    access: vec![PUBLIC_SELECT],
6103});
6104
6105pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6106    name: "mz_dataflow_channels",
6107    schema: MZ_INTROSPECTION_SCHEMA,
6108    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
6109    desc: RelationDesc::builder()
6110        .with_column("id", SqlScalarType::UInt64.nullable(false))
6111        .with_column("from_index", SqlScalarType::UInt64.nullable(false))
6112        .with_column("from_port", SqlScalarType::UInt64.nullable(false))
6113        .with_column("to_index", SqlScalarType::UInt64.nullable(false))
6114        .with_column("to_port", SqlScalarType::UInt64.nullable(false))
6115        .with_column("type", SqlScalarType::String.nullable(false))
6116        .finish(),
6117    column_comments: BTreeMap::from_iter([
6118        ("id", "The ID of the channel."),
6119        (
6120            "from_index",
6121            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
6122        ),
6123        ("from_port", "The source operator's output port."),
6124        (
6125            "to_index",
6126            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
6127        ),
6128        ("to_port", "The target operator's input port."),
6129        ("type", "The container type of the channel."),
6130    ]),
6131    sql: "
6132SELECT id, from_index, from_port, to_index, to_port, type
6133FROM mz_introspection.mz_dataflow_channels_per_worker
6134WHERE worker_id = 0",
6135    access: vec![PUBLIC_SELECT],
6136});
6137
6138pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6139    name: "mz_dataflow_operators",
6140    schema: MZ_INTROSPECTION_SCHEMA,
6141    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6142    desc: RelationDesc::builder()
6143        .with_column("id", SqlScalarType::UInt64.nullable(false))
6144        .with_column("name", SqlScalarType::String.nullable(false))
6145        .finish(),
6146    column_comments: BTreeMap::from_iter([
6147        ("id", "The ID of the operator."),
6148        ("name", "The internal name of the operator."),
6149    ]),
6150    sql: "
6151SELECT id, name
6152FROM mz_introspection.mz_dataflow_operators_per_worker
6153WHERE worker_id = 0",
6154    access: vec![PUBLIC_SELECT],
6155});
6156
6157pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6158    name: "mz_dataflow_global_ids",
6159    schema: MZ_INTROSPECTION_SCHEMA,
6160    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6161    desc: RelationDesc::builder()
6162        .with_column("id", SqlScalarType::UInt64.nullable(false))
6163        .with_column("global_id", SqlScalarType::String.nullable(false))
6164        .finish(),
6165    column_comments: BTreeMap::from_iter([
6166        ("id", "The dataflow ID."),
6167        ("global_id", "A global ID associated with that dataflow."),
6168    ]),
6169    sql: "
6170SELECT id, global_id
6171FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6172WHERE worker_id = 0",
6173    access: vec![PUBLIC_SELECT],
6174});
6175
6176pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6177    BuiltinView {
6178    name: "mz_mappable_objects",
6179    schema: MZ_INTROSPECTION_SCHEMA,
6180    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6181    desc: RelationDesc::builder()
6182        .with_column("name", SqlScalarType::String.nullable(false))
6183        .with_column("global_id", SqlScalarType::String.nullable(false))
6184        .finish(),
6185    column_comments: BTreeMap::from_iter([
6186        ("name", "The name of the object."),
6187        ("global_id", "The global ID of the object."),
6188    ]),
6189    sql: "
6190SELECT COALESCE(quote_ident(md.name) || '.', '') || quote_ident(ms.name) || '.' || quote_ident(mo.name) AS name, mgi.global_id AS global_id
6191FROM      mz_catalog.mz_objects mo
6192          JOIN mz_introspection.mz_compute_exports mce ON (mo.id = mce.export_id)
6193          JOIN mz_catalog.mz_schemas ms ON (mo.schema_id = ms.id)
6194          JOIN mz_introspection.mz_dataflow_global_ids mgi ON (mce.dataflow_id = mgi.id)
6195     LEFT JOIN mz_catalog.mz_databases md ON (ms.database_id = md.id);",
6196    access: vec![PUBLIC_SELECT],
6197}
6198});
6199
6200pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6201    name: "mz_lir_mapping",
6202    schema: MZ_INTROSPECTION_SCHEMA,
6203    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6204    desc: RelationDesc::builder()
6205        .with_column("global_id", SqlScalarType::String.nullable(false))
6206        .with_column("lir_id", SqlScalarType::UInt64.nullable(false))
6207        .with_column("operator", SqlScalarType::String.nullable(false))
6208        .with_column("parent_lir_id", SqlScalarType::UInt64.nullable(true))
6209        .with_column("nesting", SqlScalarType::UInt16.nullable(false))
6210        .with_column("operator_id_start", SqlScalarType::UInt64.nullable(false))
6211        .with_column("operator_id_end", SqlScalarType::UInt64.nullable(false))
6212        .finish(),
6213    column_comments: BTreeMap::from_iter([
6214        ("global_id", "The global ID."),
6215        ("lir_id", "The LIR node ID."),
6216        (
6217            "operator",
6218            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6219        ),
6220        (
6221            "parent_lir_id",
6222            "The parent of this LIR node. May be `NULL`.",
6223        ),
6224        ("nesting", "The nesting level of this LIR node."),
6225        (
6226            "operator_id_start",
6227            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6228        ),
6229        (
6230            "operator_id_end",
6231            "The first dataflow operator ID after this LIR operator (exclusive).",
6232        ),
6233    ]),
6234    sql: "
6235SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6236FROM mz_introspection.mz_compute_lir_mapping_per_worker
6237WHERE worker_id = 0",
6238    access: vec![PUBLIC_SELECT],
6239});
6240
6241pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6242    LazyLock::new(|| BuiltinView {
6243        name: "mz_dataflow_operator_dataflows_per_worker",
6244        schema: MZ_INTROSPECTION_SCHEMA,
6245        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6246        desc: RelationDesc::builder()
6247            .with_column("id", SqlScalarType::UInt64.nullable(false))
6248            .with_column("name", SqlScalarType::String.nullable(false))
6249            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6250            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6251            .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6252            .finish(),
6253        column_comments: BTreeMap::new(),
6254        sql: "SELECT
6255    ops.id,
6256    ops.name,
6257    ops.worker_id,
6258    dfs.id as dataflow_id,
6259    dfs.name as dataflow_name
6260FROM
6261    mz_introspection.mz_dataflow_operators_per_worker ops,
6262    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6263    mz_introspection.mz_dataflows_per_worker dfs
6264WHERE
6265    ops.id = addrs.id AND
6266    ops.worker_id = addrs.worker_id AND
6267    dfs.id = addrs.address[1] AND
6268    dfs.worker_id = addrs.worker_id",
6269        access: vec![PUBLIC_SELECT],
6270    });
6271
6272pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6273    name: "mz_dataflow_operator_dataflows",
6274    schema: MZ_INTROSPECTION_SCHEMA,
6275    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6276    desc: RelationDesc::builder()
6277        .with_column("id", SqlScalarType::UInt64.nullable(false))
6278        .with_column("name", SqlScalarType::String.nullable(false))
6279        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6280        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6281        .finish(),
6282    column_comments: BTreeMap::from_iter([
6283        (
6284            "id",
6285            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6286        ),
6287        ("name", "The internal name of the operator."),
6288        (
6289            "dataflow_id",
6290            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6291        ),
6292        (
6293            "dataflow_name",
6294            "The internal name of the dataflow hosting the operator.",
6295        ),
6296    ]),
6297    sql: "
6298SELECT id, name, dataflow_id, dataflow_name
6299FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6300WHERE worker_id = 0",
6301    access: vec![PUBLIC_SELECT],
6302});
6303
6304pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6305    BuiltinView {
6306        name: "mz_object_transitive_dependencies",
6307        schema: MZ_INTERNAL_SCHEMA,
6308        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6309        desc: RelationDesc::builder()
6310            .with_column("object_id", SqlScalarType::String.nullable(false))
6311            .with_column(
6312                "referenced_object_id",
6313                SqlScalarType::String.nullable(false),
6314            )
6315            .with_key(vec![0, 1])
6316            .finish(),
6317        column_comments: BTreeMap::from_iter([
6318            (
6319                "object_id",
6320                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6321            ),
6322            (
6323                "referenced_object_id",
6324                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6325            ),
6326        ]),
6327        sql: "
6328WITH MUTUALLY RECURSIVE
6329  reach(object_id text, referenced_object_id text) AS (
6330    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6331    UNION
6332    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6333  )
6334SELECT object_id, referenced_object_id FROM reach;",
6335        access: vec![PUBLIC_SELECT],
6336    }
6337});
6338
6339pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6340    name: "mz_compute_exports",
6341    schema: MZ_INTROSPECTION_SCHEMA,
6342    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6343    desc: RelationDesc::builder()
6344        .with_column("export_id", SqlScalarType::String.nullable(false))
6345        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6346        .finish(),
6347    column_comments: BTreeMap::from_iter([
6348        (
6349            "export_id",
6350            "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`.",
6351        ),
6352        (
6353            "dataflow_id",
6354            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6355        ),
6356    ]),
6357    sql: "
6358SELECT export_id, dataflow_id
6359FROM mz_introspection.mz_compute_exports_per_worker
6360WHERE worker_id = 0",
6361    access: vec![PUBLIC_SELECT],
6362});
6363
6364pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6365    name: "mz_compute_frontiers",
6366    schema: MZ_INTROSPECTION_SCHEMA,
6367    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6368    desc: RelationDesc::builder()
6369        .with_column("export_id", SqlScalarType::String.nullable(false))
6370        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6371        .with_key(vec![0])
6372        .finish(),
6373    column_comments: BTreeMap::from_iter([
6374        (
6375            "export_id",
6376            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6377        ),
6378        (
6379            "time",
6380            "The next timestamp at which the dataflow output may change.",
6381        ),
6382    ]),
6383    sql: "SELECT
6384    export_id, pg_catalog.min(time) AS time
6385FROM mz_introspection.mz_compute_frontiers_per_worker
6386GROUP BY export_id",
6387    access: vec![PUBLIC_SELECT],
6388});
6389
6390pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6391    LazyLock::new(|| BuiltinView {
6392        name: "mz_dataflow_channel_operators_per_worker",
6393        schema: MZ_INTROSPECTION_SCHEMA,
6394        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6395        desc: RelationDesc::builder()
6396            .with_column("id", SqlScalarType::UInt64.nullable(false))
6397            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6398            .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6399            .with_column(
6400                "from_operator_address",
6401                SqlScalarType::List {
6402                    element_type: Box::new(SqlScalarType::UInt64),
6403                    custom_id: None,
6404                }
6405                .nullable(true),
6406            )
6407            .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6408            .with_column(
6409                "to_operator_address",
6410                SqlScalarType::List {
6411                    element_type: Box::new(SqlScalarType::UInt64),
6412                    custom_id: None,
6413                }
6414                .nullable(true),
6415            )
6416            .with_column("type", SqlScalarType::String.nullable(false))
6417            .finish(),
6418        column_comments: BTreeMap::new(),
6419        sql: "
6420WITH
6421channel_addresses(id, worker_id, address, from_index, to_index, type) AS (
6422     SELECT id, worker_id, address, from_index, to_index, type
6423     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6424     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6425     USING (id, worker_id)
6426),
6427channel_operator_addresses(id, worker_id, from_address, to_address, type) AS (
6428     SELECT id, worker_id,
6429            address || from_index AS from_address,
6430            address || to_index AS to_address,
6431            type
6432     FROM channel_addresses
6433),
6434operator_addresses(id, worker_id, address) AS (
6435     SELECT id, worker_id, address
6436     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6437     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6438     USING (id, worker_id)
6439)
6440SELECT coa.id,
6441       coa.worker_id,
6442       from_ops.id AS from_operator_id,
6443       coa.from_address AS from_operator_address,
6444       to_ops.id AS to_operator_id,
6445       coa.to_address AS to_operator_address,
6446       coa.type
6447FROM channel_operator_addresses coa
6448     LEFT OUTER JOIN operator_addresses from_ops
6449          ON coa.from_address = from_ops.address AND
6450             coa.worker_id = from_ops.worker_id
6451     LEFT OUTER JOIN operator_addresses to_ops
6452          ON coa.to_address = to_ops.address AND
6453             coa.worker_id = to_ops.worker_id
6454",
6455        access: vec![PUBLIC_SELECT],
6456    });
6457
6458pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6459    name: "mz_dataflow_channel_operators",
6460    schema: MZ_INTROSPECTION_SCHEMA,
6461    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6462    desc: RelationDesc::builder()
6463        .with_column("id", SqlScalarType::UInt64.nullable(false))
6464        .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6465        .with_column(
6466            "from_operator_address",
6467            SqlScalarType::List {
6468                element_type: Box::new(SqlScalarType::UInt64),
6469                custom_id: None,
6470            }
6471            .nullable(true),
6472        )
6473        .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6474        .with_column(
6475            "to_operator_address",
6476            SqlScalarType::List {
6477                element_type: Box::new(SqlScalarType::UInt64),
6478                custom_id: None,
6479            }
6480            .nullable(true),
6481        )
6482        .with_column("type", SqlScalarType::String.nullable(false))
6483        .finish(),
6484    column_comments: BTreeMap::from_iter([
6485        (
6486            "id",
6487            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6488        ),
6489        (
6490            "from_operator_id",
6491            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6492        ),
6493        (
6494            "from_operator_address",
6495            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6496        ),
6497        (
6498            "to_operator_id",
6499            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6500        ),
6501        (
6502            "to_operator_address",
6503            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6504        ),
6505        ("type", "The container type of the channel."),
6506    ]),
6507    sql: "
6508SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address, type
6509FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6510WHERE worker_id = 0",
6511    access: vec![PUBLIC_SELECT],
6512});
6513
6514pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6515    name: "mz_compute_import_frontiers",
6516    schema: MZ_INTROSPECTION_SCHEMA,
6517    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6518    desc: RelationDesc::builder()
6519        .with_column("export_id", SqlScalarType::String.nullable(false))
6520        .with_column("import_id", SqlScalarType::String.nullable(false))
6521        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6522        .with_key(vec![0, 1])
6523        .finish(),
6524    column_comments: BTreeMap::from_iter([
6525        (
6526            "export_id",
6527            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6528        ),
6529        (
6530            "import_id",
6531            "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`.",
6532        ),
6533        (
6534            "time",
6535            "The next timestamp at which the dataflow input may change.",
6536        ),
6537    ]),
6538    sql: "SELECT
6539    export_id, import_id, pg_catalog.min(time) AS time
6540FROM mz_introspection.mz_compute_import_frontiers_per_worker
6541GROUP BY export_id, import_id",
6542    access: vec![PUBLIC_SELECT],
6543});
6544
6545pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6546    LazyLock::new(|| BuiltinView {
6547        name: "mz_records_per_dataflow_operator_per_worker",
6548        schema: MZ_INTROSPECTION_SCHEMA,
6549        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6550        desc: RelationDesc::builder()
6551            .with_column("id", SqlScalarType::UInt64.nullable(false))
6552            .with_column("name", SqlScalarType::String.nullable(false))
6553            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6554            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6555            .with_column("records", SqlScalarType::Int64.nullable(true))
6556            .with_column("batches", SqlScalarType::Int64.nullable(true))
6557            .with_column("size", SqlScalarType::Int64.nullable(true))
6558            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6559            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6560            .finish(),
6561        column_comments: BTreeMap::new(),
6562        sql: "
6563SELECT
6564    dod.id,
6565    dod.name,
6566    dod.worker_id,
6567    dod.dataflow_id,
6568    ar_size.records AS records,
6569    ar_size.batches AS batches,
6570    ar_size.size AS size,
6571    ar_size.capacity AS capacity,
6572    ar_size.allocations AS allocations
6573FROM
6574    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6575    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6576        dod.id = ar_size.operator_id AND
6577        dod.worker_id = ar_size.worker_id",
6578        access: vec![PUBLIC_SELECT],
6579    });
6580
6581pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6582    LazyLock::new(|| BuiltinView {
6583        name: "mz_records_per_dataflow_operator",
6584        schema: MZ_INTROSPECTION_SCHEMA,
6585        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6586        desc: RelationDesc::builder()
6587            .with_column("id", SqlScalarType::UInt64.nullable(false))
6588            .with_column("name", SqlScalarType::String.nullable(false))
6589            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6590            .with_column("records", SqlScalarType::Int64.nullable(true))
6591            .with_column("batches", SqlScalarType::Int64.nullable(true))
6592            .with_column("size", SqlScalarType::Int64.nullable(true))
6593            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6594            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6595            .with_key(vec![0, 1, 2])
6596            .finish(),
6597        column_comments: BTreeMap::from_iter([
6598            (
6599                "id",
6600                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6601            ),
6602            ("name", "The internal name of the operator."),
6603            (
6604                "dataflow_id",
6605                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6606            ),
6607            ("records", "The number of records in the operator."),
6608            ("batches", "The number of batches in the dataflow."),
6609            ("size", "The utilized size in bytes of the arrangement."),
6610            (
6611                "capacity",
6612                "The capacity in bytes of the arrangement. Can be larger than the size.",
6613            ),
6614            (
6615                "allocations",
6616                "The number of separate memory allocations backing the arrangement.",
6617            ),
6618        ]),
6619        sql: "
6620SELECT
6621    id,
6622    name,
6623    dataflow_id,
6624    SUM(records)::int8 AS records,
6625    SUM(batches)::int8 AS batches,
6626    SUM(size)::int8 AS size,
6627    SUM(capacity)::int8 AS capacity,
6628    SUM(allocations)::int8 AS allocations
6629FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
6630GROUP BY id, name, dataflow_id",
6631        access: vec![PUBLIC_SELECT],
6632    });
6633
6634pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
6635    LazyLock::new(|| BuiltinView {
6636        name: "mz_records_per_dataflow_per_worker",
6637        schema: MZ_INTROSPECTION_SCHEMA,
6638        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
6639        desc: RelationDesc::builder()
6640            .with_column("id", SqlScalarType::UInt64.nullable(false))
6641            .with_column("name", SqlScalarType::String.nullable(false))
6642            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6643            .with_column("records", SqlScalarType::Int64.nullable(true))
6644            .with_column("batches", SqlScalarType::Int64.nullable(true))
6645            .with_column("size", SqlScalarType::Int64.nullable(true))
6646            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6647            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6648            .with_key(vec![0, 1, 2])
6649            .finish(),
6650        column_comments: BTreeMap::new(),
6651        sql: "
6652SELECT
6653    rdo.dataflow_id as id,
6654    dfs.name,
6655    rdo.worker_id,
6656    SUM(rdo.records)::int8 as records,
6657    SUM(rdo.batches)::int8 as batches,
6658    SUM(rdo.size)::int8 as size,
6659    SUM(rdo.capacity)::int8 as capacity,
6660    SUM(rdo.allocations)::int8 as allocations
6661FROM
6662    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
6663    mz_introspection.mz_dataflows_per_worker dfs
6664WHERE
6665    rdo.dataflow_id = dfs.id AND
6666    rdo.worker_id = dfs.worker_id
6667GROUP BY
6668    rdo.dataflow_id,
6669    dfs.name,
6670    rdo.worker_id",
6671        access: vec![PUBLIC_SELECT],
6672    });
6673
6674pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6675    name: "mz_records_per_dataflow",
6676    schema: MZ_INTROSPECTION_SCHEMA,
6677    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
6678    desc: RelationDesc::builder()
6679        .with_column("id", SqlScalarType::UInt64.nullable(false))
6680        .with_column("name", SqlScalarType::String.nullable(false))
6681        .with_column("records", SqlScalarType::Int64.nullable(true))
6682        .with_column("batches", SqlScalarType::Int64.nullable(true))
6683        .with_column("size", SqlScalarType::Int64.nullable(true))
6684        .with_column("capacity", SqlScalarType::Int64.nullable(true))
6685        .with_column("allocations", SqlScalarType::Int64.nullable(true))
6686        .with_key(vec![0, 1])
6687        .finish(),
6688    column_comments: BTreeMap::from_iter([
6689        (
6690            "id",
6691            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6692        ),
6693        ("name", "The internal name of the dataflow."),
6694        ("records", "The number of records in the dataflow."),
6695        ("batches", "The number of batches in the dataflow."),
6696        ("size", "The utilized size in bytes of the arrangements."),
6697        (
6698            "capacity",
6699            "The capacity in bytes of the arrangements. Can be larger than the size.",
6700        ),
6701        (
6702            "allocations",
6703            "The number of separate memory allocations backing the arrangements.",
6704        ),
6705    ]),
6706    sql: "
6707SELECT
6708    id,
6709    name,
6710    SUM(records)::int8 as records,
6711    SUM(batches)::int8 as batches,
6712    SUM(size)::int8 as size,
6713    SUM(capacity)::int8 as capacity,
6714    SUM(allocations)::int8 as allocations
6715FROM
6716    mz_introspection.mz_records_per_dataflow_per_worker
6717GROUP BY
6718    id,
6719    name",
6720    access: vec![PUBLIC_SELECT],
6721});
6722
6723/// Peeled version of `PG_NAMESPACE`:
6724/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6725///   in order to make this view indexable.
6726/// - This has the database name as an extra column, so that downstream views can check it against
6727///  `current_database()`.
6728pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6729    name: "pg_namespace_all_databases",
6730    schema: MZ_INTERNAL_SCHEMA,
6731    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
6732    desc: RelationDesc::builder()
6733        .with_column("oid", SqlScalarType::Oid.nullable(false))
6734        .with_column("nspname", SqlScalarType::String.nullable(false))
6735        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6736        .with_column(
6737            "nspacl",
6738            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6739        )
6740        .with_column("database_name", SqlScalarType::String.nullable(true))
6741        .finish(),
6742    column_comments: BTreeMap::new(),
6743    sql: "
6744SELECT
6745    s.oid AS oid,
6746    s.name AS nspname,
6747    role_owner.oid AS nspowner,
6748    NULL::pg_catalog.text[] AS nspacl,
6749    d.name as database_name
6750FROM mz_catalog.mz_schemas s
6751LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
6752JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
6753    access: vec![PUBLIC_SELECT],
6754});
6755
6756pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6757    name: "pg_namespace_all_databases_ind",
6758    schema: MZ_INTERNAL_SCHEMA,
6759    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
6760    sql: "IN CLUSTER mz_catalog_server
6761ON mz_internal.pg_namespace_all_databases (nspname)",
6762    is_retained_metrics_object: false,
6763};
6764
6765pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6766    name: "pg_namespace",
6767    schema: PG_CATALOG_SCHEMA,
6768    oid: oid::VIEW_PG_NAMESPACE_OID,
6769    desc: RelationDesc::builder()
6770        .with_column("oid", SqlScalarType::Oid.nullable(false))
6771        .with_column("nspname", SqlScalarType::String.nullable(false))
6772        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6773        .with_column(
6774            "nspacl",
6775            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6776        )
6777        .finish(),
6778    column_comments: BTreeMap::new(),
6779    sql: "
6780SELECT
6781    oid, nspname, nspowner, nspacl
6782FROM mz_internal.pg_namespace_all_databases
6783WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
6784    access: vec![PUBLIC_SELECT],
6785});
6786
6787/// Peeled version of `PG_CLASS`:
6788/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6789///   in order to make this view indexable.
6790/// - This has the database name as an extra column, so that downstream views can check it against
6791///  `current_database()`.
6792pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
6793    BuiltinView {
6794        name: "pg_class_all_databases",
6795        schema: MZ_INTERNAL_SCHEMA,
6796        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
6797        desc: RelationDesc::builder()
6798            .with_column("oid", SqlScalarType::Oid.nullable(false))
6799            .with_column("relname", SqlScalarType::String.nullable(false))
6800            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
6801            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
6802            .with_column("relowner", SqlScalarType::Oid.nullable(false))
6803            .with_column("relam", SqlScalarType::Oid.nullable(false))
6804            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
6805            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
6806            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
6807            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
6808            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
6809            .with_column("relkind", SqlScalarType::String.nullable(true))
6810            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
6811            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
6812            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
6813            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
6814            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
6815            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
6816            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
6817            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
6818            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
6819            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
6820            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
6821            .with_column("database_name", SqlScalarType::String.nullable(true))
6822            .finish(),
6823        column_comments: BTreeMap::new(),
6824        sql: "
6825SELECT
6826    class_objects.oid,
6827    class_objects.name AS relname,
6828    mz_schemas.oid AS relnamespace,
6829    -- MZ doesn't support typed tables so reloftype is filled with 0
6830    0::pg_catalog.oid AS reloftype,
6831    role_owner.oid AS relowner,
6832    0::pg_catalog.oid AS relam,
6833    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
6834    0::pg_catalog.oid AS reltablespace,
6835    -- MZ doesn't support (estimated) row counts currently.
6836    -- Postgres defines a value of -1 as unknown.
6837    -1::float4 as reltuples,
6838    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
6839    0::pg_catalog.oid AS reltoastrelid,
6840    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
6841    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
6842    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
6843    -- TODO(jkosh44): update this column when issue is resolved.
6844    'p'::pg_catalog.\"char\" AS relpersistence,
6845    CASE
6846        WHEN class_objects.type = 'table' THEN 'r'
6847        WHEN class_objects.type = 'source' THEN 'r'
6848        WHEN class_objects.type = 'index' THEN 'i'
6849        WHEN class_objects.type = 'view' THEN 'v'
6850        WHEN class_objects.type = 'materialized-view' THEN 'm'
6851    END relkind,
6852    COALESCE(
6853        (
6854            SELECT count(*)::pg_catalog.int2
6855            FROM mz_catalog.mz_columns
6856            WHERE mz_columns.id = class_objects.id
6857        ),
6858        0::pg_catalog.int2
6859    ) AS relnatts,
6860    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
6861    0::pg_catalog.int2 AS relchecks,
6862    -- MZ doesn't support creating rules so relhasrules is filled with false
6863    false AS relhasrules,
6864    -- MZ doesn't support creating triggers so relhastriggers is filled with false
6865    false AS relhastriggers,
6866    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
6867    false AS relhassubclass,
6868    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
6869    false AS relrowsecurity,
6870    false AS relforcerowsecurity,
6871    -- MZ doesn't support replication so relreplident is filled with 'd' for default
6872    'd'::pg_catalog.\"char\" AS relreplident,
6873    -- MZ doesn't support table partitioning so relispartition is filled with false
6874    false AS relispartition,
6875    -- PG removed relhasoids in v12 so it's filled with false
6876    false AS relhasoids,
6877    -- MZ doesn't support options for relations
6878    NULL::pg_catalog.text[] as reloptions,
6879    d.name as database_name
6880FROM (
6881    -- pg_class catalogs relations and indexes
6882    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
6883    UNION ALL
6884        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
6885        FROM mz_catalog.mz_indexes
6886        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6887) AS class_objects
6888JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6889LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6890JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
6891        access: vec![PUBLIC_SELECT],
6892    }
6893});
6894
6895pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6896    name: "pg_class_all_databases_ind",
6897    schema: MZ_INTERNAL_SCHEMA,
6898    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
6899    sql: "IN CLUSTER mz_catalog_server
6900ON mz_internal.pg_class_all_databases (relname)",
6901    is_retained_metrics_object: false,
6902};
6903
6904pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| {
6905    BuiltinView {
6906    name: "pg_class",
6907    schema: PG_CATALOG_SCHEMA,
6908    oid: oid::VIEW_PG_CLASS_OID,
6909    desc: RelationDesc::builder()
6910        .with_column("oid", SqlScalarType::Oid.nullable(false))
6911        .with_column("relname", SqlScalarType::String.nullable(false))
6912        .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
6913        .with_column("reloftype", SqlScalarType::Oid.nullable(false))
6914        .with_column("relowner", SqlScalarType::Oid.nullable(false))
6915        .with_column("relam", SqlScalarType::Oid.nullable(false))
6916        .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
6917        .with_column("reltuples", SqlScalarType::Float32.nullable(false))
6918        .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
6919        .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
6920        .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
6921        .with_column("relkind", SqlScalarType::String.nullable(true))
6922        .with_column("relnatts", SqlScalarType::Int16.nullable(false))
6923        .with_column("relchecks", SqlScalarType::Int16.nullable(false))
6924        .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
6925        .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
6926        .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
6927        .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
6928        .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
6929        .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
6930        .with_column("relispartition", SqlScalarType::Bool.nullable(false))
6931        .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
6932        .with_column(
6933            "reloptions",
6934            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6935        )
6936        .finish(),
6937    column_comments: BTreeMap::new(),
6938    sql: "
6939SELECT
6940    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
6941    relhasindex, relpersistence, relkind, relnatts, relchecks, relhasrules, relhastriggers, relhassubclass,
6942    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
6943FROM mz_internal.pg_class_all_databases
6944WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
6945",
6946    access: vec![PUBLIC_SELECT],
6947}
6948});
6949
6950pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6951    name: "pg_depend",
6952    schema: PG_CATALOG_SCHEMA,
6953    oid: oid::VIEW_PG_DEPEND_OID,
6954    desc: RelationDesc::builder()
6955        .with_column("classid", SqlScalarType::Oid.nullable(true))
6956        .with_column("objid", SqlScalarType::Oid.nullable(false))
6957        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
6958        .with_column("refclassid", SqlScalarType::Oid.nullable(true))
6959        .with_column("refobjid", SqlScalarType::Oid.nullable(false))
6960        .with_column("refobjsubid", SqlScalarType::Int32.nullable(false))
6961        .with_column("deptype", SqlScalarType::PgLegacyChar.nullable(false))
6962        .finish(),
6963    column_comments: BTreeMap::new(),
6964    sql: "
6965WITH class_objects AS (
6966    SELECT
6967        CASE
6968            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6969            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6970            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
6971            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
6972        END classid,
6973        id,
6974        oid,
6975        schema_id
6976    FROM mz_catalog.mz_relations
6977    UNION ALL
6978    SELECT
6979        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
6980        i.id,
6981        i.oid,
6982        r.schema_id
6983    FROM mz_catalog.mz_indexes i
6984    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
6985),
6986
6987current_objects AS (
6988    SELECT class_objects.*
6989    FROM class_objects
6990    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6991    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6992    -- This filter is tricky, as it filters out not just objects outside the
6993    -- database, but *dependencies* on objects outside this database. It's not
6994    -- clear that this is the right choice, but because PostgreSQL doesn't
6995    -- support cross-database references, it's not clear that the other choice
6996    -- is better.
6997    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
6998)
6999
7000SELECT
7001    objects.classid::pg_catalog.oid,
7002    objects.oid::pg_catalog.oid AS objid,
7003    0::pg_catalog.int4 AS objsubid,
7004    dependents.classid::pg_catalog.oid AS refclassid,
7005    dependents.oid::pg_catalog.oid AS refobjid,
7006    0::pg_catalog.int4 AS refobjsubid,
7007    'n'::pg_catalog.char AS deptype
7008FROM mz_internal.mz_object_dependencies
7009JOIN current_objects objects ON object_id = objects.id
7010JOIN current_objects dependents ON referenced_object_id = dependents.id",
7011    access: vec![PUBLIC_SELECT],
7012});
7013
7014pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7015    name: "pg_database",
7016    schema: PG_CATALOG_SCHEMA,
7017    oid: oid::VIEW_PG_DATABASE_OID,
7018    desc: RelationDesc::builder()
7019        .with_column("oid", SqlScalarType::Oid.nullable(false))
7020        .with_column("datname", SqlScalarType::String.nullable(false))
7021        .with_column("datdba", SqlScalarType::Oid.nullable(false))
7022        .with_column("encoding", SqlScalarType::Int32.nullable(false))
7023        .with_column("datistemplate", SqlScalarType::Bool.nullable(false))
7024        .with_column("datallowconn", SqlScalarType::Bool.nullable(false))
7025        .with_column("datcollate", SqlScalarType::String.nullable(false))
7026        .with_column("datctype", SqlScalarType::String.nullable(false))
7027        .with_column(
7028            "datacl",
7029            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7030        )
7031        .with_key(vec![0])
7032        .finish(),
7033    column_comments: BTreeMap::new(),
7034    sql: "SELECT
7035    d.oid as oid,
7036    d.name as datname,
7037    role_owner.oid as datdba,
7038    6 as encoding,
7039    -- Materialize doesn't support database cloning.
7040    FALSE AS datistemplate,
7041    TRUE AS datallowconn,
7042    'C' as datcollate,
7043    'C' as datctype,
7044    NULL::pg_catalog.text[] as datacl
7045FROM mz_catalog.mz_databases d
7046JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
7047    access: vec![PUBLIC_SELECT],
7048});
7049
7050pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
7051    BuiltinView {
7052        name: "pg_index",
7053        schema: PG_CATALOG_SCHEMA,
7054        oid: oid::VIEW_PG_INDEX_OID,
7055        desc: RelationDesc::builder()
7056            .with_column("indexrelid", SqlScalarType::Oid.nullable(false))
7057            .with_column("indrelid", SqlScalarType::Oid.nullable(false))
7058            .with_column("indnatts", SqlScalarType::Int16.nullable(false))
7059            .with_column("indisunique", SqlScalarType::Bool.nullable(false))
7060            .with_column("indisprimary", SqlScalarType::Bool.nullable(false))
7061            .with_column("indimmediate", SqlScalarType::Bool.nullable(false))
7062            .with_column("indisclustered", SqlScalarType::Bool.nullable(false))
7063            .with_column("indisvalid", SqlScalarType::Bool.nullable(false))
7064            .with_column("indisreplident", SqlScalarType::Bool.nullable(false))
7065            .with_column("indkey", SqlScalarType::Int2Vector.nullable(false))
7066            .with_column("indoption", SqlScalarType::Int2Vector.nullable(false))
7067            .with_column("indexprs", SqlScalarType::String.nullable(true))
7068            .with_column("indpred", SqlScalarType::String.nullable(true))
7069            .with_key(vec![0, 1])
7070            .finish(),
7071        column_comments: BTreeMap::new(),
7072        sql: "SELECT
7073    mz_indexes.oid AS indexrelid,
7074    mz_relations.oid AS indrelid,
7075    COALESCE(
7076        (
7077            SELECT count(*)::pg_catalog.int2
7078            FROM mz_catalog.mz_columns
7079            JOIN mz_catalog.mz_relations mri ON mz_columns.id = mri.id
7080            WHERE mri.oid = mz_catalog.mz_relations.oid
7081        ),
7082        0::pg_catalog.int2
7083    ) AS indnatts,
7084    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7085    false::pg_catalog.bool AS indisunique,
7086    false::pg_catalog.bool AS indisprimary,
7087    -- MZ doesn't support unique indexes so indimmediate is filled with false
7088    false::pg_catalog.bool AS indimmediate,
7089    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7090    false::pg_catalog.bool AS indisclustered,
7091    -- MZ never creates invalid indexes so indisvalid is filled with true
7092    true::pg_catalog.bool AS indisvalid,
7093    -- MZ doesn't support replication so indisreplident is filled with false
7094    false::pg_catalog.bool AS indisreplident,
7095    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7096    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,
7097    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7098    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7099    -- Index expressions are returned in MZ format
7100    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7101    WHEN NULL THEN NULL
7102    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7103    END AS indexprs,
7104    -- MZ doesn't support indexes with predicates
7105    NULL::pg_catalog.text AS indpred
7106FROM mz_catalog.mz_indexes
7107JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7108JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7109JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7110LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7111WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7112GROUP BY mz_indexes.oid, mz_relations.oid",
7113        access: vec![PUBLIC_SELECT],
7114    }
7115});
7116
7117pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7118    name: "pg_indexes",
7119    schema: PG_CATALOG_SCHEMA,
7120    oid: oid::VIEW_PG_INDEXES_OID,
7121    desc: RelationDesc::builder()
7122        .with_column("table_catalog", SqlScalarType::String.nullable(false))
7123        .with_column("schemaname", SqlScalarType::String.nullable(false))
7124        .with_column("tablename", SqlScalarType::String.nullable(false))
7125        .with_column("indexname", SqlScalarType::String.nullable(false))
7126        .with_column("tablespace", SqlScalarType::String.nullable(true))
7127        .with_column("indexdef", SqlScalarType::String.nullable(true))
7128        .finish(),
7129    column_comments: BTreeMap::new(),
7130    sql: "SELECT
7131    current_database() as table_catalog,
7132    s.name AS schemaname,
7133    r.name AS tablename,
7134    i.name AS indexname,
7135    NULL::text AS tablespace,
7136    -- TODO(jkosh44) Fill in with actual index definition.
7137    NULL::text AS indexdef
7138FROM mz_catalog.mz_indexes i
7139JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7140JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7141LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7142WHERE s.database_id IS NULL OR d.name = current_database()",
7143    access: vec![PUBLIC_SELECT],
7144});
7145
7146/// Peeled version of `PG_DESCRIPTION`:
7147/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7148///   in order to make this view indexable.
7149/// - This has 2 extra columns for the database names, so that downstream views can check them
7150///   against `current_database()`.
7151pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7152    BuiltinView {
7153        name: "pg_description_all_databases",
7154        schema: MZ_INTERNAL_SCHEMA,
7155        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7156        desc: RelationDesc::builder()
7157            .with_column("objoid", SqlScalarType::Oid.nullable(false))
7158            .with_column("classoid", SqlScalarType::Oid.nullable(true))
7159            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7160            .with_column("description", SqlScalarType::String.nullable(false))
7161            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
7162            .with_column("class_database_name", SqlScalarType::String.nullable(true))
7163            .finish(),
7164        column_comments: BTreeMap::new(),
7165        sql: "
7166(
7167    -- Gather all of the class oid's for objects that can have comments.
7168    WITH pg_classoids AS (
7169        SELECT oid, database_name as oid_database_name,
7170          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7171          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7172        FROM mz_internal.pg_class_all_databases
7173        UNION ALL
7174        SELECT oid, database_name as oid_database_name,
7175          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7176          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7177        FROM mz_internal.pg_type_all_databases
7178        UNION ALL
7179        SELECT oid, database_name as oid_database_name,
7180          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7181          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7182        FROM mz_internal.pg_namespace_all_databases
7183    ),
7184
7185    -- Gather all of the MZ ids for objects that can have comments.
7186    mz_objects AS (
7187        SELECT id, oid, type FROM mz_catalog.mz_objects
7188        UNION ALL
7189        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7190    )
7191    SELECT
7192        pg_classoids.oid AS objoid,
7193        pg_classoids.classoid as classoid,
7194        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7195        cmt.comment AS description,
7196        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7197        oid_database_name,
7198        class_database_name
7199    FROM
7200        pg_classoids
7201    JOIN
7202        mz_objects ON pg_classoids.oid = mz_objects.oid
7203    JOIN
7204        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7205)",
7206        access: vec![PUBLIC_SELECT],
7207    }
7208});
7209
7210pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7211    name: "pg_description_all_databases_ind",
7212    schema: MZ_INTERNAL_SCHEMA,
7213    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7214    sql: "IN CLUSTER mz_catalog_server
7215ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7216    is_retained_metrics_object: false,
7217};
7218
7219/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7220/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7221/// which is required for this view.
7222pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7223    name: "pg_description",
7224    schema: PG_CATALOG_SCHEMA,
7225    oid: oid::VIEW_PG_DESCRIPTION_OID,
7226    desc: RelationDesc::builder()
7227        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7228        .with_column("classoid", SqlScalarType::Oid.nullable(true))
7229        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7230        .with_column("description", SqlScalarType::String.nullable(false))
7231        .finish(),
7232    column_comments: BTreeMap::new(),
7233    sql: "
7234SELECT
7235    objoid,
7236    classoid,
7237    objsubid,
7238    description
7239FROM
7240    mz_internal.pg_description_all_databases
7241WHERE
7242    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7243    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7244    access: vec![PUBLIC_SELECT],
7245});
7246
7247/// Peeled version of `PG_TYPE`:
7248/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7249///   in order to make this view indexable.
7250/// - This has the database name as an extra column, so that downstream views can check it against
7251///  `current_database()`.
7252pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7253    BuiltinView {
7254        name: "pg_type_all_databases",
7255        schema: MZ_INTERNAL_SCHEMA,
7256        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7257        desc: RelationDesc::builder()
7258            .with_column("oid", SqlScalarType::Oid.nullable(false))
7259            .with_column("typname", SqlScalarType::String.nullable(false))
7260            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7261            .with_column("typowner", SqlScalarType::Oid.nullable(false))
7262            .with_column("typlen", SqlScalarType::Int16.nullable(true))
7263            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7264            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7265            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7266            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7267            .with_column("typelem", SqlScalarType::Oid.nullable(false))
7268            .with_column("typarray", SqlScalarType::Oid.nullable(false))
7269            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7270            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7271            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7272            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7273            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7274            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7275            .with_column("typdefault", SqlScalarType::String.nullable(true))
7276            .with_column("database_name", SqlScalarType::String.nullable(true))
7277            .finish(),
7278        column_comments: BTreeMap::new(),
7279        sql: "
7280SELECT
7281    mz_types.oid,
7282    mz_types.name AS typname,
7283    mz_schemas.oid AS typnamespace,
7284    role_owner.oid AS typowner,
7285    NULL::pg_catalog.int2 AS typlen,
7286    -- 'a' is used internally to denote an array type, but in postgres they show up
7287    -- as 'b'.
7288    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7289    (CASE category
7290        WHEN 'array' THEN 'A'
7291        WHEN 'bit-string' THEN 'V'
7292        WHEN 'boolean' THEN 'B'
7293        WHEN 'composite' THEN 'C'
7294        WHEN 'date-time' THEN 'D'
7295        WHEN 'enum' THEN 'E'
7296        WHEN 'geometric' THEN 'G'
7297        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7298        WHEN 'network-address' THEN 'I'
7299        WHEN 'numeric' THEN 'N'
7300        WHEN 'pseudo' THEN 'P'
7301        WHEN 'string' THEN 'S'
7302        WHEN 'timespan' THEN 'T'
7303        WHEN 'user-defined' THEN 'U'
7304        WHEN 'unknown' THEN 'X'
7305    END)::pg_catalog.char AS typcategory,
7306    -- In pg only the 'box' type is not ','.
7307    ','::pg_catalog.char AS typdelim,
7308    0::pg_catalog.oid AS typrelid,
7309    coalesce(
7310        (
7311            SELECT t.oid
7312            FROM mz_catalog.mz_array_types a
7313            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7314            WHERE a.id = mz_types.id
7315        ),
7316        (
7317            SELECT t.oid
7318            FROM mz_catalog.mz_list_types l
7319            JOIN mz_catalog.mz_types t ON l.element_id = t.id
7320            WHERE l.id = mz_types.id
7321        ),
7322        0
7323    ) AS typelem,
7324    coalesce(
7325        (
7326            SELECT
7327                t.oid
7328            FROM
7329                mz_catalog.mz_array_types AS a
7330                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7331            WHERE
7332                a.element_id = mz_types.id
7333        ),
7334        0
7335    )
7336        AS typarray,
7337    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7338    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7339    false::pg_catalog.bool AS typnotnull,
7340    0::pg_catalog.oid AS typbasetype,
7341    -1::pg_catalog.int4 AS typtypmod,
7342    -- MZ doesn't support COLLATE so typcollation is filled with 0
7343    0::pg_catalog.oid AS typcollation,
7344    NULL::pg_catalog.text AS typdefault,
7345    d.name as database_name
7346FROM
7347    mz_catalog.mz_types
7348    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7349    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7350    JOIN (
7351            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7352            -- converted to the correct value above.
7353            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7354            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7355            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7356            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7357            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7358        )
7359            AS t ON mz_types.id = t.id
7360    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7361    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7362        access: vec![PUBLIC_SELECT],
7363    }
7364});
7365
7366pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7367    name: "pg_type_all_databases_ind",
7368    schema: MZ_INTERNAL_SCHEMA,
7369    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7370    sql: "IN CLUSTER mz_catalog_server
7371ON mz_internal.pg_type_all_databases (oid)",
7372    is_retained_metrics_object: false,
7373};
7374
7375pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7376    name: "pg_type",
7377    schema: PG_CATALOG_SCHEMA,
7378    oid: oid::VIEW_PG_TYPE_OID,
7379    desc: RelationDesc::builder()
7380        .with_column("oid", SqlScalarType::Oid.nullable(false))
7381        .with_column("typname", SqlScalarType::String.nullable(false))
7382        .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7383        .with_column("typowner", SqlScalarType::Oid.nullable(false))
7384        .with_column("typlen", SqlScalarType::Int16.nullable(true))
7385        .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7386        .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7387        .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7388        .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7389        .with_column("typelem", SqlScalarType::Oid.nullable(false))
7390        .with_column("typarray", SqlScalarType::Oid.nullable(false))
7391        .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7392        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7393        .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7394        .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7395        .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7396        .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7397        .with_column("typdefault", SqlScalarType::String.nullable(true))
7398        .finish(),
7399    column_comments: BTreeMap::new(),
7400    sql: "SELECT
7401    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7402    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7403FROM mz_internal.pg_type_all_databases
7404WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7405    access: vec![PUBLIC_SELECT],
7406});
7407
7408/// Peeled version of `PG_ATTRIBUTE`:
7409/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7410///   in order to make this view indexable.
7411/// - This has 2 extra columns for the database names, so that downstream views can check them
7412///   against `current_database()`.
7413pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7414    BuiltinView {
7415        name: "pg_attribute_all_databases",
7416        schema: MZ_INTERNAL_SCHEMA,
7417        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7418        desc: RelationDesc::builder()
7419            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7420            .with_column("attname", SqlScalarType::String.nullable(false))
7421            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7422            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7423            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7424            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7425            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7426            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7427            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7428            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7429            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7430            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7431            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7432            .with_column("database_name", SqlScalarType::String.nullable(true))
7433            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
7434            .finish(),
7435        column_comments: BTreeMap::new(),
7436        sql: "
7437SELECT
7438    class_objects.oid as attrelid,
7439    mz_columns.name as attname,
7440    mz_columns.type_oid AS atttypid,
7441    pg_type_all_databases.typlen AS attlen,
7442    position::int8::int2 as attnum,
7443    mz_columns.type_mod as atttypmod,
7444    -- dummy value, just to make go-jet's workaround work for now. Discussion:
7445    -- https://github.com/MaterializeInc/materialize/pull/34649#issuecomment-3714291409
7446    0::int2 as attndims,
7447    NOT nullable as attnotnull,
7448    mz_columns.default IS NOT NULL as atthasdef,
7449    ''::pg_catalog.\"char\" as attidentity,
7450    -- MZ doesn't support generated columns so attgenerated is filled with ''
7451    ''::pg_catalog.\"char\" as attgenerated,
7452    FALSE as attisdropped,
7453    -- MZ doesn't support COLLATE so attcollation is filled with 0
7454    0::pg_catalog.oid as attcollation,
7455    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7456    d.name as database_name,
7457    pg_type_all_databases.database_name as pg_type_database_name
7458FROM (
7459    -- pg_attribute catalogs columns on relations and indexes
7460    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7461    UNION ALL
7462        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7463        FROM mz_catalog.mz_indexes
7464        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7465) AS class_objects
7466JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7467JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7468JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7469LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7470        // Since this depends on pg_type, its id must be higher due to initialization
7471        // ordering.
7472        access: vec![PUBLIC_SELECT],
7473    }
7474});
7475
7476pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7477    name: "pg_attribute_all_databases_ind",
7478    schema: MZ_INTERNAL_SCHEMA,
7479    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7480    sql: "IN CLUSTER mz_catalog_server
7481ON mz_internal.pg_attribute_all_databases (
7482    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7483    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7484)",
7485    is_retained_metrics_object: false,
7486};
7487
7488/// <https://www.postgresql.org/docs/current/catalog-pg-attribute.html>
7489pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7490    BuiltinView {
7491        name: "pg_attribute",
7492        schema: PG_CATALOG_SCHEMA,
7493        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7494        desc: RelationDesc::builder()
7495            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7496            .with_column("attname", SqlScalarType::String.nullable(false))
7497            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7498            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7499            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7500            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7501            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7502            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7503            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7504            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7505            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7506            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7507            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7508            .finish(),
7509        column_comments: BTreeMap::new(),
7510        sql: "
7511SELECT
7512    attrelid, attname, atttypid, attlen, attnum, atttypmod, attndims, attnotnull, atthasdef,
7513    attidentity, attgenerated, attisdropped, attcollation
7514FROM mz_internal.pg_attribute_all_databases
7515WHERE
7516  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7517  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7518        // Since this depends on pg_type, its id must be higher due to initialization
7519        // ordering.
7520        access: vec![PUBLIC_SELECT],
7521    }
7522});
7523
7524pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7525    name: "pg_proc",
7526    schema: PG_CATALOG_SCHEMA,
7527    oid: oid::VIEW_PG_PROC_OID,
7528    desc: RelationDesc::builder()
7529        .with_column("oid", SqlScalarType::Oid.nullable(false))
7530        .with_column("proname", SqlScalarType::String.nullable(false))
7531        .with_column("pronamespace", SqlScalarType::Oid.nullable(false))
7532        .with_column("proowner", SqlScalarType::Oid.nullable(false))
7533        .with_column("proargdefaults", SqlScalarType::String.nullable(true))
7534        .with_column("prorettype", SqlScalarType::Oid.nullable(false))
7535        .finish(),
7536    column_comments: BTreeMap::new(),
7537    sql: "SELECT
7538    mz_functions.oid,
7539    mz_functions.name AS proname,
7540    mz_schemas.oid AS pronamespace,
7541    role_owner.oid AS proowner,
7542    NULL::pg_catalog.text AS proargdefaults,
7543    ret_type.oid AS prorettype
7544FROM mz_catalog.mz_functions
7545JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7546LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7547JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7548JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7549WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7550    access: vec![PUBLIC_SELECT],
7551});
7552
7553pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7554    name: "pg_operator",
7555    schema: PG_CATALOG_SCHEMA,
7556    oid: oid::VIEW_PG_OPERATOR_OID,
7557    desc: RelationDesc::builder()
7558        .with_column("oid", SqlScalarType::Oid.nullable(false))
7559        .with_column("oprname", SqlScalarType::String.nullable(false))
7560        .with_column("oprresult", SqlScalarType::Oid.nullable(false))
7561        .with_column("oprleft", SqlScalarType::Oid.nullable(false))
7562        .with_column("oprright", SqlScalarType::Oid.nullable(false))
7563        .with_key(vec![0, 1, 2, 3, 4])
7564        .finish(),
7565    column_comments: BTreeMap::new(),
7566    sql: "SELECT
7567    mz_operators.oid,
7568    mz_operators.name AS oprname,
7569    ret_type.oid AS oprresult,
7570    left_type.oid as oprleft,
7571    right_type.oid as oprright
7572FROM mz_catalog.mz_operators
7573JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7574JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7575JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7576WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7577UNION SELECT
7578    mz_operators.oid,
7579    mz_operators.name AS oprname,
7580    ret_type.oid AS oprresult,
7581    0 as oprleft,
7582    right_type.oid as oprright
7583FROM mz_catalog.mz_operators
7584JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7585JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7586WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7587    access: vec![PUBLIC_SELECT],
7588});
7589
7590pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7591    name: "pg_range",
7592    schema: PG_CATALOG_SCHEMA,
7593    oid: oid::VIEW_PG_RANGE_OID,
7594    desc: RelationDesc::builder()
7595        .with_column("rngtypid", SqlScalarType::Oid.nullable(false))
7596        .with_column("rngsubtype", SqlScalarType::Oid.nullable(false))
7597        .with_key(vec![])
7598        .finish(),
7599    column_comments: BTreeMap::new(),
7600    sql: "SELECT
7601    NULL::pg_catalog.oid AS rngtypid,
7602    NULL::pg_catalog.oid AS rngsubtype
7603WHERE false",
7604    access: vec![PUBLIC_SELECT],
7605});
7606
7607pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7608    name: "pg_enum",
7609    schema: PG_CATALOG_SCHEMA,
7610    oid: oid::VIEW_PG_ENUM_OID,
7611    desc: RelationDesc::builder()
7612        .with_column("oid", SqlScalarType::Oid.nullable(false))
7613        .with_column("enumtypid", SqlScalarType::Oid.nullable(false))
7614        .with_column("enumsortorder", SqlScalarType::Float32.nullable(false))
7615        .with_column("enumlabel", SqlScalarType::String.nullable(false))
7616        .with_key(vec![])
7617        .finish(),
7618    column_comments: BTreeMap::new(),
7619    sql: "SELECT
7620    NULL::pg_catalog.oid AS oid,
7621    NULL::pg_catalog.oid AS enumtypid,
7622    NULL::pg_catalog.float4 AS enumsortorder,
7623    NULL::pg_catalog.text AS enumlabel
7624WHERE false",
7625    access: vec![PUBLIC_SELECT],
7626});
7627
7628/// Peeled version of `PG_ATTRDEF`:
7629/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7630///   in order to make this view indexable.
7631pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7632    name: "pg_attrdef_all_databases",
7633    schema: MZ_INTERNAL_SCHEMA,
7634    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
7635    desc: RelationDesc::builder()
7636        .with_column("oid", SqlScalarType::Oid.nullable(true))
7637        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7638        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7639        .with_column("adbin", SqlScalarType::String.nullable(false))
7640        .with_column("adsrc", SqlScalarType::String.nullable(false))
7641        .finish(),
7642    column_comments: BTreeMap::new(),
7643    sql: "
7644SELECT
7645    NULL::pg_catalog.oid AS oid,
7646    mz_objects.oid AS adrelid,
7647    mz_columns.position::int8 AS adnum,
7648    mz_columns.default AS adbin,
7649    mz_columns.default AS adsrc
7650FROM mz_catalog.mz_columns
7651    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
7652WHERE default IS NOT NULL",
7653    access: vec![PUBLIC_SELECT],
7654});
7655
7656pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7657    name: "pg_attrdef_all_databases_ind",
7658    schema: MZ_INTERNAL_SCHEMA,
7659    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
7660    sql: "IN CLUSTER mz_catalog_server
7661ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
7662    is_retained_metrics_object: false,
7663};
7664
7665pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7666    name: "pg_attrdef",
7667    schema: PG_CATALOG_SCHEMA,
7668    oid: oid::VIEW_PG_ATTRDEF_OID,
7669    desc: RelationDesc::builder()
7670        .with_column("oid", SqlScalarType::Oid.nullable(true))
7671        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7672        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7673        .with_column("adbin", SqlScalarType::String.nullable(false))
7674        .with_column("adsrc", SqlScalarType::String.nullable(false))
7675        .finish(),
7676    column_comments: BTreeMap::new(),
7677    sql: "
7678SELECT
7679    pg_attrdef_all_databases.oid as oid,
7680    adrelid,
7681    adnum,
7682    adbin,
7683    adsrc
7684FROM mz_internal.pg_attrdef_all_databases
7685    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
7686    access: vec![PUBLIC_SELECT],
7687});
7688
7689pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7690    name: "pg_settings",
7691    schema: PG_CATALOG_SCHEMA,
7692    oid: oid::VIEW_PG_SETTINGS_OID,
7693    desc: RelationDesc::builder()
7694        .with_column("name", SqlScalarType::String.nullable(false))
7695        .with_column("setting", SqlScalarType::String.nullable(false))
7696        .with_key(vec![])
7697        .finish(),
7698    column_comments: BTreeMap::new(),
7699    sql: "SELECT
7700    name, setting
7701FROM (VALUES
7702    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
7703) AS _ (name, setting)",
7704    access: vec![PUBLIC_SELECT],
7705});
7706
7707pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7708    name: "pg_auth_members",
7709    schema: PG_CATALOG_SCHEMA,
7710    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
7711    desc: RelationDesc::builder()
7712        .with_column("roleid", SqlScalarType::Oid.nullable(false))
7713        .with_column("member", SqlScalarType::Oid.nullable(false))
7714        .with_column("grantor", SqlScalarType::Oid.nullable(false))
7715        .with_column("admin_option", SqlScalarType::Bool.nullable(false))
7716        .finish(),
7717    column_comments: BTreeMap::new(),
7718    sql: "SELECT
7719    role.oid AS roleid,
7720    member.oid AS member,
7721    grantor.oid AS grantor,
7722    -- Materialize hasn't implemented admin_option.
7723    false as admin_option
7724FROM mz_catalog.mz_role_members membership
7725JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
7726JOIN mz_catalog.mz_roles member ON membership.member = member.id
7727JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
7728    access: vec![PUBLIC_SELECT],
7729});
7730
7731pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7732    name: "pg_event_trigger",
7733    schema: PG_CATALOG_SCHEMA,
7734    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
7735    desc: RelationDesc::builder()
7736        .with_column("oid", SqlScalarType::Oid.nullable(false))
7737        .with_column("evtname", SqlScalarType::String.nullable(false))
7738        .with_column("evtevent", SqlScalarType::String.nullable(false))
7739        .with_column("evtowner", SqlScalarType::Oid.nullable(false))
7740        .with_column("evtfoid", SqlScalarType::Oid.nullable(false))
7741        .with_column("evtenabled", SqlScalarType::PgLegacyChar.nullable(false))
7742        .with_column(
7743            "evttags",
7744            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7745        )
7746        .with_key(vec![])
7747        .finish(),
7748    column_comments: BTreeMap::new(),
7749    sql: "SELECT
7750        NULL::pg_catalog.oid AS oid,
7751        NULL::pg_catalog.text AS evtname,
7752        NULL::pg_catalog.text AS evtevent,
7753        NULL::pg_catalog.oid AS evtowner,
7754        NULL::pg_catalog.oid AS evtfoid,
7755        NULL::pg_catalog.char AS evtenabled,
7756        NULL::pg_catalog.text[] AS evttags
7757    WHERE false",
7758    access: vec![PUBLIC_SELECT],
7759});
7760
7761pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7762    name: "pg_language",
7763    schema: PG_CATALOG_SCHEMA,
7764    oid: oid::VIEW_PG_LANGUAGE_OID,
7765    desc: RelationDesc::builder()
7766        .with_column("oid", SqlScalarType::Oid.nullable(false))
7767        .with_column("lanname", SqlScalarType::String.nullable(false))
7768        .with_column("lanowner", SqlScalarType::Oid.nullable(false))
7769        .with_column("lanispl", SqlScalarType::Bool.nullable(false))
7770        .with_column("lanpltrusted", SqlScalarType::Bool.nullable(false))
7771        .with_column("lanplcallfoid", SqlScalarType::Oid.nullable(false))
7772        .with_column("laninline", SqlScalarType::Oid.nullable(false))
7773        .with_column("lanvalidator", SqlScalarType::Oid.nullable(false))
7774        .with_column(
7775            "lanacl",
7776            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7777        )
7778        .with_key(vec![])
7779        .finish(),
7780    column_comments: BTreeMap::new(),
7781    sql: "SELECT
7782        NULL::pg_catalog.oid  AS oid,
7783        NULL::pg_catalog.text AS lanname,
7784        NULL::pg_catalog.oid  AS lanowner,
7785        NULL::pg_catalog.bool AS lanispl,
7786        NULL::pg_catalog.bool AS lanpltrusted,
7787        NULL::pg_catalog.oid  AS lanplcallfoid,
7788        NULL::pg_catalog.oid  AS laninline,
7789        NULL::pg_catalog.oid  AS lanvalidator,
7790        NULL::pg_catalog.text[] AS lanacl
7791    WHERE false",
7792    access: vec![PUBLIC_SELECT],
7793});
7794
7795pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7796    name: "pg_shdescription",
7797    schema: PG_CATALOG_SCHEMA,
7798    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
7799    desc: RelationDesc::builder()
7800        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7801        .with_column("classoid", SqlScalarType::Oid.nullable(false))
7802        .with_column("description", SqlScalarType::String.nullable(false))
7803        .with_key(vec![])
7804        .finish(),
7805    column_comments: BTreeMap::new(),
7806    sql: "SELECT
7807        NULL::pg_catalog.oid AS objoid,
7808        NULL::pg_catalog.oid AS classoid,
7809        NULL::pg_catalog.text AS description
7810    WHERE false",
7811    access: vec![PUBLIC_SELECT],
7812});
7813
7814pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
7815    BuiltinView {
7816        name: "pg_timezone_abbrevs",
7817        schema: PG_CATALOG_SCHEMA,
7818        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
7819        desc: RelationDesc::builder()
7820            .with_column("abbrev", SqlScalarType::String.nullable(false))
7821            .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7822            .with_column("is_dst", SqlScalarType::Bool.nullable(true))
7823            .with_key(vec![0])
7824            .finish(),
7825        column_comments: BTreeMap::new(),
7826        sql: "SELECT
7827    abbreviation AS abbrev,
7828    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
7829        AS utc_offset,
7830    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
7831        AS is_dst
7832FROM mz_catalog.mz_timezone_abbreviations",
7833        access: vec![PUBLIC_SELECT],
7834    }
7835});
7836
7837pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7838    name: "pg_timezone_names",
7839    schema: PG_CATALOG_SCHEMA,
7840    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
7841    desc: RelationDesc::builder()
7842        .with_column("name", SqlScalarType::String.nullable(false))
7843        .with_column("abbrev", SqlScalarType::String.nullable(true))
7844        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7845        .with_column("is_dst", SqlScalarType::Bool.nullable(true))
7846        .with_key(vec![0])
7847        .finish(),
7848    column_comments: BTreeMap::new(),
7849    sql: "SELECT
7850    name,
7851    timezone_offset(name, now()).abbrev AS abbrev,
7852    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
7853        AS utc_offset,
7854    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
7855        AS is_dst
7856FROM mz_catalog.mz_timezone_names",
7857    access: vec![PUBLIC_SELECT],
7858});
7859
7860pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7861    name: "mz_timezone_abbreviations",
7862    schema: MZ_CATALOG_SCHEMA,
7863    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
7864    desc: RelationDesc::builder()
7865        .with_column("abbreviation", SqlScalarType::String.nullable(false))
7866        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7867        .with_column("dst", SqlScalarType::Bool.nullable(true))
7868        .with_column("timezone_name", SqlScalarType::String.nullable(true))
7869        .with_key(vec![0])
7870        .finish(),
7871    column_comments: BTreeMap::from_iter([
7872        ("abbreviation", "The timezone abbreviation."),
7873        (
7874            "utc_offset",
7875            "The UTC offset of the timezone or `NULL` if fixed.",
7876        ),
7877        (
7878            "dst",
7879            "Whether the timezone is in daylight savings or `NULL` if fixed.",
7880        ),
7881        (
7882            "timezone_name",
7883            "The full name of the non-fixed timezone or `NULL` if not fixed.",
7884        ),
7885    ]),
7886    sql: format!(
7887        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
7888        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
7889    )
7890    .leak(),
7891    access: vec![PUBLIC_SELECT],
7892});
7893
7894pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7895    name: "mz_timezone_names",
7896    schema: MZ_CATALOG_SCHEMA,
7897    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
7898    desc: RelationDesc::builder()
7899        .with_column("name", SqlScalarType::String.nullable(false))
7900        .with_key(vec![0])
7901        .finish(),
7902    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
7903    sql: format!(
7904        "SELECT * FROM ({}) _ (name)",
7905        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
7906    )
7907    .leak(),
7908    access: vec![PUBLIC_SELECT],
7909});
7910
7911pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7912    LazyLock::new(|| BuiltinView {
7913        name: "mz_peek_durations_histogram_per_worker",
7914        schema: MZ_INTROSPECTION_SCHEMA,
7915        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
7916        desc: RelationDesc::builder()
7917            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7918            .with_column("type", SqlScalarType::String.nullable(false))
7919            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7920            .with_column("count", SqlScalarType::Int64.nullable(false))
7921            .with_key(vec![0, 1, 2])
7922            .finish(),
7923        column_comments: BTreeMap::new(),
7924        sql: "SELECT
7925    worker_id, type, duration_ns, pg_catalog.count(*) AS count
7926FROM
7927    mz_introspection.mz_peek_durations_histogram_raw
7928GROUP BY
7929    worker_id, type, duration_ns",
7930        access: vec![PUBLIC_SELECT],
7931    });
7932
7933pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7934    name: "mz_peek_durations_histogram",
7935    schema: MZ_INTROSPECTION_SCHEMA,
7936    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
7937    desc: RelationDesc::builder()
7938        .with_column("type", SqlScalarType::String.nullable(false))
7939        .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7940        .with_column(
7941            "count",
7942            SqlScalarType::Numeric {
7943                max_scale: Some(NumericMaxScale::ZERO),
7944            }
7945            .nullable(false),
7946        )
7947        .with_key(vec![0, 1])
7948        .finish(),
7949    column_comments: BTreeMap::from_iter([
7950        ("type", "The peek variant: `index` or `persist`."),
7951        (
7952            "duration_ns",
7953            "The upper bound of the bucket in nanoseconds.",
7954        ),
7955        (
7956            "count",
7957            "The (noncumulative) count of peeks in this bucket.",
7958        ),
7959    ]),
7960    sql: "
7961SELECT
7962    type, duration_ns,
7963    pg_catalog.sum(count) AS count
7964FROM mz_introspection.mz_peek_durations_histogram_per_worker
7965GROUP BY type, duration_ns",
7966    access: vec![PUBLIC_SELECT],
7967});
7968
7969pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
7970    LazyLock::new(|| BuiltinView {
7971        name: "mz_scheduling_elapsed_per_worker",
7972        schema: MZ_INTROSPECTION_SCHEMA,
7973        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
7974        desc: RelationDesc::builder()
7975            .with_column("id", SqlScalarType::UInt64.nullable(false))
7976            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7977            .with_column("elapsed_ns", SqlScalarType::Int64.nullable(false))
7978            .with_key(vec![0, 1])
7979            .finish(),
7980        column_comments: BTreeMap::new(),
7981        sql: "SELECT
7982    id, worker_id, pg_catalog.count(*) AS elapsed_ns
7983FROM
7984    mz_introspection.mz_scheduling_elapsed_raw
7985GROUP BY
7986    id, worker_id",
7987        access: vec![PUBLIC_SELECT],
7988    });
7989
7990pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7991    name: "mz_scheduling_elapsed",
7992    schema: MZ_INTROSPECTION_SCHEMA,
7993    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
7994    desc: RelationDesc::builder()
7995        .with_column("id", SqlScalarType::UInt64.nullable(false))
7996        .with_column(
7997            "elapsed_ns",
7998            SqlScalarType::Numeric {
7999                max_scale: Some(NumericMaxScale::ZERO),
8000            }
8001            .nullable(false),
8002        )
8003        .with_key(vec![0])
8004        .finish(),
8005    column_comments: BTreeMap::from_iter([
8006        (
8007            "id",
8008            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8009        ),
8010        (
8011            "elapsed_ns",
8012            "The total elapsed time spent in the operator in nanoseconds.",
8013        ),
8014    ]),
8015    sql: "
8016SELECT
8017    id,
8018    pg_catalog.sum(elapsed_ns) AS elapsed_ns
8019FROM mz_introspection.mz_scheduling_elapsed_per_worker
8020GROUP BY id",
8021    access: vec![PUBLIC_SELECT],
8022});
8023
8024pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8025    LazyLock::new(|| BuiltinView {
8026        name: "mz_compute_operator_durations_histogram_per_worker",
8027        schema: MZ_INTROSPECTION_SCHEMA,
8028        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8029        desc: RelationDesc::builder()
8030            .with_column("id", SqlScalarType::UInt64.nullable(false))
8031            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8032            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8033            .with_column("count", SqlScalarType::Int64.nullable(false))
8034            .with_key(vec![0, 1, 2])
8035            .finish(),
8036        column_comments: BTreeMap::new(),
8037        sql: "SELECT
8038    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8039FROM
8040    mz_introspection.mz_compute_operator_durations_histogram_raw
8041GROUP BY
8042    id, worker_id, duration_ns",
8043        access: vec![PUBLIC_SELECT],
8044    });
8045
8046pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8047    LazyLock::new(|| BuiltinView {
8048        name: "mz_compute_operator_durations_histogram",
8049        schema: MZ_INTROSPECTION_SCHEMA,
8050        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8051        desc: RelationDesc::builder()
8052            .with_column("id", SqlScalarType::UInt64.nullable(false))
8053            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8054            .with_column(
8055                "count",
8056                SqlScalarType::Numeric {
8057                    max_scale: Some(NumericMaxScale::ZERO),
8058                }
8059                .nullable(false),
8060            )
8061            .with_key(vec![0, 1])
8062            .finish(),
8063        column_comments: BTreeMap::from_iter([
8064            (
8065                "id",
8066                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8067            ),
8068            (
8069                "duration_ns",
8070                "The upper bound of the duration bucket in nanoseconds.",
8071            ),
8072            (
8073                "count",
8074                "The (noncumulative) count of invocations in the bucket.",
8075            ),
8076        ]),
8077        sql: "
8078SELECT
8079    id,
8080    duration_ns,
8081    pg_catalog.sum(count) AS count
8082FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8083GROUP BY id, duration_ns",
8084        access: vec![PUBLIC_SELECT],
8085    });
8086
8087pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8088    LazyLock::new(|| BuiltinView {
8089        name: "mz_scheduling_parks_histogram_per_worker",
8090        schema: MZ_INTROSPECTION_SCHEMA,
8091        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8092        desc: RelationDesc::builder()
8093            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8094            .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8095            .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8096            .with_column("count", SqlScalarType::Int64.nullable(false))
8097            .with_key(vec![0, 1, 2])
8098            .finish(),
8099        column_comments: BTreeMap::new(),
8100        sql: "SELECT
8101    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8102FROM
8103    mz_introspection.mz_scheduling_parks_histogram_raw
8104GROUP BY
8105    worker_id, slept_for_ns, requested_ns",
8106        access: vec![PUBLIC_SELECT],
8107    });
8108
8109pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8110    name: "mz_scheduling_parks_histogram",
8111    schema: MZ_INTROSPECTION_SCHEMA,
8112    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8113    desc: RelationDesc::builder()
8114        .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8115        .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8116        .with_column(
8117            "count",
8118            SqlScalarType::Numeric {
8119                max_scale: Some(NumericMaxScale::ZERO),
8120            }
8121            .nullable(false),
8122        )
8123        .with_key(vec![0, 1])
8124        .finish(),
8125    column_comments: BTreeMap::from_iter([
8126        (
8127            "slept_for_ns",
8128            "The actual length of the park event in nanoseconds.",
8129        ),
8130        (
8131            "requested_ns",
8132            "The requested length of the park event in nanoseconds.",
8133        ),
8134        (
8135            "count",
8136            "The (noncumulative) count of park events in this bucket.",
8137        ),
8138    ]),
8139    sql: "
8140SELECT
8141    slept_for_ns,
8142    requested_ns,
8143    pg_catalog.sum(count) AS count
8144FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8145GROUP BY slept_for_ns, requested_ns",
8146    access: vec![PUBLIC_SELECT],
8147});
8148
8149pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8150    LazyLock::new(|| BuiltinView {
8151        name: "mz_compute_error_counts_per_worker",
8152        schema: MZ_INTROSPECTION_SCHEMA,
8153        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8154        desc: RelationDesc::builder()
8155            .with_column("export_id", SqlScalarType::String.nullable(false))
8156            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8157            .with_column("count", SqlScalarType::Int64.nullable(false))
8158            .with_key(vec![0, 1, 2])
8159            .finish(),
8160        column_comments: BTreeMap::new(),
8161        sql: "
8162WITH MUTUALLY RECURSIVE
8163    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8164    -- For these we don't log error counts separately, so we need to forward the error counts from
8165    -- their dependencies instead.
8166    index_reuses(reuse_id text, index_id text) AS (
8167        SELECT d.object_id, d.dependency_id
8168        FROM mz_internal.mz_compute_dependencies d
8169        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8170        WHERE NOT EXISTS (
8171            SELECT 1 FROM mz_introspection.mz_dataflows
8172            WHERE id = e.dataflow_id
8173        )
8174    ),
8175    -- Error counts that were directly logged on compute exports.
8176    direct_errors(export_id text, worker_id uint8, count int8) AS (
8177        SELECT export_id, worker_id, count
8178        FROM mz_introspection.mz_compute_error_counts_raw
8179    ),
8180    -- Error counts propagated to index reused.
8181    all_errors(export_id text, worker_id uint8, count int8) AS (
8182        SELECT * FROM direct_errors
8183        UNION
8184        SELECT r.reuse_id, e.worker_id, e.count
8185        FROM all_errors e
8186        JOIN index_reuses r ON (r.index_id = e.export_id)
8187    )
8188SELECT * FROM all_errors",
8189        access: vec![PUBLIC_SELECT],
8190    });
8191
8192pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8193    name: "mz_compute_error_counts",
8194    schema: MZ_INTROSPECTION_SCHEMA,
8195    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8196    desc: RelationDesc::builder()
8197        .with_column("export_id", SqlScalarType::String.nullable(false))
8198        .with_column(
8199            "count",
8200            SqlScalarType::Numeric {
8201                max_scale: Some(NumericMaxScale::ZERO),
8202            }
8203            .nullable(false),
8204        )
8205        .with_key(vec![0])
8206        .finish(),
8207    column_comments: BTreeMap::from_iter([
8208        (
8209            "export_id",
8210            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8211        ),
8212        (
8213            "count",
8214            "The count of errors present in this dataflow export.",
8215        ),
8216    ]),
8217    sql: "
8218SELECT
8219    export_id,
8220    pg_catalog.sum(count) AS count
8221FROM mz_introspection.mz_compute_error_counts_per_worker
8222GROUP BY export_id
8223HAVING pg_catalog.sum(count) != 0",
8224    access: vec![PUBLIC_SELECT],
8225});
8226
8227pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8228    LazyLock::new(|| BuiltinSource {
8229        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8230        // naming conflict because the resolver stumbles over the source with the same name in
8231        // `mz_introspection` due to the automatic schema translation.
8232        name: "mz_compute_error_counts_raw_unified",
8233        schema: MZ_INTERNAL_SCHEMA,
8234        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8235        desc: RelationDesc::builder()
8236            .with_column("replica_id", SqlScalarType::String.nullable(false))
8237            .with_column("object_id", SqlScalarType::String.nullable(false))
8238            .with_column(
8239                "count",
8240                SqlScalarType::Numeric { max_scale: None }.nullable(false),
8241            )
8242            .finish(),
8243        data_source: IntrospectionType::ComputeErrorCounts,
8244        column_comments: BTreeMap::new(),
8245        is_retained_metrics_object: false,
8246        access: vec![PUBLIC_SELECT],
8247    });
8248
8249pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8250    name: "mz_compute_hydration_times",
8251    schema: MZ_INTERNAL_SCHEMA,
8252    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8253    desc: RelationDesc::builder()
8254        .with_column("replica_id", SqlScalarType::String.nullable(false))
8255        .with_column("object_id", SqlScalarType::String.nullable(false))
8256        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
8257        .finish(),
8258    data_source: IntrospectionType::ComputeHydrationTimes,
8259    column_comments: BTreeMap::new(),
8260    is_retained_metrics_object: true,
8261    access: vec![PUBLIC_SELECT],
8262});
8263
8264pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8265    LazyLock::new(|| BuiltinIndex {
8266        name: "mz_compute_hydration_times_ind",
8267        schema: MZ_INTERNAL_SCHEMA,
8268        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8269        sql: "IN CLUSTER mz_catalog_server
8270    ON mz_internal.mz_compute_hydration_times (replica_id)",
8271        is_retained_metrics_object: true,
8272    });
8273
8274pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8275    name: "mz_compute_hydration_statuses",
8276    schema: MZ_INTERNAL_SCHEMA,
8277    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8278    desc: RelationDesc::builder()
8279        .with_column("object_id", SqlScalarType::String.nullable(false))
8280        .with_column("replica_id", SqlScalarType::String.nullable(false))
8281        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8282        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
8283        .finish(),
8284    column_comments: BTreeMap::from_iter([
8285        (
8286            "object_id",
8287            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8288        ),
8289        ("replica_id", "The ID of a cluster replica."),
8290        (
8291            "hydrated",
8292            "Whether the compute object is hydrated on the replica.",
8293        ),
8294        (
8295            "hydration_time",
8296            "The amount of time it took for the replica to hydrate the compute object.",
8297        ),
8298    ]),
8299    sql: "
8300WITH
8301    dataflows AS (
8302        SELECT
8303            object_id,
8304            replica_id,
8305            time_ns IS NOT NULL AS hydrated,
8306            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8307        FROM mz_internal.mz_compute_hydration_times
8308    ),
8309    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8310    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8311    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8312    -- blue-green readiness query does), so we include them as 'hydrated'.
8313    complete_mvs AS (
8314        SELECT
8315            mv.id,
8316            f.replica_id,
8317            true AS hydrated,
8318            NULL::interval AS hydration_time
8319        FROM mz_materialized_views mv
8320        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8321        WHERE f.write_frontier IS NULL
8322    ),
8323    -- Ditto CTs
8324    complete_cts AS (
8325        SELECT
8326            ct.id,
8327            f.replica_id,
8328            true AS hydrated,
8329            NULL::interval AS hydration_time
8330        FROM mz_internal.mz_continual_tasks ct
8331        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = ct.id
8332        WHERE f.write_frontier IS NULL
8333    )
8334SELECT * FROM dataflows
8335UNION ALL
8336SELECT * FROM complete_mvs
8337UNION ALL
8338SELECT * FROM complete_cts",
8339    access: vec![PUBLIC_SELECT],
8340});
8341
8342pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
8343    BuiltinSource {
8344        name: "mz_compute_operator_hydration_statuses",
8345        schema: MZ_INTERNAL_SCHEMA,
8346        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8347        desc: RelationDesc::builder()
8348            .with_column("replica_id", SqlScalarType::String.nullable(false))
8349            .with_column("object_id", SqlScalarType::String.nullable(false))
8350            .with_column(
8351                "physical_plan_node_id",
8352                SqlScalarType::UInt64.nullable(false),
8353            )
8354            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8355            .with_key(vec![0, 1, 2])
8356            .finish(),
8357        data_source: IntrospectionType::ComputeOperatorHydrationStatus,
8358        column_comments: BTreeMap::from_iter([
8359            ("replica_id", "The ID of a cluster replica."),
8360            (
8361                "object_id",
8362                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8363            ),
8364            (
8365                "physical_plan_node_id",
8366                "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)`.",
8367            ),
8368            ("hydrated", "Whether the node is hydrated on the replica."),
8369        ]),
8370        is_retained_metrics_object: false,
8371        access: vec![PUBLIC_SELECT],
8372    }
8373});
8374
8375pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8376    name: "mz_message_counts_per_worker",
8377    schema: MZ_INTROSPECTION_SCHEMA,
8378    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8379    desc: RelationDesc::builder()
8380        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8381        .with_column("from_worker_id", SqlScalarType::UInt64.nullable(false))
8382        .with_column("to_worker_id", SqlScalarType::UInt64.nullable(false))
8383        .with_column("sent", SqlScalarType::Int64.nullable(false))
8384        .with_column("received", SqlScalarType::Int64.nullable(false))
8385        .with_column("batch_sent", SqlScalarType::Int64.nullable(false))
8386        .with_column("batch_received", SqlScalarType::Int64.nullable(false))
8387        .with_key(vec![0, 1, 2])
8388        .finish(),
8389    column_comments: BTreeMap::new(),
8390    sql: "
8391WITH batch_sent_cte AS (
8392    SELECT
8393        channel_id,
8394        from_worker_id,
8395        to_worker_id,
8396        pg_catalog.count(*) AS sent
8397    FROM
8398        mz_introspection.mz_message_batch_counts_sent_raw
8399    GROUP BY
8400        channel_id, from_worker_id, to_worker_id
8401),
8402batch_received_cte AS (
8403    SELECT
8404        channel_id,
8405        from_worker_id,
8406        to_worker_id,
8407        pg_catalog.count(*) AS received
8408    FROM
8409        mz_introspection.mz_message_batch_counts_received_raw
8410    GROUP BY
8411        channel_id, from_worker_id, to_worker_id
8412),
8413sent_cte AS (
8414    SELECT
8415        channel_id,
8416        from_worker_id,
8417        to_worker_id,
8418        pg_catalog.count(*) AS sent
8419    FROM
8420        mz_introspection.mz_message_counts_sent_raw
8421    GROUP BY
8422        channel_id, from_worker_id, to_worker_id
8423),
8424received_cte AS (
8425    SELECT
8426        channel_id,
8427        from_worker_id,
8428        to_worker_id,
8429        pg_catalog.count(*) AS received
8430    FROM
8431        mz_introspection.mz_message_counts_received_raw
8432    GROUP BY
8433        channel_id, from_worker_id, to_worker_id
8434)
8435SELECT
8436    sent_cte.channel_id,
8437    sent_cte.from_worker_id,
8438    sent_cte.to_worker_id,
8439    sent_cte.sent,
8440    received_cte.received,
8441    batch_sent_cte.sent AS batch_sent,
8442    batch_received_cte.received AS batch_received
8443FROM sent_cte
8444JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8445JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8446JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8447    access: vec![PUBLIC_SELECT],
8448});
8449
8450pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8451    name: "mz_message_counts",
8452    schema: MZ_INTROSPECTION_SCHEMA,
8453    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8454    desc: RelationDesc::builder()
8455        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8456        .with_column(
8457            "sent",
8458            SqlScalarType::Numeric {
8459                max_scale: Some(NumericMaxScale::ZERO),
8460            }
8461            .nullable(false),
8462        )
8463        .with_column(
8464            "received",
8465            SqlScalarType::Numeric {
8466                max_scale: Some(NumericMaxScale::ZERO),
8467            }
8468            .nullable(false),
8469        )
8470        .with_column(
8471            "batch_sent",
8472            SqlScalarType::Numeric {
8473                max_scale: Some(NumericMaxScale::ZERO),
8474            }
8475            .nullable(false),
8476        )
8477        .with_column(
8478            "batch_received",
8479            SqlScalarType::Numeric {
8480                max_scale: Some(NumericMaxScale::ZERO),
8481            }
8482            .nullable(false),
8483        )
8484        .with_key(vec![0])
8485        .finish(),
8486    column_comments: BTreeMap::from_iter([
8487        (
8488            "channel_id",
8489            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8490        ),
8491        ("sent", "The number of messages sent."),
8492        ("received", "The number of messages received."),
8493        ("batch_sent", "The number of batches sent."),
8494        ("batch_received", "The number of batches received."),
8495    ]),
8496    sql: "
8497SELECT
8498    channel_id,
8499    pg_catalog.sum(sent) AS sent,
8500    pg_catalog.sum(received) AS received,
8501    pg_catalog.sum(batch_sent) AS batch_sent,
8502    pg_catalog.sum(batch_received) AS batch_received
8503FROM mz_introspection.mz_message_counts_per_worker
8504GROUP BY channel_id",
8505    access: vec![PUBLIC_SELECT],
8506});
8507
8508pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8509    name: "mz_active_peeks",
8510    schema: MZ_INTROSPECTION_SCHEMA,
8511    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8512    desc: RelationDesc::builder()
8513        .with_column("id", SqlScalarType::Uuid.nullable(false))
8514        .with_column("object_id", SqlScalarType::String.nullable(false))
8515        .with_column("type", SqlScalarType::String.nullable(false))
8516        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
8517        .finish(),
8518    column_comments: BTreeMap::from_iter([
8519        ("id", "The ID of the peek request."),
8520        (
8521            "object_id",
8522            "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`.",
8523        ),
8524        (
8525            "type",
8526            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8527        ),
8528        ("time", "The timestamp the peek has requested."),
8529    ]),
8530    sql: "
8531SELECT id, object_id, type, time
8532FROM mz_introspection.mz_active_peeks_per_worker
8533WHERE worker_id = 0",
8534    access: vec![PUBLIC_SELECT],
8535});
8536
8537pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8538    LazyLock::new(|| BuiltinView {
8539        name: "mz_dataflow_operator_reachability_per_worker",
8540        schema: MZ_INTROSPECTION_SCHEMA,
8541        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8542        desc: RelationDesc::builder()
8543            .with_column("id", SqlScalarType::UInt64.nullable(false))
8544            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8545            .with_column("port", SqlScalarType::UInt64.nullable(false))
8546            .with_column("update_type", SqlScalarType::String.nullable(false))
8547            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8548            .with_column("count", SqlScalarType::Int64.nullable(false))
8549            .with_key(vec![0, 1, 2, 3, 4])
8550            .finish(),
8551        column_comments: BTreeMap::new(),
8552        sql: "SELECT
8553    addr2.id,
8554    reachability.worker_id,
8555    port,
8556    update_type,
8557    time,
8558    pg_catalog.count(*) as count
8559FROM
8560    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8561    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8562    mz_introspection.mz_dataflow_addresses_per_worker addr2
8563WHERE
8564    addr2.address =
8565    CASE
8566        WHEN source = 0 THEN addr1.address
8567        ELSE addr1.address || reachability.source
8568    END
8569    AND addr1.id = reachability.id
8570    AND addr1.worker_id = reachability.worker_id
8571    AND addr2.worker_id = reachability.worker_id
8572GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8573        access: vec![PUBLIC_SELECT],
8574    });
8575
8576pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8577    LazyLock::new(|| BuiltinView {
8578        name: "mz_dataflow_operator_reachability",
8579        schema: MZ_INTROSPECTION_SCHEMA,
8580        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8581        desc: RelationDesc::builder()
8582            .with_column("id", SqlScalarType::UInt64.nullable(false))
8583            .with_column("port", SqlScalarType::UInt64.nullable(false))
8584            .with_column("update_type", SqlScalarType::String.nullable(false))
8585            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8586            .with_column(
8587                "count",
8588                SqlScalarType::Numeric {
8589                    max_scale: Some(NumericMaxScale::ZERO),
8590                }
8591                .nullable(false),
8592            )
8593            .with_key(vec![0, 1, 2, 3])
8594            .finish(),
8595        column_comments: BTreeMap::new(),
8596        sql: "
8597SELECT
8598    id,
8599    port,
8600    update_type,
8601    time,
8602    pg_catalog.sum(count) as count
8603FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8604GROUP BY id, port, update_type, time",
8605        access: vec![PUBLIC_SELECT],
8606    });
8607
8608pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8609    BuiltinView {
8610        name: "mz_arrangement_sizes_per_worker",
8611        schema: MZ_INTROSPECTION_SCHEMA,
8612        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8613        desc: RelationDesc::builder()
8614            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8615            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8616            .with_column("records", SqlScalarType::Int64.nullable(true))
8617            .with_column("batches", SqlScalarType::Int64.nullable(true))
8618            .with_column("size", SqlScalarType::Int64.nullable(true))
8619            .with_column("capacity", SqlScalarType::Int64.nullable(true))
8620            .with_column("allocations", SqlScalarType::Int64.nullable(true))
8621            .finish(),
8622        column_comments: BTreeMap::new(),
8623        sql: "
8624WITH operators_per_worker_cte AS (
8625    SELECT
8626        id AS operator_id,
8627        worker_id
8628    FROM
8629        mz_introspection.mz_dataflow_operators_per_worker
8630),
8631batches_cte AS (
8632    SELECT
8633        operator_id,
8634        worker_id,
8635        COUNT(*) AS batches
8636    FROM
8637        mz_introspection.mz_arrangement_batches_raw
8638    GROUP BY
8639        operator_id, worker_id
8640),
8641records_cte AS (
8642    SELECT
8643        operator_id,
8644        worker_id,
8645        COUNT(*) AS records
8646    FROM
8647        mz_introspection.mz_arrangement_records_raw
8648    GROUP BY
8649        operator_id, worker_id
8650),
8651heap_size_cte AS (
8652    SELECT
8653        operator_id,
8654        worker_id,
8655        COUNT(*) AS size
8656    FROM
8657        mz_introspection.mz_arrangement_heap_size_raw
8658    GROUP BY
8659        operator_id, worker_id
8660),
8661heap_capacity_cte AS (
8662    SELECT
8663        operator_id,
8664        worker_id,
8665        COUNT(*) AS capacity
8666    FROM
8667        mz_introspection.mz_arrangement_heap_capacity_raw
8668    GROUP BY
8669        operator_id, worker_id
8670),
8671heap_allocations_cte AS (
8672    SELECT
8673        operator_id,
8674        worker_id,
8675        COUNT(*) AS allocations
8676    FROM
8677        mz_introspection.mz_arrangement_heap_allocations_raw
8678    GROUP BY
8679        operator_id, worker_id
8680),
8681batcher_records_cte AS (
8682    SELECT
8683        operator_id,
8684        worker_id,
8685        COUNT(*) AS records
8686    FROM
8687        mz_introspection.mz_arrangement_batcher_records_raw
8688    GROUP BY
8689        operator_id, worker_id
8690),
8691batcher_size_cte AS (
8692    SELECT
8693        operator_id,
8694        worker_id,
8695        COUNT(*) AS size
8696    FROM
8697        mz_introspection.mz_arrangement_batcher_size_raw
8698    GROUP BY
8699        operator_id, worker_id
8700),
8701batcher_capacity_cte AS (
8702    SELECT
8703        operator_id,
8704        worker_id,
8705        COUNT(*) AS capacity
8706    FROM
8707        mz_introspection.mz_arrangement_batcher_capacity_raw
8708    GROUP BY
8709        operator_id, worker_id
8710),
8711batcher_allocations_cte AS (
8712    SELECT
8713        operator_id,
8714        worker_id,
8715        COUNT(*) AS allocations
8716    FROM
8717        mz_introspection.mz_arrangement_batcher_allocations_raw
8718    GROUP BY
8719        operator_id, worker_id
8720),
8721combined AS (
8722    SELECT
8723        opw.operator_id,
8724        opw.worker_id,
8725        CASE
8726            WHEN records_cte.records IS NULL AND batcher_records_cte.records IS NULL THEN NULL
8727            ELSE COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0)
8728        END AS records,
8729        batches_cte.batches AS batches,
8730        CASE
8731            WHEN heap_size_cte.size IS NULL AND batcher_size_cte.size IS NULL THEN NULL
8732            ELSE COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0)
8733        END AS size,
8734        CASE
8735            WHEN heap_capacity_cte.capacity IS NULL AND batcher_capacity_cte.capacity IS NULL THEN NULL
8736            ELSE COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0)
8737        END AS capacity,
8738        CASE
8739            WHEN heap_allocations_cte.allocations IS NULL AND batcher_allocations_cte.allocations IS NULL THEN NULL
8740            ELSE COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0)
8741        END AS allocations
8742    FROM
8743                    operators_per_worker_cte opw
8744    LEFT OUTER JOIN batches_cte USING (operator_id, worker_id)
8745    LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
8746    LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
8747    LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
8748    LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
8749    LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
8750    LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
8751    LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
8752    LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)
8753)
8754SELECT
8755    operator_id, worker_id, records, batches, size, capacity, allocations
8756FROM combined
8757WHERE
8758       records     IS NOT NULL
8759    OR batches     IS NOT NULL
8760    OR size        IS NOT NULL
8761    OR capacity    IS NOT NULL
8762    OR allocations IS NOT NULL
8763",
8764        access: vec![PUBLIC_SELECT],
8765    }
8766});
8767
8768pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8769    name: "mz_arrangement_sizes",
8770    schema: MZ_INTROSPECTION_SCHEMA,
8771    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
8772    desc: RelationDesc::builder()
8773        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8774        .with_column("records", SqlScalarType::Int64.nullable(true))
8775        .with_column("batches", SqlScalarType::Int64.nullable(true))
8776        .with_column("size", SqlScalarType::Int64.nullable(true))
8777        .with_column("capacity", SqlScalarType::Int64.nullable(true))
8778        .with_column("allocations", SqlScalarType::Int64.nullable(true))
8779        .with_key(vec![0])
8780        .finish(),
8781    column_comments: BTreeMap::from_iter([
8782        (
8783            "operator_id",
8784            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8785        ),
8786        ("records", "The number of records in the arrangement."),
8787        ("batches", "The number of batches in the arrangement."),
8788        ("size", "The utilized size in bytes of the arrangement."),
8789        (
8790            "capacity",
8791            "The capacity in bytes of the arrangement. Can be larger than the size.",
8792        ),
8793        (
8794            "allocations",
8795            "The number of separate memory allocations backing the arrangement.",
8796        ),
8797    ]),
8798    sql: "
8799SELECT
8800    operator_id,
8801    SUM(records)::int8 AS records,
8802    SUM(batches)::int8 AS batches,
8803    SUM(size)::int8 AS size,
8804    SUM(capacity)::int8 AS capacity,
8805    SUM(allocations)::int8 AS allocations
8806FROM mz_introspection.mz_arrangement_sizes_per_worker
8807GROUP BY operator_id",
8808    access: vec![PUBLIC_SELECT],
8809});
8810
8811pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
8812    LazyLock::new(|| BuiltinView {
8813        name: "mz_arrangement_sharing_per_worker",
8814        schema: MZ_INTROSPECTION_SCHEMA,
8815        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
8816        desc: RelationDesc::builder()
8817            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8818            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8819            .with_column("count", SqlScalarType::Int64.nullable(false))
8820            .with_key(vec![0, 1])
8821            .finish(),
8822        column_comments: BTreeMap::new(),
8823        sql: "
8824SELECT
8825    operator_id,
8826    worker_id,
8827    pg_catalog.count(*) AS count
8828FROM mz_introspection.mz_arrangement_sharing_raw
8829GROUP BY operator_id, worker_id",
8830        access: vec![PUBLIC_SELECT],
8831    });
8832
8833pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8834    name: "mz_arrangement_sharing",
8835    schema: MZ_INTROSPECTION_SCHEMA,
8836    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
8837    desc: RelationDesc::builder()
8838        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8839        .with_column("count", SqlScalarType::Int64.nullable(false))
8840        .finish(),
8841    column_comments: BTreeMap::from_iter([
8842        (
8843            "operator_id",
8844            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8845        ),
8846        (
8847            "count",
8848            "The number of operators that share the arrangement.",
8849        ),
8850    ]),
8851    sql: "
8852SELECT operator_id, count
8853FROM mz_introspection.mz_arrangement_sharing_per_worker
8854WHERE worker_id = 0",
8855    access: vec![PUBLIC_SELECT],
8856});
8857
8858pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8859    name: "mz_cluster_replica_utilization",
8860    schema: MZ_INTERNAL_SCHEMA,
8861    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
8862    desc: RelationDesc::builder()
8863        .with_column("replica_id", SqlScalarType::String.nullable(false))
8864        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
8865        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8866        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8867        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8868        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8869        .finish(),
8870    column_comments: BTreeMap::from_iter([
8871        ("replica_id", "The ID of a cluster replica."),
8872        ("process_id", "The ID of a process within the replica."),
8873        (
8874            "cpu_percent",
8875            "Approximate CPU usage, in percent of the total allocation.",
8876        ),
8877        (
8878            "memory_percent",
8879            "Approximate RAM usage, in percent of the total allocation.",
8880        ),
8881        (
8882            "disk_percent",
8883            "Approximate disk usage, in percent of the total allocation.",
8884        ),
8885        (
8886            "heap_percent",
8887            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
8888        ),
8889    ]),
8890    sql: "
8891SELECT
8892    r.id AS replica_id,
8893    m.process_id,
8894    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
8895    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
8896    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
8897    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent
8898FROM
8899    mz_catalog.mz_cluster_replicas AS r
8900        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8901        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
8902    access: vec![PUBLIC_SELECT],
8903});
8904
8905pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
8906    LazyLock::new(|| BuiltinView {
8907        name: "mz_cluster_replica_utilization_history",
8908        schema: MZ_INTERNAL_SCHEMA,
8909        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
8910        desc: RelationDesc::builder()
8911            .with_column("replica_id", SqlScalarType::String.nullable(false))
8912            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
8913            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8914            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8915            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8916            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8917            .with_column(
8918                "occurred_at",
8919                SqlScalarType::TimestampTz { precision: None }.nullable(false),
8920            )
8921            .finish(),
8922        column_comments: BTreeMap::from_iter([
8923            ("replica_id", "The ID of a cluster replica."),
8924            ("process_id", "The ID of a process within the replica."),
8925            (
8926                "cpu_percent",
8927                "Approximate CPU usage, in percent of the total allocation.",
8928            ),
8929            (
8930                "memory_percent",
8931                "Approximate RAM usage, in percent of the total allocation.",
8932            ),
8933            (
8934                "disk_percent",
8935                "Approximate disk usage, in percent of the total allocation.",
8936            ),
8937            (
8938                "heap_percent",
8939                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
8940            ),
8941            (
8942                "occurred_at",
8943                "Wall-clock timestamp at which the event occurred.",
8944            ),
8945        ]),
8946        sql: "
8947SELECT
8948    r.id AS replica_id,
8949    m.process_id,
8950    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
8951    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
8952    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
8953    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
8954    m.occurred_at
8955FROM
8956    mz_catalog.mz_cluster_replicas AS r
8957        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8958        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
8959        access: vec![PUBLIC_SELECT],
8960    });
8961
8962pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
8963    LazyLock::new(|| BuiltinView {
8964        name: "mz_dataflow_operator_parents_per_worker",
8965        schema: MZ_INTROSPECTION_SCHEMA,
8966        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
8967        desc: RelationDesc::builder()
8968            .with_column("id", SqlScalarType::UInt64.nullable(false))
8969            .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
8970            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8971            .finish(),
8972        column_comments: BTreeMap::new(),
8973        sql: "
8974WITH operator_addrs AS(
8975    SELECT
8976        id, address, worker_id
8977    FROM mz_introspection.mz_dataflow_addresses_per_worker
8978        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
8979            USING (id, worker_id)
8980),
8981parent_addrs AS (
8982    SELECT
8983        id,
8984        address[1:list_length(address) - 1] AS parent_address,
8985        worker_id
8986    FROM operator_addrs
8987)
8988SELECT pa.id, oa.id AS parent_id, pa.worker_id
8989FROM parent_addrs AS pa
8990    INNER JOIN operator_addrs AS oa
8991        ON pa.parent_address = oa.address
8992        AND pa.worker_id = oa.worker_id",
8993        access: vec![PUBLIC_SELECT],
8994    });
8995
8996pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8997    name: "mz_dataflow_operator_parents",
8998    schema: MZ_INTROSPECTION_SCHEMA,
8999    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
9000    desc: RelationDesc::builder()
9001        .with_column("id", SqlScalarType::UInt64.nullable(false))
9002        .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9003        .finish(),
9004    column_comments: BTreeMap::from_iter([
9005        (
9006            "id",
9007            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
9008        ),
9009        (
9010            "parent_id",
9011            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
9012        ),
9013    ]),
9014    sql: "
9015SELECT id, parent_id
9016FROM mz_introspection.mz_dataflow_operator_parents_per_worker
9017WHERE worker_id = 0",
9018    access: vec![PUBLIC_SELECT],
9019});
9020
9021pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9022    name: "mz_dataflow_arrangement_sizes",
9023    schema: MZ_INTROSPECTION_SCHEMA,
9024    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
9025    desc: RelationDesc::builder()
9026        .with_column("id", SqlScalarType::UInt64.nullable(false))
9027        .with_column("name", SqlScalarType::String.nullable(false))
9028        .with_column("records", SqlScalarType::Int64.nullable(true))
9029        .with_column("batches", SqlScalarType::Int64.nullable(true))
9030        .with_column("size", SqlScalarType::Int64.nullable(true))
9031        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9032        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9033        .with_key(vec![0, 1])
9034        .finish(),
9035    column_comments: BTreeMap::from_iter([
9036        (
9037            "id",
9038            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9039        ),
9040        ("name", "The name of the [dataflow]."),
9041        (
9042            "records",
9043            "The number of records in all arrangements in the dataflow.",
9044        ),
9045        (
9046            "batches",
9047            "The number of batches in all arrangements in the dataflow.",
9048        ),
9049        ("size", "The utilized size in bytes of the arrangements."),
9050        (
9051            "capacity",
9052            "The capacity in bytes of the arrangements. Can be larger than the size.",
9053        ),
9054        (
9055            "allocations",
9056            "The number of separate memory allocations backing the arrangements.",
9057        ),
9058    ]),
9059    sql: "
9060SELECT
9061    mdod.dataflow_id AS id,
9062    mdod.dataflow_name AS name,
9063    SUM(mas.records)::int8 AS records,
9064    SUM(mas.batches)::int8 AS batches,
9065    SUM(mas.size)::int8 AS size,
9066    SUM(mas.capacity)::int8 AS capacity,
9067    SUM(mas.allocations)::int8 AS allocations
9068FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9069LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9070    ON mdod.id = mas.operator_id
9071GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9072    access: vec![PUBLIC_SELECT],
9073});
9074
9075pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9076    name: "mz_expected_group_size_advice",
9077    schema: MZ_INTROSPECTION_SCHEMA,
9078    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9079    desc: RelationDesc::builder()
9080        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
9081        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
9082        .with_column("region_id", SqlScalarType::UInt64.nullable(false))
9083        .with_column("region_name", SqlScalarType::String.nullable(false))
9084        .with_column("levels", SqlScalarType::Int64.nullable(false))
9085        .with_column("to_cut", SqlScalarType::Int64.nullable(false))
9086        .with_column(
9087            "savings",
9088            SqlScalarType::Numeric {
9089                max_scale: Some(NumericMaxScale::ZERO),
9090            }
9091            .nullable(true),
9092        )
9093        .with_column("hint", SqlScalarType::Float64.nullable(false))
9094        .finish(),
9095    column_comments: BTreeMap::from_iter([
9096        (
9097            "dataflow_id",
9098            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9099        ),
9100        (
9101            "dataflow_name",
9102            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9103        ),
9104        (
9105            "region_id",
9106            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9107        ),
9108        (
9109            "region_name",
9110            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9111        ),
9112        (
9113            "levels",
9114            "The number of levels in the hierarchical scheme implemented by the region.",
9115        ),
9116        (
9117            "to_cut",
9118            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9119        ),
9120        (
9121            "savings",
9122            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9123        ),
9124        (
9125            "hint",
9126            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9127        ),
9128    ]),
9129    sql: "
9130        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9131        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9132        -- of arrangements must be built. For each dataflow and region corresponding to one
9133        -- such pattern, we look for how many levels can be eliminated without hitting a level
9134        -- that actually substantially filters the input. The advice is constructed so that
9135        -- setting the hint for the affected region will eliminate these redundant levels of
9136        -- the hierarchical rendering.
9137        --
9138        -- A number of helper CTEs are used for the view definition. The first one, operators,
9139        -- looks for operator names that comprise arrangements of inputs to each level of a
9140        -- min/max/top-k hierarchy.
9141        WITH operators AS (
9142            SELECT
9143                dod.dataflow_id,
9144                dor.id AS region_id,
9145                dod.id,
9146                ars.records,
9147                ars.size
9148            FROM
9149                mz_introspection.mz_dataflow_operator_dataflows dod
9150                JOIN mz_introspection.mz_dataflow_addresses doa
9151                    ON dod.id = doa.id
9152                JOIN mz_introspection.mz_dataflow_addresses dra
9153                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9154                JOIN mz_introspection.mz_dataflow_operators dor
9155                    ON dor.id = dra.id
9156                JOIN mz_introspection.mz_arrangement_sizes ars
9157                    ON ars.operator_id = dod.id
9158            WHERE
9159                dod.name = 'Arranged TopK input'
9160                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9161                OR dod.name = 'Arrange ReduceMinsMaxes'
9162            ),
9163        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9164        -- identified in operators above.
9165        levels AS (
9166            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9167            FROM operators o
9168            GROUP BY o.dataflow_id, o.region_id
9169        ),
9170        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9171        -- operator. This operator is crucially important, as it records the number of records
9172        -- that was given as input to the gadget as a whole.
9173        pivot AS (
9174            SELECT
9175                o1.dataflow_id,
9176                o1.region_id,
9177                o1.id,
9178                o1.records
9179            FROM operators o1
9180            WHERE
9181                o1.id = (
9182                    SELECT MIN(o2.id)
9183                    FROM operators o2
9184                    WHERE
9185                        o2.dataflow_id = o1.dataflow_id
9186                        AND o2.region_id = o1.region_id
9187                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9188                )
9189        ),
9190        -- The fourth CTE, candidates, will look for operators where the number of records
9191        -- maintained is not significantly different from the number at the pivot (excluding
9192        -- the pivot itself). These are the candidates for being cut from the dataflow region
9193        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9194        -- load generator data, to give some room for small deviations in number of records.
9195        -- The intuition for allowing for this deviation is that we are looking for a strongly
9196        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9197        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9198        -- among groups where the min/max/top-k computation is (partially) applied. If the
9199        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9200        -- groups might be empty or contain only one row. Each subsequent level will have a number
9201        -- of groups that is reduced exponentially. So at some point, we will find the level where
9202        -- we actually start having a few rows per group. That's where we will see the row counts
9203        -- significantly drop off.
9204        candidates AS (
9205            SELECT
9206                o.dataflow_id,
9207                o.region_id,
9208                o.id,
9209                o.records,
9210                o.size
9211            FROM
9212                operators o
9213                JOIN pivot p
9214                    ON o.dataflow_id = p.dataflow_id
9215                        AND o.region_id = p.region_id
9216                        AND o.id <> p.id
9217            WHERE o.records >= p.records * (1 - 0.15)
9218        ),
9219        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9220        -- candidate levels that should be cut. We only return here dataflow regions where at
9221        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9222        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9223        -- cutting the height of the hierarchy further. This is because we will have way less
9224        -- groups in the next level, so there should be even further reduction happening or there
9225        -- is some substantial skew in the data. But if the latter is the case, then we should not
9226        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9227        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9228        -- compute a conservative estimate of the memory savings in bytes that will result from
9229        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9230        -- input arrangements for each level to be cut. These arrangements should dominate the
9231        -- size of each level that can be cut, since the reduction gadget internal to the level
9232        -- does not remove much data at these levels.
9233        cuts AS (
9234            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9235            FROM candidates c
9236            GROUP BY c.dataflow_id, c.region_id
9237            HAVING COUNT(*) > 0
9238        )
9239        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9240        -- levels and the number of candidates to be cut. The hint is computed taking into account
9241        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9242        -- currently equal to 16.
9243        SELECT
9244            dod.dataflow_id,
9245            dod.dataflow_name,
9246            dod.id AS region_id,
9247            dod.name AS region_name,
9248            l.levels,
9249            c.to_cut,
9250            c.savings,
9251            pow(16, l.levels - c.to_cut) - 1 AS hint
9252        FROM cuts c
9253            JOIN levels l
9254                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9255            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9256                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9257    access: vec![PUBLIC_SELECT],
9258});
9259
9260pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9261    BuiltinView {
9262        name: "mz_index_advice",
9263        schema: MZ_INTERNAL_SCHEMA,
9264        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9265        desc: RelationDesc::builder()
9266            .with_column("object_id", SqlScalarType::String.nullable(true))
9267            .with_column("hint", SqlScalarType::String.nullable(false))
9268            .with_column("details", SqlScalarType::String.nullable(false))
9269            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
9270            .finish(),
9271        column_comments: BTreeMap::from_iter([
9272            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9273            ("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."),
9274            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9275            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9276        ]),
9277        sql: "
9278-- To avoid confusion with sources and sinks in the materialize sense,
9279-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9280-- when referring to the object dependency graph.
9281--
9282-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9283-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9284-- that are not depended on by other maintained objects and have a justification why they must
9285-- be maintained (e.g. a materialized view that is depended on by a sink).
9286-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9287-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9288-- downstream objects, that node is marked to be converted into a maintained object and this
9289-- node is then propagated further up. Once completed, the list of objects that are marked as
9290-- maintained is checked against all objects to generate appropriate recommendations.
9291--
9292-- Note that the recommendations only incorporate dependencies between objects.
9293-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9294-- a sink if an index is added in between the sink and the filter. For very selective filters,
9295-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9296-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9297-- dependencies.
9298WITH MUTUALLY RECURSIVE
9299    -- for all objects, understand if they have an index on them and on which cluster they are running
9300    -- this avoids having different cases for views with an index and materialized views later on
9301    objects(id text, type text, cluster_id text, indexes text list) AS (
9302        -- views and materialized views without an index
9303        SELECT
9304            o.id,
9305            o.type,
9306            o.cluster_id,
9307            '{}'::text list AS indexes
9308        FROM mz_catalog.mz_objects o
9309        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9310            SELECT FROM mz_internal.mz_object_dependencies d
9311            JOIN mz_catalog.mz_objects AS i
9312                ON (i.id = d.object_id AND i.type = 'index')
9313            WHERE (o.id = d.referenced_object_id)
9314        )
9315
9316        UNION ALL
9317
9318        -- views and materialized views with an index
9319        SELECT
9320            o.id,
9321            o.type,
9322            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9323            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9324            list_agg(i.id) AS indexes
9325        FROM mz_catalog.mz_objects o
9326        JOIN mz_internal.mz_object_dependencies AS d
9327            ON (o.id = d.referenced_object_id)
9328        JOIN mz_catalog.mz_objects AS i
9329            ON (i.id = d.object_id AND i.type = 'index')
9330        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9331        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9332    ),
9333
9334    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9335    maintained_leafs(id text, justification text) AS (
9336        -- materialized views that are connected to a sink
9337        SELECT
9338            m.id,
9339            s.id AS justification
9340        FROM objects AS m
9341        JOIN mz_internal.mz_object_dependencies AS d
9342            ON (m.id = d.referenced_object_id)
9343        JOIN mz_catalog.mz_objects AS s
9344            ON (s.id = d.object_id AND s.type = 'sink')
9345        WHERE m.type = 'materialized-view'
9346
9347        UNION ALL
9348
9349        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9350        SELECT
9351            v.id,
9352            unnest(v.indexes) AS justification
9353        FROM objects AS v
9354        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9355            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9356            INNER JOIN mz_catalog.mz_objects AS child
9357                ON (d.object_id = child.id)
9358            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]
9359        )
9360    ),
9361
9362    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9363    agg_maintained_children(id text, maintained_children text list) AS (
9364        SELECT
9365            parent_id AS id,
9366            list_agg(maintained_child) AS maintained_leafs
9367        FROM (
9368            SELECT DISTINCT
9369                d.referenced_object_id AS parent_id,
9370                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9371                unnest(child.maintained_children) AS maintained_child
9372            FROM propagate_dependencies AS child
9373            INNER JOIN mz_internal.mz_object_dependencies AS d
9374                ON (child.id = d.object_id)
9375        )
9376        GROUP BY parent_id
9377    ),
9378
9379    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9380    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9381    -- 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
9382    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9383        -- base case: start with the leafs
9384        SELECT DISTINCT
9385            id,
9386            LIST[id] AS maintained_children,
9387            list_agg(justification) AS justification
9388        FROM maintained_leafs
9389        GROUP BY id
9390
9391        UNION
9392
9393        -- recursive case: if there is a child with the same dependencies as the parent,
9394        -- the parent is only reused by a single child
9395        SELECT
9396            parent.id,
9397            child.maintained_children,
9398            NULL::text list AS justification
9399        FROM agg_maintained_children AS parent
9400        INNER JOIN mz_internal.mz_object_dependencies AS d
9401            ON (parent.id = d.referenced_object_id)
9402        INNER JOIN propagate_dependencies AS child
9403            ON (d.object_id = child.id)
9404        WHERE parent.maintained_children = child.maintained_children
9405
9406        UNION
9407
9408        -- recursive case: if there is NO child with the same dependencies as the parent,
9409        -- different children are reusing the parent so maintaining the object is justified by itself
9410        SELECT DISTINCT
9411            parent.id,
9412            LIST[parent.id] AS maintained_children,
9413            parent.maintained_children AS justification
9414        FROM agg_maintained_children AS parent
9415        WHERE NOT EXISTS (
9416            SELECT FROM mz_internal.mz_object_dependencies AS d
9417            INNER JOIN propagate_dependencies AS child
9418                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9419            WHERE parent.maintained_children = child.maintained_children
9420        )
9421    ),
9422
9423    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9424        SELECT
9425            p.id,
9426            o.type,
9427            o.cluster_id,
9428            p.maintained_children,
9429            p.justification,
9430            o.indexes
9431        FROM propagate_dependencies p
9432        JOIN objects AS o
9433            ON (p.id = o.id)
9434    ),
9435
9436    hints(id text, hint text, details text, justification text list) AS (
9437        -- materialized views that are not required
9438        SELECT
9439            id,
9440            'convert to a view' AS hint,
9441            'no dependencies from sinks nor from objects on different clusters' AS details,
9442            justification
9443        FROM objects_with_justification
9444        WHERE type = 'materialized-view' AND justification IS NULL
9445
9446        UNION ALL
9447
9448        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9449        SELECT
9450            id,
9451            'keep' AS hint,
9452            'dependencies from sinks or objects on different clusters: ' AS details,
9453            justification
9454        FROM objects_with_justification AS m
9455        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9456            SELECT FROM unnest(justification) AS dependency
9457            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9458
9459            UNION ALL
9460
9461            SELECT FROM unnest(justification) AS dependency
9462            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9463            WHERE d.cluster_id != m.cluster_id
9464        )
9465
9466        UNION ALL
9467
9468        -- 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
9469        SELECT
9470            id,
9471            'convert to a view with an index' AS hint,
9472            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9473            justification
9474        FROM objects_with_justification AS m
9475        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
9476            SELECT FROM unnest(justification) AS dependency
9477            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9478
9479            UNION ALL
9480
9481            SELECT FROM unnest(justification) AS dependency
9482            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9483            WHERE d.cluster_id != m.cluster_id
9484        )
9485
9486        UNION ALL
9487
9488        -- views that have indexes on different clusters should be a materialized view
9489        SELECT
9490            o.id,
9491            'convert to materialized view' AS hint,
9492            'dependencies on multiple clusters: ' AS details,
9493            o.justification
9494        FROM objects_with_justification o,
9495            LATERAL unnest(o.justification) j
9496        LEFT JOIN mz_catalog.mz_objects AS m
9497            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9498        WHERE o.type = 'view' AND o.justification IS NOT NULL
9499        GROUP BY o.id, o.justification
9500        HAVING count(DISTINCT m.cluster_id) >= 2
9501
9502        UNION ALL
9503
9504        -- views without an index that should be maintained
9505        SELECT
9506            id,
9507            'add index' AS hint,
9508            'multiple downstream dependencies: ' AS details,
9509            justification
9510        FROM objects_with_justification
9511        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9512
9513        UNION ALL
9514
9515        -- index inside the dependency graph (not a leaf)
9516        SELECT
9517            unnest(indexes) AS id,
9518            'drop unless queried directly' AS hint,
9519            'fewer than two downstream dependencies: ' AS details,
9520            maintained_children AS justification
9521        FROM objects_with_justification
9522        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9523
9524        UNION ALL
9525
9526        -- index on a leaf of the dependency graph
9527        SELECT
9528            unnest(indexes) AS id,
9529            'drop unless queried directly' AS hint,
9530            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9531            NULL::text list AS justification
9532        FROM objects_with_justification
9533        -- indexes can only be part of justification for leaf nodes
9534        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9535
9536        UNION ALL
9537
9538        -- index on a source
9539        SELECT
9540            unnest(indexes) AS id,
9541            'drop unless queried directly' AS hint,
9542            'sources do not transform data and can expose data directly' AS details,
9543            NULL::text list AS justification
9544        FROM objects_with_justification
9545        -- indexes can only be part of justification for leaf nodes
9546        WHERE type = 'source' AND NOT indexes = '{}'::text list
9547
9548        UNION ALL
9549
9550        -- indexes on views inside the dependency graph
9551        SELECT
9552            unnest(indexes) AS id,
9553            'keep' AS hint,
9554            'multiple downstream dependencies: ' AS details,
9555            justification
9556        FROM objects_with_justification
9557        -- indexes can only be part of justification for leaf nodes
9558        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9559    ),
9560
9561    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9562        SELECT
9563            h.id,
9564            h.hint,
9565            h.details || list_agg(o.name)::text AS details,
9566            h.justification
9567        FROM hints AS h,
9568            LATERAL unnest(h.justification) j
9569        JOIN mz_catalog.mz_objects AS o
9570            ON (o.id = j)
9571        GROUP BY h.id, h.hint, h.details, h.justification
9572
9573        UNION ALL
9574
9575        SELECT
9576            id,
9577            hint,
9578            details,
9579            justification
9580        FROM hints
9581        WHERE justification IS NULL
9582    )
9583
9584SELECT
9585    h.id AS object_id,
9586    h.hint AS hint,
9587    h.details,
9588    h.justification AS referenced_object_ids
9589FROM hints_resolved_ids AS h",
9590        access: vec![PUBLIC_SELECT],
9591    }
9592});
9593
9594// NOTE: If you add real data to this implementation, then please update
9595// the related `pg_` function implementations (like `pg_get_constraintdef`)
9596pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9597    name: "pg_constraint",
9598    schema: PG_CATALOG_SCHEMA,
9599    oid: oid::VIEW_PG_CONSTRAINT_OID,
9600    desc: RelationDesc::builder()
9601        .with_column("oid", SqlScalarType::Oid.nullable(false))
9602        .with_column("conname", SqlScalarType::String.nullable(false))
9603        .with_column("connamespace", SqlScalarType::Oid.nullable(false))
9604        .with_column("contype", SqlScalarType::PgLegacyChar.nullable(false))
9605        .with_column("condeferrable", SqlScalarType::Bool.nullable(false))
9606        .with_column("condeferred", SqlScalarType::Bool.nullable(false))
9607        .with_column("convalidated", SqlScalarType::Bool.nullable(false))
9608        .with_column("conrelid", SqlScalarType::Oid.nullable(false))
9609        .with_column("contypid", SqlScalarType::Oid.nullable(false))
9610        .with_column("conindid", SqlScalarType::Oid.nullable(false))
9611        .with_column("conparentid", SqlScalarType::Oid.nullable(false))
9612        .with_column("confrelid", SqlScalarType::Oid.nullable(false))
9613        .with_column("confupdtype", SqlScalarType::PgLegacyChar.nullable(false))
9614        .with_column("confdeltype", SqlScalarType::PgLegacyChar.nullable(false))
9615        .with_column("confmatchtype", SqlScalarType::PgLegacyChar.nullable(false))
9616        .with_column("conislocal", SqlScalarType::Bool.nullable(false))
9617        .with_column("coninhcount", SqlScalarType::Int32.nullable(false))
9618        .with_column("connoinherit", SqlScalarType::Bool.nullable(false))
9619        .with_column(
9620            "conkey",
9621            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9622        )
9623        .with_column(
9624            "confkey",
9625            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9626        )
9627        .with_column(
9628            "conpfeqop",
9629            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9630        )
9631        .with_column(
9632            "conppeqop",
9633            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9634        )
9635        .with_column(
9636            "conffeqop",
9637            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9638        )
9639        .with_column(
9640            "conexclop",
9641            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9642        )
9643        .with_column("conbin", SqlScalarType::String.nullable(false))
9644        .with_key(vec![])
9645        .finish(),
9646    column_comments: BTreeMap::new(),
9647    sql: "SELECT
9648    NULL::pg_catalog.oid as oid,
9649    NULL::pg_catalog.text as conname,
9650    NULL::pg_catalog.oid as connamespace,
9651    NULL::pg_catalog.\"char\" as contype,
9652    NULL::pg_catalog.bool as condeferrable,
9653    NULL::pg_catalog.bool as condeferred,
9654    NULL::pg_catalog.bool as convalidated,
9655    NULL::pg_catalog.oid as conrelid,
9656    NULL::pg_catalog.oid as contypid,
9657    NULL::pg_catalog.oid as conindid,
9658    NULL::pg_catalog.oid as conparentid,
9659    NULL::pg_catalog.oid as confrelid,
9660    NULL::pg_catalog.\"char\" as confupdtype,
9661    NULL::pg_catalog.\"char\" as confdeltype,
9662    NULL::pg_catalog.\"char\" as confmatchtype,
9663    NULL::pg_catalog.bool as conislocal,
9664    NULL::pg_catalog.int4 as coninhcount,
9665    NULL::pg_catalog.bool as connoinherit,
9666    NULL::pg_catalog.int2[] as conkey,
9667    NULL::pg_catalog.int2[] as confkey,
9668    NULL::pg_catalog.oid[] as conpfeqop,
9669    NULL::pg_catalog.oid[] as conppeqop,
9670    NULL::pg_catalog.oid[] as conffeqop,
9671    NULL::pg_catalog.oid[] as conexclop,
9672    NULL::pg_catalog.text as conbin
9673WHERE false",
9674    access: vec![PUBLIC_SELECT],
9675});
9676
9677pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9678    name: "pg_tables",
9679    schema: PG_CATALOG_SCHEMA,
9680    oid: oid::VIEW_PG_TABLES_OID,
9681    desc: RelationDesc::builder()
9682        .with_column("schemaname", SqlScalarType::String.nullable(true))
9683        .with_column("tablename", SqlScalarType::String.nullable(false))
9684        .with_column("tableowner", SqlScalarType::String.nullable(false))
9685        .finish(),
9686    column_comments: BTreeMap::new(),
9687    sql: "
9688SELECT n.nspname AS schemaname,
9689    c.relname AS tablename,
9690    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
9691FROM pg_catalog.pg_class c
9692LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
9693WHERE c.relkind IN ('r', 'p')",
9694    access: vec![PUBLIC_SELECT],
9695});
9696
9697pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9698    name: "pg_tablespace",
9699    schema: PG_CATALOG_SCHEMA,
9700    oid: oid::VIEW_PG_TABLESPACE_OID,
9701    desc: RelationDesc::builder()
9702        .with_column("oid", SqlScalarType::Oid.nullable(false))
9703        .with_column("spcname", SqlScalarType::String.nullable(false))
9704        .with_column("spcowner", SqlScalarType::Oid.nullable(true))
9705        .with_column(
9706            "spcacl",
9707            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9708        )
9709        .with_column(
9710            "spcoptions",
9711            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9712        )
9713        .with_key(vec![])
9714        .finish(),
9715    column_comments: BTreeMap::new(),
9716    sql: "
9717    SELECT oid, spcname, spcowner, spcacl, spcoptions
9718    FROM (
9719        VALUES (
9720            --These are the same defaults CockroachDB uses.
9721            0::pg_catalog.oid,
9722            'pg_default'::pg_catalog.text,
9723            NULL::pg_catalog.oid,
9724            NULL::pg_catalog.text[],
9725            NULL::pg_catalog.text[]
9726        )
9727    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
9728",
9729    access: vec![PUBLIC_SELECT],
9730});
9731
9732pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9733    name: "pg_am",
9734    schema: PG_CATALOG_SCHEMA,
9735    oid: oid::VIEW_PG_AM_OID,
9736    desc: RelationDesc::builder()
9737        .with_column("oid", SqlScalarType::Oid.nullable(false))
9738        .with_column("amname", SqlScalarType::String.nullable(false))
9739        .with_column("amhandler", SqlScalarType::RegProc.nullable(false))
9740        .with_column("amtype", SqlScalarType::PgLegacyChar.nullable(false))
9741        .with_key(vec![])
9742        .finish(),
9743    column_comments: BTreeMap::new(),
9744    sql: "
9745SELECT NULL::pg_catalog.oid AS oid,
9746    NULL::pg_catalog.text AS amname,
9747    NULL::pg_catalog.regproc AS amhandler,
9748    NULL::pg_catalog.\"char\" AS amtype
9749WHERE false",
9750    access: vec![PUBLIC_SELECT],
9751});
9752
9753pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9754    name: "pg_roles",
9755    schema: PG_CATALOG_SCHEMA,
9756    oid: oid::VIEW_PG_ROLES_OID,
9757    desc: RelationDesc::builder()
9758        .with_column("rolname", SqlScalarType::String.nullable(false))
9759        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
9760        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
9761        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
9762        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
9763        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
9764        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
9765        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
9766        .with_column("rolpassword", SqlScalarType::String.nullable(false))
9767        .with_column(
9768            "rolvaliduntil",
9769            SqlScalarType::TimestampTz { precision: None }.nullable(true),
9770        )
9771        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
9772        .with_column(
9773            "rolconfig",
9774            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9775        )
9776        .with_column("oid", SqlScalarType::Oid.nullable(false))
9777        .finish(),
9778    column_comments: BTreeMap::new(),
9779    sql: "SELECT
9780    rolname,
9781    rolsuper,
9782    rolinherit,
9783    rolcreaterole,
9784    rolcreatedb,
9785    COALESCE(rolcanlogin, false) AS rolcanlogin,
9786    rolreplication,
9787    rolconnlimit,
9788    '********' as rolpassword,
9789    rolvaliduntil,
9790    rolbypassrls,
9791    (
9792        SELECT array_agg(parameter_name || '=' || parameter_value)
9793        FROM mz_catalog.mz_role_parameters rp
9794        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9795        WHERE ai.oid = r.oid
9796    ) AS rolconfig,
9797    oid
9798FROM pg_catalog.pg_authid ai",
9799    access: vec![PUBLIC_SELECT],
9800});
9801
9802pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9803    name: "pg_user",
9804    schema: PG_CATALOG_SCHEMA,
9805    oid: oid::VIEW_PG_USER_OID,
9806    desc: RelationDesc::builder()
9807        .with_column("usename", SqlScalarType::String.nullable(false))
9808        .with_column("usesysid", SqlScalarType::Oid.nullable(false))
9809        .with_column("usecreatedb", SqlScalarType::Bool.nullable(true))
9810        .with_column("usesuper", SqlScalarType::Bool.nullable(true))
9811        .with_column("userepl", SqlScalarType::Bool.nullable(false))
9812        .with_column("usebypassrls", SqlScalarType::Bool.nullable(false))
9813        .with_column("passwd", SqlScalarType::String.nullable(true))
9814        .with_column(
9815            "valuntil",
9816            SqlScalarType::TimestampTz { precision: None }.nullable(true),
9817        )
9818        .with_column(
9819            "useconfig",
9820            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9821        )
9822        .finish(),
9823    column_comments: BTreeMap::new(),
9824    sql: "
9825SELECT
9826    rolname as usename,
9827    ai.oid as usesysid,
9828    rolcreatedb AS usecreatedb,
9829    rolsuper AS usesuper,
9830    rolreplication AS userepl,
9831    rolbypassrls AS usebypassrls,
9832    rolpassword as passwd,
9833    rolvaliduntil as valuntil,
9834    (
9835        SELECT array_agg(parameter_name || '=' || parameter_value)
9836        FROM mz_catalog.mz_role_parameters rp
9837        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9838        WHERE ai.oid = r.oid
9839    ) AS useconfig
9840FROM pg_catalog.pg_authid ai
9841WHERE rolcanlogin",
9842    access: vec![PUBLIC_SELECT],
9843});
9844
9845pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9846    name: "pg_views",
9847    schema: PG_CATALOG_SCHEMA,
9848    oid: oid::VIEW_PG_VIEWS_OID,
9849    desc: RelationDesc::builder()
9850        .with_column("schemaname", SqlScalarType::String.nullable(true))
9851        .with_column("viewname", SqlScalarType::String.nullable(false))
9852        .with_column("viewowner", SqlScalarType::Oid.nullable(false))
9853        .with_column("definition", SqlScalarType::String.nullable(false))
9854        .finish(),
9855    column_comments: BTreeMap::new(),
9856    sql: "SELECT
9857    s.name AS schemaname,
9858    v.name AS viewname,
9859    role_owner.oid AS viewowner,
9860    v.definition AS definition
9861FROM mz_catalog.mz_views v
9862LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
9863LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9864JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
9865WHERE s.database_id IS NULL OR d.name = current_database()",
9866    access: vec![PUBLIC_SELECT],
9867});
9868
9869pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9870    name: "pg_matviews",
9871    schema: PG_CATALOG_SCHEMA,
9872    oid: oid::VIEW_PG_MATVIEWS_OID,
9873    desc: RelationDesc::builder()
9874        .with_column("schemaname", SqlScalarType::String.nullable(true))
9875        .with_column("matviewname", SqlScalarType::String.nullable(false))
9876        .with_column("matviewowner", SqlScalarType::Oid.nullable(false))
9877        .with_column("definition", SqlScalarType::String.nullable(false))
9878        .finish(),
9879    column_comments: BTreeMap::new(),
9880    sql: "SELECT
9881    s.name AS schemaname,
9882    m.name AS matviewname,
9883    role_owner.oid AS matviewowner,
9884    m.definition AS definition
9885FROM mz_catalog.mz_materialized_views m
9886LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
9887LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9888JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
9889WHERE s.database_id IS NULL OR d.name = current_database()",
9890    access: vec![PUBLIC_SELECT],
9891});
9892
9893pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
9894    LazyLock::new(|| BuiltinView {
9895        name: "applicable_roles",
9896        schema: INFORMATION_SCHEMA,
9897        oid: oid::VIEW_APPLICABLE_ROLES_OID,
9898        desc: RelationDesc::builder()
9899            .with_column("grantee", SqlScalarType::String.nullable(false))
9900            .with_column("role_name", SqlScalarType::String.nullable(false))
9901            .with_column("is_grantable", SqlScalarType::String.nullable(false))
9902            .finish(),
9903        column_comments: BTreeMap::new(),
9904        sql: "
9905SELECT
9906    member.name AS grantee,
9907    role.name AS role_name,
9908    -- ADMIN OPTION isn't implemented.
9909    'NO' AS is_grantable
9910FROM mz_catalog.mz_role_members membership
9911JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
9912JOIN mz_catalog.mz_roles member ON membership.member = member.id
9913WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
9914        access: vec![PUBLIC_SELECT],
9915    });
9916
9917pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9918    name: "columns",
9919    schema: INFORMATION_SCHEMA,
9920    oid: oid::VIEW_COLUMNS_OID,
9921    desc: RelationDesc::builder()
9922        .with_column("table_catalog", SqlScalarType::String.nullable(false))
9923        .with_column("table_schema", SqlScalarType::String.nullable(false))
9924        .with_column("table_name", SqlScalarType::String.nullable(false))
9925        .with_column("column_name", SqlScalarType::String.nullable(false))
9926        .with_column("ordinal_position", SqlScalarType::Int64.nullable(false))
9927        .with_column("column_default", SqlScalarType::String.nullable(true))
9928        .with_column("is_nullable", SqlScalarType::String.nullable(false))
9929        .with_column("data_type", SqlScalarType::String.nullable(false))
9930        .with_column(
9931            "character_maximum_length",
9932            SqlScalarType::Int32.nullable(true),
9933        )
9934        .with_column("numeric_precision", SqlScalarType::Int32.nullable(true))
9935        .with_column("numeric_scale", SqlScalarType::Int32.nullable(true))
9936        .finish(),
9937    column_comments: BTreeMap::new(),
9938    sql: "
9939SELECT
9940    current_database() as table_catalog,
9941    s.name AS table_schema,
9942    o.name AS table_name,
9943    c.name AS column_name,
9944    c.position::int8 AS ordinal_position,
9945    c.default AS column_default,
9946    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
9947    c.type AS data_type,
9948    NULL::pg_catalog.int4 AS character_maximum_length,
9949    NULL::pg_catalog.int4 AS numeric_precision,
9950    NULL::pg_catalog.int4 AS numeric_scale
9951FROM mz_catalog.mz_columns c
9952JOIN mz_catalog.mz_objects o ON o.id = c.id
9953JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
9954LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9955WHERE s.database_id IS NULL OR d.name = current_database()",
9956    access: vec![PUBLIC_SELECT],
9957});
9958
9959pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
9960    LazyLock::new(|| BuiltinView {
9961        name: "enabled_roles",
9962        schema: INFORMATION_SCHEMA,
9963        oid: oid::VIEW_ENABLED_ROLES_OID,
9964        desc: RelationDesc::builder()
9965            .with_column("role_name", SqlScalarType::String.nullable(false))
9966            .finish(),
9967        column_comments: BTreeMap::new(),
9968        sql: "
9969SELECT name AS role_name
9970FROM mz_catalog.mz_roles
9971WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
9972        access: vec![PUBLIC_SELECT],
9973    });
9974
9975pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
9976    BuiltinView {
9977        name: "role_table_grants",
9978        schema: INFORMATION_SCHEMA,
9979        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
9980        desc: RelationDesc::builder()
9981            .with_column("grantor", SqlScalarType::String.nullable(false))
9982            .with_column("grantee", SqlScalarType::String.nullable(true))
9983            .with_column("table_catalog", SqlScalarType::String.nullable(true))
9984            .with_column("table_schema", SqlScalarType::String.nullable(false))
9985            .with_column("table_name", SqlScalarType::String.nullable(false))
9986            .with_column("privilege_type", SqlScalarType::String.nullable(true))
9987            .with_column("is_grantable", SqlScalarType::String.nullable(false))
9988            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
9989            .finish(),
9990        column_comments: BTreeMap::new(),
9991        sql: "
9992SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
9993FROM information_schema.table_privileges
9994WHERE
9995    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
9996    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
9997        access: vec![PUBLIC_SELECT],
9998    }
9999});
10000
10001pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
10002    LazyLock::new(|| BuiltinView {
10003        name: "key_column_usage",
10004        schema: INFORMATION_SCHEMA,
10005        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
10006        desc: RelationDesc::builder()
10007            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10008            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10009            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10010            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10011            .with_column("table_schema", SqlScalarType::String.nullable(false))
10012            .with_column("table_name", SqlScalarType::String.nullable(false))
10013            .with_column("column_name", SqlScalarType::String.nullable(false))
10014            .with_column("ordinal_position", SqlScalarType::Int32.nullable(false))
10015            .with_column(
10016                "position_in_unique_constraint",
10017                SqlScalarType::Int32.nullable(false),
10018            )
10019            .with_key(vec![])
10020            .finish(),
10021        column_comments: BTreeMap::new(),
10022        sql: "SELECT
10023    NULL::text AS constraint_catalog,
10024    NULL::text AS constraint_schema,
10025    NULL::text AS constraint_name,
10026    NULL::text AS table_catalog,
10027    NULL::text AS table_schema,
10028    NULL::text AS table_name,
10029    NULL::text AS column_name,
10030    NULL::integer AS ordinal_position,
10031    NULL::integer AS position_in_unique_constraint
10032WHERE false",
10033        access: vec![PUBLIC_SELECT],
10034    });
10035
10036pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10037    LazyLock::new(|| BuiltinView {
10038        name: "referential_constraints",
10039        schema: INFORMATION_SCHEMA,
10040        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10041        desc: RelationDesc::builder()
10042            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10043            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10044            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10045            .with_column(
10046                "unique_constraint_catalog",
10047                SqlScalarType::String.nullable(false),
10048            )
10049            .with_column(
10050                "unique_constraint_schema",
10051                SqlScalarType::String.nullable(false),
10052            )
10053            .with_column(
10054                "unique_constraint_name",
10055                SqlScalarType::String.nullable(false),
10056            )
10057            .with_column("match_option", SqlScalarType::String.nullable(false))
10058            .with_column("update_rule", SqlScalarType::String.nullable(false))
10059            .with_column("delete_rule", SqlScalarType::String.nullable(false))
10060            .with_key(vec![])
10061            .finish(),
10062        column_comments: BTreeMap::new(),
10063        sql: "SELECT
10064    NULL::text AS constraint_catalog,
10065    NULL::text AS constraint_schema,
10066    NULL::text AS constraint_name,
10067    NULL::text AS unique_constraint_catalog,
10068    NULL::text AS unique_constraint_schema,
10069    NULL::text AS unique_constraint_name,
10070    NULL::text AS match_option,
10071    NULL::text AS update_rule,
10072    NULL::text AS delete_rule
10073WHERE false",
10074        access: vec![PUBLIC_SELECT],
10075    });
10076
10077pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10078    name: "routines",
10079    schema: INFORMATION_SCHEMA,
10080    oid: oid::VIEW_ROUTINES_OID,
10081    desc: RelationDesc::builder()
10082        .with_column("routine_catalog", SqlScalarType::String.nullable(false))
10083        .with_column("routine_schema", SqlScalarType::String.nullable(false))
10084        .with_column("routine_name", SqlScalarType::String.nullable(false))
10085        .with_column("routine_type", SqlScalarType::String.nullable(false))
10086        .with_column("routine_definition", SqlScalarType::String.nullable(true))
10087        .finish(),
10088    column_comments: BTreeMap::new(),
10089    sql: "SELECT
10090    current_database() as routine_catalog,
10091    s.name AS routine_schema,
10092    f.name AS routine_name,
10093    'FUNCTION' AS routine_type,
10094    NULL::text AS routine_definition
10095FROM mz_catalog.mz_functions f
10096JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10097LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10098WHERE s.database_id IS NULL OR d.name = current_database()",
10099    access: vec![PUBLIC_SELECT],
10100});
10101
10102pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10103    name: "schemata",
10104    schema: INFORMATION_SCHEMA,
10105    oid: oid::VIEW_SCHEMATA_OID,
10106    desc: RelationDesc::builder()
10107        .with_column("catalog_name", SqlScalarType::String.nullable(false))
10108        .with_column("schema_name", SqlScalarType::String.nullable(false))
10109        .finish(),
10110    column_comments: BTreeMap::new(),
10111    sql: "
10112SELECT
10113    current_database() as catalog_name,
10114    s.name AS schema_name
10115FROM mz_catalog.mz_schemas s
10116LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10117WHERE s.database_id IS NULL OR d.name = current_database()",
10118    access: vec![PUBLIC_SELECT],
10119});
10120
10121pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10122    name: "tables",
10123    schema: INFORMATION_SCHEMA,
10124    oid: oid::VIEW_TABLES_OID,
10125    desc: RelationDesc::builder()
10126        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10127        .with_column("table_schema", SqlScalarType::String.nullable(false))
10128        .with_column("table_name", SqlScalarType::String.nullable(false))
10129        .with_column("table_type", SqlScalarType::String.nullable(false))
10130        .finish(),
10131    column_comments: BTreeMap::new(),
10132    sql: "SELECT
10133    current_database() as table_catalog,
10134    s.name AS table_schema,
10135    r.name AS table_name,
10136    CASE r.type
10137        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10138        WHEN 'table' THEN 'BASE TABLE'
10139        ELSE pg_catalog.upper(r.type)
10140    END AS table_type
10141FROM mz_catalog.mz_relations r
10142JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10143LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10144WHERE s.database_id IS NULL OR d.name = current_database()",
10145    access: vec![PUBLIC_SELECT],
10146});
10147
10148pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10149    LazyLock::new(|| BuiltinView {
10150        name: "table_constraints",
10151        schema: INFORMATION_SCHEMA,
10152        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10153        desc: RelationDesc::builder()
10154            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10155            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10156            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10157            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10158            .with_column("table_schema", SqlScalarType::String.nullable(false))
10159            .with_column("table_name", SqlScalarType::String.nullable(false))
10160            .with_column("constraint_type", SqlScalarType::String.nullable(false))
10161            .with_column("is_deferrable", SqlScalarType::String.nullable(false))
10162            .with_column("initially_deferred", SqlScalarType::String.nullable(false))
10163            .with_column("enforced", SqlScalarType::String.nullable(false))
10164            .with_column("nulls_distinct", SqlScalarType::String.nullable(false))
10165            .with_key(vec![])
10166            .finish(),
10167        column_comments: BTreeMap::new(),
10168        sql: "SELECT
10169    NULL::text AS constraint_catalog,
10170    NULL::text AS constraint_schema,
10171    NULL::text AS constraint_name,
10172    NULL::text AS table_catalog,
10173    NULL::text AS table_schema,
10174    NULL::text AS table_name,
10175    NULL::text AS constraint_type,
10176    NULL::text AS is_deferrable,
10177    NULL::text AS initially_deferred,
10178    NULL::text AS enforced,
10179    NULL::text AS nulls_distinct
10180WHERE false",
10181        access: vec![PUBLIC_SELECT],
10182    });
10183
10184pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10185    BuiltinView {
10186        name: "table_privileges",
10187        schema: INFORMATION_SCHEMA,
10188        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10189        desc: RelationDesc::builder()
10190            .with_column("grantor", SqlScalarType::String.nullable(false))
10191            .with_column("grantee", SqlScalarType::String.nullable(true))
10192            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10193            .with_column("table_schema", SqlScalarType::String.nullable(false))
10194            .with_column("table_name", SqlScalarType::String.nullable(false))
10195            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10196            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10197            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10198            .finish(),
10199        column_comments: BTreeMap::new(),
10200        sql: "
10201SELECT
10202    grantor,
10203    grantee,
10204    table_catalog,
10205    table_schema,
10206    table_name,
10207    privilege_type,
10208    is_grantable,
10209    CASE privilege_type
10210        WHEN 'SELECT' THEN 'YES'
10211        ELSE 'NO'
10212    END AS with_hierarchy
10213FROM
10214    (SELECT
10215        grantor.name AS grantor,
10216        CASE mz_internal.mz_aclitem_grantee(privileges)
10217            WHEN 'p' THEN 'PUBLIC'
10218            ELSE grantee.name
10219        END AS grantee,
10220        table_catalog,
10221        table_schema,
10222        table_name,
10223        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10224        -- ADMIN OPTION isn't implemented.
10225        'NO' AS is_grantable
10226    FROM
10227        (SELECT
10228            unnest(relations.privileges) AS privileges,
10229            CASE
10230                WHEN schemas.database_id IS NULL THEN current_database()
10231                ELSE databases.name
10232            END AS table_catalog,
10233            schemas.name AS table_schema,
10234            relations.name AS table_name
10235        FROM mz_catalog.mz_relations AS relations
10236        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10237        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10238        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10239    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10240    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10241WHERE
10242    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10243    -- to pg_has_role. Therefore we need to use a CASE statement.
10244    CASE
10245        WHEN grantee = 'PUBLIC' THEN true
10246        ELSE mz_catalog.mz_is_superuser()
10247            OR pg_has_role(current_role, grantee, 'USAGE')
10248            OR pg_has_role(current_role, grantor, 'USAGE')
10249    END",
10250        access: vec![PUBLIC_SELECT],
10251    }
10252});
10253
10254pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10255    name: "triggers",
10256    schema: INFORMATION_SCHEMA,
10257    oid: oid::VIEW_TRIGGERS_OID,
10258    desc: RelationDesc::builder()
10259        .with_column("trigger_catalog", SqlScalarType::String.nullable(false))
10260        .with_column("trigger_schema", SqlScalarType::String.nullable(false))
10261        .with_column("trigger_name", SqlScalarType::String.nullable(false))
10262        .with_column("event_manipulation", SqlScalarType::String.nullable(false))
10263        .with_column(
10264            "event_object_catalog",
10265            SqlScalarType::String.nullable(false),
10266        )
10267        .with_column("event_object_schema", SqlScalarType::String.nullable(false))
10268        .with_column("event_object_table", SqlScalarType::String.nullable(false))
10269        .with_column("action_order", SqlScalarType::Int32.nullable(false))
10270        .with_column("action_condition", SqlScalarType::String.nullable(false))
10271        .with_column("action_statement", SqlScalarType::String.nullable(false))
10272        .with_column("action_orientation", SqlScalarType::String.nullable(false))
10273        .with_column("action_timing", SqlScalarType::String.nullable(false))
10274        .with_column(
10275            "action_reference_old_table",
10276            SqlScalarType::String.nullable(false),
10277        )
10278        .with_column(
10279            "action_reference_new_table",
10280            SqlScalarType::String.nullable(false),
10281        )
10282        .with_key(vec![])
10283        .finish(),
10284    column_comments: BTreeMap::new(),
10285    sql: "SELECT
10286    NULL::text as trigger_catalog,
10287    NULL::text AS trigger_schema,
10288    NULL::text AS trigger_name,
10289    NULL::text AS event_manipulation,
10290    NULL::text AS event_object_catalog,
10291    NULL::text AS event_object_schema,
10292    NULL::text AS event_object_table,
10293    NULL::integer AS action_order,
10294    NULL::text AS action_condition,
10295    NULL::text AS action_statement,
10296    NULL::text AS action_orientation,
10297    NULL::text AS action_timing,
10298    NULL::text AS action_reference_old_table,
10299    NULL::text AS action_reference_new_table
10300WHERE FALSE",
10301    access: vec![PUBLIC_SELECT],
10302});
10303
10304pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10305    name: "views",
10306    schema: INFORMATION_SCHEMA,
10307    oid: oid::VIEW_VIEWS_OID,
10308    desc: RelationDesc::builder()
10309        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10310        .with_column("table_schema", SqlScalarType::String.nullable(false))
10311        .with_column("table_name", SqlScalarType::String.nullable(false))
10312        .with_column("view_definition", SqlScalarType::String.nullable(false))
10313        .finish(),
10314    column_comments: BTreeMap::new(),
10315    sql: "SELECT
10316    current_database() as table_catalog,
10317    s.name AS table_schema,
10318    v.name AS table_name,
10319    v.definition AS view_definition
10320FROM mz_catalog.mz_views v
10321JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10322LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10323WHERE s.database_id IS NULL OR d.name = current_database()",
10324    access: vec![PUBLIC_SELECT],
10325});
10326
10327pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10328    LazyLock::new(|| BuiltinView {
10329        name: "character_sets",
10330        schema: INFORMATION_SCHEMA,
10331        oid: oid::VIEW_CHARACTER_SETS_OID,
10332        desc: RelationDesc::builder()
10333            .with_column(
10334                "character_set_catalog",
10335                SqlScalarType::String.nullable(true),
10336            )
10337            .with_column("character_set_schema", SqlScalarType::String.nullable(true))
10338            .with_column("character_set_name", SqlScalarType::String.nullable(false))
10339            .with_column(
10340                "character_repertoire",
10341                SqlScalarType::String.nullable(false),
10342            )
10343            .with_column("form_of_use", SqlScalarType::String.nullable(false))
10344            .with_column(
10345                "default_collate_catalog",
10346                SqlScalarType::String.nullable(false),
10347            )
10348            .with_column(
10349                "default_collate_schema",
10350                SqlScalarType::String.nullable(false),
10351            )
10352            .with_column(
10353                "default_collate_name",
10354                SqlScalarType::String.nullable(false),
10355            )
10356            .with_key(vec![])
10357            .finish(),
10358        column_comments: BTreeMap::new(),
10359        sql: "SELECT
10360    NULL as character_set_catalog,
10361    NULL as character_set_schema,
10362    'UTF8' as character_set_name,
10363    'UCS' as character_repertoire,
10364    'UTF8' as form_of_use,
10365    current_database() as default_collate_catalog,
10366    'pg_catalog' as default_collate_schema,
10367    'en_US.utf8' as default_collate_name",
10368        access: vec![PUBLIC_SELECT],
10369    });
10370
10371// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10372// codes a collation of 'C' for every database, so we could copy that here.
10373pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10374    name: "pg_collation",
10375    schema: PG_CATALOG_SCHEMA,
10376    oid: oid::VIEW_PG_COLLATION_OID,
10377    desc: RelationDesc::builder()
10378        .with_column("oid", SqlScalarType::Oid.nullable(false))
10379        .with_column("collname", SqlScalarType::String.nullable(false))
10380        .with_column("collnamespace", SqlScalarType::Oid.nullable(false))
10381        .with_column("collowner", SqlScalarType::Oid.nullable(false))
10382        .with_column("collprovider", SqlScalarType::PgLegacyChar.nullable(false))
10383        .with_column("collisdeterministic", SqlScalarType::Bool.nullable(false))
10384        .with_column("collencoding", SqlScalarType::Int32.nullable(false))
10385        .with_column("collcollate", SqlScalarType::String.nullable(false))
10386        .with_column("collctype", SqlScalarType::String.nullable(false))
10387        .with_column("collversion", SqlScalarType::String.nullable(false))
10388        .with_key(vec![])
10389        .finish(),
10390    column_comments: BTreeMap::new(),
10391    sql: "
10392SELECT
10393    NULL::pg_catalog.oid AS oid,
10394    NULL::pg_catalog.text AS collname,
10395    NULL::pg_catalog.oid AS collnamespace,
10396    NULL::pg_catalog.oid AS collowner,
10397    NULL::pg_catalog.\"char\" AS collprovider,
10398    NULL::pg_catalog.bool AS collisdeterministic,
10399    NULL::pg_catalog.int4 AS collencoding,
10400    NULL::pg_catalog.text AS collcollate,
10401    NULL::pg_catalog.text AS collctype,
10402    NULL::pg_catalog.text AS collversion
10403WHERE false",
10404    access: vec![PUBLIC_SELECT],
10405});
10406
10407// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10408pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10409    name: "pg_policy",
10410    schema: PG_CATALOG_SCHEMA,
10411    oid: oid::VIEW_PG_POLICY_OID,
10412    desc: RelationDesc::builder()
10413        .with_column("oid", SqlScalarType::Oid.nullable(false))
10414        .with_column("polname", SqlScalarType::String.nullable(false))
10415        .with_column("polrelid", SqlScalarType::Oid.nullable(false))
10416        .with_column("polcmd", SqlScalarType::PgLegacyChar.nullable(false))
10417        .with_column("polpermissive", SqlScalarType::Bool.nullable(false))
10418        .with_column(
10419            "polroles",
10420            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10421        )
10422        .with_column("polqual", SqlScalarType::String.nullable(false))
10423        .with_column("polwithcheck", SqlScalarType::String.nullable(false))
10424        .with_key(vec![])
10425        .finish(),
10426    column_comments: BTreeMap::new(),
10427    sql: "
10428SELECT
10429    NULL::pg_catalog.oid AS oid,
10430    NULL::pg_catalog.text AS polname,
10431    NULL::pg_catalog.oid AS polrelid,
10432    NULL::pg_catalog.\"char\" AS polcmd,
10433    NULL::pg_catalog.bool AS polpermissive,
10434    NULL::pg_catalog.oid[] AS polroles,
10435    NULL::pg_catalog.text AS polqual,
10436    NULL::pg_catalog.text AS polwithcheck
10437WHERE false",
10438    access: vec![PUBLIC_SELECT],
10439});
10440
10441// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10442pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10443    name: "pg_inherits",
10444    schema: PG_CATALOG_SCHEMA,
10445    oid: oid::VIEW_PG_INHERITS_OID,
10446    desc: RelationDesc::builder()
10447        .with_column("inhrelid", SqlScalarType::Oid.nullable(false))
10448        .with_column("inhparent", SqlScalarType::Oid.nullable(false))
10449        .with_column("inhseqno", SqlScalarType::Int32.nullable(false))
10450        .with_column("inhdetachpending", SqlScalarType::Bool.nullable(false))
10451        .with_key(vec![])
10452        .finish(),
10453    column_comments: BTreeMap::new(),
10454    sql: "
10455SELECT
10456    NULL::pg_catalog.oid AS inhrelid,
10457    NULL::pg_catalog.oid AS inhparent,
10458    NULL::pg_catalog.int4 AS inhseqno,
10459    NULL::pg_catalog.bool AS inhdetachpending
10460WHERE false",
10461    access: vec![PUBLIC_SELECT],
10462});
10463
10464pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10465    name: "pg_locks",
10466    schema: PG_CATALOG_SCHEMA,
10467    oid: oid::VIEW_PG_LOCKS_OID,
10468    desc: RelationDesc::builder()
10469        .with_column("locktype", SqlScalarType::String.nullable(false))
10470        .with_column("database", SqlScalarType::Oid.nullable(false))
10471        .with_column("relation", SqlScalarType::Oid.nullable(false))
10472        .with_column("page", SqlScalarType::Int32.nullable(false))
10473        .with_column("tuple", SqlScalarType::Int16.nullable(false))
10474        .with_column("virtualxid", SqlScalarType::String.nullable(false))
10475        .with_column("transactionid", SqlScalarType::String.nullable(false))
10476        .with_column("classid", SqlScalarType::Oid.nullable(false))
10477        .with_column("objid", SqlScalarType::Oid.nullable(false))
10478        .with_column("objsubid", SqlScalarType::Int16.nullable(false))
10479        .with_column("virtualtransaction", SqlScalarType::String.nullable(false))
10480        .with_column("pid", SqlScalarType::Int32.nullable(false))
10481        .with_column("mode", SqlScalarType::String.nullable(false))
10482        .with_column("granted", SqlScalarType::Bool.nullable(false))
10483        .with_column("fastpath", SqlScalarType::Bool.nullable(false))
10484        .with_column(
10485            "waitstart",
10486            SqlScalarType::TimestampTz { precision: None }.nullable(false),
10487        )
10488        .with_key(vec![])
10489        .finish(),
10490    column_comments: BTreeMap::new(),
10491    sql: "
10492SELECT
10493-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10494    NULL::pg_catalog.text AS locktype,
10495    NULL::pg_catalog.oid AS database,
10496    NULL::pg_catalog.oid AS relation,
10497    NULL::pg_catalog.int4 AS page,
10498    NULL::pg_catalog.int2 AS tuple,
10499    NULL::pg_catalog.text AS virtualxid,
10500    NULL::pg_catalog.text AS transactionid,
10501    NULL::pg_catalog.oid AS classid,
10502    NULL::pg_catalog.oid AS objid,
10503    NULL::pg_catalog.int2 AS objsubid,
10504    NULL::pg_catalog.text AS virtualtransaction,
10505    NULL::pg_catalog.int4 AS pid,
10506    NULL::pg_catalog.text AS mode,
10507    NULL::pg_catalog.bool AS granted,
10508    NULL::pg_catalog.bool AS fastpath,
10509    NULL::pg_catalog.timestamptz AS waitstart
10510WHERE false",
10511    access: vec![PUBLIC_SELECT],
10512});
10513
10514/// Peeled version of `PG_AUTHID`: Excludes the columns rolcreaterole and rolcreatedb, to make this
10515/// view indexable.
10516pub static PG_AUTHID_CORE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10517    name: "pg_authid_core",
10518    schema: MZ_INTERNAL_SCHEMA,
10519    oid: oid::VIEW_PG_AUTHID_CORE_OID,
10520    desc: RelationDesc::builder()
10521        .with_column("oid", SqlScalarType::Oid.nullable(false))
10522        .with_column("rolname", SqlScalarType::String.nullable(false))
10523        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10524        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10525        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10526        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10527        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10528        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10529        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10530        .with_column(
10531            "rolvaliduntil",
10532            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10533        )
10534        .finish(),
10535    column_comments: BTreeMap::new(),
10536    sql: r#"
10537SELECT
10538    r.oid AS oid,
10539    r.name AS rolname,
10540    rolsuper,
10541    inherit AS rolinherit,
10542    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
10543    -- MZ doesn't support replication in the same way Postgres does
10544    false AS rolreplication,
10545    -- MZ doesn't how row level security
10546    false AS rolbypassrls,
10547    -- MZ doesn't have a connection limit
10548    -1 AS rolconnlimit,
10549    a.password_hash AS rolpassword,
10550    NULL::pg_catalog.timestamptz AS rolvaliduntil
10551FROM mz_catalog.mz_roles r
10552LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
10553    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10554});
10555
10556pub const PG_AUTHID_CORE_IND: BuiltinIndex = BuiltinIndex {
10557    name: "pg_authid_core_ind",
10558    schema: MZ_INTERNAL_SCHEMA,
10559    oid: oid::INDEX_PG_AUTHID_CORE_IND_OID,
10560    sql: "IN CLUSTER mz_catalog_server
10561ON mz_internal.pg_authid_core (rolname)",
10562    is_retained_metrics_object: false,
10563};
10564
10565pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10566    name: "pg_authid",
10567    schema: PG_CATALOG_SCHEMA,
10568    oid: oid::VIEW_PG_AUTHID_OID,
10569    desc: RelationDesc::builder()
10570        .with_column("oid", SqlScalarType::Oid.nullable(false))
10571        .with_column("rolname", SqlScalarType::String.nullable(false))
10572        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10573        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10574        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10575        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10576        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10577        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10578        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10579        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10580        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10581        .with_column(
10582            "rolvaliduntil",
10583            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10584        )
10585        .finish(),
10586    column_comments: BTreeMap::new(),
10587    // The `has_system_privilege` invocations for `rolcreaterole` and `rolcreatedb` get expanded
10588    // into very complex subqueries. If we put them into the SELECT clause directly, decorrelation
10589    // produces a very complex plan that the optimizer has a hard time dealing with. In particular,
10590    // the optimizer fails to reduce a query like `SELECT oid FROM pg_authid` to a simple lookup on
10591    // the `pg_authid_core` index and instead produces a large plan that contains a bunch of
10592    // expensive joins and arrangements.
10593    //
10594    // The proper fix is likely to implement `has_system_privileges` in Rust, but for now we work
10595    // around the issue by manually decorrelating `rolcreaterole` and `rolcreatedb`. Note that to
10596    // get the desired behavior we need to make sure that the join with `extra` doesn't change the
10597    // cardinality of `pg_authid_core` (otherwise it can never be optimized away). We ensure this
10598    // by:
10599    //  * using a `LEFT JOIN`, so the optimizer knows that left elements are never filtered
10600    //  * applying a `DISTINCT ON` to the CTE, so the optimizer knows that left elements are never
10601    //    duplicated
10602    sql: r#"
10603WITH extra AS (
10604    SELECT
10605        DISTINCT ON (oid)
10606        oid,
10607        mz_catalog.has_system_privilege(oid, 'CREATEROLE') AS rolcreaterole,
10608        mz_catalog.has_system_privilege(oid, 'CREATEDB') AS rolcreatedb
10609    FROM mz_internal.pg_authid_core
10610)
10611SELECT
10612    oid,
10613    rolname,
10614    rolsuper,
10615    rolinherit,
10616    extra.rolcreaterole,
10617    extra.rolcreatedb,
10618    rolcanlogin,
10619    rolreplication,
10620    rolbypassrls,
10621    rolconnlimit,
10622    rolpassword,
10623    rolvaliduntil
10624FROM mz_internal.pg_authid_core
10625LEFT JOIN extra USING (oid)"#,
10626    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10627});
10628
10629pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10630    name: "pg_aggregate",
10631    schema: PG_CATALOG_SCHEMA,
10632    oid: oid::VIEW_PG_AGGREGATE_OID,
10633    desc: RelationDesc::builder()
10634        .with_column("aggfnoid", SqlScalarType::Oid.nullable(false))
10635        .with_column("aggkind", SqlScalarType::String.nullable(false))
10636        .with_column("aggnumdirectargs", SqlScalarType::Int16.nullable(false))
10637        .with_column("aggtransfn", SqlScalarType::RegProc.nullable(true))
10638        .with_column("aggfinalfn", SqlScalarType::RegProc.nullable(false))
10639        .with_column("aggcombinefn", SqlScalarType::RegProc.nullable(false))
10640        .with_column("aggserialfn", SqlScalarType::RegProc.nullable(false))
10641        .with_column("aggdeserialfn", SqlScalarType::RegProc.nullable(false))
10642        .with_column("aggmtransfn", SqlScalarType::RegProc.nullable(false))
10643        .with_column("aggminvtransfn", SqlScalarType::RegProc.nullable(false))
10644        .with_column("aggmfinalfn", SqlScalarType::RegProc.nullable(false))
10645        .with_column("aggfinalextra", SqlScalarType::Bool.nullable(false))
10646        .with_column("aggmfinalextra", SqlScalarType::Bool.nullable(false))
10647        .with_column("aggfinalmodify", SqlScalarType::PgLegacyChar.nullable(true))
10648        .with_column(
10649            "aggmfinalmodify",
10650            SqlScalarType::PgLegacyChar.nullable(true),
10651        )
10652        .with_column("aggsortop", SqlScalarType::Oid.nullable(false))
10653        .with_column("aggtranstype", SqlScalarType::Oid.nullable(true))
10654        .with_column("aggtransspace", SqlScalarType::Int32.nullable(true))
10655        .with_column("aggmtranstype", SqlScalarType::Oid.nullable(false))
10656        .with_column("aggmtransspace", SqlScalarType::Int32.nullable(true))
10657        .with_column("agginitval", SqlScalarType::String.nullable(true))
10658        .with_column("aggminitval", SqlScalarType::String.nullable(true))
10659        .finish(),
10660    column_comments: BTreeMap::new(),
10661    sql: "SELECT
10662    a.oid as aggfnoid,
10663    -- Currently Materialize only support 'normal' aggregate functions.
10664    a.agg_kind as aggkind,
10665    a.agg_num_direct_args as aggnumdirectargs,
10666    -- Materialize doesn't support these fields.
10667    NULL::pg_catalog.regproc as aggtransfn,
10668    '0'::pg_catalog.regproc as aggfinalfn,
10669    '0'::pg_catalog.regproc as aggcombinefn,
10670    '0'::pg_catalog.regproc as aggserialfn,
10671    '0'::pg_catalog.regproc as aggdeserialfn,
10672    '0'::pg_catalog.regproc as aggmtransfn,
10673    '0'::pg_catalog.regproc as aggminvtransfn,
10674    '0'::pg_catalog.regproc as aggmfinalfn,
10675    false as aggfinalextra,
10676    false as aggmfinalextra,
10677    NULL::pg_catalog.\"char\" AS aggfinalmodify,
10678    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
10679    '0'::pg_catalog.oid as aggsortop,
10680    NULL::pg_catalog.oid as aggtranstype,
10681    NULL::pg_catalog.int4 as aggtransspace,
10682    '0'::pg_catalog.oid as aggmtranstype,
10683    NULL::pg_catalog.int4 as aggmtransspace,
10684    NULL::pg_catalog.text as agginitval,
10685    NULL::pg_catalog.text as aggminitval
10686FROM mz_internal.mz_aggregates a",
10687    access: vec![PUBLIC_SELECT],
10688});
10689
10690pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10691    name: "pg_trigger",
10692    schema: PG_CATALOG_SCHEMA,
10693    oid: oid::VIEW_PG_TRIGGER_OID,
10694    desc: RelationDesc::builder()
10695        .with_column("oid", SqlScalarType::Oid.nullable(false))
10696        .with_column("tgrelid", SqlScalarType::Oid.nullable(false))
10697        .with_column("tgparentid", SqlScalarType::Oid.nullable(false))
10698        .with_column("tgname", SqlScalarType::String.nullable(false))
10699        .with_column("tgfoid", SqlScalarType::Oid.nullable(false))
10700        .with_column("tgtype", SqlScalarType::Int16.nullable(false))
10701        .with_column("tgenabled", SqlScalarType::PgLegacyChar.nullable(false))
10702        .with_column("tgisinternal", SqlScalarType::Bool.nullable(false))
10703        .with_column("tgconstrrelid", SqlScalarType::Oid.nullable(false))
10704        .with_column("tgconstrindid", SqlScalarType::Oid.nullable(false))
10705        .with_column("tgconstraint", SqlScalarType::Oid.nullable(false))
10706        .with_column("tgdeferrable", SqlScalarType::Bool.nullable(false))
10707        .with_column("tginitdeferred", SqlScalarType::Bool.nullable(false))
10708        .with_column("tgnargs", SqlScalarType::Int16.nullable(false))
10709        .with_column("tgattr", SqlScalarType::Int2Vector.nullable(false))
10710        .with_column("tgargs", SqlScalarType::Bytes.nullable(false))
10711        .with_column("tgqual", SqlScalarType::String.nullable(false))
10712        .with_column("tgoldtable", SqlScalarType::String.nullable(false))
10713        .with_column("tgnewtable", SqlScalarType::String.nullable(false))
10714        .with_key(vec![])
10715        .finish(),
10716    column_comments: BTreeMap::new(),
10717    sql: "SELECT
10718    -- MZ doesn't support triggers so all of these fields are NULL.
10719    NULL::pg_catalog.oid AS oid,
10720    NULL::pg_catalog.oid AS tgrelid,
10721    NULL::pg_catalog.oid AS tgparentid,
10722    NULL::pg_catalog.text AS tgname,
10723    NULL::pg_catalog.oid AS tgfoid,
10724    NULL::pg_catalog.int2 AS tgtype,
10725    NULL::pg_catalog.\"char\" AS tgenabled,
10726    NULL::pg_catalog.bool AS tgisinternal,
10727    NULL::pg_catalog.oid AS tgconstrrelid,
10728    NULL::pg_catalog.oid AS tgconstrindid,
10729    NULL::pg_catalog.oid AS tgconstraint,
10730    NULL::pg_catalog.bool AS tgdeferrable,
10731    NULL::pg_catalog.bool AS tginitdeferred,
10732    NULL::pg_catalog.int2 AS tgnargs,
10733    NULL::pg_catalog.int2vector AS tgattr,
10734    NULL::pg_catalog.bytea AS tgargs,
10735    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
10736    -- uses text as a placeholder, so we'll follow their lead here.
10737    NULL::pg_catalog.text AS tgqual,
10738    NULL::pg_catalog.text AS tgoldtable,
10739    NULL::pg_catalog.text AS tgnewtable
10740WHERE false
10741    ",
10742    access: vec![PUBLIC_SELECT],
10743});
10744
10745pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10746    name: "pg_rewrite",
10747    schema: PG_CATALOG_SCHEMA,
10748    oid: oid::VIEW_PG_REWRITE_OID,
10749    desc: RelationDesc::builder()
10750        .with_column("oid", SqlScalarType::Oid.nullable(false))
10751        .with_column("rulename", SqlScalarType::String.nullable(false))
10752        .with_column("ev_class", SqlScalarType::Oid.nullable(false))
10753        .with_column("ev_type", SqlScalarType::PgLegacyChar.nullable(false))
10754        .with_column("ev_enabled", SqlScalarType::PgLegacyChar.nullable(false))
10755        .with_column("is_instead", SqlScalarType::Bool.nullable(false))
10756        .with_column("ev_qual", SqlScalarType::String.nullable(false))
10757        .with_column("ev_action", SqlScalarType::String.nullable(false))
10758        .with_key(vec![])
10759        .finish(),
10760    column_comments: BTreeMap::new(),
10761    sql: "SELECT
10762    -- MZ doesn't support rewrite rules so all of these fields are NULL.
10763    NULL::pg_catalog.oid AS oid,
10764    NULL::pg_catalog.text AS rulename,
10765    NULL::pg_catalog.oid AS ev_class,
10766    NULL::pg_catalog.\"char\" AS ev_type,
10767    NULL::pg_catalog.\"char\" AS ev_enabled,
10768    NULL::pg_catalog.bool AS is_instead,
10769    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
10770    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
10771    NULL::pg_catalog.text AS ev_qual,
10772    NULL::pg_catalog.text AS ev_action
10773WHERE false
10774    ",
10775    access: vec![PUBLIC_SELECT],
10776});
10777
10778pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10779    name: "pg_extension",
10780    schema: PG_CATALOG_SCHEMA,
10781    oid: oid::VIEW_PG_EXTENSION_OID,
10782    desc: RelationDesc::builder()
10783        .with_column("oid", SqlScalarType::Oid.nullable(false))
10784        .with_column("extname", SqlScalarType::String.nullable(false))
10785        .with_column("extowner", SqlScalarType::Oid.nullable(false))
10786        .with_column("extnamespace", SqlScalarType::Oid.nullable(false))
10787        .with_column("extrelocatable", SqlScalarType::Bool.nullable(false))
10788        .with_column("extversion", SqlScalarType::String.nullable(false))
10789        .with_column(
10790            "extconfig",
10791            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10792        )
10793        .with_column(
10794            "extcondition",
10795            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
10796        )
10797        .with_key(vec![])
10798        .finish(),
10799    column_comments: BTreeMap::new(),
10800    sql: "SELECT
10801    -- MZ doesn't support extensions so all of these fields are NULL.
10802    NULL::pg_catalog.oid AS oid,
10803    NULL::pg_catalog.text AS extname,
10804    NULL::pg_catalog.oid AS extowner,
10805    NULL::pg_catalog.oid AS extnamespace,
10806    NULL::pg_catalog.bool AS extrelocatable,
10807    NULL::pg_catalog.text AS extversion,
10808    NULL::pg_catalog.oid[] AS extconfig,
10809    NULL::pg_catalog.text[] AS extcondition
10810WHERE false
10811    ",
10812    access: vec![PUBLIC_SELECT],
10813});
10814
10815pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10816    name: "mz_show_all_objects",
10817    schema: MZ_INTERNAL_SCHEMA,
10818    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
10819    desc: RelationDesc::builder()
10820        .with_column("schema_id", SqlScalarType::String.nullable(false))
10821        .with_column("name", SqlScalarType::String.nullable(false))
10822        .with_column("type", SqlScalarType::String.nullable(false))
10823        .with_column("comment", SqlScalarType::String.nullable(false))
10824        .finish(),
10825    column_comments: BTreeMap::new(),
10826    sql: "WITH comments AS (
10827        SELECT id, object_type, comment
10828        FROM mz_internal.mz_comments
10829        WHERE object_sub_id IS NULL
10830    )
10831    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
10832    FROM mz_catalog.mz_objects AS objs
10833    LEFT JOIN comments ON objs.id = comments.id
10834    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
10835    access: vec![PUBLIC_SELECT],
10836});
10837
10838pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
10839    BuiltinView {
10840    name: "mz_show_clusters",
10841    schema: MZ_INTERNAL_SCHEMA,
10842    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
10843    desc: RelationDesc::builder()
10844        .with_column("name", SqlScalarType::String.nullable(false))
10845        .with_column("replicas", SqlScalarType::String.nullable(true))
10846        .with_column("comment", SqlScalarType::String.nullable(false))
10847        .finish(),
10848    column_comments: BTreeMap::new(),
10849    sql: "
10850    WITH clusters AS (
10851        SELECT
10852            mc.id,
10853            mc.name,
10854            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
10855        FROM mz_catalog.mz_clusters mc
10856        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
10857        ON mc.id = mcr.cluster_id
10858        GROUP BY mc.id, mc.name
10859    ),
10860    comments AS (
10861        SELECT id, comment
10862        FROM mz_internal.mz_comments
10863        WHERE object_type = 'cluster' AND object_sub_id IS NULL
10864    )
10865    SELECT name, replicas, COALESCE(comment, '') as comment
10866    FROM clusters
10867    LEFT JOIN comments ON clusters.id = comments.id",
10868    access: vec![PUBLIC_SELECT],
10869}
10870});
10871
10872pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10873    name: "mz_show_secrets",
10874    schema: MZ_INTERNAL_SCHEMA,
10875    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
10876    desc: RelationDesc::builder()
10877        .with_column("schema_id", SqlScalarType::String.nullable(false))
10878        .with_column("name", SqlScalarType::String.nullable(false))
10879        .with_column("comment", SqlScalarType::String.nullable(false))
10880        .finish(),
10881    column_comments: BTreeMap::new(),
10882    sql: "WITH comments AS (
10883        SELECT id, comment
10884        FROM mz_internal.mz_comments
10885        WHERE object_type = 'secret' AND object_sub_id IS NULL
10886    )
10887    SELECT schema_id, name, COALESCE(comment, '') as comment
10888    FROM mz_catalog.mz_secrets secrets
10889    LEFT JOIN comments ON secrets.id = comments.id",
10890    access: vec![PUBLIC_SELECT],
10891});
10892
10893pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10894    name: "mz_show_columns",
10895    schema: MZ_INTERNAL_SCHEMA,
10896    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
10897    desc: RelationDesc::builder()
10898        .with_column("id", SqlScalarType::String.nullable(false))
10899        .with_column("name", SqlScalarType::String.nullable(false))
10900        .with_column("nullable", SqlScalarType::Bool.nullable(false))
10901        .with_column("type", SqlScalarType::String.nullable(false))
10902        .with_column("position", SqlScalarType::UInt64.nullable(false))
10903        .with_column("comment", SqlScalarType::String.nullable(false))
10904        .finish(),
10905    column_comments: BTreeMap::new(),
10906    sql: "
10907    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
10908    FROM mz_catalog.mz_columns columns
10909    LEFT JOIN mz_internal.mz_comments comments
10910    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
10911    access: vec![PUBLIC_SELECT],
10912});
10913
10914pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10915    name: "mz_show_databases",
10916    schema: MZ_INTERNAL_SCHEMA,
10917    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
10918    desc: RelationDesc::builder()
10919        .with_column("name", SqlScalarType::String.nullable(false))
10920        .with_column("comment", SqlScalarType::String.nullable(false))
10921        .finish(),
10922    column_comments: BTreeMap::new(),
10923    sql: "WITH comments AS (
10924        SELECT id, comment
10925        FROM mz_internal.mz_comments
10926        WHERE object_type = 'database' AND object_sub_id IS NULL
10927    )
10928    SELECT name, COALESCE(comment, '') as comment
10929    FROM mz_catalog.mz_databases databases
10930    LEFT JOIN comments ON databases.id = comments.id",
10931    access: vec![PUBLIC_SELECT],
10932});
10933
10934pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10935    name: "mz_show_schemas",
10936    schema: MZ_INTERNAL_SCHEMA,
10937    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
10938    desc: RelationDesc::builder()
10939        .with_column("database_id", SqlScalarType::String.nullable(true))
10940        .with_column("name", SqlScalarType::String.nullable(false))
10941        .with_column("comment", SqlScalarType::String.nullable(false))
10942        .finish(),
10943    column_comments: BTreeMap::new(),
10944    sql: "WITH comments AS (
10945        SELECT id, comment
10946        FROM mz_internal.mz_comments
10947        WHERE object_type = 'schema' AND object_sub_id IS NULL
10948    )
10949    SELECT database_id, name, COALESCE(comment, '') as comment
10950    FROM mz_catalog.mz_schemas schemas
10951    LEFT JOIN comments ON schemas.id = comments.id",
10952    access: vec![PUBLIC_SELECT],
10953});
10954
10955pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10956    name: "mz_show_roles",
10957    schema: MZ_INTERNAL_SCHEMA,
10958    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
10959    desc: RelationDesc::builder()
10960        .with_column("name", SqlScalarType::String.nullable(false))
10961        .with_column("comment", SqlScalarType::String.nullable(false))
10962        .finish(),
10963    column_comments: BTreeMap::new(),
10964    sql: "WITH comments AS (
10965        SELECT id, comment
10966        FROM mz_internal.mz_comments
10967        WHERE object_type = 'role' AND object_sub_id IS NULL
10968    )
10969    SELECT name, COALESCE(comment, '') as comment
10970    FROM mz_catalog.mz_roles roles
10971    LEFT JOIN comments ON roles.id = comments.id
10972    WHERE roles.id NOT LIKE 's%'
10973      AND roles.id NOT LIKE 'g%'",
10974    access: vec![PUBLIC_SELECT],
10975});
10976
10977pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10978    name: "mz_show_tables",
10979    schema: MZ_INTERNAL_SCHEMA,
10980    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
10981    desc: RelationDesc::builder()
10982        .with_column("schema_id", SqlScalarType::String.nullable(false))
10983        .with_column("name", SqlScalarType::String.nullable(false))
10984        .with_column("comment", SqlScalarType::String.nullable(false))
10985        .with_column("source_id", SqlScalarType::String.nullable(true))
10986        .finish(),
10987    column_comments: BTreeMap::new(),
10988    sql: "WITH comments AS (
10989        SELECT id, comment
10990        FROM mz_internal.mz_comments
10991        WHERE object_type = 'table' AND object_sub_id IS NULL
10992    )
10993    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
10994    FROM mz_catalog.mz_tables tables
10995    LEFT JOIN comments ON tables.id = comments.id",
10996    access: vec![PUBLIC_SELECT],
10997});
10998
10999pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11000    name: "mz_show_views",
11001    schema: MZ_INTERNAL_SCHEMA,
11002    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
11003    desc: RelationDesc::builder()
11004        .with_column("schema_id", SqlScalarType::String.nullable(false))
11005        .with_column("name", SqlScalarType::String.nullable(false))
11006        .with_column("comment", SqlScalarType::String.nullable(false))
11007        .finish(),
11008    column_comments: BTreeMap::new(),
11009    sql: "WITH comments AS (
11010        SELECT id, comment
11011        FROM mz_internal.mz_comments
11012        WHERE object_type = 'view' AND object_sub_id IS NULL
11013    )
11014    SELECT schema_id, name, COALESCE(comment, '') as comment
11015    FROM mz_catalog.mz_views views
11016    LEFT JOIN comments ON views.id = comments.id",
11017    access: vec![PUBLIC_SELECT],
11018});
11019
11020pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11021    name: "mz_show_types",
11022    schema: MZ_INTERNAL_SCHEMA,
11023    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
11024    desc: RelationDesc::builder()
11025        .with_column("schema_id", SqlScalarType::String.nullable(false))
11026        .with_column("name", SqlScalarType::String.nullable(false))
11027        .with_column("comment", SqlScalarType::String.nullable(false))
11028        .finish(),
11029    column_comments: BTreeMap::new(),
11030    sql: "WITH comments AS (
11031        SELECT id, comment
11032        FROM mz_internal.mz_comments
11033        WHERE object_type = 'type' AND object_sub_id IS NULL
11034    )
11035    SELECT schema_id, name, COALESCE(comment, '') as comment
11036    FROM mz_catalog.mz_types types
11037    LEFT JOIN comments ON types.id = comments.id",
11038    access: vec![PUBLIC_SELECT],
11039});
11040
11041pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11042    name: "mz_show_connections",
11043    schema: MZ_INTERNAL_SCHEMA,
11044    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
11045    desc: RelationDesc::builder()
11046        .with_column("schema_id", SqlScalarType::String.nullable(false))
11047        .with_column("name", SqlScalarType::String.nullable(false))
11048        .with_column("type", SqlScalarType::String.nullable(false))
11049        .with_column("comment", SqlScalarType::String.nullable(false))
11050        .finish(),
11051    column_comments: BTreeMap::new(),
11052    sql: "WITH comments AS (
11053        SELECT id, comment
11054        FROM mz_internal.mz_comments
11055        WHERE object_type = 'connection' AND object_sub_id IS NULL
11056    )
11057    SELECT schema_id, name, type, COALESCE(comment, '') as comment
11058    FROM mz_catalog.mz_connections connections
11059    LEFT JOIN comments ON connections.id = comments.id",
11060    access: vec![PUBLIC_SELECT],
11061});
11062
11063pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11064    name: "mz_show_sources",
11065    schema: MZ_INTERNAL_SCHEMA,
11066    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
11067    desc: RelationDesc::builder()
11068        .with_column("id", SqlScalarType::String.nullable(false))
11069        .with_column("name", SqlScalarType::String.nullable(false))
11070        .with_column("type", SqlScalarType::String.nullable(false))
11071        .with_column("cluster", SqlScalarType::String.nullable(true))
11072        .with_column("schema_id", SqlScalarType::String.nullable(false))
11073        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11074        .with_column("comment", SqlScalarType::String.nullable(false))
11075        .finish(),
11076    column_comments: BTreeMap::new(),
11077    sql: "
11078WITH comments AS (
11079    SELECT id, comment
11080    FROM mz_internal.mz_comments
11081    WHERE object_type = 'source' AND object_sub_id IS NULL
11082)
11083SELECT
11084    sources.id,
11085    sources.name,
11086    sources.type,
11087    clusters.name AS cluster,
11088    schema_id,
11089    cluster_id,
11090    COALESCE(comments.comment, '') as comment
11091FROM
11092    mz_catalog.mz_sources AS sources
11093        LEFT JOIN
11094            mz_catalog.mz_clusters AS clusters
11095            ON clusters.id = sources.cluster_id
11096        LEFT JOIN comments ON sources.id = comments.id",
11097    access: vec![PUBLIC_SELECT],
11098});
11099
11100pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11101    name: "mz_show_sinks",
11102    schema: MZ_INTERNAL_SCHEMA,
11103    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11104    desc: RelationDesc::builder()
11105        .with_column("id", SqlScalarType::String.nullable(false))
11106        .with_column("name", SqlScalarType::String.nullable(false))
11107        .with_column("type", SqlScalarType::String.nullable(false))
11108        .with_column("cluster", SqlScalarType::String.nullable(false))
11109        .with_column("schema_id", SqlScalarType::String.nullable(false))
11110        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11111        .with_column("comment", SqlScalarType::String.nullable(false))
11112        .finish(),
11113    column_comments: BTreeMap::new(),
11114    sql: "
11115WITH comments AS (
11116    SELECT id, comment
11117    FROM mz_internal.mz_comments
11118    WHERE object_type = 'sink' AND object_sub_id IS NULL
11119)
11120SELECT
11121    sinks.id,
11122    sinks.name,
11123    sinks.type,
11124    clusters.name AS cluster,
11125    schema_id,
11126    cluster_id,
11127    COALESCE(comments.comment, '') as comment
11128FROM
11129    mz_catalog.mz_sinks AS sinks
11130    JOIN
11131        mz_catalog.mz_clusters AS clusters
11132        ON clusters.id = sinks.cluster_id
11133    LEFT JOIN comments ON sinks.id = comments.id",
11134    access: vec![PUBLIC_SELECT],
11135});
11136
11137pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11138    name: "mz_show_materialized_views",
11139    schema: MZ_INTERNAL_SCHEMA,
11140    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11141    desc: RelationDesc::builder()
11142        .with_column("id", SqlScalarType::String.nullable(false))
11143        .with_column("name", SqlScalarType::String.nullable(false))
11144        .with_column("cluster", SqlScalarType::String.nullable(false))
11145        .with_column("schema_id", SqlScalarType::String.nullable(false))
11146        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11147        .with_column("comment", SqlScalarType::String.nullable(false))
11148        .finish(),
11149    column_comments: BTreeMap::new(),
11150    sql: "
11151WITH
11152    comments AS (
11153        SELECT id, comment
11154        FROM mz_internal.mz_comments
11155        WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11156    )
11157SELECT
11158    mviews.id as id,
11159    mviews.name,
11160    clusters.name AS cluster,
11161    schema_id,
11162    cluster_id,
11163    COALESCE(comments.comment, '') as comment
11164FROM
11165    mz_catalog.mz_materialized_views AS mviews
11166    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11167    LEFT JOIN comments ON mviews.id = comments.id",
11168    access: vec![PUBLIC_SELECT],
11169});
11170
11171pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11172    name: "mz_show_indexes",
11173    schema: MZ_INTERNAL_SCHEMA,
11174    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11175    desc: RelationDesc::builder()
11176        .with_column("id", SqlScalarType::String.nullable(false))
11177        .with_column("name", SqlScalarType::String.nullable(false))
11178        .with_column("on", SqlScalarType::String.nullable(false))
11179        .with_column("cluster", SqlScalarType::String.nullable(false))
11180        .with_column(
11181            "key",
11182            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11183        )
11184        .with_column("on_id", SqlScalarType::String.nullable(false))
11185        .with_column("schema_id", SqlScalarType::String.nullable(false))
11186        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11187        .with_column("comment", SqlScalarType::String.nullable(false))
11188        .finish(),
11189    column_comments: BTreeMap::new(),
11190    sql: "
11191WITH comments AS (
11192    SELECT id, comment
11193    FROM mz_internal.mz_comments
11194    WHERE object_type = 'index' AND object_sub_id IS NULL
11195)
11196SELECT
11197    idxs.id AS id,
11198    idxs.name AS name,
11199    objs.name AS on,
11200    clusters.name AS cluster,
11201    COALESCE(keys.key, '{}'::_text) AS key,
11202    idxs.on_id AS on_id,
11203    objs.schema_id AS schema_id,
11204    clusters.id AS cluster_id,
11205    COALESCE(comments.comment, '') as comment
11206FROM
11207    mz_catalog.mz_indexes AS idxs
11208    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11209    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11210    LEFT JOIN
11211        (SELECT
11212            idxs.id,
11213            ARRAY_AGG(
11214                CASE
11215                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11216                    ELSE idx_cols.on_expression
11217                END
11218                ORDER BY idx_cols.index_position ASC
11219            ) AS key
11220        FROM
11221            mz_catalog.mz_indexes AS idxs
11222            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11223            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11224                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11225        GROUP BY idxs.id) AS keys
11226    ON idxs.id = keys.id
11227    LEFT JOIN comments ON idxs.id = comments.id",
11228    access: vec![PUBLIC_SELECT],
11229});
11230
11231pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11232    name: "mz_show_cluster_replicas",
11233    schema: MZ_INTERNAL_SCHEMA,
11234    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11235    desc: RelationDesc::builder()
11236        .with_column("cluster", SqlScalarType::String.nullable(false))
11237        .with_column("replica", SqlScalarType::String.nullable(false))
11238        .with_column("replica_id", SqlScalarType::String.nullable(false))
11239        .with_column("size", SqlScalarType::String.nullable(true))
11240        .with_column("ready", SqlScalarType::Bool.nullable(false))
11241        .with_column("comment", SqlScalarType::String.nullable(false))
11242        .finish(),
11243    column_comments: BTreeMap::new(),
11244    sql: r#"SELECT
11245    mz_catalog.mz_clusters.name AS cluster,
11246    mz_catalog.mz_cluster_replicas.name AS replica,
11247    mz_catalog.mz_cluster_replicas.id as replica_id,
11248    mz_catalog.mz_cluster_replicas.size AS size,
11249    coalesce(statuses.ready, FALSE) AS ready,
11250    coalesce(comments.comment, '') as comment
11251FROM
11252    mz_catalog.mz_cluster_replicas
11253        JOIN mz_catalog.mz_clusters
11254            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11255        LEFT JOIN
11256            (
11257                SELECT
11258                    replica_id,
11259                    bool_and(hydrated) AS ready
11260                FROM mz_internal.mz_hydration_statuses
11261                WHERE replica_id is not null
11262                GROUP BY replica_id
11263            ) AS statuses
11264            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11265        LEFT JOIN mz_internal.mz_comments comments
11266            ON mz_catalog.mz_cluster_replicas.id = comments.id
11267WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11268ORDER BY 1, 2"#,
11269    access: vec![PUBLIC_SELECT],
11270});
11271
11272pub static MZ_SHOW_CONTINUAL_TASKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11273    name: "mz_show_continual_tasks",
11274    schema: MZ_INTERNAL_SCHEMA,
11275    oid: oid::VIEW_MZ_SHOW_CONTINUAL_TASKS_OID,
11276    desc: RelationDesc::builder()
11277        .with_column("id", SqlScalarType::String.nullable(false))
11278        .with_column("name", SqlScalarType::String.nullable(false))
11279        .with_column("cluster", SqlScalarType::String.nullable(false))
11280        .with_column("schema_id", SqlScalarType::String.nullable(false))
11281        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11282        .with_column("comment", SqlScalarType::String.nullable(false))
11283        .finish(),
11284    column_comments: BTreeMap::new(),
11285    sql: "
11286WITH comments AS (
11287    SELECT id, comment
11288    FROM mz_internal.mz_comments
11289    WHERE object_type = 'continual-task' AND object_sub_id IS NULL
11290)
11291SELECT
11292    cts.id as id,
11293    cts.name,
11294    clusters.name AS cluster,
11295    schema_id,
11296    cluster_id,
11297    COALESCE(comments.comment, '') as comment
11298FROM
11299    mz_internal.mz_continual_tasks AS cts
11300    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = cts.cluster_id
11301    LEFT JOIN comments ON cts.id = comments.id",
11302    access: vec![PUBLIC_SELECT],
11303});
11304
11305pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11306    name: "mz_show_role_members",
11307    schema: MZ_INTERNAL_SCHEMA,
11308    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11309    desc: RelationDesc::builder()
11310        .with_column("role", SqlScalarType::String.nullable(false))
11311        .with_column("member", SqlScalarType::String.nullable(false))
11312        .with_column("grantor", SqlScalarType::String.nullable(false))
11313        .finish(),
11314    column_comments: BTreeMap::from_iter([
11315        ("role", "The role that `member` is a member of."),
11316        ("member", "The role that is a member of `role`."),
11317        (
11318            "grantor",
11319            "The role that granted membership of `member` to `role`.",
11320        ),
11321    ]),
11322    sql: r#"SELECT
11323    r1.name AS role,
11324    r2.name AS member,
11325    r3.name AS grantor
11326FROM mz_catalog.mz_role_members rm
11327JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11328JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11329JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11330ORDER BY role"#,
11331    access: vec![PUBLIC_SELECT],
11332});
11333
11334pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11335    name: "mz_show_my_role_members",
11336    schema: MZ_INTERNAL_SCHEMA,
11337    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11338    desc: RelationDesc::builder()
11339        .with_column("role", SqlScalarType::String.nullable(false))
11340        .with_column("member", SqlScalarType::String.nullable(false))
11341        .with_column("grantor", SqlScalarType::String.nullable(false))
11342        .finish(),
11343    column_comments: BTreeMap::from_iter([
11344        ("role", "The role that `member` is a member of."),
11345        ("member", "The role that is a member of `role`."),
11346        (
11347            "grantor",
11348            "The role that granted membership of `member` to `role`.",
11349        ),
11350    ]),
11351    sql: r#"SELECT role, member, grantor
11352FROM mz_internal.mz_show_role_members
11353WHERE pg_has_role(member, 'USAGE')"#,
11354    access: vec![PUBLIC_SELECT],
11355});
11356
11357pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11358    name: "mz_show_system_privileges",
11359    schema: MZ_INTERNAL_SCHEMA,
11360    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11361    desc: RelationDesc::builder()
11362        .with_column("grantor", SqlScalarType::String.nullable(true))
11363        .with_column("grantee", SqlScalarType::String.nullable(true))
11364        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11365        .finish(),
11366    column_comments: BTreeMap::from_iter([
11367        ("grantor", "The role that granted the privilege."),
11368        ("grantee", "The role that the privilege was granted to."),
11369        ("privilege_type", "They type of privilege granted."),
11370    ]),
11371    sql: r#"SELECT
11372    grantor.name AS grantor,
11373    CASE privileges.grantee
11374        WHEN 'p' THEN 'PUBLIC'
11375        ELSE grantee.name
11376    END AS grantee,
11377    privileges.privilege_type AS privilege_type
11378FROM
11379    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11380    FROM mz_catalog.mz_system_privileges) AS privileges
11381LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11382LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11383WHERE privileges.grantee NOT LIKE 's%'"#,
11384    access: vec![PUBLIC_SELECT],
11385});
11386
11387pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11388    name: "mz_show_my_system_privileges",
11389    schema: MZ_INTERNAL_SCHEMA,
11390    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11391    desc: RelationDesc::builder()
11392        .with_column("grantor", SqlScalarType::String.nullable(true))
11393        .with_column("grantee", SqlScalarType::String.nullable(true))
11394        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11395        .finish(),
11396    column_comments: BTreeMap::from_iter([
11397        ("grantor", "The role that granted the privilege."),
11398        ("grantee", "The role that the privilege was granted to."),
11399        ("privilege_type", "They type of privilege granted."),
11400    ]),
11401    sql: r#"SELECT grantor, grantee, privilege_type
11402FROM mz_internal.mz_show_system_privileges
11403WHERE
11404    CASE
11405        WHEN grantee = 'PUBLIC' THEN true
11406        ELSE pg_has_role(grantee, 'USAGE')
11407    END"#,
11408    access: vec![PUBLIC_SELECT],
11409});
11410
11411pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11412    name: "mz_show_cluster_privileges",
11413    schema: MZ_INTERNAL_SCHEMA,
11414    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11415    desc: RelationDesc::builder()
11416        .with_column("grantor", SqlScalarType::String.nullable(true))
11417        .with_column("grantee", SqlScalarType::String.nullable(true))
11418        .with_column("name", SqlScalarType::String.nullable(false))
11419        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11420        .finish(),
11421    column_comments: BTreeMap::from_iter([
11422        ("grantor", "The role that granted the privilege."),
11423        ("grantee", "The role that the privilege was granted to."),
11424        ("name", "The name of the cluster."),
11425        ("privilege_type", "They type of privilege granted."),
11426    ]),
11427    sql: r#"SELECT
11428    grantor.name AS grantor,
11429    CASE privileges.grantee
11430        WHEN 'p' THEN 'PUBLIC'
11431        ELSE grantee.name
11432    END AS grantee,
11433    privileges.name AS name,
11434    privileges.privilege_type AS privilege_type
11435FROM
11436    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11437    FROM mz_catalog.mz_clusters
11438    WHERE id NOT LIKE 's%') AS privileges
11439LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11440LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11441WHERE privileges.grantee NOT LIKE 's%'"#,
11442    access: vec![PUBLIC_SELECT],
11443});
11444
11445pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11446    name: "mz_show_my_cluster_privileges",
11447    schema: MZ_INTERNAL_SCHEMA,
11448    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11449    desc: RelationDesc::builder()
11450        .with_column("grantor", SqlScalarType::String.nullable(true))
11451        .with_column("grantee", SqlScalarType::String.nullable(true))
11452        .with_column("name", SqlScalarType::String.nullable(false))
11453        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11454        .finish(),
11455    column_comments: BTreeMap::from_iter([
11456        ("grantor", "The role that granted the privilege."),
11457        ("grantee", "The role that the privilege was granted to."),
11458        ("name", "The name of the cluster."),
11459        ("privilege_type", "They type of privilege granted."),
11460    ]),
11461    sql: r#"SELECT grantor, grantee, name, privilege_type
11462FROM mz_internal.mz_show_cluster_privileges
11463WHERE
11464    CASE
11465        WHEN grantee = 'PUBLIC' THEN true
11466        ELSE pg_has_role(grantee, 'USAGE')
11467    END"#,
11468    access: vec![PUBLIC_SELECT],
11469});
11470
11471pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11472    name: "mz_show_database_privileges",
11473    schema: MZ_INTERNAL_SCHEMA,
11474    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
11475    desc: RelationDesc::builder()
11476        .with_column("grantor", SqlScalarType::String.nullable(true))
11477        .with_column("grantee", SqlScalarType::String.nullable(true))
11478        .with_column("name", SqlScalarType::String.nullable(false))
11479        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11480        .finish(),
11481    column_comments: BTreeMap::from_iter([
11482        ("grantor", "The role that granted the privilege."),
11483        ("grantee", "The role that the privilege was granted to."),
11484        ("name", "The name of the database."),
11485        ("privilege_type", "They type of privilege granted."),
11486    ]),
11487    sql: r#"SELECT
11488    grantor.name AS grantor,
11489    CASE privileges.grantee
11490        WHEN 'p' THEN 'PUBLIC'
11491        ELSE grantee.name
11492    END AS grantee,
11493    privileges.name AS name,
11494    privileges.privilege_type AS privilege_type
11495FROM
11496    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11497    FROM mz_catalog.mz_databases
11498    WHERE id NOT LIKE 's%') AS privileges
11499LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11500LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11501WHERE privileges.grantee NOT LIKE 's%'"#,
11502    access: vec![PUBLIC_SELECT],
11503});
11504
11505pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11506    name: "mz_show_my_database_privileges",
11507    schema: MZ_INTERNAL_SCHEMA,
11508    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
11509    desc: RelationDesc::builder()
11510        .with_column("grantor", SqlScalarType::String.nullable(true))
11511        .with_column("grantee", SqlScalarType::String.nullable(true))
11512        .with_column("name", SqlScalarType::String.nullable(false))
11513        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11514        .finish(),
11515    column_comments: BTreeMap::from_iter([
11516        ("grantor", "The role that granted the privilege."),
11517        ("grantee", "The role that the privilege was granted to."),
11518        ("name", "The name of the cluster."),
11519        ("privilege_type", "They type of privilege granted."),
11520    ]),
11521    sql: r#"SELECT grantor, grantee, name, privilege_type
11522FROM mz_internal.mz_show_database_privileges
11523WHERE
11524    CASE
11525        WHEN grantee = 'PUBLIC' THEN true
11526        ELSE pg_has_role(grantee, 'USAGE')
11527    END"#,
11528    access: vec![PUBLIC_SELECT],
11529});
11530
11531pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11532    name: "mz_show_schema_privileges",
11533    schema: MZ_INTERNAL_SCHEMA,
11534    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
11535    desc: RelationDesc::builder()
11536        .with_column("grantor", SqlScalarType::String.nullable(true))
11537        .with_column("grantee", SqlScalarType::String.nullable(true))
11538        .with_column("database", SqlScalarType::String.nullable(true))
11539        .with_column("name", SqlScalarType::String.nullable(false))
11540        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11541        .finish(),
11542    column_comments: BTreeMap::from_iter([
11543        ("grantor", "The role that granted the privilege."),
11544        ("grantee", "The role that the privilege was granted to."),
11545        (
11546            "database",
11547            "The name of the database containing the schema.",
11548        ),
11549        ("name", "The name of the schema."),
11550        ("privilege_type", "They type of privilege granted."),
11551    ]),
11552    sql: r#"SELECT
11553    grantor.name AS grantor,
11554    CASE privileges.grantee
11555        WHEN 'p' THEN 'PUBLIC'
11556        ELSE grantee.name
11557    END AS grantee,
11558    databases.name AS database,
11559    privileges.name AS name,
11560    privileges.privilege_type AS privilege_type
11561FROM
11562    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
11563    FROM mz_catalog.mz_schemas
11564    WHERE id NOT LIKE 's%') AS privileges
11565LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11566LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11567LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
11568WHERE privileges.grantee NOT LIKE 's%'"#,
11569    access: vec![PUBLIC_SELECT],
11570});
11571
11572pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11573    name: "mz_show_my_schema_privileges",
11574    schema: MZ_INTERNAL_SCHEMA,
11575    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
11576    desc: RelationDesc::builder()
11577        .with_column("grantor", SqlScalarType::String.nullable(true))
11578        .with_column("grantee", SqlScalarType::String.nullable(true))
11579        .with_column("database", SqlScalarType::String.nullable(true))
11580        .with_column("name", SqlScalarType::String.nullable(false))
11581        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11582        .finish(),
11583    column_comments: BTreeMap::from_iter([
11584        ("grantor", "The role that granted the privilege."),
11585        ("grantee", "The role that the privilege was granted to."),
11586        (
11587            "database",
11588            "The name of the database containing the schema.",
11589        ),
11590        ("name", "The name of the schema."),
11591        ("privilege_type", "They type of privilege granted."),
11592    ]),
11593    sql: r#"SELECT grantor, grantee, database, name, privilege_type
11594FROM mz_internal.mz_show_schema_privileges
11595WHERE
11596    CASE
11597        WHEN grantee = 'PUBLIC' THEN true
11598        ELSE pg_has_role(grantee, 'USAGE')
11599    END"#,
11600    access: vec![PUBLIC_SELECT],
11601});
11602
11603pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11604    name: "mz_show_object_privileges",
11605    schema: MZ_INTERNAL_SCHEMA,
11606    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
11607    desc: RelationDesc::builder()
11608        .with_column("grantor", SqlScalarType::String.nullable(true))
11609        .with_column("grantee", SqlScalarType::String.nullable(true))
11610        .with_column("database", SqlScalarType::String.nullable(true))
11611        .with_column("schema", SqlScalarType::String.nullable(true))
11612        .with_column("name", SqlScalarType::String.nullable(false))
11613        .with_column("object_type", SqlScalarType::String.nullable(false))
11614        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11615        .finish(),
11616    column_comments: BTreeMap::from_iter([
11617        ("grantor", "The role that granted the privilege."),
11618        ("grantee", "The role that the privilege was granted to."),
11619        (
11620            "database",
11621            "The name of the database containing the object.",
11622        ),
11623        ("schema", "The name of the schema containing the object."),
11624        ("name", "The name of the object."),
11625        (
11626            "object_type",
11627            "The type of object the privilege is granted on.",
11628        ),
11629        ("privilege_type", "They type of privilege granted."),
11630    ]),
11631    sql: r#"SELECT
11632    grantor.name AS grantor,
11633    CASE privileges.grantee
11634            WHEN 'p' THEN 'PUBLIC'
11635            ELSE grantee.name
11636        END AS grantee,
11637    databases.name AS database,
11638    schemas.name AS schema,
11639    privileges.name AS name,
11640    privileges.type AS object_type,
11641    privileges.privilege_type AS privilege_type
11642FROM
11643    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
11644    FROM mz_catalog.mz_objects
11645    WHERE id NOT LIKE 's%') AS privileges
11646LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11647LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11648LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
11649LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
11650WHERE privileges.grantee NOT LIKE 's%'"#,
11651    access: vec![PUBLIC_SELECT],
11652});
11653
11654pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11655    name: "mz_show_my_object_privileges",
11656    schema: MZ_INTERNAL_SCHEMA,
11657    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
11658    desc: RelationDesc::builder()
11659        .with_column("grantor", SqlScalarType::String.nullable(true))
11660        .with_column("grantee", SqlScalarType::String.nullable(true))
11661        .with_column("database", SqlScalarType::String.nullable(true))
11662        .with_column("schema", SqlScalarType::String.nullable(true))
11663        .with_column("name", SqlScalarType::String.nullable(false))
11664        .with_column("object_type", SqlScalarType::String.nullable(false))
11665        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11666        .finish(),
11667    column_comments: BTreeMap::from_iter([
11668        ("grantor", "The role that granted the privilege."),
11669        ("grantee", "The role that the privilege was granted to."),
11670        (
11671            "database",
11672            "The name of the database containing the object.",
11673        ),
11674        ("schema", "The name of the schema containing the object."),
11675        ("name", "The name of the object."),
11676        (
11677            "object_type",
11678            "The type of object the privilege is granted on.",
11679        ),
11680        ("privilege_type", "They type of privilege granted."),
11681    ]),
11682    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11683FROM mz_internal.mz_show_object_privileges
11684WHERE
11685    CASE
11686        WHEN grantee = 'PUBLIC' THEN true
11687        ELSE pg_has_role(grantee, 'USAGE')
11688    END"#,
11689    access: vec![PUBLIC_SELECT],
11690});
11691
11692pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11693    name: "mz_show_all_privileges",
11694    schema: MZ_INTERNAL_SCHEMA,
11695    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
11696    desc: RelationDesc::builder()
11697        .with_column("grantor", SqlScalarType::String.nullable(true))
11698        .with_column("grantee", SqlScalarType::String.nullable(true))
11699        .with_column("database", SqlScalarType::String.nullable(true))
11700        .with_column("schema", SqlScalarType::String.nullable(true))
11701        .with_column("name", SqlScalarType::String.nullable(true))
11702        .with_column("object_type", SqlScalarType::String.nullable(false))
11703        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11704        .finish(),
11705    column_comments: BTreeMap::from_iter([
11706        ("grantor", "The role that granted the privilege."),
11707        ("grantee", "The role that the privilege was granted to."),
11708        (
11709            "database",
11710            "The name of the database containing the object.",
11711        ),
11712        ("schema", "The name of the schema containing the object."),
11713        ("name", "The name of the privilege target."),
11714        (
11715            "object_type",
11716            "The type of object the privilege is granted on.",
11717        ),
11718        ("privilege_type", "They type of privilege granted."),
11719    ]),
11720    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
11721FROM mz_internal.mz_show_system_privileges
11722UNION ALL
11723SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
11724FROM mz_internal.mz_show_cluster_privileges
11725UNION ALL
11726SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
11727FROM mz_internal.mz_show_database_privileges
11728UNION ALL
11729SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
11730FROM mz_internal.mz_show_schema_privileges
11731UNION ALL
11732SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11733FROM mz_internal.mz_show_object_privileges"#,
11734    access: vec![PUBLIC_SELECT],
11735});
11736
11737pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11738    name: "mz_show_all_my_privileges",
11739    schema: MZ_INTERNAL_SCHEMA,
11740    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
11741    desc: RelationDesc::builder()
11742        .with_column("grantor", SqlScalarType::String.nullable(true))
11743        .with_column("grantee", SqlScalarType::String.nullable(true))
11744        .with_column("database", SqlScalarType::String.nullable(true))
11745        .with_column("schema", SqlScalarType::String.nullable(true))
11746        .with_column("name", SqlScalarType::String.nullable(true))
11747        .with_column("object_type", SqlScalarType::String.nullable(false))
11748        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11749        .finish(),
11750    column_comments: BTreeMap::from_iter([
11751        ("grantor", "The role that granted the privilege."),
11752        ("grantee", "The role that the privilege was granted to."),
11753        (
11754            "database",
11755            "The name of the database containing the object.",
11756        ),
11757        ("schema", "The name of the schema containing the object."),
11758        ("name", "The name of the privilege target."),
11759        (
11760            "object_type",
11761            "The type of object the privilege is granted on.",
11762        ),
11763        ("privilege_type", "They type of privilege granted."),
11764    ]),
11765    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11766FROM mz_internal.mz_show_all_privileges
11767WHERE
11768    CASE
11769        WHEN grantee = 'PUBLIC' THEN true
11770        ELSE pg_has_role(grantee, 'USAGE')
11771    END"#,
11772    access: vec![PUBLIC_SELECT],
11773});
11774
11775pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11776    name: "mz_show_default_privileges",
11777    schema: MZ_INTERNAL_SCHEMA,
11778    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
11779    desc: RelationDesc::builder()
11780        .with_column("object_owner", SqlScalarType::String.nullable(true))
11781        .with_column("database", SqlScalarType::String.nullable(true))
11782        .with_column("schema", SqlScalarType::String.nullable(true))
11783        .with_column("object_type", SqlScalarType::String.nullable(false))
11784        .with_column("grantee", SqlScalarType::String.nullable(true))
11785        .with_column("privilege_type", SqlScalarType::String.nullable(true))
11786        .finish(),
11787    column_comments: BTreeMap::from_iter([
11788        (
11789            "object_owner",
11790            "Privileges described in this row will be granted on objects created by `object_owner`.",
11791        ),
11792        (
11793            "database",
11794            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11795        ),
11796        (
11797            "schema",
11798            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11799        ),
11800        (
11801            "object_type",
11802            "Privileges described in this row will be granted only on objects of type `object_type`.",
11803        ),
11804        (
11805            "grantee",
11806            "Privileges described in this row will be granted to `grantee`.",
11807        ),
11808        ("privilege_type", "They type of privilege to be granted."),
11809    ]),
11810    sql: r#"SELECT
11811    CASE defaults.role_id
11812        WHEN 'p' THEN 'PUBLIC'
11813        ELSE object_owner.name
11814    END AS object_owner,
11815    databases.name AS database,
11816    schemas.name AS schema,
11817    object_type,
11818    CASE defaults.grantee
11819        WHEN 'p' THEN 'PUBLIC'
11820        ELSE grantee.name
11821    END AS grantee,
11822    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
11823FROM mz_catalog.mz_default_privileges defaults
11824LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
11825LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
11826LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
11827LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
11828WHERE defaults.grantee NOT LIKE 's%'
11829    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
11830    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
11831    access: vec![PUBLIC_SELECT],
11832});
11833
11834pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11835    name: "mz_show_my_default_privileges",
11836    schema: MZ_INTERNAL_SCHEMA,
11837    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
11838    desc: RelationDesc::builder()
11839        .with_column("object_owner", SqlScalarType::String.nullable(true))
11840        .with_column("database", SqlScalarType::String.nullable(true))
11841        .with_column("schema", SqlScalarType::String.nullable(true))
11842        .with_column("object_type", SqlScalarType::String.nullable(false))
11843        .with_column("grantee", SqlScalarType::String.nullable(true))
11844        .with_column("privilege_type", SqlScalarType::String.nullable(true))
11845        .finish(),
11846    column_comments: BTreeMap::from_iter([
11847        (
11848            "object_owner",
11849            "Privileges described in this row will be granted on objects created by `object_owner`.",
11850        ),
11851        (
11852            "database",
11853            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11854        ),
11855        (
11856            "schema",
11857            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11858        ),
11859        (
11860            "object_type",
11861            "Privileges described in this row will be granted only on objects of type `object_type`.",
11862        ),
11863        (
11864            "grantee",
11865            "Privileges described in this row will be granted to `grantee`.",
11866        ),
11867        ("privilege_type", "They type of privilege to be granted."),
11868    ]),
11869    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
11870FROM mz_internal.mz_show_default_privileges
11871WHERE
11872    CASE
11873        WHEN grantee = 'PUBLIC' THEN true
11874        ELSE pg_has_role(grantee, 'USAGE')
11875    END"#,
11876    access: vec![PUBLIC_SELECT],
11877});
11878
11879pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11880    name: "mz_show_network_policies",
11881    schema: MZ_INTERNAL_SCHEMA,
11882    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
11883    desc: RelationDesc::builder()
11884        .with_column("name", SqlScalarType::String.nullable(false))
11885        .with_column("rules", SqlScalarType::String.nullable(true))
11886        .with_column("comment", SqlScalarType::String.nullable(false))
11887        .finish(),
11888    column_comments: BTreeMap::new(),
11889    sql: "
11890WITH comments AS (
11891    SELECT id, comment
11892    FROM mz_internal.mz_comments
11893    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
11894)
11895SELECT
11896    policy.name,
11897    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
11898    COALESCE(comment, '') as comment
11899FROM
11900    mz_internal.mz_network_policies as policy
11901LEFT JOIN
11902    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
11903LEFT JOIN
11904    comments ON policy.id = comments.id
11905WHERE
11906    policy.id NOT LIKE 's%'
11907AND
11908    policy.id NOT LIKE 'g%'
11909GROUP BY policy.name, comments.comment;",
11910    access: vec![PUBLIC_SELECT],
11911});
11912
11913pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11914    name: "mz_cluster_replica_history",
11915    schema: MZ_INTERNAL_SCHEMA,
11916    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
11917    desc: RelationDesc::builder()
11918        .with_column("replica_id", SqlScalarType::String.nullable(true))
11919        .with_column("size", SqlScalarType::String.nullable(true))
11920        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11921        .with_column("cluster_name", SqlScalarType::String.nullable(true))
11922        .with_column("replica_name", SqlScalarType::String.nullable(true))
11923        .with_column(
11924            "created_at",
11925            SqlScalarType::TimestampTz { precision: None }.nullable(false),
11926        )
11927        .with_column(
11928            "dropped_at",
11929            SqlScalarType::TimestampTz { precision: None }.nullable(true),
11930        )
11931        .with_column(
11932            "credits_per_hour",
11933            SqlScalarType::Numeric { max_scale: None }.nullable(true),
11934        )
11935        .finish(),
11936    column_comments: BTreeMap::from_iter([
11937        ("replica_id", "The ID of a cluster replica."),
11938        (
11939            "size",
11940            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
11941        ),
11942        (
11943            "cluster_id",
11944            "The ID of the cluster associated with the replica.",
11945        ),
11946        (
11947            "cluster_name",
11948            "The name of the cluster associated with the replica.",
11949        ),
11950        ("replica_name", "The name of the replica."),
11951        ("created_at", "The time at which the replica was created."),
11952        (
11953            "dropped_at",
11954            "The time at which the replica was dropped, or `NULL` if it still exists.",
11955        ),
11956        (
11957            "credits_per_hour",
11958            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
11959        ),
11960    ]),
11961    sql: r#"
11962        WITH
11963            creates AS
11964            (
11965                SELECT
11966                    details ->> 'logical_size' AS size,
11967                    details ->> 'replica_id' AS replica_id,
11968                    details ->> 'replica_name' AS replica_name,
11969                    details ->> 'cluster_name' AS cluster_name,
11970                    details ->> 'cluster_id' AS cluster_id,
11971                    occurred_at
11972                FROM mz_catalog.mz_audit_events
11973                WHERE
11974                    object_type = 'cluster-replica' AND event_type = 'create'
11975                        AND
11976                    details ->> 'replica_id' IS NOT NULL
11977                        AND
11978                    details ->> 'cluster_id' !~~ 's%'
11979            ),
11980            drops AS
11981            (
11982                SELECT details ->> 'replica_id' AS replica_id, occurred_at
11983                FROM mz_catalog.mz_audit_events
11984                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
11985            )
11986        SELECT
11987            creates.replica_id,
11988            creates.size,
11989            creates.cluster_id,
11990            creates.cluster_name,
11991            creates.replica_name,
11992            creates.occurred_at AS created_at,
11993            drops.occurred_at AS dropped_at,
11994            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
11995        FROM
11996            creates
11997                LEFT JOIN drops ON creates.replica_id = drops.replica_id
11998                LEFT JOIN
11999                    mz_catalog.mz_cluster_replica_sizes
12000                    ON mz_cluster_replica_sizes.size = creates.size"#,
12001    access: vec![PUBLIC_SELECT],
12002});
12003
12004pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12005    name: "mz_cluster_replica_name_history",
12006    schema: MZ_INTERNAL_SCHEMA,
12007    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
12008    desc: RelationDesc::builder()
12009        .with_column(
12010            "occurred_at",
12011            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12012        )
12013        .with_column("id", SqlScalarType::String.nullable(true))
12014        .with_column("previous_name", SqlScalarType::String.nullable(true))
12015        .with_column("new_name", SqlScalarType::String.nullable(true))
12016        .finish(),
12017    column_comments: BTreeMap::from_iter([
12018        (
12019            "occurred_at",
12020            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
12021        ),
12022        ("id", "The ID of the cluster replica."),
12023        (
12024            "previous_name",
12025            "The previous name of the cluster replica. `NULL` if there was no previous name.",
12026        ),
12027        ("new_name", "The new name of the cluster replica."),
12028    ]),
12029    sql: r#"WITH user_replica_alter_history AS (
12030  SELECT occurred_at,
12031    audit_events.details->>'replica_id' AS id,
12032    audit_events.details->>'old_name' AS previous_name,
12033    audit_events.details->>'new_name' AS new_name
12034  FROM mz_catalog.mz_audit_events AS audit_events
12035  WHERE object_type = 'cluster-replica'
12036    AND audit_events.event_type = 'alter'
12037    AND audit_events.details->>'replica_id' like 'u%'
12038),
12039user_replica_create_history AS (
12040  SELECT occurred_at,
12041    audit_events.details->>'replica_id' AS id,
12042    NULL AS previous_name,
12043    audit_events.details->>'replica_name' AS new_name
12044  FROM mz_catalog.mz_audit_events AS audit_events
12045  WHERE object_type = 'cluster-replica'
12046    AND audit_events.event_type = 'create'
12047    AND audit_events.details->>'replica_id' like 'u%'
12048),
12049-- Because built in system cluster replicas don't have audit events, we need to manually add them
12050system_replicas AS (
12051  -- We assume that the system cluster replicas were created at the beginning of time
12052  SELECT NULL::timestamptz AS occurred_at,
12053    id,
12054    NULL AS previous_name,
12055    name AS new_name
12056  FROM mz_catalog.mz_cluster_replicas
12057  WHERE id LIKE 's%'
12058)
12059SELECT *
12060FROM user_replica_alter_history
12061UNION ALL
12062SELECT *
12063FROM user_replica_create_history
12064UNION ALL
12065SELECT *
12066FROM system_replicas"#,
12067    access: vec![PUBLIC_SELECT],
12068});
12069
12070pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12071    name: "mz_hydration_statuses",
12072    schema: MZ_INTERNAL_SCHEMA,
12073    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
12074    desc: RelationDesc::builder()
12075        .with_column("object_id", SqlScalarType::String.nullable(false))
12076        .with_column("replica_id", SqlScalarType::String.nullable(true))
12077        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
12078        .finish(),
12079    column_comments: BTreeMap::from_iter([
12080        (
12081            "object_id",
12082            "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`.",
12083        ),
12084        ("replica_id", "The ID of a cluster replica."),
12085        ("hydrated", "Whether the object is hydrated on the replica."),
12086    ]),
12087    sql: r#"WITH
12088-- Joining against the linearizable catalog tables ensures that this view
12089-- always contains the set of installed objects, even when it depends
12090-- on introspection relations that may received delayed updates.
12091--
12092-- Note that this view only includes objects that are maintained by dataflows.
12093-- In particular, some source types (webhook, introspection, ...) are not and
12094-- are therefore omitted.
12095indexes AS (
12096    SELECT
12097        i.id AS object_id,
12098        h.replica_id,
12099        COALESCE(h.hydrated, false) AS hydrated
12100    FROM mz_catalog.mz_indexes i
12101    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12102        ON (h.object_id = i.id)
12103),
12104materialized_views AS (
12105    SELECT
12106        i.id AS object_id,
12107        h.replica_id,
12108        COALESCE(h.hydrated, false) AS hydrated
12109    FROM mz_catalog.mz_materialized_views i
12110    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12111        ON (h.object_id = i.id)
12112),
12113continual_tasks AS (
12114    SELECT
12115        i.id AS object_id,
12116        h.replica_id,
12117        COALESCE(h.hydrated, false) AS hydrated
12118    FROM mz_internal.mz_continual_tasks i
12119    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12120        ON (h.object_id = i.id)
12121),
12122-- Hydration is a dataflow concept and not all sources are maintained by
12123-- dataflows, so we need to find the ones that are. Generally, sources that
12124-- have a cluster ID are maintained by a dataflow running on that cluster.
12125-- Webhook sources are an exception to this rule.
12126sources_with_clusters AS (
12127    SELECT id, cluster_id
12128    FROM mz_catalog.mz_sources
12129    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12130),
12131sources AS (
12132    SELECT
12133        s.id AS object_id,
12134        ss.replica_id AS replica_id,
12135        ss.rehydration_latency IS NOT NULL AS hydrated
12136    FROM sources_with_clusters s
12137    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12138),
12139-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12140-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12141-- There is likely still a possibility of FPs.
12142sinks AS (
12143    SELECT
12144        s.id AS object_id,
12145        r.id AS replica_id,
12146        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12147    FROM mz_catalog.mz_sinks s
12148    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12149    JOIN mz_catalog.mz_cluster_replicas r
12150        ON (r.cluster_id = s.cluster_id)
12151    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12152        ON (f.object_id = s.id AND f.replica_id = r.id)
12153)
12154SELECT * FROM indexes
12155UNION ALL
12156SELECT * FROM materialized_views
12157UNION ALL
12158SELECT * FROM continual_tasks
12159UNION ALL
12160SELECT * FROM sources
12161UNION ALL
12162SELECT * FROM sinks"#,
12163    access: vec![PUBLIC_SELECT],
12164});
12165
12166pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12167    name: "mz_materialization_dependencies",
12168    schema: MZ_INTERNAL_SCHEMA,
12169    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12170    desc: RelationDesc::builder()
12171        .with_column("object_id", SqlScalarType::String.nullable(false))
12172        .with_column("dependency_id", SqlScalarType::String.nullable(false))
12173        .finish(),
12174    column_comments: BTreeMap::from_iter([
12175        (
12176            "object_id",
12177            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12178        ),
12179        (
12180            "dependency_id",
12181            "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`.",
12182        ),
12183    ]),
12184    sql: "
12185SELECT object_id, dependency_id
12186FROM mz_internal.mz_compute_dependencies
12187UNION ALL
12188SELECT s.id, d.referenced_object_id AS dependency_id
12189FROM mz_internal.mz_object_dependencies d
12190JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12191JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12192    access: vec![PUBLIC_SELECT],
12193});
12194
12195pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12196    name: "mz_materialization_lag",
12197    schema: MZ_INTERNAL_SCHEMA,
12198    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12199    desc: RelationDesc::builder()
12200        .with_column("object_id", SqlScalarType::String.nullable(false))
12201        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
12202        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
12203        .with_column(
12204            "slowest_local_input_id",
12205            SqlScalarType::String.nullable(false),
12206        )
12207        .with_column(
12208            "slowest_global_input_id",
12209            SqlScalarType::String.nullable(false),
12210        )
12211        .finish(),
12212    column_comments: BTreeMap::from_iter([
12213        (
12214            "object_id",
12215            "The ID of the materialized view, index, or sink.",
12216        ),
12217        (
12218            "local_lag",
12219            "The amount of time the materialization lags behind its direct inputs.",
12220        ),
12221        (
12222            "global_lag",
12223            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12224        ),
12225        (
12226            "slowest_local_input_id",
12227            "The ID of the slowest direct input.",
12228        ),
12229        (
12230            "slowest_global_input_id",
12231            "The ID of the slowest root input.",
12232        ),
12233    ]),
12234    sql: "
12235WITH MUTUALLY RECURSIVE
12236    -- IDs of objects for which we want to know the lag.
12237    materializations (id text) AS (
12238        SELECT id FROM mz_catalog.mz_indexes
12239        UNION ALL
12240        SELECT id FROM mz_catalog.mz_materialized_views
12241        UNION ALL
12242        SELECT id FROM mz_internal.mz_continual_tasks
12243        UNION ALL
12244        SELECT id FROM mz_catalog.mz_sinks
12245    ),
12246    -- Direct dependencies of materializations.
12247    direct_dependencies (id text, dep_id text) AS (
12248        SELECT m.id, d.dependency_id
12249        FROM materializations m
12250        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12251    ),
12252    -- All transitive dependencies of materializations.
12253    transitive_dependencies (id text, dep_id text) AS (
12254        SELECT id, dep_id FROM direct_dependencies
12255        UNION
12256        SELECT td.id, dd.dep_id
12257        FROM transitive_dependencies td
12258        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12259    ),
12260    -- Root dependencies of materializations (sources and tables).
12261    root_dependencies (id text, dep_id text) AS (
12262        SELECT *
12263        FROM transitive_dependencies td
12264        WHERE NOT EXISTS (
12265            SELECT 1
12266            FROM direct_dependencies dd
12267            WHERE dd.id = td.dep_id
12268        )
12269    ),
12270    -- Write progress times of materializations.
12271    materialization_times (id text, time timestamptz) AS (
12272        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12273        FROM materializations m
12274        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12275    ),
12276    -- Write progress times of direct dependencies of materializations.
12277    input_times (id text, slowest_dep text, time timestamptz) AS (
12278        SELECT DISTINCT ON (d.id)
12279            d.id,
12280            d.dep_id,
12281            to_timestamp(f.write_frontier::text::double / 1000)
12282        FROM direct_dependencies d
12283        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12284        ORDER BY d.id, f.write_frontier ASC
12285    ),
12286    -- Write progress times of root dependencies of materializations.
12287    root_times (id text, slowest_dep text, time timestamptz) AS (
12288        SELECT DISTINCT ON (d.id)
12289            d.id,
12290            d.dep_id,
12291            to_timestamp(f.write_frontier::text::double / 1000)
12292        FROM root_dependencies d
12293        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12294        ORDER BY d.id, f.write_frontier ASC
12295    )
12296SELECT
12297    id AS object_id,
12298    -- Ensure that lag values are always NULL for materializations that have reached the empty
12299    -- frontier, as those have processed all their input data.
12300    -- Also make sure that lag values are never negative, even when input frontiers are before
12301    -- output frontiers (as can happen during hydration).
12302    CASE
12303        WHEN m.time IS NULL THEN INTERVAL '0'
12304        WHEN i.time IS NULL THEN NULL
12305        ELSE greatest(i.time - m.time, INTERVAL '0')
12306    END AS local_lag,
12307    CASE
12308        WHEN m.time IS NULL THEN INTERVAL '0'
12309        WHEN r.time IS NULL THEN NULL
12310        ELSE greatest(r.time - m.time, INTERVAL '0')
12311    END AS global_lag,
12312    i.slowest_dep AS slowest_local_input_id,
12313    r.slowest_dep AS slowest_global_input_id
12314FROM materialization_times m
12315JOIN input_times i USING (id)
12316JOIN root_times r USING (id)",
12317    access: vec![PUBLIC_SELECT],
12318});
12319
12320/**
12321 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12322 * It's specifically for the Console's environment overview page to speed up load times.
12323 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12324 */
12325pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12326    BuiltinView {
12327        name: "mz_console_cluster_utilization_overview",
12328        schema: MZ_INTERNAL_SCHEMA,
12329        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12330        desc: RelationDesc::builder()
12331            .with_column(
12332                "bucket_start",
12333                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12334            )
12335            .with_column("replica_id", SqlScalarType::String.nullable(false))
12336            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
12337            .with_column(
12338                "max_memory_at",
12339                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12340            )
12341            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
12342            .with_column(
12343                "max_disk_at",
12344                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12345            )
12346            .with_column(
12347                "memory_and_disk_percent",
12348                SqlScalarType::Float64.nullable(true),
12349            )
12350            .with_column(
12351                "max_memory_and_disk_memory_percent",
12352                SqlScalarType::Float64.nullable(true),
12353            )
12354            .with_column(
12355                "max_memory_and_disk_disk_percent",
12356                SqlScalarType::Float64.nullable(true),
12357            )
12358            .with_column(
12359                "max_memory_and_disk_at",
12360                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12361            )
12362            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
12363            .with_column(
12364                "max_heap_at",
12365                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12366            )
12367            .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
12368            .with_column(
12369                "max_cpu_at",
12370                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12371            )
12372            .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
12373            .with_column(
12374                "bucket_end",
12375                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12376            )
12377            .with_column("name", SqlScalarType::String.nullable(true))
12378            .with_column("cluster_id", SqlScalarType::String.nullable(true))
12379            .with_column("size", SqlScalarType::String.nullable(true))
12380            .finish(),
12381        column_comments: BTreeMap::new(),
12382        sql: r#"WITH replica_history AS (
12383  SELECT replica_id,
12384    size,
12385    cluster_id
12386  FROM mz_internal.mz_cluster_replica_history
12387  UNION
12388  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12389  SELECT id AS replica_id,
12390    size,
12391    cluster_id
12392  FROM mz_catalog.mz_cluster_replicas
12393),
12394replica_metrics_history AS (
12395  SELECT
12396    m.occurred_at,
12397    m.replica_id,
12398    r.size,
12399    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0)) / NULLIF(s.processes, 0) AS cpu_percent,
12400    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0)) / NULLIF(s.processes, 0) AS memory_percent,
12401    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0)) / NULLIF(s.processes, 0) AS disk_percent,
12402    (SUM(m.heap_bytes::float8) / NULLIF(m.heap_limit, 0)) / NULLIF(s.processes, 0) AS heap_percent,
12403    SUM(m.disk_bytes::float8) AS disk_bytes,
12404    SUM(m.memory_bytes::float8) AS memory_bytes,
12405    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12406    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12407  FROM
12408    replica_history AS r
12409    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12410    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12411  GROUP BY
12412    m.occurred_at,
12413    m.replica_id,
12414    r.size,
12415    s.cpu_nano_cores,
12416    s.memory_bytes,
12417    s.disk_bytes,
12418    m.heap_limit,
12419    s.processes
12420),
12421replica_utilization_history_binned AS (
12422  SELECT m.occurred_at,
12423    m.replica_id,
12424    m.cpu_percent,
12425    m.memory_percent,
12426    m.memory_bytes,
12427    m.disk_percent,
12428    m.disk_bytes,
12429    m.heap_percent,
12430    m.total_disk_bytes,
12431    m.total_memory_bytes,
12432    m.size,
12433    date_bin(
12434      '8 HOURS',
12435      occurred_at,
12436      '1970-01-01'::timestamp
12437    ) AS bucket_start
12438  FROM replica_history AS r
12439    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12440  WHERE mz_now() <= date_bin(
12441      '8 HOURS',
12442      occurred_at,
12443      '1970-01-01'::timestamp
12444    ) + INTERVAL '14 DAYS'
12445),
12446-- For each (replica, bucket), take the (replica, bucket) with the highest memory
12447max_memory AS (
12448  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12449    replica_id,
12450    memory_percent,
12451    occurred_at
12452  FROM replica_utilization_history_binned
12453  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12454  ORDER BY bucket_start,
12455    replica_id,
12456    COALESCE(memory_bytes, 0) DESC
12457),
12458max_disk AS (
12459  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12460    replica_id,
12461    disk_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(disk_bytes, 0) DESC
12468),
12469max_cpu AS (
12470  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12471    replica_id,
12472    cpu_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(cpu_percent, 0) DESC
12479),
12480/*
12481 This is different
12482 from adding max_memory
12483 and max_disk per bucket because both
12484 values may not occur at the same time if the bucket interval is large.
12485 */
12486max_memory_and_disk AS (
12487  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12488    replica_id,
12489    memory_percent,
12490    disk_percent,
12491    memory_and_disk_percent,
12492    occurred_at
12493  FROM (
12494      SELECT *,
12495        CASE
12496          WHEN disk_bytes IS NULL
12497          AND memory_bytes IS NULL THEN NULL
12498          ELSE (COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0))
12499               / (total_disk_bytes::numeric + total_memory_bytes::numeric)
12500        END AS memory_and_disk_percent
12501      FROM replica_utilization_history_binned
12502    ) AS max_memory_and_disk_inner
12503  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12504  ORDER BY bucket_start,
12505    replica_id,
12506    COALESCE(memory_and_disk_percent, 0) DESC
12507),
12508max_heap AS (
12509  SELECT DISTINCT ON (bucket_start, replica_id)
12510    bucket_start,
12511    replica_id,
12512    heap_percent,
12513    occurred_at
12514  FROM replica_utilization_history_binned
12515  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12516  ORDER BY bucket_start, replica_id, COALESCE(heap_percent, 0) DESC
12517),
12518-- For each (replica, bucket), get its offline events at that time
12519replica_offline_event_history AS (
12520  SELECT date_bin(
12521      '8 HOURS',
12522      occurred_at,
12523      '1970-01-01'::timestamp
12524    ) AS bucket_start,
12525    replica_id,
12526    jsonb_agg(
12527      jsonb_build_object(
12528        'replicaId',
12529        rsh.replica_id,
12530        'occurredAt',
12531        rsh.occurred_at,
12532        'status',
12533        rsh.status,
12534        'reason',
12535        rsh.reason
12536      )
12537    ) AS offline_events
12538  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
12539  WHERE process_id = '0'
12540    AND status = 'offline'
12541    AND mz_now() <= date_bin(
12542      '8 HOURS',
12543      occurred_at,
12544      '1970-01-01'::timestamp
12545    ) + INTERVAL '14 DAYS'
12546  GROUP BY bucket_start,
12547    replica_id
12548)
12549SELECT
12550  bucket_start,
12551  replica_id,
12552  max_memory.memory_percent,
12553  max_memory.occurred_at as max_memory_at,
12554  max_disk.disk_percent,
12555  max_disk.occurred_at as max_disk_at,
12556  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
12557  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
12558  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
12559  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
12560  max_heap.heap_percent,
12561  max_heap.occurred_at as max_heap_at,
12562  max_cpu.cpu_percent as max_cpu_percent,
12563  max_cpu.occurred_at as max_cpu_at,
12564  replica_offline_event_history.offline_events,
12565  bucket_start + INTERVAL '8 HOURS' as bucket_end,
12566  replica_name_history.new_name AS name,
12567  replica_history.cluster_id,
12568  replica_history.size
12569FROM max_memory
12570JOIN max_disk USING (bucket_start, replica_id)
12571JOIN max_cpu USING (bucket_start, replica_id)
12572JOIN max_memory_and_disk USING (bucket_start, replica_id)
12573JOIN max_heap USING (bucket_start, replica_id)
12574JOIN replica_history USING (replica_id)
12575CROSS JOIN LATERAL (
12576  SELECT new_name
12577  FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
12578  WHERE replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
12579    AND bucket_start + INTERVAL '8 HOURS' >= COALESCE(
12580      replica_name_history.occurred_at,
12581      '1970-01-01'::timestamp
12582    )
12583  ORDER BY replica_name_history.occurred_at DESC
12584  LIMIT '1'
12585) AS replica_name_history
12586LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
12587        access: vec![PUBLIC_SELECT],
12588    }
12589});
12590
12591/**
12592 * Traces the blue/green deployment lineage in the audit log to determine all cluster
12593 * IDs that are logically the same cluster.
12594 * cluster_id: The ID of a cluster.
12595 * current_deployment_cluster_id: The cluster ID of the last cluster in
12596 *   cluster_id's blue/green lineage.
12597 * cluster_name: The name of the cluster.
12598 * The approach taken is as follows. First, find all extant clusters and add them
12599 * to the result set. Per cluster, we do the following:
12600 * 1. Find the most recent create or rename event. This moment represents when the
12601 *    cluster took on its final logical identity.
12602 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
12603 *    appended) that was dropped within one minute of that moment. That cluster is
12604 *    almost certainly the logical predecessor of the current cluster. Add the cluster
12605 *    to the result set.
12606 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
12607 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
12608 * but one that's likely to be pretty good one. If a name is reused after more
12609 * than one minute, that's a good sign that it wasn't an automatic blue/green
12610 * process, but someone turning on a new use case that happens to have the same
12611 * name as a previous but logically distinct use case.
12612 */
12613pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12614    name: "mz_cluster_deployment_lineage",
12615    schema: MZ_INTERNAL_SCHEMA,
12616    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
12617    desc: RelationDesc::builder()
12618        .with_column("cluster_id", SqlScalarType::String.nullable(true))
12619        .with_column(
12620            "current_deployment_cluster_id",
12621            SqlScalarType::String.nullable(false),
12622        )
12623        .with_column("cluster_name", SqlScalarType::String.nullable(false))
12624        .with_key(vec![0, 1, 2])
12625        .finish(),
12626    column_comments: BTreeMap::from_iter([
12627        (
12628            "cluster_id",
12629            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
12630        ),
12631        (
12632            "current_deployment_cluster_id",
12633            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
12634        ),
12635        ("cluster_name", "The name of the cluster"),
12636    ]),
12637    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
12638  cluster_id text,
12639  cluster_name text,
12640  event_type text,
12641  occurred_at timestamptz
12642) AS (
12643  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
12644    coalesce(details->>'name', details->>'new_name') AS cluster_name,
12645    event_type,
12646    occurred_at
12647  FROM mz_audit_events
12648  WHERE (
12649      event_type IN ('create', 'drop')
12650      OR (
12651        event_type = 'alter'
12652        AND details ? 'new_name'
12653      )
12654    )
12655    AND object_type = 'cluster'
12656    AND mz_now() < occurred_at + INTERVAL '30 days'
12657),
12658mz_cluster_deployment_lineage (
12659  cluster_id text,
12660  current_deployment_cluster_id text,
12661  cluster_name text
12662) AS (
12663  SELECT c.id,
12664    c.id,
12665    c.name
12666  FROM mz_clusters c
12667  WHERE c.id LIKE 'u%'
12668  UNION
12669  SELECT *
12670  FROM dropped_clusters
12671),
12672-- Closest create or rename event based on the current clusters in the result set
12673most_recent_create_or_rename (
12674  cluster_id text,
12675  current_deployment_cluster_id text,
12676  cluster_name text,
12677  occurred_at timestamptz
12678) AS (
12679  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
12680    c.current_deployment_cluster_id,
12681    e.cluster_name,
12682    e.occurred_at
12683  FROM mz_cluster_deployment_lineage c
12684    JOIN cluster_events e ON c.cluster_id = e.cluster_id
12685    AND c.cluster_name = e.cluster_name
12686  WHERE e.event_type <> 'drop'
12687  ORDER BY e.cluster_id,
12688    e.occurred_at DESC
12689),
12690-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
12691dropped_clusters (
12692  cluster_id text,
12693  current_deployment_cluster_id text,
12694  cluster_name text
12695) AS (
12696  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
12697    cr.current_deployment_cluster_id,
12698    cr.cluster_name
12699  FROM most_recent_create_or_rename cr
12700    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
12701    AND cr.occurred_at + interval '1 minute'
12702    AND (
12703      e.cluster_name = cr.cluster_name
12704      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
12705    )
12706  WHERE e.event_type = 'drop'
12707  ORDER BY cr.cluster_id,
12708    abs(
12709      extract(
12710        epoch
12711        FROM cr.occurred_at - e.occurred_at
12712      )
12713    )
12714)
12715SELECT *
12716FROM mz_cluster_deployment_lineage"#,
12717    access: vec![PUBLIC_SELECT],
12718});
12719
12720pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12721    name: "mz_show_databases_ind",
12722    schema: MZ_INTERNAL_SCHEMA,
12723    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
12724    sql: "IN CLUSTER mz_catalog_server
12725ON mz_internal.mz_show_databases (name)",
12726    is_retained_metrics_object: false,
12727};
12728
12729pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12730    name: "mz_show_schemas_ind",
12731    schema: MZ_INTERNAL_SCHEMA,
12732    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
12733    sql: "IN CLUSTER mz_catalog_server
12734ON mz_internal.mz_show_schemas (database_id)",
12735    is_retained_metrics_object: false,
12736};
12737
12738pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12739    name: "mz_show_connections_ind",
12740    schema: MZ_INTERNAL_SCHEMA,
12741    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
12742    sql: "IN CLUSTER mz_catalog_server
12743ON mz_internal.mz_show_connections (schema_id)",
12744    is_retained_metrics_object: false,
12745};
12746
12747pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
12748    name: "mz_show_tables_ind",
12749    schema: MZ_INTERNAL_SCHEMA,
12750    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
12751    sql: "IN CLUSTER mz_catalog_server
12752ON mz_internal.mz_show_tables (schema_id)",
12753    is_retained_metrics_object: false,
12754};
12755
12756pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12757    name: "mz_show_sources_ind",
12758    schema: MZ_INTERNAL_SCHEMA,
12759    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
12760    sql: "IN CLUSTER mz_catalog_server
12761ON mz_internal.mz_show_sources (schema_id)",
12762    is_retained_metrics_object: false,
12763};
12764
12765pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12766    name: "mz_show_views_ind",
12767    schema: MZ_INTERNAL_SCHEMA,
12768    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
12769    sql: "IN CLUSTER mz_catalog_server
12770ON mz_internal.mz_show_views (schema_id)",
12771    is_retained_metrics_object: false,
12772};
12773
12774pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12775    name: "mz_show_materialized_views_ind",
12776    schema: MZ_INTERNAL_SCHEMA,
12777    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
12778    sql: "IN CLUSTER mz_catalog_server
12779ON mz_internal.mz_show_materialized_views (schema_id)",
12780    is_retained_metrics_object: false,
12781};
12782
12783pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
12784    name: "mz_show_sinks_ind",
12785    schema: MZ_INTERNAL_SCHEMA,
12786    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
12787    sql: "IN CLUSTER mz_catalog_server
12788ON mz_internal.mz_show_sinks (schema_id)",
12789    is_retained_metrics_object: false,
12790};
12791
12792pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
12793    name: "mz_show_types_ind",
12794    schema: MZ_INTERNAL_SCHEMA,
12795    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
12796    sql: "IN CLUSTER mz_catalog_server
12797ON mz_internal.mz_show_types (schema_id)",
12798    is_retained_metrics_object: false,
12799};
12800
12801pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
12802    name: "mz_show_roles_ind",
12803    schema: MZ_INTERNAL_SCHEMA,
12804    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
12805    sql: "IN CLUSTER mz_catalog_server
12806ON mz_internal.mz_show_roles (name)",
12807    is_retained_metrics_object: false,
12808};
12809
12810pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12811    name: "mz_show_all_objects_ind",
12812    schema: MZ_INTERNAL_SCHEMA,
12813    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
12814    sql: "IN CLUSTER mz_catalog_server
12815ON mz_internal.mz_show_all_objects (schema_id)",
12816    is_retained_metrics_object: false,
12817};
12818
12819pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12820    name: "mz_show_indexes_ind",
12821    schema: MZ_INTERNAL_SCHEMA,
12822    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
12823    sql: "IN CLUSTER mz_catalog_server
12824ON mz_internal.mz_show_indexes (schema_id)",
12825    is_retained_metrics_object: false,
12826};
12827
12828pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12829    name: "mz_show_columns_ind",
12830    schema: MZ_INTERNAL_SCHEMA,
12831    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
12832    sql: "IN CLUSTER mz_catalog_server
12833ON mz_internal.mz_show_columns (id)",
12834    is_retained_metrics_object: false,
12835};
12836
12837pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12838    name: "mz_show_clusters_ind",
12839    schema: MZ_INTERNAL_SCHEMA,
12840    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
12841    sql: "IN CLUSTER mz_catalog_server
12842ON mz_internal.mz_show_clusters (name)",
12843    is_retained_metrics_object: false,
12844};
12845
12846pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
12847    name: "mz_show_cluster_replicas_ind",
12848    schema: MZ_INTERNAL_SCHEMA,
12849    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
12850    sql: "IN CLUSTER mz_catalog_server
12851ON mz_internal.mz_show_cluster_replicas (cluster)",
12852    is_retained_metrics_object: false,
12853};
12854
12855pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12856    name: "mz_show_secrets_ind",
12857    schema: MZ_INTERNAL_SCHEMA,
12858    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
12859    sql: "IN CLUSTER mz_catalog_server
12860ON mz_internal.mz_show_secrets (schema_id)",
12861    is_retained_metrics_object: false,
12862};
12863
12864pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12865    name: "mz_databases_ind",
12866    schema: MZ_CATALOG_SCHEMA,
12867    oid: oid::INDEX_MZ_DATABASES_IND_OID,
12868    sql: "IN CLUSTER mz_catalog_server
12869ON mz_catalog.mz_databases (name)",
12870    is_retained_metrics_object: false,
12871};
12872
12873pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12874    name: "mz_schemas_ind",
12875    schema: MZ_CATALOG_SCHEMA,
12876    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
12877    sql: "IN CLUSTER mz_catalog_server
12878ON mz_catalog.mz_schemas (database_id)",
12879    is_retained_metrics_object: false,
12880};
12881
12882pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12883    name: "mz_connections_ind",
12884    schema: MZ_CATALOG_SCHEMA,
12885    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
12886    sql: "IN CLUSTER mz_catalog_server
12887ON mz_catalog.mz_connections (schema_id)",
12888    is_retained_metrics_object: false,
12889};
12890
12891pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
12892    name: "mz_tables_ind",
12893    schema: MZ_CATALOG_SCHEMA,
12894    oid: oid::INDEX_MZ_TABLES_IND_OID,
12895    sql: "IN CLUSTER mz_catalog_server
12896ON mz_catalog.mz_tables (schema_id)",
12897    is_retained_metrics_object: false,
12898};
12899
12900pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
12901    name: "mz_types_ind",
12902    schema: MZ_CATALOG_SCHEMA,
12903    oid: oid::INDEX_MZ_TYPES_IND_OID,
12904    sql: "IN CLUSTER mz_catalog_server
12905ON mz_catalog.mz_types (schema_id)",
12906    is_retained_metrics_object: false,
12907};
12908
12909pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12910    name: "mz_objects_ind",
12911    schema: MZ_CATALOG_SCHEMA,
12912    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
12913    sql: "IN CLUSTER mz_catalog_server
12914ON mz_catalog.mz_objects (schema_id)",
12915    is_retained_metrics_object: false,
12916};
12917
12918pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12919    name: "mz_columns_ind",
12920    schema: MZ_CATALOG_SCHEMA,
12921    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
12922    sql: "IN CLUSTER mz_catalog_server
12923ON mz_catalog.mz_columns (name)",
12924    is_retained_metrics_object: false,
12925};
12926
12927pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12928    name: "mz_secrets_ind",
12929    schema: MZ_CATALOG_SCHEMA,
12930    oid: oid::INDEX_MZ_SECRETS_IND_OID,
12931    sql: "IN CLUSTER mz_catalog_server
12932ON mz_catalog.mz_secrets (name)",
12933    is_retained_metrics_object: false,
12934};
12935
12936pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12937    name: "mz_views_ind",
12938    schema: MZ_CATALOG_SCHEMA,
12939    oid: oid::INDEX_MZ_VIEWS_IND_OID,
12940    sql: "IN CLUSTER mz_catalog_server
12941ON mz_catalog.mz_views (schema_id)",
12942    is_retained_metrics_object: false,
12943};
12944
12945pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
12946    name: "mz_console_cluster_utilization_overview_ind",
12947    schema: MZ_INTERNAL_SCHEMA,
12948    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
12949    sql: "IN CLUSTER mz_catalog_server
12950ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
12951    is_retained_metrics_object: false,
12952};
12953
12954pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
12955    name: "mz_cluster_deployment_lineage_ind",
12956    schema: MZ_INTERNAL_SCHEMA,
12957    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
12958    sql: "IN CLUSTER mz_catalog_server
12959ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
12960    is_retained_metrics_object: false,
12961};
12962
12963pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12964    name: "mz_clusters_ind",
12965    schema: MZ_CATALOG_SCHEMA,
12966    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
12967    sql: "IN CLUSTER mz_catalog_server
12968ON mz_catalog.mz_clusters (id)",
12969    is_retained_metrics_object: false,
12970};
12971
12972pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12973    name: "mz_indexes_ind",
12974    schema: MZ_CATALOG_SCHEMA,
12975    oid: oid::INDEX_MZ_INDEXES_IND_OID,
12976    sql: "IN CLUSTER mz_catalog_server
12977ON mz_catalog.mz_indexes (id)",
12978    is_retained_metrics_object: false,
12979};
12980
12981pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
12982    name: "mz_roles_ind",
12983    schema: MZ_CATALOG_SCHEMA,
12984    oid: oid::INDEX_MZ_ROLES_IND_OID,
12985    sql: "IN CLUSTER mz_catalog_server
12986ON mz_catalog.mz_roles (id)",
12987    is_retained_metrics_object: false,
12988};
12989
12990pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12991    name: "mz_sources_ind",
12992    schema: MZ_CATALOG_SCHEMA,
12993    oid: oid::INDEX_MZ_SOURCES_IND_OID,
12994    sql: "IN CLUSTER mz_catalog_server
12995ON mz_catalog.mz_sources (id)",
12996    is_retained_metrics_object: true,
12997};
12998
12999pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
13000    name: "mz_sinks_ind",
13001    schema: MZ_CATALOG_SCHEMA,
13002    oid: oid::INDEX_MZ_SINKS_IND_OID,
13003    sql: "IN CLUSTER mz_catalog_server
13004ON mz_catalog.mz_sinks (id)",
13005    is_retained_metrics_object: true,
13006};
13007
13008pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13009    name: "mz_materialized_views_ind",
13010    schema: MZ_CATALOG_SCHEMA,
13011    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
13012    sql: "IN CLUSTER mz_catalog_server
13013ON mz_catalog.mz_materialized_views (id)",
13014    is_retained_metrics_object: false,
13015};
13016
13017pub const MZ_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13018    name: "mz_continual_tasks_ind",
13019    schema: MZ_INTERNAL_SCHEMA,
13020    oid: oid::INDEX_MZ_CONTINUAL_TASKS_IND_OID,
13021    sql: "IN CLUSTER mz_catalog_server
13022ON mz_internal.mz_continual_tasks (id)",
13023    is_retained_metrics_object: false,
13024};
13025
13026pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13027    name: "mz_source_statuses_ind",
13028    schema: MZ_INTERNAL_SCHEMA,
13029    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
13030    sql: "IN CLUSTER mz_catalog_server
13031ON mz_internal.mz_source_statuses (id)",
13032    is_retained_metrics_object: false,
13033};
13034
13035pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13036    name: "mz_sink_statuses_ind",
13037    schema: MZ_INTERNAL_SCHEMA,
13038    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
13039    sql: "IN CLUSTER mz_catalog_server
13040ON mz_internal.mz_sink_statuses (id)",
13041    is_retained_metrics_object: false,
13042};
13043
13044pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13045    name: "mz_source_status_history_ind",
13046    schema: MZ_INTERNAL_SCHEMA,
13047    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
13048    sql: "IN CLUSTER mz_catalog_server
13049ON mz_internal.mz_source_status_history (source_id)",
13050    is_retained_metrics_object: false,
13051};
13052
13053pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13054    name: "mz_sink_status_history_ind",
13055    schema: MZ_INTERNAL_SCHEMA,
13056    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
13057    sql: "IN CLUSTER mz_catalog_server
13058ON mz_internal.mz_sink_status_history (sink_id)",
13059    is_retained_metrics_object: false,
13060};
13061
13062pub const MZ_SHOW_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13063    name: "mz_show_continual_tasks_ind",
13064    schema: MZ_INTERNAL_SCHEMA,
13065    oid: oid::INDEX_MZ_SHOW_CONTINUAL_TASKS_OID,
13066    sql: "IN CLUSTER mz_catalog_server
13067ON mz_internal.mz_show_continual_tasks (id)",
13068    is_retained_metrics_object: false,
13069};
13070
13071// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
13072// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
13073// save index space, and we don't expect the sum to be > 2^63
13074// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
13075//
13076//
13077// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
13078// underlying relation.
13079//
13080// We append WITH_HISTORY because we want to build a separate view + index that doesn't
13081// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
13082// to hold all records/updates, which causes CPU and latency of querying it to spike.
13083pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
13084    LazyLock::new(|| BuiltinView {
13085        name: "mz_source_statistics_with_history",
13086        schema: MZ_INTERNAL_SCHEMA,
13087        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
13088        desc: RelationDesc::builder()
13089            .with_column("id", SqlScalarType::String.nullable(false))
13090            .with_column("replica_id", SqlScalarType::String.nullable(true))
13091            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13092            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13093            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13094            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13095            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13096            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13097            .with_column(
13098                "rehydration_latency",
13099                SqlScalarType::Interval.nullable(true),
13100            )
13101            .with_column(
13102                "snapshot_records_known",
13103                SqlScalarType::UInt64.nullable(true),
13104            )
13105            .with_column(
13106                "snapshot_records_staged",
13107                SqlScalarType::UInt64.nullable(true),
13108            )
13109            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13110            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13111            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13112            .with_key(vec![0, 1])
13113            .finish(),
13114        column_comments: BTreeMap::new(),
13115        sql: "
13116WITH
13117    -- For each subsource, statistics are reported as its parent source
13118    subsource_to_parent AS
13119    (
13120        SELECT subsource.id AS id, parent.id AS report_id
13121        FROM mz_catalog.mz_sources AS subsource
13122            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
13123            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
13124        WHERE subsource.type = 'subsource'
13125    ),
13126    -- For each table from source, statistics are reported as its parent source
13127    table_to_parent AS
13128    (
13129        SELECT id, source_id AS report_id
13130        FROM mz_catalog.mz_tables
13131        WHERE source_id IS NOT NULL
13132    ),
13133    -- For each source and subsource, statistics are reported as itself
13134    source_refl AS
13135    (
13136        SELECT id, id AS report_id
13137        FROM mz_catalog.mz_sources
13138        WHERE type NOT IN ('progress', 'log')
13139    ),
13140    -- For each table from source, statistics are reported as itself
13141    table_refl AS
13142    (
13143        SELECT id, id AS report_id
13144        FROM mz_catalog.mz_tables
13145        WHERE source_id IS NOT NULL
13146    ),
13147    report_paths AS
13148    (
13149        SELECT id, report_id FROM subsource_to_parent
13150        UNION ALL SELECT id, report_id FROM table_to_parent
13151        UNION ALL SELECT id, report_id FROM source_refl
13152        UNION ALL SELECT id, report_id FROM table_refl
13153    )
13154SELECT
13155    report_paths.report_id AS id,
13156    replica_id,
13157    -- Counters
13158    SUM(messages_received)::uint8 AS messages_received,
13159    SUM(bytes_received)::uint8 AS bytes_received,
13160    SUM(updates_staged)::uint8 AS updates_staged,
13161    SUM(updates_committed)::uint8 AS updates_committed,
13162    -- Resetting Gauges
13163    SUM(records_indexed)::uint8 AS records_indexed,
13164    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13165    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13166    CASE
13167        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13168        ELSE MAX(rehydration_latency)::interval
13169    END AS rehydration_latency,
13170    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13171    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13172    bool_and(snapshot_committed) as snapshot_committed,
13173    -- Gauges
13174    MAX(offset_known)::uint8 AS offset_known,
13175    MIN(offset_committed)::uint8 AS offset_committed
13176FROM mz_internal.mz_source_statistics_raw
13177    JOIN report_paths USING (id)
13178GROUP BY report_paths.report_id, replica_id",
13179        access: vec![PUBLIC_SELECT],
13180    });
13181
13182pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13183    name: "mz_source_statistics_with_history_ind",
13184    schema: MZ_INTERNAL_SCHEMA,
13185    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13186    sql: "IN CLUSTER mz_catalog_server
13187ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
13188    is_retained_metrics_object: true,
13189};
13190
13191// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13192// Used to query MZ_SOURCE_STATISTICS at the current time.
13193pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13194    BuiltinView {
13195        name: "mz_source_statistics",
13196        schema: MZ_INTERNAL_SCHEMA,
13197        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13198        // We need to add a redundant where clause for a new dataflow to be created.
13199        desc: RelationDesc::builder()
13200            .with_column("id", SqlScalarType::String.nullable(false))
13201            .with_column("replica_id", SqlScalarType::String.nullable(true))
13202            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13203            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13204            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13205            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13206            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13207            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13208            .with_column(
13209                "rehydration_latency",
13210                SqlScalarType::Interval.nullable(true),
13211            )
13212            .with_column(
13213                "snapshot_records_known",
13214                SqlScalarType::UInt64.nullable(true),
13215            )
13216            .with_column(
13217                "snapshot_records_staged",
13218                SqlScalarType::UInt64.nullable(true),
13219            )
13220            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13221            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13222            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13223            .with_key(vec![0, 1])
13224            .finish(),
13225        column_comments: BTreeMap::from_iter([
13226            (
13227                "id",
13228                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13229            ),
13230            (
13231                "replica_id",
13232                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13233            ),
13234            (
13235                "messages_received",
13236                "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.",
13237            ),
13238            (
13239                "bytes_received",
13240                "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.",
13241            ),
13242            (
13243                "updates_staged",
13244                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13245            ),
13246            (
13247                "updates_committed",
13248                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13249            ),
13250            (
13251                "records_indexed",
13252                "The number of individual records indexed in the source envelope state.",
13253            ),
13254            (
13255                "bytes_indexed",
13256                "The number of bytes stored in the source's internal index, if any.",
13257            ),
13258            (
13259                "rehydration_latency",
13260                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13261            ),
13262            (
13263                "snapshot_records_known",
13264                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13265            ),
13266            (
13267                "snapshot_records_staged",
13268                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13269            ),
13270            (
13271                "snapshot_committed",
13272                "Whether the source has committed the initial snapshot for a source.",
13273            ),
13274            (
13275                "offset_known",
13276                "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.",
13277            ),
13278            (
13279                "offset_committed",
13280                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13281            ),
13282        ]),
13283        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13284        access: vec![PUBLIC_SELECT],
13285    }
13286});
13287
13288pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13289    name: "mz_source_statistics_ind",
13290    schema: MZ_INTERNAL_SCHEMA,
13291    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13292    sql: "IN CLUSTER mz_catalog_server
13293ON mz_internal.mz_source_statistics (id, replica_id)",
13294    is_retained_metrics_object: false,
13295};
13296
13297pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13298    name: "mz_sink_statistics",
13299    schema: MZ_INTERNAL_SCHEMA,
13300    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13301    desc: RelationDesc::builder()
13302        .with_column("id", SqlScalarType::String.nullable(false))
13303        .with_column("replica_id", SqlScalarType::String.nullable(true))
13304        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
13305        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
13306        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
13307        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
13308        .with_key(vec![0, 1])
13309        .finish(),
13310    column_comments: BTreeMap::from_iter([
13311        (
13312            "id",
13313            "The ID of the sink. Corresponds to `mz_catalog.mz_sources.id`.",
13314        ),
13315        (
13316            "replica_id",
13317            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13318        ),
13319        (
13320            "messages_staged",
13321            "The number of messages staged but possibly not committed to the sink.",
13322        ),
13323        (
13324            "messages_committed",
13325            "The number of messages committed to the sink.",
13326        ),
13327        (
13328            "bytes_staged",
13329            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13330        ),
13331        (
13332            "bytes_committed",
13333            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13334        ),
13335    ]),
13336    sql: "
13337SELECT
13338    id,
13339    replica_id,
13340    SUM(messages_staged)::uint8 AS messages_staged,
13341    SUM(messages_committed)::uint8 AS messages_committed,
13342    SUM(bytes_staged)::uint8 AS bytes_staged,
13343    SUM(bytes_committed)::uint8 AS bytes_committed
13344FROM mz_internal.mz_sink_statistics_raw
13345GROUP BY id, replica_id",
13346    access: vec![PUBLIC_SELECT],
13347});
13348
13349pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13350    name: "mz_sink_statistics_ind",
13351    schema: MZ_INTERNAL_SCHEMA,
13352    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13353    sql: "IN CLUSTER mz_catalog_server
13354ON mz_internal.mz_sink_statistics (id, replica_id)",
13355    is_retained_metrics_object: true,
13356};
13357
13358pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13359    name: "mz_cluster_replicas_ind",
13360    schema: MZ_CATALOG_SCHEMA,
13361    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13362    sql: "IN CLUSTER mz_catalog_server
13363ON mz_catalog.mz_cluster_replicas (id)",
13364    is_retained_metrics_object: true,
13365};
13366
13367pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13368    name: "mz_cluster_replica_sizes_ind",
13369    schema: MZ_CATALOG_SCHEMA,
13370    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13371    sql: "IN CLUSTER mz_catalog_server
13372ON mz_catalog.mz_cluster_replica_sizes (size)",
13373    is_retained_metrics_object: true,
13374};
13375
13376pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13377    name: "mz_cluster_replica_statuses_ind",
13378    schema: MZ_INTERNAL_SCHEMA,
13379    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13380    sql: "IN CLUSTER mz_catalog_server
13381ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13382    is_retained_metrics_object: false,
13383};
13384
13385pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13386    name: "mz_cluster_replica_status_history_ind",
13387    schema: MZ_INTERNAL_SCHEMA,
13388    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13389    sql: "IN CLUSTER mz_catalog_server
13390ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13391    is_retained_metrics_object: false,
13392};
13393
13394pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13395    name: "mz_cluster_replica_metrics_ind",
13396    schema: MZ_INTERNAL_SCHEMA,
13397    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13398    sql: "IN CLUSTER mz_catalog_server
13399ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13400    is_retained_metrics_object: false,
13401};
13402
13403pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13404    name: "mz_cluster_replica_metrics_history_ind",
13405    schema: MZ_INTERNAL_SCHEMA,
13406    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13407    sql: "IN CLUSTER mz_catalog_server
13408ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13409    is_retained_metrics_object: false,
13410};
13411
13412pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13413    name: "mz_cluster_replica_history_ind",
13414    schema: MZ_INTERNAL_SCHEMA,
13415    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13416    sql: "IN CLUSTER mz_catalog_server
13417ON mz_internal.mz_cluster_replica_history (dropped_at)",
13418    is_retained_metrics_object: true,
13419};
13420
13421pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13422    name: "mz_cluster_replica_name_history_ind",
13423    schema: MZ_INTERNAL_SCHEMA,
13424    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13425    sql: "IN CLUSTER mz_catalog_server
13426ON mz_internal.mz_cluster_replica_name_history (id)",
13427    is_retained_metrics_object: false,
13428};
13429
13430pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13431    name: "mz_object_lifetimes_ind",
13432    schema: MZ_INTERNAL_SCHEMA,
13433    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13434    sql: "IN CLUSTER mz_catalog_server
13435ON mz_internal.mz_object_lifetimes (id)",
13436    is_retained_metrics_object: false,
13437};
13438
13439pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13440    name: "mz_object_history_ind",
13441    schema: MZ_INTERNAL_SCHEMA,
13442    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13443    sql: "IN CLUSTER mz_catalog_server
13444ON mz_internal.mz_object_history (id)",
13445    is_retained_metrics_object: false,
13446};
13447
13448pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13449    name: "mz_object_dependencies_ind",
13450    schema: MZ_INTERNAL_SCHEMA,
13451    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
13452    sql: "IN CLUSTER mz_catalog_server
13453ON mz_internal.mz_object_dependencies (object_id)",
13454    is_retained_metrics_object: true,
13455};
13456
13457pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13458    name: "mz_compute_dependencies_ind",
13459    schema: MZ_INTERNAL_SCHEMA,
13460    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
13461    sql: "IN CLUSTER mz_catalog_server
13462ON mz_internal.mz_compute_dependencies (dependency_id)",
13463    is_retained_metrics_object: false,
13464};
13465
13466pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13467    name: "mz_object_transitive_dependencies_ind",
13468    schema: MZ_INTERNAL_SCHEMA,
13469    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
13470    sql: "IN CLUSTER mz_catalog_server
13471ON mz_internal.mz_object_transitive_dependencies (object_id)",
13472    is_retained_metrics_object: false,
13473};
13474
13475pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
13476    name: "mz_frontiers_ind",
13477    schema: MZ_INTERNAL_SCHEMA,
13478    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
13479    sql: "IN CLUSTER mz_catalog_server
13480ON mz_internal.mz_frontiers (object_id)",
13481    is_retained_metrics_object: false,
13482};
13483
13484pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13485    name: "mz_wallclock_global_lag_recent_history_ind",
13486    schema: MZ_INTERNAL_SCHEMA,
13487    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
13488    sql: "IN CLUSTER mz_catalog_server
13489ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
13490    is_retained_metrics_object: false,
13491};
13492
13493pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
13494    name: "mz_recent_activity_log_thinned_ind",
13495    schema: MZ_INTERNAL_SCHEMA,
13496    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
13497    sql: "IN CLUSTER mz_catalog_server
13498-- sql_hash because we plan to join
13499-- this against mz_internal.mz_sql_text
13500ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
13501    is_retained_metrics_object: false,
13502};
13503
13504pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13505    name: "mz_kafka_sources_ind",
13506    schema: MZ_CATALOG_SCHEMA,
13507    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
13508    sql: "IN CLUSTER mz_catalog_server
13509ON mz_catalog.mz_kafka_sources (id)",
13510    is_retained_metrics_object: true,
13511};
13512
13513pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13514    name: "mz_webhook_sources_ind",
13515    schema: MZ_INTERNAL_SCHEMA,
13516    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
13517    sql: "IN CLUSTER mz_catalog_server
13518ON mz_internal.mz_webhook_sources (id)",
13519    is_retained_metrics_object: true,
13520};
13521
13522pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
13523    name: "mz_comments_ind",
13524    schema: MZ_INTERNAL_SCHEMA,
13525    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
13526    sql: "IN CLUSTER mz_catalog_server
13527ON mz_internal.mz_comments (id)",
13528    is_retained_metrics_object: true,
13529};
13530
13531pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
13532    name: "mz_analytics",
13533    schema: MZ_INTERNAL_SCHEMA,
13534    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
13535    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
13536    access: &[MzAclItem {
13537        grantee: MZ_SYSTEM_ROLE_ID,
13538        grantor: MZ_ANALYTICS_ROLE_ID,
13539        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
13540    }],
13541    owner_id: &MZ_ANALYTICS_ROLE_ID,
13542    runtime_alterable: true,
13543};
13544
13545pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
13546    id: MZ_SYSTEM_ROLE_ID,
13547    name: SYSTEM_USER_NAME,
13548    oid: oid::ROLE_MZ_SYSTEM_OID,
13549    attributes: RoleAttributesRaw::new().with_all(),
13550};
13551
13552pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
13553    id: MZ_SUPPORT_ROLE_ID,
13554    name: SUPPORT_USER_NAME,
13555    oid: oid::ROLE_MZ_SUPPORT_OID,
13556    attributes: RoleAttributesRaw::new(),
13557};
13558
13559pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
13560    id: MZ_ANALYTICS_ROLE_ID,
13561    name: ANALYTICS_USER_NAME,
13562    oid: oid::ROLE_MZ_ANALYTICS_OID,
13563    attributes: RoleAttributesRaw::new(),
13564};
13565
13566/// This role can `SELECT` from various query history objects,
13567/// e.g. `mz_prepared_statement_history`.
13568pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
13569    id: MZ_MONITOR_ROLE_ID,
13570    name: "mz_monitor",
13571    oid: oid::ROLE_MZ_MONITOR_OID,
13572    attributes: RoleAttributesRaw::new(),
13573};
13574
13575/// This role is like [`MZ_MONITOR_ROLE`], but can only query
13576/// the redacted versions of the objects.
13577pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
13578    id: MZ_MONITOR_REDACTED_ROLE_ID,
13579    name: "mz_monitor_redacted",
13580    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
13581    attributes: RoleAttributesRaw::new(),
13582};
13583
13584pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
13585    name: SYSTEM_USER_NAME,
13586    owner_id: &MZ_SYSTEM_ROLE_ID,
13587    privileges: &[
13588        MzAclItem {
13589            grantee: MZ_SUPPORT_ROLE_ID,
13590            grantor: MZ_SYSTEM_ROLE_ID,
13591            acl_mode: AclMode::USAGE,
13592        },
13593        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13594    ],
13595};
13596
13597pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13598    name: BUILTIN_CLUSTER_REPLICA_NAME,
13599    cluster_name: MZ_SYSTEM_CLUSTER.name,
13600};
13601
13602pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
13603    name: "mz_catalog_server",
13604    owner_id: &MZ_SYSTEM_ROLE_ID,
13605    privileges: &[
13606        MzAclItem {
13607            grantee: RoleId::Public,
13608            grantor: MZ_SYSTEM_ROLE_ID,
13609            acl_mode: AclMode::USAGE,
13610        },
13611        MzAclItem {
13612            grantee: MZ_SUPPORT_ROLE_ID,
13613            grantor: MZ_SYSTEM_ROLE_ID,
13614            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
13615        },
13616        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13617    ],
13618};
13619
13620pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13621    name: BUILTIN_CLUSTER_REPLICA_NAME,
13622    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
13623};
13624
13625pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
13626    name: "mz_probe",
13627    owner_id: &MZ_SYSTEM_ROLE_ID,
13628    privileges: &[
13629        MzAclItem {
13630            grantee: MZ_SUPPORT_ROLE_ID,
13631            grantor: MZ_SYSTEM_ROLE_ID,
13632            acl_mode: AclMode::USAGE,
13633        },
13634        MzAclItem {
13635            grantee: MZ_MONITOR_ROLE_ID,
13636            grantor: MZ_SYSTEM_ROLE_ID,
13637            acl_mode: AclMode::USAGE,
13638        },
13639        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13640    ],
13641};
13642pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13643    name: BUILTIN_CLUSTER_REPLICA_NAME,
13644    cluster_name: MZ_PROBE_CLUSTER.name,
13645};
13646
13647pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
13648    name: "mz_support",
13649    owner_id: &MZ_SUPPORT_ROLE_ID,
13650    privileges: &[
13651        MzAclItem {
13652            grantee: MZ_SYSTEM_ROLE_ID,
13653            grantor: MZ_SUPPORT_ROLE_ID,
13654            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13655        },
13656        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
13657    ],
13658};
13659
13660pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
13661    name: "mz_analytics",
13662    owner_id: &MZ_ANALYTICS_ROLE_ID,
13663    privileges: &[
13664        MzAclItem {
13665            grantee: MZ_SYSTEM_ROLE_ID,
13666            grantor: MZ_ANALYTICS_ROLE_ID,
13667            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13668        },
13669        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
13670    ],
13671};
13672
13673/// List of all builtin objects sorted topologically by dependency.
13674pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
13675    let mut builtins = vec![
13676        Builtin::Type(&TYPE_ANY),
13677        Builtin::Type(&TYPE_ANYARRAY),
13678        Builtin::Type(&TYPE_ANYELEMENT),
13679        Builtin::Type(&TYPE_ANYNONARRAY),
13680        Builtin::Type(&TYPE_ANYRANGE),
13681        Builtin::Type(&TYPE_BOOL),
13682        Builtin::Type(&TYPE_BOOL_ARRAY),
13683        Builtin::Type(&TYPE_BYTEA),
13684        Builtin::Type(&TYPE_BYTEA_ARRAY),
13685        Builtin::Type(&TYPE_BPCHAR),
13686        Builtin::Type(&TYPE_BPCHAR_ARRAY),
13687        Builtin::Type(&TYPE_CHAR),
13688        Builtin::Type(&TYPE_CHAR_ARRAY),
13689        Builtin::Type(&TYPE_DATE),
13690        Builtin::Type(&TYPE_DATE_ARRAY),
13691        Builtin::Type(&TYPE_FLOAT4),
13692        Builtin::Type(&TYPE_FLOAT4_ARRAY),
13693        Builtin::Type(&TYPE_FLOAT8),
13694        Builtin::Type(&TYPE_FLOAT8_ARRAY),
13695        Builtin::Type(&TYPE_INT4),
13696        Builtin::Type(&TYPE_INT4_ARRAY),
13697        Builtin::Type(&TYPE_INT8),
13698        Builtin::Type(&TYPE_INT8_ARRAY),
13699        Builtin::Type(&TYPE_INTERVAL),
13700        Builtin::Type(&TYPE_INTERVAL_ARRAY),
13701        Builtin::Type(&TYPE_JSONB),
13702        Builtin::Type(&TYPE_JSONB_ARRAY),
13703        Builtin::Type(&TYPE_LIST),
13704        Builtin::Type(&TYPE_MAP),
13705        Builtin::Type(&TYPE_NAME),
13706        Builtin::Type(&TYPE_NAME_ARRAY),
13707        Builtin::Type(&TYPE_NUMERIC),
13708        Builtin::Type(&TYPE_NUMERIC_ARRAY),
13709        Builtin::Type(&TYPE_OID),
13710        Builtin::Type(&TYPE_OID_ARRAY),
13711        Builtin::Type(&TYPE_RECORD),
13712        Builtin::Type(&TYPE_RECORD_ARRAY),
13713        Builtin::Type(&TYPE_REGCLASS),
13714        Builtin::Type(&TYPE_REGCLASS_ARRAY),
13715        Builtin::Type(&TYPE_REGPROC),
13716        Builtin::Type(&TYPE_REGPROC_ARRAY),
13717        Builtin::Type(&TYPE_REGTYPE),
13718        Builtin::Type(&TYPE_REGTYPE_ARRAY),
13719        Builtin::Type(&TYPE_INT2),
13720        Builtin::Type(&TYPE_INT2_ARRAY),
13721        Builtin::Type(&TYPE_TEXT),
13722        Builtin::Type(&TYPE_TEXT_ARRAY),
13723        Builtin::Type(&TYPE_TIME),
13724        Builtin::Type(&TYPE_TIME_ARRAY),
13725        Builtin::Type(&TYPE_TIMESTAMP),
13726        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
13727        Builtin::Type(&TYPE_TIMESTAMPTZ),
13728        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
13729        Builtin::Type(&TYPE_UUID),
13730        Builtin::Type(&TYPE_UUID_ARRAY),
13731        Builtin::Type(&TYPE_VARCHAR),
13732        Builtin::Type(&TYPE_VARCHAR_ARRAY),
13733        Builtin::Type(&TYPE_INT2_VECTOR),
13734        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
13735        Builtin::Type(&TYPE_ANYCOMPATIBLE),
13736        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
13737        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
13738        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
13739        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
13740        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
13741        Builtin::Type(&TYPE_UINT2),
13742        Builtin::Type(&TYPE_UINT2_ARRAY),
13743        Builtin::Type(&TYPE_UINT4),
13744        Builtin::Type(&TYPE_UINT4_ARRAY),
13745        Builtin::Type(&TYPE_UINT8),
13746        Builtin::Type(&TYPE_UINT8_ARRAY),
13747        Builtin::Type(&TYPE_MZ_TIMESTAMP),
13748        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
13749        Builtin::Type(&TYPE_INT4_RANGE),
13750        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
13751        Builtin::Type(&TYPE_INT8_RANGE),
13752        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
13753        Builtin::Type(&TYPE_DATE_RANGE),
13754        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
13755        Builtin::Type(&TYPE_NUM_RANGE),
13756        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
13757        Builtin::Type(&TYPE_TS_RANGE),
13758        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
13759        Builtin::Type(&TYPE_TSTZ_RANGE),
13760        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
13761        Builtin::Type(&TYPE_MZ_ACL_ITEM),
13762        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
13763        Builtin::Type(&TYPE_ACL_ITEM),
13764        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
13765        Builtin::Type(&TYPE_INTERNAL),
13766    ];
13767    for (schema, funcs) in &[
13768        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
13769        (
13770            INFORMATION_SCHEMA,
13771            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
13772        ),
13773        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
13774        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
13775        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
13776    ] {
13777        for (name, func) in funcs.iter() {
13778            builtins.push(Builtin::Func(BuiltinFunc {
13779                name,
13780                schema,
13781                inner: func,
13782            }));
13783        }
13784    }
13785    builtins.append(&mut vec![
13786        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
13787        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
13788        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
13789        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
13790        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
13791        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
13792        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
13793        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
13794        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
13795        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
13796        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
13797        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
13798        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
13799        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
13800        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
13801        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
13802        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
13803        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
13804        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
13805        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
13806        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
13807        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
13808        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
13809        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
13810        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
13811        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
13812        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
13813        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
13814        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
13815        Builtin::Log(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
13816        Builtin::Table(&MZ_KAFKA_SINKS),
13817        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
13818        Builtin::Table(&MZ_KAFKA_SOURCES),
13819        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
13820        Builtin::Table(&MZ_ICEBERG_SINKS),
13821        Builtin::Table(&MZ_DATABASES),
13822        Builtin::Table(&MZ_SCHEMAS),
13823        Builtin::Table(&MZ_COLUMNS),
13824        Builtin::Table(&MZ_INDEXES),
13825        Builtin::Table(&MZ_INDEX_COLUMNS),
13826        Builtin::Table(&MZ_TABLES),
13827        Builtin::Table(&MZ_SOURCES),
13828        Builtin::Table(&MZ_SOURCE_REFERENCES),
13829        Builtin::Table(&MZ_POSTGRES_SOURCES),
13830        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
13831        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
13832        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
13833        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
13834        Builtin::Table(&MZ_SINKS),
13835        Builtin::Table(&MZ_VIEWS),
13836        Builtin::Table(&MZ_MATERIALIZED_VIEWS),
13837        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
13838        Builtin::Table(&MZ_TYPES),
13839        Builtin::Table(&MZ_TYPE_PG_METADATA),
13840        Builtin::Table(&MZ_ARRAY_TYPES),
13841        Builtin::Table(&MZ_BASE_TYPES),
13842        Builtin::Table(&MZ_LIST_TYPES),
13843        Builtin::Table(&MZ_MAP_TYPES),
13844        Builtin::Table(&MZ_ROLES),
13845        Builtin::Table(&MZ_ROLE_AUTH),
13846        Builtin::Table(&MZ_ROLE_MEMBERS),
13847        Builtin::Table(&MZ_ROLE_PARAMETERS),
13848        Builtin::Table(&MZ_PSEUDO_TYPES),
13849        Builtin::Table(&MZ_FUNCTIONS),
13850        Builtin::Table(&MZ_OPERATORS),
13851        Builtin::Table(&MZ_AGGREGATES),
13852        Builtin::Table(&MZ_CLUSTERS),
13853        Builtin::Table(&MZ_CLUSTER_WORKLOAD_CLASSES),
13854        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
13855        Builtin::Table(&MZ_SECRETS),
13856        Builtin::Table(&MZ_CONNECTIONS),
13857        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
13858        Builtin::Table(&MZ_CLUSTER_REPLICAS),
13859        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
13860        Builtin::View(&MZ_CLUSTER_REPLICA_METRICS),
13861        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
13862        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
13863        Builtin::View(&MZ_CLUSTER_REPLICA_STATUSES),
13864        Builtin::Table(&MZ_INTERNAL_CLUSTER_REPLICAS),
13865        Builtin::Table(&MZ_PENDING_CLUSTER_REPLICAS),
13866        Builtin::Table(&MZ_AUDIT_EVENTS),
13867        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
13868        Builtin::Table(&MZ_EGRESS_IPS),
13869        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
13870        Builtin::Table(&MZ_AWS_CONNECTIONS),
13871        Builtin::Table(&MZ_SUBSCRIPTIONS),
13872        Builtin::Table(&MZ_SESSIONS),
13873        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
13874        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
13875        Builtin::Table(&MZ_COMMENTS),
13876        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
13877        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
13878        Builtin::Table(&MZ_CONTINUAL_TASKS),
13879        Builtin::Table(&MZ_NETWORK_POLICIES),
13880        Builtin::Table(&MZ_NETWORK_POLICY_RULES),
13881        Builtin::Table(&MZ_LICENSE_KEYS),
13882        Builtin::Table(&MZ_REPLACEMENTS),
13883        Builtin::View(&MZ_RELATIONS),
13884        Builtin::View(&MZ_OBJECT_OID_ALIAS),
13885        Builtin::View(&MZ_OBJECTS),
13886        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
13887        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
13888        Builtin::View(&MZ_OBJECT_HISTORY),
13889        Builtin::View(&MZ_OBJECT_LIFETIMES),
13890        Builtin::Table(&MZ_OBJECT_GLOBAL_IDS),
13891        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
13892        Builtin::View(&MZ_ARRANGEMENT_SHARING),
13893        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
13894        Builtin::View(&MZ_ARRANGEMENT_SIZES),
13895        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
13896        Builtin::View(&MZ_DATAFLOWS),
13897        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
13898        Builtin::View(&MZ_DATAFLOW_CHANNELS),
13899        Builtin::View(&MZ_DATAFLOW_OPERATORS),
13900        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
13901        Builtin::View(&MZ_MAPPABLE_OBJECTS),
13902        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
13903        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
13904        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
13905        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
13906        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
13907        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
13908        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
13909        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
13910        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
13911        Builtin::View(&MZ_COMPUTE_EXPORTS),
13912        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
13913        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
13914        Builtin::View(&MZ_COMPUTE_FRONTIERS),
13915        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
13916        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
13917        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
13918        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
13919        Builtin::View(&MZ_MESSAGE_COUNTS),
13920        Builtin::View(&MZ_ACTIVE_PEEKS),
13921        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
13922        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
13923        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
13924        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
13925        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
13926        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
13927        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
13928        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
13929        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
13930        Builtin::View(&MZ_SCHEDULING_ELAPSED),
13931        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
13932        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
13933        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
13934        Builtin::View(&MZ_SHOW_COLUMNS),
13935        Builtin::View(&MZ_SHOW_CLUSTERS),
13936        Builtin::View(&MZ_SHOW_SECRETS),
13937        Builtin::View(&MZ_SHOW_DATABASES),
13938        Builtin::View(&MZ_SHOW_SCHEMAS),
13939        Builtin::View(&MZ_SHOW_TABLES),
13940        Builtin::View(&MZ_SHOW_VIEWS),
13941        Builtin::View(&MZ_SHOW_TYPES),
13942        Builtin::View(&MZ_SHOW_ROLES),
13943        Builtin::View(&MZ_SHOW_CONNECTIONS),
13944        Builtin::View(&MZ_SHOW_SOURCES),
13945        Builtin::View(&MZ_SHOW_SINKS),
13946        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
13947        Builtin::View(&MZ_SHOW_INDEXES),
13948        Builtin::View(&MZ_SHOW_CONTINUAL_TASKS),
13949        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
13950        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
13951        Builtin::View(&MZ_TIMEZONE_NAMES),
13952        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
13953        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
13954        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
13955        Builtin::View(&PG_NAMESPACE),
13956        Builtin::View(&PG_CLASS_ALL_DATABASES),
13957        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
13958        Builtin::View(&PG_CLASS),
13959        Builtin::View(&PG_DEPEND),
13960        Builtin::View(&PG_DATABASE),
13961        Builtin::View(&PG_INDEX),
13962        Builtin::View(&PG_TYPE_ALL_DATABASES),
13963        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
13964        Builtin::View(&PG_TYPE),
13965        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
13966        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
13967        Builtin::View(&PG_DESCRIPTION),
13968        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
13969        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
13970        Builtin::View(&PG_ATTRIBUTE),
13971        Builtin::View(&PG_PROC),
13972        Builtin::View(&PG_OPERATOR),
13973        Builtin::View(&PG_RANGE),
13974        Builtin::View(&PG_ENUM),
13975        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
13976        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
13977        Builtin::View(&PG_ATTRDEF),
13978        Builtin::View(&PG_SETTINGS),
13979        Builtin::View(&PG_AUTH_MEMBERS),
13980        Builtin::View(&PG_CONSTRAINT),
13981        Builtin::View(&PG_TABLES),
13982        Builtin::View(&PG_TABLESPACE),
13983        Builtin::View(&PG_ACCESS_METHODS),
13984        Builtin::View(&PG_LOCKS),
13985        Builtin::View(&PG_AUTHID_CORE),
13986        Builtin::Index(&PG_AUTHID_CORE_IND),
13987        Builtin::View(&PG_AUTHID),
13988        Builtin::View(&PG_ROLES),
13989        Builtin::View(&PG_USER),
13990        Builtin::View(&PG_VIEWS),
13991        Builtin::View(&PG_MATVIEWS),
13992        Builtin::View(&PG_COLLATION),
13993        Builtin::View(&PG_POLICY),
13994        Builtin::View(&PG_INHERITS),
13995        Builtin::View(&PG_AGGREGATE),
13996        Builtin::View(&PG_TRIGGER),
13997        Builtin::View(&PG_REWRITE),
13998        Builtin::View(&PG_EXTENSION),
13999        Builtin::View(&PG_EVENT_TRIGGER),
14000        Builtin::View(&PG_LANGUAGE),
14001        Builtin::View(&PG_SHDESCRIPTION),
14002        Builtin::View(&PG_INDEXES),
14003        Builtin::View(&PG_TIMEZONE_ABBREVS),
14004        Builtin::View(&PG_TIMEZONE_NAMES),
14005        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
14006        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
14007        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
14008        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
14009        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
14010        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
14011        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
14012        Builtin::View(&INFORMATION_SCHEMA_TABLES),
14013        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
14014        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
14015        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
14016        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
14017        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
14018        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
14019        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
14020        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
14021        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
14022        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
14023        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
14024        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
14025        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
14026        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
14027        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
14028        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
14029        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
14030        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
14031        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
14032        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
14033        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
14034        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
14035        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
14036        Builtin::View(&MZ_SINK_STATUSES),
14037        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
14038        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
14039        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
14040        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
14041        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
14042        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
14043        Builtin::Source(&MZ_SESSION_HISTORY),
14044        Builtin::Source(&MZ_SQL_TEXT),
14045        Builtin::View(&MZ_SQL_TEXT_REDACTED),
14046        Builtin::View(&MZ_RECENT_SQL_TEXT),
14047        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
14048        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
14049        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
14050        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
14051        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
14052        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
14053        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
14054        Builtin::View(&MZ_SOURCE_STATUSES),
14055        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
14056        Builtin::Source(&MZ_STORAGE_SHARDS),
14057        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
14058        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
14059        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
14060        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
14061        Builtin::View(&MZ_SOURCE_STATISTICS),
14062        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
14063        Builtin::View(&MZ_SINK_STATISTICS),
14064        Builtin::Index(&MZ_SINK_STATISTICS_IND),
14065        Builtin::View(&MZ_STORAGE_USAGE),
14066        Builtin::Source(&MZ_FRONTIERS),
14067        Builtin::View(&MZ_GLOBAL_FRONTIERS),
14068        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
14069        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
14070        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
14071        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
14072        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
14073        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
14074        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
14075        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
14076        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
14077        Builtin::View(&MZ_MATERIALIZATION_LAG),
14078        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
14079        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
14080        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
14081        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
14082        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
14083        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
14084        Builtin::View(&MZ_LIR_MAPPING),
14085        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
14086        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
14087        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
14088        Builtin::View(&MZ_HYDRATION_STATUSES),
14089        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
14090        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
14091        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
14092        Builtin::Index(&MZ_SHOW_DATABASES_IND),
14093        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
14094        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
14095        Builtin::Index(&MZ_SHOW_TABLES_IND),
14096        Builtin::Index(&MZ_SHOW_SOURCES_IND),
14097        Builtin::Index(&MZ_SHOW_VIEWS_IND),
14098        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
14099        Builtin::Index(&MZ_SHOW_SINKS_IND),
14100        Builtin::Index(&MZ_SHOW_TYPES_IND),
14101        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
14102        Builtin::Index(&MZ_SHOW_INDEXES_IND),
14103        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
14104        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
14105        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
14106        Builtin::Index(&MZ_SHOW_SECRETS_IND),
14107        Builtin::Index(&MZ_SHOW_ROLES_IND),
14108        Builtin::Index(&MZ_CLUSTERS_IND),
14109        Builtin::Index(&MZ_INDEXES_IND),
14110        Builtin::Index(&MZ_ROLES_IND),
14111        Builtin::Index(&MZ_SOURCES_IND),
14112        Builtin::Index(&MZ_SINKS_IND),
14113        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
14114        Builtin::Index(&MZ_CONTINUAL_TASKS_IND),
14115        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
14116        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
14117        Builtin::Index(&MZ_SINK_STATUSES_IND),
14118        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
14119        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
14120        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
14121        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
14122        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
14123        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
14124        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
14125        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
14126        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
14127        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
14128        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
14129        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
14130        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
14131        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
14132        Builtin::Index(&MZ_FRONTIERS_IND),
14133        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
14134        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
14135        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
14136        Builtin::Index(&MZ_COMMENTS_IND),
14137        Builtin::Index(&MZ_DATABASES_IND),
14138        Builtin::Index(&MZ_SCHEMAS_IND),
14139        Builtin::Index(&MZ_CONNECTIONS_IND),
14140        Builtin::Index(&MZ_TABLES_IND),
14141        Builtin::Index(&MZ_TYPES_IND),
14142        Builtin::Index(&MZ_OBJECTS_IND),
14143        Builtin::Index(&MZ_COLUMNS_IND),
14144        Builtin::Index(&MZ_SECRETS_IND),
14145        Builtin::Index(&MZ_VIEWS_IND),
14146        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
14147        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
14148        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
14149        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
14150        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
14151        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
14152        Builtin::Connection(&MZ_ANALYTICS),
14153        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT),
14154        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT),
14155        Builtin::ContinualTask(&MZ_WALLCLOCK_LAG_HISTORY_CT),
14156        Builtin::View(&MZ_INDEX_ADVICE),
14157    ]);
14158
14159    builtins.extend(notice::builtins());
14160
14161    builtins
14162});
14163pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
14164    &MZ_SYSTEM_ROLE,
14165    &MZ_SUPPORT_ROLE,
14166    &MZ_ANALYTICS_ROLE,
14167    &MZ_MONITOR_ROLE,
14168    &MZ_MONITOR_REDACTED,
14169];
14170pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
14171    &MZ_SYSTEM_CLUSTER,
14172    &MZ_CATALOG_SERVER_CLUSTER,
14173    &MZ_PROBE_CLUSTER,
14174    &MZ_SUPPORT_CLUSTER,
14175    &MZ_ANALYTICS_CLUSTER,
14176];
14177pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
14178    &MZ_SYSTEM_CLUSTER_REPLICA,
14179    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14180    &MZ_PROBE_CLUSTER_REPLICA,
14181];
14182
14183#[allow(non_snake_case)]
14184pub mod BUILTINS {
14185    use mz_sql::catalog::BuiltinsConfig;
14186
14187    use super::*;
14188
14189    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14190        BUILTINS_STATIC.iter().filter_map(|b| match b {
14191            Builtin::Log(log) => Some(*log),
14192            _ => None,
14193        })
14194    }
14195
14196    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14197        BUILTINS_STATIC.iter().filter_map(|b| match b {
14198            Builtin::Type(typ) => Some(*typ),
14199            _ => None,
14200        })
14201    }
14202
14203    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14204        BUILTINS_STATIC.iter().filter_map(|b| match b {
14205            Builtin::View(view) => Some(*view),
14206            _ => None,
14207        })
14208    }
14209
14210    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14211        BUILTINS_STATIC.iter().filter_map(|b| match b {
14212            Builtin::Func(func) => Some(func),
14213            _ => None,
14214        })
14215    }
14216
14217    pub fn iter(cfg: &BuiltinsConfig) -> impl Iterator<Item = &'static Builtin<NameReference>> {
14218        let include_continual_tasks = cfg.include_continual_tasks;
14219        BUILTINS_STATIC.iter().filter(move |x| match x {
14220            Builtin::ContinualTask(_) if !include_continual_tasks => false,
14221            _ => true,
14222        })
14223    }
14224}
14225
14226pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14227    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14228/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14229/// the builtin itself.
14230pub static BUILTIN_LOOKUP: LazyLock<
14231    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14232> = LazyLock::new(|| {
14233    // BUILTIN_LOOKUP is only ever used for lookups by key, it's not iterated,
14234    // so it's safe to include all of them, regardless of BuiltinConfig. We
14235    // enforce this statically by using the mz_ore HashMap which disallows
14236    // iteration.
14237    BUILTINS_STATIC
14238        .iter()
14239        .enumerate()
14240        .map(|(idx, builtin)| {
14241            (
14242                SystemObjectDescription {
14243                    schema_name: builtin.schema().to_string(),
14244                    object_type: builtin.catalog_item_type(),
14245                    object_name: builtin.name().to_string(),
14246                },
14247                (idx, builtin),
14248            )
14249        })
14250        .collect()
14251});
14252
14253#[mz_ore::test]
14254#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14255fn test_builtin_type_schema() {
14256    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14257
14258    for typ in BUILTINS::types() {
14259        if typ.oid < FIRST_MATERIALIZE_OID {
14260            assert_eq!(
14261                typ.schema, PG_CATALOG_SCHEMA,
14262                "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14263            );
14264        } else {
14265            // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the mz_catalog
14266            // schema.
14267            assert_eq!(
14268                typ.schema, MZ_CATALOG_SCHEMA,
14269                "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14270            );
14271        }
14272    }
14273}