Skip to main content

mz_catalog/
builtin.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Built-in catalog items.
11//!
12//! Builtins exist in the `mz_catalog` ambient schema. They are automatically
13//! installed into the catalog when it is opened. Their definitions are not
14//! persisted in the catalog, but hardcoded in this module. This makes it easy
15//! to add new builtins, or change the definition of existing builtins, in new
16//! versions of Materialize.
17//!
18//! Builtin's names, columns, and types are part of the stable API of
19//! Materialize. Be careful to maintain backwards compatibility when changing
20//! definitions of existing builtins!
21//!
22//! More information about builtin system tables and types can be found in
23//! <https://materialize.com/docs/sql/system-catalog/>.
24
25mod builtin;
26pub mod notice;
27
28use std::collections::BTreeMap;
29use std::hash::Hash;
30use std::string::ToString;
31use std::sync::LazyLock;
32
33use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
34use mz_ore::collections::HashMap;
35use mz_pgrepr::oid;
36use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
37use mz_repr::adt::numeric::NumericMaxScale;
38use mz_repr::namespaces::{
39    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_INTROSPECTION_SCHEMA,
40    MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA,
41};
42use mz_repr::role_id::RoleId;
43use mz_repr::{RelationDesc, SqlRelationType, SqlScalarType};
44use mz_sql::catalog::RoleAttributesRaw;
45use mz_sql::catalog::{
46    CatalogItemType, CatalogType, CatalogTypeDetails, CatalogTypePgMetadata, NameReference,
47    ObjectType, SystemObjectType, TypeReference,
48};
49use mz_sql::rbac;
50use mz_sql::session::user::{
51    ANALYTICS_USER_NAME, JWT_SYNC_ROLE_NAME, MZ_ANALYTICS_ROLE_ID, MZ_JWT_SYNC_ROLE_ID,
52    MZ_MONITOR_REDACTED_ROLE_ID, MZ_MONITOR_ROLE_ID, MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID,
53    SUPPORT_USER_NAME, SYSTEM_USER_NAME,
54};
55use mz_storage_client::controller::IntrospectionType;
56use mz_storage_client::healthcheck::WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC;
57use mz_storage_client::healthcheck::{
58    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_PREPARED_STATEMENT_HISTORY_DESC,
59    MZ_SESSION_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC, MZ_SOURCE_STATUS_HISTORY_DESC,
60    MZ_SQL_TEXT_DESC, MZ_STATEMENT_EXECUTION_HISTORY_DESC, REPLICA_METRICS_HISTORY_DESC,
61    REPLICA_STATUS_HISTORY_DESC, WALLCLOCK_LAG_HISTORY_DESC,
62};
63use mz_storage_client::statistics::{MZ_SINK_STATISTICS_RAW_DESC, MZ_SOURCE_STATISTICS_RAW_DESC};
64use serde::Serialize;
65
66use crate::durable::objects::SystemObjectDescription;
67use crate::memory::objects::DataSourceDesc;
68
69pub const BUILTIN_PREFIXES: &[&str] = &["mz_", "pg_", "external_"];
70const BUILTIN_CLUSTER_REPLICA_NAME: &str = "r1";
71
72/// A sentinel used in place of a fingerprint that indicates that a builtin
73/// object is runtime alterable. Runtime alterable objects don't have meaningful
74/// fingerprints because they may have been intentionally changed by the user
75/// after creation.
76// NOTE(benesch): ideally we'd use a fingerprint type that used a sum type
77// rather than a loosely typed string to represent the runtime alterable
78// state like so:
79//
80//     enum Fingerprint {
81//         SqlText(String),
82//         RuntimeAlterable,
83//     }
84//
85// However, that would entail a complicated migration for the existing system object
86// mapping collection stored on disk.
87pub const RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL: &str = "<RUNTIME-ALTERABLE>";
88
89#[derive(Clone, Debug)]
90pub enum Builtin<T: 'static + TypeReference> {
91    Log(&'static BuiltinLog),
92    Table(&'static BuiltinTable),
93    View(&'static BuiltinView),
94    MaterializedView(&'static BuiltinMaterializedView),
95    Type(&'static BuiltinType<T>),
96    Func(BuiltinFunc),
97    Source(&'static BuiltinSource),
98    Index(&'static BuiltinIndex),
99    Connection(&'static BuiltinConnection),
100}
101
102impl<T: TypeReference> Builtin<T> {
103    pub fn name(&self) -> &'static str {
104        match self {
105            Builtin::Log(log) => log.name,
106            Builtin::Table(table) => table.name,
107            Builtin::View(view) => view.name,
108            Builtin::MaterializedView(mv) => mv.name,
109            Builtin::Type(typ) => typ.name,
110            Builtin::Func(func) => func.name,
111            Builtin::Source(coll) => coll.name,
112            Builtin::Index(index) => index.name,
113            Builtin::Connection(connection) => connection.name,
114        }
115    }
116
117    pub fn schema(&self) -> &'static str {
118        match self {
119            Builtin::Log(log) => log.schema,
120            Builtin::Table(table) => table.schema,
121            Builtin::View(view) => view.schema,
122            Builtin::MaterializedView(mv) => mv.schema,
123            Builtin::Type(typ) => typ.schema,
124            Builtin::Func(func) => func.schema,
125            Builtin::Source(coll) => coll.schema,
126            Builtin::Index(index) => index.schema,
127            Builtin::Connection(connection) => connection.schema,
128        }
129    }
130
131    pub fn catalog_item_type(&self) -> CatalogItemType {
132        match self {
133            Builtin::Log(_) => CatalogItemType::Source,
134            Builtin::Source(_) => CatalogItemType::Source,
135            Builtin::Table(_) => CatalogItemType::Table,
136            Builtin::View(_) => CatalogItemType::View,
137            Builtin::MaterializedView(_) => CatalogItemType::MaterializedView,
138            Builtin::Type(_) => CatalogItemType::Type,
139            Builtin::Func(_) => CatalogItemType::Func,
140            Builtin::Index(_) => CatalogItemType::Index,
141            Builtin::Connection(_) => CatalogItemType::Connection,
142        }
143    }
144
145    /// Whether the object can be altered at runtime by its owner.
146    pub fn runtime_alterable(&self) -> bool {
147        match self {
148            Builtin::Connection(c) => c.runtime_alterable,
149            _ => false,
150        }
151    }
152}
153
154#[derive(Clone, Debug, Hash, Serialize)]
155pub struct BuiltinLog {
156    pub variant: LogVariant,
157    pub name: &'static str,
158    pub schema: &'static str,
159    pub oid: u32,
160    /// ACL items to apply to the object
161    pub access: Vec<MzAclItem>,
162}
163
164#[derive(Clone, Hash, Debug, PartialEq, Eq)]
165pub struct BuiltinTable {
166    pub name: &'static str,
167    pub schema: &'static str,
168    pub oid: u32,
169    pub desc: RelationDesc,
170    pub column_comments: BTreeMap<&'static str, &'static str>,
171    /// Whether the table's retention policy is controlled by
172    /// the system variable `METRICS_RETENTION`
173    pub is_retained_metrics_object: bool,
174    /// ACL items to apply to the object
175    pub access: Vec<MzAclItem>,
176}
177
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub struct BuiltinSource {
180    pub name: &'static str,
181    pub schema: &'static str,
182    pub oid: u32,
183    pub desc: RelationDesc,
184    pub column_comments: BTreeMap<&'static str, &'static str>,
185    pub data_source: DataSourceDesc,
186    /// Whether the source's retention policy is controlled by
187    /// the system variable `METRICS_RETENTION`
188    pub is_retained_metrics_object: bool,
189    /// ACL items to apply to the object
190    pub access: Vec<MzAclItem>,
191}
192
193#[derive(Hash, Debug)]
194pub struct BuiltinView {
195    pub name: &'static str,
196    pub schema: &'static str,
197    pub oid: u32,
198    pub desc: RelationDesc,
199    pub column_comments: BTreeMap<&'static str, &'static str>,
200    pub sql: &'static str,
201    /// ACL items to apply to the object
202    pub access: Vec<MzAclItem>,
203}
204
205impl BuiltinView {
206    pub fn create_sql(&self) -> String {
207        format!("CREATE VIEW {}.{} AS {}", self.schema, self.name, self.sql)
208    }
209}
210
211#[derive(Hash, Debug)]
212pub struct BuiltinMaterializedView {
213    pub name: &'static str,
214    pub schema: &'static str,
215    pub oid: u32,
216    pub desc: RelationDesc,
217    pub column_comments: BTreeMap<&'static str, &'static str>,
218    /// SQL fragment for the MV, following `CREATE MATERIALIZED VIEW [name]`
219    ///
220    /// Format: `IN CLUSTER [cluster_name] AS [query]`
221    pub sql: &'static str,
222    /// Whether the MV's retention policy is controlled by
223    /// the system variable `METRICS_RETENTION`
224    pub is_retained_metrics_object: bool,
225    /// ACL items to apply to the object
226    pub access: Vec<MzAclItem>,
227}
228
229impl BuiltinMaterializedView {
230    pub fn create_sql(&self) -> String {
231        format!(
232            "CREATE MATERIALIZED VIEW {}.{} {}",
233            self.schema, self.name, self.sql
234        )
235    }
236}
237
238#[derive(Debug)]
239pub struct BuiltinType<T: TypeReference> {
240    pub name: &'static str,
241    pub schema: &'static str,
242    pub oid: u32,
243    pub details: CatalogTypeDetails<T>,
244}
245
246#[derive(Clone, Debug)]
247pub struct BuiltinFunc {
248    pub schema: &'static str,
249    pub name: &'static str,
250    pub inner: &'static mz_sql::func::Func,
251}
252
253/// Note: When creating a built-in index, it's usually best to choose a key that has only one
254/// component. For example, if you created an index
255/// `ON mz_internal.mz_object_lifetimes (id, object_type)`, then this index couldn't be used for a
256/// lookup for `WHERE object_type = ...`, and neither for joins keyed on just `id`.
257/// See <https://materialize.com/docs/transform-data/optimization/#matching-multi-column-indexes-to-multi-column-where-clauses>
258#[derive(Debug)]
259pub struct BuiltinIndex {
260    pub name: &'static str,
261    pub schema: &'static str,
262    pub oid: u32,
263    /// SQL fragment for the index, following `CREATE INDEX [name]`
264    ///
265    /// Format: `IN CLUSTER [cluster_name] ON [table_name] ([column_exprs])`
266    pub sql: &'static str,
267    pub is_retained_metrics_object: bool,
268}
269
270impl BuiltinIndex {
271    pub fn create_sql(&self) -> String {
272        format!("CREATE INDEX {}\n{}", self.name, self.sql)
273    }
274}
275
276#[derive(Hash, Debug)]
277pub struct BuiltinConnection {
278    pub name: &'static str,
279    pub schema: &'static str,
280    pub oid: u32,
281    pub sql: &'static str,
282    pub access: &'static [MzAclItem],
283    pub owner_id: &'static RoleId,
284    /// Whether the object can be altered at runtime by its owner.
285    ///
286    /// Note that when `runtime_alterable` is true, changing the `sql` in future
287    /// versions does not trigger a migration.
288    pub runtime_alterable: bool,
289}
290
291#[derive(Clone, Debug)]
292pub struct BuiltinRole {
293    pub id: RoleId,
294    /// Name of the builtin role.
295    ///
296    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
297    pub name: &'static str,
298    pub oid: u32,
299    pub attributes: RoleAttributesRaw,
300}
301
302#[derive(Clone, Debug)]
303pub struct BuiltinCluster {
304    /// Name of the cluster.
305    ///
306    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
307    pub name: &'static str,
308    pub privileges: &'static [MzAclItem],
309    pub owner_id: &'static RoleId,
310}
311
312#[derive(Clone, Debug, PartialEq, Eq)]
313pub struct BuiltinClusterReplica {
314    /// Name of the compute replica.
315    pub name: &'static str,
316    /// Name of the cluster that this replica belongs to.
317    pub cluster_name: &'static str,
318}
319
320/// Uniquely identifies the definition of a builtin object.
321pub trait Fingerprint {
322    fn fingerprint(&self) -> String;
323}
324
325impl<T: TypeReference> Fingerprint for &Builtin<T> {
326    fn fingerprint(&self) -> String {
327        match self {
328            Builtin::Log(log) => log.fingerprint(),
329            Builtin::Table(table) => table.fingerprint(),
330            Builtin::View(view) => view.fingerprint(),
331            Builtin::MaterializedView(mv) => mv.fingerprint(),
332            Builtin::Type(typ) => typ.fingerprint(),
333            Builtin::Func(func) => func.fingerprint(),
334            Builtin::Source(coll) => coll.fingerprint(),
335            Builtin::Index(index) => index.fingerprint(),
336            Builtin::Connection(connection) => connection.fingerprint(),
337        }
338    }
339}
340
341// Types and Funcs never change fingerprints so we just return constant 0
342impl<T: TypeReference> Fingerprint for &BuiltinType<T> {
343    fn fingerprint(&self) -> String {
344        "".to_string()
345    }
346}
347
348impl Fingerprint for &BuiltinFunc {
349    fn fingerprint(&self) -> String {
350        "".to_string()
351    }
352}
353
354impl Fingerprint for &BuiltinLog {
355    fn fingerprint(&self) -> String {
356        self.variant.desc().fingerprint()
357    }
358}
359
360impl Fingerprint for &BuiltinTable {
361    fn fingerprint(&self) -> String {
362        self.desc.fingerprint()
363    }
364}
365
366impl Fingerprint for &BuiltinView {
367    fn fingerprint(&self) -> String {
368        self.sql.to_string()
369    }
370}
371
372impl Fingerprint for &BuiltinSource {
373    fn fingerprint(&self) -> String {
374        self.desc.fingerprint()
375    }
376}
377
378impl Fingerprint for &BuiltinMaterializedView {
379    fn fingerprint(&self) -> String {
380        self.create_sql()
381    }
382}
383
384impl Fingerprint for &BuiltinIndex {
385    fn fingerprint(&self) -> String {
386        self.create_sql()
387    }
388}
389
390impl Fingerprint for &BuiltinConnection {
391    fn fingerprint(&self) -> String {
392        self.sql.to_string()
393    }
394}
395
396impl Fingerprint for RelationDesc {
397    fn fingerprint(&self) -> String {
398        self.typ().fingerprint()
399    }
400}
401
402impl Fingerprint for SqlRelationType {
403    fn fingerprint(&self) -> String {
404        serde_json::to_string(self).expect("serialization cannot fail")
405    }
406}
407
408// Builtin definitions below. Ensure you add new builtins to the `BUILTINS` map.
409//
410// You SHOULD NOT delete a builtin. If you do, you will break any downstream
411// user objects that depended on the builtin.
412//
413// Builtins are loaded in dependency order, so a builtin must appear in `BUILTINS`
414// before any items it depends upon.
415//
416// WARNING: if you change the definition of an existing builtin item, you must
417// be careful to maintain backwards compatibility! Adding new columns is safe.
418// Removing a column, changing the name of a column, or changing the type of a
419// column is not safe, as persisted user views may depend upon that column.
420
421// The following types are the list of builtin data types available
422// in Materialize. This list is derived from the `pg_type` table in PostgreSQL.
423//
424// Builtin types cannot be created, updated, or deleted. Their OIDs
425// are static, unlike other objects, to match the type OIDs defined by Postgres.
426
427pub const TYPE_BOOL: BuiltinType<NameReference> = BuiltinType {
428    name: "bool",
429    schema: PG_CATALOG_SCHEMA,
430    oid: oid::TYPE_BOOL_OID,
431    details: CatalogTypeDetails {
432        typ: CatalogType::Bool,
433        array_id: None,
434        pg_metadata: Some(CatalogTypePgMetadata {
435            typinput_oid: 1242,
436            typreceive_oid: 2436,
437        }),
438    },
439};
440
441pub const TYPE_BYTEA: BuiltinType<NameReference> = BuiltinType {
442    name: "bytea",
443    schema: PG_CATALOG_SCHEMA,
444    oid: oid::TYPE_BYTEA_OID,
445    details: CatalogTypeDetails {
446        typ: CatalogType::Bytes,
447        array_id: None,
448        pg_metadata: Some(CatalogTypePgMetadata {
449            typinput_oid: 1244,
450            typreceive_oid: 2412,
451        }),
452    },
453};
454
455pub const TYPE_INT8: BuiltinType<NameReference> = BuiltinType {
456    name: "int8",
457    schema: PG_CATALOG_SCHEMA,
458    oid: oid::TYPE_INT8_OID,
459    details: CatalogTypeDetails {
460        typ: CatalogType::Int64,
461        array_id: None,
462        pg_metadata: Some(CatalogTypePgMetadata {
463            typinput_oid: 460,
464            typreceive_oid: 2408,
465        }),
466    },
467};
468
469pub const TYPE_INT4: BuiltinType<NameReference> = BuiltinType {
470    name: "int4",
471    schema: PG_CATALOG_SCHEMA,
472    oid: oid::TYPE_INT4_OID,
473    details: CatalogTypeDetails {
474        typ: CatalogType::Int32,
475        array_id: None,
476        pg_metadata: Some(CatalogTypePgMetadata {
477            typinput_oid: 42,
478            typreceive_oid: 2406,
479        }),
480    },
481};
482
483pub const TYPE_TEXT: BuiltinType<NameReference> = BuiltinType {
484    name: "text",
485    schema: PG_CATALOG_SCHEMA,
486    oid: oid::TYPE_TEXT_OID,
487    details: CatalogTypeDetails {
488        typ: CatalogType::String,
489        array_id: None,
490        pg_metadata: Some(CatalogTypePgMetadata {
491            typinput_oid: 46,
492            typreceive_oid: 2414,
493        }),
494    },
495};
496
497pub const TYPE_OID: BuiltinType<NameReference> = BuiltinType {
498    name: "oid",
499    schema: PG_CATALOG_SCHEMA,
500    oid: oid::TYPE_OID_OID,
501    details: CatalogTypeDetails {
502        typ: CatalogType::Oid,
503        array_id: None,
504        pg_metadata: Some(CatalogTypePgMetadata {
505            typinput_oid: 1798,
506            typreceive_oid: 2418,
507        }),
508    },
509};
510
511pub const TYPE_FLOAT4: BuiltinType<NameReference> = BuiltinType {
512    name: "float4",
513    schema: PG_CATALOG_SCHEMA,
514    oid: oid::TYPE_FLOAT4_OID,
515    details: CatalogTypeDetails {
516        typ: CatalogType::Float32,
517        array_id: None,
518        pg_metadata: Some(CatalogTypePgMetadata {
519            typinput_oid: 200,
520            typreceive_oid: 2424,
521        }),
522    },
523};
524
525pub const TYPE_FLOAT8: BuiltinType<NameReference> = BuiltinType {
526    name: "float8",
527    schema: PG_CATALOG_SCHEMA,
528    oid: oid::TYPE_FLOAT8_OID,
529    details: CatalogTypeDetails {
530        typ: CatalogType::Float64,
531        array_id: None,
532        pg_metadata: Some(CatalogTypePgMetadata {
533            typinput_oid: 214,
534            typreceive_oid: 2426,
535        }),
536    },
537};
538
539pub const TYPE_BOOL_ARRAY: BuiltinType<NameReference> = BuiltinType {
540    name: "_bool",
541    schema: PG_CATALOG_SCHEMA,
542    oid: oid::TYPE_BOOL_ARRAY_OID,
543    details: CatalogTypeDetails {
544        typ: CatalogType::Array {
545            element_reference: TYPE_BOOL.name,
546        },
547        array_id: None,
548        pg_metadata: Some(CatalogTypePgMetadata {
549            typinput_oid: 750,
550            typreceive_oid: 2400,
551        }),
552    },
553};
554
555pub const TYPE_BYTEA_ARRAY: BuiltinType<NameReference> = BuiltinType {
556    name: "_bytea",
557    schema: PG_CATALOG_SCHEMA,
558    oid: oid::TYPE_BYTEA_ARRAY_OID,
559    details: CatalogTypeDetails {
560        typ: CatalogType::Array {
561            element_reference: TYPE_BYTEA.name,
562        },
563        array_id: None,
564        pg_metadata: Some(CatalogTypePgMetadata {
565            typinput_oid: 750,
566            typreceive_oid: 2400,
567        }),
568    },
569};
570
571pub const TYPE_INT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
572    name: "_int4",
573    schema: PG_CATALOG_SCHEMA,
574    oid: oid::TYPE_INT4_ARRAY_OID,
575    details: CatalogTypeDetails {
576        typ: CatalogType::Array {
577            element_reference: TYPE_INT4.name,
578        },
579        array_id: None,
580        pg_metadata: Some(CatalogTypePgMetadata {
581            typinput_oid: 750,
582            typreceive_oid: 2400,
583        }),
584    },
585};
586
587pub const TYPE_TEXT_ARRAY: BuiltinType<NameReference> = BuiltinType {
588    name: "_text",
589    schema: PG_CATALOG_SCHEMA,
590    oid: oid::TYPE_TEXT_ARRAY_OID,
591    details: CatalogTypeDetails {
592        typ: CatalogType::Array {
593            element_reference: TYPE_TEXT.name,
594        },
595        array_id: None,
596        pg_metadata: Some(CatalogTypePgMetadata {
597            typinput_oid: 750,
598            typreceive_oid: 2400,
599        }),
600    },
601};
602
603pub const TYPE_INT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
604    name: "_int8",
605    schema: PG_CATALOG_SCHEMA,
606    oid: oid::TYPE_INT8_ARRAY_OID,
607    details: CatalogTypeDetails {
608        typ: CatalogType::Array {
609            element_reference: TYPE_INT8.name,
610        },
611        array_id: None,
612        pg_metadata: Some(CatalogTypePgMetadata {
613            typinput_oid: 750,
614            typreceive_oid: 2400,
615        }),
616    },
617};
618
619pub const TYPE_FLOAT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
620    name: "_float4",
621    schema: PG_CATALOG_SCHEMA,
622    oid: oid::TYPE_FLOAT4_ARRAY_OID,
623    details: CatalogTypeDetails {
624        typ: CatalogType::Array {
625            element_reference: TYPE_FLOAT4.name,
626        },
627        array_id: None,
628        pg_metadata: Some(CatalogTypePgMetadata {
629            typinput_oid: 750,
630            typreceive_oid: 2400,
631        }),
632    },
633};
634
635pub const TYPE_FLOAT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
636    name: "_float8",
637    schema: PG_CATALOG_SCHEMA,
638    oid: oid::TYPE_FLOAT8_ARRAY_OID,
639    details: CatalogTypeDetails {
640        typ: CatalogType::Array {
641            element_reference: TYPE_FLOAT8.name,
642        },
643        array_id: None,
644        pg_metadata: Some(CatalogTypePgMetadata {
645            typinput_oid: 750,
646            typreceive_oid: 2400,
647        }),
648    },
649};
650
651pub const TYPE_OID_ARRAY: BuiltinType<NameReference> = BuiltinType {
652    name: "_oid",
653    schema: PG_CATALOG_SCHEMA,
654    oid: oid::TYPE_OID_ARRAY_OID,
655    details: CatalogTypeDetails {
656        typ: CatalogType::Array {
657            element_reference: TYPE_OID.name,
658        },
659        array_id: None,
660        pg_metadata: Some(CatalogTypePgMetadata {
661            typinput_oid: 750,
662            typreceive_oid: 2400,
663        }),
664    },
665};
666
667pub const TYPE_DATE: BuiltinType<NameReference> = BuiltinType {
668    name: "date",
669    schema: PG_CATALOG_SCHEMA,
670    oid: oid::TYPE_DATE_OID,
671    details: CatalogTypeDetails {
672        typ: CatalogType::Date,
673        array_id: None,
674        pg_metadata: Some(CatalogTypePgMetadata {
675            typinput_oid: 1084,
676            typreceive_oid: 2468,
677        }),
678    },
679};
680
681pub const TYPE_TIME: BuiltinType<NameReference> = BuiltinType {
682    name: "time",
683    schema: PG_CATALOG_SCHEMA,
684    oid: oid::TYPE_TIME_OID,
685    details: CatalogTypeDetails {
686        typ: CatalogType::Time,
687        array_id: None,
688        pg_metadata: Some(CatalogTypePgMetadata {
689            typinput_oid: 1143,
690            typreceive_oid: 2470,
691        }),
692    },
693};
694
695pub const TYPE_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
696    name: "timestamp",
697    schema: PG_CATALOG_SCHEMA,
698    oid: oid::TYPE_TIMESTAMP_OID,
699    details: CatalogTypeDetails {
700        typ: CatalogType::Timestamp,
701        array_id: None,
702        pg_metadata: Some(CatalogTypePgMetadata {
703            typinput_oid: 1312,
704            typreceive_oid: 2474,
705        }),
706    },
707};
708
709pub const TYPE_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
710    name: "_timestamp",
711    schema: PG_CATALOG_SCHEMA,
712    oid: oid::TYPE_TIMESTAMP_ARRAY_OID,
713    details: CatalogTypeDetails {
714        typ: CatalogType::Array {
715            element_reference: TYPE_TIMESTAMP.name,
716        },
717        array_id: None,
718        pg_metadata: Some(CatalogTypePgMetadata {
719            typinput_oid: 750,
720            typreceive_oid: 2400,
721        }),
722    },
723};
724
725pub const TYPE_DATE_ARRAY: BuiltinType<NameReference> = BuiltinType {
726    name: "_date",
727    schema: PG_CATALOG_SCHEMA,
728    oid: oid::TYPE_DATE_ARRAY_OID,
729    details: CatalogTypeDetails {
730        typ: CatalogType::Array {
731            element_reference: TYPE_DATE.name,
732        },
733        array_id: None,
734        pg_metadata: Some(CatalogTypePgMetadata {
735            typinput_oid: 750,
736            typreceive_oid: 2400,
737        }),
738    },
739};
740
741pub const TYPE_TIME_ARRAY: BuiltinType<NameReference> = BuiltinType {
742    name: "_time",
743    schema: PG_CATALOG_SCHEMA,
744    oid: oid::TYPE_TIME_ARRAY_OID,
745    details: CatalogTypeDetails {
746        typ: CatalogType::Array {
747            element_reference: TYPE_TIME.name,
748        },
749        array_id: None,
750        pg_metadata: Some(CatalogTypePgMetadata {
751            typinput_oid: 750,
752            typreceive_oid: 2400,
753        }),
754    },
755};
756
757pub const TYPE_TIMESTAMPTZ: BuiltinType<NameReference> = BuiltinType {
758    name: "timestamptz",
759    schema: PG_CATALOG_SCHEMA,
760    oid: oid::TYPE_TIMESTAMPTZ_OID,
761    details: CatalogTypeDetails {
762        typ: CatalogType::TimestampTz,
763        array_id: None,
764        pg_metadata: Some(CatalogTypePgMetadata {
765            typinput_oid: 1150,
766            typreceive_oid: 2476,
767        }),
768    },
769};
770
771pub const TYPE_TIMESTAMPTZ_ARRAY: BuiltinType<NameReference> = BuiltinType {
772    name: "_timestamptz",
773    schema: PG_CATALOG_SCHEMA,
774    oid: oid::TYPE_TIMESTAMPTZ_ARRAY_OID,
775    details: CatalogTypeDetails {
776        typ: CatalogType::Array {
777            element_reference: TYPE_TIMESTAMPTZ.name,
778        },
779        array_id: None,
780        pg_metadata: Some(CatalogTypePgMetadata {
781            typinput_oid: 750,
782            typreceive_oid: 2400,
783        }),
784    },
785};
786
787pub const TYPE_INTERVAL: BuiltinType<NameReference> = BuiltinType {
788    name: "interval",
789    schema: PG_CATALOG_SCHEMA,
790    oid: oid::TYPE_INTERVAL_OID,
791    details: CatalogTypeDetails {
792        typ: CatalogType::Interval,
793        array_id: None,
794        pg_metadata: Some(CatalogTypePgMetadata {
795            typinput_oid: 1160,
796            typreceive_oid: 2478,
797        }),
798    },
799};
800
801pub const TYPE_INTERVAL_ARRAY: BuiltinType<NameReference> = BuiltinType {
802    name: "_interval",
803    schema: PG_CATALOG_SCHEMA,
804    oid: oid::TYPE_INTERVAL_ARRAY_OID,
805    details: CatalogTypeDetails {
806        typ: CatalogType::Array {
807            element_reference: TYPE_INTERVAL.name,
808        },
809        array_id: None,
810        pg_metadata: Some(CatalogTypePgMetadata {
811            typinput_oid: 750,
812            typreceive_oid: 2400,
813        }),
814    },
815};
816
817pub const TYPE_NAME: BuiltinType<NameReference> = BuiltinType {
818    name: "name",
819    schema: PG_CATALOG_SCHEMA,
820    oid: oid::TYPE_NAME_OID,
821    details: CatalogTypeDetails {
822        typ: CatalogType::PgLegacyName,
823        array_id: None,
824        pg_metadata: Some(CatalogTypePgMetadata {
825            typinput_oid: 34,
826            typreceive_oid: 2422,
827        }),
828    },
829};
830
831pub const TYPE_NAME_ARRAY: BuiltinType<NameReference> = BuiltinType {
832    name: "_name",
833    schema: PG_CATALOG_SCHEMA,
834    oid: oid::TYPE_NAME_ARRAY_OID,
835    details: CatalogTypeDetails {
836        typ: CatalogType::Array {
837            element_reference: TYPE_NAME.name,
838        },
839        array_id: None,
840        pg_metadata: Some(CatalogTypePgMetadata {
841            typinput_oid: 750,
842            typreceive_oid: 2400,
843        }),
844    },
845};
846
847pub const TYPE_NUMERIC: BuiltinType<NameReference> = BuiltinType {
848    name: "numeric",
849    schema: PG_CATALOG_SCHEMA,
850    oid: oid::TYPE_NUMERIC_OID,
851    details: CatalogTypeDetails {
852        typ: CatalogType::Numeric,
853        array_id: None,
854        pg_metadata: Some(CatalogTypePgMetadata {
855            typinput_oid: 1701,
856            typreceive_oid: 2460,
857        }),
858    },
859};
860
861pub const TYPE_NUMERIC_ARRAY: BuiltinType<NameReference> = BuiltinType {
862    name: "_numeric",
863    schema: PG_CATALOG_SCHEMA,
864    oid: oid::TYPE_NUMERIC_ARRAY_OID,
865    details: CatalogTypeDetails {
866        typ: CatalogType::Array {
867            element_reference: TYPE_NUMERIC.name,
868        },
869        array_id: None,
870        pg_metadata: Some(CatalogTypePgMetadata {
871            typinput_oid: 750,
872            typreceive_oid: 2400,
873        }),
874    },
875};
876
877pub const TYPE_RECORD: BuiltinType<NameReference> = BuiltinType {
878    name: "record",
879    schema: PG_CATALOG_SCHEMA,
880    oid: oid::TYPE_RECORD_OID,
881    details: CatalogTypeDetails {
882        typ: CatalogType::Pseudo,
883        array_id: None,
884        pg_metadata: Some(CatalogTypePgMetadata {
885            typinput_oid: 2290,
886            typreceive_oid: 2402,
887        }),
888    },
889};
890
891pub const TYPE_RECORD_ARRAY: BuiltinType<NameReference> = BuiltinType {
892    name: "_record",
893    schema: PG_CATALOG_SCHEMA,
894    oid: oid::TYPE_RECORD_ARRAY_OID,
895    details: CatalogTypeDetails {
896        typ: CatalogType::Array {
897            element_reference: TYPE_RECORD.name,
898        },
899        array_id: None,
900        pg_metadata: Some(CatalogTypePgMetadata {
901            typinput_oid: 750,
902            typreceive_oid: 2400,
903        }),
904    },
905};
906
907pub const TYPE_UUID: BuiltinType<NameReference> = BuiltinType {
908    name: "uuid",
909    schema: PG_CATALOG_SCHEMA,
910    oid: oid::TYPE_UUID_OID,
911    details: CatalogTypeDetails {
912        typ: CatalogType::Uuid,
913        array_id: None,
914        pg_metadata: Some(CatalogTypePgMetadata {
915            typinput_oid: 2952,
916            typreceive_oid: 2961,
917        }),
918    },
919};
920
921pub const TYPE_UUID_ARRAY: BuiltinType<NameReference> = BuiltinType {
922    name: "_uuid",
923    schema: PG_CATALOG_SCHEMA,
924    oid: oid::TYPE_UUID_ARRAY_OID,
925    details: CatalogTypeDetails {
926        typ: CatalogType::Array {
927            element_reference: TYPE_UUID.name,
928        },
929        array_id: None,
930        pg_metadata: Some(CatalogTypePgMetadata {
931            typinput_oid: 750,
932            typreceive_oid: 2400,
933        }),
934    },
935};
936
937pub const TYPE_JSONB: BuiltinType<NameReference> = BuiltinType {
938    name: "jsonb",
939    schema: PG_CATALOG_SCHEMA,
940    oid: oid::TYPE_JSONB_OID,
941    details: CatalogTypeDetails {
942        typ: CatalogType::Jsonb,
943        array_id: None,
944        pg_metadata: Some(CatalogTypePgMetadata {
945            typinput_oid: 3806,
946            typreceive_oid: 3805,
947        }),
948    },
949};
950
951pub const TYPE_JSONB_ARRAY: BuiltinType<NameReference> = BuiltinType {
952    name: "_jsonb",
953    schema: PG_CATALOG_SCHEMA,
954    oid: oid::TYPE_JSONB_ARRAY_OID,
955    details: CatalogTypeDetails {
956        typ: CatalogType::Array {
957            element_reference: TYPE_JSONB.name,
958        },
959        array_id: None,
960        pg_metadata: Some(CatalogTypePgMetadata {
961            typinput_oid: 750,
962            typreceive_oid: 2400,
963        }),
964    },
965};
966
967pub const TYPE_ANY: BuiltinType<NameReference> = BuiltinType {
968    name: "any",
969    schema: PG_CATALOG_SCHEMA,
970    oid: oid::TYPE_ANY_OID,
971    details: CatalogTypeDetails {
972        typ: CatalogType::Pseudo,
973        array_id: None,
974        pg_metadata: Some(CatalogTypePgMetadata {
975            typinput_oid: 2294,
976            typreceive_oid: 0,
977        }),
978    },
979};
980
981pub const TYPE_ANYARRAY: BuiltinType<NameReference> = BuiltinType {
982    name: "anyarray",
983    schema: PG_CATALOG_SCHEMA,
984    oid: oid::TYPE_ANYARRAY_OID,
985    details: CatalogTypeDetails {
986        typ: CatalogType::Pseudo,
987        array_id: None,
988        pg_metadata: Some(CatalogTypePgMetadata {
989            typinput_oid: 2296,
990            typreceive_oid: 2502,
991        }),
992    },
993};
994
995pub const TYPE_ANYELEMENT: BuiltinType<NameReference> = BuiltinType {
996    name: "anyelement",
997    schema: PG_CATALOG_SCHEMA,
998    oid: oid::TYPE_ANYELEMENT_OID,
999    details: CatalogTypeDetails {
1000        typ: CatalogType::Pseudo,
1001        array_id: None,
1002        pg_metadata: Some(CatalogTypePgMetadata {
1003            typinput_oid: 2312,
1004            typreceive_oid: 0,
1005        }),
1006    },
1007};
1008
1009pub const TYPE_ANYNONARRAY: BuiltinType<NameReference> = BuiltinType {
1010    name: "anynonarray",
1011    schema: PG_CATALOG_SCHEMA,
1012    oid: oid::TYPE_ANYNONARRAY_OID,
1013    details: CatalogTypeDetails {
1014        typ: CatalogType::Pseudo,
1015        array_id: None,
1016        pg_metadata: Some(CatalogTypePgMetadata {
1017            typinput_oid: 2777,
1018            typreceive_oid: 0,
1019        }),
1020    },
1021};
1022
1023pub const TYPE_ANYRANGE: BuiltinType<NameReference> = BuiltinType {
1024    name: "anyrange",
1025    schema: PG_CATALOG_SCHEMA,
1026    oid: oid::TYPE_ANYRANGE_OID,
1027    details: CatalogTypeDetails {
1028        typ: CatalogType::Pseudo,
1029        array_id: None,
1030        pg_metadata: Some(CatalogTypePgMetadata {
1031            typinput_oid: 3832,
1032            typreceive_oid: 0,
1033        }),
1034    },
1035};
1036
1037pub const TYPE_CHAR: BuiltinType<NameReference> = BuiltinType {
1038    name: "char",
1039    schema: PG_CATALOG_SCHEMA,
1040    oid: oid::TYPE_CHAR_OID,
1041    details: CatalogTypeDetails {
1042        typ: CatalogType::PgLegacyChar,
1043        array_id: None,
1044        pg_metadata: Some(CatalogTypePgMetadata {
1045            typinput_oid: 1245,
1046            typreceive_oid: 2434,
1047        }),
1048    },
1049};
1050
1051pub const TYPE_VARCHAR: BuiltinType<NameReference> = BuiltinType {
1052    name: "varchar",
1053    schema: PG_CATALOG_SCHEMA,
1054    oid: oid::TYPE_VARCHAR_OID,
1055    details: CatalogTypeDetails {
1056        typ: CatalogType::VarChar,
1057        array_id: None,
1058        pg_metadata: Some(CatalogTypePgMetadata {
1059            typinput_oid: 1046,
1060            typreceive_oid: 2432,
1061        }),
1062    },
1063};
1064
1065pub const TYPE_INT2: BuiltinType<NameReference> = BuiltinType {
1066    name: "int2",
1067    schema: PG_CATALOG_SCHEMA,
1068    oid: oid::TYPE_INT2_OID,
1069    details: CatalogTypeDetails {
1070        typ: CatalogType::Int16,
1071        array_id: None,
1072        pg_metadata: Some(CatalogTypePgMetadata {
1073            typinput_oid: 38,
1074            typreceive_oid: 2404,
1075        }),
1076    },
1077};
1078
1079pub const TYPE_INT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1080    name: "_int2",
1081    schema: PG_CATALOG_SCHEMA,
1082    oid: oid::TYPE_INT2_ARRAY_OID,
1083    details: CatalogTypeDetails {
1084        typ: CatalogType::Array {
1085            element_reference: TYPE_INT2.name,
1086        },
1087        array_id: None,
1088        pg_metadata: Some(CatalogTypePgMetadata {
1089            typinput_oid: 750,
1090            typreceive_oid: 2400,
1091        }),
1092    },
1093};
1094
1095pub const TYPE_BPCHAR: BuiltinType<NameReference> = BuiltinType {
1096    name: "bpchar",
1097    schema: PG_CATALOG_SCHEMA,
1098    oid: oid::TYPE_BPCHAR_OID,
1099    details: CatalogTypeDetails {
1100        typ: CatalogType::Char,
1101        array_id: None,
1102        pg_metadata: Some(CatalogTypePgMetadata {
1103            typinput_oid: 1044,
1104            typreceive_oid: 2430,
1105        }),
1106    },
1107};
1108
1109pub const TYPE_CHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1110    name: "_char",
1111    schema: PG_CATALOG_SCHEMA,
1112    oid: oid::TYPE_CHAR_ARRAY_OID,
1113    details: CatalogTypeDetails {
1114        typ: CatalogType::Array {
1115            element_reference: TYPE_CHAR.name,
1116        },
1117        array_id: None,
1118        pg_metadata: Some(CatalogTypePgMetadata {
1119            typinput_oid: 750,
1120            typreceive_oid: 2400,
1121        }),
1122    },
1123};
1124
1125pub const TYPE_VARCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1126    name: "_varchar",
1127    schema: PG_CATALOG_SCHEMA,
1128    oid: oid::TYPE_VARCHAR_ARRAY_OID,
1129    details: CatalogTypeDetails {
1130        typ: CatalogType::Array {
1131            element_reference: TYPE_VARCHAR.name,
1132        },
1133        array_id: None,
1134        pg_metadata: Some(CatalogTypePgMetadata {
1135            typinput_oid: 750,
1136            typreceive_oid: 2400,
1137        }),
1138    },
1139};
1140
1141pub const TYPE_BPCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1142    name: "_bpchar",
1143    schema: PG_CATALOG_SCHEMA,
1144    oid: oid::TYPE_BPCHAR_ARRAY_OID,
1145    details: CatalogTypeDetails {
1146        typ: CatalogType::Array {
1147            element_reference: TYPE_BPCHAR.name,
1148        },
1149        array_id: None,
1150        pg_metadata: Some(CatalogTypePgMetadata {
1151            typinput_oid: 750,
1152            typreceive_oid: 2400,
1153        }),
1154    },
1155};
1156
1157pub const TYPE_REGPROC: BuiltinType<NameReference> = BuiltinType {
1158    name: "regproc",
1159    schema: PG_CATALOG_SCHEMA,
1160    oid: oid::TYPE_REGPROC_OID,
1161    details: CatalogTypeDetails {
1162        typ: CatalogType::RegProc,
1163        array_id: None,
1164        pg_metadata: Some(CatalogTypePgMetadata {
1165            typinput_oid: 44,
1166            typreceive_oid: 2444,
1167        }),
1168    },
1169};
1170
1171pub const TYPE_REGPROC_ARRAY: BuiltinType<NameReference> = BuiltinType {
1172    name: "_regproc",
1173    schema: PG_CATALOG_SCHEMA,
1174    oid: oid::TYPE_REGPROC_ARRAY_OID,
1175    details: CatalogTypeDetails {
1176        typ: CatalogType::Array {
1177            element_reference: TYPE_REGPROC.name,
1178        },
1179        array_id: None,
1180        pg_metadata: Some(CatalogTypePgMetadata {
1181            typinput_oid: 750,
1182            typreceive_oid: 2400,
1183        }),
1184    },
1185};
1186
1187pub const TYPE_REGTYPE: BuiltinType<NameReference> = BuiltinType {
1188    name: "regtype",
1189    schema: PG_CATALOG_SCHEMA,
1190    oid: oid::TYPE_REGTYPE_OID,
1191    details: CatalogTypeDetails {
1192        typ: CatalogType::RegType,
1193        array_id: None,
1194        pg_metadata: Some(CatalogTypePgMetadata {
1195            typinput_oid: 2220,
1196            typreceive_oid: 2454,
1197        }),
1198    },
1199};
1200
1201pub const TYPE_REGTYPE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1202    name: "_regtype",
1203    schema: PG_CATALOG_SCHEMA,
1204    oid: oid::TYPE_REGTYPE_ARRAY_OID,
1205    details: CatalogTypeDetails {
1206        typ: CatalogType::Array {
1207            element_reference: TYPE_REGTYPE.name,
1208        },
1209        array_id: None,
1210        pg_metadata: Some(CatalogTypePgMetadata {
1211            typinput_oid: 750,
1212            typreceive_oid: 2400,
1213        }),
1214    },
1215};
1216
1217pub const TYPE_REGCLASS: BuiltinType<NameReference> = BuiltinType {
1218    name: "regclass",
1219    schema: PG_CATALOG_SCHEMA,
1220    oid: oid::TYPE_REGCLASS_OID,
1221    details: CatalogTypeDetails {
1222        typ: CatalogType::RegClass,
1223        array_id: None,
1224        pg_metadata: Some(CatalogTypePgMetadata {
1225            typinput_oid: 2218,
1226            typreceive_oid: 2452,
1227        }),
1228    },
1229};
1230
1231pub const TYPE_REGCLASS_ARRAY: BuiltinType<NameReference> = BuiltinType {
1232    name: "_regclass",
1233    schema: PG_CATALOG_SCHEMA,
1234    oid: oid::TYPE_REGCLASS_ARRAY_OID,
1235    details: CatalogTypeDetails {
1236        typ: CatalogType::Array {
1237            element_reference: TYPE_REGCLASS.name,
1238        },
1239        array_id: None,
1240        pg_metadata: Some(CatalogTypePgMetadata {
1241            typinput_oid: 750,
1242            typreceive_oid: 2400,
1243        }),
1244    },
1245};
1246
1247pub const TYPE_INT2_VECTOR: BuiltinType<NameReference> = BuiltinType {
1248    name: "int2vector",
1249    schema: PG_CATALOG_SCHEMA,
1250    oid: oid::TYPE_INT2_VECTOR_OID,
1251    details: CatalogTypeDetails {
1252        typ: CatalogType::Int2Vector,
1253        array_id: None,
1254        pg_metadata: Some(CatalogTypePgMetadata {
1255            typinput_oid: 40,
1256            typreceive_oid: 2410,
1257        }),
1258    },
1259};
1260
1261pub const TYPE_INT2_VECTOR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1262    name: "_int2vector",
1263    schema: PG_CATALOG_SCHEMA,
1264    oid: oid::TYPE_INT2_VECTOR_ARRAY_OID,
1265    details: CatalogTypeDetails {
1266        typ: CatalogType::Array {
1267            element_reference: TYPE_INT2_VECTOR.name,
1268        },
1269        array_id: None,
1270        pg_metadata: Some(CatalogTypePgMetadata {
1271            typinput_oid: 750,
1272            typreceive_oid: 2400,
1273        }),
1274    },
1275};
1276
1277pub const TYPE_ANYCOMPATIBLE: BuiltinType<NameReference> = BuiltinType {
1278    name: "anycompatible",
1279    schema: PG_CATALOG_SCHEMA,
1280    oid: oid::TYPE_ANYCOMPATIBLE_OID,
1281    details: CatalogTypeDetails {
1282        typ: CatalogType::Pseudo,
1283        array_id: None,
1284        pg_metadata: Some(CatalogTypePgMetadata {
1285            typinput_oid: 5086,
1286            typreceive_oid: 0,
1287        }),
1288    },
1289};
1290
1291pub const TYPE_ANYCOMPATIBLEARRAY: BuiltinType<NameReference> = BuiltinType {
1292    name: "anycompatiblearray",
1293    schema: PG_CATALOG_SCHEMA,
1294    oid: oid::TYPE_ANYCOMPATIBLEARRAY_OID,
1295    details: CatalogTypeDetails {
1296        typ: CatalogType::Pseudo,
1297        array_id: None,
1298        pg_metadata: Some(CatalogTypePgMetadata {
1299            typinput_oid: 5088,
1300            typreceive_oid: 5090,
1301        }),
1302    },
1303};
1304
1305pub const TYPE_ANYCOMPATIBLENONARRAY: BuiltinType<NameReference> = BuiltinType {
1306    name: "anycompatiblenonarray",
1307    schema: PG_CATALOG_SCHEMA,
1308    oid: oid::TYPE_ANYCOMPATIBLENONARRAY_OID,
1309    details: CatalogTypeDetails {
1310        typ: CatalogType::Pseudo,
1311        array_id: None,
1312        pg_metadata: Some(CatalogTypePgMetadata {
1313            typinput_oid: 5092,
1314            typreceive_oid: 0,
1315        }),
1316    },
1317};
1318
1319pub const TYPE_ANYCOMPATIBLERANGE: BuiltinType<NameReference> = BuiltinType {
1320    name: "anycompatiblerange",
1321    schema: PG_CATALOG_SCHEMA,
1322    oid: oid::TYPE_ANYCOMPATIBLERANGE_OID,
1323    details: CatalogTypeDetails {
1324        typ: CatalogType::Pseudo,
1325        array_id: None,
1326        pg_metadata: Some(CatalogTypePgMetadata {
1327            typinput_oid: 5094,
1328            typreceive_oid: 0,
1329        }),
1330    },
1331};
1332
1333pub const TYPE_LIST: BuiltinType<NameReference> = BuiltinType {
1334    name: "list",
1335    schema: MZ_CATALOG_SCHEMA,
1336    oid: mz_pgrepr::oid::TYPE_LIST_OID,
1337    details: CatalogTypeDetails {
1338        typ: CatalogType::Pseudo,
1339        array_id: None,
1340        pg_metadata: None,
1341    },
1342};
1343
1344pub const TYPE_MAP: BuiltinType<NameReference> = BuiltinType {
1345    name: "map",
1346    schema: MZ_CATALOG_SCHEMA,
1347    oid: mz_pgrepr::oid::TYPE_MAP_OID,
1348    details: CatalogTypeDetails {
1349        typ: CatalogType::Pseudo,
1350        array_id: None,
1351        pg_metadata: None,
1352    },
1353};
1354
1355pub const TYPE_ANYCOMPATIBLELIST: BuiltinType<NameReference> = BuiltinType {
1356    name: "anycompatiblelist",
1357    schema: MZ_CATALOG_SCHEMA,
1358    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLELIST_OID,
1359    details: CatalogTypeDetails {
1360        typ: CatalogType::Pseudo,
1361        array_id: None,
1362        pg_metadata: None,
1363    },
1364};
1365
1366pub const TYPE_ANYCOMPATIBLEMAP: BuiltinType<NameReference> = BuiltinType {
1367    name: "anycompatiblemap",
1368    schema: MZ_CATALOG_SCHEMA,
1369    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLEMAP_OID,
1370    details: CatalogTypeDetails {
1371        typ: CatalogType::Pseudo,
1372        array_id: None,
1373        pg_metadata: None,
1374    },
1375};
1376
1377pub const TYPE_UINT2: BuiltinType<NameReference> = BuiltinType {
1378    name: "uint2",
1379    schema: MZ_CATALOG_SCHEMA,
1380    oid: mz_pgrepr::oid::TYPE_UINT2_OID,
1381    details: CatalogTypeDetails {
1382        typ: CatalogType::UInt16,
1383        array_id: None,
1384        pg_metadata: None,
1385    },
1386};
1387
1388pub const TYPE_UINT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1389    name: "_uint2",
1390    schema: MZ_CATALOG_SCHEMA,
1391    oid: mz_pgrepr::oid::TYPE_UINT2_ARRAY_OID,
1392    details: CatalogTypeDetails {
1393        typ: CatalogType::Array {
1394            element_reference: TYPE_UINT2.name,
1395        },
1396        array_id: None,
1397        pg_metadata: None,
1398    },
1399};
1400
1401pub const TYPE_UINT4: BuiltinType<NameReference> = BuiltinType {
1402    name: "uint4",
1403    schema: MZ_CATALOG_SCHEMA,
1404    oid: mz_pgrepr::oid::TYPE_UINT4_OID,
1405    details: CatalogTypeDetails {
1406        typ: CatalogType::UInt32,
1407        array_id: None,
1408        pg_metadata: None,
1409    },
1410};
1411
1412pub const TYPE_UINT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
1413    name: "_uint4",
1414    schema: MZ_CATALOG_SCHEMA,
1415    oid: mz_pgrepr::oid::TYPE_UINT4_ARRAY_OID,
1416    details: CatalogTypeDetails {
1417        typ: CatalogType::Array {
1418            element_reference: TYPE_UINT4.name,
1419        },
1420        array_id: None,
1421        pg_metadata: None,
1422    },
1423};
1424
1425pub const TYPE_UINT8: BuiltinType<NameReference> = BuiltinType {
1426    name: "uint8",
1427    schema: MZ_CATALOG_SCHEMA,
1428    oid: mz_pgrepr::oid::TYPE_UINT8_OID,
1429    details: CatalogTypeDetails {
1430        typ: CatalogType::UInt64,
1431        array_id: None,
1432        pg_metadata: None,
1433    },
1434};
1435
1436pub const TYPE_UINT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
1437    name: "_uint8",
1438    schema: MZ_CATALOG_SCHEMA,
1439    oid: mz_pgrepr::oid::TYPE_UINT8_ARRAY_OID,
1440    details: CatalogTypeDetails {
1441        typ: CatalogType::Array {
1442            element_reference: TYPE_UINT8.name,
1443        },
1444        array_id: None,
1445        pg_metadata: None,
1446    },
1447};
1448
1449pub const TYPE_MZ_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
1450    name: "mz_timestamp",
1451    schema: MZ_CATALOG_SCHEMA,
1452    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_OID,
1453    details: CatalogTypeDetails {
1454        typ: CatalogType::MzTimestamp,
1455        array_id: None,
1456        pg_metadata: None,
1457    },
1458};
1459
1460pub const TYPE_MZ_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
1461    name: "_mz_timestamp",
1462    schema: MZ_CATALOG_SCHEMA,
1463    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_ARRAY_OID,
1464    details: CatalogTypeDetails {
1465        typ: CatalogType::Array {
1466            element_reference: TYPE_MZ_TIMESTAMP.name,
1467        },
1468        array_id: None,
1469        pg_metadata: None,
1470    },
1471};
1472
1473pub const TYPE_INT4_RANGE: BuiltinType<NameReference> = BuiltinType {
1474    name: "int4range",
1475    schema: PG_CATALOG_SCHEMA,
1476    oid: mz_pgrepr::oid::TYPE_INT4RANGE_OID,
1477    details: CatalogTypeDetails {
1478        typ: CatalogType::Range {
1479            element_reference: TYPE_INT4.name,
1480        },
1481        array_id: None,
1482        pg_metadata: Some(CatalogTypePgMetadata {
1483            typinput_oid: 3834,
1484            typreceive_oid: 3836,
1485        }),
1486    },
1487};
1488
1489pub const TYPE_INT4_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1490    name: "_int4range",
1491    schema: PG_CATALOG_SCHEMA,
1492    oid: mz_pgrepr::oid::TYPE_INT4RANGE_ARRAY_OID,
1493    details: CatalogTypeDetails {
1494        typ: CatalogType::Array {
1495            element_reference: TYPE_INT4_RANGE.name,
1496        },
1497        array_id: None,
1498        pg_metadata: Some(CatalogTypePgMetadata {
1499            typinput_oid: 750,
1500            typreceive_oid: 2400,
1501        }),
1502    },
1503};
1504
1505pub const TYPE_INT8_RANGE: BuiltinType<NameReference> = BuiltinType {
1506    name: "int8range",
1507    schema: PG_CATALOG_SCHEMA,
1508    oid: mz_pgrepr::oid::TYPE_INT8RANGE_OID,
1509    details: CatalogTypeDetails {
1510        typ: CatalogType::Range {
1511            element_reference: TYPE_INT8.name,
1512        },
1513        array_id: None,
1514        pg_metadata: Some(CatalogTypePgMetadata {
1515            typinput_oid: 3834,
1516            typreceive_oid: 3836,
1517        }),
1518    },
1519};
1520
1521pub const TYPE_INT8_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1522    name: "_int8range",
1523    schema: PG_CATALOG_SCHEMA,
1524    oid: mz_pgrepr::oid::TYPE_INT8RANGE_ARRAY_OID,
1525    details: CatalogTypeDetails {
1526        typ: CatalogType::Array {
1527            element_reference: TYPE_INT8_RANGE.name,
1528        },
1529        array_id: None,
1530        pg_metadata: Some(CatalogTypePgMetadata {
1531            typinput_oid: 750,
1532            typreceive_oid: 2400,
1533        }),
1534    },
1535};
1536
1537pub const TYPE_DATE_RANGE: BuiltinType<NameReference> = BuiltinType {
1538    name: "daterange",
1539    schema: PG_CATALOG_SCHEMA,
1540    oid: mz_pgrepr::oid::TYPE_DATERANGE_OID,
1541    details: CatalogTypeDetails {
1542        typ: CatalogType::Range {
1543            element_reference: TYPE_DATE.name,
1544        },
1545        array_id: None,
1546        pg_metadata: Some(CatalogTypePgMetadata {
1547            typinput_oid: 3834,
1548            typreceive_oid: 3836,
1549        }),
1550    },
1551};
1552
1553pub const TYPE_DATE_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1554    name: "_daterange",
1555    schema: PG_CATALOG_SCHEMA,
1556    oid: mz_pgrepr::oid::TYPE_DATERANGE_ARRAY_OID,
1557    details: CatalogTypeDetails {
1558        typ: CatalogType::Array {
1559            element_reference: TYPE_DATE_RANGE.name,
1560        },
1561        array_id: None,
1562        pg_metadata: Some(CatalogTypePgMetadata {
1563            typinput_oid: 750,
1564            typreceive_oid: 2400,
1565        }),
1566    },
1567};
1568
1569pub const TYPE_NUM_RANGE: BuiltinType<NameReference> = BuiltinType {
1570    name: "numrange",
1571    schema: PG_CATALOG_SCHEMA,
1572    oid: mz_pgrepr::oid::TYPE_NUMRANGE_OID,
1573    details: CatalogTypeDetails {
1574        typ: CatalogType::Range {
1575            element_reference: TYPE_NUMERIC.name,
1576        },
1577        array_id: None,
1578        pg_metadata: Some(CatalogTypePgMetadata {
1579            typinput_oid: 3834,
1580            typreceive_oid: 3836,
1581        }),
1582    },
1583};
1584
1585pub const TYPE_NUM_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1586    name: "_numrange",
1587    schema: PG_CATALOG_SCHEMA,
1588    oid: mz_pgrepr::oid::TYPE_NUMRANGE_ARRAY_OID,
1589    details: CatalogTypeDetails {
1590        typ: CatalogType::Array {
1591            element_reference: TYPE_NUM_RANGE.name,
1592        },
1593        array_id: None,
1594        pg_metadata: Some(CatalogTypePgMetadata {
1595            typinput_oid: 750,
1596            typreceive_oid: 2400,
1597        }),
1598    },
1599};
1600
1601pub const TYPE_TS_RANGE: BuiltinType<NameReference> = BuiltinType {
1602    name: "tsrange",
1603    schema: PG_CATALOG_SCHEMA,
1604    oid: mz_pgrepr::oid::TYPE_TSRANGE_OID,
1605    details: CatalogTypeDetails {
1606        typ: CatalogType::Range {
1607            element_reference: TYPE_TIMESTAMP.name,
1608        },
1609        array_id: None,
1610        pg_metadata: Some(CatalogTypePgMetadata {
1611            typinput_oid: 3834,
1612            typreceive_oid: 3836,
1613        }),
1614    },
1615};
1616
1617pub const TYPE_TS_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1618    name: "_tsrange",
1619    schema: PG_CATALOG_SCHEMA,
1620    oid: mz_pgrepr::oid::TYPE_TSRANGE_ARRAY_OID,
1621    details: CatalogTypeDetails {
1622        typ: CatalogType::Array {
1623            element_reference: TYPE_TS_RANGE.name,
1624        },
1625        array_id: None,
1626        pg_metadata: Some(CatalogTypePgMetadata {
1627            typinput_oid: 750,
1628            typreceive_oid: 2400,
1629        }),
1630    },
1631};
1632
1633pub const TYPE_TSTZ_RANGE: BuiltinType<NameReference> = BuiltinType {
1634    name: "tstzrange",
1635    schema: PG_CATALOG_SCHEMA,
1636    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_OID,
1637    details: CatalogTypeDetails {
1638        typ: CatalogType::Range {
1639            element_reference: TYPE_TIMESTAMPTZ.name,
1640        },
1641        array_id: None,
1642        pg_metadata: Some(CatalogTypePgMetadata {
1643            typinput_oid: 3834,
1644            typreceive_oid: 3836,
1645        }),
1646    },
1647};
1648
1649pub const TYPE_TSTZ_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1650    name: "_tstzrange",
1651    schema: PG_CATALOG_SCHEMA,
1652    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_ARRAY_OID,
1653    details: CatalogTypeDetails {
1654        typ: CatalogType::Array {
1655            element_reference: TYPE_TSTZ_RANGE.name,
1656        },
1657        array_id: None,
1658        pg_metadata: Some(CatalogTypePgMetadata {
1659            typinput_oid: 750,
1660            typreceive_oid: 2400,
1661        }),
1662    },
1663};
1664
1665pub const TYPE_MZ_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1666    name: "mz_aclitem",
1667    schema: MZ_CATALOG_SCHEMA,
1668    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_OID,
1669    details: CatalogTypeDetails {
1670        typ: CatalogType::MzAclItem,
1671        array_id: None,
1672        pg_metadata: None,
1673    },
1674};
1675
1676pub const TYPE_MZ_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1677    name: "_mz_aclitem",
1678    schema: MZ_CATALOG_SCHEMA,
1679    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_ARRAY_OID,
1680    details: CatalogTypeDetails {
1681        typ: CatalogType::Array {
1682            element_reference: TYPE_MZ_ACL_ITEM.name,
1683        },
1684        array_id: None,
1685        pg_metadata: Some(CatalogTypePgMetadata {
1686            typinput_oid: 750,
1687            typreceive_oid: 2400,
1688        }),
1689    },
1690};
1691
1692pub const TYPE_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1693    name: "aclitem",
1694    schema: PG_CATALOG_SCHEMA,
1695    oid: 1033,
1696    details: CatalogTypeDetails {
1697        typ: CatalogType::AclItem,
1698        array_id: None,
1699        pg_metadata: Some(CatalogTypePgMetadata {
1700            typinput_oid: 1031,
1701            typreceive_oid: 0,
1702        }),
1703    },
1704};
1705
1706pub const TYPE_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1707    name: "_aclitem",
1708    schema: PG_CATALOG_SCHEMA,
1709    oid: 1034,
1710    details: CatalogTypeDetails {
1711        typ: CatalogType::Array {
1712            element_reference: TYPE_ACL_ITEM.name,
1713        },
1714        array_id: None,
1715        pg_metadata: Some(CatalogTypePgMetadata {
1716            typinput_oid: 750,
1717            typreceive_oid: 2400,
1718        }),
1719    },
1720};
1721
1722pub const TYPE_INTERNAL: BuiltinType<NameReference> = BuiltinType {
1723    name: "internal",
1724    schema: PG_CATALOG_SCHEMA,
1725    oid: 2281,
1726    details: CatalogTypeDetails {
1727        typ: CatalogType::Pseudo,
1728        array_id: None,
1729        pg_metadata: Some(CatalogTypePgMetadata {
1730            typinput_oid: 2304,
1731            typreceive_oid: 0,
1732        }),
1733    },
1734};
1735
1736const PUBLIC_SELECT: MzAclItem = MzAclItem {
1737    grantee: RoleId::Public,
1738    grantor: MZ_SYSTEM_ROLE_ID,
1739    acl_mode: AclMode::SELECT,
1740};
1741
1742const SUPPORT_SELECT: MzAclItem = MzAclItem {
1743    grantee: MZ_SUPPORT_ROLE_ID,
1744    grantor: MZ_SYSTEM_ROLE_ID,
1745    acl_mode: AclMode::SELECT,
1746};
1747
1748const ANALYTICS_SELECT: MzAclItem = MzAclItem {
1749    grantee: MZ_ANALYTICS_ROLE_ID,
1750    grantor: MZ_SYSTEM_ROLE_ID,
1751    acl_mode: AclMode::SELECT,
1752};
1753
1754const MONITOR_SELECT: MzAclItem = MzAclItem {
1755    grantee: MZ_MONITOR_ROLE_ID,
1756    grantor: MZ_SYSTEM_ROLE_ID,
1757    acl_mode: AclMode::SELECT,
1758};
1759
1760const MONITOR_REDACTED_SELECT: MzAclItem = MzAclItem {
1761    grantee: MZ_MONITOR_REDACTED_ROLE_ID,
1762    grantor: MZ_SYSTEM_ROLE_ID,
1763    acl_mode: AclMode::SELECT,
1764};
1765
1766pub static MZ_CATALOG_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
1767    name: "mz_catalog_raw",
1768    schema: MZ_INTERNAL_SCHEMA,
1769    oid: oid::SOURCE_MZ_CATALOG_RAW_OID,
1770    data_source: DataSourceDesc::Catalog,
1771    desc: crate::durable::persist_desc(),
1772    column_comments: BTreeMap::new(),
1773    is_retained_metrics_object: false,
1774    // The raw catalog contains unredacted SQL statements, so we limit access to the system user.
1775    access: vec![],
1776});
1777
1778pub static MZ_CATALOG_RAW_DESCRIPTION: LazyLock<SystemObjectDescription> =
1779    LazyLock::new(|| SystemObjectDescription {
1780        schema_name: MZ_CATALOG_RAW.schema.to_string(),
1781        object_type: CatalogItemType::Source,
1782        object_name: MZ_CATALOG_RAW.name.to_string(),
1783    });
1784
1785pub static MZ_DATAFLOW_OPERATORS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1786    name: "mz_dataflow_operators_per_worker",
1787    schema: MZ_INTROSPECTION_SCHEMA,
1788    oid: oid::LOG_MZ_DATAFLOW_OPERATORS_PER_WORKER_OID,
1789    variant: LogVariant::Timely(TimelyLog::Operates),
1790    access: vec![PUBLIC_SELECT],
1791});
1792
1793pub static MZ_DATAFLOW_ADDRESSES_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1794    name: "mz_dataflow_addresses_per_worker",
1795    schema: MZ_INTROSPECTION_SCHEMA,
1796    oid: oid::LOG_MZ_DATAFLOW_ADDRESSES_PER_WORKER_OID,
1797    variant: LogVariant::Timely(TimelyLog::Addresses),
1798    access: vec![PUBLIC_SELECT],
1799});
1800
1801pub static MZ_DATAFLOW_CHANNELS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1802    name: "mz_dataflow_channels_per_worker",
1803    schema: MZ_INTROSPECTION_SCHEMA,
1804    oid: oid::LOG_MZ_DATAFLOW_CHANNELS_PER_WORKER_OID,
1805    variant: LogVariant::Timely(TimelyLog::Channels),
1806    access: vec![PUBLIC_SELECT],
1807});
1808
1809pub static MZ_SCHEDULING_ELAPSED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1810    name: "mz_scheduling_elapsed_raw",
1811    schema: MZ_INTROSPECTION_SCHEMA,
1812    oid: oid::LOG_MZ_SCHEDULING_ELAPSED_RAW_OID,
1813    variant: LogVariant::Timely(TimelyLog::Elapsed),
1814    access: vec![PUBLIC_SELECT],
1815});
1816
1817pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1818    LazyLock::new(|| BuiltinLog {
1819        name: "mz_compute_operator_durations_histogram_raw",
1820        schema: MZ_INTROSPECTION_SCHEMA,
1821        oid: oid::LOG_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW_OID,
1822        variant: LogVariant::Timely(TimelyLog::Histogram),
1823        access: vec![PUBLIC_SELECT],
1824    });
1825
1826pub static MZ_SCHEDULING_PARKS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1827    name: "mz_scheduling_parks_histogram_raw",
1828    schema: MZ_INTROSPECTION_SCHEMA,
1829    oid: oid::LOG_MZ_SCHEDULING_PARKS_HISTOGRAM_RAW_OID,
1830    variant: LogVariant::Timely(TimelyLog::Parks),
1831    access: vec![PUBLIC_SELECT],
1832});
1833
1834pub static MZ_ARRANGEMENT_RECORDS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1835    name: "mz_arrangement_records_raw",
1836    schema: MZ_INTROSPECTION_SCHEMA,
1837    oid: oid::LOG_MZ_ARRANGEMENT_RECORDS_RAW_OID,
1838    variant: LogVariant::Differential(DifferentialLog::ArrangementRecords),
1839    access: vec![PUBLIC_SELECT],
1840});
1841
1842pub static MZ_ARRANGEMENT_BATCHES_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1843    name: "mz_arrangement_batches_raw",
1844    schema: MZ_INTROSPECTION_SCHEMA,
1845    oid: oid::LOG_MZ_ARRANGEMENT_BATCHES_RAW_OID,
1846    variant: LogVariant::Differential(DifferentialLog::ArrangementBatches),
1847    access: vec![PUBLIC_SELECT],
1848});
1849
1850pub static MZ_ARRANGEMENT_SHARING_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1851    name: "mz_arrangement_sharing_raw",
1852    schema: MZ_INTROSPECTION_SCHEMA,
1853    oid: oid::LOG_MZ_ARRANGEMENT_SHARING_RAW_OID,
1854    variant: LogVariant::Differential(DifferentialLog::Sharing),
1855    access: vec![PUBLIC_SELECT],
1856});
1857
1858pub static MZ_ARRANGEMENT_BATCHER_RECORDS_RAW: LazyLock<BuiltinLog> =
1859    LazyLock::new(|| BuiltinLog {
1860        name: "mz_arrangement_batcher_records_raw",
1861        schema: MZ_INTROSPECTION_SCHEMA,
1862        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_RECORDS_RAW_OID,
1863        variant: LogVariant::Differential(DifferentialLog::BatcherRecords),
1864        access: vec![PUBLIC_SELECT],
1865    });
1866
1867pub static MZ_ARRANGEMENT_BATCHER_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1868    name: "mz_arrangement_batcher_size_raw",
1869    schema: MZ_INTROSPECTION_SCHEMA,
1870    oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_SIZE_RAW_OID,
1871    variant: LogVariant::Differential(DifferentialLog::BatcherSize),
1872    access: vec![PUBLIC_SELECT],
1873});
1874
1875pub static MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW: LazyLock<BuiltinLog> =
1876    LazyLock::new(|| BuiltinLog {
1877        name: "mz_arrangement_batcher_capacity_raw",
1878        schema: MZ_INTROSPECTION_SCHEMA,
1879        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW_OID,
1880        variant: LogVariant::Differential(DifferentialLog::BatcherCapacity),
1881        access: vec![PUBLIC_SELECT],
1882    });
1883
1884pub static MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1885    LazyLock::new(|| BuiltinLog {
1886        name: "mz_arrangement_batcher_allocations_raw",
1887        schema: MZ_INTROSPECTION_SCHEMA,
1888        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW_OID,
1889        variant: LogVariant::Differential(DifferentialLog::BatcherAllocations),
1890        access: vec![PUBLIC_SELECT],
1891    });
1892
1893pub static MZ_COMPUTE_EXPORTS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1894    name: "mz_compute_exports_per_worker",
1895    schema: MZ_INTROSPECTION_SCHEMA,
1896    oid: oid::LOG_MZ_COMPUTE_EXPORTS_PER_WORKER_OID,
1897    variant: LogVariant::Compute(ComputeLog::DataflowCurrent),
1898    access: vec![PUBLIC_SELECT],
1899});
1900
1901pub static MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER: LazyLock<BuiltinLog> =
1902    LazyLock::new(|| BuiltinLog {
1903        name: "mz_compute_dataflow_global_ids_per_worker",
1904        schema: MZ_INTROSPECTION_SCHEMA,
1905        oid: oid::LOG_MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER_OID,
1906        variant: LogVariant::Compute(ComputeLog::DataflowGlobal),
1907        access: vec![PUBLIC_SELECT],
1908    });
1909
1910pub static MZ_CLUSTER_PROMETHEUS_METRICS: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1911    name: "mz_cluster_prometheus_metrics",
1912    schema: MZ_INTROSPECTION_SCHEMA,
1913    oid: oid::LOG_MZ_CLUSTER_PROMETHEUS_METRICS_OID,
1914    variant: LogVariant::Compute(ComputeLog::PrometheusMetrics),
1915    access: vec![PUBLIC_SELECT],
1916});
1917
1918pub static MZ_COMPUTE_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1919    name: "mz_compute_frontiers_per_worker",
1920    schema: MZ_INTROSPECTION_SCHEMA,
1921    oid: oid::LOG_MZ_COMPUTE_FRONTIERS_PER_WORKER_OID,
1922    variant: LogVariant::Compute(ComputeLog::FrontierCurrent),
1923    access: vec![PUBLIC_SELECT],
1924});
1925
1926pub static MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> =
1927    LazyLock::new(|| BuiltinLog {
1928        name: "mz_compute_import_frontiers_per_worker",
1929        schema: MZ_INTROSPECTION_SCHEMA,
1930        oid: oid::LOG_MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER_OID,
1931        variant: LogVariant::Compute(ComputeLog::ImportFrontierCurrent),
1932        access: vec![PUBLIC_SELECT],
1933    });
1934
1935pub static MZ_COMPUTE_ERROR_COUNTS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1936    name: "mz_compute_error_counts_raw",
1937    schema: MZ_INTROSPECTION_SCHEMA,
1938    oid: oid::LOG_MZ_COMPUTE_ERROR_COUNTS_RAW_OID,
1939    variant: LogVariant::Compute(ComputeLog::ErrorCount),
1940    access: vec![PUBLIC_SELECT],
1941});
1942
1943pub static MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER: LazyLock<BuiltinLog> =
1944    LazyLock::new(|| BuiltinLog {
1945        name: "mz_compute_hydration_times_per_worker",
1946        schema: MZ_INTROSPECTION_SCHEMA,
1947        oid: oid::LOG_MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER_OID,
1948        variant: LogVariant::Compute(ComputeLog::HydrationTime),
1949        access: vec![PUBLIC_SELECT],
1950    });
1951
1952pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER: LazyLock<BuiltinLog> =
1953    LazyLock::new(|| BuiltinLog {
1954        name: "mz_compute_operator_hydration_statuses_per_worker",
1955        schema: MZ_INTROSPECTION_SCHEMA,
1956        oid: oid::LOG_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER_OID,
1957        variant: LogVariant::Compute(ComputeLog::OperatorHydrationStatus),
1958        access: vec![PUBLIC_SELECT],
1959    });
1960
1961pub static MZ_ACTIVE_PEEKS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1962    name: "mz_active_peeks_per_worker",
1963    schema: MZ_INTROSPECTION_SCHEMA,
1964    oid: oid::LOG_MZ_ACTIVE_PEEKS_PER_WORKER_OID,
1965    variant: LogVariant::Compute(ComputeLog::PeekCurrent),
1966    access: vec![PUBLIC_SELECT],
1967});
1968
1969pub static MZ_COMPUTE_LIR_MAPPING_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1970    name: "mz_compute_lir_mapping_per_worker",
1971    schema: MZ_INTROSPECTION_SCHEMA,
1972    oid: oid::LOG_MZ_COMPUTE_LIR_MAPPING_PER_WORKER_OID,
1973    variant: LogVariant::Compute(ComputeLog::LirMapping),
1974    access: vec![PUBLIC_SELECT],
1975});
1976
1977pub static MZ_PEEK_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1978    name: "mz_peek_durations_histogram_raw",
1979    schema: MZ_INTROSPECTION_SCHEMA,
1980    oid: oid::LOG_MZ_PEEK_DURATIONS_HISTOGRAM_RAW_OID,
1981    variant: LogVariant::Compute(ComputeLog::PeekDuration),
1982    access: vec![PUBLIC_SELECT],
1983});
1984
1985pub static MZ_ARRANGEMENT_HEAP_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1986    name: "mz_arrangement_heap_size_raw",
1987    schema: MZ_INTROSPECTION_SCHEMA,
1988    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_SIZE_RAW_OID,
1989    variant: LogVariant::Compute(ComputeLog::ArrangementHeapSize),
1990    access: vec![PUBLIC_SELECT],
1991});
1992
1993pub static MZ_ARRANGEMENT_HEAP_CAPACITY_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1994    name: "mz_arrangement_heap_capacity_raw",
1995    schema: MZ_INTROSPECTION_SCHEMA,
1996    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_CAPACITY_RAW_OID,
1997    variant: LogVariant::Compute(ComputeLog::ArrangementHeapCapacity),
1998    access: vec![PUBLIC_SELECT],
1999});
2000
2001pub static MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
2002    LazyLock::new(|| BuiltinLog {
2003        name: "mz_arrangement_heap_allocations_raw",
2004        schema: MZ_INTROSPECTION_SCHEMA,
2005        oid: oid::LOG_MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW_OID,
2006        variant: LogVariant::Compute(ComputeLog::ArrangementHeapAllocations),
2007        access: vec![PUBLIC_SELECT],
2008    });
2009
2010pub static MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> =
2011    LazyLock::new(|| BuiltinLog {
2012        name: "mz_message_batch_counts_received_raw",
2013        schema: MZ_INTROSPECTION_SCHEMA,
2014        oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW_OID,
2015        variant: LogVariant::Timely(TimelyLog::BatchesReceived),
2016        access: vec![PUBLIC_SELECT],
2017    });
2018
2019pub static MZ_MESSAGE_BATCH_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2020    name: "mz_message_batch_counts_sent_raw",
2021    schema: MZ_INTROSPECTION_SCHEMA,
2022    oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_SENT_RAW_OID,
2023    variant: LogVariant::Timely(TimelyLog::BatchesSent),
2024    access: vec![PUBLIC_SELECT],
2025});
2026
2027pub static MZ_MESSAGE_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2028    name: "mz_message_counts_received_raw",
2029    schema: MZ_INTROSPECTION_SCHEMA,
2030    oid: oid::LOG_MZ_MESSAGE_COUNTS_RECEIVED_RAW_OID,
2031    variant: LogVariant::Timely(TimelyLog::MessagesReceived),
2032    access: vec![PUBLIC_SELECT],
2033});
2034
2035pub static MZ_MESSAGE_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2036    name: "mz_message_counts_sent_raw",
2037    schema: MZ_INTROSPECTION_SCHEMA,
2038    oid: oid::LOG_MZ_MESSAGE_COUNTS_SENT_RAW_OID,
2039    variant: LogVariant::Timely(TimelyLog::MessagesSent),
2040    access: vec![PUBLIC_SELECT],
2041});
2042
2043pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW: LazyLock<BuiltinLog> =
2044    LazyLock::new(|| BuiltinLog {
2045        name: "mz_dataflow_operator_reachability_raw",
2046        schema: MZ_INTROSPECTION_SCHEMA,
2047        oid: oid::LOG_MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW_OID,
2048        variant: LogVariant::Timely(TimelyLog::Reachability),
2049        access: vec![PUBLIC_SELECT],
2050    });
2051
2052pub static MZ_ICEBERG_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2053    name: "mz_iceberg_sinks",
2054    schema: MZ_CATALOG_SCHEMA,
2055    oid: oid::TABLE_MZ_ICEBERG_SINKS_OID,
2056    desc: RelationDesc::builder()
2057        .with_column("id", SqlScalarType::String.nullable(false))
2058        .with_column("namespace", SqlScalarType::String.nullable(false))
2059        .with_column("table", SqlScalarType::String.nullable(false))
2060        .finish(),
2061    column_comments: BTreeMap::from_iter([
2062        ("id", "The ID of the sink."),
2063        (
2064            "namespace",
2065            "The namespace of the Iceberg table into which the sink is writing.",
2066        ),
2067        ("table", "The Iceberg table into which the sink is writing."),
2068    ]),
2069    is_retained_metrics_object: false,
2070    access: vec![PUBLIC_SELECT],
2071});
2072
2073pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2074    name: "mz_kafka_sinks",
2075    schema: MZ_CATALOG_SCHEMA,
2076    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2077    desc: RelationDesc::builder()
2078        .with_column("id", SqlScalarType::String.nullable(false))
2079        .with_column("topic", SqlScalarType::String.nullable(false))
2080        .with_key(vec![0])
2081        .finish(),
2082    column_comments: BTreeMap::from_iter([
2083        ("id", "The ID of the sink."),
2084        (
2085            "topic",
2086            "The name of the Kafka topic into which the sink is writing.",
2087        ),
2088    ]),
2089    is_retained_metrics_object: false,
2090    access: vec![PUBLIC_SELECT],
2091});
2092pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2093    name: "mz_kafka_connections",
2094    schema: MZ_CATALOG_SCHEMA,
2095    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2096    desc: RelationDesc::builder()
2097        .with_column("id", SqlScalarType::String.nullable(false))
2098        .with_column(
2099            "brokers",
2100            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2101        )
2102        .with_column("sink_progress_topic", SqlScalarType::String.nullable(false))
2103        .finish(),
2104    column_comments: BTreeMap::from_iter([
2105        ("id", "The ID of the connection."),
2106        (
2107            "brokers",
2108            "The addresses of the Kafka brokers to connect to.",
2109        ),
2110        (
2111            "sink_progress_topic",
2112            "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.",
2113        ),
2114    ]),
2115    is_retained_metrics_object: false,
2116    access: vec![PUBLIC_SELECT],
2117});
2118pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2119    name: "mz_kafka_sources",
2120    schema: MZ_CATALOG_SCHEMA,
2121    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2122    desc: RelationDesc::builder()
2123        .with_column("id", SqlScalarType::String.nullable(false))
2124        .with_column("group_id_prefix", SqlScalarType::String.nullable(false))
2125        .with_column("topic", SqlScalarType::String.nullable(false))
2126        .finish(),
2127    column_comments: BTreeMap::from_iter([
2128        (
2129            "id",
2130            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2131        ),
2132        (
2133            "group_id_prefix",
2134            "The value of the `GROUP ID PREFIX` connection option.",
2135        ),
2136        (
2137            "topic",
2138            "The name of the Kafka topic the source is reading from.",
2139        ),
2140    ]),
2141    is_retained_metrics_object: false,
2142    access: vec![PUBLIC_SELECT],
2143});
2144pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2145    name: "mz_postgres_sources",
2146    schema: MZ_INTERNAL_SCHEMA,
2147    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2148    desc: RelationDesc::builder()
2149        .with_column("id", SqlScalarType::String.nullable(false))
2150        .with_column("replication_slot", SqlScalarType::String.nullable(false))
2151        .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
2152        .finish(),
2153    column_comments: BTreeMap::from_iter([
2154        (
2155            "id",
2156            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2157        ),
2158        (
2159            "replication_slot",
2160            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2161        ),
2162        (
2163            "timeline_id",
2164            "The PostgreSQL timeline ID determined on source creation.",
2165        ),
2166    ]),
2167    is_retained_metrics_object: false,
2168    access: vec![PUBLIC_SELECT],
2169});
2170pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2171    name: "mz_postgres_source_tables",
2172    schema: MZ_INTERNAL_SCHEMA,
2173    oid: oid::TABLE_MZ_POSTGRES_SOURCE_TABLES_OID,
2174    desc: RelationDesc::builder()
2175        .with_column("id", SqlScalarType::String.nullable(false))
2176        .with_column("schema_name", SqlScalarType::String.nullable(false))
2177        .with_column("table_name", SqlScalarType::String.nullable(false))
2178        .finish(),
2179    column_comments: BTreeMap::from_iter([
2180        (
2181            "id",
2182            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2183        ),
2184        (
2185            "schema_name",
2186            "The schema of the upstream table being ingested.",
2187        ),
2188        (
2189            "table_name",
2190            "The name of the upstream table being ingested.",
2191        ),
2192    ]),
2193    is_retained_metrics_object: true,
2194    access: vec![PUBLIC_SELECT],
2195});
2196pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2197    name: "mz_mysql_source_tables",
2198    schema: MZ_INTERNAL_SCHEMA,
2199    oid: oid::TABLE_MZ_MYSQL_SOURCE_TABLES_OID,
2200    desc: RelationDesc::builder()
2201        .with_column("id", SqlScalarType::String.nullable(false))
2202        .with_column("schema_name", SqlScalarType::String.nullable(false))
2203        .with_column("table_name", SqlScalarType::String.nullable(false))
2204        .finish(),
2205    column_comments: BTreeMap::from_iter([
2206        (
2207            "id",
2208            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2209        ),
2210        (
2211            "schema_name",
2212            "The schema (or, database) of the upstream table being ingested.",
2213        ),
2214        (
2215            "table_name",
2216            "The name of the upstream table being ingested.",
2217        ),
2218    ]),
2219    is_retained_metrics_object: true,
2220    access: vec![PUBLIC_SELECT],
2221});
2222pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2223    name: "mz_sql_server_source_tables",
2224    schema: MZ_INTERNAL_SCHEMA,
2225    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2226    desc: RelationDesc::builder()
2227        .with_column("id", SqlScalarType::String.nullable(false))
2228        .with_column("schema_name", SqlScalarType::String.nullable(false))
2229        .with_column("table_name", SqlScalarType::String.nullable(false))
2230        .finish(),
2231    column_comments: BTreeMap::from_iter([
2232        (
2233            "id",
2234            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2235        ),
2236        (
2237            "schema_name",
2238            "The schema of the upstream table being ingested.",
2239        ),
2240        (
2241            "table_name",
2242            "The name of the upstream table being ingested.",
2243        ),
2244    ]),
2245    is_retained_metrics_object: true,
2246    access: vec![PUBLIC_SELECT],
2247});
2248pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2249    name: "mz_kafka_source_tables",
2250    schema: MZ_INTERNAL_SCHEMA,
2251    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2252    desc: RelationDesc::builder()
2253        .with_column("id", SqlScalarType::String.nullable(false))
2254        .with_column("topic", SqlScalarType::String.nullable(false))
2255        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2256        .with_column("key_format", SqlScalarType::String.nullable(true))
2257        .with_column("value_format", SqlScalarType::String.nullable(true))
2258        .finish(),
2259    column_comments: BTreeMap::from_iter([
2260        (
2261            "id",
2262            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2263        ),
2264        ("topic", "The topic being ingested."),
2265        (
2266            "envelope_type",
2267            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2268        ),
2269        (
2270            "key_format",
2271            "The format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2272        ),
2273        (
2274            "value_format",
2275            "The format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2276        ),
2277    ]),
2278    is_retained_metrics_object: true,
2279    access: vec![PUBLIC_SELECT],
2280});
2281pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2282    name: "mz_object_dependencies",
2283    schema: MZ_INTERNAL_SCHEMA,
2284    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2285    desc: RelationDesc::builder()
2286        .with_column("object_id", SqlScalarType::String.nullable(false))
2287        .with_column(
2288            "referenced_object_id",
2289            SqlScalarType::String.nullable(false),
2290        )
2291        .finish(),
2292    column_comments: BTreeMap::from_iter([
2293        (
2294            "object_id",
2295            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2296        ),
2297        (
2298            "referenced_object_id",
2299            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2300        ),
2301    ]),
2302    is_retained_metrics_object: true,
2303    access: vec![PUBLIC_SELECT],
2304});
2305pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2306    name: "mz_compute_dependencies",
2307    schema: MZ_INTERNAL_SCHEMA,
2308    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2309    data_source: IntrospectionType::ComputeDependencies.into(),
2310    desc: RelationDesc::builder()
2311        .with_column("object_id", SqlScalarType::String.nullable(false))
2312        .with_column("dependency_id", SqlScalarType::String.nullable(false))
2313        .finish(),
2314    column_comments: BTreeMap::from_iter([
2315        (
2316            "object_id",
2317            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2318        ),
2319        (
2320            "dependency_id",
2321            "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`.",
2322        ),
2323    ]),
2324    is_retained_metrics_object: false,
2325    access: vec![PUBLIC_SELECT],
2326});
2327
2328pub static MZ_DATABASES: LazyLock<BuiltinMaterializedView> =
2329    LazyLock::new(|| BuiltinMaterializedView {
2330        name: "mz_databases",
2331        schema: MZ_CATALOG_SCHEMA,
2332        oid: oid::MV_MZ_DATABASES_OID,
2333        desc: RelationDesc::builder()
2334            .with_column("id", SqlScalarType::String.nullable(false))
2335            .with_column("oid", SqlScalarType::Oid.nullable(false))
2336            .with_column("name", SqlScalarType::String.nullable(false))
2337            .with_column("owner_id", SqlScalarType::String.nullable(false))
2338            .with_column(
2339                "privileges",
2340                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2341            )
2342            .with_key(vec![0])
2343            .with_key(vec![1])
2344            .finish(),
2345        column_comments: BTreeMap::from_iter([
2346            ("id", "Materialize's unique ID for the database."),
2347            ("oid", "A PostgreSQL-compatible OID for the database."),
2348            ("name", "The name of the database."),
2349            (
2350                "owner_id",
2351                "The role ID of the owner of the database. Corresponds to `mz_roles.id`.",
2352            ),
2353            ("privileges", "The privileges belonging to the database."),
2354        ]),
2355        sql: "
2356IN CLUSTER mz_catalog_server
2357WITH (
2358    ASSERT NOT NULL id,
2359    ASSERT NOT NULL oid,
2360    ASSERT NOT NULL name,
2361    ASSERT NOT NULL owner_id,
2362    ASSERT NOT NULL privileges
2363) AS
2364SELECT
2365    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
2366    (data->'value'->>'oid')::oid AS oid,
2367    data->'value'->>'name' AS name,
2368    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2369    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
2370FROM mz_internal.mz_catalog_raw
2371WHERE data->>'kind' = 'Database'",
2372        is_retained_metrics_object: false,
2373        access: vec![PUBLIC_SELECT],
2374    });
2375
2376pub static MZ_SCHEMAS: LazyLock<BuiltinMaterializedView> =
2377    LazyLock::new(|| BuiltinMaterializedView {
2378        name: "mz_schemas",
2379        schema: MZ_CATALOG_SCHEMA,
2380        oid: oid::MV_MZ_SCHEMAS_OID,
2381        desc: RelationDesc::builder()
2382            .with_column("id", SqlScalarType::String.nullable(false))
2383            .with_column("oid", SqlScalarType::Oid.nullable(false))
2384            .with_column("database_id", SqlScalarType::String.nullable(true))
2385            .with_column("name", SqlScalarType::String.nullable(false))
2386            .with_column("owner_id", SqlScalarType::String.nullable(false))
2387            .with_column(
2388                "privileges",
2389                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2390            )
2391            .with_key(vec![0])
2392            .with_key(vec![1])
2393            .finish(),
2394        column_comments: BTreeMap::from_iter([
2395            ("id", "Materialize's unique ID for the schema."),
2396            ("oid", "A PostgreSQL-compatible oid for the schema."),
2397            (
2398                "database_id",
2399                "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2400            ),
2401            ("name", "The name of the schema."),
2402            (
2403                "owner_id",
2404                "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2405            ),
2406            ("privileges", "The privileges belonging to the schema."),
2407        ]),
2408        sql: "
2409IN CLUSTER mz_catalog_server
2410WITH (
2411    ASSERT NOT NULL id,
2412    ASSERT NOT NULL oid,
2413    ASSERT NOT NULL name,
2414    ASSERT NOT NULL owner_id,
2415    ASSERT NOT NULL privileges
2416) AS
2417SELECT
2418    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
2419    (data->'value'->>'oid')::oid AS oid,
2420    CASE WHEN data->'value'->'database_id' != 'null'
2421         THEN mz_internal.parse_catalog_id(data->'value'->'database_id')
2422    END AS database_id,
2423    data->'value'->>'name' AS name,
2424    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2425    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
2426FROM mz_internal.mz_catalog_raw
2427WHERE data->>'kind' = 'Schema'",
2428        is_retained_metrics_object: false,
2429        access: vec![PUBLIC_SELECT],
2430    });
2431
2432pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2433    name: "mz_columns",
2434    schema: MZ_CATALOG_SCHEMA,
2435    oid: oid::TABLE_MZ_COLUMNS_OID,
2436    desc: RelationDesc::builder()
2437        .with_column("id", SqlScalarType::String.nullable(false)) // not a key
2438        .with_column("name", SqlScalarType::String.nullable(false))
2439        .with_column("position", SqlScalarType::UInt64.nullable(false))
2440        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2441        .with_column("type", SqlScalarType::String.nullable(false))
2442        .with_column("default", SqlScalarType::String.nullable(true))
2443        .with_column("type_oid", SqlScalarType::Oid.nullable(false))
2444        .with_column("type_mod", SqlScalarType::Int32.nullable(false))
2445        .finish(),
2446    column_comments: BTreeMap::from_iter([
2447        (
2448            "id",
2449            "The unique ID of the table, source, or view containing the column.",
2450        ),
2451        ("name", "The name of the column."),
2452        (
2453            "position",
2454            "The 1-indexed position of the column in its containing table, source, or view.",
2455        ),
2456        ("nullable", "Can the column contain a `NULL` value?"),
2457        ("type", "The data type of the column."),
2458        ("default", "The default expression of the column."),
2459        (
2460            "type_oid",
2461            "The OID of the type of the column (references `mz_types`).",
2462        ),
2463        ("type_mod", "The packed type identifier of the column."),
2464    ]),
2465    is_retained_metrics_object: false,
2466    access: vec![PUBLIC_SELECT],
2467});
2468pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2469    name: "mz_indexes",
2470    schema: MZ_CATALOG_SCHEMA,
2471    oid: oid::TABLE_MZ_INDEXES_OID,
2472    desc: RelationDesc::builder()
2473        .with_column("id", SqlScalarType::String.nullable(false))
2474        .with_column("oid", SqlScalarType::Oid.nullable(false))
2475        .with_column("name", SqlScalarType::String.nullable(false))
2476        .with_column("on_id", SqlScalarType::String.nullable(false))
2477        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2478        .with_column("owner_id", SqlScalarType::String.nullable(false))
2479        .with_column("create_sql", SqlScalarType::String.nullable(false))
2480        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2481        .with_key(vec![0])
2482        .with_key(vec![1])
2483        .finish(),
2484    column_comments: BTreeMap::from_iter([
2485        ("id", "Materialize's unique ID for the index."),
2486        ("oid", "A PostgreSQL-compatible OID for the index."),
2487        ("name", "The name of the index."),
2488        (
2489            "on_id",
2490            "The ID of the relation on which the index is built.",
2491        ),
2492        (
2493            "cluster_id",
2494            "The ID of the cluster in which the index is built.",
2495        ),
2496        (
2497            "owner_id",
2498            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2499        ),
2500        ("create_sql", "The `CREATE` SQL statement for the index."),
2501        (
2502            "redacted_create_sql",
2503            "The redacted `CREATE` SQL statement for the index.",
2504        ),
2505    ]),
2506    is_retained_metrics_object: false,
2507    access: vec![PUBLIC_SELECT],
2508});
2509pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2510    name: "mz_index_columns",
2511    schema: MZ_CATALOG_SCHEMA,
2512    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2513    desc: RelationDesc::builder()
2514        .with_column("index_id", SqlScalarType::String.nullable(false))
2515        .with_column("index_position", SqlScalarType::UInt64.nullable(false))
2516        .with_column("on_position", SqlScalarType::UInt64.nullable(true))
2517        .with_column("on_expression", SqlScalarType::String.nullable(true))
2518        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2519        .finish(),
2520    column_comments: BTreeMap::from_iter([
2521        (
2522            "index_id",
2523            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2524        ),
2525        (
2526            "index_position",
2527            "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.)",
2528        ),
2529        (
2530            "on_position",
2531            "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.",
2532        ),
2533        (
2534            "on_expression",
2535            "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.",
2536        ),
2537        (
2538            "nullable",
2539            "Can this column of the index evaluate to `NULL`?",
2540        ),
2541    ]),
2542    is_retained_metrics_object: false,
2543    access: vec![PUBLIC_SELECT],
2544});
2545pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2546    name: "mz_tables",
2547    schema: MZ_CATALOG_SCHEMA,
2548    oid: oid::TABLE_MZ_TABLES_OID,
2549    desc: RelationDesc::builder()
2550        .with_column("id", SqlScalarType::String.nullable(false))
2551        .with_column("oid", SqlScalarType::Oid.nullable(false))
2552        .with_column("schema_id", SqlScalarType::String.nullable(false))
2553        .with_column("name", SqlScalarType::String.nullable(false))
2554        .with_column("owner_id", SqlScalarType::String.nullable(false))
2555        .with_column(
2556            "privileges",
2557            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2558        )
2559        .with_column("create_sql", SqlScalarType::String.nullable(true))
2560        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2561        .with_column("source_id", SqlScalarType::String.nullable(true))
2562        .with_key(vec![0])
2563        .with_key(vec![1])
2564        .finish(),
2565    column_comments: BTreeMap::from_iter([
2566        ("id", "Materialize's unique ID for the table."),
2567        ("oid", "A PostgreSQL-compatible OID for the table."),
2568        (
2569            "schema_id",
2570            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2571        ),
2572        ("name", "The name of the table."),
2573        (
2574            "owner_id",
2575            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2576        ),
2577        ("privileges", "The privileges belonging to the table."),
2578        ("create_sql", "The `CREATE` SQL statement for the table."),
2579        (
2580            "redacted_create_sql",
2581            "The redacted `CREATE` SQL statement for the table.",
2582        ),
2583        (
2584            "source_id",
2585            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2586        ),
2587    ]),
2588    is_retained_metrics_object: true,
2589    access: vec![PUBLIC_SELECT],
2590});
2591
2592pub static MZ_CONNECTIONS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
2593    BuiltinMaterializedView {
2594        name: "mz_connections",
2595        schema: MZ_CATALOG_SCHEMA,
2596        oid: oid::MV_MZ_CONNECTIONS_OID,
2597        desc: RelationDesc::builder()
2598            .with_column("id", SqlScalarType::String.nullable(false))
2599            .with_column("oid", SqlScalarType::Oid.nullable(false))
2600            .with_column("schema_id", SqlScalarType::String.nullable(false))
2601            .with_column("name", SqlScalarType::String.nullable(false))
2602            .with_column("type", SqlScalarType::String.nullable(false))
2603            .with_column("owner_id", SqlScalarType::String.nullable(false))
2604            .with_column(
2605                "privileges",
2606                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2607            )
2608            .with_column("create_sql", SqlScalarType::String.nullable(false))
2609            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2610            .with_key(vec![0])
2611            .with_key(vec![1])
2612            .finish(),
2613        column_comments: BTreeMap::from_iter([
2614            ("id", "The unique ID of the connection."),
2615            ("oid", "A PostgreSQL-compatible OID for the connection."),
2616            (
2617                "schema_id",
2618                "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2619            ),
2620            ("name", "The name of the connection."),
2621            (
2622                "type",
2623                "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2624            ),
2625            (
2626                "owner_id",
2627                "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2628            ),
2629            ("privileges", "The privileges belonging to the connection."),
2630            (
2631                "create_sql",
2632                "The `CREATE` SQL statement for the connection.",
2633            ),
2634            (
2635                "redacted_create_sql",
2636                "The redacted `CREATE` SQL statement for the connection.",
2637            ),
2638        ]),
2639        sql: "
2640IN CLUSTER mz_catalog_server
2641WITH (
2642    ASSERT NOT NULL id,
2643    ASSERT NOT NULL oid,
2644    ASSERT NOT NULL schema_id,
2645    ASSERT NOT NULL name,
2646    ASSERT NOT NULL type,
2647    ASSERT NOT NULL owner_id,
2648    ASSERT NOT NULL privileges,
2649    ASSERT NOT NULL create_sql,
2650    ASSERT NOT NULL redacted_create_sql
2651) AS
2652SELECT
2653    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
2654    (data->'value'->>'oid')::oid AS oid,
2655    mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
2656    data->'value'->>'name' AS name,
2657    mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'connection_type' AS type,
2658    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2659    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
2660    data->'value'->'definition'->'V1'->>'create_sql' AS create_sql,
2661    mz_internal.redact_sql(data->'value'->'definition'->'V1'->>'create_sql') AS redacted_create_sql
2662FROM mz_internal.mz_catalog_raw
2663WHERE
2664    data->>'kind' = 'Item' AND
2665    mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'type' = 'connection'",
2666        is_retained_metrics_object: false,
2667        access: vec![PUBLIC_SELECT],
2668    }
2669});
2670
2671pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2672    name: "mz_ssh_tunnel_connections",
2673    schema: MZ_CATALOG_SCHEMA,
2674    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2675    desc: RelationDesc::builder()
2676        .with_column("id", SqlScalarType::String.nullable(false))
2677        .with_column("public_key_1", SqlScalarType::String.nullable(false))
2678        .with_column("public_key_2", SqlScalarType::String.nullable(false))
2679        .finish(),
2680    column_comments: BTreeMap::from_iter([
2681        ("id", "The ID of the connection."),
2682        (
2683            "public_key_1",
2684            "The first public key associated with the SSH tunnel.",
2685        ),
2686        (
2687            "public_key_2",
2688            "The second public key associated with the SSH tunnel.",
2689        ),
2690    ]),
2691    is_retained_metrics_object: false,
2692    access: vec![PUBLIC_SELECT],
2693});
2694pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2695    name: "mz_sources",
2696    schema: MZ_CATALOG_SCHEMA,
2697    oid: oid::TABLE_MZ_SOURCES_OID,
2698    desc: RelationDesc::builder()
2699        .with_column("id", SqlScalarType::String.nullable(false))
2700        .with_column("oid", SqlScalarType::Oid.nullable(false))
2701        .with_column("schema_id", SqlScalarType::String.nullable(false))
2702        .with_column("name", SqlScalarType::String.nullable(false))
2703        .with_column("type", SqlScalarType::String.nullable(false))
2704        .with_column("connection_id", SqlScalarType::String.nullable(true))
2705        .with_column("size", SqlScalarType::String.nullable(true))
2706        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2707        .with_column("key_format", SqlScalarType::String.nullable(true))
2708        .with_column("value_format", SqlScalarType::String.nullable(true))
2709        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2710        .with_column("owner_id", SqlScalarType::String.nullable(false))
2711        .with_column(
2712            "privileges",
2713            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2714        )
2715        .with_column("create_sql", SqlScalarType::String.nullable(true))
2716        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2717        .with_key(vec![0])
2718        .with_key(vec![1])
2719        .finish(),
2720    column_comments: BTreeMap::from_iter([
2721        ("id", "Materialize's unique ID for the source."),
2722        ("oid", "A PostgreSQL-compatible OID for the source."),
2723        (
2724            "schema_id",
2725            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2726        ),
2727        ("name", "The name of the source."),
2728        (
2729            "type",
2730            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2731        ),
2732        (
2733            "connection_id",
2734            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2735        ),
2736        ("size", "*Deprecated* The size of the source."),
2737        (
2738            "envelope_type",
2739            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2740        ),
2741        (
2742            "key_format",
2743            "For Kafka sources, the format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2744        ),
2745        (
2746            "value_format",
2747            "For Kafka sources, the format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2748        ),
2749        (
2750            "cluster_id",
2751            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2752        ),
2753        (
2754            "owner_id",
2755            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2756        ),
2757        ("privileges", "The privileges granted on the source."),
2758        ("create_sql", "The `CREATE` SQL statement for the source."),
2759        (
2760            "redacted_create_sql",
2761            "The redacted `CREATE` SQL statement for the source.",
2762        ),
2763    ]),
2764    is_retained_metrics_object: true,
2765    access: vec![PUBLIC_SELECT],
2766});
2767pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2768    BuiltinTable {
2769        name: "mz_sinks",
2770        schema: MZ_CATALOG_SCHEMA,
2771        oid: oid::TABLE_MZ_SINKS_OID,
2772        desc: RelationDesc::builder()
2773            .with_column("id", SqlScalarType::String.nullable(false))
2774            .with_column("oid", SqlScalarType::Oid.nullable(false))
2775            .with_column("schema_id", SqlScalarType::String.nullable(false))
2776            .with_column("name", SqlScalarType::String.nullable(false))
2777            .with_column("type", SqlScalarType::String.nullable(false))
2778            .with_column("connection_id", SqlScalarType::String.nullable(true))
2779            .with_column("size", SqlScalarType::String.nullable(true))
2780            .with_column("envelope_type", SqlScalarType::String.nullable(true))
2781            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2782            // below. This should be removed in the future.
2783            .with_column("format", SqlScalarType::String.nullable(true))
2784            .with_column("key_format", SqlScalarType::String.nullable(true))
2785            .with_column("value_format", SqlScalarType::String.nullable(true))
2786            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2787            .with_column("owner_id", SqlScalarType::String.nullable(false))
2788            .with_column("create_sql", SqlScalarType::String.nullable(false))
2789            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2790            .with_key(vec![0])
2791            .with_key(vec![1])
2792            .finish(),
2793        column_comments: BTreeMap::from_iter([
2794            ("id", "Materialize's unique ID for the sink."),
2795            ("oid", "A PostgreSQL-compatible OID for the sink."),
2796            (
2797                "schema_id",
2798                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2799            ),
2800            ("name", "The name of the sink."),
2801            ("type", "The type of the sink: `kafka`."),
2802            (
2803                "connection_id",
2804                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2805            ),
2806            ("size", "The size of the sink."),
2807            (
2808                "envelope_type",
2809                "The envelope of the sink: `upsert`, or `debezium`.",
2810            ),
2811            (
2812                "format",
2813                "*Deprecated* The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2814            ),
2815            (
2816                "key_format",
2817                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2818            ),
2819            (
2820                "value_format",
2821                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2822            ),
2823            (
2824                "cluster_id",
2825                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2826            ),
2827            (
2828                "owner_id",
2829                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2830            ),
2831            ("create_sql", "The `CREATE` SQL statement for the sink."),
2832            (
2833                "redacted_create_sql",
2834                "The redacted `CREATE` SQL statement for the sink.",
2835            ),
2836        ]),
2837        is_retained_metrics_object: true,
2838        access: vec![PUBLIC_SELECT],
2839    }
2840});
2841pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2842    name: "mz_views",
2843    schema: MZ_CATALOG_SCHEMA,
2844    oid: oid::TABLE_MZ_VIEWS_OID,
2845    desc: RelationDesc::builder()
2846        .with_column("id", SqlScalarType::String.nullable(false))
2847        .with_column("oid", SqlScalarType::Oid.nullable(false))
2848        .with_column("schema_id", SqlScalarType::String.nullable(false))
2849        .with_column("name", SqlScalarType::String.nullable(false))
2850        .with_column("definition", SqlScalarType::String.nullable(false))
2851        .with_column("owner_id", SqlScalarType::String.nullable(false))
2852        .with_column(
2853            "privileges",
2854            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2855        )
2856        .with_column("create_sql", SqlScalarType::String.nullable(false))
2857        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2858        .with_key(vec![0])
2859        .with_key(vec![1])
2860        .finish(),
2861    column_comments: BTreeMap::from_iter([
2862        ("id", "Materialize's unique ID for the view."),
2863        ("oid", "A PostgreSQL-compatible OID for the view."),
2864        (
2865            "schema_id",
2866            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2867        ),
2868        ("name", "The name of the view."),
2869        ("definition", "The view definition (a `SELECT` query)."),
2870        (
2871            "owner_id",
2872            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2873        ),
2874        ("privileges", "The privileges belonging to the view."),
2875        ("create_sql", "The `CREATE` SQL statement for the view."),
2876        (
2877            "redacted_create_sql",
2878            "The redacted `CREATE` SQL statement for the view.",
2879        ),
2880    ]),
2881    is_retained_metrics_object: false,
2882    access: vec![PUBLIC_SELECT],
2883});
2884
2885pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
2886    BuiltinMaterializedView {
2887        name: "mz_materialized_views",
2888        schema: MZ_CATALOG_SCHEMA,
2889        oid: oid::MV_MZ_MATERIALIZED_VIEWS_OID,
2890        desc: RelationDesc::builder()
2891            .with_column("id", SqlScalarType::String.nullable(false))
2892            .with_column("oid", SqlScalarType::Oid.nullable(false))
2893            .with_column("schema_id", SqlScalarType::String.nullable(false))
2894            .with_column("name", SqlScalarType::String.nullable(false))
2895            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2896            .with_column("definition", SqlScalarType::String.nullable(false))
2897            .with_column("owner_id", SqlScalarType::String.nullable(false))
2898            .with_column(
2899                "privileges",
2900                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2901            )
2902            .with_column("create_sql", SqlScalarType::String.nullable(false))
2903            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2904            .with_key(vec![0])
2905            .with_key(vec![1])
2906            .finish(),
2907        column_comments: BTreeMap::from_iter([
2908            ("id", "Materialize's unique ID for the materialized view."),
2909            (
2910                "oid",
2911                "A PostgreSQL-compatible OID for the materialized view.",
2912            ),
2913            (
2914                "schema_id",
2915                "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2916            ),
2917            ("name", "The name of the materialized view."),
2918            (
2919                "cluster_id",
2920                "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2921            ),
2922            (
2923                "definition",
2924                "The materialized view definition (a `SELECT` query).",
2925            ),
2926            (
2927                "owner_id",
2928                "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2929            ),
2930            (
2931                "privileges",
2932                "The privileges belonging to the materialized view.",
2933            ),
2934            (
2935                "create_sql",
2936                "The `CREATE` SQL statement for the materialized view.",
2937            ),
2938            (
2939                "redacted_create_sql",
2940                "The redacted `CREATE` SQL statement for the materialized view.",
2941            ),
2942        ]),
2943        sql: Box::leak(format!("
2944IN CLUSTER mz_catalog_server
2945WITH (
2946    ASSERT NOT NULL id,
2947    ASSERT NOT NULL oid,
2948    ASSERT NOT NULL schema_id,
2949    ASSERT NOT NULL name,
2950    ASSERT NOT NULL cluster_id,
2951    ASSERT NOT NULL definition,
2952    ASSERT NOT NULL owner_id,
2953    ASSERT NOT NULL privileges,
2954    ASSERT NOT NULL create_sql,
2955    ASSERT NOT NULL redacted_create_sql
2956) AS
2957WITH
2958    user_mvs AS (
2959        SELECT
2960            mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
2961            (data->'value'->>'oid')::oid AS oid,
2962            mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
2963            data->'value'->>'name' AS name,
2964            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'cluster_id' AS cluster_id,
2965            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'definition' AS definition,
2966            mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2967            mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
2968            data->'value'->'definition'->'V1'->>'create_sql' AS create_sql,
2969            mz_internal.redact_sql(data->'value'->'definition'->'V1'->>'create_sql') AS redacted_create_sql
2970        FROM mz_internal.mz_catalog_raw
2971        WHERE
2972            data->>'kind' = 'Item' AND
2973            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'type' = 'materialized-view'
2974    ),
2975    builtin_mappings AS (
2976        SELECT
2977            data->'key'->>'schema_name' AS schema_name,
2978            data->'key'->>'object_name' AS name,
2979            's' || (data->'value'->>'catalog_id') AS id
2980        FROM mz_internal.mz_catalog_raw
2981        WHERE
2982            data->>'kind' = 'GidMapping' AND
2983            data->'key'->>'object_type' = '5'
2984    ),
2985    builtin_mvs AS (
2986        SELECT
2987            m.id,
2988            mv.oid,
2989            s.id AS schema_id,
2990            mv.name,
2991            c.id AS cluster_id,
2992            mv.definition,
2993            '{MZ_SYSTEM_ROLE_ID}' AS owner_id,
2994            mv.privileges,
2995            mv.create_sql,
2996            mz_internal.redact_sql(mv.create_sql) AS redacted_create_sql
2997        FROM mz_internal.mz_builtin_materialized_views mv
2998        JOIN builtin_mappings m USING (schema_name, name)
2999        JOIN mz_schemas s ON s.name = mv.schema_name
3000        JOIN mz_clusters c ON c.name = mv.cluster_name
3001        WHERE s.database_id IS NULL
3002    )
3003SELECT * FROM user_mvs
3004UNION ALL
3005SELECT * FROM builtin_mvs").into_boxed_str()),
3006        is_retained_metrics_object: false,
3007        access: vec![PUBLIC_SELECT],
3008    }
3009});
3010
3011pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
3012    BuiltinTable {
3013        name: "mz_materialized_view_refresh_strategies",
3014        schema: MZ_INTERNAL_SCHEMA,
3015        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
3016        desc: RelationDesc::builder()
3017            .with_column(
3018                "materialized_view_id",
3019                SqlScalarType::String.nullable(false),
3020            )
3021            .with_column("type", SqlScalarType::String.nullable(false))
3022            .with_column("interval", SqlScalarType::Interval.nullable(true))
3023            .with_column(
3024                "aligned_to",
3025                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3026            )
3027            .with_column(
3028                "at",
3029                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3030            )
3031            .finish(),
3032        column_comments: BTreeMap::from_iter([
3033            (
3034                "materialized_view_id",
3035                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
3036            ),
3037            (
3038                "type",
3039                "`at`, `every`, or `on-commit`. Default: `on-commit`",
3040            ),
3041            (
3042                "interval",
3043                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
3044            ),
3045            (
3046                "aligned_to",
3047                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
3048            ),
3049            (
3050                "at",
3051                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
3052            ),
3053        ]),
3054        is_retained_metrics_object: false,
3055        access: vec![PUBLIC_SELECT],
3056    }
3057});
3058pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3059    name: "mz_types",
3060    schema: MZ_CATALOG_SCHEMA,
3061    oid: oid::TABLE_MZ_TYPES_OID,
3062    desc: RelationDesc::builder()
3063        .with_column("id", SqlScalarType::String.nullable(false))
3064        .with_column("oid", SqlScalarType::Oid.nullable(false))
3065        .with_column("schema_id", SqlScalarType::String.nullable(false))
3066        .with_column("name", SqlScalarType::String.nullable(false))
3067        .with_column("category", SqlScalarType::String.nullable(false))
3068        .with_column("owner_id", SqlScalarType::String.nullable(false))
3069        .with_column(
3070            "privileges",
3071            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3072        )
3073        .with_column("create_sql", SqlScalarType::String.nullable(true))
3074        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
3075        .with_key(vec![0])
3076        .with_key(vec![1])
3077        .finish(),
3078    column_comments: BTreeMap::from_iter([
3079        ("id", "Materialize's unique ID for the type."),
3080        ("oid", "A PostgreSQL-compatible OID for the type."),
3081        (
3082            "schema_id",
3083            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
3084        ),
3085        ("name", "The name of the type."),
3086        ("category", "The category of the type."),
3087        (
3088            "owner_id",
3089            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
3090        ),
3091        ("privileges", "The privileges belonging to the type."),
3092        ("create_sql", "The `CREATE` SQL statement for the type."),
3093        (
3094            "redacted_create_sql",
3095            "The redacted `CREATE` SQL statement for the type.",
3096        ),
3097    ]),
3098    is_retained_metrics_object: false,
3099    access: vec![PUBLIC_SELECT],
3100});
3101
3102pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3103    BuiltinMaterializedView {
3104        name: "mz_network_policies",
3105        schema: MZ_INTERNAL_SCHEMA,
3106        oid: oid::MV_MZ_NETWORK_POLICIES_OID,
3107        desc: RelationDesc::builder()
3108            .with_column("id", SqlScalarType::String.nullable(false))
3109            .with_column("name", SqlScalarType::String.nullable(false))
3110            .with_column("owner_id", SqlScalarType::String.nullable(false))
3111            .with_column(
3112                "privileges",
3113                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3114            )
3115            .with_column("oid", SqlScalarType::Oid.nullable(false))
3116            .with_key(vec![0])
3117            .with_key(vec![4])
3118            .finish(),
3119        column_comments: BTreeMap::from_iter([
3120            ("id", "The ID of the network policy."),
3121            ("name", "The name of the network policy."),
3122            (
3123                "owner_id",
3124                "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
3125            ),
3126            (
3127                "privileges",
3128                "The privileges belonging to the network policy.",
3129            ),
3130            ("oid", "A PostgreSQL-compatible OID for the network policy."),
3131        ]),
3132        sql: "
3133IN CLUSTER mz_catalog_server
3134WITH (
3135    ASSERT NOT NULL id,
3136    ASSERT NOT NULL name,
3137    ASSERT NOT NULL owner_id,
3138    ASSERT NOT NULL privileges,
3139    ASSERT NOT NULL oid
3140) AS
3141SELECT
3142    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
3143    data->'value'->>'name' AS name,
3144    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
3145    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
3146    (data->'value'->>'oid')::oid AS oid
3147FROM mz_internal.mz_catalog_raw
3148WHERE data->>'kind' = 'NetworkPolicy'",
3149        is_retained_metrics_object: false,
3150        access: vec![PUBLIC_SELECT],
3151    }
3152});
3153
3154pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3155    BuiltinMaterializedView {
3156        name: "mz_network_policy_rules",
3157        schema: MZ_INTERNAL_SCHEMA,
3158        oid: oid::MV_MZ_NETWORK_POLICY_RULES_OID,
3159        desc: RelationDesc::builder()
3160            .with_column("name", SqlScalarType::String.nullable(false))
3161            .with_column("policy_id", SqlScalarType::String.nullable(false))
3162            .with_column("action", SqlScalarType::String.nullable(false))
3163            .with_column("address", SqlScalarType::String.nullable(false))
3164            .with_column("direction", SqlScalarType::String.nullable(false))
3165            .finish(),
3166        column_comments: BTreeMap::from_iter([
3167            (
3168                "name",
3169                "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
3170            ),
3171            (
3172                "policy_id",
3173                "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
3174            ),
3175            (
3176                "action",
3177                "The action of the rule. `allow` is the only supported action.",
3178            ),
3179            ("address", "The address the rule will take action on."),
3180            (
3181                "direction",
3182                "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3183            ),
3184        ]),
3185        sql: "
3186IN CLUSTER mz_catalog_server
3187WITH (
3188    ASSERT NOT NULL name,
3189    ASSERT NOT NULL policy_id,
3190    ASSERT NOT NULL action,
3191    ASSERT NOT NULL address,
3192    ASSERT NOT NULL direction
3193) AS
3194SELECT
3195    rule->>'name' AS name,
3196    mz_internal.parse_catalog_id(data->'key'->'id') AS policy_id,
3197    lower(rule->>'action') AS action,
3198    rule->>'address' AS address,
3199    lower(rule->>'direction') AS direction
3200FROM
3201    mz_internal.mz_catalog_raw,
3202    jsonb_array_elements(data->'value'->'rules') AS rule
3203WHERE data->>'kind' = 'NetworkPolicy'",
3204        is_retained_metrics_object: false,
3205        access: vec![PUBLIC_SELECT],
3206    }
3207});
3208
3209/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3210/// in the `mz_types` table as part of our public, stable API.
3211pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3212    name: "mz_type_pg_metadata",
3213    schema: MZ_INTERNAL_SCHEMA,
3214    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3215    desc: RelationDesc::builder()
3216        .with_column("id", SqlScalarType::String.nullable(false))
3217        .with_column("typinput", SqlScalarType::Oid.nullable(false))
3218        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
3219        .finish(),
3220    column_comments: BTreeMap::new(),
3221    is_retained_metrics_object: false,
3222    access: vec![PUBLIC_SELECT],
3223});
3224pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3225    name: "mz_array_types",
3226    schema: MZ_CATALOG_SCHEMA,
3227    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3228    desc: RelationDesc::builder()
3229        .with_column("id", SqlScalarType::String.nullable(false))
3230        .with_column("element_id", SqlScalarType::String.nullable(false))
3231        .finish(),
3232    column_comments: BTreeMap::from_iter([
3233        ("id", "The ID of the array type."),
3234        ("element_id", "The ID of the array's element type."),
3235    ]),
3236    is_retained_metrics_object: false,
3237    access: vec![PUBLIC_SELECT],
3238});
3239pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3240    name: "mz_base_types",
3241    schema: MZ_CATALOG_SCHEMA,
3242    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3243    desc: RelationDesc::builder()
3244        .with_column("id", SqlScalarType::String.nullable(false))
3245        .finish(),
3246    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3247    is_retained_metrics_object: false,
3248    access: vec![PUBLIC_SELECT],
3249});
3250pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3251    name: "mz_list_types",
3252    schema: MZ_CATALOG_SCHEMA,
3253    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3254    desc: RelationDesc::builder()
3255        .with_column("id", SqlScalarType::String.nullable(false))
3256        .with_column("element_id", SqlScalarType::String.nullable(false))
3257        .with_column(
3258            "element_modifiers",
3259            SqlScalarType::List {
3260                element_type: Box::new(SqlScalarType::Int64),
3261                custom_id: None,
3262            }
3263            .nullable(true),
3264        )
3265        .finish(),
3266    column_comments: BTreeMap::from_iter([
3267        ("id", "The ID of the list type."),
3268        ("element_id", "The IID of the list's element type."),
3269        (
3270            "element_modifiers",
3271            "The element type modifiers, or `NULL` if none.",
3272        ),
3273    ]),
3274    is_retained_metrics_object: false,
3275    access: vec![PUBLIC_SELECT],
3276});
3277pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3278    name: "mz_map_types",
3279    schema: MZ_CATALOG_SCHEMA,
3280    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3281    desc: RelationDesc::builder()
3282        .with_column("id", SqlScalarType::String.nullable(false))
3283        .with_column("key_id", SqlScalarType::String.nullable(false))
3284        .with_column("value_id", SqlScalarType::String.nullable(false))
3285        .with_column(
3286            "key_modifiers",
3287            SqlScalarType::List {
3288                element_type: Box::new(SqlScalarType::Int64),
3289                custom_id: None,
3290            }
3291            .nullable(true),
3292        )
3293        .with_column(
3294            "value_modifiers",
3295            SqlScalarType::List {
3296                element_type: Box::new(SqlScalarType::Int64),
3297                custom_id: None,
3298            }
3299            .nullable(true),
3300        )
3301        .finish(),
3302    column_comments: BTreeMap::from_iter([
3303        ("id", "The ID of the map type."),
3304        ("key_id", "The ID of the map's key type."),
3305        ("value_id", "The ID of the map's value type."),
3306        (
3307            "key_modifiers",
3308            "The key type modifiers, or `NULL` if none.",
3309        ),
3310        (
3311            "value_modifiers",
3312            "The value type modifiers, or `NULL` if none.",
3313        ),
3314    ]),
3315    is_retained_metrics_object: false,
3316    access: vec![PUBLIC_SELECT],
3317});
3318pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3319    name: "mz_roles",
3320    schema: MZ_CATALOG_SCHEMA,
3321    oid: oid::TABLE_MZ_ROLES_OID,
3322    desc: RelationDesc::builder()
3323        .with_column("id", SqlScalarType::String.nullable(false))
3324        .with_column("oid", SqlScalarType::Oid.nullable(false))
3325        .with_column("name", SqlScalarType::String.nullable(false))
3326        .with_column("inherit", SqlScalarType::Bool.nullable(false))
3327        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(true))
3328        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
3329        .with_key(vec![0])
3330        .with_key(vec![1])
3331        .finish(),
3332    column_comments: BTreeMap::from_iter([
3333        ("id", "Materialize's unique ID for the role."),
3334        ("oid", "A PostgreSQL-compatible OID for the role."),
3335        ("name", "The name of the role."),
3336        (
3337            "inherit",
3338            "Indicates whether the role has inheritance of privileges.",
3339        ),
3340        ("rolcanlogin", "Indicates whether the role can log in."),
3341        ("rolsuper", "Indicates whether the role is a superuser."),
3342    ]),
3343    is_retained_metrics_object: false,
3344    access: vec![PUBLIC_SELECT],
3345});
3346
3347pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3348    BuiltinMaterializedView {
3349        name: "mz_role_members",
3350        schema: MZ_CATALOG_SCHEMA,
3351        oid: oid::MV_MZ_ROLE_MEMBERS_OID,
3352        desc: RelationDesc::builder()
3353            .with_column("role_id", SqlScalarType::String.nullable(false))
3354            .with_column("member", SqlScalarType::String.nullable(false))
3355            .with_column("grantor", SqlScalarType::String.nullable(false))
3356            .finish(),
3357        column_comments: BTreeMap::from_iter([
3358            (
3359                "role_id",
3360                "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3361            ),
3362            (
3363                "member",
3364                "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3365            ),
3366            (
3367                "grantor",
3368                "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3369            ),
3370        ]),
3371        sql: "
3372IN CLUSTER mz_catalog_server
3373WITH (
3374    ASSERT NOT NULL role_id,
3375    ASSERT NOT NULL member,
3376    ASSERT NOT NULL grantor
3377) AS
3378SELECT
3379    mz_internal.parse_catalog_id(entry->'key') AS role_id,
3380    mz_internal.parse_catalog_id(data->'key'->'id') AS member,
3381    mz_internal.parse_catalog_id(entry->'value') AS grantor
3382FROM
3383    mz_internal.mz_catalog_raw,
3384    jsonb_array_elements(data->'value'->'membership'->'map') AS entry
3385WHERE data->>'kind' = 'Role'",
3386        is_retained_metrics_object: false,
3387        access: vec![PUBLIC_SELECT],
3388    }
3389});
3390
3391pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3392    name: "mz_role_parameters",
3393    schema: MZ_CATALOG_SCHEMA,
3394    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3395    desc: RelationDesc::builder()
3396        .with_column("role_id", SqlScalarType::String.nullable(false))
3397        .with_column("parameter_name", SqlScalarType::String.nullable(false))
3398        .with_column("parameter_value", SqlScalarType::String.nullable(false))
3399        .finish(),
3400    column_comments: BTreeMap::from_iter([
3401        (
3402            "role_id",
3403            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3404        ),
3405        (
3406            "parameter_name",
3407            "The configuration parameter name. One of the supported configuration parameters.",
3408        ),
3409        (
3410            "parameter_value",
3411            "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.",
3412        ),
3413    ]),
3414    is_retained_metrics_object: false,
3415    access: vec![PUBLIC_SELECT],
3416});
3417pub static MZ_ROLE_AUTH: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3418    name: "mz_role_auth",
3419    schema: MZ_CATALOG_SCHEMA,
3420    oid: oid::TABLE_MZ_ROLE_AUTH_OID,
3421    desc: RelationDesc::builder()
3422        .with_column("role_id", SqlScalarType::String.nullable(false))
3423        .with_column("role_oid", SqlScalarType::Oid.nullable(false))
3424        .with_column("password_hash", SqlScalarType::String.nullable(true))
3425        .with_column(
3426            "updated_at",
3427            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3428        )
3429        .finish(),
3430    column_comments: BTreeMap::from_iter([
3431        (
3432            "role_id",
3433            "The ID of the role. Corresponds to `mz_roles.id`.",
3434        ),
3435        ("role_oid", "A PostgreSQL-compatible OID for the role."),
3436        (
3437            "password_hash",
3438            "The hashed password for the role, if any. Uses the `SCRAM-SHA-256` algorithm.",
3439        ),
3440        (
3441            "updated_at",
3442            "The time at which the password was last updated.",
3443        ),
3444    ]),
3445    is_retained_metrics_object: false,
3446    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
3447});
3448pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3449    name: "mz_pseudo_types",
3450    schema: MZ_CATALOG_SCHEMA,
3451    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3452    desc: RelationDesc::builder()
3453        .with_column("id", SqlScalarType::String.nullable(false))
3454        .finish(),
3455    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3456    is_retained_metrics_object: false,
3457    access: vec![PUBLIC_SELECT],
3458});
3459pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3460    BuiltinTable {
3461        name: "mz_functions",
3462        schema: MZ_CATALOG_SCHEMA,
3463        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3464        desc: RelationDesc::builder()
3465            .with_column("id", SqlScalarType::String.nullable(false)) // not a key!
3466            .with_column("oid", SqlScalarType::Oid.nullable(false))
3467            .with_column("schema_id", SqlScalarType::String.nullable(false))
3468            .with_column("name", SqlScalarType::String.nullable(false))
3469            .with_column(
3470                "argument_type_ids",
3471                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3472            )
3473            .with_column(
3474                "variadic_argument_type_id",
3475                SqlScalarType::String.nullable(true),
3476            )
3477            .with_column("return_type_id", SqlScalarType::String.nullable(true))
3478            .with_column("returns_set", SqlScalarType::Bool.nullable(false))
3479            .with_column("owner_id", SqlScalarType::String.nullable(false))
3480            .finish(),
3481        column_comments: BTreeMap::from_iter([
3482            ("id", "Materialize's unique ID for the function."),
3483            ("oid", "A PostgreSQL-compatible OID for the function."),
3484            (
3485                "schema_id",
3486                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3487            ),
3488            ("name", "The name of the function."),
3489            (
3490                "argument_type_ids",
3491                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3492            ),
3493            (
3494                "variadic_argument_type_id",
3495                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3496            ),
3497            (
3498                "return_type_id",
3499                "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`].",
3500            ),
3501            (
3502                "returns_set",
3503                "Whether the function returns a set, i.e. the function is a table function.",
3504            ),
3505            (
3506                "owner_id",
3507                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3508            ),
3509        ]),
3510        is_retained_metrics_object: false,
3511        access: vec![PUBLIC_SELECT],
3512    }
3513});
3514pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3515    name: "mz_operators",
3516    schema: MZ_CATALOG_SCHEMA,
3517    oid: oid::TABLE_MZ_OPERATORS_OID,
3518    desc: RelationDesc::builder()
3519        .with_column("oid", SqlScalarType::Oid.nullable(false))
3520        .with_column("name", SqlScalarType::String.nullable(false))
3521        .with_column(
3522            "argument_type_ids",
3523            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3524        )
3525        .with_column("return_type_id", SqlScalarType::String.nullable(true))
3526        .finish(),
3527    column_comments: BTreeMap::new(),
3528    is_retained_metrics_object: false,
3529    access: vec![PUBLIC_SELECT],
3530});
3531pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3532    name: "mz_aggregates",
3533    schema: MZ_INTERNAL_SCHEMA,
3534    oid: oid::TABLE_MZ_AGGREGATES_OID,
3535    desc: RelationDesc::builder()
3536        .with_column("oid", SqlScalarType::Oid.nullable(false))
3537        .with_column("agg_kind", SqlScalarType::String.nullable(false))
3538        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
3539        .finish(),
3540    column_comments: BTreeMap::new(),
3541    is_retained_metrics_object: false,
3542    access: vec![PUBLIC_SELECT],
3543});
3544
3545pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3546    name: "mz_clusters",
3547    schema: MZ_CATALOG_SCHEMA,
3548    oid: oid::TABLE_MZ_CLUSTERS_OID,
3549    desc: RelationDesc::builder()
3550        .with_column("id", SqlScalarType::String.nullable(false))
3551        .with_column("name", SqlScalarType::String.nullable(false))
3552        .with_column("owner_id", SqlScalarType::String.nullable(false))
3553        .with_column(
3554            "privileges",
3555            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3556        )
3557        .with_column("managed", SqlScalarType::Bool.nullable(false))
3558        .with_column("size", SqlScalarType::String.nullable(true))
3559        .with_column("replication_factor", SqlScalarType::UInt32.nullable(true))
3560        .with_column("disk", SqlScalarType::Bool.nullable(true))
3561        .with_column(
3562            "availability_zones",
3563            SqlScalarType::List {
3564                element_type: Box::new(SqlScalarType::String),
3565                custom_id: None,
3566            }
3567            .nullable(true),
3568        )
3569        .with_column(
3570            "introspection_debugging",
3571            SqlScalarType::Bool.nullable(true),
3572        )
3573        .with_column(
3574            "introspection_interval",
3575            SqlScalarType::Interval.nullable(true),
3576        )
3577        .with_key(vec![0])
3578        .finish(),
3579    column_comments: BTreeMap::from_iter([
3580        ("id", "Materialize's unique ID for the cluster."),
3581        ("name", "The name of the cluster."),
3582        (
3583            "owner_id",
3584            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3585        ),
3586        ("privileges", "The privileges belonging to the cluster."),
3587        (
3588            "managed",
3589            "Whether the cluster is a managed cluster with automatically managed replicas.",
3590        ),
3591        (
3592            "size",
3593            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3594        ),
3595        (
3596            "replication_factor",
3597            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3598        ),
3599        (
3600            "disk",
3601            "**Unstable** If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3602        ),
3603        (
3604            "availability_zones",
3605            "**Unstable** If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3606        ),
3607        (
3608            "introspection_debugging",
3609            "Whether introspection of the gathering of the introspection data is enabled.",
3610        ),
3611        (
3612            "introspection_interval",
3613            "The interval at which to collect introspection data.",
3614        ),
3615    ]),
3616    is_retained_metrics_object: false,
3617    access: vec![PUBLIC_SELECT],
3618});
3619
3620pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinMaterializedView> =
3621    LazyLock::new(|| BuiltinMaterializedView {
3622        name: "mz_cluster_workload_classes",
3623        schema: MZ_INTERNAL_SCHEMA,
3624        oid: oid::MV_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3625        desc: RelationDesc::builder()
3626            .with_column("id", SqlScalarType::String.nullable(false))
3627            .with_column("workload_class", SqlScalarType::String.nullable(true))
3628            .with_key(vec![0])
3629            .finish(),
3630        column_comments: BTreeMap::new(),
3631        sql: "
3632IN CLUSTER mz_catalog_server
3633WITH (
3634    ASSERT NOT NULL id
3635) AS
3636SELECT
3637    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
3638    CASE WHEN data->'value'->'config'->'workload_class' != 'null'
3639         THEN data->'value'->'config'->>'workload_class'
3640    END AS workload_class
3641FROM mz_internal.mz_catalog_raw
3642WHERE data->>'kind' = 'Cluster'",
3643        is_retained_metrics_object: false,
3644        access: vec![PUBLIC_SELECT],
3645    });
3646
3647pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3648    name: "mz_cluster_workload_classes_ind",
3649    schema: MZ_INTERNAL_SCHEMA,
3650    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3651    sql: "IN CLUSTER mz_catalog_server
3652ON mz_internal.mz_cluster_workload_classes (id)",
3653    is_retained_metrics_object: false,
3654};
3655
3656pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3657    name: "mz_cluster_schedules",
3658    schema: MZ_INTERNAL_SCHEMA,
3659    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3660    desc: RelationDesc::builder()
3661        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3662        .with_column("type", SqlScalarType::String.nullable(false))
3663        .with_column(
3664            "refresh_hydration_time_estimate",
3665            SqlScalarType::Interval.nullable(true),
3666        )
3667        .finish(),
3668    column_comments: BTreeMap::from_iter([
3669        (
3670            "cluster_id",
3671            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3672        ),
3673        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3674        (
3675            "refresh_hydration_time_estimate",
3676            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3677        ),
3678    ]),
3679    is_retained_metrics_object: false,
3680    access: vec![PUBLIC_SELECT],
3681});
3682
3683pub static MZ_SECRETS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3684    BuiltinMaterializedView {
3685        name: "mz_secrets",
3686        schema: MZ_CATALOG_SCHEMA,
3687        oid: oid::MV_MZ_SECRETS_OID,
3688        desc: RelationDesc::builder()
3689            .with_column("id", SqlScalarType::String.nullable(false))
3690            .with_column("oid", SqlScalarType::Oid.nullable(false))
3691            .with_column("schema_id", SqlScalarType::String.nullable(false))
3692            .with_column("name", SqlScalarType::String.nullable(false))
3693            .with_column("owner_id", SqlScalarType::String.nullable(false))
3694            .with_column(
3695                "privileges",
3696                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3697            )
3698            .finish(),
3699        column_comments: BTreeMap::from_iter([
3700            ("id", "The unique ID of the secret."),
3701            ("oid", "A PostgreSQL-compatible oid for the secret."),
3702            (
3703                "schema_id",
3704                "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3705            ),
3706            ("name", "The name of the secret."),
3707            (
3708                "owner_id",
3709                "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3710            ),
3711            ("privileges", "The privileges belonging to the secret."),
3712        ]),
3713        sql: "
3714IN CLUSTER mz_catalog_server
3715WITH (
3716    ASSERT NOT NULL id,
3717    ASSERT NOT NULL oid,
3718    ASSERT NOT NULL schema_id,
3719    ASSERT NOT NULL name,
3720    ASSERT NOT NULL owner_id,
3721    ASSERT NOT NULL privileges
3722) AS
3723SELECT
3724    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
3725    (data->'value'->>'oid')::oid AS oid,
3726    mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
3727    data->'value'->>'name' AS name,
3728    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
3729    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
3730FROM mz_internal.mz_catalog_raw
3731WHERE
3732    data->>'kind' = 'Item' AND
3733    mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'type' = 'secret'",
3734        is_retained_metrics_object: false,
3735        access: vec![PUBLIC_SELECT],
3736    }
3737});
3738
3739pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3740    name: "mz_cluster_replicas",
3741    schema: MZ_CATALOG_SCHEMA,
3742    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3743    desc: RelationDesc::builder()
3744        .with_column("id", SqlScalarType::String.nullable(false))
3745        .with_column("name", SqlScalarType::String.nullable(false))
3746        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3747        .with_column("size", SqlScalarType::String.nullable(true))
3748        // `NULL` for un-orchestrated clusters and for replicas where the user
3749        // hasn't specified them.
3750        .with_column("availability_zone", SqlScalarType::String.nullable(true))
3751        .with_column("owner_id", SqlScalarType::String.nullable(false))
3752        .with_column("disk", SqlScalarType::Bool.nullable(true))
3753        .finish(),
3754    column_comments: BTreeMap::from_iter([
3755        ("id", "Materialize's unique ID for the cluster replica."),
3756        ("name", "The name of the cluster replica."),
3757        (
3758            "cluster_id",
3759            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3760        ),
3761        (
3762            "size",
3763            "The cluster replica's size, selected during creation.",
3764        ),
3765        (
3766            "availability_zone",
3767            "The availability zone in which the cluster is running.",
3768        ),
3769        (
3770            "owner_id",
3771            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3772        ),
3773        ("disk", "If the replica has a local disk."),
3774    ]),
3775    is_retained_metrics_object: true,
3776    access: vec![PUBLIC_SELECT],
3777});
3778
3779pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
3780    LazyLock::new(|| BuiltinMaterializedView {
3781        name: "mz_internal_cluster_replicas",
3782        schema: MZ_INTERNAL_SCHEMA,
3783        oid: oid::MV_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3784        desc: RelationDesc::builder()
3785            .with_column("id", SqlScalarType::String.nullable(false))
3786            .with_key(vec![0])
3787            .finish(),
3788        column_comments: BTreeMap::from_iter([(
3789            "id",
3790            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3791        )]),
3792        sql: "
3793IN CLUSTER mz_catalog_server
3794WITH (
3795    ASSERT NOT NULL id
3796) AS
3797SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
3798FROM mz_internal.mz_catalog_raw
3799WHERE
3800    data->>'kind' = 'ClusterReplica' AND
3801    (data->'value'->'config'->'location'->'Managed'->>'internal')::bool = true",
3802        is_retained_metrics_object: false,
3803        access: vec![PUBLIC_SELECT],
3804    });
3805
3806pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
3807    LazyLock::new(|| BuiltinMaterializedView {
3808        name: "mz_pending_cluster_replicas",
3809        schema: MZ_INTERNAL_SCHEMA,
3810        oid: oid::MV_MZ_PENDING_CLUSTER_REPLICAS_OID,
3811        desc: RelationDesc::builder()
3812            .with_column("id", SqlScalarType::String.nullable(false))
3813            .with_key(vec![0])
3814            .finish(),
3815        column_comments: BTreeMap::from_iter([(
3816            "id",
3817            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3818        )]),
3819        sql: "
3820IN CLUSTER mz_catalog_server
3821WITH (
3822    ASSERT NOT NULL id
3823) AS
3824SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
3825FROM mz_internal.mz_catalog_raw
3826WHERE
3827    data->>'kind' = 'ClusterReplica' AND
3828    (data->'value'->'config'->'location'->'Managed'->>'pending')::bool = true",
3829        is_retained_metrics_object: false,
3830        access: vec![PUBLIC_SELECT],
3831    });
3832
3833pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3834    BuiltinSource {
3835        name: "mz_cluster_replica_status_history",
3836        schema: MZ_INTERNAL_SCHEMA,
3837        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3838        data_source: IntrospectionType::ReplicaStatusHistory.into(),
3839        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3840        column_comments: BTreeMap::from_iter([
3841            ("replica_id", "The ID of a cluster replica."),
3842            ("process_id", "The ID of a process within the replica."),
3843            (
3844                "status",
3845                "The status of the cluster replica: `online` or `offline`.",
3846            ),
3847            (
3848                "reason",
3849                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3850            ),
3851            (
3852                "occurred_at",
3853                "Wall-clock timestamp at which the event occurred.",
3854            ),
3855        ]),
3856        is_retained_metrics_object: false,
3857        access: vec![PUBLIC_SELECT],
3858    }
3859});
3860
3861pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3862    name: "mz_cluster_replica_statuses",
3863    schema: MZ_INTERNAL_SCHEMA,
3864    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
3865    desc: RelationDesc::builder()
3866        .with_column("replica_id", SqlScalarType::String.nullable(false))
3867        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3868        .with_column("status", SqlScalarType::String.nullable(false))
3869        .with_column("reason", SqlScalarType::String.nullable(true))
3870        .with_column(
3871            "updated_at",
3872            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3873        )
3874        .with_key(vec![0, 1])
3875        .finish(),
3876    column_comments: BTreeMap::from_iter([
3877        (
3878            "replica_id",
3879            "Materialize's unique ID for the cluster replica.",
3880        ),
3881        (
3882            "process_id",
3883            "The ID of the process within the cluster replica.",
3884        ),
3885        (
3886            "status",
3887            "The status of the cluster replica: `online` or `offline`.",
3888        ),
3889        (
3890            "reason",
3891            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3892        ),
3893        (
3894            "updated_at",
3895            "The time at which the status was last updated.",
3896        ),
3897    ]),
3898    sql: "
3899SELECT
3900    DISTINCT ON (replica_id, process_id)
3901    replica_id,
3902    process_id,
3903    status,
3904    reason,
3905    occurred_at as updated_at
3906FROM mz_internal.mz_cluster_replica_status_history
3907JOIN mz_cluster_replicas r ON r.id = replica_id
3908ORDER BY replica_id, process_id, occurred_at DESC",
3909    access: vec![PUBLIC_SELECT],
3910});
3911
3912pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3913    name: "mz_cluster_replica_sizes",
3914    schema: MZ_CATALOG_SCHEMA,
3915    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3916    desc: RelationDesc::builder()
3917        .with_column("size", SqlScalarType::String.nullable(false))
3918        .with_column("processes", SqlScalarType::UInt64.nullable(false))
3919        .with_column("workers", SqlScalarType::UInt64.nullable(false))
3920        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(false))
3921        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(false))
3922        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3923        .with_column(
3924            "credits_per_hour",
3925            SqlScalarType::Numeric { max_scale: None }.nullable(false),
3926        )
3927        .finish(),
3928    column_comments: BTreeMap::from_iter([
3929        ("size", "The human-readable replica size."),
3930        ("processes", "The number of processes in the replica."),
3931        (
3932            "workers",
3933            "The number of Timely Dataflow workers per process.",
3934        ),
3935        (
3936            "cpu_nano_cores",
3937            "The CPU allocation per process, in billionths of a vCPU core.",
3938        ),
3939        (
3940            "memory_bytes",
3941            "The RAM allocation per process, in billionths of a vCPU core.",
3942        ),
3943        ("disk_bytes", "The disk allocation per process."),
3944        (
3945            "credits_per_hour",
3946            "The number of compute credits consumed per hour.",
3947        ),
3948    ]),
3949    is_retained_metrics_object: true,
3950    access: vec![PUBLIC_SELECT],
3951});
3952
3953pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3954    name: "mz_audit_events",
3955    schema: MZ_CATALOG_SCHEMA,
3956    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
3957    desc: RelationDesc::builder()
3958        .with_column("id", SqlScalarType::UInt64.nullable(false))
3959        .with_column("event_type", SqlScalarType::String.nullable(false))
3960        .with_column("object_type", SqlScalarType::String.nullable(false))
3961        .with_column("details", SqlScalarType::Jsonb.nullable(false))
3962        .with_column("user", SqlScalarType::String.nullable(true))
3963        .with_column(
3964            "occurred_at",
3965            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3966        )
3967        .with_key(vec![0])
3968        .finish(),
3969    column_comments: BTreeMap::from_iter([
3970        (
3971            "id",
3972            "Materialize's unique, monotonically increasing ID for the event.",
3973        ),
3974        (
3975            "event_type",
3976            "The type of the event: `create`, `drop`, or `alter`.",
3977        ),
3978        (
3979            "object_type",
3980            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
3981        ),
3982        (
3983            "details",
3984            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
3985        ),
3986        (
3987            "user",
3988            "The user who triggered the event, or `NULL` if triggered by the system.",
3989        ),
3990        (
3991            "occurred_at",
3992            "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.",
3993        ),
3994    ]),
3995    is_retained_metrics_object: false,
3996    access: vec![PUBLIC_SELECT],
3997});
3998
3999pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4000    name: "mz_source_status_history",
4001    schema: MZ_INTERNAL_SCHEMA,
4002    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
4003    data_source: IntrospectionType::SourceStatusHistory.into(),
4004    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
4005    column_comments: BTreeMap::from_iter([
4006        (
4007            "occurred_at",
4008            "Wall-clock timestamp of the source status change.",
4009        ),
4010        (
4011            "source_id",
4012            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4013        ),
4014        (
4015            "status",
4016            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4017        ),
4018        (
4019            "error",
4020            "If the source is in an error state, the error message.",
4021        ),
4022        (
4023            "details",
4024            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4025        ),
4026        (
4027            "replica_id",
4028            "The ID of the replica that an instance of a source is running on.",
4029        ),
4030    ]),
4031    is_retained_metrics_object: false,
4032    access: vec![PUBLIC_SELECT],
4033});
4034
4035pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
4036    || BuiltinSource {
4037        name: "mz_aws_privatelink_connection_status_history",
4038        schema: MZ_INTERNAL_SCHEMA,
4039        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
4040        data_source: DataSourceDesc::Introspection(
4041            IntrospectionType::PrivatelinkConnectionStatusHistory,
4042        ),
4043        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
4044        column_comments: BTreeMap::from_iter([
4045            ("occurred_at", "Wall-clock timestamp of the status change."),
4046            (
4047                "connection_id",
4048                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
4049            ),
4050            (
4051                "status",
4052                "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`.",
4053            ),
4054        ]),
4055        is_retained_metrics_object: false,
4056        access: vec![PUBLIC_SELECT],
4057    },
4058);
4059
4060pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| {
4061    BuiltinView {
4062        name: "mz_aws_privatelink_connection_statuses",
4063        schema: MZ_INTERNAL_SCHEMA,
4064        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
4065        desc: RelationDesc::builder()
4066            .with_column("id", SqlScalarType::String.nullable(false))
4067            .with_column("name", SqlScalarType::String.nullable(false))
4068            .with_column(
4069                "last_status_change_at",
4070                SqlScalarType::TimestampTz { precision: None }.nullable(true),
4071            )
4072            .with_column("status", SqlScalarType::String.nullable(true))
4073            .with_key(vec![0])
4074            .finish(),
4075        column_comments: BTreeMap::from_iter([
4076            (
4077                "id",
4078                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
4079            ),
4080            ("name", "The name of the connection."),
4081            (
4082                "last_status_change_at",
4083                "Wall-clock timestamp of the connection status change.",
4084            ),
4085            (
4086                "status",
4087                "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`.",
4088            ),
4089        ]),
4090        sql: "
4091    WITH statuses_w_last_status AS (
4092        SELECT
4093            connection_id,
4094            occurred_at,
4095            status,
4096            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
4097        FROM mz_internal.mz_aws_privatelink_connection_status_history
4098    ),
4099    latest_events AS (
4100        -- Only take the most recent transition for each ID
4101        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
4102        FROM statuses_w_last_status
4103        -- Only keep first status transitions
4104        WHERE status <> last_status OR last_status IS NULL
4105        ORDER BY connection_id, occurred_at DESC
4106    )
4107    SELECT
4108        conns.id,
4109        name,
4110        occurred_at as last_status_change_at,
4111        status
4112    FROM latest_events
4113    JOIN mz_catalog.mz_connections AS conns
4114    ON conns.id = latest_events.connection_id",
4115        access: vec![PUBLIC_SELECT],
4116    }
4117});
4118
4119pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
4120    LazyLock::new(|| BuiltinSource {
4121        name: "mz_statement_execution_history",
4122        schema: MZ_INTERNAL_SCHEMA,
4123        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
4124        data_source: IntrospectionType::StatementExecutionHistory.into(),
4125        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
4126        column_comments: BTreeMap::new(),
4127        is_retained_metrics_object: false,
4128        access: vec![MONITOR_SELECT],
4129    });
4130
4131pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4132    BuiltinView {
4133    name: "mz_statement_execution_history_redacted",
4134    schema: MZ_INTERNAL_SCHEMA,
4135    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
4136    // everything but `params` and `error_message`
4137    desc: RelationDesc::builder()
4138        .with_column("id", SqlScalarType::Uuid.nullable(false))
4139        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4140        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4141        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4142        .with_column("application_name", SqlScalarType::String.nullable(false))
4143        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4144        .with_column("database_name", SqlScalarType::String.nullable(false))
4145        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4146        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4147        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4148        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4149        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4150        .with_column("mz_version", SqlScalarType::String.nullable(false))
4151        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4152        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4153        .with_column("finished_status", SqlScalarType::String.nullable(true))
4154        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4155        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4156        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4157        .finish(),
4158    column_comments: BTreeMap::new(),
4159    sql: "
4160SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
4161cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
4162transient_index_id, mz_version, began_at, finished_at, finished_status,
4163result_size, rows_returned, execution_strategy
4164FROM mz_internal.mz_statement_execution_history",
4165    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
4166}
4167});
4168
4169pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
4170    LazyLock::new(|| BuiltinSource {
4171        name: "mz_prepared_statement_history",
4172        schema: MZ_INTERNAL_SCHEMA,
4173        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
4174        data_source: IntrospectionType::PreparedStatementHistory.into(),
4175        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
4176        column_comments: BTreeMap::new(),
4177        is_retained_metrics_object: false,
4178        access: vec![
4179            SUPPORT_SELECT,
4180            ANALYTICS_SELECT,
4181            MONITOR_REDACTED_SELECT,
4182            MONITOR_SELECT,
4183        ],
4184    });
4185
4186pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4187    name: "mz_sql_text",
4188    schema: MZ_INTERNAL_SCHEMA,
4189    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
4190    desc: MZ_SQL_TEXT_DESC.clone(),
4191    data_source: IntrospectionType::SqlText.into(),
4192    column_comments: BTreeMap::new(),
4193    is_retained_metrics_object: false,
4194    access: vec![MONITOR_SELECT],
4195});
4196
4197pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4198    name: "mz_sql_text_redacted",
4199    schema: MZ_INTERNAL_SCHEMA,
4200    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
4201    desc: RelationDesc::builder()
4202        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4203        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4204        .finish(),
4205    column_comments: BTreeMap::new(),
4206    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
4207    access: vec![
4208        MONITOR_SELECT,
4209        MONITOR_REDACTED_SELECT,
4210        SUPPORT_SELECT,
4211        ANALYTICS_SELECT,
4212    ],
4213});
4214
4215pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
4216    BuiltinView {
4217        name: "mz_recent_sql_text",
4218        schema: MZ_INTERNAL_SCHEMA,
4219        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
4220        // This should always be 1 day more than the interval in
4221        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
4222        // is rounded down to the nearest day.  Thus something that actually happened three days ago
4223        // could have a `prepared day` anywhere from 3 to 4 days back.
4224        desc: RelationDesc::builder()
4225            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4226            .with_column("sql", SqlScalarType::String.nullable(false))
4227            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4228            .with_key(vec![0, 1, 2])
4229            .finish(),
4230        column_comments: BTreeMap::new(),
4231        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
4232        access: vec![MONITOR_SELECT],
4233    }
4234});
4235
4236pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4237    name: "mz_recent_sql_text_redacted",
4238    schema: MZ_INTERNAL_SCHEMA,
4239    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
4240    desc: RelationDesc::builder()
4241        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4242        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4243        .finish(),
4244    column_comments: BTreeMap::new(),
4245    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
4246    access: vec![
4247        MONITOR_SELECT,
4248        MONITOR_REDACTED_SELECT,
4249        SUPPORT_SELECT,
4250        ANALYTICS_SELECT,
4251    ],
4252});
4253
4254pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
4255    name: "mz_recent_sql_text_ind",
4256    schema: MZ_INTERNAL_SCHEMA,
4257    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
4258    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4259    is_retained_metrics_object: false,
4260});
4261
4262pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4263    name: "mz_session_history",
4264    schema: MZ_INTERNAL_SCHEMA,
4265    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4266    data_source: IntrospectionType::SessionHistory.into(),
4267    desc: MZ_SESSION_HISTORY_DESC.clone(),
4268    column_comments: BTreeMap::from_iter([
4269        (
4270            "session_id",
4271            "The globally unique ID of the session. Corresponds to `mz_sessions.id`.",
4272        ),
4273        (
4274            "connected_at",
4275            "The time at which the session was established.",
4276        ),
4277        (
4278            "initial_application_name",
4279            "The `application_name` session metadata field.",
4280        ),
4281        (
4282            "authenticated_user",
4283            "The name of the user for which the session was established.",
4284        ),
4285    ]),
4286    is_retained_metrics_object: false,
4287    access: vec![PUBLIC_SELECT],
4288});
4289
4290pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4291    BuiltinView {
4292        name: "mz_activity_log_thinned",
4293        schema: MZ_INTERNAL_SCHEMA,
4294        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
4295        desc: RelationDesc::builder()
4296            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4297            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4298            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4299            .with_column("application_name", SqlScalarType::String.nullable(false))
4300            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4301            .with_column("database_name", SqlScalarType::String.nullable(false))
4302            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4303            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4304            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4305            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4306            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4307            .with_column("mz_version", SqlScalarType::String.nullable(false))
4308            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4309            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4310            .with_column("finished_status", SqlScalarType::String.nullable(true))
4311            .with_column("error_message", SqlScalarType::String.nullable(true))
4312            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4313            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4314            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4315            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4316            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4317            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4318            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4319            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4320            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4321            .with_column("statement_type", SqlScalarType::String.nullable(true))
4322            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4323            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4324            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4325            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4326            .finish(),
4327        column_comments: BTreeMap::new(),
4328        sql: "
4329SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
4330transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
4331error_message, result_size, rows_returned, execution_strategy, transaction_id,
4332mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
4333mpsh.session_id, prepared_at, statement_type, throttled_count,
4334connected_at, initial_application_name, authenticated_user
4335FROM mz_internal.mz_statement_execution_history mseh,
4336     mz_internal.mz_prepared_statement_history mpsh,
4337     mz_internal.mz_session_history msh
4338WHERE mseh.prepared_statement_id = mpsh.id
4339AND mpsh.session_id = msh.session_id",
4340        access: vec![MONITOR_SELECT],
4341    }
4342});
4343
4344pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4345    BuiltinView {
4346        name: "mz_recent_activity_log_thinned",
4347        schema: MZ_INTERNAL_SCHEMA,
4348        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
4349        desc: RelationDesc::builder()
4350            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4351            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4352            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4353            .with_column("application_name", SqlScalarType::String.nullable(false))
4354            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4355            .with_column("database_name", SqlScalarType::String.nullable(false))
4356            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4357            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4358            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4359            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4360            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4361            .with_column("mz_version", SqlScalarType::String.nullable(false))
4362            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4363            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4364            .with_column("finished_status", SqlScalarType::String.nullable(true))
4365            .with_column("error_message", SqlScalarType::String.nullable(true))
4366            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4367            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4368            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4369            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4370            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4371            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4372            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4373            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4374            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4375            .with_column("statement_type", SqlScalarType::String.nullable(true))
4376            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4377            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4378            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4379            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4380            .finish(),
4381        column_comments: BTreeMap::new(),
4382        // We use a temporal window of 2 days rather than 1 day for `mz_session_history`'s `connected_at` since a statement execution at
4383        // 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.
4384        sql:
4385        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
4386AND began_at + INTERVAL '1 day' > mz_now() AND connected_at + INTERVAL '2 days' > mz_now()",
4387        access: vec![MONITOR_SELECT],
4388    }
4389});
4390
4391pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4392    name: "mz_recent_activity_log",
4393    schema: MZ_INTERNAL_SCHEMA,
4394    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
4395    desc: RelationDesc::builder()
4396        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4397        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4398        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4399        .with_column("application_name", SqlScalarType::String.nullable(false))
4400        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4401        .with_column("database_name", SqlScalarType::String.nullable(false))
4402        .with_column(
4403            "search_path",
4404            SqlScalarType::List {
4405                element_type: Box::new(SqlScalarType::String),
4406                custom_id: None,
4407            }
4408            .nullable(false),
4409        )
4410        .with_column(
4411            "transaction_isolation",
4412            SqlScalarType::String.nullable(false),
4413        )
4414        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4415        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4416        .with_column(
4417            "params",
4418            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
4419        )
4420        .with_column("mz_version", SqlScalarType::String.nullable(false))
4421        .with_column(
4422            "began_at",
4423            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4424        )
4425        .with_column(
4426            "finished_at",
4427            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4428        )
4429        .with_column("finished_status", SqlScalarType::String.nullable(true))
4430        .with_column("error_message", SqlScalarType::String.nullable(true))
4431        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4432        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4433        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4434        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4435        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4436        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4437        .with_column(
4438            "prepared_statement_name",
4439            SqlScalarType::String.nullable(false),
4440        )
4441        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4442        .with_column(
4443            "prepared_at",
4444            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4445        )
4446        .with_column("statement_type", SqlScalarType::String.nullable(true))
4447        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4448        .with_column(
4449            "connected_at",
4450            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4451        )
4452        .with_column(
4453            "initial_application_name",
4454            SqlScalarType::String.nullable(false),
4455        )
4456        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4457        .with_column("sql", SqlScalarType::String.nullable(false))
4458        .finish(),
4459    column_comments: BTreeMap::from_iter([
4460        (
4461            "execution_id",
4462            "An ID that is unique for each executed statement.",
4463        ),
4464        (
4465            "sample_rate",
4466            "The actual rate at which the statement was sampled.",
4467        ),
4468        (
4469            "cluster_id",
4470            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
4471        ),
4472        (
4473            "application_name",
4474            "The value of the `application_name` configuration parameter at execution time.",
4475        ),
4476        (
4477            "cluster_name",
4478            "The name of the cluster with ID `cluster_id` at execution time.",
4479        ),
4480        (
4481            "database_name",
4482            "The value of the `database` configuration parameter at execution time.",
4483        ),
4484        (
4485            "search_path",
4486            "The value of the `search_path` configuration parameter at execution time.",
4487        ),
4488        (
4489            "transaction_isolation",
4490            "The value of the `transaction_isolation` configuration parameter at execution time.",
4491        ),
4492        (
4493            "execution_timestamp",
4494            "The logical timestamp at which execution was scheduled.",
4495        ),
4496        (
4497            "transient_index_id",
4498            "The internal index of the compute dataflow created for the query, if any.",
4499        ),
4500        (
4501            "params",
4502            "The parameters with which the statement was executed.",
4503        ),
4504        (
4505            "mz_version",
4506            "The version of Materialize that was running when the statement was executed.",
4507        ),
4508        (
4509            "began_at",
4510            "The wall-clock time at which the statement began executing.",
4511        ),
4512        (
4513            "finished_at",
4514            "The wall-clock time at which the statement finished executing.",
4515        ),
4516        (
4517            "finished_status",
4518            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). `aborted` means that Materialize exited before the statement finished executing.",
4519        ),
4520        (
4521            "error_message",
4522            "The error message, if the statement failed.",
4523        ),
4524        (
4525            "result_size",
4526            "The size in bytes of the result, for statements that return rows.",
4527        ),
4528        (
4529            "rows_returned",
4530            "The number of rows returned, for statements that return rows.",
4531        ),
4532        (
4533            "execution_strategy",
4534            "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.",
4535        ),
4536        (
4537            "transaction_id",
4538            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
4539        ),
4540        (
4541            "prepared_statement_id",
4542            "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`).",
4543        ),
4544        (
4545            "sql_hash",
4546            "An opaque value uniquely identifying the text of the query.",
4547        ),
4548        (
4549            "prepared_statement_name",
4550            "The name given by the client library to the prepared statement.",
4551        ),
4552        (
4553            "session_id",
4554            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
4555        ),
4556        (
4557            "prepared_at",
4558            "The time at which the statement was prepared.",
4559        ),
4560        (
4561            "statement_type",
4562            "The _type_ of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
4563        ),
4564        (
4565            "throttled_count",
4566            "The number of statement executions that were dropped due to throttling before the current one was seen. If you have a very high volume of queries and need to log them without throttling, contact our team.",
4567        ),
4568        (
4569            "connected_at",
4570            "The time at which the session was established.",
4571        ),
4572        (
4573            "initial_application_name",
4574            "The initial value of `application_name` at the beginning of the session.",
4575        ),
4576        (
4577            "authenticated_user",
4578            "The name of the user for which the session was established.",
4579        ),
4580        ("sql", "The SQL text of the statement."),
4581    ]),
4582    sql: "SELECT mralt.*, mrst.sql
4583FROM mz_internal.mz_recent_activity_log_thinned mralt,
4584     mz_internal.mz_recent_sql_text mrst
4585WHERE mralt.sql_hash = mrst.sql_hash",
4586    access: vec![MONITOR_SELECT],
4587});
4588
4589pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4590    BuiltinView {
4591    name: "mz_recent_activity_log_redacted",
4592    schema: MZ_INTERNAL_SCHEMA,
4593    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
4594    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
4595    desc: RelationDesc::builder()
4596        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4597        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4598        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4599        .with_column("application_name", SqlScalarType::String.nullable(false))
4600        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4601        .with_column("database_name", SqlScalarType::String.nullable(false))
4602        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4603        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4604        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4605        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4606        .with_column("mz_version", SqlScalarType::String.nullable(false))
4607        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4608        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4609        .with_column("finished_status", SqlScalarType::String.nullable(true))
4610        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4611        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4612        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4613        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4614        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4615        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4616        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4617        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4618        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4619        .with_column("statement_type", SqlScalarType::String.nullable(true))
4620        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4621        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4622        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4623        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4624        .finish(),
4625    column_comments: BTreeMap::new(),
4626    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4627    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4628    mralt.transient_index_id, mralt.mz_version, mralt.began_at, mralt.finished_at,
4629    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4630    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4631    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4632    mralt.initial_application_name, mralt.authenticated_user,
4633    mrst.redacted_sql
4634FROM mz_internal.mz_recent_activity_log_thinned mralt,
4635     mz_internal.mz_recent_sql_text mrst
4636WHERE mralt.sql_hash = mrst.sql_hash",
4637    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4638}
4639});
4640
4641pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4642    BuiltinSource {
4643        name: "mz_statement_lifecycle_history",
4644        schema: MZ_INTERNAL_SCHEMA,
4645        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4646        desc: RelationDesc::builder()
4647            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
4648            .with_column("event_type", SqlScalarType::String.nullable(false))
4649            .with_column(
4650                "occurred_at",
4651                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4652            )
4653            .finish(),
4654        data_source: IntrospectionType::StatementLifecycleHistory.into(),
4655        column_comments: BTreeMap::from_iter([
4656            (
4657                "statement_id",
4658                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4659            ),
4660            (
4661                "event_type",
4662                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4663            ),
4664            ("occurred_at", "The time at which the event took place."),
4665        ]),
4666        is_retained_metrics_object: false,
4667        // TODO[btv]: Maybe this should be public instead of
4668        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4669        // change, we probably don't need to worry about it now.
4670        access: vec![
4671            SUPPORT_SELECT,
4672            ANALYTICS_SELECT,
4673            MONITOR_REDACTED_SELECT,
4674            MONITOR_SELECT,
4675        ],
4676    }
4677});
4678
4679pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4680    name: "mz_source_statuses",
4681    schema: MZ_INTERNAL_SCHEMA,
4682    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4683    desc: RelationDesc::builder()
4684        .with_column("id", SqlScalarType::String.nullable(false))
4685        .with_column("name", SqlScalarType::String.nullable(false))
4686        .with_column("type", SqlScalarType::String.nullable(false))
4687        .with_column(
4688            "last_status_change_at",
4689            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4690        )
4691        .with_column("status", SqlScalarType::String.nullable(false))
4692        .with_column("error", SqlScalarType::String.nullable(true))
4693        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4694        .finish(),
4695    column_comments: BTreeMap::from_iter([
4696        (
4697            "id",
4698            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4699        ),
4700        ("name", "The name of the source."),
4701        ("type", "The type of the source."),
4702        (
4703            "last_status_change_at",
4704            "Wall-clock timestamp of the source status change.",
4705        ),
4706        (
4707            "status",
4708            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4709        ),
4710        (
4711            "error",
4712            "If the source is in an error state, the error message.",
4713        ),
4714        (
4715            "details",
4716            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4717        ),
4718    ]),
4719    sql: "
4720    WITH
4721    -- The status history contains per-replica events and source-global events.
4722    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4723    -- we can treat them uniformly below.
4724    uniform_status_history AS
4725    (
4726        SELECT
4727            s.source_id,
4728            COALESCE(s.replica_id, '<source>') as replica_id,
4729            s.occurred_at,
4730            s.status,
4731            s.error,
4732            s.details
4733        FROM mz_internal.mz_source_status_history s
4734    ),
4735    -- For getting the latest events, we first determine the latest per-replica
4736    -- events here and then apply precedence rules below.
4737    latest_per_replica_events AS
4738    (
4739        SELECT DISTINCT ON (source_id, replica_id)
4740            occurred_at, source_id, replica_id, status, error, details
4741        FROM uniform_status_history
4742        ORDER BY source_id, replica_id, occurred_at DESC
4743    ),
4744    -- We have a precedence list that determines the overall status in case
4745    -- there is differing per-replica (including source-global) statuses. If
4746    -- there is no 'dropped' status, and any replica reports 'running', the
4747    -- overall status is 'running' even if there might be some replica that has
4748    -- errors or is paused.
4749    latest_events AS
4750    (
4751       SELECT DISTINCT ON (source_id)
4752            source_id,
4753            occurred_at,
4754            status,
4755            error,
4756            details
4757        FROM latest_per_replica_events
4758        ORDER BY source_id, CASE status
4759                    WHEN 'dropped' THEN 1
4760                    WHEN 'running' THEN 2
4761                    WHEN 'stalled' THEN 3
4762                    WHEN 'starting' THEN 4
4763                    WHEN 'paused' THEN 5
4764                    WHEN 'ceased' THEN 6
4765                    ELSE 7  -- For any other status values
4766                END
4767    ),
4768    -- Determine which sources are subsources and which are parent sources
4769    subsources AS
4770    (
4771        SELECT subsources.id AS self, sources.id AS parent
4772        FROM
4773            mz_catalog.mz_sources AS subsources
4774                JOIN
4775                    mz_internal.mz_object_dependencies AS deps
4776                    ON subsources.id = deps.object_id
4777                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4778    ),
4779    -- Determine which sources are source tables
4780    tables AS
4781    (
4782        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4783        FROM mz_catalog.mz_tables AS tables
4784        WHERE tables.source_id IS NOT NULL
4785    ),
4786    -- Determine which collection's ID to use for the status
4787    id_of_status_to_use AS
4788    (
4789        SELECT
4790            self_events.source_id,
4791            -- If self not errored, but parent is, use parent; else self
4792            CASE
4793                WHEN
4794                    self_events.status <> 'ceased' AND
4795                    parent_events.status = 'stalled'
4796                THEN parent_events.source_id
4797                ELSE self_events.source_id
4798            END AS id_to_use
4799        FROM
4800            latest_events AS self_events
4801                LEFT JOIN subsources ON self_events.source_id = subsources.self
4802                LEFT JOIN tables ON self_events.source_id = tables.self
4803                LEFT JOIN
4804                    latest_events AS parent_events
4805                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4806    ),
4807    -- Swap out events for the ID of the event we plan to use instead
4808    latest_events_to_use AS
4809    (
4810        SELECT occurred_at, s.source_id, status, error, details
4811        FROM
4812            id_of_status_to_use AS s
4813                JOIN latest_events AS e ON e.source_id = s.id_to_use
4814    ),
4815    combined AS (
4816        SELECT
4817            mz_sources.id,
4818            mz_sources.name,
4819            mz_sources.type,
4820            occurred_at,
4821            status,
4822            error,
4823            details
4824        FROM
4825            mz_catalog.mz_sources
4826            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4827        UNION ALL
4828        SELECT
4829            tables.self AS id,
4830            tables.name,
4831            'table' AS type,
4832            occurred_at,
4833            status,
4834            error,
4835            details
4836        FROM
4837            tables
4838            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4839    )
4840SELECT
4841    id,
4842    name,
4843    type,
4844    occurred_at AS last_status_change_at,
4845    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4846    CASE
4847        WHEN
4848            type = 'webhook' OR
4849            type = 'progress'
4850        THEN 'running'
4851        ELSE COALESCE(status, 'created')
4852    END AS status,
4853    error,
4854    details
4855FROM combined
4856WHERE id NOT LIKE 's%';",
4857    access: vec![PUBLIC_SELECT],
4858});
4859
4860pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4861    name: "mz_sink_status_history",
4862    schema: MZ_INTERNAL_SCHEMA,
4863    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4864    data_source: IntrospectionType::SinkStatusHistory.into(),
4865    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4866    column_comments: BTreeMap::from_iter([
4867        (
4868            "occurred_at",
4869            "Wall-clock timestamp of the sink status change.",
4870        ),
4871        (
4872            "sink_id",
4873            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4874        ),
4875        (
4876            "status",
4877            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4878        ),
4879        (
4880            "error",
4881            "If the sink is in an error state, the error message.",
4882        ),
4883        (
4884            "details",
4885            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4886        ),
4887        (
4888            "replica_id",
4889            "The ID of the replica that an instance of a sink is running on.",
4890        ),
4891    ]),
4892    is_retained_metrics_object: false,
4893    access: vec![PUBLIC_SELECT],
4894});
4895
4896pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4897    name: "mz_sink_statuses",
4898    schema: MZ_INTERNAL_SCHEMA,
4899    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4900    desc: RelationDesc::builder()
4901        .with_column("id", SqlScalarType::String.nullable(false))
4902        .with_column("name", SqlScalarType::String.nullable(false))
4903        .with_column("type", SqlScalarType::String.nullable(false))
4904        .with_column(
4905            "last_status_change_at",
4906            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4907        )
4908        .with_column("status", SqlScalarType::String.nullable(false))
4909        .with_column("error", SqlScalarType::String.nullable(true))
4910        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4911        .finish(),
4912    column_comments: BTreeMap::from_iter([
4913        (
4914            "id",
4915            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4916        ),
4917        ("name", "The name of the sink."),
4918        ("type", "The type of the sink."),
4919        (
4920            "last_status_change_at",
4921            "Wall-clock timestamp of the sink status change.",
4922        ),
4923        (
4924            "status",
4925            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4926        ),
4927        (
4928            "error",
4929            "If the sink is in an error state, the error message.",
4930        ),
4931        (
4932            "details",
4933            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4934        ),
4935    ]),
4936    sql: "
4937WITH
4938-- The status history contains per-replica events and sink-global events.
4939-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
4940-- we can treat them uniformly below.
4941uniform_status_history AS
4942(
4943    SELECT
4944        s.sink_id,
4945        COALESCE(s.replica_id, '<sink>') as replica_id,
4946        s.occurred_at,
4947        s.status,
4948        s.error,
4949        s.details
4950    FROM mz_internal.mz_sink_status_history s
4951),
4952-- For getting the latest events, we first determine the latest per-replica
4953-- events here and then apply precedence rules below.
4954latest_per_replica_events AS
4955(
4956    SELECT DISTINCT ON (sink_id, replica_id)
4957        occurred_at, sink_id, replica_id, status, error, details
4958    FROM uniform_status_history
4959    ORDER BY sink_id, replica_id, occurred_at DESC
4960),
4961-- We have a precedence list that determines the overall status in case
4962-- there is differing per-replica (including sink-global) statuses. If
4963-- there is no 'dropped' status, and any replica reports 'running', the
4964-- overall status is 'running' even if there might be some replica that has
4965-- errors or is paused.
4966latest_events AS
4967(
4968    SELECT DISTINCT ON (sink_id)
4969        sink_id,
4970        occurred_at,
4971        status,
4972        error,
4973        details
4974    FROM latest_per_replica_events
4975    ORDER BY sink_id, CASE status
4976                WHEN 'dropped' THEN 1
4977                WHEN 'running' THEN 2
4978                WHEN 'stalled' THEN 3
4979                WHEN 'starting' THEN 4
4980                WHEN 'paused' THEN 5
4981                WHEN 'ceased' THEN 6
4982                ELSE 7  -- For any other status values
4983            END
4984)
4985SELECT
4986    mz_sinks.id,
4987    name,
4988    mz_sinks.type,
4989    occurred_at as last_status_change_at,
4990    coalesce(status, 'created') as status,
4991    error,
4992    details
4993FROM mz_catalog.mz_sinks
4994LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
4995WHERE
4996    -- This is a convenient way to filter out system sinks, like the status_history table itself.
4997    mz_sinks.id NOT LIKE 's%'",
4998    access: vec![PUBLIC_SELECT],
4999});
5000
5001pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
5002    LazyLock::new(|| SystemObjectDescription {
5003        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
5004        object_type: CatalogItemType::Table,
5005        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
5006    });
5007
5008pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5009    name: "mz_storage_usage_by_shard",
5010    schema: MZ_INTERNAL_SCHEMA,
5011    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
5012    desc: RelationDesc::builder()
5013        .with_column("id", SqlScalarType::UInt64.nullable(false))
5014        .with_column("shard_id", SqlScalarType::String.nullable(true))
5015        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5016        .with_column(
5017            "collection_timestamp",
5018            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5019        )
5020        .finish(),
5021    column_comments: BTreeMap::new(),
5022    is_retained_metrics_object: false,
5023    access: vec![PUBLIC_SELECT],
5024});
5025
5026pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5027    name: "mz_egress_ips",
5028    schema: MZ_CATALOG_SCHEMA,
5029    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
5030    desc: RelationDesc::builder()
5031        .with_column("egress_ip", SqlScalarType::String.nullable(false))
5032        .with_column("prefix_length", SqlScalarType::Int32.nullable(false))
5033        .with_column("cidr", SqlScalarType::String.nullable(false))
5034        .finish(),
5035    column_comments: BTreeMap::from_iter([
5036        ("egress_ip", "The start of the range of IP addresses."),
5037        (
5038            "prefix_length",
5039            "The number of leading bits in the CIDR netmask.",
5040        ),
5041        ("cidr", "The CIDR representation."),
5042    ]),
5043    is_retained_metrics_object: false,
5044    access: vec![PUBLIC_SELECT],
5045});
5046
5047pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
5048    LazyLock::new(|| BuiltinTable {
5049        name: "mz_aws_privatelink_connections",
5050        schema: MZ_CATALOG_SCHEMA,
5051        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
5052        desc: RelationDesc::builder()
5053            .with_column("id", SqlScalarType::String.nullable(false))
5054            .with_column("principal", SqlScalarType::String.nullable(false))
5055            .finish(),
5056        column_comments: BTreeMap::from_iter([
5057            ("id", "The ID of the connection."),
5058            (
5059                "principal",
5060                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
5061            ),
5062        ]),
5063        is_retained_metrics_object: false,
5064        access: vec![PUBLIC_SELECT],
5065    });
5066
5067pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5068    name: "mz_aws_connections",
5069    schema: MZ_INTERNAL_SCHEMA,
5070    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
5071    desc: RelationDesc::builder()
5072        .with_column("id", SqlScalarType::String.nullable(false))
5073        .with_column("endpoint", SqlScalarType::String.nullable(true))
5074        .with_column("region", SqlScalarType::String.nullable(true))
5075        .with_column("access_key_id", SqlScalarType::String.nullable(true))
5076        .with_column(
5077            "access_key_id_secret_id",
5078            SqlScalarType::String.nullable(true),
5079        )
5080        .with_column(
5081            "secret_access_key_secret_id",
5082            SqlScalarType::String.nullable(true),
5083        )
5084        .with_column("session_token", SqlScalarType::String.nullable(true))
5085        .with_column(
5086            "session_token_secret_id",
5087            SqlScalarType::String.nullable(true),
5088        )
5089        .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
5090        .with_column(
5091            "assume_role_session_name",
5092            SqlScalarType::String.nullable(true),
5093        )
5094        .with_column("principal", SqlScalarType::String.nullable(true))
5095        .with_column("external_id", SqlScalarType::String.nullable(true))
5096        .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
5097        .finish(),
5098    column_comments: BTreeMap::from_iter([
5099        ("id", "The ID of the connection."),
5100        ("endpoint", "The value of the `ENDPOINT` option, if set."),
5101        ("region", "The value of the `REGION` option, if set."),
5102        (
5103            "access_key_id",
5104            "The value of the `ACCESS KEY ID` option, if provided in line.",
5105        ),
5106        (
5107            "access_key_id_secret_id",
5108            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
5109        ),
5110        (
5111            "secret_access_key_secret_id",
5112            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
5113        ),
5114        (
5115            "session_token",
5116            "The value of the `SESSION TOKEN` option, if provided in line.",
5117        ),
5118        (
5119            "session_token_secret_id",
5120            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
5121        ),
5122        (
5123            "assume_role_arn",
5124            "The value of the `ASSUME ROLE ARN` option, if set.",
5125        ),
5126        (
5127            "assume_role_session_name",
5128            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
5129        ),
5130        (
5131            "principal",
5132            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
5133        ),
5134        (
5135            "external_id",
5136            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
5137        ),
5138        (
5139            "example_trust_policy",
5140            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
5141        ),
5142    ]),
5143    is_retained_metrics_object: false,
5144    access: vec![PUBLIC_SELECT],
5145});
5146
5147pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
5148    LazyLock::new(|| BuiltinSource {
5149        name: "mz_cluster_replica_metrics_history",
5150        schema: MZ_INTERNAL_SCHEMA,
5151        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
5152        data_source: IntrospectionType::ReplicaMetricsHistory.into(),
5153        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
5154        column_comments: BTreeMap::from_iter([
5155            ("replica_id", "The ID of a cluster replica."),
5156            ("process_id", "The ID of a process within the replica."),
5157            (
5158                "cpu_nano_cores",
5159                "Approximate CPU usage, in billionths of a vCPU core.",
5160            ),
5161            ("memory_bytes", "Approximate memory usage, in bytes."),
5162            ("disk_bytes", "Approximate disk usage, in bytes."),
5163            (
5164                "occurred_at",
5165                "Wall-clock timestamp at which the event occurred.",
5166            ),
5167            (
5168                "heap_bytes",
5169                "Approximate heap (RAM + swap) usage, in bytes.",
5170            ),
5171            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
5172        ]),
5173        is_retained_metrics_object: false,
5174        access: vec![PUBLIC_SELECT],
5175    });
5176
5177pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5178    name: "mz_cluster_replica_metrics",
5179    schema: MZ_INTERNAL_SCHEMA,
5180    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
5181    desc: RelationDesc::builder()
5182        .with_column("replica_id", SqlScalarType::String.nullable(false))
5183        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
5184        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
5185        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
5186        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
5187        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
5188        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
5189        .with_key(vec![0, 1])
5190        .finish(),
5191    column_comments: BTreeMap::from_iter([
5192        ("replica_id", "The ID of a cluster replica."),
5193        ("process_id", "The ID of a process within the replica."),
5194        (
5195            "cpu_nano_cores",
5196            "Approximate CPU usage, in billionths of a vCPU core.",
5197        ),
5198        ("memory_bytes", "Approximate RAM usage, in bytes."),
5199        ("disk_bytes", "Approximate disk usage, in bytes."),
5200        (
5201            "heap_bytes",
5202            "Approximate heap (RAM + swap) usage, in bytes.",
5203        ),
5204        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
5205    ]),
5206    sql: "
5207SELECT
5208    DISTINCT ON (replica_id, process_id)
5209    replica_id,
5210    process_id,
5211    cpu_nano_cores,
5212    memory_bytes,
5213    disk_bytes,
5214    heap_bytes,
5215    heap_limit
5216FROM mz_internal.mz_cluster_replica_metrics_history
5217JOIN mz_cluster_replicas r ON r.id = replica_id
5218ORDER BY replica_id, process_id, occurred_at DESC",
5219    access: vec![PUBLIC_SELECT],
5220});
5221
5222pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
5223    LazyLock::new(|| BuiltinSource {
5224        name: "mz_cluster_replica_frontiers",
5225        schema: MZ_CATALOG_SCHEMA,
5226        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
5227        data_source: IntrospectionType::ReplicaFrontiers.into(),
5228        desc: RelationDesc::builder()
5229            .with_column("object_id", SqlScalarType::String.nullable(false))
5230            .with_column("replica_id", SqlScalarType::String.nullable(false))
5231            .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5232            .finish(),
5233        column_comments: BTreeMap::from_iter([
5234            (
5235                "object_id",
5236                "The ID of the source, sink, index, materialized view, or subscription.",
5237            ),
5238            ("replica_id", "The ID of a cluster replica."),
5239            (
5240                "write_frontier",
5241                "The next timestamp at which the output may change.",
5242            ),
5243        ]),
5244        is_retained_metrics_object: false,
5245        access: vec![PUBLIC_SELECT],
5246    });
5247
5248pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
5249    LazyLock::new(|| BuiltinIndex {
5250        name: "mz_cluster_replica_frontiers_ind",
5251        schema: MZ_CATALOG_SCHEMA,
5252        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
5253        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
5254        is_retained_metrics_object: false,
5255    });
5256
5257pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5258    name: "mz_frontiers",
5259    schema: MZ_INTERNAL_SCHEMA,
5260    oid: oid::SOURCE_MZ_FRONTIERS_OID,
5261    data_source: IntrospectionType::Frontiers.into(),
5262    desc: RelationDesc::builder()
5263        .with_column("object_id", SqlScalarType::String.nullable(false))
5264        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
5265        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5266        .finish(),
5267    column_comments: BTreeMap::from_iter([
5268        (
5269            "object_id",
5270            "The ID of the source, sink, table, index, materialized view, or subscription.",
5271        ),
5272        (
5273            "read_frontier",
5274            "The earliest timestamp at which the output is still readable.",
5275        ),
5276        (
5277            "write_frontier",
5278            "The next timestamp at which the output may change.",
5279        ),
5280    ]),
5281    is_retained_metrics_object: false,
5282    access: vec![PUBLIC_SELECT],
5283});
5284
5285/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
5286pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5287    name: "mz_global_frontiers",
5288    schema: MZ_INTERNAL_SCHEMA,
5289    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5290    desc: RelationDesc::builder()
5291        .with_column("object_id", SqlScalarType::String.nullable(false))
5292        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
5293        .finish(),
5294    column_comments: BTreeMap::new(),
5295    sql: "
5296SELECT object_id, write_frontier AS time
5297FROM mz_internal.mz_frontiers
5298WHERE write_frontier IS NOT NULL",
5299    access: vec![PUBLIC_SELECT],
5300});
5301
5302pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5303    name: "mz_wallclock_lag_history",
5304    schema: MZ_INTERNAL_SCHEMA,
5305    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5306    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5307    data_source: IntrospectionType::WallclockLagHistory.into(),
5308    column_comments: BTreeMap::from_iter([
5309        (
5310            "object_id",
5311            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5312        ),
5313        (
5314            "replica_id",
5315            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5316        ),
5317        (
5318            "lag",
5319            "The amount of time the object's write frontier lags behind wallclock time.",
5320        ),
5321        (
5322            "occurred_at",
5323            "Wall-clock timestamp at which the event occurred.",
5324        ),
5325    ]),
5326    is_retained_metrics_object: false,
5327    access: vec![PUBLIC_SELECT],
5328});
5329
5330pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5331    name: "mz_wallclock_global_lag_history",
5332    schema: MZ_INTERNAL_SCHEMA,
5333    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5334    desc: RelationDesc::builder()
5335        .with_column("object_id", SqlScalarType::String.nullable(false))
5336        .with_column("lag", SqlScalarType::Interval.nullable(true))
5337        .with_column(
5338            "occurred_at",
5339            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5340        )
5341        .with_key(vec![0, 2])
5342        .finish(),
5343    column_comments: BTreeMap::from_iter([
5344        (
5345            "object_id",
5346            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5347        ),
5348        (
5349            "lag",
5350            "The minimum wallclock lag observed for the object during the minute.",
5351        ),
5352        (
5353            "occurred_at",
5354            "The minute-aligned timestamp of the observation.",
5355        ),
5356    ]),
5357    sql: "
5358WITH times_binned AS (
5359    SELECT
5360        object_id,
5361        lag,
5362        date_trunc('minute', occurred_at) AS occurred_at
5363    FROM mz_internal.mz_wallclock_lag_history
5364)
5365SELECT
5366    object_id,
5367    min(lag) AS lag,
5368    occurred_at
5369FROM times_binned
5370GROUP BY object_id, occurred_at
5371OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5372    access: vec![PUBLIC_SELECT],
5373});
5374
5375pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| {
5376    BuiltinView {
5377        name: "mz_wallclock_global_lag_recent_history",
5378        schema: MZ_INTERNAL_SCHEMA,
5379        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5380        desc: RelationDesc::builder()
5381            .with_column("object_id", SqlScalarType::String.nullable(false))
5382            .with_column("lag", SqlScalarType::Interval.nullable(true))
5383            .with_column(
5384                "occurred_at",
5385                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5386            )
5387            .with_key(vec![0, 2])
5388            .finish(),
5389        column_comments: BTreeMap::from_iter([
5390            (
5391                "object_id",
5392                "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5393            ),
5394            (
5395                "lag",
5396                "The minimum wallclock lag observed for the object during the minute.",
5397            ),
5398            (
5399                "occurred_at",
5400                "The minute-aligned timestamp of the observation.",
5401            ),
5402        ]),
5403        sql: "
5404SELECT object_id, lag, occurred_at
5405FROM mz_internal.mz_wallclock_global_lag_history
5406WHERE occurred_at + '1 day' > mz_now()",
5407        access: vec![PUBLIC_SELECT],
5408    }
5409});
5410
5411pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5412    name: "mz_wallclock_global_lag",
5413    schema: MZ_INTERNAL_SCHEMA,
5414    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5415    desc: RelationDesc::builder()
5416        .with_column("object_id", SqlScalarType::String.nullable(false))
5417        .with_column("lag", SqlScalarType::Interval.nullable(true))
5418        .with_key(vec![0])
5419        .finish(),
5420    column_comments: BTreeMap::from_iter([
5421        (
5422            "object_id",
5423            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5424        ),
5425        (
5426            "lag",
5427            "The amount of time the object's write frontier lags behind wallclock time.",
5428        ),
5429    ]),
5430    sql: "
5431SELECT DISTINCT ON (object_id) object_id, lag
5432FROM mz_internal.mz_wallclock_global_lag_recent_history
5433WHERE occurred_at + '5 minutes' > mz_now()
5434ORDER BY object_id, occurred_at DESC",
5435    access: vec![PUBLIC_SELECT],
5436});
5437
5438pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5439    LazyLock::new(|| BuiltinSource {
5440        name: "mz_wallclock_global_lag_histogram_raw",
5441        schema: MZ_INTERNAL_SCHEMA,
5442        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5443        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5444        column_comments: BTreeMap::new(),
5445        data_source: IntrospectionType::WallclockLagHistogram.into(),
5446        is_retained_metrics_object: false,
5447        access: vec![PUBLIC_SELECT],
5448    });
5449
5450pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5451    LazyLock::new(|| BuiltinView {
5452        name: "mz_wallclock_global_lag_histogram",
5453        schema: MZ_INTERNAL_SCHEMA,
5454        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5455        desc: RelationDesc::builder()
5456            .with_column(
5457                "period_start",
5458                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5459            )
5460            .with_column(
5461                "period_end",
5462                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5463            )
5464            .with_column("object_id", SqlScalarType::String.nullable(false))
5465            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
5466            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
5467            .with_column("count", SqlScalarType::Int64.nullable(false))
5468            .with_key(vec![0, 1, 2, 3, 4])
5469            .finish(),
5470        column_comments: BTreeMap::new(),
5471        sql: "
5472SELECT *, count(*) AS count
5473FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5474GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5475        access: vec![PUBLIC_SELECT],
5476    });
5477
5478pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5479    BuiltinSource {
5480        name: "mz_materialized_view_refreshes",
5481        schema: MZ_INTERNAL_SCHEMA,
5482        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5483        data_source: DataSourceDesc::Introspection(
5484            IntrospectionType::ComputeMaterializedViewRefreshes,
5485        ),
5486        desc: RelationDesc::builder()
5487            .with_column(
5488                "materialized_view_id",
5489                SqlScalarType::String.nullable(false),
5490            )
5491            .with_column(
5492                "last_completed_refresh",
5493                SqlScalarType::MzTimestamp.nullable(true),
5494            )
5495            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
5496            .finish(),
5497        column_comments: BTreeMap::from_iter([
5498            (
5499                "materialized_view_id",
5500                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5501            ),
5502            (
5503                "last_completed_refresh",
5504                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5505            ),
5506            (
5507                "next_refresh",
5508                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5509            ),
5510        ]),
5511        is_retained_metrics_object: false,
5512        access: vec![PUBLIC_SELECT],
5513    }
5514});
5515
5516pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5517    name: "mz_subscriptions",
5518    schema: MZ_INTERNAL_SCHEMA,
5519    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5520    desc: RelationDesc::builder()
5521        .with_column("id", SqlScalarType::String.nullable(false))
5522        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
5523        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5524        .with_column(
5525            "created_at",
5526            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5527        )
5528        .with_column(
5529            "referenced_object_ids",
5530            SqlScalarType::List {
5531                element_type: Box::new(SqlScalarType::String),
5532                custom_id: None,
5533            }
5534            .nullable(false),
5535        )
5536        .finish(),
5537    column_comments: BTreeMap::from_iter([
5538        ("id", "The ID of the subscription."),
5539        (
5540            "session_id",
5541            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5542        ),
5543        (
5544            "cluster_id",
5545            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5546        ),
5547        (
5548            "created_at",
5549            "The time at which the subscription was created.",
5550        ),
5551        (
5552            "referenced_object_ids",
5553            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5554        ),
5555    ]),
5556    is_retained_metrics_object: false,
5557    access: vec![PUBLIC_SELECT],
5558});
5559
5560pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5561    name: "mz_sessions",
5562    schema: MZ_INTERNAL_SCHEMA,
5563    oid: oid::TABLE_MZ_SESSIONS_OID,
5564    desc: RelationDesc::builder()
5565        .with_column("id", SqlScalarType::Uuid.nullable(false))
5566        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
5567        .with_column("role_id", SqlScalarType::String.nullable(false))
5568        .with_column("client_ip", SqlScalarType::String.nullable(true))
5569        .with_column(
5570            "connected_at",
5571            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5572        )
5573        .finish(),
5574    column_comments: BTreeMap::from_iter([
5575        ("id", "The globally unique ID of the session."),
5576        (
5577            "connection_id",
5578            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5579        ),
5580        (
5581            "role_id",
5582            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5583        ),
5584        (
5585            "client_ip",
5586            "The IP address of the client that initiated the session.",
5587        ),
5588        (
5589            "connected_at",
5590            "The time at which the session connected to the system.",
5591        ),
5592    ]),
5593    is_retained_metrics_object: false,
5594    access: vec![PUBLIC_SELECT],
5595});
5596
5597pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5598    name: "mz_default_privileges",
5599    schema: MZ_CATALOG_SCHEMA,
5600    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5601    desc: RelationDesc::builder()
5602        .with_column("role_id", SqlScalarType::String.nullable(false))
5603        .with_column("database_id", SqlScalarType::String.nullable(true))
5604        .with_column("schema_id", SqlScalarType::String.nullable(true))
5605        .with_column("object_type", SqlScalarType::String.nullable(false))
5606        .with_column("grantee", SqlScalarType::String.nullable(false))
5607        .with_column("privileges", SqlScalarType::String.nullable(false))
5608        .finish(),
5609    column_comments: BTreeMap::from_iter([
5610        (
5611            "role_id",
5612            "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.",
5613        ),
5614        (
5615            "database_id",
5616            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5617        ),
5618        (
5619            "schema_id",
5620            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5621        ),
5622        (
5623            "object_type",
5624            "Privileges described in this row will be granted only on objects of type `object_type`.",
5625        ),
5626        (
5627            "grantee",
5628            "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.",
5629        ),
5630        ("privileges", "The set of privileges that will be granted."),
5631    ]),
5632    is_retained_metrics_object: false,
5633    access: vec![PUBLIC_SELECT],
5634});
5635
5636pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5637    name: "mz_system_privileges",
5638    schema: MZ_CATALOG_SCHEMA,
5639    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5640    desc: RelationDesc::builder()
5641        .with_column("privileges", SqlScalarType::MzAclItem.nullable(false))
5642        .finish(),
5643    column_comments: BTreeMap::from_iter([(
5644        "privileges",
5645        "The privileges belonging to the system.",
5646    )]),
5647    is_retained_metrics_object: false,
5648    access: vec![PUBLIC_SELECT],
5649});
5650
5651pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5652    name: "mz_comments",
5653    schema: MZ_INTERNAL_SCHEMA,
5654    oid: oid::TABLE_MZ_COMMENTS_OID,
5655    desc: RelationDesc::builder()
5656        .with_column("id", SqlScalarType::String.nullable(false))
5657        .with_column("object_type", SqlScalarType::String.nullable(false))
5658        .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
5659        .with_column("comment", SqlScalarType::String.nullable(false))
5660        .finish(),
5661    column_comments: BTreeMap::from_iter([
5662        (
5663            "id",
5664            "The ID of the object. Corresponds to `mz_objects.id`.",
5665        ),
5666        (
5667            "object_type",
5668            "The type of object the comment is associated with.",
5669        ),
5670        (
5671            "object_sub_id",
5672            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5673        ),
5674        ("comment", "The comment itself."),
5675    ]),
5676    is_retained_metrics_object: false,
5677    access: vec![PUBLIC_SELECT],
5678});
5679
5680pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5681    name: "mz_source_references",
5682    schema: MZ_INTERNAL_SCHEMA,
5683    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5684    desc: RelationDesc::builder()
5685        .with_column("source_id", SqlScalarType::String.nullable(false))
5686        .with_column("namespace", SqlScalarType::String.nullable(true))
5687        .with_column("name", SqlScalarType::String.nullable(false))
5688        .with_column(
5689            "updated_at",
5690            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5691        )
5692        .with_column(
5693            "columns",
5694            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5695        )
5696        .finish(),
5697    column_comments: BTreeMap::new(),
5698    is_retained_metrics_object: false,
5699    access: vec![PUBLIC_SELECT],
5700});
5701
5702pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5703    name: "mz_webhook_sources",
5704    schema: MZ_INTERNAL_SCHEMA,
5705    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5706    desc: RelationDesc::builder()
5707        .with_column("id", SqlScalarType::String.nullable(false))
5708        .with_column("name", SqlScalarType::String.nullable(false))
5709        .with_column("url", SqlScalarType::String.nullable(false))
5710        .finish(),
5711    column_comments: BTreeMap::from_iter([
5712        (
5713            "id",
5714            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5715        ),
5716        ("name", "The name of the webhook source."),
5717        (
5718            "url",
5719            "The URL which can be used to send events to the source.",
5720        ),
5721    ]),
5722    is_retained_metrics_object: false,
5723    access: vec![PUBLIC_SELECT],
5724});
5725
5726pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5727    BuiltinTable {
5728        name: "mz_history_retention_strategies",
5729        schema: MZ_INTERNAL_SCHEMA,
5730        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5731        desc: RelationDesc::builder()
5732            .with_column("id", SqlScalarType::String.nullable(false))
5733            .with_column("strategy", SqlScalarType::String.nullable(false))
5734            .with_column("value", SqlScalarType::Jsonb.nullable(false))
5735            .finish(),
5736        column_comments: BTreeMap::from_iter([
5737            ("id", "The ID of the object."),
5738            (
5739                "strategy",
5740                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5741            ),
5742            (
5743                "value",
5744                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5745            ),
5746        ]),
5747        is_retained_metrics_object: false,
5748        access: vec![PUBLIC_SELECT],
5749    }
5750});
5751
5752pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5753    name: "mz_license_keys",
5754    schema: MZ_INTERNAL_SCHEMA,
5755    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
5756    desc: RelationDesc::builder()
5757        .with_column("id", SqlScalarType::String.nullable(false))
5758        .with_column("organization", SqlScalarType::String.nullable(false))
5759        .with_column("environment_id", SqlScalarType::String.nullable(false))
5760        .with_column(
5761            "expiration",
5762            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5763        )
5764        .with_column(
5765            "not_before",
5766            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5767        )
5768        .finish(),
5769    column_comments: BTreeMap::from_iter([
5770        ("id", "The identifier of the license key."),
5771        (
5772            "organization",
5773            "The name of the organization that this license key was issued to.",
5774        ),
5775        (
5776            "environment_id",
5777            "The environment ID that this license key was issued for.",
5778        ),
5779        (
5780            "expiration",
5781            "The date and time when this license key expires.",
5782        ),
5783        (
5784            "not_before",
5785            "The start of the validity period for this license key.",
5786        ),
5787    ]),
5788    is_retained_metrics_object: false,
5789    access: vec![PUBLIC_SELECT],
5790});
5791
5792pub static MZ_REPLACEMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5793    name: "mz_replacements",
5794    schema: MZ_INTERNAL_SCHEMA,
5795    oid: oid::TABLE_MZ_REPLACEMENTS_OID,
5796    desc: RelationDesc::builder()
5797        .with_column("id", SqlScalarType::String.nullable(false))
5798        .with_column("target_id", SqlScalarType::String.nullable(false))
5799        .finish(),
5800    column_comments: BTreeMap::from_iter([
5801        (
5802            "id",
5803            "The ID of the replacement object. Corresponds to `mz_objects.id`.",
5804        ),
5805        (
5806            "target_id",
5807            "The ID of the replacement target. Corresponds to `mz_objects.id`.",
5808        ),
5809    ]),
5810    is_retained_metrics_object: false,
5811    access: vec![PUBLIC_SELECT],
5812});
5813
5814// These will be replaced with per-replica tables once source/sink multiplexing on
5815// a single cluster is supported.
5816pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5817    name: "mz_source_statistics_raw",
5818    schema: MZ_INTERNAL_SCHEMA,
5819    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5820    data_source: IntrospectionType::StorageSourceStatistics.into(),
5821    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5822    column_comments: BTreeMap::new(),
5823    is_retained_metrics_object: true,
5824    access: vec![PUBLIC_SELECT],
5825});
5826pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5827    name: "mz_sink_statistics_raw",
5828    schema: MZ_INTERNAL_SCHEMA,
5829    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5830    data_source: IntrospectionType::StorageSinkStatistics.into(),
5831    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5832    column_comments: BTreeMap::new(),
5833    is_retained_metrics_object: true,
5834    access: vec![PUBLIC_SELECT],
5835});
5836
5837pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5838    name: "mz_storage_shards",
5839    schema: MZ_INTERNAL_SCHEMA,
5840    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5841    data_source: IntrospectionType::ShardMapping.into(),
5842    desc: RelationDesc::builder()
5843        .with_column("object_id", SqlScalarType::String.nullable(false))
5844        .with_column("shard_id", SqlScalarType::String.nullable(false))
5845        .finish(),
5846    column_comments: BTreeMap::new(),
5847    is_retained_metrics_object: false,
5848    access: vec![PUBLIC_SELECT],
5849});
5850
5851pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5852    name: "mz_storage_usage",
5853    schema: MZ_CATALOG_SCHEMA,
5854    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5855    desc: RelationDesc::builder()
5856        .with_column("object_id", SqlScalarType::String.nullable(false))
5857        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5858        .with_column(
5859            "collection_timestamp",
5860            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5861        )
5862        .with_key(vec![0, 2])
5863        .finish(),
5864    column_comments: BTreeMap::from_iter([
5865        (
5866            "object_id",
5867            "The ID of the table, source, or materialized view.",
5868        ),
5869        (
5870            "size_bytes",
5871            "The number of storage bytes used by the object.",
5872        ),
5873        (
5874            "collection_timestamp",
5875            "The time at which storage usage of the object was assessed.",
5876        ),
5877    ]),
5878    sql: "
5879SELECT
5880    object_id,
5881    sum(size_bytes)::uint8 AS size_bytes,
5882    collection_timestamp
5883FROM
5884    mz_internal.mz_storage_shards
5885    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5886GROUP BY object_id, collection_timestamp",
5887    access: vec![PUBLIC_SELECT],
5888});
5889
5890pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5891    BuiltinView {
5892    name: "mz_recent_storage_usage",
5893    schema: MZ_CATALOG_SCHEMA,
5894    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
5895    desc: RelationDesc::builder()
5896        .with_column("object_id", SqlScalarType::String.nullable(false))
5897        .with_column("size_bytes", SqlScalarType::UInt64.nullable(true))
5898        .with_key(vec![0])
5899        .finish(),
5900    column_comments: BTreeMap::from_iter([
5901        ("object_id", "The ID of the table, source, or materialized view."),
5902        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
5903    ]),
5904    sql: "
5905WITH
5906
5907recent_storage_usage_by_shard AS (
5908    SELECT shard_id, size_bytes, collection_timestamp
5909    FROM mz_internal.mz_storage_usage_by_shard
5910    -- Restricting to the last 6 hours makes it feasible to index the view.
5911    WHERE collection_timestamp + '6 hours' >= mz_now()
5912),
5913
5914most_recent_collection_timestamp_by_shard AS (
5915    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
5916    FROM recent_storage_usage_by_shard
5917    GROUP BY shard_id
5918)
5919
5920SELECT
5921    object_id,
5922    sum(size_bytes)::uint8 AS size_bytes
5923FROM
5924    mz_internal.mz_storage_shards
5925    LEFT JOIN most_recent_collection_timestamp_by_shard
5926        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
5927    LEFT JOIN recent_storage_usage_by_shard
5928        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
5929        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
5930GROUP BY object_id",
5931    access: vec![PUBLIC_SELECT],
5932}
5933});
5934
5935pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
5936    name: "mz_recent_storage_usage_ind",
5937    schema: MZ_CATALOG_SCHEMA,
5938    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
5939    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
5940    is_retained_metrics_object: false,
5941});
5942
5943pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
5944    BuiltinView {
5945        name: "mz_relations",
5946        schema: MZ_CATALOG_SCHEMA,
5947        oid: oid::VIEW_MZ_RELATIONS_OID,
5948        desc: RelationDesc::builder()
5949            .with_column("id", SqlScalarType::String.nullable(false))
5950            .with_column("oid", SqlScalarType::Oid.nullable(false))
5951            .with_column("schema_id", SqlScalarType::String.nullable(false))
5952            .with_column("name", SqlScalarType::String.nullable(false))
5953            .with_column("type", SqlScalarType::String.nullable(false))
5954            .with_column("owner_id", SqlScalarType::String.nullable(false))
5955            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5956            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false))
5957            .finish(),
5958        column_comments: BTreeMap::from_iter([
5959            ("id", "Materialize's unique ID for the relation."),
5960            ("oid", "A PostgreSQL-compatible OID for the relation."),
5961            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
5962            ("name", "The name of the relation."),
5963            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
5964            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
5965            ("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."),
5966            ("privileges", "The privileges belonging to the relation."),
5967        ]),
5968        sql: "
5969      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
5970UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
5971UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
5972UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views",
5973        access: vec![PUBLIC_SELECT],
5974    }
5975});
5976
5977pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5978    name: "mz_objects_id_namespace_types",
5979    schema: MZ_INTERNAL_SCHEMA,
5980    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
5981    desc: RelationDesc::builder()
5982        .with_column("object_type", SqlScalarType::String.nullable(false))
5983        .with_key(vec![0])
5984        .finish(),
5985    column_comments: BTreeMap::new(),
5986    sql: r#"SELECT *
5987    FROM (
5988        VALUES
5989            ('table'),
5990            ('view'),
5991            ('materialized-view'),
5992            ('source'),
5993            ('sink'),
5994            ('index'),
5995            ('connection'),
5996            ('type'),
5997            ('function'),
5998            ('secret')
5999    )
6000    AS _ (object_type)"#,
6001    access: vec![PUBLIC_SELECT],
6002});
6003
6004pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6005    name: "mz_object_oid_alias",
6006    schema: MZ_INTERNAL_SCHEMA,
6007    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
6008    desc: RelationDesc::builder()
6009        .with_column("object_type", SqlScalarType::String.nullable(false))
6010        .with_column("oid_alias", SqlScalarType::String.nullable(false))
6011        .with_key(vec![0])
6012        .finish(),
6013    column_comments: BTreeMap::new(),
6014    sql: "SELECT object_type, oid_alias
6015    FROM (
6016        VALUES
6017            (
6018                'table'::pg_catalog.text,
6019                'regclass'::pg_catalog.text
6020            ),
6021            ('source', 'regclass'),
6022            ('view', 'regclass'),
6023            ('materialized-view', 'regclass'),
6024            ('index', 'regclass'),
6025            ('type', 'regtype'),
6026            ('function', 'regproc')
6027    )
6028    AS _ (object_type, oid_alias);",
6029    access: vec![PUBLIC_SELECT],
6030});
6031
6032pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6033    BuiltinView {
6034        name: "mz_objects",
6035        schema: MZ_CATALOG_SCHEMA,
6036        oid: oid::VIEW_MZ_OBJECTS_OID,
6037        desc: RelationDesc::builder()
6038            .with_column("id", SqlScalarType::String.nullable(false))
6039            .with_column("oid", SqlScalarType::Oid.nullable(false))
6040            .with_column("schema_id", SqlScalarType::String.nullable(false))
6041            .with_column("name", SqlScalarType::String.nullable(false))
6042            .with_column("type", SqlScalarType::String.nullable(false))
6043            .with_column("owner_id", SqlScalarType::String.nullable(false))
6044            .with_column("cluster_id", SqlScalarType::String.nullable(true))
6045            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(true))
6046            .finish(),
6047        column_comments: BTreeMap::from_iter([
6048            ("id", "Materialize's unique ID for the object."),
6049            ("oid", "A PostgreSQL-compatible OID for the object."),
6050            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
6051            ("name", "The name of the object."),
6052            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
6053            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
6054            ("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."),
6055            ("privileges", "The privileges belonging to the object."),
6056        ]),
6057        sql:
6058        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
6059UNION ALL
6060    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
6061UNION ALL
6062    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[]
6063    FROM mz_catalog.mz_indexes
6064    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6065UNION ALL
6066    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
6067UNION ALL
6068    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
6069UNION ALL
6070    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
6071UNION ALL
6072    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
6073        access: vec![PUBLIC_SELECT],
6074    }
6075});
6076
6077pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6078    name: "mz_object_fully_qualified_names",
6079    schema: MZ_INTERNAL_SCHEMA,
6080    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
6081    desc: RelationDesc::builder()
6082        .with_column("id", SqlScalarType::String.nullable(false))
6083        .with_column("name", SqlScalarType::String.nullable(false))
6084        .with_column("object_type", SqlScalarType::String.nullable(false))
6085        .with_column("schema_id", SqlScalarType::String.nullable(false))
6086        .with_column("schema_name", SqlScalarType::String.nullable(false))
6087        .with_column("database_id", SqlScalarType::String.nullable(true))
6088        .with_column("database_name", SqlScalarType::String.nullable(true))
6089        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6090        .finish(),
6091    column_comments: BTreeMap::from_iter([
6092        ("id", "Materialize's unique ID for the object."),
6093        ("name", "The name of the object."),
6094        (
6095            "object_type",
6096            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6097        ),
6098        (
6099            "schema_id",
6100            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
6101        ),
6102        (
6103            "schema_name",
6104            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
6105        ),
6106        (
6107            "database_id",
6108            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
6109        ),
6110        (
6111            "database_name",
6112            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
6113        ),
6114        (
6115            "cluster_id",
6116            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
6117        ),
6118    ]),
6119    sql: "
6120    SELECT o.id,
6121        o.name,
6122        o.type as object_type,
6123        sc.id as schema_id,
6124        sc.name as schema_name,
6125        db.id as database_id,
6126        db.name as database_name,
6127        o.cluster_id
6128    FROM mz_catalog.mz_objects o
6129    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
6130    -- LEFT JOIN accounts for objects in the ambient database.
6131    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
6132    access: vec![PUBLIC_SELECT],
6133});
6134
6135pub static MZ_OBJECT_GLOBAL_IDS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
6136    name: "mz_object_global_ids",
6137    schema: MZ_INTERNAL_SCHEMA,
6138    oid: oid::VIEW_MZ_OBJECT_GLOBAL_IDS_OID,
6139    desc: RelationDesc::builder()
6140        .with_column("id", SqlScalarType::String.nullable(false))
6141        .with_column("global_id", SqlScalarType::String.nullable(false))
6142        .finish(),
6143    column_comments: BTreeMap::from_iter([
6144        (
6145            "id",
6146            "The ID of the object. Corresponds to `mz_objects.id`.",
6147        ),
6148        ("global_id", "The global ID of the object."),
6149    ]),
6150    is_retained_metrics_object: false,
6151    access: vec![PUBLIC_SELECT],
6152});
6153
6154// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
6155pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6156    name: "mz_object_lifetimes",
6157    schema: MZ_INTERNAL_SCHEMA,
6158    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
6159    desc: RelationDesc::builder()
6160        .with_column("id", SqlScalarType::String.nullable(true))
6161        .with_column("previous_id", SqlScalarType::String.nullable(true))
6162        .with_column("object_type", SqlScalarType::String.nullable(false))
6163        .with_column("event_type", SqlScalarType::String.nullable(false))
6164        .with_column(
6165            "occurred_at",
6166            SqlScalarType::TimestampTz { precision: None }.nullable(false),
6167        )
6168        .finish(),
6169    column_comments: BTreeMap::from_iter([
6170        ("id", "Materialize's unique ID for the object."),
6171        ("previous_id", "The object's previous ID, if one exists."),
6172        (
6173            "object_type",
6174            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6175        ),
6176        (
6177            "event_type",
6178            "The lifetime event, either `create` or `drop`.",
6179        ),
6180        (
6181            "occurred_at",
6182            "Wall-clock timestamp of when the event occurred.",
6183        ),
6184    ]),
6185    sql: "
6186    SELECT
6187        CASE
6188            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
6189            ELSE a.details ->> 'id'
6190        END id,
6191        a.details ->> 'previous_id' as previous_id,
6192        a.object_type,
6193        a.event_type,
6194        a.occurred_at
6195    FROM mz_catalog.mz_audit_events a
6196    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
6197    access: vec![PUBLIC_SELECT],
6198});
6199
6200pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6201    name: "mz_object_history",
6202    schema: MZ_INTERNAL_SCHEMA,
6203    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
6204    desc: RelationDesc::builder()
6205        .with_column("id", SqlScalarType::String.nullable(true))
6206        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6207        .with_column("object_type", SqlScalarType::String.nullable(false))
6208        .with_column(
6209            "created_at",
6210            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6211        )
6212        .with_column(
6213            "dropped_at",
6214            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6215        )
6216        .finish(),
6217    column_comments: BTreeMap::from_iter([
6218        ("id", "Materialize's unique ID for the object."),
6219        (
6220            "cluster_id",
6221            "The object's cluster ID. `NULL` if the object has no associated cluster.",
6222        ),
6223        (
6224            "object_type",
6225            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6226        ),
6227        (
6228            "created_at",
6229            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
6230        ),
6231        (
6232            "dropped_at",
6233            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
6234        ),
6235    ]),
6236    sql: r#"
6237    WITH
6238        creates AS
6239        (
6240            SELECT
6241                details ->> 'id' AS id,
6242                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
6243                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
6244                object_type,
6245                occurred_at
6246            FROM
6247                mz_catalog.mz_audit_events AS events
6248                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
6249            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6250        ),
6251        drops AS
6252        (
6253            SELECT details ->> 'id' AS id, occurred_at
6254            FROM mz_catalog.mz_audit_events
6255            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6256        ),
6257        user_object_history AS
6258        (
6259            SELECT
6260                creates.id,
6261                creates.cluster_id,
6262                creates.object_type,
6263                creates.occurred_at AS created_at,
6264                drops.occurred_at AS dropped_at
6265            FROM creates LEFT JOIN drops ON creates.id = drops.id
6266            WHERE creates.id LIKE 'u%'
6267        ),
6268        -- We need to union built in objects since they aren't in the audit log
6269        built_in_objects AS
6270        (
6271            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
6272            SELECT DISTINCT ON (objects.id)
6273                objects.id,
6274                objects.cluster_id,
6275                objects.type AS object_type,
6276                NULL::timestamptz AS created_at,
6277                NULL::timestamptz AS dropped_at
6278            FROM mz_catalog.mz_objects AS objects
6279            WHERE objects.id LIKE 's%'
6280        )
6281    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
6282    access: vec![PUBLIC_SELECT],
6283});
6284
6285pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6286    name: "mz_dataflows_per_worker",
6287    schema: MZ_INTROSPECTION_SCHEMA,
6288    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
6289    desc: RelationDesc::builder()
6290        .with_column("id", SqlScalarType::UInt64.nullable(true))
6291        .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6292        .with_column("name", SqlScalarType::String.nullable(false))
6293        .finish(),
6294    column_comments: BTreeMap::new(),
6295    sql: "SELECT
6296    addrs.address[1] AS id,
6297    ops.worker_id,
6298    ops.name
6299FROM
6300    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6301    mz_introspection.mz_dataflow_operators_per_worker ops
6302WHERE
6303    addrs.id = ops.id AND
6304    addrs.worker_id = ops.worker_id AND
6305    mz_catalog.list_length(addrs.address) = 1",
6306    access: vec![PUBLIC_SELECT],
6307});
6308
6309pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6310    name: "mz_dataflows",
6311    schema: MZ_INTROSPECTION_SCHEMA,
6312    oid: oid::VIEW_MZ_DATAFLOWS_OID,
6313    desc: RelationDesc::builder()
6314        .with_column("id", SqlScalarType::UInt64.nullable(true))
6315        .with_column("name", SqlScalarType::String.nullable(false))
6316        .finish(),
6317    column_comments: BTreeMap::from_iter([
6318        ("id", "The ID of the dataflow."),
6319        ("name", "The internal name of the dataflow."),
6320    ]),
6321    sql: "
6322SELECT id, name
6323FROM mz_introspection.mz_dataflows_per_worker
6324WHERE worker_id = 0::uint8",
6325    access: vec![PUBLIC_SELECT],
6326});
6327
6328pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6329    name: "mz_dataflow_addresses",
6330    schema: MZ_INTROSPECTION_SCHEMA,
6331    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
6332    desc: RelationDesc::builder()
6333        .with_column("id", SqlScalarType::UInt64.nullable(false))
6334        .with_column(
6335            "address",
6336            SqlScalarType::List {
6337                element_type: Box::new(SqlScalarType::UInt64),
6338                custom_id: None,
6339            }
6340            .nullable(false),
6341        )
6342        .with_key(vec![0])
6343        .finish(),
6344    column_comments: BTreeMap::from_iter([
6345        (
6346            "id",
6347            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
6348        ),
6349        (
6350            "address",
6351            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
6352        ),
6353    ]),
6354    sql: "
6355SELECT id, address
6356FROM mz_introspection.mz_dataflow_addresses_per_worker
6357WHERE worker_id = 0::uint8",
6358    access: vec![PUBLIC_SELECT],
6359});
6360
6361pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6362    name: "mz_dataflow_channels",
6363    schema: MZ_INTROSPECTION_SCHEMA,
6364    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
6365    desc: RelationDesc::builder()
6366        .with_column("id", SqlScalarType::UInt64.nullable(false))
6367        .with_column("from_index", SqlScalarType::UInt64.nullable(false))
6368        .with_column("from_port", SqlScalarType::UInt64.nullable(false))
6369        .with_column("to_index", SqlScalarType::UInt64.nullable(false))
6370        .with_column("to_port", SqlScalarType::UInt64.nullable(false))
6371        .with_column("type", SqlScalarType::String.nullable(false))
6372        .with_key(vec![0])
6373        .finish(),
6374    column_comments: BTreeMap::from_iter([
6375        ("id", "The ID of the channel."),
6376        (
6377            "from_index",
6378            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
6379        ),
6380        ("from_port", "The source operator's output port."),
6381        (
6382            "to_index",
6383            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
6384        ),
6385        ("to_port", "The target operator's input port."),
6386        ("type", "The container type of the channel."),
6387    ]),
6388    sql: "
6389SELECT id, from_index, from_port, to_index, to_port, type
6390FROM mz_introspection.mz_dataflow_channels_per_worker
6391WHERE worker_id = 0::uint8",
6392    access: vec![PUBLIC_SELECT],
6393});
6394
6395pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6396    name: "mz_dataflow_operators",
6397    schema: MZ_INTROSPECTION_SCHEMA,
6398    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6399    desc: RelationDesc::builder()
6400        .with_column("id", SqlScalarType::UInt64.nullable(false))
6401        .with_column("name", SqlScalarType::String.nullable(false))
6402        .with_key(vec![0])
6403        .finish(),
6404    column_comments: BTreeMap::from_iter([
6405        ("id", "The ID of the operator."),
6406        ("name", "The internal name of the operator."),
6407    ]),
6408    sql: "
6409SELECT id, name
6410FROM mz_introspection.mz_dataflow_operators_per_worker
6411WHERE worker_id = 0::uint8",
6412    access: vec![PUBLIC_SELECT],
6413});
6414
6415pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6416    name: "mz_dataflow_global_ids",
6417    schema: MZ_INTROSPECTION_SCHEMA,
6418    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6419    desc: RelationDesc::builder()
6420        .with_column("id", SqlScalarType::UInt64.nullable(false))
6421        .with_column("global_id", SqlScalarType::String.nullable(false))
6422        .with_key(vec![0, 1])
6423        .finish(),
6424    column_comments: BTreeMap::from_iter([
6425        ("id", "The dataflow ID."),
6426        ("global_id", "A global ID associated with that dataflow."),
6427    ]),
6428    sql: "
6429SELECT id, global_id
6430FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6431WHERE worker_id = 0::uint8",
6432    access: vec![PUBLIC_SELECT],
6433});
6434
6435pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6436    name: "mz_mappable_objects",
6437    schema: MZ_INTROSPECTION_SCHEMA,
6438    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6439    desc: RelationDesc::builder()
6440        .with_column("name", SqlScalarType::String.nullable(false))
6441        .with_column("global_id", SqlScalarType::String.nullable(false))
6442        .finish(),
6443    column_comments: BTreeMap::from_iter([
6444        (
6445            "name",
6446            "The name of the object. This name is unquoted, and you might need to call `quote_ident` if you want to reference the name shown here.",
6447        ),
6448        ("global_id", "The global ID of the object."),
6449    ]),
6450    sql: "
6451SELECT COALESCE(md.name || '.', '') || ms.name || '.' || mo.name AS name, mgi.global_id AS global_id
6452FROM      mz_catalog.mz_objects mo
6453          JOIN mz_introspection.mz_compute_exports mce ON (mo.id = mce.export_id)
6454          JOIN mz_catalog.mz_schemas ms ON (mo.schema_id = ms.id)
6455          JOIN mz_introspection.mz_dataflow_global_ids mgi ON (mce.dataflow_id = mgi.id)
6456     LEFT JOIN mz_catalog.mz_databases md ON (ms.database_id = md.id);",
6457    access: vec![PUBLIC_SELECT],
6458});
6459
6460pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6461    name: "mz_lir_mapping",
6462    schema: MZ_INTROSPECTION_SCHEMA,
6463    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6464    desc: RelationDesc::builder()
6465        .with_column("global_id", SqlScalarType::String.nullable(false))
6466        .with_column("lir_id", SqlScalarType::UInt64.nullable(false))
6467        .with_column("operator", SqlScalarType::String.nullable(false))
6468        .with_column("parent_lir_id", SqlScalarType::UInt64.nullable(true))
6469        .with_column("nesting", SqlScalarType::UInt16.nullable(false))
6470        .with_column("operator_id_start", SqlScalarType::UInt64.nullable(false))
6471        .with_column("operator_id_end", SqlScalarType::UInt64.nullable(false))
6472        .with_key(vec![0, 1])
6473        .finish(),
6474    column_comments: BTreeMap::from_iter([
6475        ("global_id", "The global ID."),
6476        ("lir_id", "The LIR node ID."),
6477        (
6478            "operator",
6479            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6480        ),
6481        (
6482            "parent_lir_id",
6483            "The parent of this LIR node. May be `NULL`.",
6484        ),
6485        ("nesting", "The nesting level of this LIR node."),
6486        (
6487            "operator_id_start",
6488            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6489        ),
6490        (
6491            "operator_id_end",
6492            "The first dataflow operator ID _after_ this LIR operator (exclusive).",
6493        ),
6494    ]),
6495    sql: "
6496SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6497FROM mz_introspection.mz_compute_lir_mapping_per_worker
6498WHERE worker_id = 0::uint8",
6499    access: vec![PUBLIC_SELECT],
6500});
6501
6502pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6503    LazyLock::new(|| BuiltinView {
6504        name: "mz_dataflow_operator_dataflows_per_worker",
6505        schema: MZ_INTROSPECTION_SCHEMA,
6506        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6507        desc: RelationDesc::builder()
6508            .with_column("id", SqlScalarType::UInt64.nullable(false))
6509            .with_column("name", SqlScalarType::String.nullable(false))
6510            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6511            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6512            .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6513            .finish(),
6514        column_comments: BTreeMap::new(),
6515        sql: "SELECT
6516    ops.id,
6517    ops.name,
6518    ops.worker_id,
6519    dfs.id as dataflow_id,
6520    dfs.name as dataflow_name
6521FROM
6522    mz_introspection.mz_dataflow_operators_per_worker ops,
6523    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6524    mz_introspection.mz_dataflows_per_worker dfs
6525WHERE
6526    ops.id = addrs.id AND
6527    ops.worker_id = addrs.worker_id AND
6528    dfs.id = addrs.address[1] AND
6529    dfs.worker_id = addrs.worker_id",
6530        access: vec![PUBLIC_SELECT],
6531    });
6532
6533pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6534    name: "mz_dataflow_operator_dataflows",
6535    schema: MZ_INTROSPECTION_SCHEMA,
6536    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6537    desc: RelationDesc::builder()
6538        .with_column("id", SqlScalarType::UInt64.nullable(false))
6539        .with_column("name", SqlScalarType::String.nullable(false))
6540        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6541        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6542        .finish(),
6543    column_comments: BTreeMap::from_iter([
6544        (
6545            "id",
6546            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6547        ),
6548        ("name", "The internal name of the operator."),
6549        (
6550            "dataflow_id",
6551            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6552        ),
6553        (
6554            "dataflow_name",
6555            "The internal name of the dataflow hosting the operator.",
6556        ),
6557    ]),
6558    sql: "
6559SELECT id, name, dataflow_id, dataflow_name
6560FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6561WHERE worker_id = 0::uint8",
6562    access: vec![PUBLIC_SELECT],
6563});
6564
6565pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6566    BuiltinView {
6567        name: "mz_object_transitive_dependencies",
6568        schema: MZ_INTERNAL_SCHEMA,
6569        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6570        desc: RelationDesc::builder()
6571            .with_column("object_id", SqlScalarType::String.nullable(false))
6572            .with_column(
6573                "referenced_object_id",
6574                SqlScalarType::String.nullable(false),
6575            )
6576            .with_key(vec![0, 1])
6577            .finish(),
6578        column_comments: BTreeMap::from_iter([
6579            (
6580                "object_id",
6581                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6582            ),
6583            (
6584                "referenced_object_id",
6585                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6586            ),
6587        ]),
6588        sql: "
6589WITH MUTUALLY RECURSIVE
6590  reach(object_id text, referenced_object_id text) AS (
6591    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6592    UNION
6593    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6594  )
6595SELECT object_id, referenced_object_id FROM reach;",
6596        access: vec![PUBLIC_SELECT],
6597    }
6598});
6599
6600pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6601    name: "mz_compute_exports",
6602    schema: MZ_INTROSPECTION_SCHEMA,
6603    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6604    desc: RelationDesc::builder()
6605        .with_column("export_id", SqlScalarType::String.nullable(false))
6606        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6607        .with_key(vec![0])
6608        .finish(),
6609    column_comments: BTreeMap::from_iter([
6610        (
6611            "export_id",
6612            "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`.",
6613        ),
6614        (
6615            "dataflow_id",
6616            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6617        ),
6618    ]),
6619    sql: "
6620SELECT export_id, dataflow_id
6621FROM mz_introspection.mz_compute_exports_per_worker
6622WHERE worker_id = 0::uint8",
6623    access: vec![PUBLIC_SELECT],
6624});
6625
6626pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6627    name: "mz_compute_frontiers",
6628    schema: MZ_INTROSPECTION_SCHEMA,
6629    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6630    desc: RelationDesc::builder()
6631        .with_column("export_id", SqlScalarType::String.nullable(false))
6632        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6633        .with_key(vec![0])
6634        .finish(),
6635    column_comments: BTreeMap::from_iter([
6636        (
6637            "export_id",
6638            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6639        ),
6640        (
6641            "time",
6642            "The next timestamp at which the dataflow output may change.",
6643        ),
6644    ]),
6645    sql: "SELECT
6646    export_id, pg_catalog.min(time) AS time
6647FROM mz_introspection.mz_compute_frontiers_per_worker
6648GROUP BY export_id",
6649    access: vec![PUBLIC_SELECT],
6650});
6651
6652pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6653    LazyLock::new(|| BuiltinView {
6654        name: "mz_dataflow_channel_operators_per_worker",
6655        schema: MZ_INTROSPECTION_SCHEMA,
6656        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6657        desc: RelationDesc::builder()
6658            .with_column("id", SqlScalarType::UInt64.nullable(false))
6659            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6660            .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6661            .with_column(
6662                "from_operator_address",
6663                SqlScalarType::List {
6664                    element_type: Box::new(SqlScalarType::UInt64),
6665                    custom_id: None,
6666                }
6667                .nullable(false),
6668            )
6669            .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6670            .with_column(
6671                "to_operator_address",
6672                SqlScalarType::List {
6673                    element_type: Box::new(SqlScalarType::UInt64),
6674                    custom_id: None,
6675                }
6676                .nullable(false),
6677            )
6678            .with_column("type", SqlScalarType::String.nullable(false))
6679            .finish(),
6680        column_comments: BTreeMap::new(),
6681        sql: "
6682WITH
6683channel_addresses(id, worker_id, address, from_index, to_index, type) AS (
6684     SELECT id, worker_id, address, from_index, to_index, type
6685     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6686     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6687     USING (id, worker_id)
6688),
6689channel_operator_addresses(id, worker_id, from_address, to_address, type) AS (
6690     SELECT id, worker_id,
6691            address || from_index AS from_address,
6692            address || to_index AS to_address,
6693            type
6694     FROM channel_addresses
6695),
6696operator_addresses(id, worker_id, address) AS (
6697     SELECT id, worker_id, address
6698     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6699     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6700     USING (id, worker_id)
6701)
6702SELECT coa.id,
6703       coa.worker_id,
6704       from_ops.id AS from_operator_id,
6705       coa.from_address AS from_operator_address,
6706       to_ops.id AS to_operator_id,
6707       coa.to_address AS to_operator_address,
6708       coa.type
6709FROM channel_operator_addresses coa
6710     LEFT OUTER JOIN operator_addresses from_ops
6711          ON coa.from_address = from_ops.address AND
6712             coa.worker_id = from_ops.worker_id
6713     LEFT OUTER JOIN operator_addresses to_ops
6714          ON coa.to_address = to_ops.address AND
6715             coa.worker_id = to_ops.worker_id
6716",
6717        access: vec![PUBLIC_SELECT],
6718    });
6719
6720pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6721    name: "mz_dataflow_channel_operators",
6722    schema: MZ_INTROSPECTION_SCHEMA,
6723    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6724    desc: RelationDesc::builder()
6725        .with_column("id", SqlScalarType::UInt64.nullable(false))
6726        .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6727        .with_column(
6728            "from_operator_address",
6729            SqlScalarType::List {
6730                element_type: Box::new(SqlScalarType::UInt64),
6731                custom_id: None,
6732            }
6733            .nullable(false),
6734        )
6735        .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6736        .with_column(
6737            "to_operator_address",
6738            SqlScalarType::List {
6739                element_type: Box::new(SqlScalarType::UInt64),
6740                custom_id: None,
6741            }
6742            .nullable(false),
6743        )
6744        .with_column("type", SqlScalarType::String.nullable(false))
6745        .finish(),
6746    column_comments: BTreeMap::from_iter([
6747        (
6748            "id",
6749            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6750        ),
6751        (
6752            "from_operator_id",
6753            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6754        ),
6755        (
6756            "from_operator_address",
6757            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6758        ),
6759        (
6760            "to_operator_id",
6761            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6762        ),
6763        (
6764            "to_operator_address",
6765            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6766        ),
6767        ("type", "The container type of the channel."),
6768    ]),
6769    sql: "
6770SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address, type
6771FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6772WHERE worker_id = 0::uint8",
6773    access: vec![PUBLIC_SELECT],
6774});
6775
6776pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6777    name: "mz_compute_import_frontiers",
6778    schema: MZ_INTROSPECTION_SCHEMA,
6779    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6780    desc: RelationDesc::builder()
6781        .with_column("export_id", SqlScalarType::String.nullable(false))
6782        .with_column("import_id", SqlScalarType::String.nullable(false))
6783        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6784        .with_key(vec![0, 1])
6785        .finish(),
6786    column_comments: BTreeMap::from_iter([
6787        (
6788            "export_id",
6789            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6790        ),
6791        (
6792            "import_id",
6793            "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`.",
6794        ),
6795        (
6796            "time",
6797            "The next timestamp at which the dataflow input may change.",
6798        ),
6799    ]),
6800    sql: "SELECT
6801    export_id, import_id, pg_catalog.min(time) AS time
6802FROM mz_introspection.mz_compute_import_frontiers_per_worker
6803GROUP BY export_id, import_id",
6804    access: vec![PUBLIC_SELECT],
6805});
6806
6807pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6808    LazyLock::new(|| BuiltinView {
6809        name: "mz_records_per_dataflow_operator_per_worker",
6810        schema: MZ_INTROSPECTION_SCHEMA,
6811        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6812        desc: RelationDesc::builder()
6813            .with_column("id", SqlScalarType::UInt64.nullable(false))
6814            .with_column("name", SqlScalarType::String.nullable(false))
6815            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6816            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6817            .with_column("records", SqlScalarType::Int64.nullable(true))
6818            .with_column("batches", SqlScalarType::Int64.nullable(true))
6819            .with_column("size", SqlScalarType::Int64.nullable(true))
6820            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6821            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6822            .finish(),
6823        column_comments: BTreeMap::new(),
6824        sql: "
6825SELECT
6826    dod.id,
6827    dod.name,
6828    dod.worker_id,
6829    dod.dataflow_id,
6830    ar_size.records AS records,
6831    ar_size.batches AS batches,
6832    ar_size.size AS size,
6833    ar_size.capacity AS capacity,
6834    ar_size.allocations AS allocations
6835FROM
6836    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6837    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6838        dod.id = ar_size.operator_id AND
6839        dod.worker_id = ar_size.worker_id",
6840        access: vec![PUBLIC_SELECT],
6841    });
6842
6843pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6844    LazyLock::new(|| BuiltinView {
6845        name: "mz_records_per_dataflow_operator",
6846        schema: MZ_INTROSPECTION_SCHEMA,
6847        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6848        desc: RelationDesc::builder()
6849            .with_column("id", SqlScalarType::UInt64.nullable(false))
6850            .with_column("name", SqlScalarType::String.nullable(false))
6851            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6852            .with_column("records", SqlScalarType::Int64.nullable(true))
6853            .with_column("batches", SqlScalarType::Int64.nullable(true))
6854            .with_column("size", SqlScalarType::Int64.nullable(true))
6855            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6856            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6857            .with_key(vec![0, 1, 2])
6858            .finish(),
6859        column_comments: BTreeMap::from_iter([
6860            (
6861                "id",
6862                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6863            ),
6864            ("name", "The internal name of the operator."),
6865            (
6866                "dataflow_id",
6867                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6868            ),
6869            ("records", "The number of records in the operator."),
6870            ("batches", "The number of batches in the dataflow."),
6871            ("size", "The utilized size in bytes of the arrangement."),
6872            (
6873                "capacity",
6874                "The capacity in bytes of the arrangement. Can be larger than the size.",
6875            ),
6876            (
6877                "allocations",
6878                "The number of separate memory allocations backing the arrangement.",
6879            ),
6880        ]),
6881        sql: "
6882SELECT
6883    id,
6884    name,
6885    dataflow_id,
6886    SUM(records)::int8 AS records,
6887    SUM(batches)::int8 AS batches,
6888    SUM(size)::int8 AS size,
6889    SUM(capacity)::int8 AS capacity,
6890    SUM(allocations)::int8 AS allocations
6891FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
6892GROUP BY id, name, dataflow_id",
6893        access: vec![PUBLIC_SELECT],
6894    });
6895
6896pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
6897    LazyLock::new(|| BuiltinView {
6898        name: "mz_records_per_dataflow_per_worker",
6899        schema: MZ_INTROSPECTION_SCHEMA,
6900        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
6901        desc: RelationDesc::builder()
6902            .with_column("id", SqlScalarType::UInt64.nullable(false))
6903            .with_column("name", SqlScalarType::String.nullable(false))
6904            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6905            .with_column("records", SqlScalarType::Int64.nullable(true))
6906            .with_column("batches", SqlScalarType::Int64.nullable(true))
6907            .with_column("size", SqlScalarType::Int64.nullable(true))
6908            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6909            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6910            .with_key(vec![0, 1, 2])
6911            .finish(),
6912        column_comments: BTreeMap::new(),
6913        sql: "
6914SELECT
6915    rdo.dataflow_id as id,
6916    dfs.name,
6917    rdo.worker_id,
6918    SUM(rdo.records)::int8 as records,
6919    SUM(rdo.batches)::int8 as batches,
6920    SUM(rdo.size)::int8 as size,
6921    SUM(rdo.capacity)::int8 as capacity,
6922    SUM(rdo.allocations)::int8 as allocations
6923FROM
6924    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
6925    mz_introspection.mz_dataflows_per_worker dfs
6926WHERE
6927    rdo.dataflow_id = dfs.id AND
6928    rdo.worker_id = dfs.worker_id
6929GROUP BY
6930    rdo.dataflow_id,
6931    dfs.name,
6932    rdo.worker_id",
6933        access: vec![PUBLIC_SELECT],
6934    });
6935
6936pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6937    name: "mz_records_per_dataflow",
6938    schema: MZ_INTROSPECTION_SCHEMA,
6939    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
6940    desc: RelationDesc::builder()
6941        .with_column("id", SqlScalarType::UInt64.nullable(false))
6942        .with_column("name", SqlScalarType::String.nullable(false))
6943        .with_column("records", SqlScalarType::Int64.nullable(true))
6944        .with_column("batches", SqlScalarType::Int64.nullable(true))
6945        .with_column("size", SqlScalarType::Int64.nullable(true))
6946        .with_column("capacity", SqlScalarType::Int64.nullable(true))
6947        .with_column("allocations", SqlScalarType::Int64.nullable(true))
6948        .with_key(vec![0, 1])
6949        .finish(),
6950    column_comments: BTreeMap::from_iter([
6951        (
6952            "id",
6953            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6954        ),
6955        ("name", "The internal name of the dataflow."),
6956        ("records", "The number of records in the dataflow."),
6957        ("batches", "The number of batches in the dataflow."),
6958        ("size", "The utilized size in bytes of the arrangements."),
6959        (
6960            "capacity",
6961            "The capacity in bytes of the arrangements. Can be larger than the size.",
6962        ),
6963        (
6964            "allocations",
6965            "The number of separate memory allocations backing the arrangements.",
6966        ),
6967    ]),
6968    sql: "
6969SELECT
6970    id,
6971    name,
6972    SUM(records)::int8 as records,
6973    SUM(batches)::int8 as batches,
6974    SUM(size)::int8 as size,
6975    SUM(capacity)::int8 as capacity,
6976    SUM(allocations)::int8 as allocations
6977FROM
6978    mz_introspection.mz_records_per_dataflow_per_worker
6979GROUP BY
6980    id,
6981    name",
6982    access: vec![PUBLIC_SELECT],
6983});
6984
6985/// Peeled version of `PG_NAMESPACE`:
6986/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6987///   in order to make this view indexable.
6988/// - This has the database name as an extra column, so that downstream views can check it against
6989///  `current_database()`.
6990pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6991    name: "pg_namespace_all_databases",
6992    schema: MZ_INTERNAL_SCHEMA,
6993    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
6994    desc: RelationDesc::builder()
6995        .with_column("oid", SqlScalarType::Oid.nullable(false))
6996        .with_column("nspname", SqlScalarType::String.nullable(false))
6997        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6998        .with_column(
6999            "nspacl",
7000            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7001        )
7002        .with_column("database_name", SqlScalarType::String.nullable(true))
7003        .finish(),
7004    column_comments: BTreeMap::new(),
7005    sql: "
7006SELECT
7007    s.oid AS oid,
7008    s.name AS nspname,
7009    role_owner.oid AS nspowner,
7010    NULL::pg_catalog.text[] AS nspacl,
7011    d.name as database_name
7012FROM mz_catalog.mz_schemas s
7013LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7014JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
7015    access: vec![PUBLIC_SELECT],
7016});
7017
7018pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7019    name: "pg_namespace_all_databases_ind",
7020    schema: MZ_INTERNAL_SCHEMA,
7021    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
7022    sql: "IN CLUSTER mz_catalog_server
7023ON mz_internal.pg_namespace_all_databases (nspname)",
7024    is_retained_metrics_object: false,
7025};
7026
7027pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7028    name: "pg_namespace",
7029    schema: PG_CATALOG_SCHEMA,
7030    oid: oid::VIEW_PG_NAMESPACE_OID,
7031    desc: RelationDesc::builder()
7032        .with_column("oid", SqlScalarType::Oid.nullable(false))
7033        .with_column("nspname", SqlScalarType::String.nullable(false))
7034        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
7035        .with_column(
7036            "nspacl",
7037            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7038        )
7039        .finish(),
7040    column_comments: BTreeMap::new(),
7041    sql: "
7042SELECT
7043    oid, nspname, nspowner, nspacl
7044FROM mz_internal.pg_namespace_all_databases
7045WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7046    access: vec![PUBLIC_SELECT],
7047});
7048
7049/// Peeled version of `PG_CLASS`:
7050/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7051///   in order to make this view indexable.
7052/// - This has the database name as an extra column, so that downstream views can check it against
7053///  `current_database()`.
7054pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7055    BuiltinView {
7056        name: "pg_class_all_databases",
7057        schema: MZ_INTERNAL_SCHEMA,
7058        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
7059        desc: RelationDesc::builder()
7060            .with_column("oid", SqlScalarType::Oid.nullable(false))
7061            .with_column("relname", SqlScalarType::String.nullable(false))
7062            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
7063            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
7064            .with_column("relowner", SqlScalarType::Oid.nullable(false))
7065            .with_column("relam", SqlScalarType::Oid.nullable(false))
7066            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
7067            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
7068            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
7069            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
7070            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
7071            .with_column("relkind", SqlScalarType::String.nullable(true))
7072            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
7073            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
7074            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
7075            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
7076            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
7077            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
7078            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
7079            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
7080            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
7081            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
7082            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
7083            .with_column("database_name", SqlScalarType::String.nullable(true))
7084            .finish(),
7085        column_comments: BTreeMap::new(),
7086        sql: "
7087SELECT
7088    class_objects.oid,
7089    class_objects.name AS relname,
7090    mz_schemas.oid AS relnamespace,
7091    -- MZ doesn't support typed tables so reloftype is filled with 0
7092    0::pg_catalog.oid AS reloftype,
7093    role_owner.oid AS relowner,
7094    0::pg_catalog.oid AS relam,
7095    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
7096    0::pg_catalog.oid AS reltablespace,
7097    -- MZ doesn't support (estimated) row counts currently.
7098    -- Postgres defines a value of -1 as unknown.
7099    -1::float4 as reltuples,
7100    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
7101    0::pg_catalog.oid AS reltoastrelid,
7102    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
7103    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
7104    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
7105    -- TODO(jkosh44): update this column when issue is resolved.
7106    'p'::pg_catalog.\"char\" AS relpersistence,
7107    CASE
7108        WHEN class_objects.type = 'table' THEN 'r'
7109        WHEN class_objects.type = 'source' THEN 'r'
7110        WHEN class_objects.type = 'index' THEN 'i'
7111        WHEN class_objects.type = 'view' THEN 'v'
7112        WHEN class_objects.type = 'materialized-view' THEN 'm'
7113    END relkind,
7114    COALESCE(
7115        (
7116            SELECT count(*)::pg_catalog.int2
7117            FROM mz_catalog.mz_columns
7118            WHERE mz_columns.id = class_objects.id
7119        ),
7120        0::pg_catalog.int2
7121    ) AS relnatts,
7122    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
7123    0::pg_catalog.int2 AS relchecks,
7124    -- MZ doesn't support creating rules so relhasrules is filled with false
7125    false AS relhasrules,
7126    -- MZ doesn't support creating triggers so relhastriggers is filled with false
7127    false AS relhastriggers,
7128    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
7129    false AS relhassubclass,
7130    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
7131    false AS relrowsecurity,
7132    false AS relforcerowsecurity,
7133    -- MZ doesn't support replication so relreplident is filled with 'd' for default
7134    'd'::pg_catalog.\"char\" AS relreplident,
7135    -- MZ doesn't support table partitioning so relispartition is filled with false
7136    false AS relispartition,
7137    -- PG removed relhasoids in v12 so it's filled with false
7138    false AS relhasoids,
7139    -- MZ doesn't support options for relations
7140    NULL::pg_catalog.text[] as reloptions,
7141    d.name as database_name
7142FROM (
7143    -- pg_class catalogs relations and indexes
7144    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
7145    UNION ALL
7146        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
7147        FROM mz_catalog.mz_indexes
7148        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7149) AS class_objects
7150JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7151LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7152JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
7153        access: vec![PUBLIC_SELECT],
7154    }
7155});
7156
7157pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7158    name: "pg_class_all_databases_ind",
7159    schema: MZ_INTERNAL_SCHEMA,
7160    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
7161    sql: "IN CLUSTER mz_catalog_server
7162ON mz_internal.pg_class_all_databases (relname)",
7163    is_retained_metrics_object: false,
7164};
7165
7166pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| {
7167    BuiltinView {
7168    name: "pg_class",
7169    schema: PG_CATALOG_SCHEMA,
7170    oid: oid::VIEW_PG_CLASS_OID,
7171    desc: RelationDesc::builder()
7172        .with_column("oid", SqlScalarType::Oid.nullable(false))
7173        .with_column("relname", SqlScalarType::String.nullable(false))
7174        .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
7175        .with_column("reloftype", SqlScalarType::Oid.nullable(false))
7176        .with_column("relowner", SqlScalarType::Oid.nullable(false))
7177        .with_column("relam", SqlScalarType::Oid.nullable(false))
7178        .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
7179        .with_column("reltuples", SqlScalarType::Float32.nullable(false))
7180        .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
7181        .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
7182        .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
7183        .with_column("relkind", SqlScalarType::String.nullable(true))
7184        .with_column("relnatts", SqlScalarType::Int16.nullable(false))
7185        .with_column("relchecks", SqlScalarType::Int16.nullable(false))
7186        .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
7187        .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
7188        .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
7189        .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
7190        .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
7191        .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
7192        .with_column("relispartition", SqlScalarType::Bool.nullable(false))
7193        .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
7194        .with_column(
7195            "reloptions",
7196            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7197        )
7198        .finish(),
7199    column_comments: BTreeMap::new(),
7200    sql: "
7201SELECT
7202    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
7203    relhasindex, relpersistence, relkind, relnatts, relchecks, relhasrules, relhastriggers, relhassubclass,
7204    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
7205FROM mz_internal.pg_class_all_databases
7206WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
7207",
7208    access: vec![PUBLIC_SELECT],
7209}
7210});
7211
7212pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7213    name: "pg_depend",
7214    schema: PG_CATALOG_SCHEMA,
7215    oid: oid::VIEW_PG_DEPEND_OID,
7216    desc: RelationDesc::builder()
7217        .with_column("classid", SqlScalarType::Oid.nullable(true))
7218        .with_column("objid", SqlScalarType::Oid.nullable(false))
7219        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7220        .with_column("refclassid", SqlScalarType::Oid.nullable(true))
7221        .with_column("refobjid", SqlScalarType::Oid.nullable(false))
7222        .with_column("refobjsubid", SqlScalarType::Int32.nullable(false))
7223        .with_column("deptype", SqlScalarType::PgLegacyChar.nullable(false))
7224        .finish(),
7225    column_comments: BTreeMap::new(),
7226    sql: "
7227WITH class_objects AS (
7228    SELECT
7229        CASE
7230            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
7231            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
7232            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
7233            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
7234        END classid,
7235        id,
7236        oid,
7237        schema_id
7238    FROM mz_catalog.mz_relations
7239    UNION ALL
7240    SELECT
7241        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
7242        i.id,
7243        i.oid,
7244        r.schema_id
7245    FROM mz_catalog.mz_indexes i
7246    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7247),
7248
7249current_objects AS (
7250    SELECT class_objects.*
7251    FROM class_objects
7252    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7253    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7254    -- This filter is tricky, as it filters out not just objects outside the
7255    -- database, but *dependencies* on objects outside this database. It's not
7256    -- clear that this is the right choice, but because PostgreSQL doesn't
7257    -- support cross-database references, it's not clear that the other choice
7258    -- is better.
7259    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7260)
7261
7262SELECT
7263    objects.classid::pg_catalog.oid,
7264    objects.oid::pg_catalog.oid AS objid,
7265    0::pg_catalog.int4 AS objsubid,
7266    dependents.classid::pg_catalog.oid AS refclassid,
7267    dependents.oid::pg_catalog.oid AS refobjid,
7268    0::pg_catalog.int4 AS refobjsubid,
7269    'n'::pg_catalog.char AS deptype
7270FROM mz_internal.mz_object_dependencies
7271JOIN current_objects objects ON object_id = objects.id
7272JOIN current_objects dependents ON referenced_object_id = dependents.id",
7273    access: vec![PUBLIC_SELECT],
7274});
7275
7276pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7277    name: "pg_database",
7278    schema: PG_CATALOG_SCHEMA,
7279    oid: oid::VIEW_PG_DATABASE_OID,
7280    desc: RelationDesc::builder()
7281        .with_column("oid", SqlScalarType::Oid.nullable(false))
7282        .with_column("datname", SqlScalarType::String.nullable(false))
7283        .with_column("datdba", SqlScalarType::Oid.nullable(false))
7284        .with_column("encoding", SqlScalarType::Int32.nullable(false))
7285        .with_column("datistemplate", SqlScalarType::Bool.nullable(false))
7286        .with_column("datallowconn", SqlScalarType::Bool.nullable(false))
7287        .with_column("datcollate", SqlScalarType::String.nullable(false))
7288        .with_column("datctype", SqlScalarType::String.nullable(false))
7289        .with_column(
7290            "datacl",
7291            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7292        )
7293        .with_key(vec![0])
7294        .finish(),
7295    column_comments: BTreeMap::new(),
7296    sql: "SELECT
7297    d.oid as oid,
7298    d.name as datname,
7299    role_owner.oid as datdba,
7300    6 as encoding,
7301    -- Materialize doesn't support database cloning.
7302    FALSE AS datistemplate,
7303    TRUE AS datallowconn,
7304    'C' as datcollate,
7305    'C' as datctype,
7306    NULL::pg_catalog.text[] as datacl
7307FROM mz_catalog.mz_databases d
7308JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
7309    access: vec![PUBLIC_SELECT],
7310});
7311
7312pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
7313    BuiltinView {
7314        name: "pg_index",
7315        schema: PG_CATALOG_SCHEMA,
7316        oid: oid::VIEW_PG_INDEX_OID,
7317        desc: RelationDesc::builder()
7318            .with_column("indexrelid", SqlScalarType::Oid.nullable(false))
7319            .with_column("indrelid", SqlScalarType::Oid.nullable(false))
7320            .with_column("indnatts", SqlScalarType::Int16.nullable(false))
7321            .with_column("indisunique", SqlScalarType::Bool.nullable(false))
7322            .with_column("indisprimary", SqlScalarType::Bool.nullable(false))
7323            .with_column("indimmediate", SqlScalarType::Bool.nullable(false))
7324            .with_column("indisclustered", SqlScalarType::Bool.nullable(false))
7325            .with_column("indisvalid", SqlScalarType::Bool.nullable(false))
7326            .with_column("indisreplident", SqlScalarType::Bool.nullable(false))
7327            .with_column("indkey", SqlScalarType::Int2Vector.nullable(false))
7328            .with_column("indoption", SqlScalarType::Int2Vector.nullable(false))
7329            .with_column("indexprs", SqlScalarType::String.nullable(true))
7330            .with_column("indpred", SqlScalarType::String.nullable(true))
7331            .with_key(vec![0, 1])
7332            .finish(),
7333        column_comments: BTreeMap::new(),
7334        sql: "SELECT
7335    mz_indexes.oid AS indexrelid,
7336    mz_relations.oid AS indrelid,
7337    COALESCE(
7338        (
7339            SELECT count(*)::pg_catalog.int2
7340            FROM mz_catalog.mz_columns
7341            JOIN mz_catalog.mz_relations mri ON mz_columns.id = mri.id
7342            WHERE mri.oid = mz_catalog.mz_relations.oid
7343        ),
7344        0::pg_catalog.int2
7345    ) AS indnatts,
7346    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7347    false::pg_catalog.bool AS indisunique,
7348    false::pg_catalog.bool AS indisprimary,
7349    -- MZ doesn't support unique indexes so indimmediate is filled with false
7350    false::pg_catalog.bool AS indimmediate,
7351    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7352    false::pg_catalog.bool AS indisclustered,
7353    -- MZ never creates invalid indexes so indisvalid is filled with true
7354    true::pg_catalog.bool AS indisvalid,
7355    -- MZ doesn't support replication so indisreplident is filled with false
7356    false::pg_catalog.bool AS indisreplident,
7357    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7358    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,
7359    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7360    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7361    -- Index expressions are returned in MZ format
7362    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7363    WHEN NULL THEN NULL
7364    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7365    END AS indexprs,
7366    -- MZ doesn't support indexes with predicates
7367    NULL::pg_catalog.text AS indpred
7368FROM mz_catalog.mz_indexes
7369JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7370JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7371JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7372LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7373WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7374GROUP BY mz_indexes.oid, mz_relations.oid",
7375        access: vec![PUBLIC_SELECT],
7376    }
7377});
7378
7379pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7380    name: "pg_indexes",
7381    schema: PG_CATALOG_SCHEMA,
7382    oid: oid::VIEW_PG_INDEXES_OID,
7383    desc: RelationDesc::builder()
7384        .with_column("table_catalog", SqlScalarType::String.nullable(false))
7385        .with_column("schemaname", SqlScalarType::String.nullable(false))
7386        .with_column("tablename", SqlScalarType::String.nullable(false))
7387        .with_column("indexname", SqlScalarType::String.nullable(false))
7388        .with_column("tablespace", SqlScalarType::String.nullable(true))
7389        .with_column("indexdef", SqlScalarType::String.nullable(true))
7390        .finish(),
7391    column_comments: BTreeMap::new(),
7392    sql: "SELECT
7393    current_database() as table_catalog,
7394    s.name AS schemaname,
7395    r.name AS tablename,
7396    i.name AS indexname,
7397    NULL::text AS tablespace,
7398    -- TODO(jkosh44) Fill in with actual index definition.
7399    NULL::text AS indexdef
7400FROM mz_catalog.mz_indexes i
7401JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7402JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7403LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7404WHERE s.database_id IS NULL OR d.name = current_database()",
7405    access: vec![PUBLIC_SELECT],
7406});
7407
7408/// Peeled version of `PG_DESCRIPTION`:
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_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7414    BuiltinView {
7415        name: "pg_description_all_databases",
7416        schema: MZ_INTERNAL_SCHEMA,
7417        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7418        desc: RelationDesc::builder()
7419            .with_column("objoid", SqlScalarType::Oid.nullable(false))
7420            .with_column("classoid", SqlScalarType::Oid.nullable(true))
7421            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7422            .with_column("description", SqlScalarType::String.nullable(false))
7423            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
7424            .with_column("class_database_name", SqlScalarType::String.nullable(true))
7425            .finish(),
7426        column_comments: BTreeMap::new(),
7427        sql: "
7428(
7429    -- Gather all of the class oid's for objects that can have comments.
7430    WITH pg_classoids AS (
7431        SELECT oid, database_name as oid_database_name,
7432          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7433          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7434        FROM mz_internal.pg_class_all_databases
7435        UNION ALL
7436        SELECT oid, database_name as oid_database_name,
7437          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7438          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7439        FROM mz_internal.pg_type_all_databases
7440        UNION ALL
7441        SELECT oid, database_name as oid_database_name,
7442          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7443          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7444        FROM mz_internal.pg_namespace_all_databases
7445    ),
7446
7447    -- Gather all of the MZ ids for objects that can have comments.
7448    mz_objects AS (
7449        SELECT id, oid, type FROM mz_catalog.mz_objects
7450        UNION ALL
7451        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7452    )
7453    SELECT
7454        pg_classoids.oid AS objoid,
7455        pg_classoids.classoid as classoid,
7456        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7457        cmt.comment AS description,
7458        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7459        oid_database_name,
7460        class_database_name
7461    FROM
7462        pg_classoids
7463    JOIN
7464        mz_objects ON pg_classoids.oid = mz_objects.oid
7465    JOIN
7466        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7467)",
7468        access: vec![PUBLIC_SELECT],
7469    }
7470});
7471
7472pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7473    name: "pg_description_all_databases_ind",
7474    schema: MZ_INTERNAL_SCHEMA,
7475    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7476    sql: "IN CLUSTER mz_catalog_server
7477ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7478    is_retained_metrics_object: false,
7479};
7480
7481/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7482/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7483/// which is required for this view.
7484pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7485    name: "pg_description",
7486    schema: PG_CATALOG_SCHEMA,
7487    oid: oid::VIEW_PG_DESCRIPTION_OID,
7488    desc: RelationDesc::builder()
7489        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7490        .with_column("classoid", SqlScalarType::Oid.nullable(true))
7491        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7492        .with_column("description", SqlScalarType::String.nullable(false))
7493        .finish(),
7494    column_comments: BTreeMap::new(),
7495    sql: "
7496SELECT
7497    objoid,
7498    classoid,
7499    objsubid,
7500    description
7501FROM
7502    mz_internal.pg_description_all_databases
7503WHERE
7504    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7505    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7506    access: vec![PUBLIC_SELECT],
7507});
7508
7509/// Peeled version of `PG_TYPE`:
7510/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7511///   in order to make this view indexable.
7512/// - This has the database name as an extra column, so that downstream views can check it against
7513///  `current_database()`.
7514pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7515    BuiltinView {
7516        name: "pg_type_all_databases",
7517        schema: MZ_INTERNAL_SCHEMA,
7518        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7519        desc: RelationDesc::builder()
7520            .with_column("oid", SqlScalarType::Oid.nullable(false))
7521            .with_column("typname", SqlScalarType::String.nullable(false))
7522            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7523            .with_column("typowner", SqlScalarType::Oid.nullable(false))
7524            .with_column("typlen", SqlScalarType::Int16.nullable(true))
7525            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7526            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7527            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7528            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7529            .with_column("typelem", SqlScalarType::Oid.nullable(false))
7530            .with_column("typarray", SqlScalarType::Oid.nullable(false))
7531            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7532            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7533            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7534            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7535            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7536            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7537            .with_column("typdefault", SqlScalarType::String.nullable(true))
7538            .with_column("database_name", SqlScalarType::String.nullable(true))
7539            .finish(),
7540        column_comments: BTreeMap::new(),
7541        sql: "
7542SELECT
7543    mz_types.oid,
7544    mz_types.name AS typname,
7545    mz_schemas.oid AS typnamespace,
7546    role_owner.oid AS typowner,
7547    NULL::pg_catalog.int2 AS typlen,
7548    -- 'a' is used internally to denote an array type, but in postgres they show up
7549    -- as 'b'.
7550    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7551    (CASE category
7552        WHEN 'array' THEN 'A'
7553        WHEN 'bit-string' THEN 'V'
7554        WHEN 'boolean' THEN 'B'
7555        WHEN 'composite' THEN 'C'
7556        WHEN 'date-time' THEN 'D'
7557        WHEN 'enum' THEN 'E'
7558        WHEN 'geometric' THEN 'G'
7559        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7560        WHEN 'network-address' THEN 'I'
7561        WHEN 'numeric' THEN 'N'
7562        WHEN 'pseudo' THEN 'P'
7563        WHEN 'string' THEN 'S'
7564        WHEN 'timespan' THEN 'T'
7565        WHEN 'user-defined' THEN 'U'
7566        WHEN 'unknown' THEN 'X'
7567    END)::pg_catalog.char AS typcategory,
7568    -- In pg only the 'box' type is not ','.
7569    ','::pg_catalog.char AS typdelim,
7570    0::pg_catalog.oid AS typrelid,
7571    coalesce(
7572        (
7573            SELECT t.oid
7574            FROM mz_catalog.mz_array_types a
7575            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7576            WHERE a.id = mz_types.id
7577        ),
7578        (
7579            SELECT t.oid
7580            FROM mz_catalog.mz_list_types l
7581            JOIN mz_catalog.mz_types t ON l.element_id = t.id
7582            WHERE l.id = mz_types.id
7583        ),
7584        0
7585    ) AS typelem,
7586    coalesce(
7587        (
7588            SELECT
7589                t.oid
7590            FROM
7591                mz_catalog.mz_array_types AS a
7592                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7593            WHERE
7594                a.element_id = mz_types.id
7595        ),
7596        0
7597    )
7598        AS typarray,
7599    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7600    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7601    false::pg_catalog.bool AS typnotnull,
7602    0::pg_catalog.oid AS typbasetype,
7603    -1::pg_catalog.int4 AS typtypmod,
7604    -- MZ doesn't support COLLATE so typcollation is filled with 0
7605    0::pg_catalog.oid AS typcollation,
7606    NULL::pg_catalog.text AS typdefault,
7607    d.name as database_name
7608FROM
7609    mz_catalog.mz_types
7610    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7611    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7612    JOIN (
7613            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7614            -- converted to the correct value above.
7615            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7616            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7617            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7618            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7619            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7620        )
7621            AS t ON mz_types.id = t.id
7622    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7623    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7624        access: vec![PUBLIC_SELECT],
7625    }
7626});
7627
7628pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7629    name: "pg_type_all_databases_ind",
7630    schema: MZ_INTERNAL_SCHEMA,
7631    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7632    sql: "IN CLUSTER mz_catalog_server
7633ON mz_internal.pg_type_all_databases (oid)",
7634    is_retained_metrics_object: false,
7635};
7636
7637pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7638    name: "pg_type",
7639    schema: PG_CATALOG_SCHEMA,
7640    oid: oid::VIEW_PG_TYPE_OID,
7641    desc: RelationDesc::builder()
7642        .with_column("oid", SqlScalarType::Oid.nullable(false))
7643        .with_column("typname", SqlScalarType::String.nullable(false))
7644        .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7645        .with_column("typowner", SqlScalarType::Oid.nullable(false))
7646        .with_column("typlen", SqlScalarType::Int16.nullable(true))
7647        .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7648        .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7649        .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7650        .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7651        .with_column("typelem", SqlScalarType::Oid.nullable(false))
7652        .with_column("typarray", SqlScalarType::Oid.nullable(false))
7653        .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7654        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7655        .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7656        .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7657        .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7658        .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7659        .with_column("typdefault", SqlScalarType::String.nullable(true))
7660        .finish(),
7661    column_comments: BTreeMap::new(),
7662    sql: "SELECT
7663    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7664    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7665FROM mz_internal.pg_type_all_databases
7666WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7667    access: vec![PUBLIC_SELECT],
7668});
7669
7670/// Peeled version of `PG_ATTRIBUTE`:
7671/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7672///   in order to make this view indexable.
7673/// - This has 2 extra columns for the database names, so that downstream views can check them
7674///   against `current_database()`.
7675pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7676    BuiltinView {
7677        name: "pg_attribute_all_databases",
7678        schema: MZ_INTERNAL_SCHEMA,
7679        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7680        desc: RelationDesc::builder()
7681            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7682            .with_column("attname", SqlScalarType::String.nullable(false))
7683            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7684            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7685            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7686            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7687            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7688            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7689            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7690            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7691            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7692            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7693            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7694            .with_column("database_name", SqlScalarType::String.nullable(true))
7695            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
7696            .finish(),
7697        column_comments: BTreeMap::new(),
7698        sql: "
7699SELECT
7700    class_objects.oid as attrelid,
7701    mz_columns.name as attname,
7702    mz_columns.type_oid AS atttypid,
7703    pg_type_all_databases.typlen AS attlen,
7704    position::int8::int2 as attnum,
7705    mz_columns.type_mod as atttypmod,
7706    -- dummy value, just to make go-jet's workaround work for now. Discussion:
7707    -- https://github.com/MaterializeInc/materialize/pull/34649#issuecomment-3714291409
7708    0::int2 as attndims,
7709    NOT nullable as attnotnull,
7710    mz_columns.default IS NOT NULL as atthasdef,
7711    ''::pg_catalog.\"char\" as attidentity,
7712    -- MZ doesn't support generated columns so attgenerated is filled with ''
7713    ''::pg_catalog.\"char\" as attgenerated,
7714    FALSE as attisdropped,
7715    -- MZ doesn't support COLLATE so attcollation is filled with 0
7716    0::pg_catalog.oid as attcollation,
7717    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7718    d.name as database_name,
7719    pg_type_all_databases.database_name as pg_type_database_name
7720FROM (
7721    -- pg_attribute catalogs columns on relations and indexes
7722    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7723    UNION ALL
7724        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7725        FROM mz_catalog.mz_indexes
7726        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7727) AS class_objects
7728JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7729JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7730JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7731LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7732        // Since this depends on pg_type, its id must be higher due to initialization
7733        // ordering.
7734        access: vec![PUBLIC_SELECT],
7735    }
7736});
7737
7738pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7739    name: "pg_attribute_all_databases_ind",
7740    schema: MZ_INTERNAL_SCHEMA,
7741    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7742    sql: "IN CLUSTER mz_catalog_server
7743ON mz_internal.pg_attribute_all_databases (
7744    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7745    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7746)",
7747    is_retained_metrics_object: false,
7748};
7749
7750/// <https://www.postgresql.org/docs/current/catalog-pg-attribute.html>
7751pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7752    BuiltinView {
7753        name: "pg_attribute",
7754        schema: PG_CATALOG_SCHEMA,
7755        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7756        desc: RelationDesc::builder()
7757            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7758            .with_column("attname", SqlScalarType::String.nullable(false))
7759            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7760            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7761            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7762            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7763            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7764            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7765            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7766            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7767            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7768            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7769            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7770            .finish(),
7771        column_comments: BTreeMap::new(),
7772        sql: "
7773SELECT
7774    attrelid, attname, atttypid, attlen, attnum, atttypmod, attndims, attnotnull, atthasdef,
7775    attidentity, attgenerated, attisdropped, attcollation
7776FROM mz_internal.pg_attribute_all_databases
7777WHERE
7778  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7779  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7780        // Since this depends on pg_type, its id must be higher due to initialization
7781        // ordering.
7782        access: vec![PUBLIC_SELECT],
7783    }
7784});
7785
7786pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7787    name: "pg_proc",
7788    schema: PG_CATALOG_SCHEMA,
7789    oid: oid::VIEW_PG_PROC_OID,
7790    desc: RelationDesc::builder()
7791        .with_column("oid", SqlScalarType::Oid.nullable(false))
7792        .with_column("proname", SqlScalarType::String.nullable(false))
7793        .with_column("pronamespace", SqlScalarType::Oid.nullable(false))
7794        .with_column("proowner", SqlScalarType::Oid.nullable(false))
7795        .with_column("proargdefaults", SqlScalarType::String.nullable(true))
7796        .with_column("prorettype", SqlScalarType::Oid.nullable(false))
7797        .finish(),
7798    column_comments: BTreeMap::new(),
7799    sql: "SELECT
7800    mz_functions.oid,
7801    mz_functions.name AS proname,
7802    mz_schemas.oid AS pronamespace,
7803    role_owner.oid AS proowner,
7804    NULL::pg_catalog.text AS proargdefaults,
7805    ret_type.oid AS prorettype
7806FROM mz_catalog.mz_functions
7807JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7808LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7809JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7810JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7811WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7812    access: vec![PUBLIC_SELECT],
7813});
7814
7815pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7816    name: "pg_operator",
7817    schema: PG_CATALOG_SCHEMA,
7818    oid: oid::VIEW_PG_OPERATOR_OID,
7819    desc: RelationDesc::builder()
7820        .with_column("oid", SqlScalarType::Oid.nullable(false))
7821        .with_column("oprname", SqlScalarType::String.nullable(false))
7822        .with_column("oprresult", SqlScalarType::Oid.nullable(false))
7823        .with_column("oprleft", SqlScalarType::Oid.nullable(false))
7824        .with_column("oprright", SqlScalarType::Oid.nullable(false))
7825        .with_key(vec![0, 1, 2, 3, 4])
7826        .finish(),
7827    column_comments: BTreeMap::new(),
7828    sql: "SELECT
7829    mz_operators.oid,
7830    mz_operators.name AS oprname,
7831    ret_type.oid AS oprresult,
7832    left_type.oid as oprleft,
7833    right_type.oid as oprright
7834FROM mz_catalog.mz_operators
7835JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7836JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7837JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7838WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7839UNION SELECT
7840    mz_operators.oid,
7841    mz_operators.name AS oprname,
7842    ret_type.oid AS oprresult,
7843    0 as oprleft,
7844    right_type.oid as oprright
7845FROM mz_catalog.mz_operators
7846JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7847JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7848WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7849    access: vec![PUBLIC_SELECT],
7850});
7851
7852pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7853    name: "pg_range",
7854    schema: PG_CATALOG_SCHEMA,
7855    oid: oid::VIEW_PG_RANGE_OID,
7856    desc: RelationDesc::builder()
7857        .with_column("rngtypid", SqlScalarType::Oid.nullable(false))
7858        .with_column("rngsubtype", SqlScalarType::Oid.nullable(false))
7859        .with_key(vec![])
7860        .finish(),
7861    column_comments: BTreeMap::new(),
7862    sql: "SELECT
7863    NULL::pg_catalog.oid AS rngtypid,
7864    NULL::pg_catalog.oid AS rngsubtype
7865WHERE false",
7866    access: vec![PUBLIC_SELECT],
7867});
7868
7869pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7870    name: "pg_enum",
7871    schema: PG_CATALOG_SCHEMA,
7872    oid: oid::VIEW_PG_ENUM_OID,
7873    desc: RelationDesc::builder()
7874        .with_column("oid", SqlScalarType::Oid.nullable(false))
7875        .with_column("enumtypid", SqlScalarType::Oid.nullable(false))
7876        .with_column("enumsortorder", SqlScalarType::Float32.nullable(false))
7877        .with_column("enumlabel", SqlScalarType::String.nullable(false))
7878        .with_key(vec![])
7879        .finish(),
7880    column_comments: BTreeMap::new(),
7881    sql: "SELECT
7882    NULL::pg_catalog.oid AS oid,
7883    NULL::pg_catalog.oid AS enumtypid,
7884    NULL::pg_catalog.float4 AS enumsortorder,
7885    NULL::pg_catalog.text AS enumlabel
7886WHERE false",
7887    access: vec![PUBLIC_SELECT],
7888});
7889
7890/// Peeled version of `PG_ATTRDEF`:
7891/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7892///   in order to make this view indexable.
7893pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7894    name: "pg_attrdef_all_databases",
7895    schema: MZ_INTERNAL_SCHEMA,
7896    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
7897    desc: RelationDesc::builder()
7898        .with_column("oid", SqlScalarType::Oid.nullable(true))
7899        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7900        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7901        .with_column("adbin", SqlScalarType::String.nullable(false))
7902        .with_column("adsrc", SqlScalarType::String.nullable(false))
7903        .finish(),
7904    column_comments: BTreeMap::new(),
7905    sql: "
7906SELECT
7907    NULL::pg_catalog.oid AS oid,
7908    mz_objects.oid AS adrelid,
7909    mz_columns.position::int8 AS adnum,
7910    mz_columns.default AS adbin,
7911    mz_columns.default AS adsrc
7912FROM mz_catalog.mz_columns
7913    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
7914WHERE default IS NOT NULL",
7915    access: vec![PUBLIC_SELECT],
7916});
7917
7918pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7919    name: "pg_attrdef_all_databases_ind",
7920    schema: MZ_INTERNAL_SCHEMA,
7921    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
7922    sql: "IN CLUSTER mz_catalog_server
7923ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
7924    is_retained_metrics_object: false,
7925};
7926
7927pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7928    name: "pg_attrdef",
7929    schema: PG_CATALOG_SCHEMA,
7930    oid: oid::VIEW_PG_ATTRDEF_OID,
7931    desc: RelationDesc::builder()
7932        .with_column("oid", SqlScalarType::Oid.nullable(true))
7933        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7934        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7935        .with_column("adbin", SqlScalarType::String.nullable(false))
7936        .with_column("adsrc", SqlScalarType::String.nullable(false))
7937        .finish(),
7938    column_comments: BTreeMap::new(),
7939    sql: "
7940SELECT
7941    pg_attrdef_all_databases.oid as oid,
7942    adrelid,
7943    adnum,
7944    adbin,
7945    adsrc
7946FROM mz_internal.pg_attrdef_all_databases
7947    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
7948    access: vec![PUBLIC_SELECT],
7949});
7950
7951pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7952    name: "pg_settings",
7953    schema: PG_CATALOG_SCHEMA,
7954    oid: oid::VIEW_PG_SETTINGS_OID,
7955    desc: RelationDesc::builder()
7956        .with_column("name", SqlScalarType::String.nullable(false))
7957        .with_column("setting", SqlScalarType::String.nullable(false))
7958        .with_key(vec![])
7959        .finish(),
7960    column_comments: BTreeMap::new(),
7961    sql: "SELECT
7962    name, setting
7963FROM (VALUES
7964    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
7965) AS _ (name, setting)",
7966    access: vec![PUBLIC_SELECT],
7967});
7968
7969pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7970    name: "pg_auth_members",
7971    schema: PG_CATALOG_SCHEMA,
7972    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
7973    desc: RelationDesc::builder()
7974        .with_column("roleid", SqlScalarType::Oid.nullable(false))
7975        .with_column("member", SqlScalarType::Oid.nullable(false))
7976        .with_column("grantor", SqlScalarType::Oid.nullable(false))
7977        .with_column("admin_option", SqlScalarType::Bool.nullable(false))
7978        .finish(),
7979    column_comments: BTreeMap::new(),
7980    sql: "SELECT
7981    role.oid AS roleid,
7982    member.oid AS member,
7983    grantor.oid AS grantor,
7984    -- Materialize hasn't implemented admin_option.
7985    false as admin_option
7986FROM mz_catalog.mz_role_members membership
7987JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
7988JOIN mz_catalog.mz_roles member ON membership.member = member.id
7989JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
7990    access: vec![PUBLIC_SELECT],
7991});
7992
7993pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7994    name: "pg_event_trigger",
7995    schema: PG_CATALOG_SCHEMA,
7996    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
7997    desc: RelationDesc::builder()
7998        .with_column("oid", SqlScalarType::Oid.nullable(false))
7999        .with_column("evtname", SqlScalarType::String.nullable(false))
8000        .with_column("evtevent", SqlScalarType::String.nullable(false))
8001        .with_column("evtowner", SqlScalarType::Oid.nullable(false))
8002        .with_column("evtfoid", SqlScalarType::Oid.nullable(false))
8003        .with_column("evtenabled", SqlScalarType::PgLegacyChar.nullable(false))
8004        .with_column(
8005            "evttags",
8006            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
8007        )
8008        .with_key(vec![])
8009        .finish(),
8010    column_comments: BTreeMap::new(),
8011    sql: "SELECT
8012        NULL::pg_catalog.oid AS oid,
8013        NULL::pg_catalog.text AS evtname,
8014        NULL::pg_catalog.text AS evtevent,
8015        NULL::pg_catalog.oid AS evtowner,
8016        NULL::pg_catalog.oid AS evtfoid,
8017        NULL::pg_catalog.char AS evtenabled,
8018        NULL::pg_catalog.text[] AS evttags
8019    WHERE false",
8020    access: vec![PUBLIC_SELECT],
8021});
8022
8023pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8024    name: "pg_language",
8025    schema: PG_CATALOG_SCHEMA,
8026    oid: oid::VIEW_PG_LANGUAGE_OID,
8027    desc: RelationDesc::builder()
8028        .with_column("oid", SqlScalarType::Oid.nullable(false))
8029        .with_column("lanname", SqlScalarType::String.nullable(false))
8030        .with_column("lanowner", SqlScalarType::Oid.nullable(false))
8031        .with_column("lanispl", SqlScalarType::Bool.nullable(false))
8032        .with_column("lanpltrusted", SqlScalarType::Bool.nullable(false))
8033        .with_column("lanplcallfoid", SqlScalarType::Oid.nullable(false))
8034        .with_column("laninline", SqlScalarType::Oid.nullable(false))
8035        .with_column("lanvalidator", SqlScalarType::Oid.nullable(false))
8036        .with_column(
8037            "lanacl",
8038            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
8039        )
8040        .with_key(vec![])
8041        .finish(),
8042    column_comments: BTreeMap::new(),
8043    sql: "SELECT
8044        NULL::pg_catalog.oid  AS oid,
8045        NULL::pg_catalog.text AS lanname,
8046        NULL::pg_catalog.oid  AS lanowner,
8047        NULL::pg_catalog.bool AS lanispl,
8048        NULL::pg_catalog.bool AS lanpltrusted,
8049        NULL::pg_catalog.oid  AS lanplcallfoid,
8050        NULL::pg_catalog.oid  AS laninline,
8051        NULL::pg_catalog.oid  AS lanvalidator,
8052        NULL::pg_catalog.text[] AS lanacl
8053    WHERE false",
8054    access: vec![PUBLIC_SELECT],
8055});
8056
8057pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8058    name: "pg_shdescription",
8059    schema: PG_CATALOG_SCHEMA,
8060    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
8061    desc: RelationDesc::builder()
8062        .with_column("objoid", SqlScalarType::Oid.nullable(false))
8063        .with_column("classoid", SqlScalarType::Oid.nullable(false))
8064        .with_column("description", SqlScalarType::String.nullable(false))
8065        .with_key(vec![])
8066        .finish(),
8067    column_comments: BTreeMap::new(),
8068    sql: "SELECT
8069        NULL::pg_catalog.oid AS objoid,
8070        NULL::pg_catalog.oid AS classoid,
8071        NULL::pg_catalog.text AS description
8072    WHERE false",
8073    access: vec![PUBLIC_SELECT],
8074});
8075
8076pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
8077    BuiltinView {
8078        name: "pg_timezone_abbrevs",
8079        schema: PG_CATALOG_SCHEMA,
8080        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
8081        desc: RelationDesc::builder()
8082            .with_column("abbrev", SqlScalarType::String.nullable(false))
8083            .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8084            .with_column("is_dst", SqlScalarType::Bool.nullable(true))
8085            .with_key(vec![0])
8086            .finish(),
8087        column_comments: BTreeMap::new(),
8088        sql: "SELECT
8089    abbreviation AS abbrev,
8090    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
8091        AS utc_offset,
8092    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
8093        AS is_dst
8094FROM mz_catalog.mz_timezone_abbreviations",
8095        access: vec![PUBLIC_SELECT],
8096    }
8097});
8098
8099pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8100    name: "pg_timezone_names",
8101    schema: PG_CATALOG_SCHEMA,
8102    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
8103    desc: RelationDesc::builder()
8104        .with_column("name", SqlScalarType::String.nullable(false))
8105        .with_column("abbrev", SqlScalarType::String.nullable(true))
8106        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8107        .with_column("is_dst", SqlScalarType::Bool.nullable(true))
8108        .with_key(vec![0])
8109        .finish(),
8110    column_comments: BTreeMap::new(),
8111    sql: "SELECT
8112    name,
8113    timezone_offset(name, now()).abbrev AS abbrev,
8114    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
8115        AS utc_offset,
8116    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
8117        AS is_dst
8118FROM mz_catalog.mz_timezone_names",
8119    access: vec![PUBLIC_SELECT],
8120});
8121
8122pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8123    name: "mz_timezone_abbreviations",
8124    schema: MZ_CATALOG_SCHEMA,
8125    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
8126    desc: RelationDesc::builder()
8127        .with_column("abbreviation", SqlScalarType::String.nullable(false))
8128        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8129        .with_column("dst", SqlScalarType::Bool.nullable(true))
8130        .with_column("timezone_name", SqlScalarType::String.nullable(true))
8131        .with_key(vec![0])
8132        .finish(),
8133    column_comments: BTreeMap::from_iter([
8134        ("abbreviation", "The timezone abbreviation."),
8135        (
8136            "utc_offset",
8137            "The UTC offset of the timezone or `NULL` if fixed.",
8138        ),
8139        (
8140            "dst",
8141            "Whether the timezone is in daylight savings or `NULL` if fixed.",
8142        ),
8143        (
8144            "timezone_name",
8145            "The full name of the non-fixed timezone or `NULL` if not fixed.",
8146        ),
8147    ]),
8148    sql: format!(
8149        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
8150        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
8151    )
8152    .leak(),
8153    access: vec![PUBLIC_SELECT],
8154});
8155
8156pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8157    name: "mz_timezone_names",
8158    schema: MZ_CATALOG_SCHEMA,
8159    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
8160    desc: RelationDesc::builder()
8161        .with_column("name", SqlScalarType::String.nullable(false))
8162        .with_key(vec![0])
8163        .finish(),
8164    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
8165    sql: format!(
8166        "SELECT * FROM ({}) _ (name)",
8167        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
8168    )
8169    .leak(),
8170    access: vec![PUBLIC_SELECT],
8171});
8172
8173pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8174    LazyLock::new(|| BuiltinView {
8175        name: "mz_peek_durations_histogram_per_worker",
8176        schema: MZ_INTROSPECTION_SCHEMA,
8177        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8178        desc: RelationDesc::builder()
8179            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8180            .with_column("type", SqlScalarType::String.nullable(false))
8181            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8182            .with_column("count", SqlScalarType::Int64.nullable(false))
8183            .with_key(vec![0, 1, 2])
8184            .finish(),
8185        column_comments: BTreeMap::new(),
8186        sql: "SELECT
8187    worker_id, type, duration_ns, pg_catalog.count(*) AS count
8188FROM
8189    mz_introspection.mz_peek_durations_histogram_raw
8190GROUP BY
8191    worker_id, type, duration_ns",
8192        access: vec![PUBLIC_SELECT],
8193    });
8194
8195pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8196    name: "mz_peek_durations_histogram",
8197    schema: MZ_INTROSPECTION_SCHEMA,
8198    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
8199    desc: RelationDesc::builder()
8200        .with_column("type", SqlScalarType::String.nullable(false))
8201        .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8202        .with_column(
8203            "count",
8204            SqlScalarType::Numeric {
8205                max_scale: Some(NumericMaxScale::ZERO),
8206            }
8207            .nullable(false),
8208        )
8209        .with_key(vec![0, 1])
8210        .finish(),
8211    column_comments: BTreeMap::from_iter([
8212        ("type", "The peek variant: `index` or `persist`."),
8213        (
8214            "duration_ns",
8215            "The upper bound of the bucket in nanoseconds.",
8216        ),
8217        (
8218            "count",
8219            "The (noncumulative) count of peeks in this bucket.",
8220        ),
8221    ]),
8222    sql: "
8223SELECT
8224    type, duration_ns,
8225    pg_catalog.sum(count) AS count
8226FROM mz_introspection.mz_peek_durations_histogram_per_worker
8227GROUP BY type, duration_ns",
8228    access: vec![PUBLIC_SELECT],
8229});
8230
8231pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
8232    LazyLock::new(|| BuiltinView {
8233        name: "mz_scheduling_elapsed_per_worker",
8234        schema: MZ_INTROSPECTION_SCHEMA,
8235        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
8236        desc: RelationDesc::builder()
8237            .with_column("id", SqlScalarType::UInt64.nullable(false))
8238            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8239            .with_column("elapsed_ns", SqlScalarType::Int64.nullable(false))
8240            .with_key(vec![0, 1])
8241            .finish(),
8242        column_comments: BTreeMap::new(),
8243        sql: "SELECT
8244    id, worker_id, pg_catalog.count(*) AS elapsed_ns
8245FROM
8246    mz_introspection.mz_scheduling_elapsed_raw
8247GROUP BY
8248    id, worker_id",
8249        access: vec![PUBLIC_SELECT],
8250    });
8251
8252pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8253    name: "mz_scheduling_elapsed",
8254    schema: MZ_INTROSPECTION_SCHEMA,
8255    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
8256    desc: RelationDesc::builder()
8257        .with_column("id", SqlScalarType::UInt64.nullable(false))
8258        .with_column(
8259            "elapsed_ns",
8260            SqlScalarType::Numeric {
8261                max_scale: Some(NumericMaxScale::ZERO),
8262            }
8263            .nullable(false),
8264        )
8265        .with_key(vec![0])
8266        .finish(),
8267    column_comments: BTreeMap::from_iter([
8268        (
8269            "id",
8270            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8271        ),
8272        (
8273            "elapsed_ns",
8274            "The total elapsed time spent in the operator in nanoseconds.",
8275        ),
8276    ]),
8277    sql: "
8278SELECT
8279    id,
8280    pg_catalog.sum(elapsed_ns) AS elapsed_ns
8281FROM mz_introspection.mz_scheduling_elapsed_per_worker
8282GROUP BY id",
8283    access: vec![PUBLIC_SELECT],
8284});
8285
8286pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8287    LazyLock::new(|| BuiltinView {
8288        name: "mz_compute_operator_durations_histogram_per_worker",
8289        schema: MZ_INTROSPECTION_SCHEMA,
8290        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8291        desc: RelationDesc::builder()
8292            .with_column("id", SqlScalarType::UInt64.nullable(false))
8293            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8294            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8295            .with_column("count", SqlScalarType::Int64.nullable(false))
8296            .with_key(vec![0, 1, 2])
8297            .finish(),
8298        column_comments: BTreeMap::new(),
8299        sql: "SELECT
8300    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8301FROM
8302    mz_introspection.mz_compute_operator_durations_histogram_raw
8303GROUP BY
8304    id, worker_id, duration_ns",
8305        access: vec![PUBLIC_SELECT],
8306    });
8307
8308pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8309    LazyLock::new(|| BuiltinView {
8310        name: "mz_compute_operator_durations_histogram",
8311        schema: MZ_INTROSPECTION_SCHEMA,
8312        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8313        desc: RelationDesc::builder()
8314            .with_column("id", SqlScalarType::UInt64.nullable(false))
8315            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8316            .with_column(
8317                "count",
8318                SqlScalarType::Numeric {
8319                    max_scale: Some(NumericMaxScale::ZERO),
8320                }
8321                .nullable(false),
8322            )
8323            .with_key(vec![0, 1])
8324            .finish(),
8325        column_comments: BTreeMap::from_iter([
8326            (
8327                "id",
8328                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8329            ),
8330            (
8331                "duration_ns",
8332                "The upper bound of the duration bucket in nanoseconds.",
8333            ),
8334            (
8335                "count",
8336                "The (noncumulative) count of invocations in the bucket.",
8337            ),
8338        ]),
8339        sql: "
8340SELECT
8341    id,
8342    duration_ns,
8343    pg_catalog.sum(count) AS count
8344FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8345GROUP BY id, duration_ns",
8346        access: vec![PUBLIC_SELECT],
8347    });
8348
8349pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8350    LazyLock::new(|| BuiltinView {
8351        name: "mz_scheduling_parks_histogram_per_worker",
8352        schema: MZ_INTROSPECTION_SCHEMA,
8353        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8354        desc: RelationDesc::builder()
8355            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8356            .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8357            .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8358            .with_column("count", SqlScalarType::Int64.nullable(false))
8359            .with_key(vec![0, 1, 2])
8360            .finish(),
8361        column_comments: BTreeMap::new(),
8362        sql: "SELECT
8363    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8364FROM
8365    mz_introspection.mz_scheduling_parks_histogram_raw
8366GROUP BY
8367    worker_id, slept_for_ns, requested_ns",
8368        access: vec![PUBLIC_SELECT],
8369    });
8370
8371pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8372    name: "mz_scheduling_parks_histogram",
8373    schema: MZ_INTROSPECTION_SCHEMA,
8374    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8375    desc: RelationDesc::builder()
8376        .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8377        .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8378        .with_column(
8379            "count",
8380            SqlScalarType::Numeric {
8381                max_scale: Some(NumericMaxScale::ZERO),
8382            }
8383            .nullable(false),
8384        )
8385        .with_key(vec![0, 1])
8386        .finish(),
8387    column_comments: BTreeMap::from_iter([
8388        (
8389            "slept_for_ns",
8390            "The actual length of the park event in nanoseconds.",
8391        ),
8392        (
8393            "requested_ns",
8394            "The requested length of the park event in nanoseconds.",
8395        ),
8396        (
8397            "count",
8398            "The (noncumulative) count of park events in this bucket.",
8399        ),
8400    ]),
8401    sql: "
8402SELECT
8403    slept_for_ns,
8404    requested_ns,
8405    pg_catalog.sum(count) AS count
8406FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8407GROUP BY slept_for_ns, requested_ns",
8408    access: vec![PUBLIC_SELECT],
8409});
8410
8411pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8412    LazyLock::new(|| BuiltinView {
8413        name: "mz_compute_error_counts_per_worker",
8414        schema: MZ_INTROSPECTION_SCHEMA,
8415        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8416        desc: RelationDesc::builder()
8417            .with_column("export_id", SqlScalarType::String.nullable(false))
8418            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8419            .with_column("count", SqlScalarType::Int64.nullable(false))
8420            .with_key(vec![0, 1, 2])
8421            .finish(),
8422        column_comments: BTreeMap::new(),
8423        sql: "
8424WITH MUTUALLY RECURSIVE
8425    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8426    -- For these we don't log error counts separately, so we need to forward the error counts from
8427    -- their dependencies instead.
8428    index_reuses(reuse_id text, index_id text) AS (
8429        SELECT d.object_id, d.dependency_id
8430        FROM mz_internal.mz_compute_dependencies d
8431        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8432        WHERE NOT EXISTS (
8433            SELECT 1 FROM mz_introspection.mz_dataflows
8434            WHERE id = e.dataflow_id
8435        )
8436    ),
8437    -- Error counts that were directly logged on compute exports.
8438    direct_errors(export_id text, worker_id uint8, count int8) AS (
8439        SELECT export_id, worker_id, count
8440        FROM mz_introspection.mz_compute_error_counts_raw
8441    ),
8442    -- Error counts propagated to index reused.
8443    all_errors(export_id text, worker_id uint8, count int8) AS (
8444        SELECT * FROM direct_errors
8445        UNION
8446        SELECT r.reuse_id, e.worker_id, e.count
8447        FROM all_errors e
8448        JOIN index_reuses r ON (r.index_id = e.export_id)
8449    )
8450SELECT * FROM all_errors",
8451        access: vec![PUBLIC_SELECT],
8452    });
8453
8454pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8455    name: "mz_compute_error_counts",
8456    schema: MZ_INTROSPECTION_SCHEMA,
8457    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8458    desc: RelationDesc::builder()
8459        .with_column("export_id", SqlScalarType::String.nullable(false))
8460        .with_column(
8461            "count",
8462            SqlScalarType::Numeric {
8463                max_scale: Some(NumericMaxScale::ZERO),
8464            }
8465            .nullable(false),
8466        )
8467        .with_key(vec![0])
8468        .finish(),
8469    column_comments: BTreeMap::from_iter([
8470        (
8471            "export_id",
8472            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8473        ),
8474        (
8475            "count",
8476            "The count of errors present in this dataflow export.",
8477        ),
8478    ]),
8479    sql: "
8480SELECT
8481    export_id,
8482    pg_catalog.sum(count) AS count
8483FROM mz_introspection.mz_compute_error_counts_per_worker
8484GROUP BY export_id
8485HAVING pg_catalog.sum(count) != 0",
8486    access: vec![PUBLIC_SELECT],
8487});
8488
8489pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8490    LazyLock::new(|| BuiltinSource {
8491        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8492        // naming conflict because the resolver stumbles over the source with the same name in
8493        // `mz_introspection` due to the automatic schema translation.
8494        name: "mz_compute_error_counts_raw_unified",
8495        schema: MZ_INTERNAL_SCHEMA,
8496        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8497        desc: RelationDesc::builder()
8498            .with_column("replica_id", SqlScalarType::String.nullable(false))
8499            .with_column("object_id", SqlScalarType::String.nullable(false))
8500            .with_column(
8501                "count",
8502                SqlScalarType::Numeric { max_scale: None }.nullable(false),
8503            )
8504            .finish(),
8505        data_source: IntrospectionType::ComputeErrorCounts.into(),
8506        column_comments: BTreeMap::new(),
8507        is_retained_metrics_object: false,
8508        access: vec![PUBLIC_SELECT],
8509    });
8510
8511pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8512    name: "mz_compute_hydration_times",
8513    schema: MZ_INTERNAL_SCHEMA,
8514    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8515    desc: RelationDesc::builder()
8516        .with_column("replica_id", SqlScalarType::String.nullable(false))
8517        .with_column("object_id", SqlScalarType::String.nullable(false))
8518        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
8519        .finish(),
8520    data_source: IntrospectionType::ComputeHydrationTimes.into(),
8521    column_comments: BTreeMap::new(),
8522    is_retained_metrics_object: true,
8523    access: vec![PUBLIC_SELECT],
8524});
8525
8526pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8527    LazyLock::new(|| BuiltinIndex {
8528        name: "mz_compute_hydration_times_ind",
8529        schema: MZ_INTERNAL_SCHEMA,
8530        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8531        sql: "IN CLUSTER mz_catalog_server
8532    ON mz_internal.mz_compute_hydration_times (replica_id)",
8533        is_retained_metrics_object: true,
8534    });
8535
8536pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8537    name: "mz_compute_hydration_statuses",
8538    schema: MZ_INTERNAL_SCHEMA,
8539    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8540    desc: RelationDesc::builder()
8541        .with_column("object_id", SqlScalarType::String.nullable(false))
8542        .with_column("replica_id", SqlScalarType::String.nullable(false))
8543        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8544        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
8545        .finish(),
8546    column_comments: BTreeMap::from_iter([
8547        (
8548            "object_id",
8549            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8550        ),
8551        ("replica_id", "The ID of a cluster replica."),
8552        (
8553            "hydrated",
8554            "Whether the compute object is hydrated on the replica.",
8555        ),
8556        (
8557            "hydration_time",
8558            "The amount of time it took for the replica to hydrate the compute object.",
8559        ),
8560    ]),
8561    sql: "
8562WITH
8563    dataflows AS (
8564        SELECT
8565            object_id,
8566            replica_id,
8567            time_ns IS NOT NULL AS hydrated,
8568            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8569        FROM mz_internal.mz_compute_hydration_times
8570    ),
8571    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8572    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8573    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8574    -- blue-green readiness query does), so we include them as 'hydrated'.
8575    complete_mvs AS (
8576        SELECT
8577            mv.id,
8578            f.replica_id,
8579            true AS hydrated,
8580            NULL::interval AS hydration_time
8581        FROM mz_materialized_views mv
8582        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8583        WHERE f.write_frontier IS NULL
8584    )
8585SELECT * FROM dataflows
8586UNION ALL
8587SELECT * FROM complete_mvs",
8588    access: vec![PUBLIC_SELECT],
8589});
8590
8591pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
8592    BuiltinSource {
8593        name: "mz_compute_operator_hydration_statuses",
8594        schema: MZ_INTERNAL_SCHEMA,
8595        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8596        desc: RelationDesc::builder()
8597            .with_column("replica_id", SqlScalarType::String.nullable(false))
8598            .with_column("object_id", SqlScalarType::String.nullable(false))
8599            .with_column(
8600                "physical_plan_node_id",
8601                SqlScalarType::UInt64.nullable(false),
8602            )
8603            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8604            .with_key(vec![0, 1, 2])
8605            .finish(),
8606        data_source: IntrospectionType::ComputeOperatorHydrationStatus.into(),
8607        column_comments: BTreeMap::from_iter([
8608            ("replica_id", "The ID of a cluster replica."),
8609            (
8610                "object_id",
8611                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8612            ),
8613            (
8614                "physical_plan_node_id",
8615                "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)`.",
8616            ),
8617            ("hydrated", "Whether the node is hydrated on the replica."),
8618        ]),
8619        is_retained_metrics_object: false,
8620        access: vec![PUBLIC_SELECT],
8621    }
8622});
8623
8624pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8625    name: "mz_message_counts_per_worker",
8626    schema: MZ_INTROSPECTION_SCHEMA,
8627    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8628    desc: RelationDesc::builder()
8629        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8630        .with_column("from_worker_id", SqlScalarType::UInt64.nullable(false))
8631        .with_column("to_worker_id", SqlScalarType::UInt64.nullable(false))
8632        .with_column("sent", SqlScalarType::Int64.nullable(false))
8633        .with_column("received", SqlScalarType::Int64.nullable(false))
8634        .with_column("batch_sent", SqlScalarType::Int64.nullable(false))
8635        .with_column("batch_received", SqlScalarType::Int64.nullable(false))
8636        .with_key(vec![0, 1, 2])
8637        .finish(),
8638    column_comments: BTreeMap::new(),
8639    sql: "
8640WITH batch_sent_cte AS (
8641    SELECT
8642        channel_id,
8643        from_worker_id,
8644        to_worker_id,
8645        pg_catalog.count(*) AS sent
8646    FROM
8647        mz_introspection.mz_message_batch_counts_sent_raw
8648    GROUP BY
8649        channel_id, from_worker_id, to_worker_id
8650),
8651batch_received_cte AS (
8652    SELECT
8653        channel_id,
8654        from_worker_id,
8655        to_worker_id,
8656        pg_catalog.count(*) AS received
8657    FROM
8658        mz_introspection.mz_message_batch_counts_received_raw
8659    GROUP BY
8660        channel_id, from_worker_id, to_worker_id
8661),
8662sent_cte AS (
8663    SELECT
8664        channel_id,
8665        from_worker_id,
8666        to_worker_id,
8667        pg_catalog.count(*) AS sent
8668    FROM
8669        mz_introspection.mz_message_counts_sent_raw
8670    GROUP BY
8671        channel_id, from_worker_id, to_worker_id
8672),
8673received_cte AS (
8674    SELECT
8675        channel_id,
8676        from_worker_id,
8677        to_worker_id,
8678        pg_catalog.count(*) AS received
8679    FROM
8680        mz_introspection.mz_message_counts_received_raw
8681    GROUP BY
8682        channel_id, from_worker_id, to_worker_id
8683)
8684SELECT
8685    sent_cte.channel_id,
8686    sent_cte.from_worker_id,
8687    sent_cte.to_worker_id,
8688    sent_cte.sent,
8689    received_cte.received,
8690    batch_sent_cte.sent AS batch_sent,
8691    batch_received_cte.received AS batch_received
8692FROM sent_cte
8693JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8694JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8695JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8696    access: vec![PUBLIC_SELECT],
8697});
8698
8699pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8700    name: "mz_message_counts",
8701    schema: MZ_INTROSPECTION_SCHEMA,
8702    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8703    desc: RelationDesc::builder()
8704        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8705        .with_column(
8706            "sent",
8707            SqlScalarType::Numeric {
8708                max_scale: Some(NumericMaxScale::ZERO),
8709            }
8710            .nullable(false),
8711        )
8712        .with_column(
8713            "received",
8714            SqlScalarType::Numeric {
8715                max_scale: Some(NumericMaxScale::ZERO),
8716            }
8717            .nullable(false),
8718        )
8719        .with_column(
8720            "batch_sent",
8721            SqlScalarType::Numeric {
8722                max_scale: Some(NumericMaxScale::ZERO),
8723            }
8724            .nullable(false),
8725        )
8726        .with_column(
8727            "batch_received",
8728            SqlScalarType::Numeric {
8729                max_scale: Some(NumericMaxScale::ZERO),
8730            }
8731            .nullable(false),
8732        )
8733        .with_key(vec![0])
8734        .finish(),
8735    column_comments: BTreeMap::from_iter([
8736        (
8737            "channel_id",
8738            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8739        ),
8740        ("sent", "The number of messages sent."),
8741        ("received", "The number of messages received."),
8742        ("batch_sent", "The number of batches sent."),
8743        ("batch_received", "The number of batches received."),
8744    ]),
8745    sql: "
8746SELECT
8747    channel_id,
8748    pg_catalog.sum(sent) AS sent,
8749    pg_catalog.sum(received) AS received,
8750    pg_catalog.sum(batch_sent) AS batch_sent,
8751    pg_catalog.sum(batch_received) AS batch_received
8752FROM mz_introspection.mz_message_counts_per_worker
8753GROUP BY channel_id",
8754    access: vec![PUBLIC_SELECT],
8755});
8756
8757pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8758    name: "mz_active_peeks",
8759    schema: MZ_INTROSPECTION_SCHEMA,
8760    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8761    desc: RelationDesc::builder()
8762        .with_column("id", SqlScalarType::Uuid.nullable(false))
8763        .with_column("object_id", SqlScalarType::String.nullable(false))
8764        .with_column("type", SqlScalarType::String.nullable(false))
8765        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
8766        .with_key(vec![0])
8767        .finish(),
8768    column_comments: BTreeMap::from_iter([
8769        ("id", "The ID of the peek request."),
8770        (
8771            "object_id",
8772            "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`.",
8773        ),
8774        (
8775            "type",
8776            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8777        ),
8778        ("time", "The timestamp the peek has requested."),
8779    ]),
8780    sql: "
8781SELECT id, object_id, type, time
8782FROM mz_introspection.mz_active_peeks_per_worker
8783WHERE worker_id = 0::uint8",
8784    access: vec![PUBLIC_SELECT],
8785});
8786
8787pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8788    LazyLock::new(|| BuiltinView {
8789        name: "mz_dataflow_operator_reachability_per_worker",
8790        schema: MZ_INTROSPECTION_SCHEMA,
8791        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8792        desc: RelationDesc::builder()
8793            .with_column("id", SqlScalarType::UInt64.nullable(false))
8794            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8795            .with_column("port", SqlScalarType::UInt64.nullable(false))
8796            .with_column("update_type", SqlScalarType::String.nullable(false))
8797            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8798            .with_column("count", SqlScalarType::Int64.nullable(false))
8799            .with_key(vec![0, 1, 2, 3, 4])
8800            .finish(),
8801        column_comments: BTreeMap::new(),
8802        sql: "SELECT
8803    addr2.id,
8804    reachability.worker_id,
8805    port,
8806    update_type,
8807    time,
8808    pg_catalog.count(*) as count
8809FROM
8810    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8811    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8812    mz_introspection.mz_dataflow_addresses_per_worker addr2
8813WHERE
8814    addr2.address =
8815    CASE
8816        WHEN source = 0 THEN addr1.address
8817        ELSE addr1.address || reachability.source
8818    END
8819    AND addr1.id = reachability.id
8820    AND addr1.worker_id = reachability.worker_id
8821    AND addr2.worker_id = reachability.worker_id
8822GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8823        access: vec![PUBLIC_SELECT],
8824    });
8825
8826pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8827    LazyLock::new(|| BuiltinView {
8828        name: "mz_dataflow_operator_reachability",
8829        schema: MZ_INTROSPECTION_SCHEMA,
8830        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8831        desc: RelationDesc::builder()
8832            .with_column("id", SqlScalarType::UInt64.nullable(false))
8833            .with_column("port", SqlScalarType::UInt64.nullable(false))
8834            .with_column("update_type", SqlScalarType::String.nullable(false))
8835            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8836            .with_column(
8837                "count",
8838                SqlScalarType::Numeric {
8839                    max_scale: Some(NumericMaxScale::ZERO),
8840                }
8841                .nullable(false),
8842            )
8843            .with_key(vec![0, 1, 2, 3])
8844            .finish(),
8845        column_comments: BTreeMap::new(),
8846        sql: "
8847SELECT
8848    id,
8849    port,
8850    update_type,
8851    time,
8852    pg_catalog.sum(count) as count
8853FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8854GROUP BY id, port, update_type, time",
8855        access: vec![PUBLIC_SELECT],
8856    });
8857
8858pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8859    BuiltinView {
8860        name: "mz_arrangement_sizes_per_worker",
8861        schema: MZ_INTROSPECTION_SCHEMA,
8862        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8863        desc: RelationDesc::builder()
8864            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8865            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8866            .with_column("records", SqlScalarType::Int64.nullable(true))
8867            .with_column("batches", SqlScalarType::Int64.nullable(true))
8868            .with_column("size", SqlScalarType::Int64.nullable(true))
8869            .with_column("capacity", SqlScalarType::Int64.nullable(true))
8870            .with_column("allocations", SqlScalarType::Int64.nullable(true))
8871            .finish(),
8872        column_comments: BTreeMap::new(),
8873        sql: "
8874WITH operators_per_worker_cte AS (
8875    SELECT
8876        id AS operator_id,
8877        worker_id
8878    FROM
8879        mz_introspection.mz_dataflow_operators_per_worker
8880),
8881batches_cte AS (
8882    SELECT
8883        operator_id,
8884        worker_id,
8885        COUNT(*) AS batches
8886    FROM
8887        mz_introspection.mz_arrangement_batches_raw
8888    GROUP BY
8889        operator_id, worker_id
8890),
8891records_cte AS (
8892    SELECT
8893        operator_id,
8894        worker_id,
8895        COUNT(*) AS records
8896    FROM
8897        mz_introspection.mz_arrangement_records_raw
8898    GROUP BY
8899        operator_id, worker_id
8900),
8901heap_size_cte AS (
8902    SELECT
8903        operator_id,
8904        worker_id,
8905        COUNT(*) AS size
8906    FROM
8907        mz_introspection.mz_arrangement_heap_size_raw
8908    GROUP BY
8909        operator_id, worker_id
8910),
8911heap_capacity_cte AS (
8912    SELECT
8913        operator_id,
8914        worker_id,
8915        COUNT(*) AS capacity
8916    FROM
8917        mz_introspection.mz_arrangement_heap_capacity_raw
8918    GROUP BY
8919        operator_id, worker_id
8920),
8921heap_allocations_cte AS (
8922    SELECT
8923        operator_id,
8924        worker_id,
8925        COUNT(*) AS allocations
8926    FROM
8927        mz_introspection.mz_arrangement_heap_allocations_raw
8928    GROUP BY
8929        operator_id, worker_id
8930),
8931batcher_records_cte AS (
8932    SELECT
8933        operator_id,
8934        worker_id,
8935        COUNT(*) AS records
8936    FROM
8937        mz_introspection.mz_arrangement_batcher_records_raw
8938    GROUP BY
8939        operator_id, worker_id
8940),
8941batcher_size_cte AS (
8942    SELECT
8943        operator_id,
8944        worker_id,
8945        COUNT(*) AS size
8946    FROM
8947        mz_introspection.mz_arrangement_batcher_size_raw
8948    GROUP BY
8949        operator_id, worker_id
8950),
8951batcher_capacity_cte AS (
8952    SELECT
8953        operator_id,
8954        worker_id,
8955        COUNT(*) AS capacity
8956    FROM
8957        mz_introspection.mz_arrangement_batcher_capacity_raw
8958    GROUP BY
8959        operator_id, worker_id
8960),
8961batcher_allocations_cte AS (
8962    SELECT
8963        operator_id,
8964        worker_id,
8965        COUNT(*) AS allocations
8966    FROM
8967        mz_introspection.mz_arrangement_batcher_allocations_raw
8968    GROUP BY
8969        operator_id, worker_id
8970),
8971combined AS (
8972    SELECT
8973        opw.operator_id,
8974        opw.worker_id,
8975        CASE
8976            WHEN records_cte.records IS NULL AND batcher_records_cte.records IS NULL THEN NULL
8977            ELSE COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0)
8978        END AS records,
8979        batches_cte.batches AS batches,
8980        CASE
8981            WHEN heap_size_cte.size IS NULL AND batcher_size_cte.size IS NULL THEN NULL
8982            ELSE COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0)
8983        END AS size,
8984        CASE
8985            WHEN heap_capacity_cte.capacity IS NULL AND batcher_capacity_cte.capacity IS NULL THEN NULL
8986            ELSE COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0)
8987        END AS capacity,
8988        CASE
8989            WHEN heap_allocations_cte.allocations IS NULL AND batcher_allocations_cte.allocations IS NULL THEN NULL
8990            ELSE COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0)
8991        END AS allocations
8992    FROM
8993                    operators_per_worker_cte opw
8994    LEFT OUTER JOIN batches_cte USING (operator_id, worker_id)
8995    LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
8996    LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
8997    LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
8998    LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
8999    LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
9000    LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
9001    LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
9002    LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)
9003)
9004SELECT
9005    operator_id, worker_id, records, batches, size, capacity, allocations
9006FROM combined
9007WHERE
9008       records     IS NOT NULL
9009    OR batches     IS NOT NULL
9010    OR size        IS NOT NULL
9011    OR capacity    IS NOT NULL
9012    OR allocations IS NOT NULL
9013",
9014        access: vec![PUBLIC_SELECT],
9015    }
9016});
9017
9018pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9019    name: "mz_arrangement_sizes",
9020    schema: MZ_INTROSPECTION_SCHEMA,
9021    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
9022    desc: RelationDesc::builder()
9023        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9024        .with_column("records", SqlScalarType::Int64.nullable(true))
9025        .with_column("batches", SqlScalarType::Int64.nullable(true))
9026        .with_column("size", SqlScalarType::Int64.nullable(true))
9027        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9028        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9029        .with_key(vec![0])
9030        .finish(),
9031    column_comments: BTreeMap::from_iter([
9032        (
9033            "operator_id",
9034            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
9035        ),
9036        ("records", "The number of records in the arrangement."),
9037        ("batches", "The number of batches in the arrangement."),
9038        ("size", "The utilized size in bytes of the arrangement."),
9039        (
9040            "capacity",
9041            "The capacity in bytes of the arrangement. Can be larger than the size.",
9042        ),
9043        (
9044            "allocations",
9045            "The number of separate memory allocations backing the arrangement.",
9046        ),
9047    ]),
9048    sql: "
9049SELECT
9050    operator_id,
9051    SUM(records)::int8 AS records,
9052    SUM(batches)::int8 AS batches,
9053    SUM(size)::int8 AS size,
9054    SUM(capacity)::int8 AS capacity,
9055    SUM(allocations)::int8 AS allocations
9056FROM mz_introspection.mz_arrangement_sizes_per_worker
9057GROUP BY operator_id",
9058    access: vec![PUBLIC_SELECT],
9059});
9060
9061pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
9062    LazyLock::new(|| BuiltinView {
9063        name: "mz_arrangement_sharing_per_worker",
9064        schema: MZ_INTROSPECTION_SCHEMA,
9065        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
9066        desc: RelationDesc::builder()
9067            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9068            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
9069            .with_column("count", SqlScalarType::Int64.nullable(false))
9070            .with_key(vec![0, 1])
9071            .finish(),
9072        column_comments: BTreeMap::new(),
9073        sql: "
9074SELECT
9075    operator_id,
9076    worker_id,
9077    pg_catalog.count(*) AS count
9078FROM mz_introspection.mz_arrangement_sharing_raw
9079GROUP BY operator_id, worker_id",
9080        access: vec![PUBLIC_SELECT],
9081    });
9082
9083pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9084    name: "mz_arrangement_sharing",
9085    schema: MZ_INTROSPECTION_SCHEMA,
9086    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
9087    desc: RelationDesc::builder()
9088        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9089        .with_column("count", SqlScalarType::Int64.nullable(false))
9090        .with_key(vec![0])
9091        .finish(),
9092    column_comments: BTreeMap::from_iter([
9093        (
9094            "operator_id",
9095            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
9096        ),
9097        (
9098            "count",
9099            "The number of operators that share the arrangement.",
9100        ),
9101    ]),
9102    sql: "
9103SELECT operator_id, count
9104FROM mz_introspection.mz_arrangement_sharing_per_worker
9105WHERE worker_id = 0::uint8",
9106    access: vec![PUBLIC_SELECT],
9107});
9108
9109pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9110    name: "mz_cluster_replica_utilization",
9111    schema: MZ_INTERNAL_SCHEMA,
9112    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
9113    desc: RelationDesc::builder()
9114        .with_column("replica_id", SqlScalarType::String.nullable(false))
9115        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
9116        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
9117        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
9118        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
9119        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
9120        .finish(),
9121    column_comments: BTreeMap::from_iter([
9122        ("replica_id", "The ID of a cluster replica."),
9123        ("process_id", "The ID of a process within the replica."),
9124        (
9125            "cpu_percent",
9126            "Approximate CPU usage, in percent of the total allocation.",
9127        ),
9128        (
9129            "memory_percent",
9130            "Approximate RAM usage, in percent of the total allocation.",
9131        ),
9132        (
9133            "disk_percent",
9134            "Approximate disk usage, in percent of the total allocation.",
9135        ),
9136        (
9137            "heap_percent",
9138            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
9139        ),
9140    ]),
9141    sql: "
9142SELECT
9143    r.id AS replica_id,
9144    m.process_id,
9145    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
9146    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
9147    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
9148    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent
9149FROM
9150    mz_catalog.mz_cluster_replicas AS r
9151        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
9152        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
9153    access: vec![PUBLIC_SELECT],
9154});
9155
9156pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
9157    LazyLock::new(|| BuiltinView {
9158        name: "mz_cluster_replica_utilization_history",
9159        schema: MZ_INTERNAL_SCHEMA,
9160        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
9161        desc: RelationDesc::builder()
9162            .with_column("replica_id", SqlScalarType::String.nullable(false))
9163            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
9164            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
9165            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
9166            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
9167            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
9168            .with_column(
9169                "occurred_at",
9170                SqlScalarType::TimestampTz { precision: None }.nullable(false),
9171            )
9172            .finish(),
9173        column_comments: BTreeMap::from_iter([
9174            ("replica_id", "The ID of a cluster replica."),
9175            ("process_id", "The ID of a process within the replica."),
9176            (
9177                "cpu_percent",
9178                "Approximate CPU usage, in percent of the total allocation.",
9179            ),
9180            (
9181                "memory_percent",
9182                "Approximate RAM usage, in percent of the total allocation.",
9183            ),
9184            (
9185                "disk_percent",
9186                "Approximate disk usage, in percent of the total allocation.",
9187            ),
9188            (
9189                "heap_percent",
9190                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
9191            ),
9192            (
9193                "occurred_at",
9194                "Wall-clock timestamp at which the event occurred.",
9195            ),
9196        ]),
9197        sql: "
9198SELECT
9199    r.id AS replica_id,
9200    m.process_id,
9201    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
9202    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
9203    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
9204    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
9205    m.occurred_at
9206FROM
9207    mz_catalog.mz_cluster_replicas AS r
9208        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
9209        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
9210        access: vec![PUBLIC_SELECT],
9211    });
9212
9213pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
9214    LazyLock::new(|| BuiltinView {
9215        name: "mz_dataflow_operator_parents_per_worker",
9216        schema: MZ_INTROSPECTION_SCHEMA,
9217        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
9218        desc: RelationDesc::builder()
9219            .with_column("id", SqlScalarType::UInt64.nullable(false))
9220            .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9221            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
9222            .finish(),
9223        column_comments: BTreeMap::new(),
9224        sql: "
9225WITH operator_addrs AS(
9226    SELECT
9227        id, address, worker_id
9228    FROM mz_introspection.mz_dataflow_addresses_per_worker
9229        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
9230            USING (id, worker_id)
9231),
9232parent_addrs AS (
9233    SELECT
9234        id,
9235        address[1:list_length(address) - 1] AS parent_address,
9236        worker_id
9237    FROM operator_addrs
9238)
9239SELECT pa.id, oa.id AS parent_id, pa.worker_id
9240FROM parent_addrs AS pa
9241    INNER JOIN operator_addrs AS oa
9242        ON pa.parent_address = oa.address
9243        AND pa.worker_id = oa.worker_id",
9244        access: vec![PUBLIC_SELECT],
9245    });
9246
9247pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9248    name: "mz_dataflow_operator_parents",
9249    schema: MZ_INTROSPECTION_SCHEMA,
9250    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
9251    desc: RelationDesc::builder()
9252        .with_column("id", SqlScalarType::UInt64.nullable(false))
9253        .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9254        .finish(),
9255    column_comments: BTreeMap::from_iter([
9256        (
9257            "id",
9258            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
9259        ),
9260        (
9261            "parent_id",
9262            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
9263        ),
9264    ]),
9265    sql: "
9266SELECT id, parent_id
9267FROM mz_introspection.mz_dataflow_operator_parents_per_worker
9268WHERE worker_id = 0::uint8",
9269    access: vec![PUBLIC_SELECT],
9270});
9271
9272pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9273    name: "mz_dataflow_arrangement_sizes",
9274    schema: MZ_INTROSPECTION_SCHEMA,
9275    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
9276    desc: RelationDesc::builder()
9277        .with_column("id", SqlScalarType::UInt64.nullable(false))
9278        .with_column("name", SqlScalarType::String.nullable(false))
9279        .with_column("records", SqlScalarType::Int64.nullable(true))
9280        .with_column("batches", SqlScalarType::Int64.nullable(true))
9281        .with_column("size", SqlScalarType::Int64.nullable(true))
9282        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9283        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9284        .with_key(vec![0, 1])
9285        .finish(),
9286    column_comments: BTreeMap::from_iter([
9287        (
9288            "id",
9289            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9290        ),
9291        ("name", "The name of the [dataflow]."),
9292        (
9293            "records",
9294            "The number of records in all arrangements in the dataflow.",
9295        ),
9296        (
9297            "batches",
9298            "The number of batches in all arrangements in the dataflow.",
9299        ),
9300        ("size", "The utilized size in bytes of the arrangements."),
9301        (
9302            "capacity",
9303            "The capacity in bytes of the arrangements. Can be larger than the size.",
9304        ),
9305        (
9306            "allocations",
9307            "The number of separate memory allocations backing the arrangements.",
9308        ),
9309    ]),
9310    sql: "
9311SELECT
9312    mdod.dataflow_id AS id,
9313    mdod.dataflow_name AS name,
9314    SUM(mas.records)::int8 AS records,
9315    SUM(mas.batches)::int8 AS batches,
9316    SUM(mas.size)::int8 AS size,
9317    SUM(mas.capacity)::int8 AS capacity,
9318    SUM(mas.allocations)::int8 AS allocations
9319FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9320LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9321    ON mdod.id = mas.operator_id
9322GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9323    access: vec![PUBLIC_SELECT],
9324});
9325
9326pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9327    name: "mz_expected_group_size_advice",
9328    schema: MZ_INTROSPECTION_SCHEMA,
9329    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9330    desc: RelationDesc::builder()
9331        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
9332        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
9333        .with_column("region_id", SqlScalarType::UInt64.nullable(false))
9334        .with_column("region_name", SqlScalarType::String.nullable(false))
9335        .with_column("levels", SqlScalarType::Int64.nullable(false))
9336        .with_column("to_cut", SqlScalarType::Int64.nullable(false))
9337        .with_column(
9338            "savings",
9339            SqlScalarType::Numeric {
9340                max_scale: Some(NumericMaxScale::ZERO),
9341            }
9342            .nullable(true),
9343        )
9344        .with_column("hint", SqlScalarType::Float64.nullable(false))
9345        .finish(),
9346    column_comments: BTreeMap::from_iter([
9347        (
9348            "dataflow_id",
9349            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9350        ),
9351        (
9352            "dataflow_name",
9353            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9354        ),
9355        (
9356            "region_id",
9357            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9358        ),
9359        (
9360            "region_name",
9361            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9362        ),
9363        (
9364            "levels",
9365            "The number of levels in the hierarchical scheme implemented by the region.",
9366        ),
9367        (
9368            "to_cut",
9369            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9370        ),
9371        (
9372            "savings",
9373            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9374        ),
9375        (
9376            "hint",
9377            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9378        ),
9379    ]),
9380    sql: "
9381        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9382        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9383        -- of arrangements must be built. For each dataflow and region corresponding to one
9384        -- such pattern, we look for how many levels can be eliminated without hitting a level
9385        -- that actually substantially filters the input. The advice is constructed so that
9386        -- setting the hint for the affected region will eliminate these redundant levels of
9387        -- the hierarchical rendering.
9388        --
9389        -- A number of helper CTEs are used for the view definition. The first one, operators,
9390        -- looks for operator names that comprise arrangements of inputs to each level of a
9391        -- min/max/top-k hierarchy.
9392        WITH operators AS (
9393            SELECT
9394                dod.dataflow_id,
9395                dor.id AS region_id,
9396                dod.id,
9397                ars.records,
9398                ars.size
9399            FROM
9400                mz_introspection.mz_dataflow_operator_dataflows dod
9401                JOIN mz_introspection.mz_dataflow_addresses doa
9402                    ON dod.id = doa.id
9403                JOIN mz_introspection.mz_dataflow_addresses dra
9404                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9405                JOIN mz_introspection.mz_dataflow_operators dor
9406                    ON dor.id = dra.id
9407                JOIN mz_introspection.mz_arrangement_sizes ars
9408                    ON ars.operator_id = dod.id
9409            WHERE
9410                dod.name = 'Arranged TopK input'
9411                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9412                OR dod.name = 'Arrange ReduceMinsMaxes'
9413            ),
9414        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9415        -- identified in operators above.
9416        levels AS (
9417            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9418            FROM operators o
9419            GROUP BY o.dataflow_id, o.region_id
9420        ),
9421        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9422        -- operator. This operator is crucially important, as it records the number of records
9423        -- that was given as input to the gadget as a whole.
9424        pivot AS (
9425            SELECT
9426                o1.dataflow_id,
9427                o1.region_id,
9428                o1.id,
9429                o1.records
9430            FROM operators o1
9431            WHERE
9432                o1.id = (
9433                    SELECT MIN(o2.id)
9434                    FROM operators o2
9435                    WHERE
9436                        o2.dataflow_id = o1.dataflow_id
9437                        AND o2.region_id = o1.region_id
9438                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9439                )
9440        ),
9441        -- The fourth CTE, candidates, will look for operators where the number of records
9442        -- maintained is not significantly different from the number at the pivot (excluding
9443        -- the pivot itself). These are the candidates for being cut from the dataflow region
9444        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9445        -- load generator data, to give some room for small deviations in number of records.
9446        -- The intuition for allowing for this deviation is that we are looking for a strongly
9447        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9448        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9449        -- among groups where the min/max/top-k computation is (partially) applied. If the
9450        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9451        -- groups might be empty or contain only one row. Each subsequent level will have a number
9452        -- of groups that is reduced exponentially. So at some point, we will find the level where
9453        -- we actually start having a few rows per group. That's where we will see the row counts
9454        -- significantly drop off.
9455        candidates AS (
9456            SELECT
9457                o.dataflow_id,
9458                o.region_id,
9459                o.id,
9460                o.records,
9461                o.size
9462            FROM
9463                operators o
9464                JOIN pivot p
9465                    ON o.dataflow_id = p.dataflow_id
9466                        AND o.region_id = p.region_id
9467                        AND o.id <> p.id
9468            WHERE o.records >= p.records * (1 - 0.15)
9469        ),
9470        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9471        -- candidate levels that should be cut. We only return here dataflow regions where at
9472        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9473        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9474        -- cutting the height of the hierarchy further. This is because we will have way less
9475        -- groups in the next level, so there should be even further reduction happening or there
9476        -- is some substantial skew in the data. But if the latter is the case, then we should not
9477        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9478        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9479        -- compute a conservative estimate of the memory savings in bytes that will result from
9480        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9481        -- input arrangements for each level to be cut. These arrangements should dominate the
9482        -- size of each level that can be cut, since the reduction gadget internal to the level
9483        -- does not remove much data at these levels.
9484        cuts AS (
9485            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9486            FROM candidates c
9487            GROUP BY c.dataflow_id, c.region_id
9488            HAVING COUNT(*) > 0
9489        )
9490        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9491        -- levels and the number of candidates to be cut. The hint is computed taking into account
9492        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9493        -- currently equal to 16.
9494        SELECT
9495            dod.dataflow_id,
9496            dod.dataflow_name,
9497            dod.id AS region_id,
9498            dod.name AS region_name,
9499            l.levels,
9500            c.to_cut,
9501            c.savings,
9502            pow(16, l.levels - c.to_cut) - 1 AS hint
9503        FROM cuts c
9504            JOIN levels l
9505                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9506            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9507                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9508    access: vec![PUBLIC_SELECT],
9509});
9510
9511pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9512    BuiltinView {
9513        name: "mz_index_advice",
9514        schema: MZ_INTERNAL_SCHEMA,
9515        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9516        desc: RelationDesc::builder()
9517            .with_column("object_id", SqlScalarType::String.nullable(true))
9518            .with_column("hint", SqlScalarType::String.nullable(false))
9519            .with_column("details", SqlScalarType::String.nullable(false))
9520            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
9521            .finish(),
9522        column_comments: BTreeMap::from_iter([
9523            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9524            ("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."),
9525            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9526            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9527        ]),
9528        sql: "
9529-- To avoid confusion with sources and sinks in the materialize sense,
9530-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9531-- when referring to the object dependency graph.
9532--
9533-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9534-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9535-- that are not depended on by other maintained objects and have a justification why they must
9536-- be maintained (e.g. a materialized view that is depended on by a sink).
9537-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9538-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9539-- downstream objects, that node is marked to be converted into a maintained object and this
9540-- node is then propagated further up. Once completed, the list of objects that are marked as
9541-- maintained is checked against all objects to generate appropriate recommendations.
9542--
9543-- Note that the recommendations only incorporate dependencies between objects.
9544-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9545-- a sink if an index is added in between the sink and the filter. For very selective filters,
9546-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9547-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9548-- dependencies.
9549WITH MUTUALLY RECURSIVE
9550    -- for all objects, understand if they have an index on them and on which cluster they are running
9551    -- this avoids having different cases for views with an index and materialized views later on
9552    objects(id text, type text, cluster_id text, indexes text list) AS (
9553        -- views and materialized views without an index
9554        SELECT
9555            o.id,
9556            o.type,
9557            o.cluster_id,
9558            '{}'::text list AS indexes
9559        FROM mz_catalog.mz_objects o
9560        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9561            SELECT FROM mz_internal.mz_object_dependencies d
9562            JOIN mz_catalog.mz_objects AS i
9563                ON (i.id = d.object_id AND i.type = 'index')
9564            WHERE (o.id = d.referenced_object_id)
9565        )
9566
9567        UNION ALL
9568
9569        -- views and materialized views with an index
9570        SELECT
9571            o.id,
9572            o.type,
9573            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9574            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9575            list_agg(i.id) AS indexes
9576        FROM mz_catalog.mz_objects o
9577        JOIN mz_internal.mz_object_dependencies AS d
9578            ON (o.id = d.referenced_object_id)
9579        JOIN mz_catalog.mz_objects AS i
9580            ON (i.id = d.object_id AND i.type = 'index')
9581        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9582        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9583    ),
9584
9585    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9586    maintained_leafs(id text, justification text) AS (
9587        -- materialized views that are connected to a sink
9588        SELECT
9589            m.id,
9590            s.id AS justification
9591        FROM objects AS m
9592        JOIN mz_internal.mz_object_dependencies AS d
9593            ON (m.id = d.referenced_object_id)
9594        JOIN mz_catalog.mz_objects AS s
9595            ON (s.id = d.object_id AND s.type = 'sink')
9596        WHERE m.type = 'materialized-view'
9597
9598        UNION ALL
9599
9600        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9601        SELECT
9602            v.id,
9603            unnest(v.indexes) AS justification
9604        FROM objects AS v
9605        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9606            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9607            INNER JOIN mz_catalog.mz_objects AS child
9608                ON (d.object_id = child.id)
9609            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]
9610        )
9611    ),
9612
9613    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9614    agg_maintained_children(id text, maintained_children text list) AS (
9615        SELECT
9616            parent_id AS id,
9617            list_agg(maintained_child) AS maintained_leafs
9618        FROM (
9619            SELECT DISTINCT
9620                d.referenced_object_id AS parent_id,
9621                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9622                unnest(child.maintained_children) AS maintained_child
9623            FROM propagate_dependencies AS child
9624            INNER JOIN mz_internal.mz_object_dependencies AS d
9625                ON (child.id = d.object_id)
9626        )
9627        GROUP BY parent_id
9628    ),
9629
9630    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9631    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9632    -- 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
9633    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9634        -- base case: start with the leafs
9635        SELECT DISTINCT
9636            id,
9637            LIST[id] AS maintained_children,
9638            list_agg(justification) AS justification
9639        FROM maintained_leafs
9640        GROUP BY id
9641
9642        UNION
9643
9644        -- recursive case: if there is a child with the same dependencies as the parent,
9645        -- the parent is only reused by a single child
9646        SELECT
9647            parent.id,
9648            child.maintained_children,
9649            NULL::text list AS justification
9650        FROM agg_maintained_children AS parent
9651        INNER JOIN mz_internal.mz_object_dependencies AS d
9652            ON (parent.id = d.referenced_object_id)
9653        INNER JOIN propagate_dependencies AS child
9654            ON (d.object_id = child.id)
9655        WHERE parent.maintained_children = child.maintained_children
9656
9657        UNION
9658
9659        -- recursive case: if there is NO child with the same dependencies as the parent,
9660        -- different children are reusing the parent so maintaining the object is justified by itself
9661        SELECT DISTINCT
9662            parent.id,
9663            LIST[parent.id] AS maintained_children,
9664            parent.maintained_children AS justification
9665        FROM agg_maintained_children AS parent
9666        WHERE NOT EXISTS (
9667            SELECT FROM mz_internal.mz_object_dependencies AS d
9668            INNER JOIN propagate_dependencies AS child
9669                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9670            WHERE parent.maintained_children = child.maintained_children
9671        )
9672    ),
9673
9674    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9675        SELECT
9676            p.id,
9677            o.type,
9678            o.cluster_id,
9679            p.maintained_children,
9680            p.justification,
9681            o.indexes
9682        FROM propagate_dependencies p
9683        JOIN objects AS o
9684            ON (p.id = o.id)
9685    ),
9686
9687    hints(id text, hint text, details text, justification text list) AS (
9688        -- materialized views that are not required
9689        SELECT
9690            id,
9691            'convert to a view' AS hint,
9692            'no dependencies from sinks nor from objects on different clusters' AS details,
9693            justification
9694        FROM objects_with_justification
9695        WHERE type = 'materialized-view' AND justification IS NULL
9696
9697        UNION ALL
9698
9699        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9700        SELECT
9701            id,
9702            'keep' AS hint,
9703            'dependencies from sinks or objects on different clusters: ' AS details,
9704            justification
9705        FROM objects_with_justification AS m
9706        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9707            SELECT FROM unnest(justification) AS dependency
9708            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9709
9710            UNION ALL
9711
9712            SELECT FROM unnest(justification) AS dependency
9713            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9714            WHERE d.cluster_id != m.cluster_id
9715        )
9716
9717        UNION ALL
9718
9719        -- 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
9720        SELECT
9721            id,
9722            'convert to a view with an index' AS hint,
9723            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9724            justification
9725        FROM objects_with_justification AS m
9726        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
9727            SELECT FROM unnest(justification) AS dependency
9728            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9729
9730            UNION ALL
9731
9732            SELECT FROM unnest(justification) AS dependency
9733            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9734            WHERE d.cluster_id != m.cluster_id
9735        )
9736
9737        UNION ALL
9738
9739        -- views that have indexes on different clusters should be a materialized view
9740        SELECT
9741            o.id,
9742            'convert to materialized view' AS hint,
9743            'dependencies on multiple clusters: ' AS details,
9744            o.justification
9745        FROM objects_with_justification o,
9746            LATERAL unnest(o.justification) j
9747        LEFT JOIN mz_catalog.mz_objects AS m
9748            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9749        WHERE o.type = 'view' AND o.justification IS NOT NULL
9750        GROUP BY o.id, o.justification
9751        HAVING count(DISTINCT m.cluster_id) >= 2
9752
9753        UNION ALL
9754
9755        -- views without an index that should be maintained
9756        SELECT
9757            id,
9758            'add index' AS hint,
9759            'multiple downstream dependencies: ' AS details,
9760            justification
9761        FROM objects_with_justification
9762        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9763
9764        UNION ALL
9765
9766        -- index inside the dependency graph (not a leaf)
9767        SELECT
9768            unnest(indexes) AS id,
9769            'drop unless queried directly' AS hint,
9770            'fewer than two downstream dependencies: ' AS details,
9771            maintained_children AS justification
9772        FROM objects_with_justification
9773        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9774
9775        UNION ALL
9776
9777        -- index on a leaf of the dependency graph
9778        SELECT
9779            unnest(indexes) AS id,
9780            'drop unless queried directly' AS hint,
9781            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9782            NULL::text list AS justification
9783        FROM objects_with_justification
9784        -- indexes can only be part of justification for leaf nodes
9785        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9786
9787        UNION ALL
9788
9789        -- index on a source
9790        SELECT
9791            unnest(indexes) AS id,
9792            'drop unless queried directly' AS hint,
9793            'sources do not transform data and can expose data directly' AS details,
9794            NULL::text list AS justification
9795        FROM objects_with_justification
9796        -- indexes can only be part of justification for leaf nodes
9797        WHERE type = 'source' AND NOT indexes = '{}'::text list
9798
9799        UNION ALL
9800
9801        -- indexes on views inside the dependency graph
9802        SELECT
9803            unnest(indexes) AS id,
9804            'keep' AS hint,
9805            'multiple downstream dependencies: ' AS details,
9806            justification
9807        FROM objects_with_justification
9808        -- indexes can only be part of justification for leaf nodes
9809        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9810    ),
9811
9812    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9813        SELECT
9814            h.id,
9815            h.hint,
9816            h.details || list_agg(o.name)::text AS details,
9817            h.justification
9818        FROM hints AS h,
9819            LATERAL unnest(h.justification) j
9820        JOIN mz_catalog.mz_objects AS o
9821            ON (o.id = j)
9822        GROUP BY h.id, h.hint, h.details, h.justification
9823
9824        UNION ALL
9825
9826        SELECT
9827            id,
9828            hint,
9829            details,
9830            justification
9831        FROM hints
9832        WHERE justification IS NULL
9833    )
9834
9835SELECT
9836    h.id AS object_id,
9837    h.hint AS hint,
9838    h.details,
9839    h.justification AS referenced_object_ids
9840FROM hints_resolved_ids AS h",
9841        access: vec![PUBLIC_SELECT],
9842    }
9843});
9844
9845// NOTE: If you add real data to this implementation, then please update
9846// the related `pg_` function implementations (like `pg_get_constraintdef`)
9847pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9848    name: "pg_constraint",
9849    schema: PG_CATALOG_SCHEMA,
9850    oid: oid::VIEW_PG_CONSTRAINT_OID,
9851    desc: RelationDesc::builder()
9852        .with_column("oid", SqlScalarType::Oid.nullable(false))
9853        .with_column("conname", SqlScalarType::String.nullable(false))
9854        .with_column("connamespace", SqlScalarType::Oid.nullable(false))
9855        .with_column("contype", SqlScalarType::PgLegacyChar.nullable(false))
9856        .with_column("condeferrable", SqlScalarType::Bool.nullable(false))
9857        .with_column("condeferred", SqlScalarType::Bool.nullable(false))
9858        .with_column("convalidated", SqlScalarType::Bool.nullable(false))
9859        .with_column("conrelid", SqlScalarType::Oid.nullable(false))
9860        .with_column("contypid", SqlScalarType::Oid.nullable(false))
9861        .with_column("conindid", SqlScalarType::Oid.nullable(false))
9862        .with_column("conparentid", SqlScalarType::Oid.nullable(false))
9863        .with_column("confrelid", SqlScalarType::Oid.nullable(false))
9864        .with_column("confupdtype", SqlScalarType::PgLegacyChar.nullable(false))
9865        .with_column("confdeltype", SqlScalarType::PgLegacyChar.nullable(false))
9866        .with_column("confmatchtype", SqlScalarType::PgLegacyChar.nullable(false))
9867        .with_column("conislocal", SqlScalarType::Bool.nullable(false))
9868        .with_column("coninhcount", SqlScalarType::Int32.nullable(false))
9869        .with_column("connoinherit", SqlScalarType::Bool.nullable(false))
9870        .with_column(
9871            "conkey",
9872            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9873        )
9874        .with_column(
9875            "confkey",
9876            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9877        )
9878        .with_column(
9879            "conpfeqop",
9880            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9881        )
9882        .with_column(
9883            "conppeqop",
9884            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9885        )
9886        .with_column(
9887            "conffeqop",
9888            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9889        )
9890        .with_column(
9891            "conexclop",
9892            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9893        )
9894        .with_column("conbin", SqlScalarType::String.nullable(false))
9895        .with_key(vec![])
9896        .finish(),
9897    column_comments: BTreeMap::new(),
9898    sql: "SELECT
9899    NULL::pg_catalog.oid as oid,
9900    NULL::pg_catalog.text as conname,
9901    NULL::pg_catalog.oid as connamespace,
9902    NULL::pg_catalog.\"char\" as contype,
9903    NULL::pg_catalog.bool as condeferrable,
9904    NULL::pg_catalog.bool as condeferred,
9905    NULL::pg_catalog.bool as convalidated,
9906    NULL::pg_catalog.oid as conrelid,
9907    NULL::pg_catalog.oid as contypid,
9908    NULL::pg_catalog.oid as conindid,
9909    NULL::pg_catalog.oid as conparentid,
9910    NULL::pg_catalog.oid as confrelid,
9911    NULL::pg_catalog.\"char\" as confupdtype,
9912    NULL::pg_catalog.\"char\" as confdeltype,
9913    NULL::pg_catalog.\"char\" as confmatchtype,
9914    NULL::pg_catalog.bool as conislocal,
9915    NULL::pg_catalog.int4 as coninhcount,
9916    NULL::pg_catalog.bool as connoinherit,
9917    NULL::pg_catalog.int2[] as conkey,
9918    NULL::pg_catalog.int2[] as confkey,
9919    NULL::pg_catalog.oid[] as conpfeqop,
9920    NULL::pg_catalog.oid[] as conppeqop,
9921    NULL::pg_catalog.oid[] as conffeqop,
9922    NULL::pg_catalog.oid[] as conexclop,
9923    NULL::pg_catalog.text as conbin
9924WHERE false",
9925    access: vec![PUBLIC_SELECT],
9926});
9927
9928pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9929    name: "pg_tables",
9930    schema: PG_CATALOG_SCHEMA,
9931    oid: oid::VIEW_PG_TABLES_OID,
9932    desc: RelationDesc::builder()
9933        .with_column("schemaname", SqlScalarType::String.nullable(true))
9934        .with_column("tablename", SqlScalarType::String.nullable(false))
9935        .with_column("tableowner", SqlScalarType::String.nullable(false))
9936        .finish(),
9937    column_comments: BTreeMap::new(),
9938    sql: "
9939SELECT n.nspname AS schemaname,
9940    c.relname AS tablename,
9941    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
9942FROM pg_catalog.pg_class c
9943LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
9944WHERE c.relkind IN ('r', 'p')",
9945    access: vec![PUBLIC_SELECT],
9946});
9947
9948pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9949    name: "pg_tablespace",
9950    schema: PG_CATALOG_SCHEMA,
9951    oid: oid::VIEW_PG_TABLESPACE_OID,
9952    desc: RelationDesc::builder()
9953        .with_column("oid", SqlScalarType::Oid.nullable(false))
9954        .with_column("spcname", SqlScalarType::String.nullable(false))
9955        .with_column("spcowner", SqlScalarType::Oid.nullable(true))
9956        .with_column(
9957            "spcacl",
9958            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9959        )
9960        .with_column(
9961            "spcoptions",
9962            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9963        )
9964        .with_key(vec![])
9965        .finish(),
9966    column_comments: BTreeMap::new(),
9967    sql: "
9968    SELECT oid, spcname, spcowner, spcacl, spcoptions
9969    FROM (
9970        VALUES (
9971            --These are the same defaults CockroachDB uses.
9972            0::pg_catalog.oid,
9973            'pg_default'::pg_catalog.text,
9974            NULL::pg_catalog.oid,
9975            NULL::pg_catalog.text[],
9976            NULL::pg_catalog.text[]
9977        )
9978    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
9979",
9980    access: vec![PUBLIC_SELECT],
9981});
9982
9983pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9984    name: "pg_am",
9985    schema: PG_CATALOG_SCHEMA,
9986    oid: oid::VIEW_PG_AM_OID,
9987    desc: RelationDesc::builder()
9988        .with_column("oid", SqlScalarType::Oid.nullable(false))
9989        .with_column("amname", SqlScalarType::String.nullable(false))
9990        .with_column("amhandler", SqlScalarType::RegProc.nullable(false))
9991        .with_column("amtype", SqlScalarType::PgLegacyChar.nullable(false))
9992        .with_key(vec![])
9993        .finish(),
9994    column_comments: BTreeMap::new(),
9995    sql: "
9996SELECT NULL::pg_catalog.oid AS oid,
9997    NULL::pg_catalog.text AS amname,
9998    NULL::pg_catalog.regproc AS amhandler,
9999    NULL::pg_catalog.\"char\" AS amtype
10000WHERE false",
10001    access: vec![PUBLIC_SELECT],
10002});
10003
10004pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10005    name: "pg_roles",
10006    schema: PG_CATALOG_SCHEMA,
10007    oid: oid::VIEW_PG_ROLES_OID,
10008    desc: RelationDesc::builder()
10009        .with_column("rolname", SqlScalarType::String.nullable(false))
10010        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10011        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10012        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10013        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10014        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10015        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10016        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10017        .with_column("rolpassword", SqlScalarType::String.nullable(false))
10018        .with_column(
10019            "rolvaliduntil",
10020            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10021        )
10022        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10023        .with_column(
10024            "rolconfig",
10025            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10026        )
10027        .with_column("oid", SqlScalarType::Oid.nullable(false))
10028        .finish(),
10029    column_comments: BTreeMap::new(),
10030    sql: "SELECT
10031    rolname,
10032    rolsuper,
10033    rolinherit,
10034    rolcreaterole,
10035    rolcreatedb,
10036    COALESCE(rolcanlogin, false) AS rolcanlogin,
10037    rolreplication,
10038    rolconnlimit,
10039    '********' as rolpassword,
10040    rolvaliduntil,
10041    rolbypassrls,
10042    (
10043        SELECT array_agg(parameter_name || '=' || parameter_value)
10044        FROM mz_catalog.mz_role_parameters rp
10045        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
10046        WHERE ai.oid = r.oid
10047    ) AS rolconfig,
10048    oid
10049FROM pg_catalog.pg_authid ai",
10050    access: vec![PUBLIC_SELECT],
10051});
10052
10053pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10054    name: "pg_user",
10055    schema: PG_CATALOG_SCHEMA,
10056    oid: oid::VIEW_PG_USER_OID,
10057    desc: RelationDesc::builder()
10058        .with_column("usename", SqlScalarType::String.nullable(false))
10059        .with_column("usesysid", SqlScalarType::Oid.nullable(false))
10060        .with_column("usecreatedb", SqlScalarType::Bool.nullable(true))
10061        .with_column("usesuper", SqlScalarType::Bool.nullable(true))
10062        .with_column("userepl", SqlScalarType::Bool.nullable(false))
10063        .with_column("usebypassrls", SqlScalarType::Bool.nullable(false))
10064        .with_column("passwd", SqlScalarType::String.nullable(true))
10065        .with_column(
10066            "valuntil",
10067            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10068        )
10069        .with_column(
10070            "useconfig",
10071            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10072        )
10073        .finish(),
10074    column_comments: BTreeMap::new(),
10075    sql: "
10076SELECT
10077    rolname as usename,
10078    ai.oid as usesysid,
10079    rolcreatedb AS usecreatedb,
10080    rolsuper AS usesuper,
10081    rolreplication AS userepl,
10082    rolbypassrls AS usebypassrls,
10083    rolpassword as passwd,
10084    rolvaliduntil as valuntil,
10085    (
10086        SELECT array_agg(parameter_name || '=' || parameter_value)
10087        FROM mz_catalog.mz_role_parameters rp
10088        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
10089        WHERE ai.oid = r.oid
10090    ) AS useconfig
10091FROM pg_catalog.pg_authid ai
10092WHERE rolcanlogin",
10093    access: vec![PUBLIC_SELECT],
10094});
10095
10096pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10097    name: "pg_views",
10098    schema: PG_CATALOG_SCHEMA,
10099    oid: oid::VIEW_PG_VIEWS_OID,
10100    desc: RelationDesc::builder()
10101        .with_column("schemaname", SqlScalarType::String.nullable(true))
10102        .with_column("viewname", SqlScalarType::String.nullable(false))
10103        .with_column("viewowner", SqlScalarType::Oid.nullable(false))
10104        .with_column("definition", SqlScalarType::String.nullable(false))
10105        .finish(),
10106    column_comments: BTreeMap::new(),
10107    sql: "SELECT
10108    s.name AS schemaname,
10109    v.name AS viewname,
10110    role_owner.oid AS viewowner,
10111    v.definition AS definition
10112FROM mz_catalog.mz_views v
10113LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10114LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10115JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
10116WHERE s.database_id IS NULL OR d.name = current_database()",
10117    access: vec![PUBLIC_SELECT],
10118});
10119
10120pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10121    name: "pg_matviews",
10122    schema: PG_CATALOG_SCHEMA,
10123    oid: oid::VIEW_PG_MATVIEWS_OID,
10124    desc: RelationDesc::builder()
10125        .with_column("schemaname", SqlScalarType::String.nullable(true))
10126        .with_column("matviewname", SqlScalarType::String.nullable(false))
10127        .with_column("matviewowner", SqlScalarType::Oid.nullable(false))
10128        .with_column("definition", SqlScalarType::String.nullable(false))
10129        .finish(),
10130    column_comments: BTreeMap::new(),
10131    sql: "SELECT
10132    s.name AS schemaname,
10133    m.name AS matviewname,
10134    role_owner.oid AS matviewowner,
10135    m.definition AS definition
10136FROM mz_catalog.mz_materialized_views m
10137LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
10138LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10139JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
10140WHERE s.database_id IS NULL OR d.name = current_database()",
10141    access: vec![PUBLIC_SELECT],
10142});
10143
10144pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
10145    LazyLock::new(|| BuiltinView {
10146        name: "applicable_roles",
10147        schema: INFORMATION_SCHEMA,
10148        oid: oid::VIEW_APPLICABLE_ROLES_OID,
10149        desc: RelationDesc::builder()
10150            .with_column("grantee", SqlScalarType::String.nullable(false))
10151            .with_column("role_name", SqlScalarType::String.nullable(false))
10152            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10153            .finish(),
10154        column_comments: BTreeMap::new(),
10155        sql: "
10156SELECT
10157    member.name AS grantee,
10158    role.name AS role_name,
10159    -- ADMIN OPTION isn't implemented.
10160    'NO' AS is_grantable
10161FROM mz_catalog.mz_role_members membership
10162JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
10163JOIN mz_catalog.mz_roles member ON membership.member = member.id
10164WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
10165        access: vec![PUBLIC_SELECT],
10166    });
10167
10168pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10169    name: "columns",
10170    schema: INFORMATION_SCHEMA,
10171    oid: oid::VIEW_COLUMNS_OID,
10172    desc: RelationDesc::builder()
10173        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10174        .with_column("table_schema", SqlScalarType::String.nullable(false))
10175        .with_column("table_name", SqlScalarType::String.nullable(false))
10176        .with_column("column_name", SqlScalarType::String.nullable(false))
10177        .with_column("ordinal_position", SqlScalarType::Int64.nullable(false))
10178        .with_column("column_default", SqlScalarType::String.nullable(true))
10179        .with_column("is_nullable", SqlScalarType::String.nullable(false))
10180        .with_column("data_type", SqlScalarType::String.nullable(false))
10181        .with_column(
10182            "character_maximum_length",
10183            SqlScalarType::Int32.nullable(true),
10184        )
10185        .with_column("numeric_precision", SqlScalarType::Int32.nullable(true))
10186        .with_column("numeric_scale", SqlScalarType::Int32.nullable(true))
10187        .finish(),
10188    column_comments: BTreeMap::new(),
10189    sql: "
10190SELECT
10191    current_database() as table_catalog,
10192    s.name AS table_schema,
10193    o.name AS table_name,
10194    c.name AS column_name,
10195    c.position::int8 AS ordinal_position,
10196    c.default AS column_default,
10197    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
10198    c.type AS data_type,
10199    NULL::pg_catalog.int4 AS character_maximum_length,
10200    NULL::pg_catalog.int4 AS numeric_precision,
10201    NULL::pg_catalog.int4 AS numeric_scale
10202FROM mz_catalog.mz_columns c
10203JOIN mz_catalog.mz_objects o ON o.id = c.id
10204JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
10205LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10206WHERE s.database_id IS NULL OR d.name = current_database()",
10207    access: vec![PUBLIC_SELECT],
10208});
10209
10210pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
10211    LazyLock::new(|| BuiltinView {
10212        name: "enabled_roles",
10213        schema: INFORMATION_SCHEMA,
10214        oid: oid::VIEW_ENABLED_ROLES_OID,
10215        desc: RelationDesc::builder()
10216            .with_column("role_name", SqlScalarType::String.nullable(false))
10217            .finish(),
10218        column_comments: BTreeMap::new(),
10219        sql: "
10220SELECT name AS role_name
10221FROM mz_catalog.mz_roles
10222WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
10223        access: vec![PUBLIC_SELECT],
10224    });
10225
10226pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
10227    BuiltinView {
10228        name: "role_table_grants",
10229        schema: INFORMATION_SCHEMA,
10230        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
10231        desc: RelationDesc::builder()
10232            .with_column("grantor", SqlScalarType::String.nullable(false))
10233            .with_column("grantee", SqlScalarType::String.nullable(true))
10234            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10235            .with_column("table_schema", SqlScalarType::String.nullable(false))
10236            .with_column("table_name", SqlScalarType::String.nullable(false))
10237            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10238            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10239            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10240            .finish(),
10241        column_comments: BTreeMap::new(),
10242        sql: "
10243SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
10244FROM information_schema.table_privileges
10245WHERE
10246    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
10247    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
10248        access: vec![PUBLIC_SELECT],
10249    }
10250});
10251
10252pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
10253    LazyLock::new(|| BuiltinView {
10254        name: "key_column_usage",
10255        schema: INFORMATION_SCHEMA,
10256        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
10257        desc: RelationDesc::builder()
10258            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10259            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10260            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10261            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10262            .with_column("table_schema", SqlScalarType::String.nullable(false))
10263            .with_column("table_name", SqlScalarType::String.nullable(false))
10264            .with_column("column_name", SqlScalarType::String.nullable(false))
10265            .with_column("ordinal_position", SqlScalarType::Int32.nullable(false))
10266            .with_column(
10267                "position_in_unique_constraint",
10268                SqlScalarType::Int32.nullable(false),
10269            )
10270            .with_key(vec![])
10271            .finish(),
10272        column_comments: BTreeMap::new(),
10273        sql: "SELECT
10274    NULL::text AS constraint_catalog,
10275    NULL::text AS constraint_schema,
10276    NULL::text AS constraint_name,
10277    NULL::text AS table_catalog,
10278    NULL::text AS table_schema,
10279    NULL::text AS table_name,
10280    NULL::text AS column_name,
10281    NULL::integer AS ordinal_position,
10282    NULL::integer AS position_in_unique_constraint
10283WHERE false",
10284        access: vec![PUBLIC_SELECT],
10285    });
10286
10287pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10288    LazyLock::new(|| BuiltinView {
10289        name: "referential_constraints",
10290        schema: INFORMATION_SCHEMA,
10291        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10292        desc: RelationDesc::builder()
10293            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10294            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10295            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10296            .with_column(
10297                "unique_constraint_catalog",
10298                SqlScalarType::String.nullable(false),
10299            )
10300            .with_column(
10301                "unique_constraint_schema",
10302                SqlScalarType::String.nullable(false),
10303            )
10304            .with_column(
10305                "unique_constraint_name",
10306                SqlScalarType::String.nullable(false),
10307            )
10308            .with_column("match_option", SqlScalarType::String.nullable(false))
10309            .with_column("update_rule", SqlScalarType::String.nullable(false))
10310            .with_column("delete_rule", SqlScalarType::String.nullable(false))
10311            .with_key(vec![])
10312            .finish(),
10313        column_comments: BTreeMap::new(),
10314        sql: "SELECT
10315    NULL::text AS constraint_catalog,
10316    NULL::text AS constraint_schema,
10317    NULL::text AS constraint_name,
10318    NULL::text AS unique_constraint_catalog,
10319    NULL::text AS unique_constraint_schema,
10320    NULL::text AS unique_constraint_name,
10321    NULL::text AS match_option,
10322    NULL::text AS update_rule,
10323    NULL::text AS delete_rule
10324WHERE false",
10325        access: vec![PUBLIC_SELECT],
10326    });
10327
10328pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10329    name: "routines",
10330    schema: INFORMATION_SCHEMA,
10331    oid: oid::VIEW_ROUTINES_OID,
10332    desc: RelationDesc::builder()
10333        .with_column("routine_catalog", SqlScalarType::String.nullable(false))
10334        .with_column("routine_schema", SqlScalarType::String.nullable(false))
10335        .with_column("routine_name", SqlScalarType::String.nullable(false))
10336        .with_column("routine_type", SqlScalarType::String.nullable(false))
10337        .with_column("routine_definition", SqlScalarType::String.nullable(true))
10338        .finish(),
10339    column_comments: BTreeMap::new(),
10340    sql: "SELECT
10341    current_database() as routine_catalog,
10342    s.name AS routine_schema,
10343    f.name AS routine_name,
10344    'FUNCTION' AS routine_type,
10345    NULL::text AS routine_definition
10346FROM mz_catalog.mz_functions f
10347JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10348LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10349WHERE s.database_id IS NULL OR d.name = current_database()",
10350    access: vec![PUBLIC_SELECT],
10351});
10352
10353pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10354    name: "schemata",
10355    schema: INFORMATION_SCHEMA,
10356    oid: oid::VIEW_SCHEMATA_OID,
10357    desc: RelationDesc::builder()
10358        .with_column("catalog_name", SqlScalarType::String.nullable(false))
10359        .with_column("schema_name", SqlScalarType::String.nullable(false))
10360        .finish(),
10361    column_comments: BTreeMap::new(),
10362    sql: "
10363SELECT
10364    current_database() as catalog_name,
10365    s.name AS schema_name
10366FROM mz_catalog.mz_schemas s
10367LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10368WHERE s.database_id IS NULL OR d.name = current_database()",
10369    access: vec![PUBLIC_SELECT],
10370});
10371
10372pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10373    name: "tables",
10374    schema: INFORMATION_SCHEMA,
10375    oid: oid::VIEW_TABLES_OID,
10376    desc: RelationDesc::builder()
10377        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10378        .with_column("table_schema", SqlScalarType::String.nullable(false))
10379        .with_column("table_name", SqlScalarType::String.nullable(false))
10380        .with_column("table_type", SqlScalarType::String.nullable(false))
10381        .finish(),
10382    column_comments: BTreeMap::new(),
10383    sql: "SELECT
10384    current_database() as table_catalog,
10385    s.name AS table_schema,
10386    r.name AS table_name,
10387    CASE r.type
10388        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10389        WHEN 'table' THEN 'BASE TABLE'
10390        ELSE pg_catalog.upper(r.type)
10391    END AS table_type
10392FROM mz_catalog.mz_relations r
10393JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10394LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10395WHERE s.database_id IS NULL OR d.name = current_database()",
10396    access: vec![PUBLIC_SELECT],
10397});
10398
10399pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10400    LazyLock::new(|| BuiltinView {
10401        name: "table_constraints",
10402        schema: INFORMATION_SCHEMA,
10403        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10404        desc: RelationDesc::builder()
10405            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10406            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10407            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10408            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10409            .with_column("table_schema", SqlScalarType::String.nullable(false))
10410            .with_column("table_name", SqlScalarType::String.nullable(false))
10411            .with_column("constraint_type", SqlScalarType::String.nullable(false))
10412            .with_column("is_deferrable", SqlScalarType::String.nullable(false))
10413            .with_column("initially_deferred", SqlScalarType::String.nullable(false))
10414            .with_column("enforced", SqlScalarType::String.nullable(false))
10415            .with_column("nulls_distinct", SqlScalarType::String.nullable(false))
10416            .with_key(vec![])
10417            .finish(),
10418        column_comments: BTreeMap::new(),
10419        sql: "SELECT
10420    NULL::text AS constraint_catalog,
10421    NULL::text AS constraint_schema,
10422    NULL::text AS constraint_name,
10423    NULL::text AS table_catalog,
10424    NULL::text AS table_schema,
10425    NULL::text AS table_name,
10426    NULL::text AS constraint_type,
10427    NULL::text AS is_deferrable,
10428    NULL::text AS initially_deferred,
10429    NULL::text AS enforced,
10430    NULL::text AS nulls_distinct
10431WHERE false",
10432        access: vec![PUBLIC_SELECT],
10433    });
10434
10435pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10436    BuiltinView {
10437        name: "table_privileges",
10438        schema: INFORMATION_SCHEMA,
10439        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10440        desc: RelationDesc::builder()
10441            .with_column("grantor", SqlScalarType::String.nullable(false))
10442            .with_column("grantee", SqlScalarType::String.nullable(true))
10443            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10444            .with_column("table_schema", SqlScalarType::String.nullable(false))
10445            .with_column("table_name", SqlScalarType::String.nullable(false))
10446            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10447            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10448            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10449            .finish(),
10450        column_comments: BTreeMap::new(),
10451        sql: "
10452SELECT
10453    grantor,
10454    grantee,
10455    table_catalog,
10456    table_schema,
10457    table_name,
10458    privilege_type,
10459    is_grantable,
10460    CASE privilege_type
10461        WHEN 'SELECT' THEN 'YES'
10462        ELSE 'NO'
10463    END AS with_hierarchy
10464FROM
10465    (SELECT
10466        grantor.name AS grantor,
10467        CASE mz_internal.mz_aclitem_grantee(privileges)
10468            WHEN 'p' THEN 'PUBLIC'
10469            ELSE grantee.name
10470        END AS grantee,
10471        table_catalog,
10472        table_schema,
10473        table_name,
10474        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10475        -- ADMIN OPTION isn't implemented.
10476        'NO' AS is_grantable
10477    FROM
10478        (SELECT
10479            unnest(relations.privileges) AS privileges,
10480            CASE
10481                WHEN schemas.database_id IS NULL THEN current_database()
10482                ELSE databases.name
10483            END AS table_catalog,
10484            schemas.name AS table_schema,
10485            relations.name AS table_name
10486        FROM mz_catalog.mz_relations AS relations
10487        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10488        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10489        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10490    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10491    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10492WHERE
10493    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10494    -- to pg_has_role. Therefore we need to use a CASE statement.
10495    CASE
10496        WHEN grantee = 'PUBLIC' THEN true
10497        ELSE mz_catalog.mz_is_superuser()
10498            OR pg_has_role(current_role, grantee, 'USAGE')
10499            OR pg_has_role(current_role, grantor, 'USAGE')
10500    END",
10501        access: vec![PUBLIC_SELECT],
10502    }
10503});
10504
10505pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10506    name: "triggers",
10507    schema: INFORMATION_SCHEMA,
10508    oid: oid::VIEW_TRIGGERS_OID,
10509    desc: RelationDesc::builder()
10510        .with_column("trigger_catalog", SqlScalarType::String.nullable(false))
10511        .with_column("trigger_schema", SqlScalarType::String.nullable(false))
10512        .with_column("trigger_name", SqlScalarType::String.nullable(false))
10513        .with_column("event_manipulation", SqlScalarType::String.nullable(false))
10514        .with_column(
10515            "event_object_catalog",
10516            SqlScalarType::String.nullable(false),
10517        )
10518        .with_column("event_object_schema", SqlScalarType::String.nullable(false))
10519        .with_column("event_object_table", SqlScalarType::String.nullable(false))
10520        .with_column("action_order", SqlScalarType::Int32.nullable(false))
10521        .with_column("action_condition", SqlScalarType::String.nullable(false))
10522        .with_column("action_statement", SqlScalarType::String.nullable(false))
10523        .with_column("action_orientation", SqlScalarType::String.nullable(false))
10524        .with_column("action_timing", SqlScalarType::String.nullable(false))
10525        .with_column(
10526            "action_reference_old_table",
10527            SqlScalarType::String.nullable(false),
10528        )
10529        .with_column(
10530            "action_reference_new_table",
10531            SqlScalarType::String.nullable(false),
10532        )
10533        .with_key(vec![])
10534        .finish(),
10535    column_comments: BTreeMap::new(),
10536    sql: "SELECT
10537    NULL::text as trigger_catalog,
10538    NULL::text AS trigger_schema,
10539    NULL::text AS trigger_name,
10540    NULL::text AS event_manipulation,
10541    NULL::text AS event_object_catalog,
10542    NULL::text AS event_object_schema,
10543    NULL::text AS event_object_table,
10544    NULL::integer AS action_order,
10545    NULL::text AS action_condition,
10546    NULL::text AS action_statement,
10547    NULL::text AS action_orientation,
10548    NULL::text AS action_timing,
10549    NULL::text AS action_reference_old_table,
10550    NULL::text AS action_reference_new_table
10551WHERE FALSE",
10552    access: vec![PUBLIC_SELECT],
10553});
10554
10555pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10556    name: "views",
10557    schema: INFORMATION_SCHEMA,
10558    oid: oid::VIEW_VIEWS_OID,
10559    desc: RelationDesc::builder()
10560        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10561        .with_column("table_schema", SqlScalarType::String.nullable(false))
10562        .with_column("table_name", SqlScalarType::String.nullable(false))
10563        .with_column("view_definition", SqlScalarType::String.nullable(false))
10564        .finish(),
10565    column_comments: BTreeMap::new(),
10566    sql: "SELECT
10567    current_database() as table_catalog,
10568    s.name AS table_schema,
10569    v.name AS table_name,
10570    v.definition AS view_definition
10571FROM mz_catalog.mz_views v
10572JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10573LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10574WHERE s.database_id IS NULL OR d.name = current_database()",
10575    access: vec![PUBLIC_SELECT],
10576});
10577
10578pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10579    LazyLock::new(|| BuiltinView {
10580        name: "character_sets",
10581        schema: INFORMATION_SCHEMA,
10582        oid: oid::VIEW_CHARACTER_SETS_OID,
10583        desc: RelationDesc::builder()
10584            .with_column(
10585                "character_set_catalog",
10586                SqlScalarType::String.nullable(true),
10587            )
10588            .with_column("character_set_schema", SqlScalarType::String.nullable(true))
10589            .with_column("character_set_name", SqlScalarType::String.nullable(false))
10590            .with_column(
10591                "character_repertoire",
10592                SqlScalarType::String.nullable(false),
10593            )
10594            .with_column("form_of_use", SqlScalarType::String.nullable(false))
10595            .with_column(
10596                "default_collate_catalog",
10597                SqlScalarType::String.nullable(false),
10598            )
10599            .with_column(
10600                "default_collate_schema",
10601                SqlScalarType::String.nullable(false),
10602            )
10603            .with_column(
10604                "default_collate_name",
10605                SqlScalarType::String.nullable(false),
10606            )
10607            .with_key(vec![])
10608            .finish(),
10609        column_comments: BTreeMap::new(),
10610        sql: "SELECT
10611    NULL as character_set_catalog,
10612    NULL as character_set_schema,
10613    'UTF8' as character_set_name,
10614    'UCS' as character_repertoire,
10615    'UTF8' as form_of_use,
10616    current_database() as default_collate_catalog,
10617    'pg_catalog' as default_collate_schema,
10618    'en_US.utf8' as default_collate_name",
10619        access: vec![PUBLIC_SELECT],
10620    });
10621
10622// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10623// codes a collation of 'C' for every database, so we could copy that here.
10624pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10625    name: "pg_collation",
10626    schema: PG_CATALOG_SCHEMA,
10627    oid: oid::VIEW_PG_COLLATION_OID,
10628    desc: RelationDesc::builder()
10629        .with_column("oid", SqlScalarType::Oid.nullable(false))
10630        .with_column("collname", SqlScalarType::String.nullable(false))
10631        .with_column("collnamespace", SqlScalarType::Oid.nullable(false))
10632        .with_column("collowner", SqlScalarType::Oid.nullable(false))
10633        .with_column("collprovider", SqlScalarType::PgLegacyChar.nullable(false))
10634        .with_column("collisdeterministic", SqlScalarType::Bool.nullable(false))
10635        .with_column("collencoding", SqlScalarType::Int32.nullable(false))
10636        .with_column("collcollate", SqlScalarType::String.nullable(false))
10637        .with_column("collctype", SqlScalarType::String.nullable(false))
10638        .with_column("collversion", SqlScalarType::String.nullable(false))
10639        .with_key(vec![])
10640        .finish(),
10641    column_comments: BTreeMap::new(),
10642    sql: "
10643SELECT
10644    NULL::pg_catalog.oid AS oid,
10645    NULL::pg_catalog.text AS collname,
10646    NULL::pg_catalog.oid AS collnamespace,
10647    NULL::pg_catalog.oid AS collowner,
10648    NULL::pg_catalog.\"char\" AS collprovider,
10649    NULL::pg_catalog.bool AS collisdeterministic,
10650    NULL::pg_catalog.int4 AS collencoding,
10651    NULL::pg_catalog.text AS collcollate,
10652    NULL::pg_catalog.text AS collctype,
10653    NULL::pg_catalog.text AS collversion
10654WHERE false",
10655    access: vec![PUBLIC_SELECT],
10656});
10657
10658// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10659pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10660    name: "pg_policy",
10661    schema: PG_CATALOG_SCHEMA,
10662    oid: oid::VIEW_PG_POLICY_OID,
10663    desc: RelationDesc::builder()
10664        .with_column("oid", SqlScalarType::Oid.nullable(false))
10665        .with_column("polname", SqlScalarType::String.nullable(false))
10666        .with_column("polrelid", SqlScalarType::Oid.nullable(false))
10667        .with_column("polcmd", SqlScalarType::PgLegacyChar.nullable(false))
10668        .with_column("polpermissive", SqlScalarType::Bool.nullable(false))
10669        .with_column(
10670            "polroles",
10671            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10672        )
10673        .with_column("polqual", SqlScalarType::String.nullable(false))
10674        .with_column("polwithcheck", SqlScalarType::String.nullable(false))
10675        .with_key(vec![])
10676        .finish(),
10677    column_comments: BTreeMap::new(),
10678    sql: "
10679SELECT
10680    NULL::pg_catalog.oid AS oid,
10681    NULL::pg_catalog.text AS polname,
10682    NULL::pg_catalog.oid AS polrelid,
10683    NULL::pg_catalog.\"char\" AS polcmd,
10684    NULL::pg_catalog.bool AS polpermissive,
10685    NULL::pg_catalog.oid[] AS polroles,
10686    NULL::pg_catalog.text AS polqual,
10687    NULL::pg_catalog.text AS polwithcheck
10688WHERE false",
10689    access: vec![PUBLIC_SELECT],
10690});
10691
10692// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10693pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10694    name: "pg_inherits",
10695    schema: PG_CATALOG_SCHEMA,
10696    oid: oid::VIEW_PG_INHERITS_OID,
10697    desc: RelationDesc::builder()
10698        .with_column("inhrelid", SqlScalarType::Oid.nullable(false))
10699        .with_column("inhparent", SqlScalarType::Oid.nullable(false))
10700        .with_column("inhseqno", SqlScalarType::Int32.nullable(false))
10701        .with_column("inhdetachpending", SqlScalarType::Bool.nullable(false))
10702        .with_key(vec![])
10703        .finish(),
10704    column_comments: BTreeMap::new(),
10705    sql: "
10706SELECT
10707    NULL::pg_catalog.oid AS inhrelid,
10708    NULL::pg_catalog.oid AS inhparent,
10709    NULL::pg_catalog.int4 AS inhseqno,
10710    NULL::pg_catalog.bool AS inhdetachpending
10711WHERE false",
10712    access: vec![PUBLIC_SELECT],
10713});
10714
10715pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10716    name: "pg_locks",
10717    schema: PG_CATALOG_SCHEMA,
10718    oid: oid::VIEW_PG_LOCKS_OID,
10719    desc: RelationDesc::builder()
10720        .with_column("locktype", SqlScalarType::String.nullable(false))
10721        .with_column("database", SqlScalarType::Oid.nullable(false))
10722        .with_column("relation", SqlScalarType::Oid.nullable(false))
10723        .with_column("page", SqlScalarType::Int32.nullable(false))
10724        .with_column("tuple", SqlScalarType::Int16.nullable(false))
10725        .with_column("virtualxid", SqlScalarType::String.nullable(false))
10726        .with_column("transactionid", SqlScalarType::String.nullable(false))
10727        .with_column("classid", SqlScalarType::Oid.nullable(false))
10728        .with_column("objid", SqlScalarType::Oid.nullable(false))
10729        .with_column("objsubid", SqlScalarType::Int16.nullable(false))
10730        .with_column("virtualtransaction", SqlScalarType::String.nullable(false))
10731        .with_column("pid", SqlScalarType::Int32.nullable(false))
10732        .with_column("mode", SqlScalarType::String.nullable(false))
10733        .with_column("granted", SqlScalarType::Bool.nullable(false))
10734        .with_column("fastpath", SqlScalarType::Bool.nullable(false))
10735        .with_column(
10736            "waitstart",
10737            SqlScalarType::TimestampTz { precision: None }.nullable(false),
10738        )
10739        .with_key(vec![])
10740        .finish(),
10741    column_comments: BTreeMap::new(),
10742    sql: "
10743SELECT
10744-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10745    NULL::pg_catalog.text AS locktype,
10746    NULL::pg_catalog.oid AS database,
10747    NULL::pg_catalog.oid AS relation,
10748    NULL::pg_catalog.int4 AS page,
10749    NULL::pg_catalog.int2 AS tuple,
10750    NULL::pg_catalog.text AS virtualxid,
10751    NULL::pg_catalog.text AS transactionid,
10752    NULL::pg_catalog.oid AS classid,
10753    NULL::pg_catalog.oid AS objid,
10754    NULL::pg_catalog.int2 AS objsubid,
10755    NULL::pg_catalog.text AS virtualtransaction,
10756    NULL::pg_catalog.int4 AS pid,
10757    NULL::pg_catalog.text AS mode,
10758    NULL::pg_catalog.bool AS granted,
10759    NULL::pg_catalog.bool AS fastpath,
10760    NULL::pg_catalog.timestamptz AS waitstart
10761WHERE false",
10762    access: vec![PUBLIC_SELECT],
10763});
10764
10765/// Peeled version of `PG_AUTHID`: Excludes the columns rolcreaterole and rolcreatedb, to make this
10766/// view indexable.
10767pub static PG_AUTHID_CORE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10768    name: "pg_authid_core",
10769    schema: MZ_INTERNAL_SCHEMA,
10770    oid: oid::VIEW_PG_AUTHID_CORE_OID,
10771    desc: RelationDesc::builder()
10772        .with_column("oid", SqlScalarType::Oid.nullable(false))
10773        .with_column("rolname", SqlScalarType::String.nullable(false))
10774        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10775        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10776        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10777        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10778        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10779        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10780        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10781        .with_column(
10782            "rolvaliduntil",
10783            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10784        )
10785        .finish(),
10786    column_comments: BTreeMap::new(),
10787    sql: r#"
10788SELECT
10789    r.oid AS oid,
10790    r.name AS rolname,
10791    rolsuper,
10792    inherit AS rolinherit,
10793    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
10794    -- MZ doesn't support replication in the same way Postgres does
10795    false AS rolreplication,
10796    -- MZ doesn't how row level security
10797    false AS rolbypassrls,
10798    -- MZ doesn't have a connection limit
10799    -1 AS rolconnlimit,
10800    a.password_hash AS rolpassword,
10801    NULL::pg_catalog.timestamptz AS rolvaliduntil
10802FROM mz_catalog.mz_roles r
10803LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
10804    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10805});
10806
10807pub const PG_AUTHID_CORE_IND: BuiltinIndex = BuiltinIndex {
10808    name: "pg_authid_core_ind",
10809    schema: MZ_INTERNAL_SCHEMA,
10810    oid: oid::INDEX_PG_AUTHID_CORE_IND_OID,
10811    sql: "IN CLUSTER mz_catalog_server
10812ON mz_internal.pg_authid_core (rolname)",
10813    is_retained_metrics_object: false,
10814};
10815
10816pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10817    name: "pg_authid",
10818    schema: PG_CATALOG_SCHEMA,
10819    oid: oid::VIEW_PG_AUTHID_OID,
10820    desc: RelationDesc::builder()
10821        .with_column("oid", SqlScalarType::Oid.nullable(false))
10822        .with_column("rolname", SqlScalarType::String.nullable(false))
10823        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10824        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10825        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10826        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10827        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10828        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10829        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10830        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10831        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10832        .with_column(
10833            "rolvaliduntil",
10834            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10835        )
10836        .finish(),
10837    column_comments: BTreeMap::new(),
10838    // The `has_system_privilege` invocations for `rolcreaterole` and `rolcreatedb` get expanded
10839    // into very complex subqueries. If we put them into the SELECT clause directly, decorrelation
10840    // produces a very complex plan that the optimizer has a hard time dealing with. In particular,
10841    // the optimizer fails to reduce a query like `SELECT oid FROM pg_authid` to a simple lookup on
10842    // the `pg_authid_core` index and instead produces a large plan that contains a bunch of
10843    // expensive joins and arrangements.
10844    //
10845    // The proper fix is likely to implement `has_system_privileges` in Rust, but for now we work
10846    // around the issue by manually decorrelating `rolcreaterole` and `rolcreatedb`. Note that to
10847    // get the desired behavior we need to make sure that the join with `extra` doesn't change the
10848    // cardinality of `pg_authid_core` (otherwise it can never be optimized away). We ensure this
10849    // by:
10850    //  * using a `LEFT JOIN`, so the optimizer knows that left elements are never filtered
10851    //  * applying a `DISTINCT ON` to the CTE, so the optimizer knows that left elements are never
10852    //    duplicated
10853    sql: r#"
10854WITH extra AS (
10855    SELECT
10856        DISTINCT ON (oid)
10857        oid,
10858        mz_catalog.has_system_privilege(oid, 'CREATEROLE') AS rolcreaterole,
10859        mz_catalog.has_system_privilege(oid, 'CREATEDB') AS rolcreatedb
10860    FROM mz_internal.pg_authid_core
10861)
10862SELECT
10863    oid,
10864    rolname,
10865    rolsuper,
10866    rolinherit,
10867    extra.rolcreaterole,
10868    extra.rolcreatedb,
10869    rolcanlogin,
10870    rolreplication,
10871    rolbypassrls,
10872    rolconnlimit,
10873    rolpassword,
10874    rolvaliduntil
10875FROM mz_internal.pg_authid_core
10876LEFT JOIN extra USING (oid)"#,
10877    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10878});
10879
10880pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10881    name: "pg_aggregate",
10882    schema: PG_CATALOG_SCHEMA,
10883    oid: oid::VIEW_PG_AGGREGATE_OID,
10884    desc: RelationDesc::builder()
10885        .with_column("aggfnoid", SqlScalarType::Oid.nullable(false))
10886        .with_column("aggkind", SqlScalarType::String.nullable(false))
10887        .with_column("aggnumdirectargs", SqlScalarType::Int16.nullable(false))
10888        .with_column("aggtransfn", SqlScalarType::RegProc.nullable(true))
10889        .with_column("aggfinalfn", SqlScalarType::RegProc.nullable(false))
10890        .with_column("aggcombinefn", SqlScalarType::RegProc.nullable(false))
10891        .with_column("aggserialfn", SqlScalarType::RegProc.nullable(false))
10892        .with_column("aggdeserialfn", SqlScalarType::RegProc.nullable(false))
10893        .with_column("aggmtransfn", SqlScalarType::RegProc.nullable(false))
10894        .with_column("aggminvtransfn", SqlScalarType::RegProc.nullable(false))
10895        .with_column("aggmfinalfn", SqlScalarType::RegProc.nullable(false))
10896        .with_column("aggfinalextra", SqlScalarType::Bool.nullable(false))
10897        .with_column("aggmfinalextra", SqlScalarType::Bool.nullable(false))
10898        .with_column("aggfinalmodify", SqlScalarType::PgLegacyChar.nullable(true))
10899        .with_column(
10900            "aggmfinalmodify",
10901            SqlScalarType::PgLegacyChar.nullable(true),
10902        )
10903        .with_column("aggsortop", SqlScalarType::Oid.nullable(false))
10904        .with_column("aggtranstype", SqlScalarType::Oid.nullable(true))
10905        .with_column("aggtransspace", SqlScalarType::Int32.nullable(true))
10906        .with_column("aggmtranstype", SqlScalarType::Oid.nullable(false))
10907        .with_column("aggmtransspace", SqlScalarType::Int32.nullable(true))
10908        .with_column("agginitval", SqlScalarType::String.nullable(true))
10909        .with_column("aggminitval", SqlScalarType::String.nullable(true))
10910        .finish(),
10911    column_comments: BTreeMap::new(),
10912    sql: "SELECT
10913    a.oid as aggfnoid,
10914    -- Currently Materialize only support 'normal' aggregate functions.
10915    a.agg_kind as aggkind,
10916    a.agg_num_direct_args as aggnumdirectargs,
10917    -- Materialize doesn't support these fields.
10918    NULL::pg_catalog.regproc as aggtransfn,
10919    '0'::pg_catalog.regproc as aggfinalfn,
10920    '0'::pg_catalog.regproc as aggcombinefn,
10921    '0'::pg_catalog.regproc as aggserialfn,
10922    '0'::pg_catalog.regproc as aggdeserialfn,
10923    '0'::pg_catalog.regproc as aggmtransfn,
10924    '0'::pg_catalog.regproc as aggminvtransfn,
10925    '0'::pg_catalog.regproc as aggmfinalfn,
10926    false as aggfinalextra,
10927    false as aggmfinalextra,
10928    NULL::pg_catalog.\"char\" AS aggfinalmodify,
10929    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
10930    '0'::pg_catalog.oid as aggsortop,
10931    NULL::pg_catalog.oid as aggtranstype,
10932    NULL::pg_catalog.int4 as aggtransspace,
10933    '0'::pg_catalog.oid as aggmtranstype,
10934    NULL::pg_catalog.int4 as aggmtransspace,
10935    NULL::pg_catalog.text as agginitval,
10936    NULL::pg_catalog.text as aggminitval
10937FROM mz_internal.mz_aggregates a",
10938    access: vec![PUBLIC_SELECT],
10939});
10940
10941pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10942    name: "pg_trigger",
10943    schema: PG_CATALOG_SCHEMA,
10944    oid: oid::VIEW_PG_TRIGGER_OID,
10945    desc: RelationDesc::builder()
10946        .with_column("oid", SqlScalarType::Oid.nullable(false))
10947        .with_column("tgrelid", SqlScalarType::Oid.nullable(false))
10948        .with_column("tgparentid", SqlScalarType::Oid.nullable(false))
10949        .with_column("tgname", SqlScalarType::String.nullable(false))
10950        .with_column("tgfoid", SqlScalarType::Oid.nullable(false))
10951        .with_column("tgtype", SqlScalarType::Int16.nullable(false))
10952        .with_column("tgenabled", SqlScalarType::PgLegacyChar.nullable(false))
10953        .with_column("tgisinternal", SqlScalarType::Bool.nullable(false))
10954        .with_column("tgconstrrelid", SqlScalarType::Oid.nullable(false))
10955        .with_column("tgconstrindid", SqlScalarType::Oid.nullable(false))
10956        .with_column("tgconstraint", SqlScalarType::Oid.nullable(false))
10957        .with_column("tgdeferrable", SqlScalarType::Bool.nullable(false))
10958        .with_column("tginitdeferred", SqlScalarType::Bool.nullable(false))
10959        .with_column("tgnargs", SqlScalarType::Int16.nullable(false))
10960        .with_column("tgattr", SqlScalarType::Int2Vector.nullable(false))
10961        .with_column("tgargs", SqlScalarType::Bytes.nullable(false))
10962        .with_column("tgqual", SqlScalarType::String.nullable(false))
10963        .with_column("tgoldtable", SqlScalarType::String.nullable(false))
10964        .with_column("tgnewtable", SqlScalarType::String.nullable(false))
10965        .with_key(vec![])
10966        .finish(),
10967    column_comments: BTreeMap::new(),
10968    sql: "SELECT
10969    -- MZ doesn't support triggers so all of these fields are NULL.
10970    NULL::pg_catalog.oid AS oid,
10971    NULL::pg_catalog.oid AS tgrelid,
10972    NULL::pg_catalog.oid AS tgparentid,
10973    NULL::pg_catalog.text AS tgname,
10974    NULL::pg_catalog.oid AS tgfoid,
10975    NULL::pg_catalog.int2 AS tgtype,
10976    NULL::pg_catalog.\"char\" AS tgenabled,
10977    NULL::pg_catalog.bool AS tgisinternal,
10978    NULL::pg_catalog.oid AS tgconstrrelid,
10979    NULL::pg_catalog.oid AS tgconstrindid,
10980    NULL::pg_catalog.oid AS tgconstraint,
10981    NULL::pg_catalog.bool AS tgdeferrable,
10982    NULL::pg_catalog.bool AS tginitdeferred,
10983    NULL::pg_catalog.int2 AS tgnargs,
10984    NULL::pg_catalog.int2vector AS tgattr,
10985    NULL::pg_catalog.bytea AS tgargs,
10986    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
10987    -- uses text as a placeholder, so we'll follow their lead here.
10988    NULL::pg_catalog.text AS tgqual,
10989    NULL::pg_catalog.text AS tgoldtable,
10990    NULL::pg_catalog.text AS tgnewtable
10991WHERE false
10992    ",
10993    access: vec![PUBLIC_SELECT],
10994});
10995
10996pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10997    name: "pg_rewrite",
10998    schema: PG_CATALOG_SCHEMA,
10999    oid: oid::VIEW_PG_REWRITE_OID,
11000    desc: RelationDesc::builder()
11001        .with_column("oid", SqlScalarType::Oid.nullable(false))
11002        .with_column("rulename", SqlScalarType::String.nullable(false))
11003        .with_column("ev_class", SqlScalarType::Oid.nullable(false))
11004        .with_column("ev_type", SqlScalarType::PgLegacyChar.nullable(false))
11005        .with_column("ev_enabled", SqlScalarType::PgLegacyChar.nullable(false))
11006        .with_column("is_instead", SqlScalarType::Bool.nullable(false))
11007        .with_column("ev_qual", SqlScalarType::String.nullable(false))
11008        .with_column("ev_action", SqlScalarType::String.nullable(false))
11009        .with_key(vec![])
11010        .finish(),
11011    column_comments: BTreeMap::new(),
11012    sql: "SELECT
11013    -- MZ doesn't support rewrite rules so all of these fields are NULL.
11014    NULL::pg_catalog.oid AS oid,
11015    NULL::pg_catalog.text AS rulename,
11016    NULL::pg_catalog.oid AS ev_class,
11017    NULL::pg_catalog.\"char\" AS ev_type,
11018    NULL::pg_catalog.\"char\" AS ev_enabled,
11019    NULL::pg_catalog.bool AS is_instead,
11020    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
11021    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
11022    NULL::pg_catalog.text AS ev_qual,
11023    NULL::pg_catalog.text AS ev_action
11024WHERE false
11025    ",
11026    access: vec![PUBLIC_SELECT],
11027});
11028
11029pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11030    name: "pg_extension",
11031    schema: PG_CATALOG_SCHEMA,
11032    oid: oid::VIEW_PG_EXTENSION_OID,
11033    desc: RelationDesc::builder()
11034        .with_column("oid", SqlScalarType::Oid.nullable(false))
11035        .with_column("extname", SqlScalarType::String.nullable(false))
11036        .with_column("extowner", SqlScalarType::Oid.nullable(false))
11037        .with_column("extnamespace", SqlScalarType::Oid.nullable(false))
11038        .with_column("extrelocatable", SqlScalarType::Bool.nullable(false))
11039        .with_column("extversion", SqlScalarType::String.nullable(false))
11040        .with_column(
11041            "extconfig",
11042            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
11043        )
11044        .with_column(
11045            "extcondition",
11046            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11047        )
11048        .with_key(vec![])
11049        .finish(),
11050    column_comments: BTreeMap::new(),
11051    sql: "SELECT
11052    -- MZ doesn't support extensions so all of these fields are NULL.
11053    NULL::pg_catalog.oid AS oid,
11054    NULL::pg_catalog.text AS extname,
11055    NULL::pg_catalog.oid AS extowner,
11056    NULL::pg_catalog.oid AS extnamespace,
11057    NULL::pg_catalog.bool AS extrelocatable,
11058    NULL::pg_catalog.text AS extversion,
11059    NULL::pg_catalog.oid[] AS extconfig,
11060    NULL::pg_catalog.text[] AS extcondition
11061WHERE false
11062    ",
11063    access: vec![PUBLIC_SELECT],
11064});
11065
11066pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11067    name: "mz_show_all_objects",
11068    schema: MZ_INTERNAL_SCHEMA,
11069    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
11070    desc: RelationDesc::builder()
11071        .with_column("schema_id", SqlScalarType::String.nullable(false))
11072        .with_column("name", SqlScalarType::String.nullable(false))
11073        .with_column("type", SqlScalarType::String.nullable(false))
11074        .with_column("comment", SqlScalarType::String.nullable(false))
11075        .finish(),
11076    column_comments: BTreeMap::new(),
11077    sql: "WITH comments AS (
11078        SELECT id, object_type, comment
11079        FROM mz_internal.mz_comments
11080        WHERE object_sub_id IS NULL
11081    )
11082    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
11083    FROM mz_catalog.mz_objects AS objs
11084    LEFT JOIN comments ON objs.id = comments.id
11085    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
11086    access: vec![PUBLIC_SELECT],
11087});
11088
11089pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
11090    BuiltinView {
11091    name: "mz_show_clusters",
11092    schema: MZ_INTERNAL_SCHEMA,
11093    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
11094    desc: RelationDesc::builder()
11095        .with_column("name", SqlScalarType::String.nullable(false))
11096        .with_column("replicas", SqlScalarType::String.nullable(true))
11097        .with_column("comment", SqlScalarType::String.nullable(false))
11098        .finish(),
11099    column_comments: BTreeMap::new(),
11100    sql: "
11101    WITH clusters AS (
11102        SELECT
11103            mc.id,
11104            mc.name,
11105            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
11106        FROM mz_catalog.mz_clusters mc
11107        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
11108        ON mc.id = mcr.cluster_id
11109        GROUP BY mc.id, mc.name
11110    ),
11111    comments AS (
11112        SELECT id, comment
11113        FROM mz_internal.mz_comments
11114        WHERE object_type = 'cluster' AND object_sub_id IS NULL
11115    )
11116    SELECT name, replicas, COALESCE(comment, '') as comment
11117    FROM clusters
11118    LEFT JOIN comments ON clusters.id = comments.id",
11119    access: vec![PUBLIC_SELECT],
11120}
11121});
11122
11123pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11124    name: "mz_show_secrets",
11125    schema: MZ_INTERNAL_SCHEMA,
11126    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
11127    desc: RelationDesc::builder()
11128        .with_column("schema_id", SqlScalarType::String.nullable(false))
11129        .with_column("name", SqlScalarType::String.nullable(false))
11130        .with_column("comment", SqlScalarType::String.nullable(false))
11131        .finish(),
11132    column_comments: BTreeMap::new(),
11133    sql: "WITH comments AS (
11134        SELECT id, comment
11135        FROM mz_internal.mz_comments
11136        WHERE object_type = 'secret' AND object_sub_id IS NULL
11137    )
11138    SELECT schema_id, name, COALESCE(comment, '') as comment
11139    FROM mz_catalog.mz_secrets secrets
11140    LEFT JOIN comments ON secrets.id = comments.id",
11141    access: vec![PUBLIC_SELECT],
11142});
11143
11144pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11145    name: "mz_show_columns",
11146    schema: MZ_INTERNAL_SCHEMA,
11147    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
11148    desc: RelationDesc::builder()
11149        .with_column("id", SqlScalarType::String.nullable(false))
11150        .with_column("name", SqlScalarType::String.nullable(false))
11151        .with_column("nullable", SqlScalarType::Bool.nullable(false))
11152        .with_column("type", SqlScalarType::String.nullable(false))
11153        .with_column("position", SqlScalarType::UInt64.nullable(false))
11154        .with_column("comment", SqlScalarType::String.nullable(false))
11155        .finish(),
11156    column_comments: BTreeMap::new(),
11157    sql: "
11158    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
11159    FROM mz_catalog.mz_columns columns
11160    LEFT JOIN mz_internal.mz_comments comments
11161    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
11162    access: vec![PUBLIC_SELECT],
11163});
11164
11165pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11166    name: "mz_show_databases",
11167    schema: MZ_INTERNAL_SCHEMA,
11168    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
11169    desc: RelationDesc::builder()
11170        .with_column("name", SqlScalarType::String.nullable(false))
11171        .with_column("comment", SqlScalarType::String.nullable(false))
11172        .finish(),
11173    column_comments: BTreeMap::new(),
11174    sql: "WITH comments AS (
11175        SELECT id, comment
11176        FROM mz_internal.mz_comments
11177        WHERE object_type = 'database' AND object_sub_id IS NULL
11178    )
11179    SELECT name, COALESCE(comment, '') as comment
11180    FROM mz_catalog.mz_databases databases
11181    LEFT JOIN comments ON databases.id = comments.id",
11182    access: vec![PUBLIC_SELECT],
11183});
11184
11185pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11186    name: "mz_show_schemas",
11187    schema: MZ_INTERNAL_SCHEMA,
11188    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
11189    desc: RelationDesc::builder()
11190        .with_column("database_id", SqlScalarType::String.nullable(true))
11191        .with_column("name", SqlScalarType::String.nullable(false))
11192        .with_column("comment", SqlScalarType::String.nullable(false))
11193        .finish(),
11194    column_comments: BTreeMap::new(),
11195    sql: "WITH comments AS (
11196        SELECT id, comment
11197        FROM mz_internal.mz_comments
11198        WHERE object_type = 'schema' AND object_sub_id IS NULL
11199    )
11200    SELECT database_id, name, COALESCE(comment, '') as comment
11201    FROM mz_catalog.mz_schemas schemas
11202    LEFT JOIN comments ON schemas.id = comments.id",
11203    access: vec![PUBLIC_SELECT],
11204});
11205
11206pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11207    name: "mz_show_roles",
11208    schema: MZ_INTERNAL_SCHEMA,
11209    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
11210    desc: RelationDesc::builder()
11211        .with_column("name", SqlScalarType::String.nullable(false))
11212        .with_column("comment", SqlScalarType::String.nullable(false))
11213        .finish(),
11214    column_comments: BTreeMap::new(),
11215    sql: "WITH comments AS (
11216        SELECT id, comment
11217        FROM mz_internal.mz_comments
11218        WHERE object_type = 'role' AND object_sub_id IS NULL
11219    )
11220    SELECT name, COALESCE(comment, '') as comment
11221    FROM mz_catalog.mz_roles roles
11222    LEFT JOIN comments ON roles.id = comments.id
11223    WHERE roles.id NOT LIKE 's%'
11224      AND roles.id NOT LIKE 'g%'",
11225    access: vec![PUBLIC_SELECT],
11226});
11227
11228pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11229    name: "mz_show_tables",
11230    schema: MZ_INTERNAL_SCHEMA,
11231    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
11232    desc: RelationDesc::builder()
11233        .with_column("schema_id", SqlScalarType::String.nullable(false))
11234        .with_column("name", SqlScalarType::String.nullable(false))
11235        .with_column("comment", SqlScalarType::String.nullable(false))
11236        .with_column("source_id", SqlScalarType::String.nullable(true))
11237        .finish(),
11238    column_comments: BTreeMap::new(),
11239    sql: "WITH comments AS (
11240        SELECT id, comment
11241        FROM mz_internal.mz_comments
11242        WHERE object_type = 'table' AND object_sub_id IS NULL
11243    )
11244    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
11245    FROM mz_catalog.mz_tables tables
11246    LEFT JOIN comments ON tables.id = comments.id",
11247    access: vec![PUBLIC_SELECT],
11248});
11249
11250pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11251    name: "mz_show_views",
11252    schema: MZ_INTERNAL_SCHEMA,
11253    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
11254    desc: RelationDesc::builder()
11255        .with_column("schema_id", SqlScalarType::String.nullable(false))
11256        .with_column("name", SqlScalarType::String.nullable(false))
11257        .with_column("comment", SqlScalarType::String.nullable(false))
11258        .finish(),
11259    column_comments: BTreeMap::new(),
11260    sql: "WITH comments AS (
11261        SELECT id, comment
11262        FROM mz_internal.mz_comments
11263        WHERE object_type = 'view' AND object_sub_id IS NULL
11264    )
11265    SELECT schema_id, name, COALESCE(comment, '') as comment
11266    FROM mz_catalog.mz_views views
11267    LEFT JOIN comments ON views.id = comments.id",
11268    access: vec![PUBLIC_SELECT],
11269});
11270
11271pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11272    name: "mz_show_types",
11273    schema: MZ_INTERNAL_SCHEMA,
11274    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
11275    desc: RelationDesc::builder()
11276        .with_column("schema_id", SqlScalarType::String.nullable(false))
11277        .with_column("name", SqlScalarType::String.nullable(false))
11278        .with_column("comment", SqlScalarType::String.nullable(false))
11279        .finish(),
11280    column_comments: BTreeMap::new(),
11281    sql: "WITH comments AS (
11282        SELECT id, comment
11283        FROM mz_internal.mz_comments
11284        WHERE object_type = 'type' AND object_sub_id IS NULL
11285    )
11286    SELECT schema_id, name, COALESCE(comment, '') as comment
11287    FROM mz_catalog.mz_types types
11288    LEFT JOIN comments ON types.id = comments.id",
11289    access: vec![PUBLIC_SELECT],
11290});
11291
11292pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11293    name: "mz_show_connections",
11294    schema: MZ_INTERNAL_SCHEMA,
11295    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
11296    desc: RelationDesc::builder()
11297        .with_column("schema_id", SqlScalarType::String.nullable(false))
11298        .with_column("name", SqlScalarType::String.nullable(false))
11299        .with_column("type", SqlScalarType::String.nullable(false))
11300        .with_column("comment", SqlScalarType::String.nullable(false))
11301        .finish(),
11302    column_comments: BTreeMap::new(),
11303    sql: "WITH comments AS (
11304        SELECT id, comment
11305        FROM mz_internal.mz_comments
11306        WHERE object_type = 'connection' AND object_sub_id IS NULL
11307    )
11308    SELECT schema_id, name, type, COALESCE(comment, '') as comment
11309    FROM mz_catalog.mz_connections connections
11310    LEFT JOIN comments ON connections.id = comments.id",
11311    access: vec![PUBLIC_SELECT],
11312});
11313
11314pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11315    name: "mz_show_sources",
11316    schema: MZ_INTERNAL_SCHEMA,
11317    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
11318    desc: RelationDesc::builder()
11319        .with_column("id", SqlScalarType::String.nullable(false))
11320        .with_column("name", SqlScalarType::String.nullable(false))
11321        .with_column("type", SqlScalarType::String.nullable(false))
11322        .with_column("cluster", SqlScalarType::String.nullable(true))
11323        .with_column("schema_id", SqlScalarType::String.nullable(false))
11324        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11325        .with_column("comment", SqlScalarType::String.nullable(false))
11326        .finish(),
11327    column_comments: BTreeMap::new(),
11328    sql: "
11329WITH comments AS (
11330    SELECT id, comment
11331    FROM mz_internal.mz_comments
11332    WHERE object_type = 'source' AND object_sub_id IS NULL
11333)
11334SELECT
11335    sources.id,
11336    sources.name,
11337    sources.type,
11338    clusters.name AS cluster,
11339    schema_id,
11340    cluster_id,
11341    COALESCE(comments.comment, '') as comment
11342FROM
11343    mz_catalog.mz_sources AS sources
11344        LEFT JOIN
11345            mz_catalog.mz_clusters AS clusters
11346            ON clusters.id = sources.cluster_id
11347        LEFT JOIN comments ON sources.id = comments.id",
11348    access: vec![PUBLIC_SELECT],
11349});
11350
11351pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11352    name: "mz_show_sinks",
11353    schema: MZ_INTERNAL_SCHEMA,
11354    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11355    desc: RelationDesc::builder()
11356        .with_column("id", SqlScalarType::String.nullable(false))
11357        .with_column("name", SqlScalarType::String.nullable(false))
11358        .with_column("type", SqlScalarType::String.nullable(false))
11359        .with_column("cluster", SqlScalarType::String.nullable(false))
11360        .with_column("schema_id", SqlScalarType::String.nullable(false))
11361        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11362        .with_column("comment", SqlScalarType::String.nullable(false))
11363        .finish(),
11364    column_comments: BTreeMap::new(),
11365    sql: "
11366WITH comments AS (
11367    SELECT id, comment
11368    FROM mz_internal.mz_comments
11369    WHERE object_type = 'sink' AND object_sub_id IS NULL
11370)
11371SELECT
11372    sinks.id,
11373    sinks.name,
11374    sinks.type,
11375    clusters.name AS cluster,
11376    schema_id,
11377    cluster_id,
11378    COALESCE(comments.comment, '') as comment
11379FROM
11380    mz_catalog.mz_sinks AS sinks
11381    JOIN
11382        mz_catalog.mz_clusters AS clusters
11383        ON clusters.id = sinks.cluster_id
11384    LEFT JOIN comments ON sinks.id = comments.id",
11385    access: vec![PUBLIC_SELECT],
11386});
11387
11388pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11389    name: "mz_show_materialized_views",
11390    schema: MZ_INTERNAL_SCHEMA,
11391    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11392    desc: RelationDesc::builder()
11393        .with_column("id", SqlScalarType::String.nullable(false))
11394        .with_column("name", SqlScalarType::String.nullable(false))
11395        .with_column("cluster", SqlScalarType::String.nullable(false))
11396        .with_column("schema_id", SqlScalarType::String.nullable(false))
11397        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11398        .with_column("comment", SqlScalarType::String.nullable(false))
11399        .finish(),
11400    column_comments: BTreeMap::new(),
11401    sql: "
11402WITH
11403    comments AS (
11404        SELECT id, comment
11405        FROM mz_internal.mz_comments
11406        WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11407    )
11408SELECT
11409    mviews.id as id,
11410    mviews.name,
11411    clusters.name AS cluster,
11412    schema_id,
11413    cluster_id,
11414    COALESCE(comments.comment, '') as comment
11415FROM
11416    mz_catalog.mz_materialized_views AS mviews
11417    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11418    LEFT JOIN comments ON mviews.id = comments.id",
11419    access: vec![PUBLIC_SELECT],
11420});
11421
11422pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11423    name: "mz_show_indexes",
11424    schema: MZ_INTERNAL_SCHEMA,
11425    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11426    desc: RelationDesc::builder()
11427        .with_column("id", SqlScalarType::String.nullable(false))
11428        .with_column("name", SqlScalarType::String.nullable(false))
11429        .with_column("on", SqlScalarType::String.nullable(false))
11430        .with_column("cluster", SqlScalarType::String.nullable(false))
11431        .with_column(
11432            "key",
11433            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11434        )
11435        .with_column("on_id", SqlScalarType::String.nullable(false))
11436        .with_column("schema_id", SqlScalarType::String.nullable(false))
11437        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11438        .with_column("comment", SqlScalarType::String.nullable(false))
11439        .finish(),
11440    column_comments: BTreeMap::new(),
11441    sql: "
11442WITH comments AS (
11443    SELECT id, comment
11444    FROM mz_internal.mz_comments
11445    WHERE object_type = 'index' AND object_sub_id IS NULL
11446)
11447SELECT
11448    idxs.id AS id,
11449    idxs.name AS name,
11450    objs.name AS on,
11451    clusters.name AS cluster,
11452    COALESCE(keys.key, '{}'::_text) AS key,
11453    idxs.on_id AS on_id,
11454    objs.schema_id AS schema_id,
11455    clusters.id AS cluster_id,
11456    COALESCE(comments.comment, '') as comment
11457FROM
11458    mz_catalog.mz_indexes AS idxs
11459    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11460    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11461    LEFT JOIN
11462        (SELECT
11463            idxs.id,
11464            ARRAY_AGG(
11465                CASE
11466                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11467                    ELSE idx_cols.on_expression
11468                END
11469                ORDER BY idx_cols.index_position ASC
11470            ) AS key
11471        FROM
11472            mz_catalog.mz_indexes AS idxs
11473            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11474            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11475                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11476        GROUP BY idxs.id) AS keys
11477    ON idxs.id = keys.id
11478    LEFT JOIN comments ON idxs.id = comments.id",
11479    access: vec![PUBLIC_SELECT],
11480});
11481
11482pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11483    name: "mz_show_cluster_replicas",
11484    schema: MZ_INTERNAL_SCHEMA,
11485    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11486    desc: RelationDesc::builder()
11487        .with_column("cluster", SqlScalarType::String.nullable(false))
11488        .with_column("replica", SqlScalarType::String.nullable(false))
11489        .with_column("replica_id", SqlScalarType::String.nullable(false))
11490        .with_column("size", SqlScalarType::String.nullable(true))
11491        .with_column("ready", SqlScalarType::Bool.nullable(false))
11492        .with_column("comment", SqlScalarType::String.nullable(false))
11493        .finish(),
11494    column_comments: BTreeMap::new(),
11495    sql: r#"SELECT
11496    mz_catalog.mz_clusters.name AS cluster,
11497    mz_catalog.mz_cluster_replicas.name AS replica,
11498    mz_catalog.mz_cluster_replicas.id as replica_id,
11499    mz_catalog.mz_cluster_replicas.size AS size,
11500    coalesce(statuses.ready, FALSE) AS ready,
11501    coalesce(comments.comment, '') as comment
11502FROM
11503    mz_catalog.mz_cluster_replicas
11504        JOIN mz_catalog.mz_clusters
11505            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11506        LEFT JOIN
11507            (
11508                SELECT
11509                    replica_id,
11510                    bool_and(hydrated) AS ready
11511                FROM mz_internal.mz_hydration_statuses
11512                WHERE replica_id is not null
11513                GROUP BY replica_id
11514            ) AS statuses
11515            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11516        LEFT JOIN mz_internal.mz_comments comments
11517            ON mz_catalog.mz_cluster_replicas.id = comments.id
11518WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11519ORDER BY 1, 2"#,
11520    access: vec![PUBLIC_SELECT],
11521});
11522
11523/// Lightweight data product discovery for MCP (Model Context Protocol).
11524///
11525/// Lists materialized views and indexed views that the current user has
11526/// SELECT privileges on. Non-indexed regular views are excluded because
11527/// querying them would trigger a full recompute. Comments are optional
11528/// enrichment.
11529/// Used by the `get_data_products` and `read_data_product` MCP tools.
11530/// Does not include schema details: use `mz_mcp_data_product_details` for that.
11531pub static MZ_MCP_DATA_PRODUCTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11532    name: "mz_mcp_data_products",
11533    schema: MZ_INTERNAL_SCHEMA,
11534    oid: oid::VIEW_MZ_MCP_DATA_PRODUCTS_OID,
11535    desc: RelationDesc::builder()
11536        .with_column("object_name", SqlScalarType::String.nullable(false))
11537        .with_column("cluster", SqlScalarType::String.nullable(true))
11538        .with_column("description", SqlScalarType::String.nullable(true))
11539        .with_key(vec![0, 1, 2])
11540        .finish(),
11541    column_comments: BTreeMap::from_iter([
11542        (
11543            "object_name",
11544            "Fully qualified object name (database.schema.name).",
11545        ),
11546        (
11547            "cluster",
11548            "Cluster where the object computes or its index is hosted. The object can be read from any cluster.",
11549        ),
11550        (
11551            "description",
11552            "Index comment if available, otherwise object comment. Used as data product description.",
11553        ),
11554    ]),
11555    sql: r#"
11556SELECT DISTINCT
11557    '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
11558    COALESCE(c_idx.name, c_obj.name) AS cluster,
11559    COALESCE(cts_idx.comment, cts_obj.comment) AS description
11560FROM mz_internal.mz_show_my_object_privileges op
11561JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
11562JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
11563JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
11564LEFT JOIN mz_indexes i ON i.on_id = o.id
11565LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
11566LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
11567LEFT JOIN mz_internal.mz_comments cts_idx ON cts_idx.id = i.id AND cts_idx.object_sub_id IS NULL
11568LEFT JOIN mz_internal.mz_comments cts_obj ON cts_obj.id = o.id AND cts_obj.object_sub_id IS NULL
11569WHERE op.privilege_type = 'SELECT'
11570  AND (o.type = 'materialized-view' OR (o.type = 'view' AND i.id IS NOT NULL))
11571  AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
11572"#,
11573    access: vec![PUBLIC_SELECT],
11574});
11575
11576/// Full data product details with JSON Schema for MCP agents.
11577///
11578/// Extends `mz_mcp_data_products` with column types, index keys (when
11579/// available), and column comments, formatted as a JSON Schema object.
11580/// Used by the `get_data_product_details` MCP tool. Lists materialized
11581/// views and indexed views; non-indexed regular views are excluded to
11582/// avoid triggering full recompute on query. Comments are optional
11583/// enrichment.
11584pub static MZ_MCP_DATA_PRODUCT_DETAILS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11585    name: "mz_mcp_data_product_details",
11586    schema: MZ_INTERNAL_SCHEMA,
11587    oid: oid::VIEW_MZ_MCP_DATA_PRODUCT_DETAILS_OID,
11588    desc: RelationDesc::builder()
11589        .with_column("object_name", SqlScalarType::String.nullable(false))
11590        .with_column("cluster", SqlScalarType::String.nullable(true))
11591        .with_column("description", SqlScalarType::String.nullable(true))
11592        .with_column("schema", SqlScalarType::Jsonb.nullable(false))
11593        .with_key(vec![0, 1, 2])
11594        .finish(),
11595    column_comments: BTreeMap::from_iter([
11596        (
11597            "object_name",
11598            "Fully qualified object name (database.schema.name).",
11599        ),
11600        (
11601            "cluster",
11602            "Cluster where the object computes or its index is hosted. The object can be read from any cluster.",
11603        ),
11604        (
11605            "description",
11606            "Index comment if available, otherwise object comment. Used as data product description.",
11607        ),
11608        (
11609            "schema",
11610            "JSON Schema describing the object's columns and types.",
11611        ),
11612    ]),
11613    sql: r#"
11614SELECT * FROM (
11615    SELECT
11616        '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
11617        COALESCE(c_idx.name, c_obj.name) AS cluster,
11618        COALESCE(cts_idx.comment, cts_obj.comment) AS description,
11619        COALESCE(jsonb_build_object(
11620        'type', 'object',
11621        'required', jsonb_agg(distinct ccol.name) FILTER (WHERE ccol.position = ic.on_position),
11622        'properties', jsonb_strip_nulls(jsonb_object_agg(
11623            ccol.name,
11624            CASE
11625                WHEN ccol.type IN (
11626                    'uint2', 'uint4','uint8', 'int', 'integer', 'smallint',
11627                    'double', 'double precision', 'bigint', 'float',
11628                    'numeric', 'real'
11629                ) THEN jsonb_build_object(
11630                    'type', 'number',
11631                    'description', cts_col.comment
11632                )
11633                WHEN ccol.type = 'boolean' THEN jsonb_build_object(
11634                    'type', 'boolean',
11635                    'description', cts_col.comment
11636                )
11637                WHEN ccol.type = 'bytea' THEN jsonb_build_object(
11638                    'type', 'string',
11639                    'description', cts_col.comment,
11640                    'contentEncoding', 'base64',
11641                    'contentMediaType', 'application/octet-stream'
11642                )
11643                WHEN ccol.type = 'date' THEN jsonb_build_object(
11644                    'type', 'string',
11645                    'format', 'date',
11646                    'description', cts_col.comment
11647                )
11648                WHEN ccol.type = 'time' THEN jsonb_build_object(
11649                    'type', 'string',
11650                    'format', 'time',
11651                    'description', cts_col.comment
11652                )
11653                WHEN ccol.type ilike 'timestamp%%' THEN jsonb_build_object(
11654                    'type', 'string',
11655                    'format', 'date-time',
11656                    'description', cts_col.comment
11657                )
11658                WHEN ccol.type = 'jsonb' THEN jsonb_build_object(
11659                    'type', 'object',
11660                    'description', cts_col.comment
11661                )
11662                WHEN ccol.type = 'uuid' THEN jsonb_build_object(
11663                    'type', 'string',
11664                    'format', 'uuid',
11665                    'description', cts_col.comment
11666                )
11667                ELSE jsonb_build_object(
11668                    'type', 'string',
11669                    'description', cts_col.comment
11670                )
11671            END
11672        ))
11673    ), '{"type": "object", "properties": {}}'::jsonb) AS schema
11674FROM mz_internal.mz_show_my_object_privileges op
11675JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
11676JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
11677JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
11678JOIN mz_columns ccol ON ccol.id = o.id
11679LEFT JOIN mz_indexes i ON i.on_id = o.id
11680LEFT JOIN mz_index_columns ic ON i.id = ic.index_id
11681LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
11682LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
11683LEFT JOIN mz_internal.mz_comments cts_idx ON cts_idx.id = i.id AND cts_idx.object_sub_id IS NULL
11684LEFT JOIN mz_internal.mz_comments cts_obj ON cts_obj.id = o.id AND cts_obj.object_sub_id IS NULL
11685LEFT JOIN mz_internal.mz_comments cts_col ON cts_col.id = o.id AND cts_col.object_sub_id = ccol.position
11686WHERE op.privilege_type = 'SELECT'
11687  AND (o.type = 'materialized-view' OR (o.type = 'view' AND i.id IS NOT NULL))
11688  AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
11689GROUP BY 1, 2, 3
11690)
11691"#,
11692    access: vec![PUBLIC_SELECT],
11693});
11694
11695pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11696    name: "mz_show_role_members",
11697    schema: MZ_INTERNAL_SCHEMA,
11698    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11699    desc: RelationDesc::builder()
11700        .with_column("role", SqlScalarType::String.nullable(false))
11701        .with_column("member", SqlScalarType::String.nullable(false))
11702        .with_column("grantor", SqlScalarType::String.nullable(false))
11703        .finish(),
11704    column_comments: BTreeMap::from_iter([
11705        ("role", "The role that `member` is a member of."),
11706        ("member", "The role that is a member of `role`."),
11707        (
11708            "grantor",
11709            "The role that granted membership of `member` to `role`.",
11710        ),
11711    ]),
11712    sql: r#"SELECT
11713    r1.name AS role,
11714    r2.name AS member,
11715    r3.name AS grantor
11716FROM mz_catalog.mz_role_members rm
11717JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11718JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11719JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11720ORDER BY role"#,
11721    access: vec![PUBLIC_SELECT],
11722});
11723
11724pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11725    name: "mz_show_my_role_members",
11726    schema: MZ_INTERNAL_SCHEMA,
11727    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11728    desc: RelationDesc::builder()
11729        .with_column("role", SqlScalarType::String.nullable(false))
11730        .with_column("member", SqlScalarType::String.nullable(false))
11731        .with_column("grantor", SqlScalarType::String.nullable(false))
11732        .finish(),
11733    column_comments: BTreeMap::from_iter([
11734        ("role", "The role that `member` is a member of."),
11735        ("member", "The role that is a member of `role`."),
11736        (
11737            "grantor",
11738            "The role that granted membership of `member` to `role`.",
11739        ),
11740    ]),
11741    sql: r#"SELECT role, member, grantor
11742FROM mz_internal.mz_show_role_members
11743WHERE pg_has_role(member, 'USAGE')"#,
11744    access: vec![PUBLIC_SELECT],
11745});
11746
11747pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11748    name: "mz_show_system_privileges",
11749    schema: MZ_INTERNAL_SCHEMA,
11750    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11751    desc: RelationDesc::builder()
11752        .with_column("grantor", SqlScalarType::String.nullable(true))
11753        .with_column("grantee", SqlScalarType::String.nullable(true))
11754        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11755        .finish(),
11756    column_comments: BTreeMap::from_iter([
11757        ("grantor", "The role that granted the privilege."),
11758        ("grantee", "The role that the privilege was granted to."),
11759        ("privilege_type", "They type of privilege granted."),
11760    ]),
11761    sql: r#"SELECT
11762    grantor.name AS grantor,
11763    CASE privileges.grantee
11764        WHEN 'p' THEN 'PUBLIC'
11765        ELSE grantee.name
11766    END AS grantee,
11767    privileges.privilege_type AS privilege_type
11768FROM
11769    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11770    FROM mz_catalog.mz_system_privileges) AS privileges
11771LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11772LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11773WHERE privileges.grantee NOT LIKE 's%'"#,
11774    access: vec![PUBLIC_SELECT],
11775});
11776
11777pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11778    name: "mz_show_my_system_privileges",
11779    schema: MZ_INTERNAL_SCHEMA,
11780    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11781    desc: RelationDesc::builder()
11782        .with_column("grantor", SqlScalarType::String.nullable(true))
11783        .with_column("grantee", SqlScalarType::String.nullable(true))
11784        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11785        .finish(),
11786    column_comments: BTreeMap::from_iter([
11787        ("grantor", "The role that granted the privilege."),
11788        ("grantee", "The role that the privilege was granted to."),
11789        ("privilege_type", "They type of privilege granted."),
11790    ]),
11791    sql: r#"SELECT grantor, grantee, privilege_type
11792FROM mz_internal.mz_show_system_privileges
11793WHERE
11794    CASE
11795        WHEN grantee = 'PUBLIC' THEN true
11796        ELSE pg_has_role(grantee, 'USAGE')
11797    END"#,
11798    access: vec![PUBLIC_SELECT],
11799});
11800
11801pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11802    name: "mz_show_cluster_privileges",
11803    schema: MZ_INTERNAL_SCHEMA,
11804    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11805    desc: RelationDesc::builder()
11806        .with_column("grantor", SqlScalarType::String.nullable(true))
11807        .with_column("grantee", SqlScalarType::String.nullable(true))
11808        .with_column("name", SqlScalarType::String.nullable(false))
11809        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11810        .finish(),
11811    column_comments: BTreeMap::from_iter([
11812        ("grantor", "The role that granted the privilege."),
11813        ("grantee", "The role that the privilege was granted to."),
11814        ("name", "The name of the cluster."),
11815        ("privilege_type", "They type of privilege granted."),
11816    ]),
11817    sql: r#"SELECT
11818    grantor.name AS grantor,
11819    CASE privileges.grantee
11820        WHEN 'p' THEN 'PUBLIC'
11821        ELSE grantee.name
11822    END AS grantee,
11823    privileges.name AS name,
11824    privileges.privilege_type AS privilege_type
11825FROM
11826    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11827    FROM mz_catalog.mz_clusters
11828    WHERE id NOT LIKE 's%') AS privileges
11829LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11830LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11831WHERE privileges.grantee NOT LIKE 's%'"#,
11832    access: vec![PUBLIC_SELECT],
11833});
11834
11835pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11836    name: "mz_show_my_cluster_privileges",
11837    schema: MZ_INTERNAL_SCHEMA,
11838    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11839    desc: RelationDesc::builder()
11840        .with_column("grantor", SqlScalarType::String.nullable(true))
11841        .with_column("grantee", SqlScalarType::String.nullable(true))
11842        .with_column("name", SqlScalarType::String.nullable(false))
11843        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11844        .finish(),
11845    column_comments: BTreeMap::from_iter([
11846        ("grantor", "The role that granted the privilege."),
11847        ("grantee", "The role that the privilege was granted to."),
11848        ("name", "The name of the cluster."),
11849        ("privilege_type", "They type of privilege granted."),
11850    ]),
11851    sql: r#"SELECT grantor, grantee, name, privilege_type
11852FROM mz_internal.mz_show_cluster_privileges
11853WHERE
11854    CASE
11855        WHEN grantee = 'PUBLIC' THEN true
11856        ELSE pg_has_role(grantee, 'USAGE')
11857    END"#,
11858    access: vec![PUBLIC_SELECT],
11859});
11860
11861pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11862    name: "mz_show_database_privileges",
11863    schema: MZ_INTERNAL_SCHEMA,
11864    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
11865    desc: RelationDesc::builder()
11866        .with_column("grantor", SqlScalarType::String.nullable(true))
11867        .with_column("grantee", SqlScalarType::String.nullable(true))
11868        .with_column("name", SqlScalarType::String.nullable(false))
11869        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11870        .finish(),
11871    column_comments: BTreeMap::from_iter([
11872        ("grantor", "The role that granted the privilege."),
11873        ("grantee", "The role that the privilege was granted to."),
11874        ("name", "The name of the database."),
11875        ("privilege_type", "They type of privilege granted."),
11876    ]),
11877    sql: r#"SELECT
11878    grantor.name AS grantor,
11879    CASE privileges.grantee
11880        WHEN 'p' THEN 'PUBLIC'
11881        ELSE grantee.name
11882    END AS grantee,
11883    privileges.name AS name,
11884    privileges.privilege_type AS privilege_type
11885FROM
11886    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11887    FROM mz_catalog.mz_databases
11888    WHERE id NOT LIKE 's%') AS privileges
11889LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11890LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11891WHERE privileges.grantee NOT LIKE 's%'"#,
11892    access: vec![PUBLIC_SELECT],
11893});
11894
11895pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11896    name: "mz_show_my_database_privileges",
11897    schema: MZ_INTERNAL_SCHEMA,
11898    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
11899    desc: RelationDesc::builder()
11900        .with_column("grantor", SqlScalarType::String.nullable(true))
11901        .with_column("grantee", SqlScalarType::String.nullable(true))
11902        .with_column("name", SqlScalarType::String.nullable(false))
11903        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11904        .finish(),
11905    column_comments: BTreeMap::from_iter([
11906        ("grantor", "The role that granted the privilege."),
11907        ("grantee", "The role that the privilege was granted to."),
11908        ("name", "The name of the cluster."),
11909        ("privilege_type", "They type of privilege granted."),
11910    ]),
11911    sql: r#"SELECT grantor, grantee, name, privilege_type
11912FROM mz_internal.mz_show_database_privileges
11913WHERE
11914    CASE
11915        WHEN grantee = 'PUBLIC' THEN true
11916        ELSE pg_has_role(grantee, 'USAGE')
11917    END"#,
11918    access: vec![PUBLIC_SELECT],
11919});
11920
11921pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11922    name: "mz_show_schema_privileges",
11923    schema: MZ_INTERNAL_SCHEMA,
11924    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
11925    desc: RelationDesc::builder()
11926        .with_column("grantor", SqlScalarType::String.nullable(true))
11927        .with_column("grantee", SqlScalarType::String.nullable(true))
11928        .with_column("database", SqlScalarType::String.nullable(true))
11929        .with_column("name", SqlScalarType::String.nullable(false))
11930        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11931        .finish(),
11932    column_comments: BTreeMap::from_iter([
11933        ("grantor", "The role that granted the privilege."),
11934        ("grantee", "The role that the privilege was granted to."),
11935        (
11936            "database",
11937            "The name of the database containing the schema.",
11938        ),
11939        ("name", "The name of the schema."),
11940        ("privilege_type", "They type of privilege granted."),
11941    ]),
11942    sql: r#"SELECT
11943    grantor.name AS grantor,
11944    CASE privileges.grantee
11945        WHEN 'p' THEN 'PUBLIC'
11946        ELSE grantee.name
11947    END AS grantee,
11948    databases.name AS database,
11949    privileges.name AS name,
11950    privileges.privilege_type AS privilege_type
11951FROM
11952    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
11953    FROM mz_catalog.mz_schemas
11954    WHERE id NOT LIKE 's%') AS privileges
11955LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11956LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11957LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
11958WHERE privileges.grantee NOT LIKE 's%'"#,
11959    access: vec![PUBLIC_SELECT],
11960});
11961
11962pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11963    name: "mz_show_my_schema_privileges",
11964    schema: MZ_INTERNAL_SCHEMA,
11965    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
11966    desc: RelationDesc::builder()
11967        .with_column("grantor", SqlScalarType::String.nullable(true))
11968        .with_column("grantee", SqlScalarType::String.nullable(true))
11969        .with_column("database", SqlScalarType::String.nullable(true))
11970        .with_column("name", SqlScalarType::String.nullable(false))
11971        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11972        .finish(),
11973    column_comments: BTreeMap::from_iter([
11974        ("grantor", "The role that granted the privilege."),
11975        ("grantee", "The role that the privilege was granted to."),
11976        (
11977            "database",
11978            "The name of the database containing the schema.",
11979        ),
11980        ("name", "The name of the schema."),
11981        ("privilege_type", "They type of privilege granted."),
11982    ]),
11983    sql: r#"SELECT grantor, grantee, database, name, privilege_type
11984FROM mz_internal.mz_show_schema_privileges
11985WHERE
11986    CASE
11987        WHEN grantee = 'PUBLIC' THEN true
11988        ELSE pg_has_role(grantee, 'USAGE')
11989    END"#,
11990    access: vec![PUBLIC_SELECT],
11991});
11992
11993pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11994    name: "mz_show_object_privileges",
11995    schema: MZ_INTERNAL_SCHEMA,
11996    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
11997    desc: RelationDesc::builder()
11998        .with_column("grantor", SqlScalarType::String.nullable(true))
11999        .with_column("grantee", SqlScalarType::String.nullable(true))
12000        .with_column("database", SqlScalarType::String.nullable(true))
12001        .with_column("schema", SqlScalarType::String.nullable(true))
12002        .with_column("name", SqlScalarType::String.nullable(false))
12003        .with_column("object_type", SqlScalarType::String.nullable(false))
12004        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12005        .finish(),
12006    column_comments: BTreeMap::from_iter([
12007        ("grantor", "The role that granted the privilege."),
12008        ("grantee", "The role that the privilege was granted to."),
12009        (
12010            "database",
12011            "The name of the database containing the object.",
12012        ),
12013        ("schema", "The name of the schema containing the object."),
12014        ("name", "The name of the object."),
12015        (
12016            "object_type",
12017            "The type of object the privilege is granted on.",
12018        ),
12019        ("privilege_type", "They type of privilege granted."),
12020    ]),
12021    sql: r#"SELECT
12022    grantor.name AS grantor,
12023    CASE privileges.grantee
12024            WHEN 'p' THEN 'PUBLIC'
12025            ELSE grantee.name
12026        END AS grantee,
12027    databases.name AS database,
12028    schemas.name AS schema,
12029    privileges.name AS name,
12030    privileges.type AS object_type,
12031    privileges.privilege_type AS privilege_type
12032FROM
12033    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
12034    FROM mz_catalog.mz_objects
12035    WHERE id NOT LIKE 's%') AS privileges
12036LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
12037LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
12038LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
12039LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
12040WHERE privileges.grantee NOT LIKE 's%'"#,
12041    access: vec![PUBLIC_SELECT],
12042});
12043
12044pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12045    name: "mz_show_my_object_privileges",
12046    schema: MZ_INTERNAL_SCHEMA,
12047    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
12048    desc: RelationDesc::builder()
12049        .with_column("grantor", SqlScalarType::String.nullable(true))
12050        .with_column("grantee", SqlScalarType::String.nullable(true))
12051        .with_column("database", SqlScalarType::String.nullable(true))
12052        .with_column("schema", SqlScalarType::String.nullable(true))
12053        .with_column("name", SqlScalarType::String.nullable(false))
12054        .with_column("object_type", SqlScalarType::String.nullable(false))
12055        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12056        .finish(),
12057    column_comments: BTreeMap::from_iter([
12058        ("grantor", "The role that granted the privilege."),
12059        ("grantee", "The role that the privilege was granted to."),
12060        (
12061            "database",
12062            "The name of the database containing the object.",
12063        ),
12064        ("schema", "The name of the schema containing the object."),
12065        ("name", "The name of the object."),
12066        (
12067            "object_type",
12068            "The type of object the privilege is granted on.",
12069        ),
12070        ("privilege_type", "They type of privilege granted."),
12071    ]),
12072    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12073FROM mz_internal.mz_show_object_privileges
12074WHERE
12075    CASE
12076        WHEN grantee = 'PUBLIC' THEN true
12077        ELSE pg_has_role(grantee, 'USAGE')
12078    END"#,
12079    access: vec![PUBLIC_SELECT],
12080});
12081
12082pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12083    name: "mz_show_all_privileges",
12084    schema: MZ_INTERNAL_SCHEMA,
12085    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
12086    desc: RelationDesc::builder()
12087        .with_column("grantor", SqlScalarType::String.nullable(true))
12088        .with_column("grantee", SqlScalarType::String.nullable(true))
12089        .with_column("database", SqlScalarType::String.nullable(true))
12090        .with_column("schema", SqlScalarType::String.nullable(true))
12091        .with_column("name", SqlScalarType::String.nullable(true))
12092        .with_column("object_type", SqlScalarType::String.nullable(false))
12093        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12094        .finish(),
12095    column_comments: BTreeMap::from_iter([
12096        ("grantor", "The role that granted the privilege."),
12097        ("grantee", "The role that the privilege was granted to."),
12098        (
12099            "database",
12100            "The name of the database containing the object.",
12101        ),
12102        ("schema", "The name of the schema containing the object."),
12103        ("name", "The name of the privilege target."),
12104        (
12105            "object_type",
12106            "The type of object the privilege is granted on.",
12107        ),
12108        ("privilege_type", "They type of privilege granted."),
12109    ]),
12110    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
12111FROM mz_internal.mz_show_system_privileges
12112UNION ALL
12113SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
12114FROM mz_internal.mz_show_cluster_privileges
12115UNION ALL
12116SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
12117FROM mz_internal.mz_show_database_privileges
12118UNION ALL
12119SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
12120FROM mz_internal.mz_show_schema_privileges
12121UNION ALL
12122SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12123FROM mz_internal.mz_show_object_privileges"#,
12124    access: vec![PUBLIC_SELECT],
12125});
12126
12127pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12128    name: "mz_show_all_my_privileges",
12129    schema: MZ_INTERNAL_SCHEMA,
12130    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
12131    desc: RelationDesc::builder()
12132        .with_column("grantor", SqlScalarType::String.nullable(true))
12133        .with_column("grantee", SqlScalarType::String.nullable(true))
12134        .with_column("database", SqlScalarType::String.nullable(true))
12135        .with_column("schema", SqlScalarType::String.nullable(true))
12136        .with_column("name", SqlScalarType::String.nullable(true))
12137        .with_column("object_type", SqlScalarType::String.nullable(false))
12138        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12139        .finish(),
12140    column_comments: BTreeMap::from_iter([
12141        ("grantor", "The role that granted the privilege."),
12142        ("grantee", "The role that the privilege was granted to."),
12143        (
12144            "database",
12145            "The name of the database containing the object.",
12146        ),
12147        ("schema", "The name of the schema containing the object."),
12148        ("name", "The name of the privilege target."),
12149        (
12150            "object_type",
12151            "The type of object the privilege is granted on.",
12152        ),
12153        ("privilege_type", "They type of privilege granted."),
12154    ]),
12155    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12156FROM mz_internal.mz_show_all_privileges
12157WHERE
12158    CASE
12159        WHEN grantee = 'PUBLIC' THEN true
12160        ELSE pg_has_role(grantee, 'USAGE')
12161    END"#,
12162    access: vec![PUBLIC_SELECT],
12163});
12164
12165pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12166    name: "mz_show_default_privileges",
12167    schema: MZ_INTERNAL_SCHEMA,
12168    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
12169    desc: RelationDesc::builder()
12170        .with_column("object_owner", SqlScalarType::String.nullable(true))
12171        .with_column("database", SqlScalarType::String.nullable(true))
12172        .with_column("schema", SqlScalarType::String.nullable(true))
12173        .with_column("object_type", SqlScalarType::String.nullable(false))
12174        .with_column("grantee", SqlScalarType::String.nullable(true))
12175        .with_column("privilege_type", SqlScalarType::String.nullable(true))
12176        .finish(),
12177    column_comments: BTreeMap::from_iter([
12178        (
12179            "object_owner",
12180            "Privileges described in this row will be granted on objects created by `object_owner`.",
12181        ),
12182        (
12183            "database",
12184            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
12185        ),
12186        (
12187            "schema",
12188            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
12189        ),
12190        (
12191            "object_type",
12192            "Privileges described in this row will be granted only on objects of type `object_type`.",
12193        ),
12194        (
12195            "grantee",
12196            "Privileges described in this row will be granted to `grantee`.",
12197        ),
12198        ("privilege_type", "They type of privilege to be granted."),
12199    ]),
12200    sql: r#"SELECT
12201    CASE defaults.role_id
12202        WHEN 'p' THEN 'PUBLIC'
12203        ELSE object_owner.name
12204    END AS object_owner,
12205    databases.name AS database,
12206    schemas.name AS schema,
12207    object_type,
12208    CASE defaults.grantee
12209        WHEN 'p' THEN 'PUBLIC'
12210        ELSE grantee.name
12211    END AS grantee,
12212    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
12213FROM mz_catalog.mz_default_privileges defaults
12214LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
12215LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
12216LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
12217LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
12218WHERE defaults.grantee NOT LIKE 's%'
12219    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
12220    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
12221    access: vec![PUBLIC_SELECT],
12222});
12223
12224pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12225    name: "mz_show_my_default_privileges",
12226    schema: MZ_INTERNAL_SCHEMA,
12227    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
12228    desc: RelationDesc::builder()
12229        .with_column("object_owner", SqlScalarType::String.nullable(true))
12230        .with_column("database", SqlScalarType::String.nullable(true))
12231        .with_column("schema", SqlScalarType::String.nullable(true))
12232        .with_column("object_type", SqlScalarType::String.nullable(false))
12233        .with_column("grantee", SqlScalarType::String.nullable(true))
12234        .with_column("privilege_type", SqlScalarType::String.nullable(true))
12235        .finish(),
12236    column_comments: BTreeMap::from_iter([
12237        (
12238            "object_owner",
12239            "Privileges described in this row will be granted on objects created by `object_owner`.",
12240        ),
12241        (
12242            "database",
12243            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
12244        ),
12245        (
12246            "schema",
12247            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
12248        ),
12249        (
12250            "object_type",
12251            "Privileges described in this row will be granted only on objects of type `object_type`.",
12252        ),
12253        (
12254            "grantee",
12255            "Privileges described in this row will be granted to `grantee`.",
12256        ),
12257        ("privilege_type", "They type of privilege to be granted."),
12258    ]),
12259    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
12260FROM mz_internal.mz_show_default_privileges
12261WHERE
12262    CASE
12263        WHEN grantee = 'PUBLIC' THEN true
12264        ELSE pg_has_role(grantee, 'USAGE')
12265    END"#,
12266    access: vec![PUBLIC_SELECT],
12267});
12268
12269pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12270    name: "mz_show_network_policies",
12271    schema: MZ_INTERNAL_SCHEMA,
12272    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
12273    desc: RelationDesc::builder()
12274        .with_column("name", SqlScalarType::String.nullable(false))
12275        .with_column("rules", SqlScalarType::String.nullable(true))
12276        .with_column("comment", SqlScalarType::String.nullable(false))
12277        .finish(),
12278    column_comments: BTreeMap::new(),
12279    sql: "
12280WITH comments AS (
12281    SELECT id, comment
12282    FROM mz_internal.mz_comments
12283    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
12284)
12285SELECT
12286    policy.name,
12287    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
12288    COALESCE(comment, '') as comment
12289FROM
12290    mz_internal.mz_network_policies as policy
12291LEFT JOIN
12292    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
12293LEFT JOIN
12294    comments ON policy.id = comments.id
12295WHERE
12296    policy.id NOT LIKE 's%'
12297AND
12298    policy.id NOT LIKE 'g%'
12299GROUP BY policy.name, comments.comment;",
12300    access: vec![PUBLIC_SELECT],
12301});
12302
12303pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12304    name: "mz_cluster_replica_history",
12305    schema: MZ_INTERNAL_SCHEMA,
12306    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
12307    desc: RelationDesc::builder()
12308        .with_column("replica_id", SqlScalarType::String.nullable(true))
12309        .with_column("size", SqlScalarType::String.nullable(true))
12310        .with_column("cluster_id", SqlScalarType::String.nullable(true))
12311        .with_column("cluster_name", SqlScalarType::String.nullable(true))
12312        .with_column("replica_name", SqlScalarType::String.nullable(true))
12313        .with_column(
12314            "created_at",
12315            SqlScalarType::TimestampTz { precision: None }.nullable(false),
12316        )
12317        .with_column(
12318            "dropped_at",
12319            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12320        )
12321        .with_column(
12322            "credits_per_hour",
12323            SqlScalarType::Numeric { max_scale: None }.nullable(true),
12324        )
12325        .finish(),
12326    column_comments: BTreeMap::from_iter([
12327        ("replica_id", "The ID of a cluster replica."),
12328        (
12329            "size",
12330            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
12331        ),
12332        (
12333            "cluster_id",
12334            "The ID of the cluster associated with the replica.",
12335        ),
12336        (
12337            "cluster_name",
12338            "The name of the cluster associated with the replica.",
12339        ),
12340        ("replica_name", "The name of the replica."),
12341        ("created_at", "The time at which the replica was created."),
12342        (
12343            "dropped_at",
12344            "The time at which the replica was dropped, or `NULL` if it still exists.",
12345        ),
12346        (
12347            "credits_per_hour",
12348            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
12349        ),
12350    ]),
12351    sql: r#"
12352        WITH
12353            creates AS
12354            (
12355                SELECT
12356                    details ->> 'logical_size' AS size,
12357                    details ->> 'replica_id' AS replica_id,
12358                    details ->> 'replica_name' AS replica_name,
12359                    details ->> 'cluster_name' AS cluster_name,
12360                    details ->> 'cluster_id' AS cluster_id,
12361                    occurred_at
12362                FROM mz_catalog.mz_audit_events
12363                WHERE
12364                    object_type = 'cluster-replica' AND event_type = 'create'
12365                        AND
12366                    details ->> 'replica_id' IS NOT NULL
12367                        AND
12368                    details ->> 'cluster_id' !~~ 's%'
12369            ),
12370            drops AS
12371            (
12372                SELECT details ->> 'replica_id' AS replica_id, occurred_at
12373                FROM mz_catalog.mz_audit_events
12374                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
12375            )
12376        SELECT
12377            creates.replica_id,
12378            creates.size,
12379            creates.cluster_id,
12380            creates.cluster_name,
12381            creates.replica_name,
12382            creates.occurred_at AS created_at,
12383            drops.occurred_at AS dropped_at,
12384            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
12385        FROM
12386            creates
12387                LEFT JOIN drops ON creates.replica_id = drops.replica_id
12388                LEFT JOIN
12389                    mz_catalog.mz_cluster_replica_sizes
12390                    ON mz_cluster_replica_sizes.size = creates.size"#,
12391    access: vec![PUBLIC_SELECT],
12392});
12393
12394pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12395    name: "mz_cluster_replica_name_history",
12396    schema: MZ_INTERNAL_SCHEMA,
12397    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
12398    desc: RelationDesc::builder()
12399        .with_column(
12400            "occurred_at",
12401            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12402        )
12403        .with_column("id", SqlScalarType::String.nullable(true))
12404        .with_column("previous_name", SqlScalarType::String.nullable(true))
12405        .with_column("new_name", SqlScalarType::String.nullable(true))
12406        .finish(),
12407    column_comments: BTreeMap::from_iter([
12408        (
12409            "occurred_at",
12410            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
12411        ),
12412        ("id", "The ID of the cluster replica."),
12413        (
12414            "previous_name",
12415            "The previous name of the cluster replica. `NULL` if there was no previous name.",
12416        ),
12417        ("new_name", "The new name of the cluster replica."),
12418    ]),
12419    sql: r#"WITH user_replica_alter_history AS (
12420  SELECT occurred_at,
12421    audit_events.details->>'replica_id' AS id,
12422    audit_events.details->>'old_name' AS previous_name,
12423    audit_events.details->>'new_name' AS new_name
12424  FROM mz_catalog.mz_audit_events AS audit_events
12425  WHERE object_type = 'cluster-replica'
12426    AND audit_events.event_type = 'alter'
12427    AND audit_events.details->>'replica_id' like 'u%'
12428),
12429user_replica_create_history AS (
12430  SELECT occurred_at,
12431    audit_events.details->>'replica_id' AS id,
12432    NULL AS previous_name,
12433    audit_events.details->>'replica_name' AS new_name
12434  FROM mz_catalog.mz_audit_events AS audit_events
12435  WHERE object_type = 'cluster-replica'
12436    AND audit_events.event_type = 'create'
12437    AND audit_events.details->>'replica_id' like 'u%'
12438),
12439-- Because built in system cluster replicas don't have audit events, we need to manually add them
12440system_replicas AS (
12441  -- We assume that the system cluster replicas were created at the beginning of time
12442  SELECT NULL::timestamptz AS occurred_at,
12443    id,
12444    NULL AS previous_name,
12445    name AS new_name
12446  FROM mz_catalog.mz_cluster_replicas
12447  WHERE id LIKE 's%'
12448)
12449SELECT *
12450FROM user_replica_alter_history
12451UNION ALL
12452SELECT *
12453FROM user_replica_create_history
12454UNION ALL
12455SELECT *
12456FROM system_replicas"#,
12457    access: vec![PUBLIC_SELECT],
12458});
12459
12460pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12461    name: "mz_hydration_statuses",
12462    schema: MZ_INTERNAL_SCHEMA,
12463    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
12464    desc: RelationDesc::builder()
12465        .with_column("object_id", SqlScalarType::String.nullable(false))
12466        .with_column("replica_id", SqlScalarType::String.nullable(true))
12467        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
12468        .finish(),
12469    column_comments: BTreeMap::from_iter([
12470        (
12471            "object_id",
12472            "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`.",
12473        ),
12474        ("replica_id", "The ID of a cluster replica."),
12475        ("hydrated", "Whether the object is hydrated on the replica."),
12476    ]),
12477    sql: r#"WITH
12478-- Joining against the linearizable catalog tables ensures that this view
12479-- always contains the set of installed objects, even when it depends
12480-- on introspection relations that may received delayed updates.
12481--
12482-- Note that this view only includes objects that are maintained by dataflows.
12483-- In particular, some source types (webhook, introspection, ...) are not and
12484-- are therefore omitted.
12485indexes AS (
12486    SELECT
12487        i.id AS object_id,
12488        h.replica_id,
12489        COALESCE(h.hydrated, false) AS hydrated
12490    FROM mz_catalog.mz_indexes i
12491    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12492        ON (h.object_id = i.id)
12493),
12494materialized_views AS (
12495    SELECT
12496        i.id AS object_id,
12497        h.replica_id,
12498        COALESCE(h.hydrated, false) AS hydrated
12499    FROM mz_catalog.mz_materialized_views i
12500    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12501        ON (h.object_id = i.id)
12502),
12503-- Hydration is a dataflow concept and not all sources are maintained by
12504-- dataflows, so we need to find the ones that are. Generally, sources that
12505-- have a cluster ID are maintained by a dataflow running on that cluster.
12506-- Webhook sources are an exception to this rule.
12507sources_with_clusters AS (
12508    SELECT id, cluster_id
12509    FROM mz_catalog.mz_sources
12510    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12511),
12512sources AS (
12513    SELECT
12514        s.id AS object_id,
12515        ss.replica_id AS replica_id,
12516        ss.rehydration_latency IS NOT NULL AS hydrated
12517    FROM sources_with_clusters s
12518    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12519),
12520-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12521-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12522-- There is likely still a possibility of FPs.
12523sinks AS (
12524    SELECT
12525        s.id AS object_id,
12526        r.id AS replica_id,
12527        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12528    FROM mz_catalog.mz_sinks s
12529    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12530    JOIN mz_catalog.mz_cluster_replicas r
12531        ON (r.cluster_id = s.cluster_id)
12532    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12533        ON (f.object_id = s.id AND f.replica_id = r.id)
12534)
12535SELECT * FROM indexes
12536UNION ALL
12537SELECT * FROM materialized_views
12538UNION ALL
12539SELECT * FROM sources
12540UNION ALL
12541SELECT * FROM sinks"#,
12542    access: vec![PUBLIC_SELECT],
12543});
12544
12545pub const MZ_HYDRATION_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12546    name: "mz_hydration_statuses_ind",
12547    schema: MZ_INTERNAL_SCHEMA,
12548    oid: oid::INDEX_MZ_HYDRATION_STATUSES_IND_OID,
12549    sql: "IN CLUSTER mz_catalog_server
12550ON mz_internal.mz_hydration_statuses (object_id, replica_id)",
12551    is_retained_metrics_object: false,
12552};
12553
12554pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12555    name: "mz_materialization_dependencies",
12556    schema: MZ_INTERNAL_SCHEMA,
12557    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12558    desc: RelationDesc::builder()
12559        .with_column("object_id", SqlScalarType::String.nullable(false))
12560        .with_column("dependency_id", SqlScalarType::String.nullable(false))
12561        .finish(),
12562    column_comments: BTreeMap::from_iter([
12563        (
12564            "object_id",
12565            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12566        ),
12567        (
12568            "dependency_id",
12569            "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`.",
12570        ),
12571    ]),
12572    sql: "
12573SELECT object_id, dependency_id
12574FROM mz_internal.mz_compute_dependencies
12575UNION ALL
12576SELECT s.id, d.referenced_object_id AS dependency_id
12577FROM mz_internal.mz_object_dependencies d
12578JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12579JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12580    access: vec![PUBLIC_SELECT],
12581});
12582
12583pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12584    name: "mz_materialization_lag",
12585    schema: MZ_INTERNAL_SCHEMA,
12586    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12587    desc: RelationDesc::builder()
12588        .with_column("object_id", SqlScalarType::String.nullable(false))
12589        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
12590        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
12591        .with_column(
12592            "slowest_local_input_id",
12593            SqlScalarType::String.nullable(false),
12594        )
12595        .with_column(
12596            "slowest_global_input_id",
12597            SqlScalarType::String.nullable(false),
12598        )
12599        .finish(),
12600    column_comments: BTreeMap::from_iter([
12601        (
12602            "object_id",
12603            "The ID of the materialized view, index, or sink.",
12604        ),
12605        (
12606            "local_lag",
12607            "The amount of time the materialization lags behind its direct inputs.",
12608        ),
12609        (
12610            "global_lag",
12611            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12612        ),
12613        (
12614            "slowest_local_input_id",
12615            "The ID of the slowest direct input.",
12616        ),
12617        (
12618            "slowest_global_input_id",
12619            "The ID of the slowest root input.",
12620        ),
12621    ]),
12622    sql: "
12623WITH MUTUALLY RECURSIVE
12624    -- IDs of objects for which we want to know the lag.
12625    materializations (id text) AS (
12626        SELECT id FROM mz_catalog.mz_indexes
12627        UNION ALL
12628        SELECT id FROM mz_catalog.mz_materialized_views
12629        UNION ALL
12630        SELECT id FROM mz_catalog.mz_sinks
12631    ),
12632    -- Direct dependencies of materializations.
12633    direct_dependencies (id text, dep_id text) AS (
12634        SELECT m.id, d.dependency_id
12635        FROM materializations m
12636        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12637    ),
12638    -- All transitive dependencies of materializations.
12639    transitive_dependencies (id text, dep_id text) AS (
12640        SELECT id, dep_id FROM direct_dependencies
12641        UNION
12642        SELECT td.id, dd.dep_id
12643        FROM transitive_dependencies td
12644        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12645    ),
12646    -- Root dependencies of materializations (sources and tables).
12647    root_dependencies (id text, dep_id text) AS (
12648        SELECT *
12649        FROM transitive_dependencies td
12650        WHERE NOT EXISTS (
12651            SELECT 1
12652            FROM direct_dependencies dd
12653            WHERE dd.id = td.dep_id
12654        )
12655    ),
12656    -- Write progress times of materializations.
12657    materialization_times (id text, time timestamptz) AS (
12658        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12659        FROM materializations m
12660        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12661    ),
12662    -- Write progress times of direct dependencies of materializations.
12663    input_times (id text, slowest_dep text, time timestamptz) AS (
12664        SELECT DISTINCT ON (d.id)
12665            d.id,
12666            d.dep_id,
12667            to_timestamp(f.write_frontier::text::double / 1000)
12668        FROM direct_dependencies d
12669        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12670        ORDER BY d.id, f.write_frontier ASC
12671    ),
12672    -- Write progress times of root dependencies of materializations.
12673    root_times (id text, slowest_dep text, time timestamptz) AS (
12674        SELECT DISTINCT ON (d.id)
12675            d.id,
12676            d.dep_id,
12677            to_timestamp(f.write_frontier::text::double / 1000)
12678        FROM root_dependencies d
12679        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12680        ORDER BY d.id, f.write_frontier ASC
12681    )
12682SELECT
12683    id AS object_id,
12684    -- Ensure that lag values are always NULL for materializations that have reached the empty
12685    -- frontier, as those have processed all their input data.
12686    -- Also make sure that lag values are never negative, even when input frontiers are before
12687    -- output frontiers (as can happen during hydration).
12688    CASE
12689        WHEN m.time IS NULL THEN INTERVAL '0'
12690        WHEN i.time IS NULL THEN NULL
12691        ELSE greatest(i.time - m.time, INTERVAL '0')
12692    END AS local_lag,
12693    CASE
12694        WHEN m.time IS NULL THEN INTERVAL '0'
12695        WHEN r.time IS NULL THEN NULL
12696        ELSE greatest(r.time - m.time, INTERVAL '0')
12697    END AS global_lag,
12698    i.slowest_dep AS slowest_local_input_id,
12699    r.slowest_dep AS slowest_global_input_id
12700FROM materialization_times m
12701JOIN input_times i USING (id)
12702JOIN root_times r USING (id)",
12703    access: vec![PUBLIC_SELECT],
12704});
12705
12706/**
12707 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12708 * It's specifically for the Console's environment overview page to speed up load times.
12709 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12710 */
12711pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12712    BuiltinView {
12713        name: "mz_console_cluster_utilization_overview",
12714        schema: MZ_INTERNAL_SCHEMA,
12715        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12716        desc: RelationDesc::builder()
12717            .with_column(
12718                "bucket_start",
12719                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12720            )
12721            .with_column("replica_id", SqlScalarType::String.nullable(false))
12722            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
12723            .with_column(
12724                "max_memory_at",
12725                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12726            )
12727            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
12728            .with_column(
12729                "max_disk_at",
12730                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12731            )
12732            .with_column(
12733                "memory_and_disk_percent",
12734                SqlScalarType::Float64.nullable(true),
12735            )
12736            .with_column(
12737                "max_memory_and_disk_memory_percent",
12738                SqlScalarType::Float64.nullable(true),
12739            )
12740            .with_column(
12741                "max_memory_and_disk_disk_percent",
12742                SqlScalarType::Float64.nullable(true),
12743            )
12744            .with_column(
12745                "max_memory_and_disk_at",
12746                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12747            )
12748            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
12749            .with_column(
12750                "max_heap_at",
12751                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12752            )
12753            .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
12754            .with_column(
12755                "max_cpu_at",
12756                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12757            )
12758            .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
12759            .with_column(
12760                "bucket_end",
12761                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12762            )
12763            .with_column("name", SqlScalarType::String.nullable(true))
12764            .with_column("cluster_id", SqlScalarType::String.nullable(true))
12765            .with_column("size", SqlScalarType::String.nullable(true))
12766            .finish(),
12767        column_comments: BTreeMap::new(),
12768        sql: r#"WITH replica_history AS (
12769  SELECT replica_id,
12770    size,
12771    cluster_id
12772  FROM mz_internal.mz_cluster_replica_history
12773  UNION
12774  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12775  SELECT id AS replica_id,
12776    size,
12777    cluster_id
12778  FROM mz_catalog.mz_cluster_replicas
12779),
12780replica_metrics_history AS (
12781  SELECT
12782    m.occurred_at,
12783    m.replica_id,
12784    r.size,
12785    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0)) / NULLIF(s.processes, 0) AS cpu_percent,
12786    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0)) / NULLIF(s.processes, 0) AS memory_percent,
12787    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0)) / NULLIF(s.processes, 0) AS disk_percent,
12788    (SUM(m.heap_bytes::float8) / NULLIF(m.heap_limit, 0)) / NULLIF(s.processes, 0) AS heap_percent,
12789    SUM(m.disk_bytes::float8) AS disk_bytes,
12790    SUM(m.memory_bytes::float8) AS memory_bytes,
12791    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12792    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12793  FROM
12794    replica_history AS r
12795    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12796    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12797  GROUP BY
12798    m.occurred_at,
12799    m.replica_id,
12800    r.size,
12801    s.cpu_nano_cores,
12802    s.memory_bytes,
12803    s.disk_bytes,
12804    m.heap_limit,
12805    s.processes
12806),
12807replica_utilization_history_binned AS (
12808  SELECT m.occurred_at,
12809    m.replica_id,
12810    m.cpu_percent,
12811    m.memory_percent,
12812    m.memory_bytes,
12813    m.disk_percent,
12814    m.disk_bytes,
12815    m.heap_percent,
12816    m.total_disk_bytes,
12817    m.total_memory_bytes,
12818    m.size,
12819    date_bin(
12820      '8 HOURS',
12821      occurred_at,
12822      '1970-01-01'::timestamp
12823    ) AS bucket_start
12824  FROM replica_history AS r
12825    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12826  WHERE mz_now() <= date_bin(
12827      '8 HOURS',
12828      occurred_at,
12829      '1970-01-01'::timestamp
12830    ) + INTERVAL '14 DAYS'
12831),
12832-- For each (replica, bucket), take the (replica, bucket) with the highest memory
12833max_memory AS (
12834  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12835    replica_id,
12836    memory_percent,
12837    occurred_at
12838  FROM replica_utilization_history_binned
12839  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12840  ORDER BY bucket_start,
12841    replica_id,
12842    COALESCE(memory_bytes, 0) DESC
12843),
12844max_disk AS (
12845  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12846    replica_id,
12847    disk_percent,
12848    occurred_at
12849  FROM replica_utilization_history_binned
12850  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12851  ORDER BY bucket_start,
12852    replica_id,
12853    COALESCE(disk_bytes, 0) DESC
12854),
12855max_cpu AS (
12856  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12857    replica_id,
12858    cpu_percent,
12859    occurred_at
12860  FROM replica_utilization_history_binned
12861  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12862  ORDER BY bucket_start,
12863    replica_id,
12864    COALESCE(cpu_percent, 0) DESC
12865),
12866/*
12867 This is different
12868 from adding max_memory
12869 and max_disk per bucket because both
12870 values may not occur at the same time if the bucket interval is large.
12871 */
12872max_memory_and_disk AS (
12873  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12874    replica_id,
12875    memory_percent,
12876    disk_percent,
12877    memory_and_disk_percent,
12878    occurred_at
12879  FROM (
12880      SELECT *,
12881        CASE
12882          WHEN disk_bytes IS NULL
12883          AND memory_bytes IS NULL THEN NULL
12884          ELSE (COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0))
12885               / (total_disk_bytes::numeric + total_memory_bytes::numeric)
12886        END AS memory_and_disk_percent
12887      FROM replica_utilization_history_binned
12888    ) AS max_memory_and_disk_inner
12889  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12890  ORDER BY bucket_start,
12891    replica_id,
12892    COALESCE(memory_and_disk_percent, 0) DESC
12893),
12894max_heap AS (
12895  SELECT DISTINCT ON (bucket_start, replica_id)
12896    bucket_start,
12897    replica_id,
12898    heap_percent,
12899    occurred_at
12900  FROM replica_utilization_history_binned
12901  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12902  ORDER BY bucket_start, replica_id, COALESCE(heap_percent, 0) DESC
12903),
12904-- For each (replica, bucket), get its offline events at that time
12905replica_offline_event_history AS (
12906  SELECT date_bin(
12907      '8 HOURS',
12908      occurred_at,
12909      '1970-01-01'::timestamp
12910    ) AS bucket_start,
12911    replica_id,
12912    jsonb_agg(
12913      jsonb_build_object(
12914        'replicaId',
12915        rsh.replica_id,
12916        'occurredAt',
12917        rsh.occurred_at,
12918        'status',
12919        rsh.status,
12920        'reason',
12921        rsh.reason
12922      )
12923    ) AS offline_events
12924  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
12925  WHERE process_id = '0'
12926    AND status = 'offline'
12927    AND mz_now() <= date_bin(
12928      '8 HOURS',
12929      occurred_at,
12930      '1970-01-01'::timestamp
12931    ) + INTERVAL '14 DAYS'
12932  GROUP BY bucket_start,
12933    replica_id
12934)
12935SELECT
12936  bucket_start,
12937  replica_id,
12938  max_memory.memory_percent,
12939  max_memory.occurred_at as max_memory_at,
12940  max_disk.disk_percent,
12941  max_disk.occurred_at as max_disk_at,
12942  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
12943  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
12944  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
12945  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
12946  max_heap.heap_percent,
12947  max_heap.occurred_at as max_heap_at,
12948  max_cpu.cpu_percent as max_cpu_percent,
12949  max_cpu.occurred_at as max_cpu_at,
12950  replica_offline_event_history.offline_events,
12951  bucket_start + INTERVAL '8 HOURS' as bucket_end,
12952  replica_name_history.new_name AS name,
12953  replica_history.cluster_id,
12954  replica_history.size
12955FROM max_memory
12956JOIN max_disk USING (bucket_start, replica_id)
12957JOIN max_cpu USING (bucket_start, replica_id)
12958JOIN max_memory_and_disk USING (bucket_start, replica_id)
12959JOIN max_heap USING (bucket_start, replica_id)
12960JOIN replica_history USING (replica_id)
12961CROSS JOIN LATERAL (
12962  SELECT new_name
12963  FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
12964  WHERE replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
12965    AND bucket_start + INTERVAL '8 HOURS' >= COALESCE(
12966      replica_name_history.occurred_at,
12967      '1970-01-01'::timestamp
12968    )
12969  ORDER BY replica_name_history.occurred_at DESC
12970  LIMIT '1'
12971) AS replica_name_history
12972LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
12973        access: vec![PUBLIC_SELECT],
12974    }
12975});
12976
12977/**
12978 * Traces the blue/green deployment lineage in the audit log to determine all cluster
12979 * IDs that are logically the same cluster.
12980 * cluster_id: The ID of a cluster.
12981 * current_deployment_cluster_id: The cluster ID of the last cluster in
12982 *   cluster_id's blue/green lineage.
12983 * cluster_name: The name of the cluster.
12984 * The approach taken is as follows. First, find all extant clusters and add them
12985 * to the result set. Per cluster, we do the following:
12986 * 1. Find the most recent create or rename event. This moment represents when the
12987 *    cluster took on its final logical identity.
12988 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
12989 *    appended) that was dropped within one minute of that moment. That cluster is
12990 *    almost certainly the logical predecessor of the current cluster. Add the cluster
12991 *    to the result set.
12992 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
12993 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
12994 * but one that's likely to be pretty good one. If a name is reused after more
12995 * than one minute, that's a good sign that it wasn't an automatic blue/green
12996 * process, but someone turning on a new use case that happens to have the same
12997 * name as a previous but logically distinct use case.
12998 */
12999pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13000    name: "mz_cluster_deployment_lineage",
13001    schema: MZ_INTERNAL_SCHEMA,
13002    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
13003    desc: RelationDesc::builder()
13004        .with_column("cluster_id", SqlScalarType::String.nullable(true))
13005        .with_column(
13006            "current_deployment_cluster_id",
13007            SqlScalarType::String.nullable(false),
13008        )
13009        .with_column("cluster_name", SqlScalarType::String.nullable(false))
13010        .with_key(vec![0, 1, 2])
13011        .finish(),
13012    column_comments: BTreeMap::from_iter([
13013        (
13014            "cluster_id",
13015            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
13016        ),
13017        (
13018            "current_deployment_cluster_id",
13019            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
13020        ),
13021        ("cluster_name", "The name of the cluster"),
13022    ]),
13023    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
13024  cluster_id text,
13025  cluster_name text,
13026  event_type text,
13027  occurred_at timestamptz
13028) AS (
13029  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
13030    coalesce(details->>'name', details->>'new_name') AS cluster_name,
13031    event_type,
13032    occurred_at
13033  FROM mz_audit_events
13034  WHERE (
13035      event_type IN ('create', 'drop')
13036      OR (
13037        event_type = 'alter'
13038        AND details ? 'new_name'
13039      )
13040    )
13041    AND object_type = 'cluster'
13042    AND mz_now() < occurred_at + INTERVAL '30 days'
13043),
13044mz_cluster_deployment_lineage (
13045  cluster_id text,
13046  current_deployment_cluster_id text,
13047  cluster_name text
13048) AS (
13049  SELECT c.id,
13050    c.id,
13051    c.name
13052  FROM mz_clusters c
13053  WHERE c.id LIKE 'u%'
13054  UNION
13055  SELECT *
13056  FROM dropped_clusters
13057),
13058-- Closest create or rename event based on the current clusters in the result set
13059most_recent_create_or_rename (
13060  cluster_id text,
13061  current_deployment_cluster_id text,
13062  cluster_name text,
13063  occurred_at timestamptz
13064) AS (
13065  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
13066    c.current_deployment_cluster_id,
13067    e.cluster_name,
13068    e.occurred_at
13069  FROM mz_cluster_deployment_lineage c
13070    JOIN cluster_events e ON c.cluster_id = e.cluster_id
13071    AND c.cluster_name = e.cluster_name
13072  WHERE e.event_type <> 'drop'
13073  ORDER BY e.cluster_id,
13074    e.occurred_at DESC
13075),
13076-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
13077dropped_clusters (
13078  cluster_id text,
13079  current_deployment_cluster_id text,
13080  cluster_name text
13081) AS (
13082  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
13083    cr.current_deployment_cluster_id,
13084    cr.cluster_name
13085  FROM most_recent_create_or_rename cr
13086    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
13087    AND cr.occurred_at + interval '1 minute'
13088    AND (
13089      e.cluster_name = cr.cluster_name
13090      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
13091    )
13092  WHERE e.event_type = 'drop'
13093  ORDER BY cr.cluster_id,
13094    abs(
13095      extract(
13096        epoch
13097        FROM cr.occurred_at - e.occurred_at
13098      )
13099    )
13100)
13101SELECT *
13102FROM mz_cluster_deployment_lineage"#,
13103    access: vec![PUBLIC_SELECT],
13104});
13105
13106pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
13107    name: "mz_show_databases_ind",
13108    schema: MZ_INTERNAL_SCHEMA,
13109    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
13110    sql: "IN CLUSTER mz_catalog_server
13111ON mz_internal.mz_show_databases (name)",
13112    is_retained_metrics_object: false,
13113};
13114
13115pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
13116    name: "mz_show_schemas_ind",
13117    schema: MZ_INTERNAL_SCHEMA,
13118    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
13119    sql: "IN CLUSTER mz_catalog_server
13120ON mz_internal.mz_show_schemas (database_id)",
13121    is_retained_metrics_object: false,
13122};
13123
13124pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
13125    name: "mz_show_connections_ind",
13126    schema: MZ_INTERNAL_SCHEMA,
13127    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
13128    sql: "IN CLUSTER mz_catalog_server
13129ON mz_internal.mz_show_connections (schema_id)",
13130    is_retained_metrics_object: false,
13131};
13132
13133pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
13134    name: "mz_show_tables_ind",
13135    schema: MZ_INTERNAL_SCHEMA,
13136    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
13137    sql: "IN CLUSTER mz_catalog_server
13138ON mz_internal.mz_show_tables (schema_id)",
13139    is_retained_metrics_object: false,
13140};
13141
13142pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13143    name: "mz_show_sources_ind",
13144    schema: MZ_INTERNAL_SCHEMA,
13145    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
13146    sql: "IN CLUSTER mz_catalog_server
13147ON mz_internal.mz_show_sources (schema_id)",
13148    is_retained_metrics_object: false,
13149};
13150
13151pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13152    name: "mz_show_views_ind",
13153    schema: MZ_INTERNAL_SCHEMA,
13154    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
13155    sql: "IN CLUSTER mz_catalog_server
13156ON mz_internal.mz_show_views (schema_id)",
13157    is_retained_metrics_object: false,
13158};
13159
13160pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13161    name: "mz_show_materialized_views_ind",
13162    schema: MZ_INTERNAL_SCHEMA,
13163    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
13164    sql: "IN CLUSTER mz_catalog_server
13165ON mz_internal.mz_show_materialized_views (schema_id)",
13166    is_retained_metrics_object: false,
13167};
13168
13169pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
13170    name: "mz_show_sinks_ind",
13171    schema: MZ_INTERNAL_SCHEMA,
13172    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
13173    sql: "IN CLUSTER mz_catalog_server
13174ON mz_internal.mz_show_sinks (schema_id)",
13175    is_retained_metrics_object: false,
13176};
13177
13178pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
13179    name: "mz_show_types_ind",
13180    schema: MZ_INTERNAL_SCHEMA,
13181    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
13182    sql: "IN CLUSTER mz_catalog_server
13183ON mz_internal.mz_show_types (schema_id)",
13184    is_retained_metrics_object: false,
13185};
13186
13187pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
13188    name: "mz_show_roles_ind",
13189    schema: MZ_INTERNAL_SCHEMA,
13190    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
13191    sql: "IN CLUSTER mz_catalog_server
13192ON mz_internal.mz_show_roles (name)",
13193    is_retained_metrics_object: false,
13194};
13195
13196pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
13197    name: "mz_show_all_objects_ind",
13198    schema: MZ_INTERNAL_SCHEMA,
13199    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
13200    sql: "IN CLUSTER mz_catalog_server
13201ON mz_internal.mz_show_all_objects (schema_id)",
13202    is_retained_metrics_object: false,
13203};
13204
13205pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
13206    name: "mz_show_indexes_ind",
13207    schema: MZ_INTERNAL_SCHEMA,
13208    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
13209    sql: "IN CLUSTER mz_catalog_server
13210ON mz_internal.mz_show_indexes (schema_id)",
13211    is_retained_metrics_object: false,
13212};
13213
13214pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
13215    name: "mz_show_columns_ind",
13216    schema: MZ_INTERNAL_SCHEMA,
13217    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
13218    sql: "IN CLUSTER mz_catalog_server
13219ON mz_internal.mz_show_columns (id)",
13220    is_retained_metrics_object: false,
13221};
13222
13223pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
13224    name: "mz_show_clusters_ind",
13225    schema: MZ_INTERNAL_SCHEMA,
13226    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
13227    sql: "IN CLUSTER mz_catalog_server
13228ON mz_internal.mz_show_clusters (name)",
13229    is_retained_metrics_object: false,
13230};
13231
13232pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13233    name: "mz_show_cluster_replicas_ind",
13234    schema: MZ_INTERNAL_SCHEMA,
13235    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
13236    sql: "IN CLUSTER mz_catalog_server
13237ON mz_internal.mz_show_cluster_replicas (cluster)",
13238    is_retained_metrics_object: false,
13239};
13240
13241pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
13242    name: "mz_show_secrets_ind",
13243    schema: MZ_INTERNAL_SCHEMA,
13244    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
13245    sql: "IN CLUSTER mz_catalog_server
13246ON mz_internal.mz_show_secrets (schema_id)",
13247    is_retained_metrics_object: false,
13248};
13249
13250pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
13251    name: "mz_databases_ind",
13252    schema: MZ_CATALOG_SCHEMA,
13253    oid: oid::INDEX_MZ_DATABASES_IND_OID,
13254    sql: "IN CLUSTER mz_catalog_server
13255ON mz_catalog.mz_databases (name)",
13256    is_retained_metrics_object: false,
13257};
13258
13259pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
13260    name: "mz_schemas_ind",
13261    schema: MZ_CATALOG_SCHEMA,
13262    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
13263    sql: "IN CLUSTER mz_catalog_server
13264ON mz_catalog.mz_schemas (database_id)",
13265    is_retained_metrics_object: false,
13266};
13267
13268pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
13269    name: "mz_connections_ind",
13270    schema: MZ_CATALOG_SCHEMA,
13271    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
13272    sql: "IN CLUSTER mz_catalog_server
13273ON mz_catalog.mz_connections (schema_id)",
13274    is_retained_metrics_object: false,
13275};
13276
13277pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
13278    name: "mz_tables_ind",
13279    schema: MZ_CATALOG_SCHEMA,
13280    oid: oid::INDEX_MZ_TABLES_IND_OID,
13281    sql: "IN CLUSTER mz_catalog_server
13282ON mz_catalog.mz_tables (schema_id)",
13283    is_retained_metrics_object: false,
13284};
13285
13286pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
13287    name: "mz_types_ind",
13288    schema: MZ_CATALOG_SCHEMA,
13289    oid: oid::INDEX_MZ_TYPES_IND_OID,
13290    sql: "IN CLUSTER mz_catalog_server
13291ON mz_catalog.mz_types (schema_id)",
13292    is_retained_metrics_object: false,
13293};
13294
13295pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
13296    name: "mz_objects_ind",
13297    schema: MZ_CATALOG_SCHEMA,
13298    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
13299    sql: "IN CLUSTER mz_catalog_server
13300ON mz_catalog.mz_objects (schema_id)",
13301    is_retained_metrics_object: false,
13302};
13303
13304pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
13305    name: "mz_columns_ind",
13306    schema: MZ_CATALOG_SCHEMA,
13307    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
13308    sql: "IN CLUSTER mz_catalog_server
13309ON mz_catalog.mz_columns (name)",
13310    is_retained_metrics_object: false,
13311};
13312
13313pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
13314    name: "mz_secrets_ind",
13315    schema: MZ_CATALOG_SCHEMA,
13316    oid: oid::INDEX_MZ_SECRETS_IND_OID,
13317    sql: "IN CLUSTER mz_catalog_server
13318ON mz_catalog.mz_secrets (name)",
13319    is_retained_metrics_object: false,
13320};
13321
13322pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13323    name: "mz_views_ind",
13324    schema: MZ_CATALOG_SCHEMA,
13325    oid: oid::INDEX_MZ_VIEWS_IND_OID,
13326    sql: "IN CLUSTER mz_catalog_server
13327ON mz_catalog.mz_views (schema_id)",
13328    is_retained_metrics_object: false,
13329};
13330
13331pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
13332    name: "mz_console_cluster_utilization_overview_ind",
13333    schema: MZ_INTERNAL_SCHEMA,
13334    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
13335    sql: "IN CLUSTER mz_catalog_server
13336ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
13337    is_retained_metrics_object: false,
13338};
13339
13340pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
13341    name: "mz_cluster_deployment_lineage_ind",
13342    schema: MZ_INTERNAL_SCHEMA,
13343    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
13344    sql: "IN CLUSTER mz_catalog_server
13345ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
13346    is_retained_metrics_object: false,
13347};
13348
13349pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
13350    name: "mz_clusters_ind",
13351    schema: MZ_CATALOG_SCHEMA,
13352    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
13353    sql: "IN CLUSTER mz_catalog_server
13354ON mz_catalog.mz_clusters (id)",
13355    is_retained_metrics_object: false,
13356};
13357
13358pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
13359    name: "mz_indexes_ind",
13360    schema: MZ_CATALOG_SCHEMA,
13361    oid: oid::INDEX_MZ_INDEXES_IND_OID,
13362    sql: "IN CLUSTER mz_catalog_server
13363ON mz_catalog.mz_indexes (id)",
13364    is_retained_metrics_object: false,
13365};
13366
13367pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
13368    name: "mz_roles_ind",
13369    schema: MZ_CATALOG_SCHEMA,
13370    oid: oid::INDEX_MZ_ROLES_IND_OID,
13371    sql: "IN CLUSTER mz_catalog_server
13372ON mz_catalog.mz_roles (id)",
13373    is_retained_metrics_object: false,
13374};
13375
13376pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13377    name: "mz_sources_ind",
13378    schema: MZ_CATALOG_SCHEMA,
13379    oid: oid::INDEX_MZ_SOURCES_IND_OID,
13380    sql: "IN CLUSTER mz_catalog_server
13381ON mz_catalog.mz_sources (id)",
13382    is_retained_metrics_object: true,
13383};
13384
13385pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
13386    name: "mz_sinks_ind",
13387    schema: MZ_CATALOG_SCHEMA,
13388    oid: oid::INDEX_MZ_SINKS_IND_OID,
13389    sql: "IN CLUSTER mz_catalog_server
13390ON mz_catalog.mz_sinks (id)",
13391    is_retained_metrics_object: true,
13392};
13393
13394pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13395    name: "mz_materialized_views_ind",
13396    schema: MZ_CATALOG_SCHEMA,
13397    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
13398    sql: "IN CLUSTER mz_catalog_server
13399ON mz_catalog.mz_materialized_views (id)",
13400    is_retained_metrics_object: false,
13401};
13402
13403pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13404    name: "mz_source_statuses_ind",
13405    schema: MZ_INTERNAL_SCHEMA,
13406    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
13407    sql: "IN CLUSTER mz_catalog_server
13408ON mz_internal.mz_source_statuses (id)",
13409    is_retained_metrics_object: false,
13410};
13411
13412pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13413    name: "mz_sink_statuses_ind",
13414    schema: MZ_INTERNAL_SCHEMA,
13415    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
13416    sql: "IN CLUSTER mz_catalog_server
13417ON mz_internal.mz_sink_statuses (id)",
13418    is_retained_metrics_object: false,
13419};
13420
13421pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13422    name: "mz_source_status_history_ind",
13423    schema: MZ_INTERNAL_SCHEMA,
13424    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
13425    sql: "IN CLUSTER mz_catalog_server
13426ON mz_internal.mz_source_status_history (source_id)",
13427    is_retained_metrics_object: false,
13428};
13429
13430pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13431    name: "mz_sink_status_history_ind",
13432    schema: MZ_INTERNAL_SCHEMA,
13433    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
13434    sql: "IN CLUSTER mz_catalog_server
13435ON mz_internal.mz_sink_status_history (sink_id)",
13436    is_retained_metrics_object: false,
13437};
13438
13439// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
13440// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
13441// save index space, and we don't expect the sum to be > 2^63
13442// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
13443//
13444//
13445// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
13446// underlying relation.
13447//
13448// We append WITH_HISTORY because we want to build a separate view + index that doesn't
13449// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
13450// to hold all records/updates, which causes CPU and latency of querying it to spike.
13451pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
13452    LazyLock::new(|| BuiltinView {
13453        name: "mz_source_statistics_with_history",
13454        schema: MZ_INTERNAL_SCHEMA,
13455        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
13456        desc: RelationDesc::builder()
13457            .with_column("id", SqlScalarType::String.nullable(false))
13458            .with_column("replica_id", SqlScalarType::String.nullable(true))
13459            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13460            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13461            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13462            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13463            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13464            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13465            .with_column(
13466                "rehydration_latency",
13467                SqlScalarType::Interval.nullable(true),
13468            )
13469            .with_column(
13470                "snapshot_records_known",
13471                SqlScalarType::UInt64.nullable(true),
13472            )
13473            .with_column(
13474                "snapshot_records_staged",
13475                SqlScalarType::UInt64.nullable(true),
13476            )
13477            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13478            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13479            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13480            .with_key(vec![0, 1])
13481            .finish(),
13482        column_comments: BTreeMap::new(),
13483        sql: "
13484WITH
13485    -- For each subsource, statistics are reported as its parent source
13486    subsource_to_parent AS
13487    (
13488        SELECT subsource.id AS id, parent.id AS report_id
13489        FROM mz_catalog.mz_sources AS subsource
13490            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
13491            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
13492        WHERE subsource.type = 'subsource'
13493    ),
13494    -- For each table from source, statistics are reported as its parent source
13495    table_to_parent AS
13496    (
13497        SELECT id, source_id AS report_id
13498        FROM mz_catalog.mz_tables
13499        WHERE source_id IS NOT NULL
13500    ),
13501    -- For each source and subsource, statistics are reported as itself
13502    source_refl AS
13503    (
13504        SELECT id, id AS report_id
13505        FROM mz_catalog.mz_sources
13506        WHERE type NOT IN ('progress', 'log')
13507    ),
13508    -- For each table from source, statistics are reported as itself
13509    table_refl AS
13510    (
13511        SELECT id, id AS report_id
13512        FROM mz_catalog.mz_tables
13513        WHERE source_id IS NOT NULL
13514    ),
13515    report_paths AS
13516    (
13517        SELECT id, report_id FROM subsource_to_parent
13518        UNION ALL SELECT id, report_id FROM table_to_parent
13519        UNION ALL SELECT id, report_id FROM source_refl
13520        UNION ALL SELECT id, report_id FROM table_refl
13521    )
13522SELECT
13523    report_paths.report_id AS id,
13524    replica_id,
13525    -- Counters
13526    SUM(messages_received)::uint8 AS messages_received,
13527    SUM(bytes_received)::uint8 AS bytes_received,
13528    SUM(updates_staged)::uint8 AS updates_staged,
13529    SUM(updates_committed)::uint8 AS updates_committed,
13530    -- Resetting Gauges
13531    SUM(records_indexed)::uint8 AS records_indexed,
13532    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13533    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13534    CASE
13535        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13536        ELSE MAX(rehydration_latency)::interval
13537    END AS rehydration_latency,
13538    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13539    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13540    bool_and(snapshot_committed) as snapshot_committed,
13541    -- Gauges
13542    MAX(offset_known)::uint8 AS offset_known,
13543    MIN(offset_committed)::uint8 AS offset_committed
13544FROM mz_internal.mz_source_statistics_raw
13545    JOIN report_paths USING (id)
13546GROUP BY report_paths.report_id, replica_id",
13547        access: vec![PUBLIC_SELECT],
13548    });
13549
13550pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13551    name: "mz_source_statistics_with_history_ind",
13552    schema: MZ_INTERNAL_SCHEMA,
13553    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13554    sql: "IN CLUSTER mz_catalog_server
13555ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
13556    is_retained_metrics_object: true,
13557};
13558
13559// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13560// Used to query MZ_SOURCE_STATISTICS at the current time.
13561pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13562    BuiltinView {
13563        name: "mz_source_statistics",
13564        schema: MZ_INTERNAL_SCHEMA,
13565        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13566        // We need to add a redundant where clause for a new dataflow to be created.
13567        desc: RelationDesc::builder()
13568            .with_column("id", SqlScalarType::String.nullable(false))
13569            .with_column("replica_id", SqlScalarType::String.nullable(true))
13570            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13571            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13572            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13573            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13574            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13575            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13576            .with_column(
13577                "rehydration_latency",
13578                SqlScalarType::Interval.nullable(true),
13579            )
13580            .with_column(
13581                "snapshot_records_known",
13582                SqlScalarType::UInt64.nullable(true),
13583            )
13584            .with_column(
13585                "snapshot_records_staged",
13586                SqlScalarType::UInt64.nullable(true),
13587            )
13588            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13589            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13590            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13591            .with_key(vec![0, 1])
13592            .finish(),
13593        column_comments: BTreeMap::from_iter([
13594            (
13595                "id",
13596                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13597            ),
13598            (
13599                "replica_id",
13600                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13601            ),
13602            (
13603                "messages_received",
13604                "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.",
13605            ),
13606            (
13607                "bytes_received",
13608                "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.",
13609            ),
13610            (
13611                "updates_staged",
13612                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13613            ),
13614            (
13615                "updates_committed",
13616                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13617            ),
13618            (
13619                "records_indexed",
13620                "The number of individual records indexed in the source envelope state.",
13621            ),
13622            (
13623                "bytes_indexed",
13624                "The number of bytes stored in the source's internal index, if any.",
13625            ),
13626            (
13627                "rehydration_latency",
13628                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13629            ),
13630            (
13631                "snapshot_records_known",
13632                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13633            ),
13634            (
13635                "snapshot_records_staged",
13636                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13637            ),
13638            (
13639                "snapshot_committed",
13640                "Whether the source has committed the initial snapshot for a source.",
13641            ),
13642            (
13643                "offset_known",
13644                "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.",
13645            ),
13646            (
13647                "offset_committed",
13648                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13649            ),
13650        ]),
13651        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13652        access: vec![PUBLIC_SELECT],
13653    }
13654});
13655
13656pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13657    name: "mz_source_statistics_ind",
13658    schema: MZ_INTERNAL_SCHEMA,
13659    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13660    sql: "IN CLUSTER mz_catalog_server
13661ON mz_internal.mz_source_statistics (id, replica_id)",
13662    is_retained_metrics_object: false,
13663};
13664
13665pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13666    name: "mz_sink_statistics",
13667    schema: MZ_INTERNAL_SCHEMA,
13668    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13669    desc: RelationDesc::builder()
13670        .with_column("id", SqlScalarType::String.nullable(false))
13671        .with_column("replica_id", SqlScalarType::String.nullable(true))
13672        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
13673        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
13674        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
13675        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
13676        .with_key(vec![0, 1])
13677        .finish(),
13678    column_comments: BTreeMap::from_iter([
13679        (
13680            "id",
13681            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
13682        ),
13683        (
13684            "replica_id",
13685            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13686        ),
13687        (
13688            "messages_staged",
13689            "The number of messages staged but possibly not committed to the sink.",
13690        ),
13691        (
13692            "messages_committed",
13693            "The number of messages committed to the sink.",
13694        ),
13695        (
13696            "bytes_staged",
13697            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13698        ),
13699        (
13700            "bytes_committed",
13701            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13702        ),
13703    ]),
13704    sql: "
13705SELECT
13706    id,
13707    replica_id,
13708    SUM(messages_staged)::uint8 AS messages_staged,
13709    SUM(messages_committed)::uint8 AS messages_committed,
13710    SUM(bytes_staged)::uint8 AS bytes_staged,
13711    SUM(bytes_committed)::uint8 AS bytes_committed
13712FROM mz_internal.mz_sink_statistics_raw
13713GROUP BY id, replica_id",
13714    access: vec![PUBLIC_SELECT],
13715});
13716
13717pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13718    name: "mz_sink_statistics_ind",
13719    schema: MZ_INTERNAL_SCHEMA,
13720    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13721    sql: "IN CLUSTER mz_catalog_server
13722ON mz_internal.mz_sink_statistics (id, replica_id)",
13723    is_retained_metrics_object: true,
13724};
13725
13726pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13727    name: "mz_cluster_replicas_ind",
13728    schema: MZ_CATALOG_SCHEMA,
13729    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13730    sql: "IN CLUSTER mz_catalog_server
13731ON mz_catalog.mz_cluster_replicas (id)",
13732    is_retained_metrics_object: true,
13733};
13734
13735pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13736    name: "mz_cluster_replica_sizes_ind",
13737    schema: MZ_CATALOG_SCHEMA,
13738    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13739    sql: "IN CLUSTER mz_catalog_server
13740ON mz_catalog.mz_cluster_replica_sizes (size)",
13741    is_retained_metrics_object: true,
13742};
13743
13744pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13745    name: "mz_cluster_replica_statuses_ind",
13746    schema: MZ_INTERNAL_SCHEMA,
13747    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13748    sql: "IN CLUSTER mz_catalog_server
13749ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13750    is_retained_metrics_object: false,
13751};
13752
13753pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13754    name: "mz_cluster_replica_status_history_ind",
13755    schema: MZ_INTERNAL_SCHEMA,
13756    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13757    sql: "IN CLUSTER mz_catalog_server
13758ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13759    is_retained_metrics_object: false,
13760};
13761
13762pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13763    name: "mz_cluster_replica_metrics_ind",
13764    schema: MZ_INTERNAL_SCHEMA,
13765    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13766    sql: "IN CLUSTER mz_catalog_server
13767ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13768    is_retained_metrics_object: false,
13769};
13770
13771pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13772    name: "mz_cluster_replica_metrics_history_ind",
13773    schema: MZ_INTERNAL_SCHEMA,
13774    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13775    sql: "IN CLUSTER mz_catalog_server
13776ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13777    is_retained_metrics_object: false,
13778};
13779
13780pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13781    name: "mz_cluster_replica_history_ind",
13782    schema: MZ_INTERNAL_SCHEMA,
13783    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13784    sql: "IN CLUSTER mz_catalog_server
13785ON mz_internal.mz_cluster_replica_history (dropped_at)",
13786    is_retained_metrics_object: true,
13787};
13788
13789pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13790    name: "mz_cluster_replica_name_history_ind",
13791    schema: MZ_INTERNAL_SCHEMA,
13792    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13793    sql: "IN CLUSTER mz_catalog_server
13794ON mz_internal.mz_cluster_replica_name_history (id)",
13795    is_retained_metrics_object: false,
13796};
13797
13798pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13799    name: "mz_object_lifetimes_ind",
13800    schema: MZ_INTERNAL_SCHEMA,
13801    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13802    sql: "IN CLUSTER mz_catalog_server
13803ON mz_internal.mz_object_lifetimes (id)",
13804    is_retained_metrics_object: false,
13805};
13806
13807pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13808    name: "mz_object_history_ind",
13809    schema: MZ_INTERNAL_SCHEMA,
13810    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13811    sql: "IN CLUSTER mz_catalog_server
13812ON mz_internal.mz_object_history (id)",
13813    is_retained_metrics_object: false,
13814};
13815
13816pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13817    name: "mz_object_dependencies_ind",
13818    schema: MZ_INTERNAL_SCHEMA,
13819    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
13820    sql: "IN CLUSTER mz_catalog_server
13821ON mz_internal.mz_object_dependencies (object_id)",
13822    is_retained_metrics_object: true,
13823};
13824
13825pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13826    name: "mz_compute_dependencies_ind",
13827    schema: MZ_INTERNAL_SCHEMA,
13828    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
13829    sql: "IN CLUSTER mz_catalog_server
13830ON mz_internal.mz_compute_dependencies (dependency_id)",
13831    is_retained_metrics_object: false,
13832};
13833
13834pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13835    name: "mz_object_transitive_dependencies_ind",
13836    schema: MZ_INTERNAL_SCHEMA,
13837    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
13838    sql: "IN CLUSTER mz_catalog_server
13839ON mz_internal.mz_object_transitive_dependencies (object_id)",
13840    is_retained_metrics_object: false,
13841};
13842
13843pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
13844    name: "mz_frontiers_ind",
13845    schema: MZ_INTERNAL_SCHEMA,
13846    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
13847    sql: "IN CLUSTER mz_catalog_server
13848ON mz_internal.mz_frontiers (object_id)",
13849    is_retained_metrics_object: false,
13850};
13851
13852pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13853    name: "mz_wallclock_global_lag_recent_history_ind",
13854    schema: MZ_INTERNAL_SCHEMA,
13855    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
13856    sql: "IN CLUSTER mz_catalog_server
13857ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
13858    is_retained_metrics_object: false,
13859};
13860
13861pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
13862    name: "mz_recent_activity_log_thinned_ind",
13863    schema: MZ_INTERNAL_SCHEMA,
13864    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
13865    sql: "IN CLUSTER mz_catalog_server
13866-- sql_hash because we plan to join
13867-- this against mz_internal.mz_sql_text
13868ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
13869    is_retained_metrics_object: false,
13870};
13871
13872pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13873    name: "mz_kafka_sources_ind",
13874    schema: MZ_CATALOG_SCHEMA,
13875    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
13876    sql: "IN CLUSTER mz_catalog_server
13877ON mz_catalog.mz_kafka_sources (id)",
13878    is_retained_metrics_object: true,
13879};
13880
13881pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13882    name: "mz_webhook_sources_ind",
13883    schema: MZ_INTERNAL_SCHEMA,
13884    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
13885    sql: "IN CLUSTER mz_catalog_server
13886ON mz_internal.mz_webhook_sources (id)",
13887    is_retained_metrics_object: true,
13888};
13889
13890pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
13891    name: "mz_comments_ind",
13892    schema: MZ_INTERNAL_SCHEMA,
13893    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
13894    sql: "IN CLUSTER mz_catalog_server
13895ON mz_internal.mz_comments (id)",
13896    is_retained_metrics_object: true,
13897};
13898
13899pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
13900    name: "mz_analytics",
13901    schema: MZ_INTERNAL_SCHEMA,
13902    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
13903    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
13904    access: &[MzAclItem {
13905        grantee: MZ_SYSTEM_ROLE_ID,
13906        grantor: MZ_ANALYTICS_ROLE_ID,
13907        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
13908    }],
13909    owner_id: &MZ_ANALYTICS_ROLE_ID,
13910    runtime_alterable: true,
13911};
13912
13913pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
13914    id: MZ_SYSTEM_ROLE_ID,
13915    name: SYSTEM_USER_NAME,
13916    oid: oid::ROLE_MZ_SYSTEM_OID,
13917    attributes: RoleAttributesRaw::new().with_all(),
13918};
13919
13920pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
13921    id: MZ_SUPPORT_ROLE_ID,
13922    name: SUPPORT_USER_NAME,
13923    oid: oid::ROLE_MZ_SUPPORT_OID,
13924    attributes: RoleAttributesRaw::new(),
13925};
13926
13927pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
13928    id: MZ_ANALYTICS_ROLE_ID,
13929    name: ANALYTICS_USER_NAME,
13930    oid: oid::ROLE_MZ_ANALYTICS_OID,
13931    attributes: RoleAttributesRaw::new(),
13932};
13933
13934/// This role can `SELECT` from various query history objects,
13935/// e.g. `mz_prepared_statement_history`.
13936pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
13937    id: MZ_MONITOR_ROLE_ID,
13938    name: "mz_monitor",
13939    oid: oid::ROLE_MZ_MONITOR_OID,
13940    attributes: RoleAttributesRaw::new(),
13941};
13942
13943/// This role is like [`MZ_MONITOR_ROLE`], but can only query
13944/// the redacted versions of the objects.
13945pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
13946    id: MZ_MONITOR_REDACTED_ROLE_ID,
13947    name: "mz_monitor_redacted",
13948    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
13949    attributes: RoleAttributesRaw::new(),
13950};
13951
13952/// Sentinel role used as the grantor for JWT group-sync-managed
13953/// role memberships. Never logged into directly.
13954pub const MZ_JWT_SYNC_ROLE: BuiltinRole = BuiltinRole {
13955    id: MZ_JWT_SYNC_ROLE_ID,
13956    name: JWT_SYNC_ROLE_NAME,
13957    oid: oid::ROLE_MZ_JWT_SYNC_OID,
13958    attributes: RoleAttributesRaw::new(),
13959};
13960
13961pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
13962    name: SYSTEM_USER_NAME,
13963    owner_id: &MZ_SYSTEM_ROLE_ID,
13964    privileges: &[
13965        MzAclItem {
13966            grantee: MZ_SUPPORT_ROLE_ID,
13967            grantor: MZ_SYSTEM_ROLE_ID,
13968            acl_mode: AclMode::USAGE,
13969        },
13970        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13971    ],
13972};
13973
13974pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13975    name: BUILTIN_CLUSTER_REPLICA_NAME,
13976    cluster_name: MZ_SYSTEM_CLUSTER.name,
13977};
13978
13979pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
13980    name: "mz_catalog_server",
13981    owner_id: &MZ_SYSTEM_ROLE_ID,
13982    privileges: &[
13983        MzAclItem {
13984            grantee: RoleId::Public,
13985            grantor: MZ_SYSTEM_ROLE_ID,
13986            acl_mode: AclMode::USAGE,
13987        },
13988        MzAclItem {
13989            grantee: MZ_SUPPORT_ROLE_ID,
13990            grantor: MZ_SYSTEM_ROLE_ID,
13991            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
13992        },
13993        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13994    ],
13995};
13996
13997pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13998    name: BUILTIN_CLUSTER_REPLICA_NAME,
13999    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
14000};
14001
14002pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
14003    name: "mz_probe",
14004    owner_id: &MZ_SYSTEM_ROLE_ID,
14005    privileges: &[
14006        MzAclItem {
14007            grantee: MZ_SUPPORT_ROLE_ID,
14008            grantor: MZ_SYSTEM_ROLE_ID,
14009            acl_mode: AclMode::USAGE,
14010        },
14011        MzAclItem {
14012            grantee: MZ_MONITOR_ROLE_ID,
14013            grantor: MZ_SYSTEM_ROLE_ID,
14014            acl_mode: AclMode::USAGE,
14015        },
14016        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
14017    ],
14018};
14019pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
14020    name: BUILTIN_CLUSTER_REPLICA_NAME,
14021    cluster_name: MZ_PROBE_CLUSTER.name,
14022};
14023
14024pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
14025    name: "mz_support",
14026    owner_id: &MZ_SUPPORT_ROLE_ID,
14027    privileges: &[
14028        MzAclItem {
14029            grantee: MZ_SYSTEM_ROLE_ID,
14030            grantor: MZ_SUPPORT_ROLE_ID,
14031            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
14032        },
14033        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
14034    ],
14035};
14036
14037pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
14038    name: "mz_analytics",
14039    owner_id: &MZ_ANALYTICS_ROLE_ID,
14040    privileges: &[
14041        MzAclItem {
14042            grantee: MZ_SYSTEM_ROLE_ID,
14043            grantor: MZ_ANALYTICS_ROLE_ID,
14044            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
14045        },
14046        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
14047    ],
14048};
14049
14050/// List of all builtin objects sorted topologically by dependency.
14051pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
14052    let mut builtin_types = vec![
14053        Builtin::Type(&TYPE_ANY),
14054        Builtin::Type(&TYPE_ANYARRAY),
14055        Builtin::Type(&TYPE_ANYELEMENT),
14056        Builtin::Type(&TYPE_ANYNONARRAY),
14057        Builtin::Type(&TYPE_ANYRANGE),
14058        Builtin::Type(&TYPE_BOOL),
14059        Builtin::Type(&TYPE_BOOL_ARRAY),
14060        Builtin::Type(&TYPE_BYTEA),
14061        Builtin::Type(&TYPE_BYTEA_ARRAY),
14062        Builtin::Type(&TYPE_BPCHAR),
14063        Builtin::Type(&TYPE_BPCHAR_ARRAY),
14064        Builtin::Type(&TYPE_CHAR),
14065        Builtin::Type(&TYPE_CHAR_ARRAY),
14066        Builtin::Type(&TYPE_DATE),
14067        Builtin::Type(&TYPE_DATE_ARRAY),
14068        Builtin::Type(&TYPE_FLOAT4),
14069        Builtin::Type(&TYPE_FLOAT4_ARRAY),
14070        Builtin::Type(&TYPE_FLOAT8),
14071        Builtin::Type(&TYPE_FLOAT8_ARRAY),
14072        Builtin::Type(&TYPE_INT4),
14073        Builtin::Type(&TYPE_INT4_ARRAY),
14074        Builtin::Type(&TYPE_INT8),
14075        Builtin::Type(&TYPE_INT8_ARRAY),
14076        Builtin::Type(&TYPE_INTERVAL),
14077        Builtin::Type(&TYPE_INTERVAL_ARRAY),
14078        Builtin::Type(&TYPE_JSONB),
14079        Builtin::Type(&TYPE_JSONB_ARRAY),
14080        Builtin::Type(&TYPE_LIST),
14081        Builtin::Type(&TYPE_MAP),
14082        Builtin::Type(&TYPE_NAME),
14083        Builtin::Type(&TYPE_NAME_ARRAY),
14084        Builtin::Type(&TYPE_NUMERIC),
14085        Builtin::Type(&TYPE_NUMERIC_ARRAY),
14086        Builtin::Type(&TYPE_OID),
14087        Builtin::Type(&TYPE_OID_ARRAY),
14088        Builtin::Type(&TYPE_RECORD),
14089        Builtin::Type(&TYPE_RECORD_ARRAY),
14090        Builtin::Type(&TYPE_REGCLASS),
14091        Builtin::Type(&TYPE_REGCLASS_ARRAY),
14092        Builtin::Type(&TYPE_REGPROC),
14093        Builtin::Type(&TYPE_REGPROC_ARRAY),
14094        Builtin::Type(&TYPE_REGTYPE),
14095        Builtin::Type(&TYPE_REGTYPE_ARRAY),
14096        Builtin::Type(&TYPE_INT2),
14097        Builtin::Type(&TYPE_INT2_ARRAY),
14098        Builtin::Type(&TYPE_TEXT),
14099        Builtin::Type(&TYPE_TEXT_ARRAY),
14100        Builtin::Type(&TYPE_TIME),
14101        Builtin::Type(&TYPE_TIME_ARRAY),
14102        Builtin::Type(&TYPE_TIMESTAMP),
14103        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
14104        Builtin::Type(&TYPE_TIMESTAMPTZ),
14105        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
14106        Builtin::Type(&TYPE_UUID),
14107        Builtin::Type(&TYPE_UUID_ARRAY),
14108        Builtin::Type(&TYPE_VARCHAR),
14109        Builtin::Type(&TYPE_VARCHAR_ARRAY),
14110        Builtin::Type(&TYPE_INT2_VECTOR),
14111        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
14112        Builtin::Type(&TYPE_ANYCOMPATIBLE),
14113        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
14114        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
14115        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
14116        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
14117        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
14118        Builtin::Type(&TYPE_UINT2),
14119        Builtin::Type(&TYPE_UINT2_ARRAY),
14120        Builtin::Type(&TYPE_UINT4),
14121        Builtin::Type(&TYPE_UINT4_ARRAY),
14122        Builtin::Type(&TYPE_UINT8),
14123        Builtin::Type(&TYPE_UINT8_ARRAY),
14124        Builtin::Type(&TYPE_MZ_TIMESTAMP),
14125        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
14126        Builtin::Type(&TYPE_INT4_RANGE),
14127        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
14128        Builtin::Type(&TYPE_INT8_RANGE),
14129        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
14130        Builtin::Type(&TYPE_DATE_RANGE),
14131        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
14132        Builtin::Type(&TYPE_NUM_RANGE),
14133        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
14134        Builtin::Type(&TYPE_TS_RANGE),
14135        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
14136        Builtin::Type(&TYPE_TSTZ_RANGE),
14137        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
14138        Builtin::Type(&TYPE_MZ_ACL_ITEM),
14139        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
14140        Builtin::Type(&TYPE_ACL_ITEM),
14141        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
14142        Builtin::Type(&TYPE_INTERNAL),
14143    ];
14144
14145    let mut builtin_funcs = Vec::new();
14146    for (schema, funcs) in &[
14147        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
14148        (
14149            INFORMATION_SCHEMA,
14150            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
14151        ),
14152        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
14153        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
14154        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
14155    ] {
14156        for (name, func) in funcs.iter() {
14157            builtin_funcs.push(Builtin::Func(BuiltinFunc {
14158                name,
14159                schema,
14160                inner: func,
14161            }));
14162        }
14163    }
14164
14165    let mut builtin_items = vec![
14166        Builtin::Source(&MZ_CATALOG_RAW),
14167        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
14168        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
14169        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
14170        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
14171        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
14172        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
14173        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
14174        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
14175        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
14176        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
14177        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
14178        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
14179        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
14180        Builtin::Log(&MZ_CLUSTER_PROMETHEUS_METRICS),
14181        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
14182        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
14183        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
14184        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
14185        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
14186        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
14187        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
14188        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
14189        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
14190        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
14191        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
14192        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
14193        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
14194        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
14195        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
14196        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
14197        Builtin::Log(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
14198        Builtin::Table(&MZ_KAFKA_SINKS),
14199        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
14200        Builtin::Table(&MZ_KAFKA_SOURCES),
14201        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
14202        Builtin::Table(&MZ_ICEBERG_SINKS),
14203        Builtin::MaterializedView(&MZ_DATABASES),
14204        Builtin::MaterializedView(&MZ_SCHEMAS),
14205        Builtin::Table(&MZ_COLUMNS),
14206        Builtin::Table(&MZ_INDEXES),
14207        Builtin::Table(&MZ_INDEX_COLUMNS),
14208        Builtin::Table(&MZ_TABLES),
14209        Builtin::Table(&MZ_SOURCES),
14210        Builtin::Table(&MZ_SOURCE_REFERENCES),
14211        Builtin::Table(&MZ_POSTGRES_SOURCES),
14212        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
14213        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
14214        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
14215        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
14216        Builtin::Table(&MZ_SINKS),
14217        Builtin::Table(&MZ_VIEWS),
14218        Builtin::Table(&MZ_TYPES),
14219        Builtin::Table(&MZ_TYPE_PG_METADATA),
14220        Builtin::Table(&MZ_ARRAY_TYPES),
14221        Builtin::Table(&MZ_BASE_TYPES),
14222        Builtin::Table(&MZ_LIST_TYPES),
14223        Builtin::Table(&MZ_MAP_TYPES),
14224        Builtin::Table(&MZ_ROLES),
14225        Builtin::Table(&MZ_ROLE_AUTH),
14226        Builtin::MaterializedView(&MZ_ROLE_MEMBERS),
14227        Builtin::Table(&MZ_ROLE_PARAMETERS),
14228        Builtin::Table(&MZ_PSEUDO_TYPES),
14229        Builtin::Table(&MZ_FUNCTIONS),
14230        Builtin::Table(&MZ_OPERATORS),
14231        Builtin::Table(&MZ_AGGREGATES),
14232        Builtin::Table(&MZ_CLUSTERS),
14233        Builtin::MaterializedView(&MZ_CLUSTER_WORKLOAD_CLASSES),
14234        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
14235        Builtin::MaterializedView(&MZ_SECRETS),
14236        Builtin::MaterializedView(&MZ_CONNECTIONS),
14237        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
14238        Builtin::Table(&MZ_CLUSTER_REPLICAS),
14239        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
14240        Builtin::View(&MZ_CLUSTER_REPLICA_METRICS),
14241        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
14242        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
14243        Builtin::View(&MZ_CLUSTER_REPLICA_STATUSES),
14244        Builtin::MaterializedView(&MZ_INTERNAL_CLUSTER_REPLICAS),
14245        Builtin::MaterializedView(&MZ_PENDING_CLUSTER_REPLICAS),
14246        Builtin::Table(&MZ_AUDIT_EVENTS),
14247        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
14248        Builtin::Table(&MZ_EGRESS_IPS),
14249        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
14250        Builtin::Table(&MZ_AWS_CONNECTIONS),
14251        Builtin::Table(&MZ_SUBSCRIPTIONS),
14252        Builtin::Table(&MZ_SESSIONS),
14253        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
14254        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
14255        Builtin::Table(&MZ_COMMENTS),
14256        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
14257        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
14258        Builtin::MaterializedView(&MZ_MATERIALIZED_VIEWS),
14259        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
14260        Builtin::MaterializedView(&MZ_NETWORK_POLICIES),
14261        Builtin::MaterializedView(&MZ_NETWORK_POLICY_RULES),
14262        Builtin::Table(&MZ_LICENSE_KEYS),
14263        Builtin::Table(&MZ_REPLACEMENTS),
14264        Builtin::View(&MZ_RELATIONS),
14265        Builtin::View(&MZ_OBJECT_OID_ALIAS),
14266        Builtin::View(&MZ_OBJECTS),
14267        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
14268        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
14269        Builtin::View(&MZ_OBJECT_HISTORY),
14270        Builtin::View(&MZ_OBJECT_LIFETIMES),
14271        Builtin::Table(&MZ_OBJECT_GLOBAL_IDS),
14272        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
14273        Builtin::View(&MZ_ARRANGEMENT_SHARING),
14274        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
14275        Builtin::View(&MZ_ARRANGEMENT_SIZES),
14276        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
14277        Builtin::View(&MZ_DATAFLOWS),
14278        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
14279        Builtin::View(&MZ_DATAFLOW_CHANNELS),
14280        Builtin::View(&MZ_DATAFLOW_OPERATORS),
14281        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
14282        Builtin::View(&MZ_COMPUTE_EXPORTS),
14283        Builtin::View(&MZ_MAPPABLE_OBJECTS),
14284        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
14285        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
14286        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
14287        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
14288        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
14289        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
14290        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
14291        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
14292        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
14293        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
14294        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
14295        Builtin::View(&MZ_COMPUTE_FRONTIERS),
14296        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
14297        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
14298        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
14299        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
14300        Builtin::View(&MZ_MESSAGE_COUNTS),
14301        Builtin::View(&MZ_ACTIVE_PEEKS),
14302        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
14303        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
14304        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
14305        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
14306        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
14307        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
14308        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
14309        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
14310        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
14311        Builtin::View(&MZ_SCHEDULING_ELAPSED),
14312        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
14313        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
14314        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
14315        Builtin::View(&MZ_SHOW_COLUMNS),
14316        Builtin::View(&MZ_SHOW_CLUSTERS),
14317        Builtin::View(&MZ_SHOW_SECRETS),
14318        Builtin::View(&MZ_SHOW_DATABASES),
14319        Builtin::View(&MZ_SHOW_SCHEMAS),
14320        Builtin::View(&MZ_SHOW_TABLES),
14321        Builtin::View(&MZ_SHOW_VIEWS),
14322        Builtin::View(&MZ_SHOW_TYPES),
14323        Builtin::View(&MZ_SHOW_ROLES),
14324        Builtin::View(&MZ_SHOW_CONNECTIONS),
14325        Builtin::View(&MZ_SHOW_SOURCES),
14326        Builtin::View(&MZ_SHOW_SINKS),
14327        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
14328        Builtin::View(&MZ_SHOW_INDEXES),
14329        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
14330        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
14331        Builtin::View(&MZ_TIMEZONE_NAMES),
14332        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
14333        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
14334        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
14335        Builtin::View(&PG_NAMESPACE),
14336        Builtin::View(&PG_CLASS_ALL_DATABASES),
14337        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
14338        Builtin::View(&PG_CLASS),
14339        Builtin::View(&PG_DEPEND),
14340        Builtin::View(&PG_DATABASE),
14341        Builtin::View(&PG_INDEX),
14342        Builtin::View(&PG_TYPE_ALL_DATABASES),
14343        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
14344        Builtin::View(&PG_TYPE),
14345        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
14346        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
14347        Builtin::View(&PG_DESCRIPTION),
14348        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
14349        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
14350        Builtin::View(&PG_ATTRIBUTE),
14351        Builtin::View(&PG_PROC),
14352        Builtin::View(&PG_OPERATOR),
14353        Builtin::View(&PG_RANGE),
14354        Builtin::View(&PG_ENUM),
14355        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
14356        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
14357        Builtin::View(&PG_ATTRDEF),
14358        Builtin::View(&PG_SETTINGS),
14359        Builtin::View(&PG_AUTH_MEMBERS),
14360        Builtin::View(&PG_CONSTRAINT),
14361        Builtin::View(&PG_TABLES),
14362        Builtin::View(&PG_TABLESPACE),
14363        Builtin::View(&PG_ACCESS_METHODS),
14364        Builtin::View(&PG_LOCKS),
14365        Builtin::View(&PG_AUTHID_CORE),
14366        Builtin::Index(&PG_AUTHID_CORE_IND),
14367        Builtin::View(&PG_AUTHID),
14368        Builtin::View(&PG_ROLES),
14369        Builtin::View(&PG_USER),
14370        Builtin::View(&PG_VIEWS),
14371        Builtin::View(&PG_MATVIEWS),
14372        Builtin::View(&PG_COLLATION),
14373        Builtin::View(&PG_POLICY),
14374        Builtin::View(&PG_INHERITS),
14375        Builtin::View(&PG_AGGREGATE),
14376        Builtin::View(&PG_TRIGGER),
14377        Builtin::View(&PG_REWRITE),
14378        Builtin::View(&PG_EXTENSION),
14379        Builtin::View(&PG_EVENT_TRIGGER),
14380        Builtin::View(&PG_LANGUAGE),
14381        Builtin::View(&PG_SHDESCRIPTION),
14382        Builtin::View(&PG_INDEXES),
14383        Builtin::View(&PG_TIMEZONE_ABBREVS),
14384        Builtin::View(&PG_TIMEZONE_NAMES),
14385        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
14386        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
14387        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
14388        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
14389        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
14390        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
14391        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
14392        Builtin::View(&INFORMATION_SCHEMA_TABLES),
14393        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
14394        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
14395        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
14396        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
14397        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
14398        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
14399        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
14400        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
14401        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
14402        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
14403        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
14404        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
14405        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
14406        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
14407        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
14408        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
14409        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
14410        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
14411        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
14412        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
14413        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
14414        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
14415        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
14416        Builtin::View(&MZ_SINK_STATUSES),
14417        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
14418        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
14419        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
14420        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
14421        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
14422        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
14423        Builtin::Source(&MZ_SESSION_HISTORY),
14424        Builtin::Source(&MZ_SQL_TEXT),
14425        Builtin::View(&MZ_SQL_TEXT_REDACTED),
14426        Builtin::View(&MZ_RECENT_SQL_TEXT),
14427        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
14428        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
14429        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
14430        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
14431        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
14432        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
14433        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
14434        Builtin::View(&MZ_SOURCE_STATUSES),
14435        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
14436        Builtin::Source(&MZ_STORAGE_SHARDS),
14437        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
14438        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
14439        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
14440        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
14441        Builtin::View(&MZ_SOURCE_STATISTICS),
14442        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
14443        Builtin::View(&MZ_SINK_STATISTICS),
14444        Builtin::Index(&MZ_SINK_STATISTICS_IND),
14445        Builtin::View(&MZ_STORAGE_USAGE),
14446        Builtin::Source(&MZ_FRONTIERS),
14447        Builtin::View(&MZ_GLOBAL_FRONTIERS),
14448        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
14449        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
14450        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
14451        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
14452        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
14453        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
14454        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
14455        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
14456        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
14457        Builtin::View(&MZ_MATERIALIZATION_LAG),
14458        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
14459        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
14460        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
14461        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
14462        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
14463        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
14464        Builtin::View(&MZ_LIR_MAPPING),
14465        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
14466        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
14467        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
14468        Builtin::View(&MZ_HYDRATION_STATUSES),
14469        Builtin::Index(&MZ_HYDRATION_STATUSES_IND),
14470        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
14471        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
14472        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
14473        Builtin::Index(&MZ_SHOW_DATABASES_IND),
14474        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
14475        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
14476        Builtin::Index(&MZ_SHOW_TABLES_IND),
14477        Builtin::Index(&MZ_SHOW_SOURCES_IND),
14478        Builtin::Index(&MZ_SHOW_VIEWS_IND),
14479        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
14480        Builtin::Index(&MZ_SHOW_SINKS_IND),
14481        Builtin::Index(&MZ_SHOW_TYPES_IND),
14482        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
14483        Builtin::Index(&MZ_SHOW_INDEXES_IND),
14484        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
14485        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
14486        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
14487        Builtin::Index(&MZ_SHOW_SECRETS_IND),
14488        Builtin::Index(&MZ_SHOW_ROLES_IND),
14489        Builtin::Index(&MZ_CLUSTERS_IND),
14490        Builtin::Index(&MZ_INDEXES_IND),
14491        Builtin::Index(&MZ_ROLES_IND),
14492        Builtin::Index(&MZ_SOURCES_IND),
14493        Builtin::Index(&MZ_SINKS_IND),
14494        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
14495        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
14496        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
14497        Builtin::Index(&MZ_SINK_STATUSES_IND),
14498        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
14499        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
14500        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
14501        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
14502        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
14503        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
14504        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
14505        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
14506        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
14507        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
14508        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
14509        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
14510        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
14511        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
14512        Builtin::Index(&MZ_FRONTIERS_IND),
14513        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
14514        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
14515        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
14516        Builtin::Index(&MZ_COMMENTS_IND),
14517        Builtin::Index(&MZ_DATABASES_IND),
14518        Builtin::Index(&MZ_SCHEMAS_IND),
14519        Builtin::Index(&MZ_CONNECTIONS_IND),
14520        Builtin::Index(&MZ_TABLES_IND),
14521        Builtin::Index(&MZ_TYPES_IND),
14522        Builtin::Index(&MZ_OBJECTS_IND),
14523        Builtin::Index(&MZ_COLUMNS_IND),
14524        Builtin::Index(&MZ_SECRETS_IND),
14525        Builtin::Index(&MZ_VIEWS_IND),
14526        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
14527        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
14528        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
14529        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
14530        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
14531        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
14532        Builtin::Connection(&MZ_ANALYTICS),
14533        Builtin::View(&MZ_INDEX_ADVICE),
14534        Builtin::View(&MZ_MCP_DATA_PRODUCTS),
14535        Builtin::View(&MZ_MCP_DATA_PRODUCT_DETAILS),
14536    ];
14537
14538    builtin_items.extend(notice::builtins());
14539
14540    // Generate builtin relations reporting builtin objects last, since they need a complete view
14541    // of all other builtins.
14542    let mut builtin_builtins = builtin::builtins(&builtin_items).collect();
14543
14544    // Construct the full list of builtins, retaining dependency order.
14545    let mut builtins = Vec::new();
14546    builtins.append(&mut builtin_types);
14547    builtins.append(&mut builtin_funcs);
14548    builtins.append(&mut builtin_builtins);
14549    builtins.append(&mut builtin_items);
14550
14551    builtins
14552});
14553pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
14554    &MZ_SYSTEM_ROLE,
14555    &MZ_SUPPORT_ROLE,
14556    &MZ_ANALYTICS_ROLE,
14557    &MZ_MONITOR_ROLE,
14558    &MZ_MONITOR_REDACTED,
14559    &MZ_JWT_SYNC_ROLE,
14560];
14561pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
14562    &MZ_SYSTEM_CLUSTER,
14563    &MZ_CATALOG_SERVER_CLUSTER,
14564    &MZ_PROBE_CLUSTER,
14565    &MZ_SUPPORT_CLUSTER,
14566    &MZ_ANALYTICS_CLUSTER,
14567];
14568pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
14569    &MZ_SYSTEM_CLUSTER_REPLICA,
14570    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14571    &MZ_PROBE_CLUSTER_REPLICA,
14572];
14573
14574#[allow(non_snake_case)]
14575pub mod BUILTINS {
14576    use super::*;
14577
14578    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14579        BUILTINS_STATIC.iter().filter_map(|b| match b {
14580            Builtin::Log(log) => Some(*log),
14581            _ => None,
14582        })
14583    }
14584
14585    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14586        BUILTINS_STATIC.iter().filter_map(|b| match b {
14587            Builtin::Type(typ) => Some(*typ),
14588            _ => None,
14589        })
14590    }
14591
14592    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14593        BUILTINS_STATIC.iter().filter_map(|b| match b {
14594            Builtin::View(view) => Some(*view),
14595            _ => None,
14596        })
14597    }
14598
14599    pub fn materialized_views() -> impl Iterator<Item = &'static BuiltinMaterializedView> {
14600        BUILTINS_STATIC.iter().filter_map(|b| match b {
14601            Builtin::MaterializedView(mv) => Some(*mv),
14602            _ => None,
14603        })
14604    }
14605
14606    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14607        BUILTINS_STATIC.iter().filter_map(|b| match b {
14608            Builtin::Func(func) => Some(func),
14609            _ => None,
14610        })
14611    }
14612
14613    pub fn iter() -> impl Iterator<Item = &'static Builtin<NameReference>> {
14614        BUILTINS_STATIC.iter()
14615    }
14616}
14617
14618pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14619    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14620/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14621/// the builtin itself.
14622pub static BUILTIN_LOOKUP: LazyLock<
14623    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14624> = LazyLock::new(|| {
14625    BUILTINS_STATIC
14626        .iter()
14627        .enumerate()
14628        .map(|(idx, builtin)| {
14629            (
14630                SystemObjectDescription {
14631                    schema_name: builtin.schema().to_string(),
14632                    object_type: builtin.catalog_item_type(),
14633                    object_name: builtin.name().to_string(),
14634                },
14635                (idx, builtin),
14636            )
14637        })
14638        .collect()
14639});
14640
14641#[cfg(test)]
14642mod tests {
14643    use std::collections::{BTreeMap, BTreeSet};
14644
14645    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14646    use mz_sql_parser::ast::visit::{self, Visit};
14647    use mz_sql_parser::ast::{Raw, RawItemName, UnresolvedItemName};
14648
14649    use super::*;
14650
14651    #[mz_ore::test]
14652    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14653    fn test_builtin_type_schema() {
14654        for typ in BUILTINS::types() {
14655            if typ.oid < FIRST_MATERIALIZE_OID {
14656                assert_eq!(
14657                    typ.schema, PG_CATALOG_SCHEMA,
14658                    "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14659                );
14660            } else {
14661                // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the
14662                // mz_catalog schema.
14663                assert_eq!(
14664                    typ.schema, MZ_CATALOG_SCHEMA,
14665                    "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14666                );
14667            }
14668        }
14669    }
14670
14671    /// Visitor that collects the last component of all referenced
14672    /// item names from a SQL AST.
14673    struct ItemNameCollector {
14674        names: BTreeSet<String>,
14675    }
14676
14677    impl<'ast> Visit<'ast, Raw> for ItemNameCollector {
14678        fn visit_item_name(&mut self, name: &'ast <Raw as mz_sql_parser::ast::AstInfo>::ItemName) {
14679            let unresolved: &UnresolvedItemName = match name {
14680                RawItemName::Name(n) | RawItemName::Id(_, n, _) => n,
14681            };
14682            let parts = &unresolved.0;
14683            if !parts.is_empty() {
14684                let obj_name = parts[parts.len() - 1].as_str().to_string();
14685                self.names.insert(obj_name);
14686            }
14687            visit::visit_item_name(self, name);
14688        }
14689    }
14690
14691    /// Tests that `BUILTINS_STATIC` is ordered respecting dependencies:
14692    /// if builtin A references builtin B in its SQL, then B must appear
14693    /// before A in the list. (This ordering is assumed by, e.g.,
14694    /// `sort_updates` during catalog migrations.)
14695    #[mz_ore::test]
14696    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14697    fn test_builtins_static_dependency_order() {
14698        // Build a map from name -> (schema, index) for all builtins.
14699        // We look up by just the name (last component) to catch
14700        // unqualified references in SQL.
14701        let mut builtin_by_name: BTreeMap<&str, (&str, usize)> = BTreeMap::new();
14702        let mut duplicate_names = Vec::new();
14703        for (idx, builtin) in BUILTINS_STATIC.iter().enumerate() {
14704            if let Some((prev_schema, prev_idx)) =
14705                builtin_by_name.insert(builtin.name(), (builtin.schema(), idx))
14706            {
14707                // Only flag duplicates across different schemas.
14708                // Same-schema duplicates (e.g., range types that
14709                // appear as both Type and Func) are fine because
14710                // they resolve to the same schema.
14711                if prev_schema != builtin.schema() {
14712                    duplicate_names.push(format!(
14713                        "name {:?} appears in both {}.{} (index \
14714                         {}) and {}.{} (index {})",
14715                        builtin.name(),
14716                        prev_schema,
14717                        builtin.name(),
14718                        prev_idx,
14719                        builtin.schema(),
14720                        builtin.name(),
14721                        idx,
14722                    ));
14723                }
14724            }
14725        }
14726        assert!(
14727            duplicate_names.is_empty(),
14728            "BUILTINS_STATIC has duplicate names across different \
14729             schemas (this test needs adjustment if such duplicates \
14730             are intentional):\n{}",
14731            duplicate_names.join("\n"),
14732        );
14733
14734        // Get the `CREATE ...` SQL for builtins that have it.
14735        let get_create_sql = |builtin: &Builtin<NameReference>| -> Option<String> {
14736            match builtin {
14737                Builtin::View(v) => Some(v.create_sql()),
14738                Builtin::MaterializedView(mv) => Some(mv.create_sql()),
14739                Builtin::Index(idx) => Some(idx.create_sql()),
14740                _ => None,
14741            }
14742        };
14743
14744        // For each SQL-bearing builtin, parse its SQL, walk the AST to
14745        // find referenced item names, and check that all referenced
14746        // builtins appear earlier in BUILTINS_STATIC.
14747        let mut violations = Vec::new();
14748        for (idx, builtin) in BUILTINS_STATIC.iter().enumerate() {
14749            let create_sql = match get_create_sql(builtin) {
14750                Some(sql) => sql,
14751                None => continue,
14752            };
14753
14754            let stmts = mz_sql_parser::parser::parse_statements(&create_sql).unwrap_or_else(|e| {
14755                panic!(
14756                    "failed to parse SQL for {}.{}: \
14757                         {e}\nSQL: {create_sql}",
14758                    builtin.schema(),
14759                    builtin.name(),
14760                )
14761            });
14762
14763            let mut collector = ItemNameCollector {
14764                names: BTreeSet::new(),
14765            };
14766            for stmt in &stmts {
14767                collector.visit_statement(&stmt.ast);
14768            }
14769
14770            for ref_name in &collector.names {
14771                if let Some(&(ref_schema, dep_idx)) = builtin_by_name.get(ref_name.as_str()) {
14772                    if dep_idx > idx {
14773                        violations.push(format!(
14774                            "{}.{} (index {}) references \
14775                             {}.{} (index {}), but the \
14776                             dependency appears later in \
14777                             BUILTINS_STATIC",
14778                            builtin.schema(),
14779                            builtin.name(),
14780                            idx,
14781                            ref_schema,
14782                            ref_name,
14783                            dep_idx,
14784                        ));
14785                    }
14786                }
14787            }
14788        }
14789
14790        assert!(
14791            violations.is_empty(),
14792            "BUILTINS_STATIC has dependency ordering violations:\n{}",
14793            violations.join("\n"),
14794        );
14795    }
14796}