Skip to main content

mz_catalog/
builtin.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Built-in catalog items.
11//!
12//! Builtins exist in the `mz_catalog` ambient schema. They are automatically
13//! installed into the catalog when it is opened. Their definitions are not
14//! persisted in the catalog, but hardcoded in this module. This makes it easy
15//! to add new builtins, or change the definition of existing builtins, in new
16//! versions of Materialize.
17//!
18//! Builtin's names, columns, and types are part of the stable API of
19//! Materialize. Be careful to maintain backwards compatibility when changing
20//! definitions of existing builtins!
21//!
22//! More information about builtin system tables and types can be found in
23//! <https://materialize.com/docs/sql/system-catalog/>.
24
25pub mod notice;
26
27use std::collections::BTreeMap;
28use std::hash::Hash;
29use std::string::ToString;
30use std::sync::LazyLock;
31
32use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
33use mz_ore::collections::HashMap;
34use mz_pgrepr::oid;
35use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
36use mz_repr::adt::numeric::NumericMaxScale;
37use mz_repr::namespaces::{
38    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_INTROSPECTION_SCHEMA,
39    MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA,
40};
41use mz_repr::role_id::RoleId;
42use mz_repr::{RelationDesc, SqlRelationType, SqlScalarType};
43use mz_sql::catalog::RoleAttributesRaw;
44use mz_sql::catalog::{
45    CatalogItemType, CatalogType, CatalogTypeDetails, CatalogTypePgMetadata, NameReference,
46    ObjectType, SystemObjectType, TypeReference,
47};
48use mz_sql::rbac;
49use mz_sql::session::user::{
50    ANALYTICS_USER_NAME, MZ_ANALYTICS_ROLE_ID, MZ_MONITOR_REDACTED_ROLE_ID, MZ_MONITOR_ROLE_ID,
51    MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID, SUPPORT_USER_NAME, SYSTEM_USER_NAME,
52};
53use mz_storage_client::controller::IntrospectionType;
54use mz_storage_client::healthcheck::WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC;
55use mz_storage_client::healthcheck::{
56    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_PREPARED_STATEMENT_HISTORY_DESC,
57    MZ_SESSION_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC, MZ_SOURCE_STATUS_HISTORY_DESC,
58    MZ_SQL_TEXT_DESC, MZ_STATEMENT_EXECUTION_HISTORY_DESC, REPLICA_METRICS_HISTORY_DESC,
59    REPLICA_STATUS_HISTORY_DESC, WALLCLOCK_LAG_HISTORY_DESC,
60};
61use mz_storage_client::statistics::{MZ_SINK_STATISTICS_RAW_DESC, MZ_SOURCE_STATISTICS_RAW_DESC};
62use serde::Serialize;
63
64use crate::durable::objects::SystemObjectDescription;
65use crate::memory::objects::DataSourceDesc;
66
67pub const BUILTIN_PREFIXES: &[&str] = &["mz_", "pg_", "external_"];
68const BUILTIN_CLUSTER_REPLICA_NAME: &str = "r1";
69
70/// A sentinel used in place of a fingerprint that indicates that a builtin
71/// object is runtime alterable. Runtime alterable objects don't have meaningful
72/// fingerprints because they may have been intentionally changed by the user
73/// after creation.
74// NOTE(benesch): ideally we'd use a fingerprint type that used a sum type
75// rather than a loosely typed string to represent the runtime alterable
76// state like so:
77//
78//     enum Fingerprint {
79//         SqlText(String),
80//         RuntimeAlterable,
81//     }
82//
83// However, that would entail a complicated migration for the existing system object
84// mapping collection stored on disk.
85pub const RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL: &str = "<RUNTIME-ALTERABLE>";
86
87#[derive(Clone, Debug)]
88pub enum Builtin<T: 'static + TypeReference> {
89    Log(&'static BuiltinLog),
90    Table(&'static BuiltinTable),
91    View(&'static BuiltinView),
92    MaterializedView(&'static BuiltinMaterializedView),
93    Type(&'static BuiltinType<T>),
94    Func(BuiltinFunc),
95    Source(&'static BuiltinSource),
96    ContinualTask(&'static BuiltinContinualTask),
97    Index(&'static BuiltinIndex),
98    Connection(&'static BuiltinConnection),
99}
100
101impl<T: TypeReference> Builtin<T> {
102    pub fn name(&self) -> &'static str {
103        match self {
104            Builtin::Log(log) => log.name,
105            Builtin::Table(table) => table.name,
106            Builtin::View(view) => view.name,
107            Builtin::MaterializedView(mv) => mv.name,
108            Builtin::Type(typ) => typ.name,
109            Builtin::Func(func) => func.name,
110            Builtin::Source(coll) => coll.name,
111            Builtin::ContinualTask(ct) => ct.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::ContinualTask(ct) => ct.schema,
127            Builtin::Index(index) => index.schema,
128            Builtin::Connection(connection) => connection.schema,
129        }
130    }
131
132    pub fn catalog_item_type(&self) -> CatalogItemType {
133        match self {
134            Builtin::Log(_) => CatalogItemType::Source,
135            Builtin::Source(_) => CatalogItemType::Source,
136            Builtin::ContinualTask(_) => CatalogItemType::ContinualTask,
137            Builtin::Table(_) => CatalogItemType::Table,
138            Builtin::View(_) => CatalogItemType::View,
139            Builtin::MaterializedView(_) => CatalogItemType::MaterializedView,
140            Builtin::Type(_) => CatalogItemType::Type,
141            Builtin::Func(_) => CatalogItemType::Func,
142            Builtin::Index(_) => CatalogItemType::Index,
143            Builtin::Connection(_) => CatalogItemType::Connection,
144        }
145    }
146
147    /// Whether the object can be altered at runtime by its owner.
148    pub fn runtime_alterable(&self) -> bool {
149        match self {
150            Builtin::Connection(c) => c.runtime_alterable,
151            _ => false,
152        }
153    }
154}
155
156#[derive(Clone, Debug, Hash, Serialize)]
157pub struct BuiltinLog {
158    pub variant: LogVariant,
159    pub name: &'static str,
160    pub schema: &'static str,
161    pub oid: u32,
162    /// ACL items to apply to the object
163    pub access: Vec<MzAclItem>,
164}
165
166#[derive(Clone, Hash, Debug, PartialEq, Eq)]
167pub struct BuiltinTable {
168    pub name: &'static str,
169    pub schema: &'static str,
170    pub oid: u32,
171    pub desc: RelationDesc,
172    pub column_comments: BTreeMap<&'static str, &'static str>,
173    /// Whether the table's retention policy is controlled by
174    /// the system variable `METRICS_RETENTION`
175    pub is_retained_metrics_object: bool,
176    /// ACL items to apply to the object
177    pub access: Vec<MzAclItem>,
178}
179
180#[derive(Clone, Debug, PartialEq, Eq)]
181pub struct BuiltinSource {
182    pub name: &'static str,
183    pub schema: &'static str,
184    pub oid: u32,
185    pub desc: RelationDesc,
186    pub column_comments: BTreeMap<&'static str, &'static str>,
187    pub data_source: DataSourceDesc,
188    /// Whether the source's retention policy is controlled by
189    /// the system variable `METRICS_RETENTION`
190    pub is_retained_metrics_object: bool,
191    /// ACL items to apply to the object
192    pub access: Vec<MzAclItem>,
193}
194
195#[derive(Hash, Debug, PartialEq, Eq)]
196pub struct BuiltinContinualTask {
197    pub name: &'static str,
198    pub schema: &'static str,
199    pub oid: u32,
200    pub desc: RelationDesc,
201    pub sql: &'static str,
202    /// ACL items to apply to the object
203    pub access: Vec<MzAclItem>,
204}
205
206#[derive(Hash, Debug)]
207pub struct BuiltinView {
208    pub name: &'static str,
209    pub schema: &'static str,
210    pub oid: u32,
211    pub desc: RelationDesc,
212    pub column_comments: BTreeMap<&'static str, &'static str>,
213    pub sql: &'static str,
214    /// ACL items to apply to the object
215    pub access: Vec<MzAclItem>,
216}
217
218impl BuiltinView {
219    pub fn create_sql(&self) -> String {
220        format!("CREATE VIEW {}.{} AS {}", self.schema, self.name, self.sql)
221    }
222}
223
224#[derive(Hash, Debug)]
225pub struct BuiltinMaterializedView {
226    pub name: &'static str,
227    pub schema: &'static str,
228    pub oid: u32,
229    pub desc: RelationDesc,
230    pub column_comments: BTreeMap<&'static str, &'static str>,
231    /// SQL fragment for the MV, following `CREATE MATERIALIZED VIEW [name]`
232    ///
233    /// Format: `IN CLUSTER [cluster_name] AS [query]`
234    pub sql: &'static str,
235    /// ACL items to apply to the object
236    pub access: Vec<MzAclItem>,
237}
238
239impl BuiltinMaterializedView {
240    pub fn create_sql(&self) -> String {
241        format!(
242            "CREATE MATERIALIZED VIEW {}.{} {}",
243            self.schema, self.name, self.sql
244        )
245    }
246}
247
248#[derive(Debug)]
249pub struct BuiltinType<T: TypeReference> {
250    pub name: &'static str,
251    pub schema: &'static str,
252    pub oid: u32,
253    pub details: CatalogTypeDetails<T>,
254}
255
256#[derive(Clone, Debug)]
257pub struct BuiltinFunc {
258    pub schema: &'static str,
259    pub name: &'static str,
260    pub inner: &'static mz_sql::func::Func,
261}
262
263/// Note: When creating a built-in index, it's usually best to choose a key that has only one
264/// component. For example, if you created an index
265/// `ON mz_internal.mz_object_lifetimes (id, object_type)`, then this index couldn't be used for a
266/// lookup for `WHERE object_type = ...`, and neither for joins keyed on just `id`.
267/// See <https://materialize.com/docs/transform-data/optimization/#matching-multi-column-indexes-to-multi-column-where-clauses>
268#[derive(Debug)]
269pub struct BuiltinIndex {
270    pub name: &'static str,
271    pub schema: &'static str,
272    pub oid: u32,
273    /// SQL fragment for the index, following `CREATE INDEX [name]`
274    ///
275    /// Format: `IN CLUSTER [cluster_name] ON [table_name] ([column_exprs])`
276    pub sql: &'static str,
277    pub is_retained_metrics_object: bool,
278}
279
280impl BuiltinIndex {
281    pub fn create_sql(&self) -> String {
282        format!("CREATE INDEX {}\n{}", self.name, self.sql)
283    }
284}
285
286impl BuiltinContinualTask {
287    pub fn create_sql(&self) -> String {
288        format!(
289            "CREATE CONTINUAL TASK {}.{}\n{}",
290            self.schema, self.name, self.sql
291        )
292    }
293}
294
295#[derive(Hash, Debug)]
296pub struct BuiltinConnection {
297    pub name: &'static str,
298    pub schema: &'static str,
299    pub oid: u32,
300    pub sql: &'static str,
301    pub access: &'static [MzAclItem],
302    pub owner_id: &'static RoleId,
303    /// Whether the object can be altered at runtime by its owner.
304    ///
305    /// Note that when `runtime_alterable` is true, changing the `sql` in future
306    /// versions does not trigger a migration.
307    pub runtime_alterable: bool,
308}
309
310#[derive(Clone, Debug)]
311pub struct BuiltinRole {
312    pub id: RoleId,
313    /// Name of the builtin role.
314    ///
315    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
316    pub name: &'static str,
317    pub oid: u32,
318    pub attributes: RoleAttributesRaw,
319}
320
321#[derive(Clone, Debug)]
322pub struct BuiltinCluster {
323    /// Name of the cluster.
324    ///
325    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
326    pub name: &'static str,
327    pub privileges: &'static [MzAclItem],
328    pub owner_id: &'static RoleId,
329}
330
331#[derive(Clone, Debug, PartialEq, Eq)]
332pub struct BuiltinClusterReplica {
333    /// Name of the compute replica.
334    pub name: &'static str,
335    /// Name of the cluster that this replica belongs to.
336    pub cluster_name: &'static str,
337}
338
339/// Uniquely identifies the definition of a builtin object.
340pub trait Fingerprint {
341    fn fingerprint(&self) -> String;
342}
343
344impl<T: TypeReference> Fingerprint for &Builtin<T> {
345    fn fingerprint(&self) -> String {
346        match self {
347            Builtin::Log(log) => log.fingerprint(),
348            Builtin::Table(table) => table.fingerprint(),
349            Builtin::View(view) => view.fingerprint(),
350            Builtin::MaterializedView(mv) => mv.fingerprint(),
351            Builtin::Type(typ) => typ.fingerprint(),
352            Builtin::Func(func) => func.fingerprint(),
353            Builtin::Source(coll) => coll.fingerprint(),
354            Builtin::ContinualTask(ct) => ct.fingerprint(),
355            Builtin::Index(index) => index.fingerprint(),
356            Builtin::Connection(connection) => connection.fingerprint(),
357        }
358    }
359}
360
361// Types and Funcs never change fingerprints so we just return constant 0
362impl<T: TypeReference> Fingerprint for &BuiltinType<T> {
363    fn fingerprint(&self) -> String {
364        "".to_string()
365    }
366}
367
368impl Fingerprint for &BuiltinFunc {
369    fn fingerprint(&self) -> String {
370        "".to_string()
371    }
372}
373
374impl Fingerprint for &BuiltinLog {
375    fn fingerprint(&self) -> String {
376        self.variant.desc().fingerprint()
377    }
378}
379
380impl Fingerprint for &BuiltinTable {
381    fn fingerprint(&self) -> String {
382        self.desc.fingerprint()
383    }
384}
385
386impl Fingerprint for &BuiltinView {
387    fn fingerprint(&self) -> String {
388        self.sql.to_string()
389    }
390}
391
392impl Fingerprint for &BuiltinSource {
393    fn fingerprint(&self) -> String {
394        self.desc.fingerprint()
395    }
396}
397
398impl Fingerprint for &BuiltinMaterializedView {
399    fn fingerprint(&self) -> String {
400        self.create_sql()
401    }
402}
403
404impl Fingerprint for &BuiltinContinualTask {
405    fn fingerprint(&self) -> String {
406        self.create_sql()
407    }
408}
409
410impl Fingerprint for &BuiltinIndex {
411    fn fingerprint(&self) -> String {
412        self.create_sql()
413    }
414}
415
416impl Fingerprint for &BuiltinConnection {
417    fn fingerprint(&self) -> String {
418        self.sql.to_string()
419    }
420}
421
422impl Fingerprint for RelationDesc {
423    fn fingerprint(&self) -> String {
424        self.typ().fingerprint()
425    }
426}
427
428impl Fingerprint for SqlRelationType {
429    fn fingerprint(&self) -> String {
430        serde_json::to_string(self).expect("serialization cannot fail")
431    }
432}
433
434// Builtin definitions below. Ensure you add new builtins to the `BUILTINS` map.
435//
436// You SHOULD NOT delete a builtin. If you do, you will break any downstream
437// user objects that depended on the builtin.
438//
439// Builtins are loaded in dependency order, so a builtin must appear in `BUILTINS`
440// before any items it depends upon.
441//
442// WARNING: if you change the definition of an existing builtin item, you must
443// be careful to maintain backwards compatibility! Adding new columns is safe.
444// Removing a column, changing the name of a column, or changing the type of a
445// column is not safe, as persisted user views may depend upon that column.
446
447// The following types are the list of builtin data types available
448// in Materialize. This list is derived from the `pg_type` table in PostgreSQL.
449//
450// Builtin types cannot be created, updated, or deleted. Their OIDs
451// are static, unlike other objects, to match the type OIDs defined by Postgres.
452
453pub const TYPE_BOOL: BuiltinType<NameReference> = BuiltinType {
454    name: "bool",
455    schema: PG_CATALOG_SCHEMA,
456    oid: oid::TYPE_BOOL_OID,
457    details: CatalogTypeDetails {
458        typ: CatalogType::Bool,
459        array_id: None,
460        pg_metadata: Some(CatalogTypePgMetadata {
461            typinput_oid: 1242,
462            typreceive_oid: 2436,
463        }),
464    },
465};
466
467pub const TYPE_BYTEA: BuiltinType<NameReference> = BuiltinType {
468    name: "bytea",
469    schema: PG_CATALOG_SCHEMA,
470    oid: oid::TYPE_BYTEA_OID,
471    details: CatalogTypeDetails {
472        typ: CatalogType::Bytes,
473        array_id: None,
474        pg_metadata: Some(CatalogTypePgMetadata {
475            typinput_oid: 1244,
476            typreceive_oid: 2412,
477        }),
478    },
479};
480
481pub const TYPE_INT8: BuiltinType<NameReference> = BuiltinType {
482    name: "int8",
483    schema: PG_CATALOG_SCHEMA,
484    oid: oid::TYPE_INT8_OID,
485    details: CatalogTypeDetails {
486        typ: CatalogType::Int64,
487        array_id: None,
488        pg_metadata: Some(CatalogTypePgMetadata {
489            typinput_oid: 460,
490            typreceive_oid: 2408,
491        }),
492    },
493};
494
495pub const TYPE_INT4: BuiltinType<NameReference> = BuiltinType {
496    name: "int4",
497    schema: PG_CATALOG_SCHEMA,
498    oid: oid::TYPE_INT4_OID,
499    details: CatalogTypeDetails {
500        typ: CatalogType::Int32,
501        array_id: None,
502        pg_metadata: Some(CatalogTypePgMetadata {
503            typinput_oid: 42,
504            typreceive_oid: 2406,
505        }),
506    },
507};
508
509pub const TYPE_TEXT: BuiltinType<NameReference> = BuiltinType {
510    name: "text",
511    schema: PG_CATALOG_SCHEMA,
512    oid: oid::TYPE_TEXT_OID,
513    details: CatalogTypeDetails {
514        typ: CatalogType::String,
515        array_id: None,
516        pg_metadata: Some(CatalogTypePgMetadata {
517            typinput_oid: 46,
518            typreceive_oid: 2414,
519        }),
520    },
521};
522
523pub const TYPE_OID: BuiltinType<NameReference> = BuiltinType {
524    name: "oid",
525    schema: PG_CATALOG_SCHEMA,
526    oid: oid::TYPE_OID_OID,
527    details: CatalogTypeDetails {
528        typ: CatalogType::Oid,
529        array_id: None,
530        pg_metadata: Some(CatalogTypePgMetadata {
531            typinput_oid: 1798,
532            typreceive_oid: 2418,
533        }),
534    },
535};
536
537pub const TYPE_FLOAT4: BuiltinType<NameReference> = BuiltinType {
538    name: "float4",
539    schema: PG_CATALOG_SCHEMA,
540    oid: oid::TYPE_FLOAT4_OID,
541    details: CatalogTypeDetails {
542        typ: CatalogType::Float32,
543        array_id: None,
544        pg_metadata: Some(CatalogTypePgMetadata {
545            typinput_oid: 200,
546            typreceive_oid: 2424,
547        }),
548    },
549};
550
551pub const TYPE_FLOAT8: BuiltinType<NameReference> = BuiltinType {
552    name: "float8",
553    schema: PG_CATALOG_SCHEMA,
554    oid: oid::TYPE_FLOAT8_OID,
555    details: CatalogTypeDetails {
556        typ: CatalogType::Float64,
557        array_id: None,
558        pg_metadata: Some(CatalogTypePgMetadata {
559            typinput_oid: 214,
560            typreceive_oid: 2426,
561        }),
562    },
563};
564
565pub const TYPE_BOOL_ARRAY: BuiltinType<NameReference> = BuiltinType {
566    name: "_bool",
567    schema: PG_CATALOG_SCHEMA,
568    oid: oid::TYPE_BOOL_ARRAY_OID,
569    details: CatalogTypeDetails {
570        typ: CatalogType::Array {
571            element_reference: TYPE_BOOL.name,
572        },
573        array_id: None,
574        pg_metadata: Some(CatalogTypePgMetadata {
575            typinput_oid: 750,
576            typreceive_oid: 2400,
577        }),
578    },
579};
580
581pub const TYPE_BYTEA_ARRAY: BuiltinType<NameReference> = BuiltinType {
582    name: "_bytea",
583    schema: PG_CATALOG_SCHEMA,
584    oid: oid::TYPE_BYTEA_ARRAY_OID,
585    details: CatalogTypeDetails {
586        typ: CatalogType::Array {
587            element_reference: TYPE_BYTEA.name,
588        },
589        array_id: None,
590        pg_metadata: Some(CatalogTypePgMetadata {
591            typinput_oid: 750,
592            typreceive_oid: 2400,
593        }),
594    },
595};
596
597pub const TYPE_INT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
598    name: "_int4",
599    schema: PG_CATALOG_SCHEMA,
600    oid: oid::TYPE_INT4_ARRAY_OID,
601    details: CatalogTypeDetails {
602        typ: CatalogType::Array {
603            element_reference: TYPE_INT4.name,
604        },
605        array_id: None,
606        pg_metadata: Some(CatalogTypePgMetadata {
607            typinput_oid: 750,
608            typreceive_oid: 2400,
609        }),
610    },
611};
612
613pub const TYPE_TEXT_ARRAY: BuiltinType<NameReference> = BuiltinType {
614    name: "_text",
615    schema: PG_CATALOG_SCHEMA,
616    oid: oid::TYPE_TEXT_ARRAY_OID,
617    details: CatalogTypeDetails {
618        typ: CatalogType::Array {
619            element_reference: TYPE_TEXT.name,
620        },
621        array_id: None,
622        pg_metadata: Some(CatalogTypePgMetadata {
623            typinput_oid: 750,
624            typreceive_oid: 2400,
625        }),
626    },
627};
628
629pub const TYPE_INT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
630    name: "_int8",
631    schema: PG_CATALOG_SCHEMA,
632    oid: oid::TYPE_INT8_ARRAY_OID,
633    details: CatalogTypeDetails {
634        typ: CatalogType::Array {
635            element_reference: TYPE_INT8.name,
636        },
637        array_id: None,
638        pg_metadata: Some(CatalogTypePgMetadata {
639            typinput_oid: 750,
640            typreceive_oid: 2400,
641        }),
642    },
643};
644
645pub const TYPE_FLOAT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
646    name: "_float4",
647    schema: PG_CATALOG_SCHEMA,
648    oid: oid::TYPE_FLOAT4_ARRAY_OID,
649    details: CatalogTypeDetails {
650        typ: CatalogType::Array {
651            element_reference: TYPE_FLOAT4.name,
652        },
653        array_id: None,
654        pg_metadata: Some(CatalogTypePgMetadata {
655            typinput_oid: 750,
656            typreceive_oid: 2400,
657        }),
658    },
659};
660
661pub const TYPE_FLOAT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
662    name: "_float8",
663    schema: PG_CATALOG_SCHEMA,
664    oid: oid::TYPE_FLOAT8_ARRAY_OID,
665    details: CatalogTypeDetails {
666        typ: CatalogType::Array {
667            element_reference: TYPE_FLOAT8.name,
668        },
669        array_id: None,
670        pg_metadata: Some(CatalogTypePgMetadata {
671            typinput_oid: 750,
672            typreceive_oid: 2400,
673        }),
674    },
675};
676
677pub const TYPE_OID_ARRAY: BuiltinType<NameReference> = BuiltinType {
678    name: "_oid",
679    schema: PG_CATALOG_SCHEMA,
680    oid: oid::TYPE_OID_ARRAY_OID,
681    details: CatalogTypeDetails {
682        typ: CatalogType::Array {
683            element_reference: TYPE_OID.name,
684        },
685        array_id: None,
686        pg_metadata: Some(CatalogTypePgMetadata {
687            typinput_oid: 750,
688            typreceive_oid: 2400,
689        }),
690    },
691};
692
693pub const TYPE_DATE: BuiltinType<NameReference> = BuiltinType {
694    name: "date",
695    schema: PG_CATALOG_SCHEMA,
696    oid: oid::TYPE_DATE_OID,
697    details: CatalogTypeDetails {
698        typ: CatalogType::Date,
699        array_id: None,
700        pg_metadata: Some(CatalogTypePgMetadata {
701            typinput_oid: 1084,
702            typreceive_oid: 2468,
703        }),
704    },
705};
706
707pub const TYPE_TIME: BuiltinType<NameReference> = BuiltinType {
708    name: "time",
709    schema: PG_CATALOG_SCHEMA,
710    oid: oid::TYPE_TIME_OID,
711    details: CatalogTypeDetails {
712        typ: CatalogType::Time,
713        array_id: None,
714        pg_metadata: Some(CatalogTypePgMetadata {
715            typinput_oid: 1143,
716            typreceive_oid: 2470,
717        }),
718    },
719};
720
721pub const TYPE_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
722    name: "timestamp",
723    schema: PG_CATALOG_SCHEMA,
724    oid: oid::TYPE_TIMESTAMP_OID,
725    details: CatalogTypeDetails {
726        typ: CatalogType::Timestamp,
727        array_id: None,
728        pg_metadata: Some(CatalogTypePgMetadata {
729            typinput_oid: 1312,
730            typreceive_oid: 2474,
731        }),
732    },
733};
734
735pub const TYPE_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
736    name: "_timestamp",
737    schema: PG_CATALOG_SCHEMA,
738    oid: oid::TYPE_TIMESTAMP_ARRAY_OID,
739    details: CatalogTypeDetails {
740        typ: CatalogType::Array {
741            element_reference: TYPE_TIMESTAMP.name,
742        },
743        array_id: None,
744        pg_metadata: Some(CatalogTypePgMetadata {
745            typinput_oid: 750,
746            typreceive_oid: 2400,
747        }),
748    },
749};
750
751pub const TYPE_DATE_ARRAY: BuiltinType<NameReference> = BuiltinType {
752    name: "_date",
753    schema: PG_CATALOG_SCHEMA,
754    oid: oid::TYPE_DATE_ARRAY_OID,
755    details: CatalogTypeDetails {
756        typ: CatalogType::Array {
757            element_reference: TYPE_DATE.name,
758        },
759        array_id: None,
760        pg_metadata: Some(CatalogTypePgMetadata {
761            typinput_oid: 750,
762            typreceive_oid: 2400,
763        }),
764    },
765};
766
767pub const TYPE_TIME_ARRAY: BuiltinType<NameReference> = BuiltinType {
768    name: "_time",
769    schema: PG_CATALOG_SCHEMA,
770    oid: oid::TYPE_TIME_ARRAY_OID,
771    details: CatalogTypeDetails {
772        typ: CatalogType::Array {
773            element_reference: TYPE_TIME.name,
774        },
775        array_id: None,
776        pg_metadata: Some(CatalogTypePgMetadata {
777            typinput_oid: 750,
778            typreceive_oid: 2400,
779        }),
780    },
781};
782
783pub const TYPE_TIMESTAMPTZ: BuiltinType<NameReference> = BuiltinType {
784    name: "timestamptz",
785    schema: PG_CATALOG_SCHEMA,
786    oid: oid::TYPE_TIMESTAMPTZ_OID,
787    details: CatalogTypeDetails {
788        typ: CatalogType::TimestampTz,
789        array_id: None,
790        pg_metadata: Some(CatalogTypePgMetadata {
791            typinput_oid: 1150,
792            typreceive_oid: 2476,
793        }),
794    },
795};
796
797pub const TYPE_TIMESTAMPTZ_ARRAY: BuiltinType<NameReference> = BuiltinType {
798    name: "_timestamptz",
799    schema: PG_CATALOG_SCHEMA,
800    oid: oid::TYPE_TIMESTAMPTZ_ARRAY_OID,
801    details: CatalogTypeDetails {
802        typ: CatalogType::Array {
803            element_reference: TYPE_TIMESTAMPTZ.name,
804        },
805        array_id: None,
806        pg_metadata: Some(CatalogTypePgMetadata {
807            typinput_oid: 750,
808            typreceive_oid: 2400,
809        }),
810    },
811};
812
813pub const TYPE_INTERVAL: BuiltinType<NameReference> = BuiltinType {
814    name: "interval",
815    schema: PG_CATALOG_SCHEMA,
816    oid: oid::TYPE_INTERVAL_OID,
817    details: CatalogTypeDetails {
818        typ: CatalogType::Interval,
819        array_id: None,
820        pg_metadata: Some(CatalogTypePgMetadata {
821            typinput_oid: 1160,
822            typreceive_oid: 2478,
823        }),
824    },
825};
826
827pub const TYPE_INTERVAL_ARRAY: BuiltinType<NameReference> = BuiltinType {
828    name: "_interval",
829    schema: PG_CATALOG_SCHEMA,
830    oid: oid::TYPE_INTERVAL_ARRAY_OID,
831    details: CatalogTypeDetails {
832        typ: CatalogType::Array {
833            element_reference: TYPE_INTERVAL.name,
834        },
835        array_id: None,
836        pg_metadata: Some(CatalogTypePgMetadata {
837            typinput_oid: 750,
838            typreceive_oid: 2400,
839        }),
840    },
841};
842
843pub const TYPE_NAME: BuiltinType<NameReference> = BuiltinType {
844    name: "name",
845    schema: PG_CATALOG_SCHEMA,
846    oid: oid::TYPE_NAME_OID,
847    details: CatalogTypeDetails {
848        typ: CatalogType::PgLegacyName,
849        array_id: None,
850        pg_metadata: Some(CatalogTypePgMetadata {
851            typinput_oid: 34,
852            typreceive_oid: 2422,
853        }),
854    },
855};
856
857pub const TYPE_NAME_ARRAY: BuiltinType<NameReference> = BuiltinType {
858    name: "_name",
859    schema: PG_CATALOG_SCHEMA,
860    oid: oid::TYPE_NAME_ARRAY_OID,
861    details: CatalogTypeDetails {
862        typ: CatalogType::Array {
863            element_reference: TYPE_NAME.name,
864        },
865        array_id: None,
866        pg_metadata: Some(CatalogTypePgMetadata {
867            typinput_oid: 750,
868            typreceive_oid: 2400,
869        }),
870    },
871};
872
873pub const TYPE_NUMERIC: BuiltinType<NameReference> = BuiltinType {
874    name: "numeric",
875    schema: PG_CATALOG_SCHEMA,
876    oid: oid::TYPE_NUMERIC_OID,
877    details: CatalogTypeDetails {
878        typ: CatalogType::Numeric,
879        array_id: None,
880        pg_metadata: Some(CatalogTypePgMetadata {
881            typinput_oid: 1701,
882            typreceive_oid: 2460,
883        }),
884    },
885};
886
887pub const TYPE_NUMERIC_ARRAY: BuiltinType<NameReference> = BuiltinType {
888    name: "_numeric",
889    schema: PG_CATALOG_SCHEMA,
890    oid: oid::TYPE_NUMERIC_ARRAY_OID,
891    details: CatalogTypeDetails {
892        typ: CatalogType::Array {
893            element_reference: TYPE_NUMERIC.name,
894        },
895        array_id: None,
896        pg_metadata: Some(CatalogTypePgMetadata {
897            typinput_oid: 750,
898            typreceive_oid: 2400,
899        }),
900    },
901};
902
903pub const TYPE_RECORD: BuiltinType<NameReference> = BuiltinType {
904    name: "record",
905    schema: PG_CATALOG_SCHEMA,
906    oid: oid::TYPE_RECORD_OID,
907    details: CatalogTypeDetails {
908        typ: CatalogType::Pseudo,
909        array_id: None,
910        pg_metadata: Some(CatalogTypePgMetadata {
911            typinput_oid: 2290,
912            typreceive_oid: 2402,
913        }),
914    },
915};
916
917pub const TYPE_RECORD_ARRAY: BuiltinType<NameReference> = BuiltinType {
918    name: "_record",
919    schema: PG_CATALOG_SCHEMA,
920    oid: oid::TYPE_RECORD_ARRAY_OID,
921    details: CatalogTypeDetails {
922        typ: CatalogType::Array {
923            element_reference: TYPE_RECORD.name,
924        },
925        array_id: None,
926        pg_metadata: Some(CatalogTypePgMetadata {
927            typinput_oid: 750,
928            typreceive_oid: 2400,
929        }),
930    },
931};
932
933pub const TYPE_UUID: BuiltinType<NameReference> = BuiltinType {
934    name: "uuid",
935    schema: PG_CATALOG_SCHEMA,
936    oid: oid::TYPE_UUID_OID,
937    details: CatalogTypeDetails {
938        typ: CatalogType::Uuid,
939        array_id: None,
940        pg_metadata: Some(CatalogTypePgMetadata {
941            typinput_oid: 2952,
942            typreceive_oid: 2961,
943        }),
944    },
945};
946
947pub const TYPE_UUID_ARRAY: BuiltinType<NameReference> = BuiltinType {
948    name: "_uuid",
949    schema: PG_CATALOG_SCHEMA,
950    oid: oid::TYPE_UUID_ARRAY_OID,
951    details: CatalogTypeDetails {
952        typ: CatalogType::Array {
953            element_reference: TYPE_UUID.name,
954        },
955        array_id: None,
956        pg_metadata: Some(CatalogTypePgMetadata {
957            typinput_oid: 750,
958            typreceive_oid: 2400,
959        }),
960    },
961};
962
963pub const TYPE_JSONB: BuiltinType<NameReference> = BuiltinType {
964    name: "jsonb",
965    schema: PG_CATALOG_SCHEMA,
966    oid: oid::TYPE_JSONB_OID,
967    details: CatalogTypeDetails {
968        typ: CatalogType::Jsonb,
969        array_id: None,
970        pg_metadata: Some(CatalogTypePgMetadata {
971            typinput_oid: 3806,
972            typreceive_oid: 3805,
973        }),
974    },
975};
976
977pub const TYPE_JSONB_ARRAY: BuiltinType<NameReference> = BuiltinType {
978    name: "_jsonb",
979    schema: PG_CATALOG_SCHEMA,
980    oid: oid::TYPE_JSONB_ARRAY_OID,
981    details: CatalogTypeDetails {
982        typ: CatalogType::Array {
983            element_reference: TYPE_JSONB.name,
984        },
985        array_id: None,
986        pg_metadata: Some(CatalogTypePgMetadata {
987            typinput_oid: 750,
988            typreceive_oid: 2400,
989        }),
990    },
991};
992
993pub const TYPE_ANY: BuiltinType<NameReference> = BuiltinType {
994    name: "any",
995    schema: PG_CATALOG_SCHEMA,
996    oid: oid::TYPE_ANY_OID,
997    details: CatalogTypeDetails {
998        typ: CatalogType::Pseudo,
999        array_id: None,
1000        pg_metadata: Some(CatalogTypePgMetadata {
1001            typinput_oid: 2294,
1002            typreceive_oid: 0,
1003        }),
1004    },
1005};
1006
1007pub const TYPE_ANYARRAY: BuiltinType<NameReference> = BuiltinType {
1008    name: "anyarray",
1009    schema: PG_CATALOG_SCHEMA,
1010    oid: oid::TYPE_ANYARRAY_OID,
1011    details: CatalogTypeDetails {
1012        typ: CatalogType::Pseudo,
1013        array_id: None,
1014        pg_metadata: Some(CatalogTypePgMetadata {
1015            typinput_oid: 2296,
1016            typreceive_oid: 2502,
1017        }),
1018    },
1019};
1020
1021pub const TYPE_ANYELEMENT: BuiltinType<NameReference> = BuiltinType {
1022    name: "anyelement",
1023    schema: PG_CATALOG_SCHEMA,
1024    oid: oid::TYPE_ANYELEMENT_OID,
1025    details: CatalogTypeDetails {
1026        typ: CatalogType::Pseudo,
1027        array_id: None,
1028        pg_metadata: Some(CatalogTypePgMetadata {
1029            typinput_oid: 2312,
1030            typreceive_oid: 0,
1031        }),
1032    },
1033};
1034
1035pub const TYPE_ANYNONARRAY: BuiltinType<NameReference> = BuiltinType {
1036    name: "anynonarray",
1037    schema: PG_CATALOG_SCHEMA,
1038    oid: oid::TYPE_ANYNONARRAY_OID,
1039    details: CatalogTypeDetails {
1040        typ: CatalogType::Pseudo,
1041        array_id: None,
1042        pg_metadata: Some(CatalogTypePgMetadata {
1043            typinput_oid: 2777,
1044            typreceive_oid: 0,
1045        }),
1046    },
1047};
1048
1049pub const TYPE_ANYRANGE: BuiltinType<NameReference> = BuiltinType {
1050    name: "anyrange",
1051    schema: PG_CATALOG_SCHEMA,
1052    oid: oid::TYPE_ANYRANGE_OID,
1053    details: CatalogTypeDetails {
1054        typ: CatalogType::Pseudo,
1055        array_id: None,
1056        pg_metadata: Some(CatalogTypePgMetadata {
1057            typinput_oid: 3832,
1058            typreceive_oid: 0,
1059        }),
1060    },
1061};
1062
1063pub const TYPE_CHAR: BuiltinType<NameReference> = BuiltinType {
1064    name: "char",
1065    schema: PG_CATALOG_SCHEMA,
1066    oid: oid::TYPE_CHAR_OID,
1067    details: CatalogTypeDetails {
1068        typ: CatalogType::PgLegacyChar,
1069        array_id: None,
1070        pg_metadata: Some(CatalogTypePgMetadata {
1071            typinput_oid: 1245,
1072            typreceive_oid: 2434,
1073        }),
1074    },
1075};
1076
1077pub const TYPE_VARCHAR: BuiltinType<NameReference> = BuiltinType {
1078    name: "varchar",
1079    schema: PG_CATALOG_SCHEMA,
1080    oid: oid::TYPE_VARCHAR_OID,
1081    details: CatalogTypeDetails {
1082        typ: CatalogType::VarChar,
1083        array_id: None,
1084        pg_metadata: Some(CatalogTypePgMetadata {
1085            typinput_oid: 1046,
1086            typreceive_oid: 2432,
1087        }),
1088    },
1089};
1090
1091pub const TYPE_INT2: BuiltinType<NameReference> = BuiltinType {
1092    name: "int2",
1093    schema: PG_CATALOG_SCHEMA,
1094    oid: oid::TYPE_INT2_OID,
1095    details: CatalogTypeDetails {
1096        typ: CatalogType::Int16,
1097        array_id: None,
1098        pg_metadata: Some(CatalogTypePgMetadata {
1099            typinput_oid: 38,
1100            typreceive_oid: 2404,
1101        }),
1102    },
1103};
1104
1105pub const TYPE_INT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1106    name: "_int2",
1107    schema: PG_CATALOG_SCHEMA,
1108    oid: oid::TYPE_INT2_ARRAY_OID,
1109    details: CatalogTypeDetails {
1110        typ: CatalogType::Array {
1111            element_reference: TYPE_INT2.name,
1112        },
1113        array_id: None,
1114        pg_metadata: Some(CatalogTypePgMetadata {
1115            typinput_oid: 750,
1116            typreceive_oid: 2400,
1117        }),
1118    },
1119};
1120
1121pub const TYPE_BPCHAR: BuiltinType<NameReference> = BuiltinType {
1122    name: "bpchar",
1123    schema: PG_CATALOG_SCHEMA,
1124    oid: oid::TYPE_BPCHAR_OID,
1125    details: CatalogTypeDetails {
1126        typ: CatalogType::Char,
1127        array_id: None,
1128        pg_metadata: Some(CatalogTypePgMetadata {
1129            typinput_oid: 1044,
1130            typreceive_oid: 2430,
1131        }),
1132    },
1133};
1134
1135pub const TYPE_CHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1136    name: "_char",
1137    schema: PG_CATALOG_SCHEMA,
1138    oid: oid::TYPE_CHAR_ARRAY_OID,
1139    details: CatalogTypeDetails {
1140        typ: CatalogType::Array {
1141            element_reference: TYPE_CHAR.name,
1142        },
1143        array_id: None,
1144        pg_metadata: Some(CatalogTypePgMetadata {
1145            typinput_oid: 750,
1146            typreceive_oid: 2400,
1147        }),
1148    },
1149};
1150
1151pub const TYPE_VARCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1152    name: "_varchar",
1153    schema: PG_CATALOG_SCHEMA,
1154    oid: oid::TYPE_VARCHAR_ARRAY_OID,
1155    details: CatalogTypeDetails {
1156        typ: CatalogType::Array {
1157            element_reference: TYPE_VARCHAR.name,
1158        },
1159        array_id: None,
1160        pg_metadata: Some(CatalogTypePgMetadata {
1161            typinput_oid: 750,
1162            typreceive_oid: 2400,
1163        }),
1164    },
1165};
1166
1167pub const TYPE_BPCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1168    name: "_bpchar",
1169    schema: PG_CATALOG_SCHEMA,
1170    oid: oid::TYPE_BPCHAR_ARRAY_OID,
1171    details: CatalogTypeDetails {
1172        typ: CatalogType::Array {
1173            element_reference: TYPE_BPCHAR.name,
1174        },
1175        array_id: None,
1176        pg_metadata: Some(CatalogTypePgMetadata {
1177            typinput_oid: 750,
1178            typreceive_oid: 2400,
1179        }),
1180    },
1181};
1182
1183pub const TYPE_REGPROC: BuiltinType<NameReference> = BuiltinType {
1184    name: "regproc",
1185    schema: PG_CATALOG_SCHEMA,
1186    oid: oid::TYPE_REGPROC_OID,
1187    details: CatalogTypeDetails {
1188        typ: CatalogType::RegProc,
1189        array_id: None,
1190        pg_metadata: Some(CatalogTypePgMetadata {
1191            typinput_oid: 44,
1192            typreceive_oid: 2444,
1193        }),
1194    },
1195};
1196
1197pub const TYPE_REGPROC_ARRAY: BuiltinType<NameReference> = BuiltinType {
1198    name: "_regproc",
1199    schema: PG_CATALOG_SCHEMA,
1200    oid: oid::TYPE_REGPROC_ARRAY_OID,
1201    details: CatalogTypeDetails {
1202        typ: CatalogType::Array {
1203            element_reference: TYPE_REGPROC.name,
1204        },
1205        array_id: None,
1206        pg_metadata: Some(CatalogTypePgMetadata {
1207            typinput_oid: 750,
1208            typreceive_oid: 2400,
1209        }),
1210    },
1211};
1212
1213pub const TYPE_REGTYPE: BuiltinType<NameReference> = BuiltinType {
1214    name: "regtype",
1215    schema: PG_CATALOG_SCHEMA,
1216    oid: oid::TYPE_REGTYPE_OID,
1217    details: CatalogTypeDetails {
1218        typ: CatalogType::RegType,
1219        array_id: None,
1220        pg_metadata: Some(CatalogTypePgMetadata {
1221            typinput_oid: 2220,
1222            typreceive_oid: 2454,
1223        }),
1224    },
1225};
1226
1227pub const TYPE_REGTYPE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1228    name: "_regtype",
1229    schema: PG_CATALOG_SCHEMA,
1230    oid: oid::TYPE_REGTYPE_ARRAY_OID,
1231    details: CatalogTypeDetails {
1232        typ: CatalogType::Array {
1233            element_reference: TYPE_REGTYPE.name,
1234        },
1235        array_id: None,
1236        pg_metadata: Some(CatalogTypePgMetadata {
1237            typinput_oid: 750,
1238            typreceive_oid: 2400,
1239        }),
1240    },
1241};
1242
1243pub const TYPE_REGCLASS: BuiltinType<NameReference> = BuiltinType {
1244    name: "regclass",
1245    schema: PG_CATALOG_SCHEMA,
1246    oid: oid::TYPE_REGCLASS_OID,
1247    details: CatalogTypeDetails {
1248        typ: CatalogType::RegClass,
1249        array_id: None,
1250        pg_metadata: Some(CatalogTypePgMetadata {
1251            typinput_oid: 2218,
1252            typreceive_oid: 2452,
1253        }),
1254    },
1255};
1256
1257pub const TYPE_REGCLASS_ARRAY: BuiltinType<NameReference> = BuiltinType {
1258    name: "_regclass",
1259    schema: PG_CATALOG_SCHEMA,
1260    oid: oid::TYPE_REGCLASS_ARRAY_OID,
1261    details: CatalogTypeDetails {
1262        typ: CatalogType::Array {
1263            element_reference: TYPE_REGCLASS.name,
1264        },
1265        array_id: None,
1266        pg_metadata: Some(CatalogTypePgMetadata {
1267            typinput_oid: 750,
1268            typreceive_oid: 2400,
1269        }),
1270    },
1271};
1272
1273pub const TYPE_INT2_VECTOR: BuiltinType<NameReference> = BuiltinType {
1274    name: "int2vector",
1275    schema: PG_CATALOG_SCHEMA,
1276    oid: oid::TYPE_INT2_VECTOR_OID,
1277    details: CatalogTypeDetails {
1278        typ: CatalogType::Int2Vector,
1279        array_id: None,
1280        pg_metadata: Some(CatalogTypePgMetadata {
1281            typinput_oid: 40,
1282            typreceive_oid: 2410,
1283        }),
1284    },
1285};
1286
1287pub const TYPE_INT2_VECTOR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1288    name: "_int2vector",
1289    schema: PG_CATALOG_SCHEMA,
1290    oid: oid::TYPE_INT2_VECTOR_ARRAY_OID,
1291    details: CatalogTypeDetails {
1292        typ: CatalogType::Array {
1293            element_reference: TYPE_INT2_VECTOR.name,
1294        },
1295        array_id: None,
1296        pg_metadata: Some(CatalogTypePgMetadata {
1297            typinput_oid: 750,
1298            typreceive_oid: 2400,
1299        }),
1300    },
1301};
1302
1303pub const TYPE_ANYCOMPATIBLE: BuiltinType<NameReference> = BuiltinType {
1304    name: "anycompatible",
1305    schema: PG_CATALOG_SCHEMA,
1306    oid: oid::TYPE_ANYCOMPATIBLE_OID,
1307    details: CatalogTypeDetails {
1308        typ: CatalogType::Pseudo,
1309        array_id: None,
1310        pg_metadata: Some(CatalogTypePgMetadata {
1311            typinput_oid: 5086,
1312            typreceive_oid: 0,
1313        }),
1314    },
1315};
1316
1317pub const TYPE_ANYCOMPATIBLEARRAY: BuiltinType<NameReference> = BuiltinType {
1318    name: "anycompatiblearray",
1319    schema: PG_CATALOG_SCHEMA,
1320    oid: oid::TYPE_ANYCOMPATIBLEARRAY_OID,
1321    details: CatalogTypeDetails {
1322        typ: CatalogType::Pseudo,
1323        array_id: None,
1324        pg_metadata: Some(CatalogTypePgMetadata {
1325            typinput_oid: 5088,
1326            typreceive_oid: 5090,
1327        }),
1328    },
1329};
1330
1331pub const TYPE_ANYCOMPATIBLENONARRAY: BuiltinType<NameReference> = BuiltinType {
1332    name: "anycompatiblenonarray",
1333    schema: PG_CATALOG_SCHEMA,
1334    oid: oid::TYPE_ANYCOMPATIBLENONARRAY_OID,
1335    details: CatalogTypeDetails {
1336        typ: CatalogType::Pseudo,
1337        array_id: None,
1338        pg_metadata: Some(CatalogTypePgMetadata {
1339            typinput_oid: 5092,
1340            typreceive_oid: 0,
1341        }),
1342    },
1343};
1344
1345pub const TYPE_ANYCOMPATIBLERANGE: BuiltinType<NameReference> = BuiltinType {
1346    name: "anycompatiblerange",
1347    schema: PG_CATALOG_SCHEMA,
1348    oid: oid::TYPE_ANYCOMPATIBLERANGE_OID,
1349    details: CatalogTypeDetails {
1350        typ: CatalogType::Pseudo,
1351        array_id: None,
1352        pg_metadata: Some(CatalogTypePgMetadata {
1353            typinput_oid: 5094,
1354            typreceive_oid: 0,
1355        }),
1356    },
1357};
1358
1359pub const TYPE_LIST: BuiltinType<NameReference> = BuiltinType {
1360    name: "list",
1361    schema: MZ_CATALOG_SCHEMA,
1362    oid: mz_pgrepr::oid::TYPE_LIST_OID,
1363    details: CatalogTypeDetails {
1364        typ: CatalogType::Pseudo,
1365        array_id: None,
1366        pg_metadata: None,
1367    },
1368};
1369
1370pub const TYPE_MAP: BuiltinType<NameReference> = BuiltinType {
1371    name: "map",
1372    schema: MZ_CATALOG_SCHEMA,
1373    oid: mz_pgrepr::oid::TYPE_MAP_OID,
1374    details: CatalogTypeDetails {
1375        typ: CatalogType::Pseudo,
1376        array_id: None,
1377        pg_metadata: None,
1378    },
1379};
1380
1381pub const TYPE_ANYCOMPATIBLELIST: BuiltinType<NameReference> = BuiltinType {
1382    name: "anycompatiblelist",
1383    schema: MZ_CATALOG_SCHEMA,
1384    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLELIST_OID,
1385    details: CatalogTypeDetails {
1386        typ: CatalogType::Pseudo,
1387        array_id: None,
1388        pg_metadata: None,
1389    },
1390};
1391
1392pub const TYPE_ANYCOMPATIBLEMAP: BuiltinType<NameReference> = BuiltinType {
1393    name: "anycompatiblemap",
1394    schema: MZ_CATALOG_SCHEMA,
1395    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLEMAP_OID,
1396    details: CatalogTypeDetails {
1397        typ: CatalogType::Pseudo,
1398        array_id: None,
1399        pg_metadata: None,
1400    },
1401};
1402
1403pub const TYPE_UINT2: BuiltinType<NameReference> = BuiltinType {
1404    name: "uint2",
1405    schema: MZ_CATALOG_SCHEMA,
1406    oid: mz_pgrepr::oid::TYPE_UINT2_OID,
1407    details: CatalogTypeDetails {
1408        typ: CatalogType::UInt16,
1409        array_id: None,
1410        pg_metadata: None,
1411    },
1412};
1413
1414pub const TYPE_UINT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1415    name: "_uint2",
1416    schema: MZ_CATALOG_SCHEMA,
1417    oid: mz_pgrepr::oid::TYPE_UINT2_ARRAY_OID,
1418    details: CatalogTypeDetails {
1419        typ: CatalogType::Array {
1420            element_reference: TYPE_UINT2.name,
1421        },
1422        array_id: None,
1423        pg_metadata: None,
1424    },
1425};
1426
1427pub const TYPE_UINT4: BuiltinType<NameReference> = BuiltinType {
1428    name: "uint4",
1429    schema: MZ_CATALOG_SCHEMA,
1430    oid: mz_pgrepr::oid::TYPE_UINT4_OID,
1431    details: CatalogTypeDetails {
1432        typ: CatalogType::UInt32,
1433        array_id: None,
1434        pg_metadata: None,
1435    },
1436};
1437
1438pub const TYPE_UINT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
1439    name: "_uint4",
1440    schema: MZ_CATALOG_SCHEMA,
1441    oid: mz_pgrepr::oid::TYPE_UINT4_ARRAY_OID,
1442    details: CatalogTypeDetails {
1443        typ: CatalogType::Array {
1444            element_reference: TYPE_UINT4.name,
1445        },
1446        array_id: None,
1447        pg_metadata: None,
1448    },
1449};
1450
1451pub const TYPE_UINT8: BuiltinType<NameReference> = BuiltinType {
1452    name: "uint8",
1453    schema: MZ_CATALOG_SCHEMA,
1454    oid: mz_pgrepr::oid::TYPE_UINT8_OID,
1455    details: CatalogTypeDetails {
1456        typ: CatalogType::UInt64,
1457        array_id: None,
1458        pg_metadata: None,
1459    },
1460};
1461
1462pub const TYPE_UINT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
1463    name: "_uint8",
1464    schema: MZ_CATALOG_SCHEMA,
1465    oid: mz_pgrepr::oid::TYPE_UINT8_ARRAY_OID,
1466    details: CatalogTypeDetails {
1467        typ: CatalogType::Array {
1468            element_reference: TYPE_UINT8.name,
1469        },
1470        array_id: None,
1471        pg_metadata: None,
1472    },
1473};
1474
1475pub const TYPE_MZ_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
1476    name: "mz_timestamp",
1477    schema: MZ_CATALOG_SCHEMA,
1478    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_OID,
1479    details: CatalogTypeDetails {
1480        typ: CatalogType::MzTimestamp,
1481        array_id: None,
1482        pg_metadata: None,
1483    },
1484};
1485
1486pub const TYPE_MZ_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
1487    name: "_mz_timestamp",
1488    schema: MZ_CATALOG_SCHEMA,
1489    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_ARRAY_OID,
1490    details: CatalogTypeDetails {
1491        typ: CatalogType::Array {
1492            element_reference: TYPE_MZ_TIMESTAMP.name,
1493        },
1494        array_id: None,
1495        pg_metadata: None,
1496    },
1497};
1498
1499pub const TYPE_INT4_RANGE: BuiltinType<NameReference> = BuiltinType {
1500    name: "int4range",
1501    schema: PG_CATALOG_SCHEMA,
1502    oid: mz_pgrepr::oid::TYPE_INT4RANGE_OID,
1503    details: CatalogTypeDetails {
1504        typ: CatalogType::Range {
1505            element_reference: TYPE_INT4.name,
1506        },
1507        array_id: None,
1508        pg_metadata: Some(CatalogTypePgMetadata {
1509            typinput_oid: 3834,
1510            typreceive_oid: 3836,
1511        }),
1512    },
1513};
1514
1515pub const TYPE_INT4_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1516    name: "_int4range",
1517    schema: PG_CATALOG_SCHEMA,
1518    oid: mz_pgrepr::oid::TYPE_INT4RANGE_ARRAY_OID,
1519    details: CatalogTypeDetails {
1520        typ: CatalogType::Array {
1521            element_reference: TYPE_INT4_RANGE.name,
1522        },
1523        array_id: None,
1524        pg_metadata: Some(CatalogTypePgMetadata {
1525            typinput_oid: 750,
1526            typreceive_oid: 2400,
1527        }),
1528    },
1529};
1530
1531pub const TYPE_INT8_RANGE: BuiltinType<NameReference> = BuiltinType {
1532    name: "int8range",
1533    schema: PG_CATALOG_SCHEMA,
1534    oid: mz_pgrepr::oid::TYPE_INT8RANGE_OID,
1535    details: CatalogTypeDetails {
1536        typ: CatalogType::Range {
1537            element_reference: TYPE_INT8.name,
1538        },
1539        array_id: None,
1540        pg_metadata: Some(CatalogTypePgMetadata {
1541            typinput_oid: 3834,
1542            typreceive_oid: 3836,
1543        }),
1544    },
1545};
1546
1547pub const TYPE_INT8_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1548    name: "_int8range",
1549    schema: PG_CATALOG_SCHEMA,
1550    oid: mz_pgrepr::oid::TYPE_INT8RANGE_ARRAY_OID,
1551    details: CatalogTypeDetails {
1552        typ: CatalogType::Array {
1553            element_reference: TYPE_INT8_RANGE.name,
1554        },
1555        array_id: None,
1556        pg_metadata: Some(CatalogTypePgMetadata {
1557            typinput_oid: 750,
1558            typreceive_oid: 2400,
1559        }),
1560    },
1561};
1562
1563pub const TYPE_DATE_RANGE: BuiltinType<NameReference> = BuiltinType {
1564    name: "daterange",
1565    schema: PG_CATALOG_SCHEMA,
1566    oid: mz_pgrepr::oid::TYPE_DATERANGE_OID,
1567    details: CatalogTypeDetails {
1568        typ: CatalogType::Range {
1569            element_reference: TYPE_DATE.name,
1570        },
1571        array_id: None,
1572        pg_metadata: Some(CatalogTypePgMetadata {
1573            typinput_oid: 3834,
1574            typreceive_oid: 3836,
1575        }),
1576    },
1577};
1578
1579pub const TYPE_DATE_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1580    name: "_daterange",
1581    schema: PG_CATALOG_SCHEMA,
1582    oid: mz_pgrepr::oid::TYPE_DATERANGE_ARRAY_OID,
1583    details: CatalogTypeDetails {
1584        typ: CatalogType::Array {
1585            element_reference: TYPE_DATE_RANGE.name,
1586        },
1587        array_id: None,
1588        pg_metadata: Some(CatalogTypePgMetadata {
1589            typinput_oid: 750,
1590            typreceive_oid: 2400,
1591        }),
1592    },
1593};
1594
1595pub const TYPE_NUM_RANGE: BuiltinType<NameReference> = BuiltinType {
1596    name: "numrange",
1597    schema: PG_CATALOG_SCHEMA,
1598    oid: mz_pgrepr::oid::TYPE_NUMRANGE_OID,
1599    details: CatalogTypeDetails {
1600        typ: CatalogType::Range {
1601            element_reference: TYPE_NUMERIC.name,
1602        },
1603        array_id: None,
1604        pg_metadata: Some(CatalogTypePgMetadata {
1605            typinput_oid: 3834,
1606            typreceive_oid: 3836,
1607        }),
1608    },
1609};
1610
1611pub const TYPE_NUM_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1612    name: "_numrange",
1613    schema: PG_CATALOG_SCHEMA,
1614    oid: mz_pgrepr::oid::TYPE_NUMRANGE_ARRAY_OID,
1615    details: CatalogTypeDetails {
1616        typ: CatalogType::Array {
1617            element_reference: TYPE_NUM_RANGE.name,
1618        },
1619        array_id: None,
1620        pg_metadata: Some(CatalogTypePgMetadata {
1621            typinput_oid: 750,
1622            typreceive_oid: 2400,
1623        }),
1624    },
1625};
1626
1627pub const TYPE_TS_RANGE: BuiltinType<NameReference> = BuiltinType {
1628    name: "tsrange",
1629    schema: PG_CATALOG_SCHEMA,
1630    oid: mz_pgrepr::oid::TYPE_TSRANGE_OID,
1631    details: CatalogTypeDetails {
1632        typ: CatalogType::Range {
1633            element_reference: TYPE_TIMESTAMP.name,
1634        },
1635        array_id: None,
1636        pg_metadata: Some(CatalogTypePgMetadata {
1637            typinput_oid: 3834,
1638            typreceive_oid: 3836,
1639        }),
1640    },
1641};
1642
1643pub const TYPE_TS_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1644    name: "_tsrange",
1645    schema: PG_CATALOG_SCHEMA,
1646    oid: mz_pgrepr::oid::TYPE_TSRANGE_ARRAY_OID,
1647    details: CatalogTypeDetails {
1648        typ: CatalogType::Array {
1649            element_reference: TYPE_TS_RANGE.name,
1650        },
1651        array_id: None,
1652        pg_metadata: Some(CatalogTypePgMetadata {
1653            typinput_oid: 750,
1654            typreceive_oid: 2400,
1655        }),
1656    },
1657};
1658
1659pub const TYPE_TSTZ_RANGE: BuiltinType<NameReference> = BuiltinType {
1660    name: "tstzrange",
1661    schema: PG_CATALOG_SCHEMA,
1662    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_OID,
1663    details: CatalogTypeDetails {
1664        typ: CatalogType::Range {
1665            element_reference: TYPE_TIMESTAMPTZ.name,
1666        },
1667        array_id: None,
1668        pg_metadata: Some(CatalogTypePgMetadata {
1669            typinput_oid: 3834,
1670            typreceive_oid: 3836,
1671        }),
1672    },
1673};
1674
1675pub const TYPE_TSTZ_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1676    name: "_tstzrange",
1677    schema: PG_CATALOG_SCHEMA,
1678    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_ARRAY_OID,
1679    details: CatalogTypeDetails {
1680        typ: CatalogType::Array {
1681            element_reference: TYPE_TSTZ_RANGE.name,
1682        },
1683        array_id: None,
1684        pg_metadata: Some(CatalogTypePgMetadata {
1685            typinput_oid: 750,
1686            typreceive_oid: 2400,
1687        }),
1688    },
1689};
1690
1691pub const TYPE_MZ_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1692    name: "mz_aclitem",
1693    schema: MZ_CATALOG_SCHEMA,
1694    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_OID,
1695    details: CatalogTypeDetails {
1696        typ: CatalogType::MzAclItem,
1697        array_id: None,
1698        pg_metadata: None,
1699    },
1700};
1701
1702pub const TYPE_MZ_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1703    name: "_mz_aclitem",
1704    schema: MZ_CATALOG_SCHEMA,
1705    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_ARRAY_OID,
1706    details: CatalogTypeDetails {
1707        typ: CatalogType::Array {
1708            element_reference: TYPE_MZ_ACL_ITEM.name,
1709        },
1710        array_id: None,
1711        pg_metadata: Some(CatalogTypePgMetadata {
1712            typinput_oid: 750,
1713            typreceive_oid: 2400,
1714        }),
1715    },
1716};
1717
1718pub const TYPE_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1719    name: "aclitem",
1720    schema: PG_CATALOG_SCHEMA,
1721    oid: 1033,
1722    details: CatalogTypeDetails {
1723        typ: CatalogType::AclItem,
1724        array_id: None,
1725        pg_metadata: Some(CatalogTypePgMetadata {
1726            typinput_oid: 1031,
1727            typreceive_oid: 0,
1728        }),
1729    },
1730};
1731
1732pub const TYPE_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1733    name: "_aclitem",
1734    schema: PG_CATALOG_SCHEMA,
1735    oid: 1034,
1736    details: CatalogTypeDetails {
1737        typ: CatalogType::Array {
1738            element_reference: TYPE_ACL_ITEM.name,
1739        },
1740        array_id: None,
1741        pg_metadata: Some(CatalogTypePgMetadata {
1742            typinput_oid: 750,
1743            typreceive_oid: 2400,
1744        }),
1745    },
1746};
1747
1748pub const TYPE_INTERNAL: BuiltinType<NameReference> = BuiltinType {
1749    name: "internal",
1750    schema: PG_CATALOG_SCHEMA,
1751    oid: 2281,
1752    details: CatalogTypeDetails {
1753        typ: CatalogType::Pseudo,
1754        array_id: None,
1755        pg_metadata: Some(CatalogTypePgMetadata {
1756            typinput_oid: 2304,
1757            typreceive_oid: 0,
1758        }),
1759    },
1760};
1761
1762const PUBLIC_SELECT: MzAclItem = MzAclItem {
1763    grantee: RoleId::Public,
1764    grantor: MZ_SYSTEM_ROLE_ID,
1765    acl_mode: AclMode::SELECT,
1766};
1767
1768const SUPPORT_SELECT: MzAclItem = MzAclItem {
1769    grantee: MZ_SUPPORT_ROLE_ID,
1770    grantor: MZ_SYSTEM_ROLE_ID,
1771    acl_mode: AclMode::SELECT,
1772};
1773
1774const ANALYTICS_SELECT: MzAclItem = MzAclItem {
1775    grantee: MZ_ANALYTICS_ROLE_ID,
1776    grantor: MZ_SYSTEM_ROLE_ID,
1777    acl_mode: AclMode::SELECT,
1778};
1779
1780const MONITOR_SELECT: MzAclItem = MzAclItem {
1781    grantee: MZ_MONITOR_ROLE_ID,
1782    grantor: MZ_SYSTEM_ROLE_ID,
1783    acl_mode: AclMode::SELECT,
1784};
1785
1786const MONITOR_REDACTED_SELECT: MzAclItem = MzAclItem {
1787    grantee: MZ_MONITOR_REDACTED_ROLE_ID,
1788    grantor: MZ_SYSTEM_ROLE_ID,
1789    acl_mode: AclMode::SELECT,
1790};
1791
1792pub static MZ_CATALOG_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
1793    name: "mz_catalog_raw",
1794    schema: MZ_INTERNAL_SCHEMA,
1795    oid: oid::SOURCE_MZ_CATALOG_RAW_OID,
1796    data_source: DataSourceDesc::Catalog,
1797    desc: crate::durable::persist_desc(),
1798    column_comments: BTreeMap::new(),
1799    is_retained_metrics_object: false,
1800    // The raw catalog contains unredacted SQL statements, so we limit access to the system user.
1801    access: vec![],
1802});
1803
1804pub static MZ_CATALOG_RAW_DESCRIPTION: LazyLock<SystemObjectDescription> =
1805    LazyLock::new(|| SystemObjectDescription {
1806        schema_name: MZ_CATALOG_RAW.schema.to_string(),
1807        object_type: CatalogItemType::Source,
1808        object_name: MZ_CATALOG_RAW.name.to_string(),
1809    });
1810
1811pub static MZ_DATAFLOW_OPERATORS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1812    name: "mz_dataflow_operators_per_worker",
1813    schema: MZ_INTROSPECTION_SCHEMA,
1814    oid: oid::LOG_MZ_DATAFLOW_OPERATORS_PER_WORKER_OID,
1815    variant: LogVariant::Timely(TimelyLog::Operates),
1816    access: vec![PUBLIC_SELECT],
1817});
1818
1819pub static MZ_DATAFLOW_ADDRESSES_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1820    name: "mz_dataflow_addresses_per_worker",
1821    schema: MZ_INTROSPECTION_SCHEMA,
1822    oid: oid::LOG_MZ_DATAFLOW_ADDRESSES_PER_WORKER_OID,
1823    variant: LogVariant::Timely(TimelyLog::Addresses),
1824    access: vec![PUBLIC_SELECT],
1825});
1826
1827pub static MZ_DATAFLOW_CHANNELS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1828    name: "mz_dataflow_channels_per_worker",
1829    schema: MZ_INTROSPECTION_SCHEMA,
1830    oid: oid::LOG_MZ_DATAFLOW_CHANNELS_PER_WORKER_OID,
1831    variant: LogVariant::Timely(TimelyLog::Channels),
1832    access: vec![PUBLIC_SELECT],
1833});
1834
1835pub static MZ_SCHEDULING_ELAPSED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1836    name: "mz_scheduling_elapsed_raw",
1837    schema: MZ_INTROSPECTION_SCHEMA,
1838    oid: oid::LOG_MZ_SCHEDULING_ELAPSED_RAW_OID,
1839    variant: LogVariant::Timely(TimelyLog::Elapsed),
1840    access: vec![PUBLIC_SELECT],
1841});
1842
1843pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1844    LazyLock::new(|| BuiltinLog {
1845        name: "mz_compute_operator_durations_histogram_raw",
1846        schema: MZ_INTROSPECTION_SCHEMA,
1847        oid: oid::LOG_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW_OID,
1848        variant: LogVariant::Timely(TimelyLog::Histogram),
1849        access: vec![PUBLIC_SELECT],
1850    });
1851
1852pub static MZ_SCHEDULING_PARKS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1853    name: "mz_scheduling_parks_histogram_raw",
1854    schema: MZ_INTROSPECTION_SCHEMA,
1855    oid: oid::LOG_MZ_SCHEDULING_PARKS_HISTOGRAM_RAW_OID,
1856    variant: LogVariant::Timely(TimelyLog::Parks),
1857    access: vec![PUBLIC_SELECT],
1858});
1859
1860pub static MZ_ARRANGEMENT_RECORDS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1861    name: "mz_arrangement_records_raw",
1862    schema: MZ_INTROSPECTION_SCHEMA,
1863    oid: oid::LOG_MZ_ARRANGEMENT_RECORDS_RAW_OID,
1864    variant: LogVariant::Differential(DifferentialLog::ArrangementRecords),
1865    access: vec![PUBLIC_SELECT],
1866});
1867
1868pub static MZ_ARRANGEMENT_BATCHES_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1869    name: "mz_arrangement_batches_raw",
1870    schema: MZ_INTROSPECTION_SCHEMA,
1871    oid: oid::LOG_MZ_ARRANGEMENT_BATCHES_RAW_OID,
1872    variant: LogVariant::Differential(DifferentialLog::ArrangementBatches),
1873    access: vec![PUBLIC_SELECT],
1874});
1875
1876pub static MZ_ARRANGEMENT_SHARING_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1877    name: "mz_arrangement_sharing_raw",
1878    schema: MZ_INTROSPECTION_SCHEMA,
1879    oid: oid::LOG_MZ_ARRANGEMENT_SHARING_RAW_OID,
1880    variant: LogVariant::Differential(DifferentialLog::Sharing),
1881    access: vec![PUBLIC_SELECT],
1882});
1883
1884pub static MZ_ARRANGEMENT_BATCHER_RECORDS_RAW: LazyLock<BuiltinLog> =
1885    LazyLock::new(|| BuiltinLog {
1886        name: "mz_arrangement_batcher_records_raw",
1887        schema: MZ_INTROSPECTION_SCHEMA,
1888        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_RECORDS_RAW_OID,
1889        variant: LogVariant::Differential(DifferentialLog::BatcherRecords),
1890        access: vec![PUBLIC_SELECT],
1891    });
1892
1893pub static MZ_ARRANGEMENT_BATCHER_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1894    name: "mz_arrangement_batcher_size_raw",
1895    schema: MZ_INTROSPECTION_SCHEMA,
1896    oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_SIZE_RAW_OID,
1897    variant: LogVariant::Differential(DifferentialLog::BatcherSize),
1898    access: vec![PUBLIC_SELECT],
1899});
1900
1901pub static MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW: LazyLock<BuiltinLog> =
1902    LazyLock::new(|| BuiltinLog {
1903        name: "mz_arrangement_batcher_capacity_raw",
1904        schema: MZ_INTROSPECTION_SCHEMA,
1905        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW_OID,
1906        variant: LogVariant::Differential(DifferentialLog::BatcherCapacity),
1907        access: vec![PUBLIC_SELECT],
1908    });
1909
1910pub static MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1911    LazyLock::new(|| BuiltinLog {
1912        name: "mz_arrangement_batcher_allocations_raw",
1913        schema: MZ_INTROSPECTION_SCHEMA,
1914        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW_OID,
1915        variant: LogVariant::Differential(DifferentialLog::BatcherAllocations),
1916        access: vec![PUBLIC_SELECT],
1917    });
1918
1919pub static MZ_COMPUTE_EXPORTS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1920    name: "mz_compute_exports_per_worker",
1921    schema: MZ_INTROSPECTION_SCHEMA,
1922    oid: oid::LOG_MZ_COMPUTE_EXPORTS_PER_WORKER_OID,
1923    variant: LogVariant::Compute(ComputeLog::DataflowCurrent),
1924    access: vec![PUBLIC_SELECT],
1925});
1926
1927pub static MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER: LazyLock<BuiltinLog> =
1928    LazyLock::new(|| BuiltinLog {
1929        name: "mz_compute_dataflow_global_ids_per_worker",
1930        schema: MZ_INTROSPECTION_SCHEMA,
1931        oid: oid::LOG_MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER_OID,
1932        variant: LogVariant::Compute(ComputeLog::DataflowGlobal),
1933        access: vec![PUBLIC_SELECT],
1934    });
1935
1936pub static MZ_CLUSTER_PROMETHEUS_METRICS: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1937    name: "mz_cluster_prometheus_metrics",
1938    schema: MZ_INTROSPECTION_SCHEMA,
1939    oid: oid::LOG_MZ_CLUSTER_PROMETHEUS_METRICS_OID,
1940    variant: LogVariant::Compute(ComputeLog::PrometheusMetrics),
1941    access: vec![PUBLIC_SELECT],
1942});
1943
1944pub static MZ_COMPUTE_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1945    name: "mz_compute_frontiers_per_worker",
1946    schema: MZ_INTROSPECTION_SCHEMA,
1947    oid: oid::LOG_MZ_COMPUTE_FRONTIERS_PER_WORKER_OID,
1948    variant: LogVariant::Compute(ComputeLog::FrontierCurrent),
1949    access: vec![PUBLIC_SELECT],
1950});
1951
1952pub static MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> =
1953    LazyLock::new(|| BuiltinLog {
1954        name: "mz_compute_import_frontiers_per_worker",
1955        schema: MZ_INTROSPECTION_SCHEMA,
1956        oid: oid::LOG_MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER_OID,
1957        variant: LogVariant::Compute(ComputeLog::ImportFrontierCurrent),
1958        access: vec![PUBLIC_SELECT],
1959    });
1960
1961pub static MZ_COMPUTE_ERROR_COUNTS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1962    name: "mz_compute_error_counts_raw",
1963    schema: MZ_INTROSPECTION_SCHEMA,
1964    oid: oid::LOG_MZ_COMPUTE_ERROR_COUNTS_RAW_OID,
1965    variant: LogVariant::Compute(ComputeLog::ErrorCount),
1966    access: vec![PUBLIC_SELECT],
1967});
1968
1969pub static MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER: LazyLock<BuiltinLog> =
1970    LazyLock::new(|| BuiltinLog {
1971        name: "mz_compute_hydration_times_per_worker",
1972        schema: MZ_INTROSPECTION_SCHEMA,
1973        oid: oid::LOG_MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER_OID,
1974        variant: LogVariant::Compute(ComputeLog::HydrationTime),
1975        access: vec![PUBLIC_SELECT],
1976    });
1977
1978pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER: LazyLock<BuiltinLog> =
1979    LazyLock::new(|| BuiltinLog {
1980        name: "mz_compute_operator_hydration_statuses_per_worker",
1981        schema: MZ_INTROSPECTION_SCHEMA,
1982        oid: oid::LOG_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER_OID,
1983        variant: LogVariant::Compute(ComputeLog::OperatorHydrationStatus),
1984        access: vec![PUBLIC_SELECT],
1985    });
1986
1987pub static MZ_ACTIVE_PEEKS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1988    name: "mz_active_peeks_per_worker",
1989    schema: MZ_INTROSPECTION_SCHEMA,
1990    oid: oid::LOG_MZ_ACTIVE_PEEKS_PER_WORKER_OID,
1991    variant: LogVariant::Compute(ComputeLog::PeekCurrent),
1992    access: vec![PUBLIC_SELECT],
1993});
1994
1995pub static MZ_COMPUTE_LIR_MAPPING_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1996    name: "mz_compute_lir_mapping_per_worker",
1997    schema: MZ_INTROSPECTION_SCHEMA,
1998    oid: oid::LOG_MZ_COMPUTE_LIR_MAPPING_PER_WORKER_OID,
1999    variant: LogVariant::Compute(ComputeLog::LirMapping),
2000    access: vec![PUBLIC_SELECT],
2001});
2002
2003pub static MZ_PEEK_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2004    name: "mz_peek_durations_histogram_raw",
2005    schema: MZ_INTROSPECTION_SCHEMA,
2006    oid: oid::LOG_MZ_PEEK_DURATIONS_HISTOGRAM_RAW_OID,
2007    variant: LogVariant::Compute(ComputeLog::PeekDuration),
2008    access: vec![PUBLIC_SELECT],
2009});
2010
2011pub static MZ_ARRANGEMENT_HEAP_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2012    name: "mz_arrangement_heap_size_raw",
2013    schema: MZ_INTROSPECTION_SCHEMA,
2014    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_SIZE_RAW_OID,
2015    variant: LogVariant::Compute(ComputeLog::ArrangementHeapSize),
2016    access: vec![PUBLIC_SELECT],
2017});
2018
2019pub static MZ_ARRANGEMENT_HEAP_CAPACITY_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2020    name: "mz_arrangement_heap_capacity_raw",
2021    schema: MZ_INTROSPECTION_SCHEMA,
2022    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_CAPACITY_RAW_OID,
2023    variant: LogVariant::Compute(ComputeLog::ArrangementHeapCapacity),
2024    access: vec![PUBLIC_SELECT],
2025});
2026
2027pub static MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
2028    LazyLock::new(|| BuiltinLog {
2029        name: "mz_arrangement_heap_allocations_raw",
2030        schema: MZ_INTROSPECTION_SCHEMA,
2031        oid: oid::LOG_MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW_OID,
2032        variant: LogVariant::Compute(ComputeLog::ArrangementHeapAllocations),
2033        access: vec![PUBLIC_SELECT],
2034    });
2035
2036pub static MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> =
2037    LazyLock::new(|| BuiltinLog {
2038        name: "mz_message_batch_counts_received_raw",
2039        schema: MZ_INTROSPECTION_SCHEMA,
2040        oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW_OID,
2041        variant: LogVariant::Timely(TimelyLog::BatchesReceived),
2042        access: vec![PUBLIC_SELECT],
2043    });
2044
2045pub static MZ_MESSAGE_BATCH_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2046    name: "mz_message_batch_counts_sent_raw",
2047    schema: MZ_INTROSPECTION_SCHEMA,
2048    oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_SENT_RAW_OID,
2049    variant: LogVariant::Timely(TimelyLog::BatchesSent),
2050    access: vec![PUBLIC_SELECT],
2051});
2052
2053pub static MZ_MESSAGE_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2054    name: "mz_message_counts_received_raw",
2055    schema: MZ_INTROSPECTION_SCHEMA,
2056    oid: oid::LOG_MZ_MESSAGE_COUNTS_RECEIVED_RAW_OID,
2057    variant: LogVariant::Timely(TimelyLog::MessagesReceived),
2058    access: vec![PUBLIC_SELECT],
2059});
2060
2061pub static MZ_MESSAGE_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2062    name: "mz_message_counts_sent_raw",
2063    schema: MZ_INTROSPECTION_SCHEMA,
2064    oid: oid::LOG_MZ_MESSAGE_COUNTS_SENT_RAW_OID,
2065    variant: LogVariant::Timely(TimelyLog::MessagesSent),
2066    access: vec![PUBLIC_SELECT],
2067});
2068
2069pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW: LazyLock<BuiltinLog> =
2070    LazyLock::new(|| BuiltinLog {
2071        name: "mz_dataflow_operator_reachability_raw",
2072        schema: MZ_INTROSPECTION_SCHEMA,
2073        oid: oid::LOG_MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW_OID,
2074        variant: LogVariant::Timely(TimelyLog::Reachability),
2075        access: vec![PUBLIC_SELECT],
2076    });
2077
2078pub static MZ_ICEBERG_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2079    name: "mz_iceberg_sinks",
2080    schema: MZ_CATALOG_SCHEMA,
2081    oid: oid::TABLE_MZ_ICEBERG_SINKS_OID,
2082    desc: RelationDesc::builder()
2083        .with_column("id", SqlScalarType::String.nullable(false))
2084        .with_column("namespace", SqlScalarType::String.nullable(false))
2085        .with_column("table", SqlScalarType::String.nullable(false))
2086        .finish(),
2087    column_comments: BTreeMap::from_iter([
2088        ("id", "The ID of the sink."),
2089        (
2090            "namespace",
2091            "The namespace of the Iceberg table into which the sink is writing.",
2092        ),
2093        ("table", "The Iceberg table into which the sink is writing."),
2094    ]),
2095    is_retained_metrics_object: false,
2096    access: vec![PUBLIC_SELECT],
2097});
2098
2099pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2100    name: "mz_kafka_sinks",
2101    schema: MZ_CATALOG_SCHEMA,
2102    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2103    desc: RelationDesc::builder()
2104        .with_column("id", SqlScalarType::String.nullable(false))
2105        .with_column("topic", SqlScalarType::String.nullable(false))
2106        .with_key(vec![0])
2107        .finish(),
2108    column_comments: BTreeMap::from_iter([
2109        ("id", "The ID of the sink."),
2110        (
2111            "topic",
2112            "The name of the Kafka topic into which the sink is writing.",
2113        ),
2114    ]),
2115    is_retained_metrics_object: false,
2116    access: vec![PUBLIC_SELECT],
2117});
2118pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2119    name: "mz_kafka_connections",
2120    schema: MZ_CATALOG_SCHEMA,
2121    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2122    desc: RelationDesc::builder()
2123        .with_column("id", SqlScalarType::String.nullable(false))
2124        .with_column(
2125            "brokers",
2126            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2127        )
2128        .with_column("sink_progress_topic", SqlScalarType::String.nullable(false))
2129        .finish(),
2130    column_comments: BTreeMap::from_iter([
2131        ("id", "The ID of the connection."),
2132        (
2133            "brokers",
2134            "The addresses of the Kafka brokers to connect to.",
2135        ),
2136        (
2137            "sink_progress_topic",
2138            "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.",
2139        ),
2140    ]),
2141    is_retained_metrics_object: false,
2142    access: vec![PUBLIC_SELECT],
2143});
2144pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2145    name: "mz_kafka_sources",
2146    schema: MZ_CATALOG_SCHEMA,
2147    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2148    desc: RelationDesc::builder()
2149        .with_column("id", SqlScalarType::String.nullable(false))
2150        .with_column("group_id_prefix", SqlScalarType::String.nullable(false))
2151        .with_column("topic", SqlScalarType::String.nullable(false))
2152        .finish(),
2153    column_comments: BTreeMap::from_iter([
2154        (
2155            "id",
2156            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2157        ),
2158        (
2159            "group_id_prefix",
2160            "The value of the `GROUP ID PREFIX` connection option.",
2161        ),
2162        (
2163            "topic",
2164            "The name of the Kafka topic the source is reading from.",
2165        ),
2166    ]),
2167    is_retained_metrics_object: false,
2168    access: vec![PUBLIC_SELECT],
2169});
2170pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2171    name: "mz_postgres_sources",
2172    schema: MZ_INTERNAL_SCHEMA,
2173    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2174    desc: RelationDesc::builder()
2175        .with_column("id", SqlScalarType::String.nullable(false))
2176        .with_column("replication_slot", SqlScalarType::String.nullable(false))
2177        .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
2178        .finish(),
2179    column_comments: BTreeMap::from_iter([
2180        (
2181            "id",
2182            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2183        ),
2184        (
2185            "replication_slot",
2186            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2187        ),
2188        (
2189            "timeline_id",
2190            "The PostgreSQL timeline ID determined on source creation.",
2191        ),
2192    ]),
2193    is_retained_metrics_object: false,
2194    access: vec![PUBLIC_SELECT],
2195});
2196pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2197    name: "mz_postgres_source_tables",
2198    schema: MZ_INTERNAL_SCHEMA,
2199    oid: oid::TABLE_MZ_POSTGRES_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 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_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2223    name: "mz_mysql_source_tables",
2224    schema: MZ_INTERNAL_SCHEMA,
2225    oid: oid::TABLE_MZ_MYSQL_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 (or, database) 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_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2249    name: "mz_sql_server_source_tables",
2250    schema: MZ_INTERNAL_SCHEMA,
2251    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2252    desc: RelationDesc::builder()
2253        .with_column("id", SqlScalarType::String.nullable(false))
2254        .with_column("schema_name", SqlScalarType::String.nullable(false))
2255        .with_column("table_name", SqlScalarType::String.nullable(false))
2256        .finish(),
2257    column_comments: BTreeMap::from_iter([
2258        (
2259            "id",
2260            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2261        ),
2262        (
2263            "schema_name",
2264            "The schema of the upstream table being ingested.",
2265        ),
2266        (
2267            "table_name",
2268            "The name of the upstream table being ingested.",
2269        ),
2270    ]),
2271    is_retained_metrics_object: true,
2272    access: vec![PUBLIC_SELECT],
2273});
2274pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2275    name: "mz_kafka_source_tables",
2276    schema: MZ_INTERNAL_SCHEMA,
2277    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2278    desc: RelationDesc::builder()
2279        .with_column("id", SqlScalarType::String.nullable(false))
2280        .with_column("topic", SqlScalarType::String.nullable(false))
2281        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2282        .with_column("key_format", SqlScalarType::String.nullable(true))
2283        .with_column("value_format", SqlScalarType::String.nullable(true))
2284        .finish(),
2285    column_comments: BTreeMap::from_iter([
2286        (
2287            "id",
2288            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2289        ),
2290        ("topic", "The topic being ingested."),
2291        (
2292            "envelope_type",
2293            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2294        ),
2295        (
2296            "key_format",
2297            "The format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2298        ),
2299        (
2300            "value_format",
2301            "The format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2302        ),
2303    ]),
2304    is_retained_metrics_object: true,
2305    access: vec![PUBLIC_SELECT],
2306});
2307pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2308    name: "mz_object_dependencies",
2309    schema: MZ_INTERNAL_SCHEMA,
2310    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2311    desc: RelationDesc::builder()
2312        .with_column("object_id", SqlScalarType::String.nullable(false))
2313        .with_column(
2314            "referenced_object_id",
2315            SqlScalarType::String.nullable(false),
2316        )
2317        .finish(),
2318    column_comments: BTreeMap::from_iter([
2319        (
2320            "object_id",
2321            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2322        ),
2323        (
2324            "referenced_object_id",
2325            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2326        ),
2327    ]),
2328    is_retained_metrics_object: true,
2329    access: vec![PUBLIC_SELECT],
2330});
2331pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2332    name: "mz_compute_dependencies",
2333    schema: MZ_INTERNAL_SCHEMA,
2334    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2335    data_source: IntrospectionType::ComputeDependencies.into(),
2336    desc: RelationDesc::builder()
2337        .with_column("object_id", SqlScalarType::String.nullable(false))
2338        .with_column("dependency_id", SqlScalarType::String.nullable(false))
2339        .finish(),
2340    column_comments: BTreeMap::from_iter([
2341        (
2342            "object_id",
2343            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2344        ),
2345        (
2346            "dependency_id",
2347            "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`.",
2348        ),
2349    ]),
2350    is_retained_metrics_object: false,
2351    access: vec![PUBLIC_SELECT],
2352});
2353
2354pub static MZ_DATABASES: LazyLock<BuiltinMaterializedView> =
2355    LazyLock::new(|| BuiltinMaterializedView {
2356        name: "mz_databases",
2357        schema: MZ_CATALOG_SCHEMA,
2358        oid: oid::MV_MZ_DATABASES_OID,
2359        desc: RelationDesc::builder()
2360            .with_column("id", SqlScalarType::String.nullable(false))
2361            .with_column("oid", SqlScalarType::Oid.nullable(false))
2362            .with_column("name", SqlScalarType::String.nullable(false))
2363            .with_column("owner_id", SqlScalarType::String.nullable(false))
2364            .with_column(
2365                "privileges",
2366                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2367            )
2368            .with_key(vec![0])
2369            .with_key(vec![1])
2370            .finish(),
2371        column_comments: BTreeMap::from_iter([
2372            ("id", "Materialize's unique ID for the database."),
2373            ("oid", "A PostgreSQL-compatible OID for the database."),
2374            ("name", "The name of the database."),
2375            (
2376                "owner_id",
2377                "The role ID of the owner of the database. Corresponds to `mz_roles.id`.",
2378            ),
2379            ("privileges", "The privileges belonging to the database."),
2380        ]),
2381        sql: "
2382IN CLUSTER mz_catalog_server
2383WITH (
2384    ASSERT NOT NULL id,
2385    ASSERT NOT NULL oid,
2386    ASSERT NOT NULL name,
2387    ASSERT NOT NULL owner_id,
2388    ASSERT NOT NULL privileges
2389) AS
2390SELECT
2391    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
2392    (data->'value'->>'oid')::oid AS oid,
2393    data->'value'->>'name' AS name,
2394    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2395    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
2396FROM mz_internal.mz_catalog_raw
2397WHERE data->>'kind' = 'Database'",
2398        access: vec![PUBLIC_SELECT],
2399    });
2400
2401pub static MZ_SCHEMAS: LazyLock<BuiltinMaterializedView> =
2402    LazyLock::new(|| BuiltinMaterializedView {
2403        name: "mz_schemas",
2404        schema: MZ_CATALOG_SCHEMA,
2405        oid: oid::MV_MZ_SCHEMAS_OID,
2406        desc: RelationDesc::builder()
2407            .with_column("id", SqlScalarType::String.nullable(false))
2408            .with_column("oid", SqlScalarType::Oid.nullable(false))
2409            .with_column("database_id", SqlScalarType::String.nullable(true))
2410            .with_column("name", SqlScalarType::String.nullable(false))
2411            .with_column("owner_id", SqlScalarType::String.nullable(false))
2412            .with_column(
2413                "privileges",
2414                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2415            )
2416            .with_key(vec![0])
2417            .with_key(vec![1])
2418            .finish(),
2419        column_comments: BTreeMap::from_iter([
2420            ("id", "Materialize's unique ID for the schema."),
2421            ("oid", "A PostgreSQL-compatible oid for the schema."),
2422            (
2423                "database_id",
2424                "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2425            ),
2426            ("name", "The name of the schema."),
2427            (
2428                "owner_id",
2429                "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2430            ),
2431            ("privileges", "The privileges belonging to the schema."),
2432        ]),
2433        sql: "
2434IN CLUSTER mz_catalog_server
2435WITH (
2436    ASSERT NOT NULL id,
2437    ASSERT NOT NULL oid,
2438    ASSERT NOT NULL name,
2439    ASSERT NOT NULL owner_id,
2440    ASSERT NOT NULL privileges
2441) AS
2442SELECT
2443    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
2444    (data->'value'->>'oid')::oid AS oid,
2445    CASE WHEN data->'value'->'database_id' != 'null'
2446         THEN mz_internal.parse_catalog_id(data->'value'->'database_id')
2447    END AS database_id,
2448    data->'value'->>'name' AS name,
2449    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2450    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
2451FROM mz_internal.mz_catalog_raw
2452WHERE data->>'kind' = 'Schema'",
2453        access: vec![PUBLIC_SELECT],
2454    });
2455
2456pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2457    name: "mz_columns",
2458    schema: MZ_CATALOG_SCHEMA,
2459    oid: oid::TABLE_MZ_COLUMNS_OID,
2460    desc: RelationDesc::builder()
2461        .with_column("id", SqlScalarType::String.nullable(false)) // not a key
2462        .with_column("name", SqlScalarType::String.nullable(false))
2463        .with_column("position", SqlScalarType::UInt64.nullable(false))
2464        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2465        .with_column("type", SqlScalarType::String.nullable(false))
2466        .with_column("default", SqlScalarType::String.nullable(true))
2467        .with_column("type_oid", SqlScalarType::Oid.nullable(false))
2468        .with_column("type_mod", SqlScalarType::Int32.nullable(false))
2469        .finish(),
2470    column_comments: BTreeMap::from_iter([
2471        (
2472            "id",
2473            "The unique ID of the table, source, or view containing the column.",
2474        ),
2475        ("name", "The name of the column."),
2476        (
2477            "position",
2478            "The 1-indexed position of the column in its containing table, source, or view.",
2479        ),
2480        ("nullable", "Can the column contain a `NULL` value?"),
2481        ("type", "The data type of the column."),
2482        ("default", "The default expression of the column."),
2483        (
2484            "type_oid",
2485            "The OID of the type of the column (references `mz_types`).",
2486        ),
2487        ("type_mod", "The packed type identifier of the column."),
2488    ]),
2489    is_retained_metrics_object: false,
2490    access: vec![PUBLIC_SELECT],
2491});
2492pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2493    name: "mz_indexes",
2494    schema: MZ_CATALOG_SCHEMA,
2495    oid: oid::TABLE_MZ_INDEXES_OID,
2496    desc: RelationDesc::builder()
2497        .with_column("id", SqlScalarType::String.nullable(false))
2498        .with_column("oid", SqlScalarType::Oid.nullable(false))
2499        .with_column("name", SqlScalarType::String.nullable(false))
2500        .with_column("on_id", SqlScalarType::String.nullable(false))
2501        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2502        .with_column("owner_id", SqlScalarType::String.nullable(false))
2503        .with_column("create_sql", SqlScalarType::String.nullable(false))
2504        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2505        .with_key(vec![0])
2506        .with_key(vec![1])
2507        .finish(),
2508    column_comments: BTreeMap::from_iter([
2509        ("id", "Materialize's unique ID for the index."),
2510        ("oid", "A PostgreSQL-compatible OID for the index."),
2511        ("name", "The name of the index."),
2512        (
2513            "on_id",
2514            "The ID of the relation on which the index is built.",
2515        ),
2516        (
2517            "cluster_id",
2518            "The ID of the cluster in which the index is built.",
2519        ),
2520        (
2521            "owner_id",
2522            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2523        ),
2524        ("create_sql", "The `CREATE` SQL statement for the index."),
2525        (
2526            "redacted_create_sql",
2527            "The redacted `CREATE` SQL statement for the index.",
2528        ),
2529    ]),
2530    is_retained_metrics_object: false,
2531    access: vec![PUBLIC_SELECT],
2532});
2533pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2534    name: "mz_index_columns",
2535    schema: MZ_CATALOG_SCHEMA,
2536    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2537    desc: RelationDesc::builder()
2538        .with_column("index_id", SqlScalarType::String.nullable(false))
2539        .with_column("index_position", SqlScalarType::UInt64.nullable(false))
2540        .with_column("on_position", SqlScalarType::UInt64.nullable(true))
2541        .with_column("on_expression", SqlScalarType::String.nullable(true))
2542        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2543        .finish(),
2544    column_comments: BTreeMap::from_iter([
2545        (
2546            "index_id",
2547            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2548        ),
2549        (
2550            "index_position",
2551            "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.)",
2552        ),
2553        (
2554            "on_position",
2555            "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.",
2556        ),
2557        (
2558            "on_expression",
2559            "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.",
2560        ),
2561        (
2562            "nullable",
2563            "Can this column of the index evaluate to `NULL`?",
2564        ),
2565    ]),
2566    is_retained_metrics_object: false,
2567    access: vec![PUBLIC_SELECT],
2568});
2569pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2570    name: "mz_tables",
2571    schema: MZ_CATALOG_SCHEMA,
2572    oid: oid::TABLE_MZ_TABLES_OID,
2573    desc: RelationDesc::builder()
2574        .with_column("id", SqlScalarType::String.nullable(false))
2575        .with_column("oid", SqlScalarType::Oid.nullable(false))
2576        .with_column("schema_id", SqlScalarType::String.nullable(false))
2577        .with_column("name", SqlScalarType::String.nullable(false))
2578        .with_column("owner_id", SqlScalarType::String.nullable(false))
2579        .with_column(
2580            "privileges",
2581            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2582        )
2583        .with_column("create_sql", SqlScalarType::String.nullable(true))
2584        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2585        .with_column("source_id", SqlScalarType::String.nullable(true))
2586        .with_key(vec![0])
2587        .with_key(vec![1])
2588        .finish(),
2589    column_comments: BTreeMap::from_iter([
2590        ("id", "Materialize's unique ID for the table."),
2591        ("oid", "A PostgreSQL-compatible OID for the table."),
2592        (
2593            "schema_id",
2594            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2595        ),
2596        ("name", "The name of the table."),
2597        (
2598            "owner_id",
2599            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2600        ),
2601        ("privileges", "The privileges belonging to the table."),
2602        ("create_sql", "The `CREATE` SQL statement for the table."),
2603        (
2604            "redacted_create_sql",
2605            "The redacted `CREATE` SQL statement for the table.",
2606        ),
2607        (
2608            "source_id",
2609            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2610        ),
2611    ]),
2612    is_retained_metrics_object: true,
2613    access: vec![PUBLIC_SELECT],
2614});
2615pub static MZ_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2616    name: "mz_connections",
2617    schema: MZ_CATALOG_SCHEMA,
2618    oid: oid::TABLE_MZ_CONNECTIONS_OID,
2619    desc: RelationDesc::builder()
2620        .with_column("id", SqlScalarType::String.nullable(false))
2621        .with_column("oid", SqlScalarType::Oid.nullable(false))
2622        .with_column("schema_id", SqlScalarType::String.nullable(false))
2623        .with_column("name", SqlScalarType::String.nullable(false))
2624        .with_column("type", SqlScalarType::String.nullable(false))
2625        .with_column("owner_id", SqlScalarType::String.nullable(false))
2626        .with_column(
2627            "privileges",
2628            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2629        )
2630        .with_column("create_sql", SqlScalarType::String.nullable(false))
2631        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2632        .with_key(vec![0])
2633        .with_key(vec![1])
2634        .finish(),
2635    column_comments: BTreeMap::from_iter([
2636        ("id", "The unique ID of the connection."),
2637        ("oid", "A PostgreSQL-compatible OID for the connection."),
2638        (
2639            "schema_id",
2640            "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2641        ),
2642        ("name", "The name of the connection."),
2643        (
2644            "type",
2645            "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2646        ),
2647        (
2648            "owner_id",
2649            "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2650        ),
2651        ("privileges", "The privileges belonging to the connection."),
2652        (
2653            "create_sql",
2654            "The `CREATE` SQL statement for the connection.",
2655        ),
2656        (
2657            "redacted_create_sql",
2658            "The redacted `CREATE` SQL statement for the connection.",
2659        ),
2660    ]),
2661    is_retained_metrics_object: false,
2662    access: vec![PUBLIC_SELECT],
2663});
2664pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2665    name: "mz_ssh_tunnel_connections",
2666    schema: MZ_CATALOG_SCHEMA,
2667    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2668    desc: RelationDesc::builder()
2669        .with_column("id", SqlScalarType::String.nullable(false))
2670        .with_column("public_key_1", SqlScalarType::String.nullable(false))
2671        .with_column("public_key_2", SqlScalarType::String.nullable(false))
2672        .finish(),
2673    column_comments: BTreeMap::from_iter([
2674        ("id", "The ID of the connection."),
2675        (
2676            "public_key_1",
2677            "The first public key associated with the SSH tunnel.",
2678        ),
2679        (
2680            "public_key_2",
2681            "The second public key associated with the SSH tunnel.",
2682        ),
2683    ]),
2684    is_retained_metrics_object: false,
2685    access: vec![PUBLIC_SELECT],
2686});
2687pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2688    name: "mz_sources",
2689    schema: MZ_CATALOG_SCHEMA,
2690    oid: oid::TABLE_MZ_SOURCES_OID,
2691    desc: RelationDesc::builder()
2692        .with_column("id", SqlScalarType::String.nullable(false))
2693        .with_column("oid", SqlScalarType::Oid.nullable(false))
2694        .with_column("schema_id", SqlScalarType::String.nullable(false))
2695        .with_column("name", SqlScalarType::String.nullable(false))
2696        .with_column("type", SqlScalarType::String.nullable(false))
2697        .with_column("connection_id", SqlScalarType::String.nullable(true))
2698        .with_column("size", SqlScalarType::String.nullable(true))
2699        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2700        .with_column("key_format", SqlScalarType::String.nullable(true))
2701        .with_column("value_format", SqlScalarType::String.nullable(true))
2702        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2703        .with_column("owner_id", SqlScalarType::String.nullable(false))
2704        .with_column(
2705            "privileges",
2706            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2707        )
2708        .with_column("create_sql", SqlScalarType::String.nullable(true))
2709        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2710        .with_key(vec![0])
2711        .with_key(vec![1])
2712        .finish(),
2713    column_comments: BTreeMap::from_iter([
2714        ("id", "Materialize's unique ID for the source."),
2715        ("oid", "A PostgreSQL-compatible OID for the source."),
2716        (
2717            "schema_id",
2718            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2719        ),
2720        ("name", "The name of the source."),
2721        (
2722            "type",
2723            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2724        ),
2725        (
2726            "connection_id",
2727            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2728        ),
2729        ("size", "*Deprecated* The size of the source."),
2730        (
2731            "envelope_type",
2732            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2733        ),
2734        (
2735            "key_format",
2736            "For Kafka sources, the format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2737        ),
2738        (
2739            "value_format",
2740            "For Kafka sources, the format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2741        ),
2742        (
2743            "cluster_id",
2744            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2745        ),
2746        (
2747            "owner_id",
2748            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2749        ),
2750        ("privileges", "The privileges granted on the source."),
2751        ("create_sql", "The `CREATE` SQL statement for the source."),
2752        (
2753            "redacted_create_sql",
2754            "The redacted `CREATE` SQL statement for the source.",
2755        ),
2756    ]),
2757    is_retained_metrics_object: true,
2758    access: vec![PUBLIC_SELECT],
2759});
2760pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2761    BuiltinTable {
2762        name: "mz_sinks",
2763        schema: MZ_CATALOG_SCHEMA,
2764        oid: oid::TABLE_MZ_SINKS_OID,
2765        desc: RelationDesc::builder()
2766            .with_column("id", SqlScalarType::String.nullable(false))
2767            .with_column("oid", SqlScalarType::Oid.nullable(false))
2768            .with_column("schema_id", SqlScalarType::String.nullable(false))
2769            .with_column("name", SqlScalarType::String.nullable(false))
2770            .with_column("type", SqlScalarType::String.nullable(false))
2771            .with_column("connection_id", SqlScalarType::String.nullable(true))
2772            .with_column("size", SqlScalarType::String.nullable(true))
2773            .with_column("envelope_type", SqlScalarType::String.nullable(true))
2774            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2775            // below. This should be removed in the future.
2776            .with_column("format", SqlScalarType::String.nullable(true))
2777            .with_column("key_format", SqlScalarType::String.nullable(true))
2778            .with_column("value_format", SqlScalarType::String.nullable(true))
2779            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2780            .with_column("owner_id", SqlScalarType::String.nullable(false))
2781            .with_column("create_sql", SqlScalarType::String.nullable(false))
2782            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2783            .with_key(vec![0])
2784            .with_key(vec![1])
2785            .finish(),
2786        column_comments: BTreeMap::from_iter([
2787            ("id", "Materialize's unique ID for the sink."),
2788            ("oid", "A PostgreSQL-compatible OID for the sink."),
2789            (
2790                "schema_id",
2791                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2792            ),
2793            ("name", "The name of the sink."),
2794            ("type", "The type of the sink: `kafka`."),
2795            (
2796                "connection_id",
2797                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2798            ),
2799            ("size", "The size of the sink."),
2800            (
2801                "envelope_type",
2802                "The envelope of the sink: `upsert`, or `debezium`.",
2803            ),
2804            (
2805                "format",
2806                "*Deprecated* The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2807            ),
2808            (
2809                "key_format",
2810                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2811            ),
2812            (
2813                "value_format",
2814                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2815            ),
2816            (
2817                "cluster_id",
2818                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2819            ),
2820            (
2821                "owner_id",
2822                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2823            ),
2824            ("create_sql", "The `CREATE` SQL statement for the sink."),
2825            (
2826                "redacted_create_sql",
2827                "The redacted `CREATE` SQL statement for the sink.",
2828            ),
2829        ]),
2830        is_retained_metrics_object: true,
2831        access: vec![PUBLIC_SELECT],
2832    }
2833});
2834pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2835    name: "mz_views",
2836    schema: MZ_CATALOG_SCHEMA,
2837    oid: oid::TABLE_MZ_VIEWS_OID,
2838    desc: RelationDesc::builder()
2839        .with_column("id", SqlScalarType::String.nullable(false))
2840        .with_column("oid", SqlScalarType::Oid.nullable(false))
2841        .with_column("schema_id", SqlScalarType::String.nullable(false))
2842        .with_column("name", SqlScalarType::String.nullable(false))
2843        .with_column("definition", SqlScalarType::String.nullable(false))
2844        .with_column("owner_id", SqlScalarType::String.nullable(false))
2845        .with_column(
2846            "privileges",
2847            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2848        )
2849        .with_column("create_sql", SqlScalarType::String.nullable(false))
2850        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2851        .with_key(vec![0])
2852        .with_key(vec![1])
2853        .finish(),
2854    column_comments: BTreeMap::from_iter([
2855        ("id", "Materialize's unique ID for the view."),
2856        ("oid", "A PostgreSQL-compatible OID for the view."),
2857        (
2858            "schema_id",
2859            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2860        ),
2861        ("name", "The name of the view."),
2862        ("definition", "The view definition (a `SELECT` query)."),
2863        (
2864            "owner_id",
2865            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2866        ),
2867        ("privileges", "The privileges belonging to the view."),
2868        ("create_sql", "The `CREATE` SQL statement for the view."),
2869        (
2870            "redacted_create_sql",
2871            "The redacted `CREATE` SQL statement for the view.",
2872        ),
2873    ]),
2874    is_retained_metrics_object: false,
2875    access: vec![PUBLIC_SELECT],
2876});
2877pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2878    name: "mz_materialized_views",
2879    schema: MZ_CATALOG_SCHEMA,
2880    oid: oid::TABLE_MZ_MATERIALIZED_VIEWS_OID,
2881    desc: RelationDesc::builder()
2882        .with_column("id", SqlScalarType::String.nullable(false))
2883        .with_column("oid", SqlScalarType::Oid.nullable(false))
2884        .with_column("schema_id", SqlScalarType::String.nullable(false))
2885        .with_column("name", SqlScalarType::String.nullable(false))
2886        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2887        .with_column("definition", SqlScalarType::String.nullable(false))
2888        .with_column("owner_id", SqlScalarType::String.nullable(false))
2889        .with_column(
2890            "privileges",
2891            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2892        )
2893        .with_column("create_sql", SqlScalarType::String.nullable(false))
2894        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2895        .with_key(vec![0])
2896        .with_key(vec![1])
2897        .finish(),
2898    column_comments: BTreeMap::from_iter([
2899        ("id", "Materialize's unique ID for the materialized view."),
2900        (
2901            "oid",
2902            "A PostgreSQL-compatible OID for the materialized view.",
2903        ),
2904        (
2905            "schema_id",
2906            "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2907        ),
2908        ("name", "The name of the materialized view."),
2909        (
2910            "cluster_id",
2911            "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2912        ),
2913        (
2914            "definition",
2915            "The materialized view definition (a `SELECT` query).",
2916        ),
2917        (
2918            "owner_id",
2919            "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2920        ),
2921        (
2922            "privileges",
2923            "The privileges belonging to the materialized view.",
2924        ),
2925        (
2926            "create_sql",
2927            "The `CREATE` SQL statement for the materialized view.",
2928        ),
2929        (
2930            "redacted_create_sql",
2931            "The redacted `CREATE` SQL statement for the materialized view.",
2932        ),
2933    ]),
2934    is_retained_metrics_object: false,
2935    access: vec![PUBLIC_SELECT],
2936});
2937pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
2938    BuiltinTable {
2939        name: "mz_materialized_view_refresh_strategies",
2940        schema: MZ_INTERNAL_SCHEMA,
2941        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
2942        desc: RelationDesc::builder()
2943            .with_column(
2944                "materialized_view_id",
2945                SqlScalarType::String.nullable(false),
2946            )
2947            .with_column("type", SqlScalarType::String.nullable(false))
2948            .with_column("interval", SqlScalarType::Interval.nullable(true))
2949            .with_column(
2950                "aligned_to",
2951                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2952            )
2953            .with_column(
2954                "at",
2955                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2956            )
2957            .finish(),
2958        column_comments: BTreeMap::from_iter([
2959            (
2960                "materialized_view_id",
2961                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
2962            ),
2963            (
2964                "type",
2965                "`at`, `every`, or `on-commit`. Default: `on-commit`",
2966            ),
2967            (
2968                "interval",
2969                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2970            ),
2971            (
2972                "aligned_to",
2973                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2974            ),
2975            (
2976                "at",
2977                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
2978            ),
2979        ]),
2980        is_retained_metrics_object: false,
2981        access: vec![PUBLIC_SELECT],
2982    }
2983});
2984pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2985    name: "mz_types",
2986    schema: MZ_CATALOG_SCHEMA,
2987    oid: oid::TABLE_MZ_TYPES_OID,
2988    desc: RelationDesc::builder()
2989        .with_column("id", SqlScalarType::String.nullable(false))
2990        .with_column("oid", SqlScalarType::Oid.nullable(false))
2991        .with_column("schema_id", SqlScalarType::String.nullable(false))
2992        .with_column("name", SqlScalarType::String.nullable(false))
2993        .with_column("category", SqlScalarType::String.nullable(false))
2994        .with_column("owner_id", SqlScalarType::String.nullable(false))
2995        .with_column(
2996            "privileges",
2997            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2998        )
2999        .with_column("create_sql", SqlScalarType::String.nullable(true))
3000        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
3001        .with_key(vec![0])
3002        .with_key(vec![1])
3003        .finish(),
3004    column_comments: BTreeMap::from_iter([
3005        ("id", "Materialize's unique ID for the type."),
3006        ("oid", "A PostgreSQL-compatible OID for the type."),
3007        (
3008            "schema_id",
3009            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
3010        ),
3011        ("name", "The name of the type."),
3012        ("category", "The category of the type."),
3013        (
3014            "owner_id",
3015            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
3016        ),
3017        ("privileges", "The privileges belonging to the type."),
3018        ("create_sql", "The `CREATE` SQL statement for the type."),
3019        (
3020            "redacted_create_sql",
3021            "The redacted `CREATE` SQL statement for the type.",
3022        ),
3023    ]),
3024    is_retained_metrics_object: false,
3025    access: vec![PUBLIC_SELECT],
3026});
3027pub static MZ_CONTINUAL_TASKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3028    name: "mz_continual_tasks",
3029    schema: MZ_INTERNAL_SCHEMA,
3030    oid: oid::TABLE_MZ_CONTINUAL_TASKS_OID,
3031    desc: RelationDesc::builder()
3032        .with_column("id", SqlScalarType::String.nullable(false))
3033        .with_column("oid", SqlScalarType::Oid.nullable(false))
3034        .with_column("schema_id", SqlScalarType::String.nullable(false))
3035        .with_column("name", SqlScalarType::String.nullable(false))
3036        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3037        .with_column("definition", SqlScalarType::String.nullable(false))
3038        .with_column("owner_id", SqlScalarType::String.nullable(false))
3039        .with_column(
3040            "privileges",
3041            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3042        )
3043        .with_column("create_sql", SqlScalarType::String.nullable(false))
3044        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
3045        .with_key(vec![0])
3046        .with_key(vec![1])
3047        .finish(),
3048    column_comments: BTreeMap::new(),
3049    is_retained_metrics_object: false,
3050    access: vec![PUBLIC_SELECT],
3051});
3052
3053pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3054    BuiltinMaterializedView {
3055        name: "mz_network_policies",
3056        schema: MZ_INTERNAL_SCHEMA,
3057        oid: oid::MV_MZ_NETWORK_POLICIES_OID,
3058        desc: RelationDesc::builder()
3059            .with_column("id", SqlScalarType::String.nullable(false))
3060            .with_column("name", SqlScalarType::String.nullable(false))
3061            .with_column("owner_id", SqlScalarType::String.nullable(false))
3062            .with_column(
3063                "privileges",
3064                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3065            )
3066            .with_column("oid", SqlScalarType::Oid.nullable(false))
3067            .with_key(vec![0])
3068            .with_key(vec![4])
3069            .finish(),
3070        column_comments: BTreeMap::from_iter([
3071            ("id", "The ID of the network policy."),
3072            ("name", "The name of the network policy."),
3073            (
3074                "owner_id",
3075                "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
3076            ),
3077            (
3078                "privileges",
3079                "The privileges belonging to the network policy.",
3080            ),
3081            ("oid", "A PostgreSQL-compatible OID for the network policy."),
3082        ]),
3083        sql: "
3084IN CLUSTER mz_catalog_server
3085WITH (
3086    ASSERT NOT NULL id,
3087    ASSERT NOT NULL name,
3088    ASSERT NOT NULL owner_id,
3089    ASSERT NOT NULL privileges,
3090    ASSERT NOT NULL oid
3091) AS
3092SELECT
3093    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
3094    data->'value'->>'name' AS name,
3095    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
3096    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
3097    (data->'value'->>'oid')::oid AS oid
3098FROM mz_internal.mz_catalog_raw
3099WHERE data->>'kind' = 'NetworkPolicy'",
3100        access: vec![PUBLIC_SELECT],
3101    }
3102});
3103
3104pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3105    BuiltinMaterializedView {
3106        name: "mz_network_policy_rules",
3107        schema: MZ_INTERNAL_SCHEMA,
3108        oid: oid::MV_MZ_NETWORK_POLICY_RULES_OID,
3109        desc: RelationDesc::builder()
3110            .with_column("name", SqlScalarType::String.nullable(false))
3111            .with_column("policy_id", SqlScalarType::String.nullable(false))
3112            .with_column("action", SqlScalarType::String.nullable(false))
3113            .with_column("address", SqlScalarType::String.nullable(false))
3114            .with_column("direction", SqlScalarType::String.nullable(false))
3115            .finish(),
3116        column_comments: BTreeMap::from_iter([
3117            (
3118                "name",
3119                "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
3120            ),
3121            (
3122                "policy_id",
3123                "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
3124            ),
3125            (
3126                "action",
3127                "The action of the rule. `allow` is the only supported action.",
3128            ),
3129            ("address", "The address the rule will take action on."),
3130            (
3131                "direction",
3132                "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3133            ),
3134        ]),
3135        sql: "
3136IN CLUSTER mz_catalog_server
3137WITH (
3138    ASSERT NOT NULL name,
3139    ASSERT NOT NULL policy_id,
3140    ASSERT NOT NULL action,
3141    ASSERT NOT NULL address,
3142    ASSERT NOT NULL direction
3143) AS
3144SELECT
3145    rule->>'name' AS name,
3146    mz_internal.parse_catalog_id(data->'key'->'id') AS policy_id,
3147    lower(rule->>'action') AS action,
3148    rule->>'address' AS address,
3149    lower(rule->>'direction') AS direction
3150FROM
3151    mz_internal.mz_catalog_raw,
3152    jsonb_array_elements(data->'value'->'rules') AS rule
3153WHERE data->>'kind' = 'NetworkPolicy'",
3154        access: vec![PUBLIC_SELECT],
3155    }
3156});
3157
3158/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3159/// in the `mz_types` table as part of our public, stable API.
3160pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3161    name: "mz_type_pg_metadata",
3162    schema: MZ_INTERNAL_SCHEMA,
3163    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3164    desc: RelationDesc::builder()
3165        .with_column("id", SqlScalarType::String.nullable(false))
3166        .with_column("typinput", SqlScalarType::Oid.nullable(false))
3167        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
3168        .finish(),
3169    column_comments: BTreeMap::new(),
3170    is_retained_metrics_object: false,
3171    access: vec![PUBLIC_SELECT],
3172});
3173pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3174    name: "mz_array_types",
3175    schema: MZ_CATALOG_SCHEMA,
3176    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3177    desc: RelationDesc::builder()
3178        .with_column("id", SqlScalarType::String.nullable(false))
3179        .with_column("element_id", SqlScalarType::String.nullable(false))
3180        .finish(),
3181    column_comments: BTreeMap::from_iter([
3182        ("id", "The ID of the array type."),
3183        ("element_id", "The ID of the array's element type."),
3184    ]),
3185    is_retained_metrics_object: false,
3186    access: vec![PUBLIC_SELECT],
3187});
3188pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3189    name: "mz_base_types",
3190    schema: MZ_CATALOG_SCHEMA,
3191    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3192    desc: RelationDesc::builder()
3193        .with_column("id", SqlScalarType::String.nullable(false))
3194        .finish(),
3195    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3196    is_retained_metrics_object: false,
3197    access: vec![PUBLIC_SELECT],
3198});
3199pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3200    name: "mz_list_types",
3201    schema: MZ_CATALOG_SCHEMA,
3202    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3203    desc: RelationDesc::builder()
3204        .with_column("id", SqlScalarType::String.nullable(false))
3205        .with_column("element_id", SqlScalarType::String.nullable(false))
3206        .with_column(
3207            "element_modifiers",
3208            SqlScalarType::List {
3209                element_type: Box::new(SqlScalarType::Int64),
3210                custom_id: None,
3211            }
3212            .nullable(true),
3213        )
3214        .finish(),
3215    column_comments: BTreeMap::from_iter([
3216        ("id", "The ID of the list type."),
3217        ("element_id", "The IID of the list's element type."),
3218        (
3219            "element_modifiers",
3220            "The element type modifiers, or `NULL` if none.",
3221        ),
3222    ]),
3223    is_retained_metrics_object: false,
3224    access: vec![PUBLIC_SELECT],
3225});
3226pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3227    name: "mz_map_types",
3228    schema: MZ_CATALOG_SCHEMA,
3229    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3230    desc: RelationDesc::builder()
3231        .with_column("id", SqlScalarType::String.nullable(false))
3232        .with_column("key_id", SqlScalarType::String.nullable(false))
3233        .with_column("value_id", SqlScalarType::String.nullable(false))
3234        .with_column(
3235            "key_modifiers",
3236            SqlScalarType::List {
3237                element_type: Box::new(SqlScalarType::Int64),
3238                custom_id: None,
3239            }
3240            .nullable(true),
3241        )
3242        .with_column(
3243            "value_modifiers",
3244            SqlScalarType::List {
3245                element_type: Box::new(SqlScalarType::Int64),
3246                custom_id: None,
3247            }
3248            .nullable(true),
3249        )
3250        .finish(),
3251    column_comments: BTreeMap::from_iter([
3252        ("id", "The ID of the map type."),
3253        ("key_id", "The ID of the map's key type."),
3254        ("value_id", "The ID of the map's value type."),
3255        (
3256            "key_modifiers",
3257            "The key type modifiers, or `NULL` if none.",
3258        ),
3259        (
3260            "value_modifiers",
3261            "The value type modifiers, or `NULL` if none.",
3262        ),
3263    ]),
3264    is_retained_metrics_object: false,
3265    access: vec![PUBLIC_SELECT],
3266});
3267pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3268    name: "mz_roles",
3269    schema: MZ_CATALOG_SCHEMA,
3270    oid: oid::TABLE_MZ_ROLES_OID,
3271    desc: RelationDesc::builder()
3272        .with_column("id", SqlScalarType::String.nullable(false))
3273        .with_column("oid", SqlScalarType::Oid.nullable(false))
3274        .with_column("name", SqlScalarType::String.nullable(false))
3275        .with_column("inherit", SqlScalarType::Bool.nullable(false))
3276        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(true))
3277        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
3278        .with_key(vec![0])
3279        .with_key(vec![1])
3280        .finish(),
3281    column_comments: BTreeMap::from_iter([
3282        ("id", "Materialize's unique ID for the role."),
3283        ("oid", "A PostgreSQL-compatible OID for the role."),
3284        ("name", "The name of the role."),
3285        (
3286            "inherit",
3287            "Indicates whether the role has inheritance of privileges.",
3288        ),
3289        ("rolcanlogin", "Indicates whether the role can log in."),
3290        ("rolsuper", "Indicates whether the role is a superuser."),
3291    ]),
3292    is_retained_metrics_object: false,
3293    access: vec![PUBLIC_SELECT],
3294});
3295
3296pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3297    BuiltinMaterializedView {
3298        name: "mz_role_members",
3299        schema: MZ_CATALOG_SCHEMA,
3300        oid: oid::MV_MZ_ROLE_MEMBERS_OID,
3301        desc: RelationDesc::builder()
3302            .with_column("role_id", SqlScalarType::String.nullable(false))
3303            .with_column("member", SqlScalarType::String.nullable(false))
3304            .with_column("grantor", SqlScalarType::String.nullable(false))
3305            .finish(),
3306        column_comments: BTreeMap::from_iter([
3307            (
3308                "role_id",
3309                "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3310            ),
3311            (
3312                "member",
3313                "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3314            ),
3315            (
3316                "grantor",
3317                "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3318            ),
3319        ]),
3320        sql: "
3321IN CLUSTER mz_catalog_server
3322WITH (
3323    ASSERT NOT NULL role_id,
3324    ASSERT NOT NULL member,
3325    ASSERT NOT NULL grantor
3326) AS
3327SELECT
3328    mz_internal.parse_catalog_id(entry->'key') AS role_id,
3329    mz_internal.parse_catalog_id(data->'key'->'id') AS member,
3330    mz_internal.parse_catalog_id(entry->'value') AS grantor
3331FROM
3332    mz_internal.mz_catalog_raw,
3333    jsonb_array_elements(data->'value'->'membership'->'map') AS entry
3334WHERE data->>'kind' = 'Role'",
3335        access: vec![PUBLIC_SELECT],
3336    }
3337});
3338
3339pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3340    name: "mz_role_parameters",
3341    schema: MZ_CATALOG_SCHEMA,
3342    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3343    desc: RelationDesc::builder()
3344        .with_column("role_id", SqlScalarType::String.nullable(false))
3345        .with_column("parameter_name", SqlScalarType::String.nullable(false))
3346        .with_column("parameter_value", SqlScalarType::String.nullable(false))
3347        .finish(),
3348    column_comments: BTreeMap::from_iter([
3349        (
3350            "role_id",
3351            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3352        ),
3353        (
3354            "parameter_name",
3355            "The configuration parameter name. One of the supported configuration parameters.",
3356        ),
3357        (
3358            "parameter_value",
3359            "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.",
3360        ),
3361    ]),
3362    is_retained_metrics_object: false,
3363    access: vec![PUBLIC_SELECT],
3364});
3365pub static MZ_ROLE_AUTH: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3366    name: "mz_role_auth",
3367    schema: MZ_CATALOG_SCHEMA,
3368    oid: oid::TABLE_MZ_ROLE_AUTH_OID,
3369    desc: RelationDesc::builder()
3370        .with_column("role_id", SqlScalarType::String.nullable(false))
3371        .with_column("role_oid", SqlScalarType::Oid.nullable(false))
3372        .with_column("password_hash", SqlScalarType::String.nullable(true))
3373        .with_column(
3374            "updated_at",
3375            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3376        )
3377        .finish(),
3378    column_comments: BTreeMap::from_iter([
3379        (
3380            "role_id",
3381            "The ID of the role. Corresponds to `mz_roles.id`.",
3382        ),
3383        ("role_oid", "A PostgreSQL-compatible OID for the role."),
3384        (
3385            "password_hash",
3386            "The hashed password for the role, if any. Uses the `SCRAM-SHA-256` algorithm.",
3387        ),
3388        (
3389            "updated_at",
3390            "The time at which the password was last updated.",
3391        ),
3392    ]),
3393    is_retained_metrics_object: false,
3394    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
3395});
3396pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3397    name: "mz_pseudo_types",
3398    schema: MZ_CATALOG_SCHEMA,
3399    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3400    desc: RelationDesc::builder()
3401        .with_column("id", SqlScalarType::String.nullable(false))
3402        .finish(),
3403    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3404    is_retained_metrics_object: false,
3405    access: vec![PUBLIC_SELECT],
3406});
3407pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3408    BuiltinTable {
3409        name: "mz_functions",
3410        schema: MZ_CATALOG_SCHEMA,
3411        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3412        desc: RelationDesc::builder()
3413            .with_column("id", SqlScalarType::String.nullable(false)) // not a key!
3414            .with_column("oid", SqlScalarType::Oid.nullable(false))
3415            .with_column("schema_id", SqlScalarType::String.nullable(false))
3416            .with_column("name", SqlScalarType::String.nullable(false))
3417            .with_column(
3418                "argument_type_ids",
3419                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3420            )
3421            .with_column(
3422                "variadic_argument_type_id",
3423                SqlScalarType::String.nullable(true),
3424            )
3425            .with_column("return_type_id", SqlScalarType::String.nullable(true))
3426            .with_column("returns_set", SqlScalarType::Bool.nullable(false))
3427            .with_column("owner_id", SqlScalarType::String.nullable(false))
3428            .finish(),
3429        column_comments: BTreeMap::from_iter([
3430            ("id", "Materialize's unique ID for the function."),
3431            ("oid", "A PostgreSQL-compatible OID for the function."),
3432            (
3433                "schema_id",
3434                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3435            ),
3436            ("name", "The name of the function."),
3437            (
3438                "argument_type_ids",
3439                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3440            ),
3441            (
3442                "variadic_argument_type_id",
3443                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3444            ),
3445            (
3446                "return_type_id",
3447                "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`].",
3448            ),
3449            (
3450                "returns_set",
3451                "Whether the function returns a set, i.e. the function is a table function.",
3452            ),
3453            (
3454                "owner_id",
3455                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3456            ),
3457        ]),
3458        is_retained_metrics_object: false,
3459        access: vec![PUBLIC_SELECT],
3460    }
3461});
3462pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3463    name: "mz_operators",
3464    schema: MZ_CATALOG_SCHEMA,
3465    oid: oid::TABLE_MZ_OPERATORS_OID,
3466    desc: RelationDesc::builder()
3467        .with_column("oid", SqlScalarType::Oid.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("return_type_id", SqlScalarType::String.nullable(true))
3474        .finish(),
3475    column_comments: BTreeMap::new(),
3476    is_retained_metrics_object: false,
3477    access: vec![PUBLIC_SELECT],
3478});
3479pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3480    name: "mz_aggregates",
3481    schema: MZ_INTERNAL_SCHEMA,
3482    oid: oid::TABLE_MZ_AGGREGATES_OID,
3483    desc: RelationDesc::builder()
3484        .with_column("oid", SqlScalarType::Oid.nullable(false))
3485        .with_column("agg_kind", SqlScalarType::String.nullable(false))
3486        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
3487        .finish(),
3488    column_comments: BTreeMap::new(),
3489    is_retained_metrics_object: false,
3490    access: vec![PUBLIC_SELECT],
3491});
3492
3493pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3494    name: "mz_clusters",
3495    schema: MZ_CATALOG_SCHEMA,
3496    oid: oid::TABLE_MZ_CLUSTERS_OID,
3497    desc: RelationDesc::builder()
3498        .with_column("id", SqlScalarType::String.nullable(false))
3499        .with_column("name", SqlScalarType::String.nullable(false))
3500        .with_column("owner_id", SqlScalarType::String.nullable(false))
3501        .with_column(
3502            "privileges",
3503            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3504        )
3505        .with_column("managed", SqlScalarType::Bool.nullable(false))
3506        .with_column("size", SqlScalarType::String.nullable(true))
3507        .with_column("replication_factor", SqlScalarType::UInt32.nullable(true))
3508        .with_column("disk", SqlScalarType::Bool.nullable(true))
3509        .with_column(
3510            "availability_zones",
3511            SqlScalarType::List {
3512                element_type: Box::new(SqlScalarType::String),
3513                custom_id: None,
3514            }
3515            .nullable(true),
3516        )
3517        .with_column(
3518            "introspection_debugging",
3519            SqlScalarType::Bool.nullable(true),
3520        )
3521        .with_column(
3522            "introspection_interval",
3523            SqlScalarType::Interval.nullable(true),
3524        )
3525        .with_key(vec![0])
3526        .finish(),
3527    column_comments: BTreeMap::from_iter([
3528        ("id", "Materialize's unique ID for the cluster."),
3529        ("name", "The name of the cluster."),
3530        (
3531            "owner_id",
3532            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3533        ),
3534        ("privileges", "The privileges belonging to the cluster."),
3535        (
3536            "managed",
3537            "Whether the cluster is a managed cluster with automatically managed replicas.",
3538        ),
3539        (
3540            "size",
3541            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3542        ),
3543        (
3544            "replication_factor",
3545            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3546        ),
3547        (
3548            "disk",
3549            "**Unstable** If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3550        ),
3551        (
3552            "availability_zones",
3553            "**Unstable** If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3554        ),
3555        (
3556            "introspection_debugging",
3557            "Whether introspection of the gathering of the introspection data is enabled.",
3558        ),
3559        (
3560            "introspection_interval",
3561            "The interval at which to collect introspection data.",
3562        ),
3563    ]),
3564    is_retained_metrics_object: false,
3565    access: vec![PUBLIC_SELECT],
3566});
3567
3568pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinMaterializedView> =
3569    LazyLock::new(|| BuiltinMaterializedView {
3570        name: "mz_cluster_workload_classes",
3571        schema: MZ_INTERNAL_SCHEMA,
3572        oid: oid::MV_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3573        desc: RelationDesc::builder()
3574            .with_column("id", SqlScalarType::String.nullable(false))
3575            .with_column("workload_class", SqlScalarType::String.nullable(true))
3576            .with_key(vec![0])
3577            .finish(),
3578        column_comments: BTreeMap::new(),
3579        sql: "
3580IN CLUSTER mz_catalog_server
3581WITH (
3582    ASSERT NOT NULL id
3583) AS
3584SELECT
3585    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
3586    CASE WHEN data->'value'->'config'->'workload_class' != 'null'
3587         THEN data->'value'->'config'->>'workload_class'
3588    END AS workload_class
3589FROM mz_internal.mz_catalog_raw
3590WHERE data->>'kind' = 'Cluster'",
3591        access: vec![PUBLIC_SELECT],
3592    });
3593
3594pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3595    name: "mz_cluster_workload_classes_ind",
3596    schema: MZ_INTERNAL_SCHEMA,
3597    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3598    sql: "IN CLUSTER mz_catalog_server
3599ON mz_internal.mz_cluster_workload_classes (id)",
3600    is_retained_metrics_object: false,
3601};
3602
3603pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3604    name: "mz_cluster_schedules",
3605    schema: MZ_INTERNAL_SCHEMA,
3606    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3607    desc: RelationDesc::builder()
3608        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3609        .with_column("type", SqlScalarType::String.nullable(false))
3610        .with_column(
3611            "refresh_hydration_time_estimate",
3612            SqlScalarType::Interval.nullable(true),
3613        )
3614        .finish(),
3615    column_comments: BTreeMap::from_iter([
3616        (
3617            "cluster_id",
3618            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3619        ),
3620        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3621        (
3622            "refresh_hydration_time_estimate",
3623            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3624        ),
3625    ]),
3626    is_retained_metrics_object: false,
3627    access: vec![PUBLIC_SELECT],
3628});
3629
3630pub static MZ_SECRETS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3631    name: "mz_secrets",
3632    schema: MZ_CATALOG_SCHEMA,
3633    oid: oid::TABLE_MZ_SECRETS_OID,
3634    desc: RelationDesc::builder()
3635        .with_column("id", SqlScalarType::String.nullable(false))
3636        .with_column("oid", SqlScalarType::Oid.nullable(false))
3637        .with_column("schema_id", SqlScalarType::String.nullable(false))
3638        .with_column("name", SqlScalarType::String.nullable(false))
3639        .with_column("owner_id", SqlScalarType::String.nullable(false))
3640        .with_column(
3641            "privileges",
3642            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3643        )
3644        .finish(),
3645    column_comments: BTreeMap::from_iter([
3646        ("id", "The unique ID of the secret."),
3647        ("oid", "A PostgreSQL-compatible oid for the secret."),
3648        (
3649            "schema_id",
3650            "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3651        ),
3652        ("name", "The name of the secret."),
3653        (
3654            "owner_id",
3655            "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3656        ),
3657        ("privileges", "The privileges belonging to the secret."),
3658    ]),
3659    is_retained_metrics_object: false,
3660    access: vec![PUBLIC_SELECT],
3661});
3662
3663pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3664    name: "mz_cluster_replicas",
3665    schema: MZ_CATALOG_SCHEMA,
3666    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3667    desc: RelationDesc::builder()
3668        .with_column("id", SqlScalarType::String.nullable(false))
3669        .with_column("name", SqlScalarType::String.nullable(false))
3670        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3671        .with_column("size", SqlScalarType::String.nullable(true))
3672        // `NULL` for un-orchestrated clusters and for replicas where the user
3673        // hasn't specified them.
3674        .with_column("availability_zone", SqlScalarType::String.nullable(true))
3675        .with_column("owner_id", SqlScalarType::String.nullable(false))
3676        .with_column("disk", SqlScalarType::Bool.nullable(true))
3677        .finish(),
3678    column_comments: BTreeMap::from_iter([
3679        ("id", "Materialize's unique ID for the cluster replica."),
3680        ("name", "The name of the cluster replica."),
3681        (
3682            "cluster_id",
3683            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3684        ),
3685        (
3686            "size",
3687            "The cluster replica's size, selected during creation.",
3688        ),
3689        (
3690            "availability_zone",
3691            "The availability zone in which the cluster is running.",
3692        ),
3693        (
3694            "owner_id",
3695            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3696        ),
3697        ("disk", "If the replica has a local disk."),
3698    ]),
3699    is_retained_metrics_object: true,
3700    access: vec![PUBLIC_SELECT],
3701});
3702
3703pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
3704    LazyLock::new(|| BuiltinMaterializedView {
3705        name: "mz_internal_cluster_replicas",
3706        schema: MZ_INTERNAL_SCHEMA,
3707        oid: oid::MV_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3708        desc: RelationDesc::builder()
3709            .with_column("id", SqlScalarType::String.nullable(false))
3710            .with_key(vec![0])
3711            .finish(),
3712        column_comments: BTreeMap::from_iter([(
3713            "id",
3714            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3715        )]),
3716        sql: "
3717IN CLUSTER mz_catalog_server
3718WITH (
3719    ASSERT NOT NULL id
3720) AS
3721SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
3722FROM mz_internal.mz_catalog_raw
3723WHERE
3724    data->>'kind' = 'ClusterReplica' AND
3725    (data->'value'->'config'->'location'->'Managed'->>'internal')::bool = true",
3726        access: vec![PUBLIC_SELECT],
3727    });
3728
3729pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
3730    LazyLock::new(|| BuiltinMaterializedView {
3731        name: "mz_pending_cluster_replicas",
3732        schema: MZ_INTERNAL_SCHEMA,
3733        oid: oid::MV_MZ_PENDING_CLUSTER_REPLICAS_OID,
3734        desc: RelationDesc::builder()
3735            .with_column("id", SqlScalarType::String.nullable(false))
3736            .with_key(vec![0])
3737            .finish(),
3738        column_comments: BTreeMap::from_iter([(
3739            "id",
3740            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3741        )]),
3742        sql: "
3743IN CLUSTER mz_catalog_server
3744WITH (
3745    ASSERT NOT NULL id
3746) AS
3747SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
3748FROM mz_internal.mz_catalog_raw
3749WHERE
3750    data->>'kind' = 'ClusterReplica' AND
3751    (data->'value'->'config'->'location'->'Managed'->>'pending')::bool = true",
3752        access: vec![PUBLIC_SELECT],
3753    });
3754
3755pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3756    BuiltinSource {
3757        name: "mz_cluster_replica_status_history",
3758        schema: MZ_INTERNAL_SCHEMA,
3759        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3760        data_source: IntrospectionType::ReplicaStatusHistory.into(),
3761        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3762        column_comments: BTreeMap::from_iter([
3763            ("replica_id", "The ID of a cluster replica."),
3764            ("process_id", "The ID of a process within the replica."),
3765            (
3766                "status",
3767                "The status of the cluster replica: `online` or `offline`.",
3768            ),
3769            (
3770                "reason",
3771                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3772            ),
3773            (
3774                "occurred_at",
3775                "Wall-clock timestamp at which the event occurred.",
3776            ),
3777        ]),
3778        is_retained_metrics_object: false,
3779        access: vec![PUBLIC_SELECT],
3780    }
3781});
3782
3783pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
3784    || {
3785        BuiltinContinualTask {
3786            name: "mz_cluster_replica_status_history_ct",
3787            schema: MZ_INTERNAL_SCHEMA,
3788            oid: oid::CT_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3789            desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3790            sql: "
3791IN CLUSTER mz_catalog_server
3792ON INPUT mz_internal.mz_cluster_replica_status_history AS (
3793    DELETE FROM mz_internal.mz_cluster_replica_status_history_ct WHERE occurred_at + '30d' < mz_now();
3794    INSERT INTO mz_internal.mz_cluster_replica_status_history_ct SELECT * FROM mz_internal.mz_cluster_replica_status_history;
3795)",
3796            access: vec![PUBLIC_SELECT],
3797        }
3798    },
3799);
3800
3801pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3802    name: "mz_cluster_replica_statuses",
3803    schema: MZ_INTERNAL_SCHEMA,
3804    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
3805    desc: RelationDesc::builder()
3806        .with_column("replica_id", SqlScalarType::String.nullable(false))
3807        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3808        .with_column("status", SqlScalarType::String.nullable(false))
3809        .with_column("reason", SqlScalarType::String.nullable(true))
3810        .with_column(
3811            "updated_at",
3812            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3813        )
3814        .with_key(vec![0, 1])
3815        .finish(),
3816    column_comments: BTreeMap::from_iter([
3817        (
3818            "replica_id",
3819            "Materialize's unique ID for the cluster replica.",
3820        ),
3821        (
3822            "process_id",
3823            "The ID of the process within the cluster replica.",
3824        ),
3825        (
3826            "status",
3827            "The status of the cluster replica: `online` or `offline`.",
3828        ),
3829        (
3830            "reason",
3831            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3832        ),
3833        (
3834            "updated_at",
3835            "The time at which the status was last updated.",
3836        ),
3837    ]),
3838    sql: "
3839SELECT
3840    DISTINCT ON (replica_id, process_id)
3841    replica_id,
3842    process_id,
3843    status,
3844    reason,
3845    occurred_at as updated_at
3846FROM mz_internal.mz_cluster_replica_status_history
3847JOIN mz_cluster_replicas r ON r.id = replica_id
3848ORDER BY replica_id, process_id, occurred_at DESC",
3849    access: vec![PUBLIC_SELECT],
3850});
3851
3852pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3853    name: "mz_cluster_replica_sizes",
3854    schema: MZ_CATALOG_SCHEMA,
3855    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3856    desc: RelationDesc::builder()
3857        .with_column("size", SqlScalarType::String.nullable(false))
3858        .with_column("processes", SqlScalarType::UInt64.nullable(false))
3859        .with_column("workers", SqlScalarType::UInt64.nullable(false))
3860        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(false))
3861        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(false))
3862        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3863        .with_column(
3864            "credits_per_hour",
3865            SqlScalarType::Numeric { max_scale: None }.nullable(false),
3866        )
3867        .finish(),
3868    column_comments: BTreeMap::from_iter([
3869        ("size", "The human-readable replica size."),
3870        ("processes", "The number of processes in the replica."),
3871        (
3872            "workers",
3873            "The number of Timely Dataflow workers per process.",
3874        ),
3875        (
3876            "cpu_nano_cores",
3877            "The CPU allocation per process, in billionths of a vCPU core.",
3878        ),
3879        (
3880            "memory_bytes",
3881            "The RAM allocation per process, in billionths of a vCPU core.",
3882        ),
3883        ("disk_bytes", "The disk allocation per process."),
3884        (
3885            "credits_per_hour",
3886            "The number of compute credits consumed per hour.",
3887        ),
3888    ]),
3889    is_retained_metrics_object: true,
3890    access: vec![PUBLIC_SELECT],
3891});
3892
3893pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3894    name: "mz_audit_events",
3895    schema: MZ_CATALOG_SCHEMA,
3896    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
3897    desc: RelationDesc::builder()
3898        .with_column("id", SqlScalarType::UInt64.nullable(false))
3899        .with_column("event_type", SqlScalarType::String.nullable(false))
3900        .with_column("object_type", SqlScalarType::String.nullable(false))
3901        .with_column("details", SqlScalarType::Jsonb.nullable(false))
3902        .with_column("user", SqlScalarType::String.nullable(true))
3903        .with_column(
3904            "occurred_at",
3905            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3906        )
3907        .with_key(vec![0])
3908        .finish(),
3909    column_comments: BTreeMap::from_iter([
3910        (
3911            "id",
3912            "Materialize's unique, monotonically increasing ID for the event.",
3913        ),
3914        (
3915            "event_type",
3916            "The type of the event: `create`, `drop`, or `alter`.",
3917        ),
3918        (
3919            "object_type",
3920            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
3921        ),
3922        (
3923            "details",
3924            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
3925        ),
3926        (
3927            "user",
3928            "The user who triggered the event, or `NULL` if triggered by the system.",
3929        ),
3930        (
3931            "occurred_at",
3932            "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.",
3933        ),
3934    ]),
3935    is_retained_metrics_object: false,
3936    access: vec![PUBLIC_SELECT],
3937});
3938
3939pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3940    name: "mz_source_status_history",
3941    schema: MZ_INTERNAL_SCHEMA,
3942    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
3943    data_source: IntrospectionType::SourceStatusHistory.into(),
3944    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
3945    column_comments: BTreeMap::from_iter([
3946        (
3947            "occurred_at",
3948            "Wall-clock timestamp of the source status change.",
3949        ),
3950        (
3951            "source_id",
3952            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
3953        ),
3954        (
3955            "status",
3956            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
3957        ),
3958        (
3959            "error",
3960            "If the source is in an error state, the error message.",
3961        ),
3962        (
3963            "details",
3964            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
3965        ),
3966        (
3967            "replica_id",
3968            "The ID of the replica that an instance of a source is running on.",
3969        ),
3970    ]),
3971    is_retained_metrics_object: false,
3972    access: vec![PUBLIC_SELECT],
3973});
3974
3975pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
3976    || BuiltinSource {
3977        name: "mz_aws_privatelink_connection_status_history",
3978        schema: MZ_INTERNAL_SCHEMA,
3979        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
3980        data_source: DataSourceDesc::Introspection(
3981            IntrospectionType::PrivatelinkConnectionStatusHistory,
3982        ),
3983        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
3984        column_comments: BTreeMap::from_iter([
3985            ("occurred_at", "Wall-clock timestamp of the status change."),
3986            (
3987                "connection_id",
3988                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
3989            ),
3990            (
3991                "status",
3992                "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`.",
3993            ),
3994        ]),
3995        is_retained_metrics_object: false,
3996        access: vec![PUBLIC_SELECT],
3997    },
3998);
3999
4000pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| {
4001    BuiltinView {
4002        name: "mz_aws_privatelink_connection_statuses",
4003        schema: MZ_INTERNAL_SCHEMA,
4004        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
4005        desc: RelationDesc::builder()
4006            .with_column("id", SqlScalarType::String.nullable(false))
4007            .with_column("name", SqlScalarType::String.nullable(false))
4008            .with_column(
4009                "last_status_change_at",
4010                SqlScalarType::TimestampTz { precision: None }.nullable(true),
4011            )
4012            .with_column("status", SqlScalarType::String.nullable(true))
4013            .with_key(vec![0])
4014            .finish(),
4015        column_comments: BTreeMap::from_iter([
4016            (
4017                "id",
4018                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
4019            ),
4020            ("name", "The name of the connection."),
4021            (
4022                "last_status_change_at",
4023                "Wall-clock timestamp of the connection status change.",
4024            ),
4025            (
4026                "status",
4027                "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`.",
4028            ),
4029        ]),
4030        sql: "
4031    WITH statuses_w_last_status AS (
4032        SELECT
4033            connection_id,
4034            occurred_at,
4035            status,
4036            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
4037        FROM mz_internal.mz_aws_privatelink_connection_status_history
4038    ),
4039    latest_events AS (
4040        -- Only take the most recent transition for each ID
4041        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
4042        FROM statuses_w_last_status
4043        -- Only keep first status transitions
4044        WHERE status <> last_status OR last_status IS NULL
4045        ORDER BY connection_id, occurred_at DESC
4046    )
4047    SELECT
4048        conns.id,
4049        name,
4050        occurred_at as last_status_change_at,
4051        status
4052    FROM latest_events
4053    JOIN mz_catalog.mz_connections AS conns
4054    ON conns.id = latest_events.connection_id",
4055        access: vec![PUBLIC_SELECT],
4056    }
4057});
4058
4059pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
4060    LazyLock::new(|| BuiltinSource {
4061        name: "mz_statement_execution_history",
4062        schema: MZ_INTERNAL_SCHEMA,
4063        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
4064        data_source: IntrospectionType::StatementExecutionHistory.into(),
4065        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
4066        column_comments: BTreeMap::new(),
4067        is_retained_metrics_object: false,
4068        access: vec![MONITOR_SELECT],
4069    });
4070
4071pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4072    BuiltinView {
4073    name: "mz_statement_execution_history_redacted",
4074    schema: MZ_INTERNAL_SCHEMA,
4075    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
4076    // everything but `params` and `error_message`
4077    desc: RelationDesc::builder()
4078        .with_column("id", SqlScalarType::Uuid.nullable(false))
4079        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4080        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4081        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4082        .with_column("application_name", SqlScalarType::String.nullable(false))
4083        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4084        .with_column("database_name", SqlScalarType::String.nullable(false))
4085        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4086        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4087        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4088        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4089        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4090        .with_column("mz_version", SqlScalarType::String.nullable(false))
4091        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4092        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4093        .with_column("finished_status", SqlScalarType::String.nullable(true))
4094        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4095        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4096        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4097        .finish(),
4098    column_comments: BTreeMap::new(),
4099    sql: "
4100SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
4101cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
4102transient_index_id, mz_version, began_at, finished_at, finished_status,
4103result_size, rows_returned, execution_strategy
4104FROM mz_internal.mz_statement_execution_history",
4105    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
4106}
4107});
4108
4109pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
4110    LazyLock::new(|| BuiltinSource {
4111        name: "mz_prepared_statement_history",
4112        schema: MZ_INTERNAL_SCHEMA,
4113        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
4114        data_source: IntrospectionType::PreparedStatementHistory.into(),
4115        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
4116        column_comments: BTreeMap::new(),
4117        is_retained_metrics_object: false,
4118        access: vec![
4119            SUPPORT_SELECT,
4120            ANALYTICS_SELECT,
4121            MONITOR_REDACTED_SELECT,
4122            MONITOR_SELECT,
4123        ],
4124    });
4125
4126pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4127    name: "mz_sql_text",
4128    schema: MZ_INTERNAL_SCHEMA,
4129    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
4130    desc: MZ_SQL_TEXT_DESC.clone(),
4131    data_source: IntrospectionType::SqlText.into(),
4132    column_comments: BTreeMap::new(),
4133    is_retained_metrics_object: false,
4134    access: vec![MONITOR_SELECT],
4135});
4136
4137pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4138    name: "mz_sql_text_redacted",
4139    schema: MZ_INTERNAL_SCHEMA,
4140    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
4141    desc: RelationDesc::builder()
4142        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4143        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4144        .finish(),
4145    column_comments: BTreeMap::new(),
4146    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
4147    access: vec![
4148        MONITOR_SELECT,
4149        MONITOR_REDACTED_SELECT,
4150        SUPPORT_SELECT,
4151        ANALYTICS_SELECT,
4152    ],
4153});
4154
4155pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
4156    BuiltinView {
4157        name: "mz_recent_sql_text",
4158        schema: MZ_INTERNAL_SCHEMA,
4159        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
4160        // This should always be 1 day more than the interval in
4161        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
4162        // is rounded down to the nearest day.  Thus something that actually happened three days ago
4163        // could have a `prepared day` anywhere from 3 to 4 days back.
4164        desc: RelationDesc::builder()
4165            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4166            .with_column("sql", SqlScalarType::String.nullable(false))
4167            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4168            .with_key(vec![0, 1, 2])
4169            .finish(),
4170        column_comments: BTreeMap::new(),
4171        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
4172        access: vec![MONITOR_SELECT],
4173    }
4174});
4175
4176pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4177    name: "mz_recent_sql_text_redacted",
4178    schema: MZ_INTERNAL_SCHEMA,
4179    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
4180    desc: RelationDesc::builder()
4181        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4182        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4183        .finish(),
4184    column_comments: BTreeMap::new(),
4185    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
4186    access: vec![
4187        MONITOR_SELECT,
4188        MONITOR_REDACTED_SELECT,
4189        SUPPORT_SELECT,
4190        ANALYTICS_SELECT,
4191    ],
4192});
4193
4194pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
4195    name: "mz_recent_sql_text_ind",
4196    schema: MZ_INTERNAL_SCHEMA,
4197    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
4198    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4199    is_retained_metrics_object: false,
4200});
4201
4202pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4203    name: "mz_session_history",
4204    schema: MZ_INTERNAL_SCHEMA,
4205    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4206    data_source: IntrospectionType::SessionHistory.into(),
4207    desc: MZ_SESSION_HISTORY_DESC.clone(),
4208    column_comments: BTreeMap::from_iter([
4209        (
4210            "session_id",
4211            "The globally unique ID of the session. Corresponds to `mz_sessions.id`.",
4212        ),
4213        (
4214            "connected_at",
4215            "The time at which the session was established.",
4216        ),
4217        (
4218            "initial_application_name",
4219            "The `application_name` session metadata field.",
4220        ),
4221        (
4222            "authenticated_user",
4223            "The name of the user for which the session was established.",
4224        ),
4225    ]),
4226    is_retained_metrics_object: false,
4227    access: vec![PUBLIC_SELECT],
4228});
4229
4230pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4231    BuiltinView {
4232        name: "mz_activity_log_thinned",
4233        schema: MZ_INTERNAL_SCHEMA,
4234        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
4235        desc: RelationDesc::builder()
4236            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4237            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4238            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4239            .with_column("application_name", SqlScalarType::String.nullable(false))
4240            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4241            .with_column("database_name", SqlScalarType::String.nullable(false))
4242            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4243            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4244            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4245            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4246            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4247            .with_column("mz_version", SqlScalarType::String.nullable(false))
4248            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4249            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4250            .with_column("finished_status", SqlScalarType::String.nullable(true))
4251            .with_column("error_message", SqlScalarType::String.nullable(true))
4252            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4253            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4254            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4255            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4256            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4257            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4258            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4259            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4260            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4261            .with_column("statement_type", SqlScalarType::String.nullable(true))
4262            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4263            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4264            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4265            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4266            .finish(),
4267        column_comments: BTreeMap::new(),
4268        sql: "
4269SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
4270transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
4271error_message, result_size, rows_returned, execution_strategy, transaction_id,
4272mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
4273mpsh.session_id, prepared_at, statement_type, throttled_count,
4274connected_at, initial_application_name, authenticated_user
4275FROM mz_internal.mz_statement_execution_history mseh,
4276     mz_internal.mz_prepared_statement_history mpsh,
4277     mz_internal.mz_session_history msh
4278WHERE mseh.prepared_statement_id = mpsh.id
4279AND mpsh.session_id = msh.session_id",
4280        access: vec![MONITOR_SELECT],
4281    }
4282});
4283
4284pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4285    BuiltinView {
4286        name: "mz_recent_activity_log_thinned",
4287        schema: MZ_INTERNAL_SCHEMA,
4288        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
4289        desc: RelationDesc::builder()
4290            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4291            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4292            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4293            .with_column("application_name", SqlScalarType::String.nullable(false))
4294            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4295            .with_column("database_name", SqlScalarType::String.nullable(false))
4296            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4297            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4298            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4299            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4300            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4301            .with_column("mz_version", SqlScalarType::String.nullable(false))
4302            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4303            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4304            .with_column("finished_status", SqlScalarType::String.nullable(true))
4305            .with_column("error_message", SqlScalarType::String.nullable(true))
4306            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4307            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4308            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4309            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4310            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4311            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4312            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4313            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4314            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4315            .with_column("statement_type", SqlScalarType::String.nullable(true))
4316            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4317            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4318            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4319            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4320            .finish(),
4321        column_comments: BTreeMap::new(),
4322        // We use a temporal window of 2 days rather than 1 day for `mz_session_history`'s `connected_at` since a statement execution at
4323        // 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.
4324        sql:
4325        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
4326AND began_at + INTERVAL '1 day' > mz_now() AND connected_at + INTERVAL '2 days' > mz_now()",
4327        access: vec![MONITOR_SELECT],
4328    }
4329});
4330
4331pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4332    name: "mz_recent_activity_log",
4333    schema: MZ_INTERNAL_SCHEMA,
4334    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
4335    desc: RelationDesc::builder()
4336        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4337        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4338        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4339        .with_column("application_name", SqlScalarType::String.nullable(false))
4340        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4341        .with_column("database_name", SqlScalarType::String.nullable(false))
4342        .with_column(
4343            "search_path",
4344            SqlScalarType::List {
4345                element_type: Box::new(SqlScalarType::String),
4346                custom_id: None,
4347            }
4348            .nullable(false),
4349        )
4350        .with_column(
4351            "transaction_isolation",
4352            SqlScalarType::String.nullable(false),
4353        )
4354        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4355        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4356        .with_column(
4357            "params",
4358            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
4359        )
4360        .with_column("mz_version", SqlScalarType::String.nullable(false))
4361        .with_column(
4362            "began_at",
4363            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4364        )
4365        .with_column(
4366            "finished_at",
4367            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4368        )
4369        .with_column("finished_status", SqlScalarType::String.nullable(true))
4370        .with_column("error_message", SqlScalarType::String.nullable(true))
4371        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4372        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4373        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4374        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4375        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4376        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4377        .with_column(
4378            "prepared_statement_name",
4379            SqlScalarType::String.nullable(false),
4380        )
4381        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4382        .with_column(
4383            "prepared_at",
4384            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4385        )
4386        .with_column("statement_type", SqlScalarType::String.nullable(true))
4387        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4388        .with_column(
4389            "connected_at",
4390            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4391        )
4392        .with_column(
4393            "initial_application_name",
4394            SqlScalarType::String.nullable(false),
4395        )
4396        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4397        .with_column("sql", SqlScalarType::String.nullable(false))
4398        .finish(),
4399    column_comments: BTreeMap::from_iter([
4400        (
4401            "execution_id",
4402            "An ID that is unique for each executed statement.",
4403        ),
4404        (
4405            "sample_rate",
4406            "The actual rate at which the statement was sampled.",
4407        ),
4408        (
4409            "cluster_id",
4410            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
4411        ),
4412        (
4413            "application_name",
4414            "The value of the `application_name` configuration parameter at execution time.",
4415        ),
4416        (
4417            "cluster_name",
4418            "The name of the cluster with ID `cluster_id` at execution time.",
4419        ),
4420        (
4421            "database_name",
4422            "The value of the `database` configuration parameter at execution time.",
4423        ),
4424        (
4425            "search_path",
4426            "The value of the `search_path` configuration parameter at execution time.",
4427        ),
4428        (
4429            "transaction_isolation",
4430            "The value of the `transaction_isolation` configuration parameter at execution time.",
4431        ),
4432        (
4433            "execution_timestamp",
4434            "The logical timestamp at which execution was scheduled.",
4435        ),
4436        (
4437            "transient_index_id",
4438            "The internal index of the compute dataflow created for the query, if any.",
4439        ),
4440        (
4441            "params",
4442            "The parameters with which the statement was executed.",
4443        ),
4444        (
4445            "mz_version",
4446            "The version of Materialize that was running when the statement was executed.",
4447        ),
4448        (
4449            "began_at",
4450            "The wall-clock time at which the statement began executing.",
4451        ),
4452        (
4453            "finished_at",
4454            "The wall-clock time at which the statement finished executing.",
4455        ),
4456        (
4457            "finished_status",
4458            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). `aborted` means that Materialize exited before the statement finished executing.",
4459        ),
4460        (
4461            "error_message",
4462            "The error message, if the statement failed.",
4463        ),
4464        (
4465            "result_size",
4466            "The size in bytes of the result, for statements that return rows.",
4467        ),
4468        (
4469            "rows_returned",
4470            "The number of rows returned, for statements that return rows.",
4471        ),
4472        (
4473            "execution_strategy",
4474            "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.",
4475        ),
4476        (
4477            "transaction_id",
4478            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
4479        ),
4480        (
4481            "prepared_statement_id",
4482            "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`).",
4483        ),
4484        (
4485            "sql_hash",
4486            "An opaque value uniquely identifying the text of the query.",
4487        ),
4488        (
4489            "prepared_statement_name",
4490            "The name given by the client library to the prepared statement.",
4491        ),
4492        (
4493            "session_id",
4494            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
4495        ),
4496        (
4497            "prepared_at",
4498            "The time at which the statement was prepared.",
4499        ),
4500        (
4501            "statement_type",
4502            "The _type_ of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
4503        ),
4504        (
4505            "throttled_count",
4506            "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.",
4507        ),
4508        (
4509            "connected_at",
4510            "The time at which the session was established.",
4511        ),
4512        (
4513            "initial_application_name",
4514            "The initial value of `application_name` at the beginning of the session.",
4515        ),
4516        (
4517            "authenticated_user",
4518            "The name of the user for which the session was established.",
4519        ),
4520        ("sql", "The SQL text of the statement."),
4521    ]),
4522    sql: "SELECT mralt.*, mrst.sql
4523FROM mz_internal.mz_recent_activity_log_thinned mralt,
4524     mz_internal.mz_recent_sql_text mrst
4525WHERE mralt.sql_hash = mrst.sql_hash",
4526    access: vec![MONITOR_SELECT],
4527});
4528
4529pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4530    BuiltinView {
4531    name: "mz_recent_activity_log_redacted",
4532    schema: MZ_INTERNAL_SCHEMA,
4533    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
4534    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
4535    desc: RelationDesc::builder()
4536        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4537        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4538        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4539        .with_column("application_name", SqlScalarType::String.nullable(false))
4540        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4541        .with_column("database_name", SqlScalarType::String.nullable(false))
4542        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4543        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4544        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4545        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4546        .with_column("mz_version", SqlScalarType::String.nullable(false))
4547        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4548        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4549        .with_column("finished_status", SqlScalarType::String.nullable(true))
4550        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4551        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4552        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4553        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4554        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4555        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4556        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4557        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4558        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4559        .with_column("statement_type", SqlScalarType::String.nullable(true))
4560        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4561        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4562        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4563        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4564        .finish(),
4565    column_comments: BTreeMap::new(),
4566    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4567    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4568    mralt.transient_index_id, mralt.mz_version, mralt.began_at, mralt.finished_at,
4569    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4570    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4571    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4572    mralt.initial_application_name, mralt.authenticated_user,
4573    mrst.redacted_sql
4574FROM mz_internal.mz_recent_activity_log_thinned mralt,
4575     mz_internal.mz_recent_sql_text mrst
4576WHERE mralt.sql_hash = mrst.sql_hash",
4577    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4578}
4579});
4580
4581pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4582    BuiltinSource {
4583        name: "mz_statement_lifecycle_history",
4584        schema: MZ_INTERNAL_SCHEMA,
4585        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4586        desc: RelationDesc::builder()
4587            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
4588            .with_column("event_type", SqlScalarType::String.nullable(false))
4589            .with_column(
4590                "occurred_at",
4591                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4592            )
4593            .finish(),
4594        data_source: IntrospectionType::StatementLifecycleHistory.into(),
4595        column_comments: BTreeMap::from_iter([
4596            (
4597                "statement_id",
4598                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4599            ),
4600            (
4601                "event_type",
4602                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4603            ),
4604            ("occurred_at", "The time at which the event took place."),
4605        ]),
4606        is_retained_metrics_object: false,
4607        // TODO[btv]: Maybe this should be public instead of
4608        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4609        // change, we probably don't need to worry about it now.
4610        access: vec![
4611            SUPPORT_SELECT,
4612            ANALYTICS_SELECT,
4613            MONITOR_REDACTED_SELECT,
4614            MONITOR_SELECT,
4615        ],
4616    }
4617});
4618
4619pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4620    name: "mz_source_statuses",
4621    schema: MZ_INTERNAL_SCHEMA,
4622    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4623    desc: RelationDesc::builder()
4624        .with_column("id", SqlScalarType::String.nullable(false))
4625        .with_column("name", SqlScalarType::String.nullable(false))
4626        .with_column("type", SqlScalarType::String.nullable(false))
4627        .with_column(
4628            "last_status_change_at",
4629            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4630        )
4631        .with_column("status", SqlScalarType::String.nullable(false))
4632        .with_column("error", SqlScalarType::String.nullable(true))
4633        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4634        .finish(),
4635    column_comments: BTreeMap::from_iter([
4636        (
4637            "id",
4638            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4639        ),
4640        ("name", "The name of the source."),
4641        ("type", "The type of the source."),
4642        (
4643            "last_status_change_at",
4644            "Wall-clock timestamp of the source status change.",
4645        ),
4646        (
4647            "status",
4648            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4649        ),
4650        (
4651            "error",
4652            "If the source is in an error state, the error message.",
4653        ),
4654        (
4655            "details",
4656            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4657        ),
4658    ]),
4659    sql: "
4660    WITH
4661    -- The status history contains per-replica events and source-global events.
4662    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4663    -- we can treat them uniformly below.
4664    uniform_status_history AS
4665    (
4666        SELECT
4667            s.source_id,
4668            COALESCE(s.replica_id, '<source>') as replica_id,
4669            s.occurred_at,
4670            s.status,
4671            s.error,
4672            s.details
4673        FROM mz_internal.mz_source_status_history s
4674    ),
4675    -- For getting the latest events, we first determine the latest per-replica
4676    -- events here and then apply precedence rules below.
4677    latest_per_replica_events AS
4678    (
4679        SELECT DISTINCT ON (source_id, replica_id)
4680            occurred_at, source_id, replica_id, status, error, details
4681        FROM uniform_status_history
4682        ORDER BY source_id, replica_id, occurred_at DESC
4683    ),
4684    -- We have a precedence list that determines the overall status in case
4685    -- there is differing per-replica (including source-global) statuses. If
4686    -- there is no 'dropped' status, and any replica reports 'running', the
4687    -- overall status is 'running' even if there might be some replica that has
4688    -- errors or is paused.
4689    latest_events AS
4690    (
4691       SELECT DISTINCT ON (source_id)
4692            source_id,
4693            occurred_at,
4694            status,
4695            error,
4696            details
4697        FROM latest_per_replica_events
4698        ORDER BY source_id, CASE status
4699                    WHEN 'dropped' THEN 1
4700                    WHEN 'running' THEN 2
4701                    WHEN 'stalled' THEN 3
4702                    WHEN 'starting' THEN 4
4703                    WHEN 'paused' THEN 5
4704                    WHEN 'ceased' THEN 6
4705                    ELSE 7  -- For any other status values
4706                END
4707    ),
4708    -- Determine which sources are subsources and which are parent sources
4709    subsources AS
4710    (
4711        SELECT subsources.id AS self, sources.id AS parent
4712        FROM
4713            mz_catalog.mz_sources AS subsources
4714                JOIN
4715                    mz_internal.mz_object_dependencies AS deps
4716                    ON subsources.id = deps.object_id
4717                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4718    ),
4719    -- Determine which sources are source tables
4720    tables AS
4721    (
4722        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4723        FROM mz_catalog.mz_tables AS tables
4724        WHERE tables.source_id IS NOT NULL
4725    ),
4726    -- Determine which collection's ID to use for the status
4727    id_of_status_to_use AS
4728    (
4729        SELECT
4730            self_events.source_id,
4731            -- If self not errored, but parent is, use parent; else self
4732            CASE
4733                WHEN
4734                    self_events.status <> 'ceased' AND
4735                    parent_events.status = 'stalled'
4736                THEN parent_events.source_id
4737                ELSE self_events.source_id
4738            END AS id_to_use
4739        FROM
4740            latest_events AS self_events
4741                LEFT JOIN subsources ON self_events.source_id = subsources.self
4742                LEFT JOIN tables ON self_events.source_id = tables.self
4743                LEFT JOIN
4744                    latest_events AS parent_events
4745                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4746    ),
4747    -- Swap out events for the ID of the event we plan to use instead
4748    latest_events_to_use AS
4749    (
4750        SELECT occurred_at, s.source_id, status, error, details
4751        FROM
4752            id_of_status_to_use AS s
4753                JOIN latest_events AS e ON e.source_id = s.id_to_use
4754    ),
4755    combined AS (
4756        SELECT
4757            mz_sources.id,
4758            mz_sources.name,
4759            mz_sources.type,
4760            occurred_at,
4761            status,
4762            error,
4763            details
4764        FROM
4765            mz_catalog.mz_sources
4766            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4767        UNION ALL
4768        SELECT
4769            tables.self AS id,
4770            tables.name,
4771            'table' AS type,
4772            occurred_at,
4773            status,
4774            error,
4775            details
4776        FROM
4777            tables
4778            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4779    )
4780SELECT
4781    id,
4782    name,
4783    type,
4784    occurred_at AS last_status_change_at,
4785    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4786    CASE
4787        WHEN
4788            type = 'webhook' OR
4789            type = 'progress'
4790        THEN 'running'
4791        ELSE COALESCE(status, 'created')
4792    END AS status,
4793    error,
4794    details
4795FROM combined
4796WHERE id NOT LIKE 's%';",
4797    access: vec![PUBLIC_SELECT],
4798});
4799
4800pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4801    name: "mz_sink_status_history",
4802    schema: MZ_INTERNAL_SCHEMA,
4803    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4804    data_source: IntrospectionType::SinkStatusHistory.into(),
4805    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4806    column_comments: BTreeMap::from_iter([
4807        (
4808            "occurred_at",
4809            "Wall-clock timestamp of the sink status change.",
4810        ),
4811        (
4812            "sink_id",
4813            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4814        ),
4815        (
4816            "status",
4817            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4818        ),
4819        (
4820            "error",
4821            "If the sink is in an error state, the error message.",
4822        ),
4823        (
4824            "details",
4825            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4826        ),
4827        (
4828            "replica_id",
4829            "The ID of the replica that an instance of a sink is running on.",
4830        ),
4831    ]),
4832    is_retained_metrics_object: false,
4833    access: vec![PUBLIC_SELECT],
4834});
4835
4836pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4837    name: "mz_sink_statuses",
4838    schema: MZ_INTERNAL_SCHEMA,
4839    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4840    desc: RelationDesc::builder()
4841        .with_column("id", SqlScalarType::String.nullable(false))
4842        .with_column("name", SqlScalarType::String.nullable(false))
4843        .with_column("type", SqlScalarType::String.nullable(false))
4844        .with_column(
4845            "last_status_change_at",
4846            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4847        )
4848        .with_column("status", SqlScalarType::String.nullable(false))
4849        .with_column("error", SqlScalarType::String.nullable(true))
4850        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4851        .finish(),
4852    column_comments: BTreeMap::from_iter([
4853        (
4854            "id",
4855            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4856        ),
4857        ("name", "The name of the sink."),
4858        ("type", "The type of the sink."),
4859        (
4860            "last_status_change_at",
4861            "Wall-clock timestamp of the sink status change.",
4862        ),
4863        (
4864            "status",
4865            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4866        ),
4867        (
4868            "error",
4869            "If the sink is in an error state, the error message.",
4870        ),
4871        (
4872            "details",
4873            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4874        ),
4875    ]),
4876    sql: "
4877WITH
4878-- The status history contains per-replica events and sink-global events.
4879-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
4880-- we can treat them uniformly below.
4881uniform_status_history AS
4882(
4883    SELECT
4884        s.sink_id,
4885        COALESCE(s.replica_id, '<sink>') as replica_id,
4886        s.occurred_at,
4887        s.status,
4888        s.error,
4889        s.details
4890    FROM mz_internal.mz_sink_status_history s
4891),
4892-- For getting the latest events, we first determine the latest per-replica
4893-- events here and then apply precedence rules below.
4894latest_per_replica_events AS
4895(
4896    SELECT DISTINCT ON (sink_id, replica_id)
4897        occurred_at, sink_id, replica_id, status, error, details
4898    FROM uniform_status_history
4899    ORDER BY sink_id, replica_id, occurred_at DESC
4900),
4901-- We have a precedence list that determines the overall status in case
4902-- there is differing per-replica (including sink-global) statuses. If
4903-- there is no 'dropped' status, and any replica reports 'running', the
4904-- overall status is 'running' even if there might be some replica that has
4905-- errors or is paused.
4906latest_events AS
4907(
4908    SELECT DISTINCT ON (sink_id)
4909        sink_id,
4910        occurred_at,
4911        status,
4912        error,
4913        details
4914    FROM latest_per_replica_events
4915    ORDER BY sink_id, CASE status
4916                WHEN 'dropped' THEN 1
4917                WHEN 'running' THEN 2
4918                WHEN 'stalled' THEN 3
4919                WHEN 'starting' THEN 4
4920                WHEN 'paused' THEN 5
4921                WHEN 'ceased' THEN 6
4922                ELSE 7  -- For any other status values
4923            END
4924)
4925SELECT
4926    mz_sinks.id,
4927    name,
4928    mz_sinks.type,
4929    occurred_at as last_status_change_at,
4930    coalesce(status, 'created') as status,
4931    error,
4932    details
4933FROM mz_catalog.mz_sinks
4934LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
4935WHERE
4936    -- This is a convenient way to filter out system sinks, like the status_history table itself.
4937    mz_sinks.id NOT LIKE 's%'",
4938    access: vec![PUBLIC_SELECT],
4939});
4940
4941pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
4942    LazyLock::new(|| SystemObjectDescription {
4943        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
4944        object_type: CatalogItemType::Table,
4945        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
4946    });
4947
4948pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4949    name: "mz_storage_usage_by_shard",
4950    schema: MZ_INTERNAL_SCHEMA,
4951    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
4952    desc: RelationDesc::builder()
4953        .with_column("id", SqlScalarType::UInt64.nullable(false))
4954        .with_column("shard_id", SqlScalarType::String.nullable(true))
4955        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
4956        .with_column(
4957            "collection_timestamp",
4958            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4959        )
4960        .finish(),
4961    column_comments: BTreeMap::new(),
4962    is_retained_metrics_object: false,
4963    access: vec![PUBLIC_SELECT],
4964});
4965
4966pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4967    name: "mz_egress_ips",
4968    schema: MZ_CATALOG_SCHEMA,
4969    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
4970    desc: RelationDesc::builder()
4971        .with_column("egress_ip", SqlScalarType::String.nullable(false))
4972        .with_column("prefix_length", SqlScalarType::Int32.nullable(false))
4973        .with_column("cidr", SqlScalarType::String.nullable(false))
4974        .finish(),
4975    column_comments: BTreeMap::from_iter([
4976        ("egress_ip", "The start of the range of IP addresses."),
4977        (
4978            "prefix_length",
4979            "The number of leading bits in the CIDR netmask.",
4980        ),
4981        ("cidr", "The CIDR representation."),
4982    ]),
4983    is_retained_metrics_object: false,
4984    access: vec![PUBLIC_SELECT],
4985});
4986
4987pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
4988    LazyLock::new(|| BuiltinTable {
4989        name: "mz_aws_privatelink_connections",
4990        schema: MZ_CATALOG_SCHEMA,
4991        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
4992        desc: RelationDesc::builder()
4993            .with_column("id", SqlScalarType::String.nullable(false))
4994            .with_column("principal", SqlScalarType::String.nullable(false))
4995            .finish(),
4996        column_comments: BTreeMap::from_iter([
4997            ("id", "The ID of the connection."),
4998            (
4999                "principal",
5000                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
5001            ),
5002        ]),
5003        is_retained_metrics_object: false,
5004        access: vec![PUBLIC_SELECT],
5005    });
5006
5007pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5008    name: "mz_aws_connections",
5009    schema: MZ_INTERNAL_SCHEMA,
5010    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
5011    desc: RelationDesc::builder()
5012        .with_column("id", SqlScalarType::String.nullable(false))
5013        .with_column("endpoint", SqlScalarType::String.nullable(true))
5014        .with_column("region", SqlScalarType::String.nullable(true))
5015        .with_column("access_key_id", SqlScalarType::String.nullable(true))
5016        .with_column(
5017            "access_key_id_secret_id",
5018            SqlScalarType::String.nullable(true),
5019        )
5020        .with_column(
5021            "secret_access_key_secret_id",
5022            SqlScalarType::String.nullable(true),
5023        )
5024        .with_column("session_token", SqlScalarType::String.nullable(true))
5025        .with_column(
5026            "session_token_secret_id",
5027            SqlScalarType::String.nullable(true),
5028        )
5029        .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
5030        .with_column(
5031            "assume_role_session_name",
5032            SqlScalarType::String.nullable(true),
5033        )
5034        .with_column("principal", SqlScalarType::String.nullable(true))
5035        .with_column("external_id", SqlScalarType::String.nullable(true))
5036        .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
5037        .finish(),
5038    column_comments: BTreeMap::from_iter([
5039        ("id", "The ID of the connection."),
5040        ("endpoint", "The value of the `ENDPOINT` option, if set."),
5041        ("region", "The value of the `REGION` option, if set."),
5042        (
5043            "access_key_id",
5044            "The value of the `ACCESS KEY ID` option, if provided in line.",
5045        ),
5046        (
5047            "access_key_id_secret_id",
5048            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
5049        ),
5050        (
5051            "secret_access_key_secret_id",
5052            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
5053        ),
5054        (
5055            "session_token",
5056            "The value of the `SESSION TOKEN` option, if provided in line.",
5057        ),
5058        (
5059            "session_token_secret_id",
5060            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
5061        ),
5062        (
5063            "assume_role_arn",
5064            "The value of the `ASSUME ROLE ARN` option, if set.",
5065        ),
5066        (
5067            "assume_role_session_name",
5068            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
5069        ),
5070        (
5071            "principal",
5072            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
5073        ),
5074        (
5075            "external_id",
5076            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
5077        ),
5078        (
5079            "example_trust_policy",
5080            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
5081        ),
5082    ]),
5083    is_retained_metrics_object: false,
5084    access: vec![PUBLIC_SELECT],
5085});
5086
5087pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
5088    LazyLock::new(|| BuiltinSource {
5089        name: "mz_cluster_replica_metrics_history",
5090        schema: MZ_INTERNAL_SCHEMA,
5091        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
5092        data_source: IntrospectionType::ReplicaMetricsHistory.into(),
5093        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
5094        column_comments: BTreeMap::from_iter([
5095            ("replica_id", "The ID of a cluster replica."),
5096            ("process_id", "The ID of a process within the replica."),
5097            (
5098                "cpu_nano_cores",
5099                "Approximate CPU usage, in billionths of a vCPU core.",
5100            ),
5101            ("memory_bytes", "Approximate memory usage, in bytes."),
5102            ("disk_bytes", "Approximate disk usage, in bytes."),
5103            (
5104                "occurred_at",
5105                "Wall-clock timestamp at which the event occurred.",
5106            ),
5107            (
5108                "heap_bytes",
5109                "Approximate heap (RAM + swap) usage, in bytes.",
5110            ),
5111            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
5112        ]),
5113        is_retained_metrics_object: false,
5114        access: vec![PUBLIC_SELECT],
5115    });
5116
5117pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
5118    || {
5119        BuiltinContinualTask {
5120            name: "mz_cluster_replica_metrics_history_ct",
5121            schema: MZ_INTERNAL_SCHEMA,
5122            oid: oid::CT_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
5123            desc: REPLICA_METRICS_HISTORY_DESC.clone(),
5124            sql: "
5125IN CLUSTER mz_catalog_server
5126ON INPUT mz_internal.mz_cluster_replica_metrics_history AS (
5127    DELETE FROM mz_internal.mz_cluster_replica_metrics_history_ct WHERE occurred_at + '30d' < mz_now();
5128    INSERT INTO mz_internal.mz_cluster_replica_metrics_history_ct SELECT * FROM mz_internal.mz_cluster_replica_metrics_history;
5129)",
5130            access: vec![PUBLIC_SELECT],
5131        }
5132    },
5133);
5134
5135pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5136    name: "mz_cluster_replica_metrics",
5137    schema: MZ_INTERNAL_SCHEMA,
5138    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
5139    desc: RelationDesc::builder()
5140        .with_column("replica_id", SqlScalarType::String.nullable(false))
5141        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
5142        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
5143        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
5144        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
5145        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
5146        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
5147        .with_key(vec![0, 1])
5148        .finish(),
5149    column_comments: BTreeMap::from_iter([
5150        ("replica_id", "The ID of a cluster replica."),
5151        ("process_id", "The ID of a process within the replica."),
5152        (
5153            "cpu_nano_cores",
5154            "Approximate CPU usage, in billionths of a vCPU core.",
5155        ),
5156        ("memory_bytes", "Approximate RAM usage, in bytes."),
5157        ("disk_bytes", "Approximate disk usage, in bytes."),
5158        (
5159            "heap_bytes",
5160            "Approximate heap (RAM + swap) usage, in bytes.",
5161        ),
5162        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
5163    ]),
5164    sql: "
5165SELECT
5166    DISTINCT ON (replica_id, process_id)
5167    replica_id,
5168    process_id,
5169    cpu_nano_cores,
5170    memory_bytes,
5171    disk_bytes,
5172    heap_bytes,
5173    heap_limit
5174FROM mz_internal.mz_cluster_replica_metrics_history
5175JOIN mz_cluster_replicas r ON r.id = replica_id
5176ORDER BY replica_id, process_id, occurred_at DESC",
5177    access: vec![PUBLIC_SELECT],
5178});
5179
5180pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
5181    LazyLock::new(|| BuiltinSource {
5182        name: "mz_cluster_replica_frontiers",
5183        schema: MZ_CATALOG_SCHEMA,
5184        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
5185        data_source: IntrospectionType::ReplicaFrontiers.into(),
5186        desc: RelationDesc::builder()
5187            .with_column("object_id", SqlScalarType::String.nullable(false))
5188            .with_column("replica_id", SqlScalarType::String.nullable(false))
5189            .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5190            .finish(),
5191        column_comments: BTreeMap::from_iter([
5192            (
5193                "object_id",
5194                "The ID of the source, sink, index, materialized view, or subscription.",
5195            ),
5196            ("replica_id", "The ID of a cluster replica."),
5197            (
5198                "write_frontier",
5199                "The next timestamp at which the output may change.",
5200            ),
5201        ]),
5202        is_retained_metrics_object: false,
5203        access: vec![PUBLIC_SELECT],
5204    });
5205
5206pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
5207    LazyLock::new(|| BuiltinIndex {
5208        name: "mz_cluster_replica_frontiers_ind",
5209        schema: MZ_CATALOG_SCHEMA,
5210        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
5211        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
5212        is_retained_metrics_object: false,
5213    });
5214
5215pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5216    name: "mz_frontiers",
5217    schema: MZ_INTERNAL_SCHEMA,
5218    oid: oid::SOURCE_MZ_FRONTIERS_OID,
5219    data_source: IntrospectionType::Frontiers.into(),
5220    desc: RelationDesc::builder()
5221        .with_column("object_id", SqlScalarType::String.nullable(false))
5222        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
5223        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5224        .finish(),
5225    column_comments: BTreeMap::from_iter([
5226        (
5227            "object_id",
5228            "The ID of the source, sink, table, index, materialized view, or subscription.",
5229        ),
5230        (
5231            "read_frontier",
5232            "The earliest timestamp at which the output is still readable.",
5233        ),
5234        (
5235            "write_frontier",
5236            "The next timestamp at which the output may change.",
5237        ),
5238    ]),
5239    is_retained_metrics_object: false,
5240    access: vec![PUBLIC_SELECT],
5241});
5242
5243/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
5244pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5245    name: "mz_global_frontiers",
5246    schema: MZ_INTERNAL_SCHEMA,
5247    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5248    desc: RelationDesc::builder()
5249        .with_column("object_id", SqlScalarType::String.nullable(false))
5250        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
5251        .finish(),
5252    column_comments: BTreeMap::new(),
5253    sql: "
5254SELECT object_id, write_frontier AS time
5255FROM mz_internal.mz_frontiers
5256WHERE write_frontier IS NOT NULL",
5257    access: vec![PUBLIC_SELECT],
5258});
5259
5260pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5261    name: "mz_wallclock_lag_history",
5262    schema: MZ_INTERNAL_SCHEMA,
5263    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5264    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5265    data_source: IntrospectionType::WallclockLagHistory.into(),
5266    column_comments: BTreeMap::from_iter([
5267        (
5268            "object_id",
5269            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5270        ),
5271        (
5272            "replica_id",
5273            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5274        ),
5275        (
5276            "lag",
5277            "The amount of time the object's write frontier lags behind wallclock time.",
5278        ),
5279        (
5280            "occurred_at",
5281            "Wall-clock timestamp at which the event occurred.",
5282        ),
5283    ]),
5284    is_retained_metrics_object: false,
5285    access: vec![PUBLIC_SELECT],
5286});
5287
5288pub static MZ_WALLCLOCK_LAG_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(|| {
5289    BuiltinContinualTask {
5290    name: "mz_wallclock_lag_history_ct",
5291    schema: MZ_INTERNAL_SCHEMA,
5292    oid: oid::CT_MZ_WALLCLOCK_LAG_HISTORY_OID,
5293    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5294    sql: "
5295IN CLUSTER mz_catalog_server
5296ON INPUT mz_internal.mz_wallclock_lag_history AS (
5297    DELETE FROM mz_internal.mz_wallclock_lag_history_ct WHERE occurred_at + '30d' < mz_now();
5298    INSERT INTO mz_internal.mz_wallclock_lag_history_ct SELECT * FROM mz_internal.mz_wallclock_lag_history;
5299)",
5300            access: vec![PUBLIC_SELECT],
5301        }
5302});
5303
5304pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5305    name: "mz_wallclock_global_lag_history",
5306    schema: MZ_INTERNAL_SCHEMA,
5307    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5308    desc: RelationDesc::builder()
5309        .with_column("object_id", SqlScalarType::String.nullable(false))
5310        .with_column("lag", SqlScalarType::Interval.nullable(true))
5311        .with_column(
5312            "occurred_at",
5313            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5314        )
5315        .with_key(vec![0, 2])
5316        .finish(),
5317    column_comments: BTreeMap::from_iter([
5318        (
5319            "object_id",
5320            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5321        ),
5322        (
5323            "lag",
5324            "The minimum wallclock lag observed for the object during the minute.",
5325        ),
5326        (
5327            "occurred_at",
5328            "The minute-aligned timestamp of the observation.",
5329        ),
5330    ]),
5331    sql: "
5332WITH times_binned AS (
5333    SELECT
5334        object_id,
5335        lag,
5336        date_trunc('minute', occurred_at) AS occurred_at
5337    FROM mz_internal.mz_wallclock_lag_history
5338)
5339SELECT
5340    object_id,
5341    min(lag) AS lag,
5342    occurred_at
5343FROM times_binned
5344GROUP BY object_id, occurred_at
5345OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5346    access: vec![PUBLIC_SELECT],
5347});
5348
5349pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| {
5350    BuiltinView {
5351        name: "mz_wallclock_global_lag_recent_history",
5352        schema: MZ_INTERNAL_SCHEMA,
5353        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5354        desc: RelationDesc::builder()
5355            .with_column("object_id", SqlScalarType::String.nullable(false))
5356            .with_column("lag", SqlScalarType::Interval.nullable(true))
5357            .with_column(
5358                "occurred_at",
5359                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5360            )
5361            .with_key(vec![0, 2])
5362            .finish(),
5363        column_comments: BTreeMap::from_iter([
5364            (
5365                "object_id",
5366                "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5367            ),
5368            (
5369                "lag",
5370                "The minimum wallclock lag observed for the object during the minute.",
5371            ),
5372            (
5373                "occurred_at",
5374                "The minute-aligned timestamp of the observation.",
5375            ),
5376        ]),
5377        sql: "
5378SELECT object_id, lag, occurred_at
5379FROM mz_internal.mz_wallclock_global_lag_history
5380WHERE occurred_at + '1 day' > mz_now()",
5381        access: vec![PUBLIC_SELECT],
5382    }
5383});
5384
5385pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5386    name: "mz_wallclock_global_lag",
5387    schema: MZ_INTERNAL_SCHEMA,
5388    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5389    desc: RelationDesc::builder()
5390        .with_column("object_id", SqlScalarType::String.nullable(false))
5391        .with_column("lag", SqlScalarType::Interval.nullable(true))
5392        .with_key(vec![0])
5393        .finish(),
5394    column_comments: BTreeMap::from_iter([
5395        (
5396            "object_id",
5397            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5398        ),
5399        (
5400            "lag",
5401            "The amount of time the object's write frontier lags behind wallclock time.",
5402        ),
5403    ]),
5404    sql: "
5405SELECT DISTINCT ON (object_id) object_id, lag
5406FROM mz_internal.mz_wallclock_global_lag_recent_history
5407WHERE occurred_at + '5 minutes' > mz_now()
5408ORDER BY object_id, occurred_at DESC",
5409    access: vec![PUBLIC_SELECT],
5410});
5411
5412pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5413    LazyLock::new(|| BuiltinSource {
5414        name: "mz_wallclock_global_lag_histogram_raw",
5415        schema: MZ_INTERNAL_SCHEMA,
5416        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5417        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5418        column_comments: BTreeMap::new(),
5419        data_source: IntrospectionType::WallclockLagHistogram.into(),
5420        is_retained_metrics_object: false,
5421        access: vec![PUBLIC_SELECT],
5422    });
5423
5424pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5425    LazyLock::new(|| BuiltinView {
5426        name: "mz_wallclock_global_lag_histogram",
5427        schema: MZ_INTERNAL_SCHEMA,
5428        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5429        desc: RelationDesc::builder()
5430            .with_column(
5431                "period_start",
5432                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5433            )
5434            .with_column(
5435                "period_end",
5436                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5437            )
5438            .with_column("object_id", SqlScalarType::String.nullable(false))
5439            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
5440            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
5441            .with_column("count", SqlScalarType::Int64.nullable(false))
5442            .with_key(vec![0, 1, 2, 3, 4])
5443            .finish(),
5444        column_comments: BTreeMap::new(),
5445        sql: "
5446SELECT *, count(*) AS count
5447FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5448GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5449        access: vec![PUBLIC_SELECT],
5450    });
5451
5452pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5453    BuiltinSource {
5454        name: "mz_materialized_view_refreshes",
5455        schema: MZ_INTERNAL_SCHEMA,
5456        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5457        data_source: DataSourceDesc::Introspection(
5458            IntrospectionType::ComputeMaterializedViewRefreshes,
5459        ),
5460        desc: RelationDesc::builder()
5461            .with_column(
5462                "materialized_view_id",
5463                SqlScalarType::String.nullable(false),
5464            )
5465            .with_column(
5466                "last_completed_refresh",
5467                SqlScalarType::MzTimestamp.nullable(true),
5468            )
5469            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
5470            .finish(),
5471        column_comments: BTreeMap::from_iter([
5472            (
5473                "materialized_view_id",
5474                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5475            ),
5476            (
5477                "last_completed_refresh",
5478                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5479            ),
5480            (
5481                "next_refresh",
5482                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5483            ),
5484        ]),
5485        is_retained_metrics_object: false,
5486        access: vec![PUBLIC_SELECT],
5487    }
5488});
5489
5490pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5491    name: "mz_subscriptions",
5492    schema: MZ_INTERNAL_SCHEMA,
5493    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5494    desc: RelationDesc::builder()
5495        .with_column("id", SqlScalarType::String.nullable(false))
5496        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
5497        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5498        .with_column(
5499            "created_at",
5500            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5501        )
5502        .with_column(
5503            "referenced_object_ids",
5504            SqlScalarType::List {
5505                element_type: Box::new(SqlScalarType::String),
5506                custom_id: None,
5507            }
5508            .nullable(false),
5509        )
5510        .finish(),
5511    column_comments: BTreeMap::from_iter([
5512        ("id", "The ID of the subscription."),
5513        (
5514            "session_id",
5515            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5516        ),
5517        (
5518            "cluster_id",
5519            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5520        ),
5521        (
5522            "created_at",
5523            "The time at which the subscription was created.",
5524        ),
5525        (
5526            "referenced_object_ids",
5527            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5528        ),
5529    ]),
5530    is_retained_metrics_object: false,
5531    access: vec![PUBLIC_SELECT],
5532});
5533
5534pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5535    name: "mz_sessions",
5536    schema: MZ_INTERNAL_SCHEMA,
5537    oid: oid::TABLE_MZ_SESSIONS_OID,
5538    desc: RelationDesc::builder()
5539        .with_column("id", SqlScalarType::Uuid.nullable(false))
5540        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
5541        .with_column("role_id", SqlScalarType::String.nullable(false))
5542        .with_column("client_ip", SqlScalarType::String.nullable(true))
5543        .with_column(
5544            "connected_at",
5545            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5546        )
5547        .finish(),
5548    column_comments: BTreeMap::from_iter([
5549        ("id", "The globally unique ID of the session."),
5550        (
5551            "connection_id",
5552            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5553        ),
5554        (
5555            "role_id",
5556            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5557        ),
5558        (
5559            "client_ip",
5560            "The IP address of the client that initiated the session.",
5561        ),
5562        (
5563            "connected_at",
5564            "The time at which the session connected to the system.",
5565        ),
5566    ]),
5567    is_retained_metrics_object: false,
5568    access: vec![PUBLIC_SELECT],
5569});
5570
5571pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5572    name: "mz_default_privileges",
5573    schema: MZ_CATALOG_SCHEMA,
5574    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5575    desc: RelationDesc::builder()
5576        .with_column("role_id", SqlScalarType::String.nullable(false))
5577        .with_column("database_id", SqlScalarType::String.nullable(true))
5578        .with_column("schema_id", SqlScalarType::String.nullable(true))
5579        .with_column("object_type", SqlScalarType::String.nullable(false))
5580        .with_column("grantee", SqlScalarType::String.nullable(false))
5581        .with_column("privileges", SqlScalarType::String.nullable(false))
5582        .finish(),
5583    column_comments: BTreeMap::from_iter([
5584        (
5585            "role_id",
5586            "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.",
5587        ),
5588        (
5589            "database_id",
5590            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5591        ),
5592        (
5593            "schema_id",
5594            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5595        ),
5596        (
5597            "object_type",
5598            "Privileges described in this row will be granted only on objects of type `object_type`.",
5599        ),
5600        (
5601            "grantee",
5602            "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.",
5603        ),
5604        ("privileges", "The set of privileges that will be granted."),
5605    ]),
5606    is_retained_metrics_object: false,
5607    access: vec![PUBLIC_SELECT],
5608});
5609
5610pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5611    name: "mz_system_privileges",
5612    schema: MZ_CATALOG_SCHEMA,
5613    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5614    desc: RelationDesc::builder()
5615        .with_column("privileges", SqlScalarType::MzAclItem.nullable(false))
5616        .finish(),
5617    column_comments: BTreeMap::from_iter([(
5618        "privileges",
5619        "The privileges belonging to the system.",
5620    )]),
5621    is_retained_metrics_object: false,
5622    access: vec![PUBLIC_SELECT],
5623});
5624
5625pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5626    name: "mz_comments",
5627    schema: MZ_INTERNAL_SCHEMA,
5628    oid: oid::TABLE_MZ_COMMENTS_OID,
5629    desc: RelationDesc::builder()
5630        .with_column("id", SqlScalarType::String.nullable(false))
5631        .with_column("object_type", SqlScalarType::String.nullable(false))
5632        .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
5633        .with_column("comment", SqlScalarType::String.nullable(false))
5634        .finish(),
5635    column_comments: BTreeMap::from_iter([
5636        (
5637            "id",
5638            "The ID of the object. Corresponds to `mz_objects.id`.",
5639        ),
5640        (
5641            "object_type",
5642            "The type of object the comment is associated with.",
5643        ),
5644        (
5645            "object_sub_id",
5646            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5647        ),
5648        ("comment", "The comment itself."),
5649    ]),
5650    is_retained_metrics_object: false,
5651    access: vec![PUBLIC_SELECT],
5652});
5653
5654pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5655    name: "mz_source_references",
5656    schema: MZ_INTERNAL_SCHEMA,
5657    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5658    desc: RelationDesc::builder()
5659        .with_column("source_id", SqlScalarType::String.nullable(false))
5660        .with_column("namespace", SqlScalarType::String.nullable(true))
5661        .with_column("name", SqlScalarType::String.nullable(false))
5662        .with_column(
5663            "updated_at",
5664            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5665        )
5666        .with_column(
5667            "columns",
5668            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5669        )
5670        .finish(),
5671    column_comments: BTreeMap::new(),
5672    is_retained_metrics_object: false,
5673    access: vec![PUBLIC_SELECT],
5674});
5675
5676pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5677    name: "mz_webhook_sources",
5678    schema: MZ_INTERNAL_SCHEMA,
5679    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5680    desc: RelationDesc::builder()
5681        .with_column("id", SqlScalarType::String.nullable(false))
5682        .with_column("name", SqlScalarType::String.nullable(false))
5683        .with_column("url", SqlScalarType::String.nullable(false))
5684        .finish(),
5685    column_comments: BTreeMap::from_iter([
5686        (
5687            "id",
5688            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5689        ),
5690        ("name", "The name of the webhook source."),
5691        (
5692            "url",
5693            "The URL which can be used to send events to the source.",
5694        ),
5695    ]),
5696    is_retained_metrics_object: false,
5697    access: vec![PUBLIC_SELECT],
5698});
5699
5700pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5701    BuiltinTable {
5702        name: "mz_history_retention_strategies",
5703        schema: MZ_INTERNAL_SCHEMA,
5704        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5705        desc: RelationDesc::builder()
5706            .with_column("id", SqlScalarType::String.nullable(false))
5707            .with_column("strategy", SqlScalarType::String.nullable(false))
5708            .with_column("value", SqlScalarType::Jsonb.nullable(false))
5709            .finish(),
5710        column_comments: BTreeMap::from_iter([
5711            ("id", "The ID of the object."),
5712            (
5713                "strategy",
5714                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5715            ),
5716            (
5717                "value",
5718                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5719            ),
5720        ]),
5721        is_retained_metrics_object: false,
5722        access: vec![PUBLIC_SELECT],
5723    }
5724});
5725
5726pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5727    name: "mz_license_keys",
5728    schema: MZ_INTERNAL_SCHEMA,
5729    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
5730    desc: RelationDesc::builder()
5731        .with_column("id", SqlScalarType::String.nullable(false))
5732        .with_column("organization", SqlScalarType::String.nullable(false))
5733        .with_column("environment_id", SqlScalarType::String.nullable(false))
5734        .with_column(
5735            "expiration",
5736            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5737        )
5738        .with_column(
5739            "not_before",
5740            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5741        )
5742        .finish(),
5743    column_comments: BTreeMap::from_iter([
5744        ("id", "The identifier of the license key."),
5745        (
5746            "organization",
5747            "The name of the organization that this license key was issued to.",
5748        ),
5749        (
5750            "environment_id",
5751            "The environment ID that this license key was issued for.",
5752        ),
5753        (
5754            "expiration",
5755            "The date and time when this license key expires.",
5756        ),
5757        (
5758            "not_before",
5759            "The start of the validity period for this license key.",
5760        ),
5761    ]),
5762    is_retained_metrics_object: false,
5763    access: vec![PUBLIC_SELECT],
5764});
5765
5766pub static MZ_REPLACEMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5767    name: "mz_replacements",
5768    schema: MZ_INTERNAL_SCHEMA,
5769    oid: oid::TABLE_MZ_REPLACEMENTS_OID,
5770    desc: RelationDesc::builder()
5771        .with_column("id", SqlScalarType::String.nullable(false))
5772        .with_column("target_id", SqlScalarType::String.nullable(false))
5773        .finish(),
5774    column_comments: BTreeMap::from_iter([
5775        (
5776            "id",
5777            "The ID of the replacement object. Corresponds to `mz_objects.id`.",
5778        ),
5779        (
5780            "target_id",
5781            "The ID of the replacement target. Corresponds to `mz_objects.id`.",
5782        ),
5783    ]),
5784    is_retained_metrics_object: false,
5785    access: vec![PUBLIC_SELECT],
5786});
5787
5788// These will be replaced with per-replica tables once source/sink multiplexing on
5789// a single cluster is supported.
5790pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5791    name: "mz_source_statistics_raw",
5792    schema: MZ_INTERNAL_SCHEMA,
5793    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5794    data_source: IntrospectionType::StorageSourceStatistics.into(),
5795    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5796    column_comments: BTreeMap::new(),
5797    is_retained_metrics_object: true,
5798    access: vec![PUBLIC_SELECT],
5799});
5800pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5801    name: "mz_sink_statistics_raw",
5802    schema: MZ_INTERNAL_SCHEMA,
5803    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5804    data_source: IntrospectionType::StorageSinkStatistics.into(),
5805    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5806    column_comments: BTreeMap::new(),
5807    is_retained_metrics_object: true,
5808    access: vec![PUBLIC_SELECT],
5809});
5810
5811pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5812    name: "mz_storage_shards",
5813    schema: MZ_INTERNAL_SCHEMA,
5814    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5815    data_source: IntrospectionType::ShardMapping.into(),
5816    desc: RelationDesc::builder()
5817        .with_column("object_id", SqlScalarType::String.nullable(false))
5818        .with_column("shard_id", SqlScalarType::String.nullable(false))
5819        .finish(),
5820    column_comments: BTreeMap::new(),
5821    is_retained_metrics_object: false,
5822    access: vec![PUBLIC_SELECT],
5823});
5824
5825pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5826    name: "mz_storage_usage",
5827    schema: MZ_CATALOG_SCHEMA,
5828    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5829    desc: RelationDesc::builder()
5830        .with_column("object_id", SqlScalarType::String.nullable(false))
5831        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5832        .with_column(
5833            "collection_timestamp",
5834            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5835        )
5836        .with_key(vec![0, 2])
5837        .finish(),
5838    column_comments: BTreeMap::from_iter([
5839        (
5840            "object_id",
5841            "The ID of the table, source, or materialized view.",
5842        ),
5843        (
5844            "size_bytes",
5845            "The number of storage bytes used by the object.",
5846        ),
5847        (
5848            "collection_timestamp",
5849            "The time at which storage usage of the object was assessed.",
5850        ),
5851    ]),
5852    sql: "
5853SELECT
5854    object_id,
5855    sum(size_bytes)::uint8 AS size_bytes,
5856    collection_timestamp
5857FROM
5858    mz_internal.mz_storage_shards
5859    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5860GROUP BY object_id, collection_timestamp",
5861    access: vec![PUBLIC_SELECT],
5862});
5863
5864pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5865    BuiltinView {
5866    name: "mz_recent_storage_usage",
5867    schema: MZ_CATALOG_SCHEMA,
5868    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
5869    desc: RelationDesc::builder()
5870        .with_column("object_id", SqlScalarType::String.nullable(false))
5871        .with_column("size_bytes", SqlScalarType::UInt64.nullable(true))
5872        .with_key(vec![0])
5873        .finish(),
5874    column_comments: BTreeMap::from_iter([
5875        ("object_id", "The ID of the table, source, or materialized view."),
5876        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
5877    ]),
5878    sql: "
5879WITH
5880
5881recent_storage_usage_by_shard AS (
5882    SELECT shard_id, size_bytes, collection_timestamp
5883    FROM mz_internal.mz_storage_usage_by_shard
5884    -- Restricting to the last 6 hours makes it feasible to index the view.
5885    WHERE collection_timestamp + '6 hours' >= mz_now()
5886),
5887
5888most_recent_collection_timestamp_by_shard AS (
5889    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
5890    FROM recent_storage_usage_by_shard
5891    GROUP BY shard_id
5892)
5893
5894SELECT
5895    object_id,
5896    sum(size_bytes)::uint8 AS size_bytes
5897FROM
5898    mz_internal.mz_storage_shards
5899    LEFT JOIN most_recent_collection_timestamp_by_shard
5900        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
5901    LEFT JOIN recent_storage_usage_by_shard
5902        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
5903        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
5904GROUP BY object_id",
5905    access: vec![PUBLIC_SELECT],
5906}
5907});
5908
5909pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
5910    name: "mz_recent_storage_usage_ind",
5911    schema: MZ_CATALOG_SCHEMA,
5912    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
5913    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
5914    is_retained_metrics_object: false,
5915});
5916
5917pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
5918    BuiltinView {
5919        name: "mz_relations",
5920        schema: MZ_CATALOG_SCHEMA,
5921        oid: oid::VIEW_MZ_RELATIONS_OID,
5922        desc: RelationDesc::builder()
5923            .with_column("id", SqlScalarType::String.nullable(false))
5924            .with_column("oid", SqlScalarType::Oid.nullable(false))
5925            .with_column("schema_id", SqlScalarType::String.nullable(false))
5926            .with_column("name", SqlScalarType::String.nullable(false))
5927            .with_column("type", SqlScalarType::String.nullable(false))
5928            .with_column("owner_id", SqlScalarType::String.nullable(false))
5929            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5930            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false))
5931            .finish(),
5932        column_comments: BTreeMap::from_iter([
5933            ("id", "Materialize's unique ID for the relation."),
5934            ("oid", "A PostgreSQL-compatible OID for the relation."),
5935            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
5936            ("name", "The name of the relation."),
5937            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
5938            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
5939            ("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."),
5940            ("privileges", "The privileges belonging to the relation."),
5941        ]),
5942        sql: "
5943      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
5944UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
5945UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
5946UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views
5947UNION ALL SELECT id, oid, schema_id, name, 'continual-task', owner_id, cluster_id, privileges FROM mz_internal.mz_continual_tasks",
5948        access: vec![PUBLIC_SELECT],
5949    }
5950});
5951
5952pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5953    name: "mz_objects_id_namespace_types",
5954    schema: MZ_INTERNAL_SCHEMA,
5955    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
5956    desc: RelationDesc::builder()
5957        .with_column("object_type", SqlScalarType::String.nullable(false))
5958        .with_key(vec![0])
5959        .finish(),
5960    column_comments: BTreeMap::new(),
5961    sql: r#"SELECT *
5962    FROM (
5963        VALUES
5964            ('table'),
5965            ('view'),
5966            ('materialized-view'),
5967            ('source'),
5968            ('sink'),
5969            ('index'),
5970            ('connection'),
5971            ('type'),
5972            ('function'),
5973            ('secret')
5974    )
5975    AS _ (object_type)"#,
5976    access: vec![PUBLIC_SELECT],
5977});
5978
5979pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5980    name: "mz_object_oid_alias",
5981    schema: MZ_INTERNAL_SCHEMA,
5982    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
5983    desc: RelationDesc::builder()
5984        .with_column("object_type", SqlScalarType::String.nullable(false))
5985        .with_column("oid_alias", SqlScalarType::String.nullable(false))
5986        .with_key(vec![0])
5987        .finish(),
5988    column_comments: BTreeMap::new(),
5989    sql: "SELECT object_type, oid_alias
5990    FROM (
5991        VALUES
5992            (
5993                'table'::pg_catalog.text,
5994                'regclass'::pg_catalog.text
5995            ),
5996            ('source', 'regclass'),
5997            ('view', 'regclass'),
5998            ('materialized-view', 'regclass'),
5999            ('index', 'regclass'),
6000            ('type', 'regtype'),
6001            ('function', 'regproc')
6002    )
6003    AS _ (object_type, oid_alias);",
6004    access: vec![PUBLIC_SELECT],
6005});
6006
6007pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6008    BuiltinView {
6009        name: "mz_objects",
6010        schema: MZ_CATALOG_SCHEMA,
6011        oid: oid::VIEW_MZ_OBJECTS_OID,
6012        desc: RelationDesc::builder()
6013            .with_column("id", SqlScalarType::String.nullable(false))
6014            .with_column("oid", SqlScalarType::Oid.nullable(false))
6015            .with_column("schema_id", SqlScalarType::String.nullable(false))
6016            .with_column("name", SqlScalarType::String.nullable(false))
6017            .with_column("type", SqlScalarType::String.nullable(false))
6018            .with_column("owner_id", SqlScalarType::String.nullable(false))
6019            .with_column("cluster_id", SqlScalarType::String.nullable(true))
6020            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(true))
6021            .finish(),
6022        column_comments: BTreeMap::from_iter([
6023            ("id", "Materialize's unique ID for the object."),
6024            ("oid", "A PostgreSQL-compatible OID for the object."),
6025            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
6026            ("name", "The name of the object."),
6027            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
6028            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
6029            ("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."),
6030            ("privileges", "The privileges belonging to the object."),
6031        ]),
6032        sql:
6033        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
6034UNION ALL
6035    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
6036UNION ALL
6037    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[]
6038    FROM mz_catalog.mz_indexes
6039    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6040UNION ALL
6041    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
6042UNION ALL
6043    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
6044UNION ALL
6045    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
6046UNION ALL
6047    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
6048        access: vec![PUBLIC_SELECT],
6049    }
6050});
6051
6052pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6053    name: "mz_object_fully_qualified_names",
6054    schema: MZ_INTERNAL_SCHEMA,
6055    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
6056    desc: RelationDesc::builder()
6057        .with_column("id", SqlScalarType::String.nullable(false))
6058        .with_column("name", SqlScalarType::String.nullable(false))
6059        .with_column("object_type", SqlScalarType::String.nullable(false))
6060        .with_column("schema_id", SqlScalarType::String.nullable(false))
6061        .with_column("schema_name", SqlScalarType::String.nullable(false))
6062        .with_column("database_id", SqlScalarType::String.nullable(true))
6063        .with_column("database_name", SqlScalarType::String.nullable(true))
6064        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6065        .finish(),
6066    column_comments: BTreeMap::from_iter([
6067        ("id", "Materialize's unique ID for the object."),
6068        ("name", "The name of the object."),
6069        (
6070            "object_type",
6071            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6072        ),
6073        (
6074            "schema_id",
6075            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
6076        ),
6077        (
6078            "schema_name",
6079            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
6080        ),
6081        (
6082            "database_id",
6083            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
6084        ),
6085        (
6086            "database_name",
6087            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
6088        ),
6089        (
6090            "cluster_id",
6091            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
6092        ),
6093    ]),
6094    sql: "
6095    SELECT o.id,
6096        o.name,
6097        o.type as object_type,
6098        sc.id as schema_id,
6099        sc.name as schema_name,
6100        db.id as database_id,
6101        db.name as database_name,
6102        o.cluster_id
6103    FROM mz_catalog.mz_objects o
6104    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
6105    -- LEFT JOIN accounts for objects in the ambient database.
6106    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
6107    access: vec![PUBLIC_SELECT],
6108});
6109
6110pub static MZ_OBJECT_GLOBAL_IDS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
6111    name: "mz_object_global_ids",
6112    schema: MZ_INTERNAL_SCHEMA,
6113    oid: oid::VIEW_MZ_OBJECT_GLOBAL_IDS_OID,
6114    desc: RelationDesc::builder()
6115        .with_column("id", SqlScalarType::String.nullable(false))
6116        .with_column("global_id", SqlScalarType::String.nullable(false))
6117        .finish(),
6118    column_comments: BTreeMap::from_iter([
6119        (
6120            "id",
6121            "The ID of the object. Corresponds to `mz_objects.id`.",
6122        ),
6123        ("global_id", "The global ID of the object."),
6124    ]),
6125    is_retained_metrics_object: false,
6126    access: vec![PUBLIC_SELECT],
6127});
6128
6129// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
6130pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6131    name: "mz_object_lifetimes",
6132    schema: MZ_INTERNAL_SCHEMA,
6133    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
6134    desc: RelationDesc::builder()
6135        .with_column("id", SqlScalarType::String.nullable(true))
6136        .with_column("previous_id", SqlScalarType::String.nullable(true))
6137        .with_column("object_type", SqlScalarType::String.nullable(false))
6138        .with_column("event_type", SqlScalarType::String.nullable(false))
6139        .with_column(
6140            "occurred_at",
6141            SqlScalarType::TimestampTz { precision: None }.nullable(false),
6142        )
6143        .finish(),
6144    column_comments: BTreeMap::from_iter([
6145        ("id", "Materialize's unique ID for the object."),
6146        ("previous_id", "The object's previous ID, if one exists."),
6147        (
6148            "object_type",
6149            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6150        ),
6151        (
6152            "event_type",
6153            "The lifetime event, either `create` or `drop`.",
6154        ),
6155        (
6156            "occurred_at",
6157            "Wall-clock timestamp of when the event occurred.",
6158        ),
6159    ]),
6160    sql: "
6161    SELECT
6162        CASE
6163            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
6164            ELSE a.details ->> 'id'
6165        END id,
6166        a.details ->> 'previous_id' as previous_id,
6167        a.object_type,
6168        a.event_type,
6169        a.occurred_at
6170    FROM mz_catalog.mz_audit_events a
6171    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
6172    access: vec![PUBLIC_SELECT],
6173});
6174
6175pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6176    name: "mz_object_history",
6177    schema: MZ_INTERNAL_SCHEMA,
6178    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
6179    desc: RelationDesc::builder()
6180        .with_column("id", SqlScalarType::String.nullable(true))
6181        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6182        .with_column("object_type", SqlScalarType::String.nullable(false))
6183        .with_column(
6184            "created_at",
6185            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6186        )
6187        .with_column(
6188            "dropped_at",
6189            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6190        )
6191        .finish(),
6192    column_comments: BTreeMap::from_iter([
6193        ("id", "Materialize's unique ID for the object."),
6194        (
6195            "cluster_id",
6196            "The object's cluster ID. `NULL` if the object has no associated cluster.",
6197        ),
6198        (
6199            "object_type",
6200            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6201        ),
6202        (
6203            "created_at",
6204            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
6205        ),
6206        (
6207            "dropped_at",
6208            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
6209        ),
6210    ]),
6211    sql: r#"
6212    WITH
6213        creates AS
6214        (
6215            SELECT
6216                details ->> 'id' AS id,
6217                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
6218                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
6219                object_type,
6220                occurred_at
6221            FROM
6222                mz_catalog.mz_audit_events AS events
6223                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
6224            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6225        ),
6226        drops AS
6227        (
6228            SELECT details ->> 'id' AS id, occurred_at
6229            FROM mz_catalog.mz_audit_events
6230            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6231        ),
6232        user_object_history AS
6233        (
6234            SELECT
6235                creates.id,
6236                creates.cluster_id,
6237                creates.object_type,
6238                creates.occurred_at AS created_at,
6239                drops.occurred_at AS dropped_at
6240            FROM creates LEFT JOIN drops ON creates.id = drops.id
6241            WHERE creates.id LIKE 'u%'
6242        ),
6243        -- We need to union built in objects since they aren't in the audit log
6244        built_in_objects AS
6245        (
6246            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
6247            SELECT DISTINCT ON (objects.id)
6248                objects.id,
6249                objects.cluster_id,
6250                objects.type AS object_type,
6251                NULL::timestamptz AS created_at,
6252                NULL::timestamptz AS dropped_at
6253            FROM mz_catalog.mz_objects AS objects
6254            WHERE objects.id LIKE 's%'
6255        )
6256    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
6257    access: vec![PUBLIC_SELECT],
6258});
6259
6260pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6261    name: "mz_dataflows_per_worker",
6262    schema: MZ_INTROSPECTION_SCHEMA,
6263    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
6264    desc: RelationDesc::builder()
6265        .with_column("id", SqlScalarType::UInt64.nullable(true))
6266        .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6267        .with_column("name", SqlScalarType::String.nullable(false))
6268        .finish(),
6269    column_comments: BTreeMap::new(),
6270    sql: "SELECT
6271    addrs.address[1] AS id,
6272    ops.worker_id,
6273    ops.name
6274FROM
6275    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6276    mz_introspection.mz_dataflow_operators_per_worker ops
6277WHERE
6278    addrs.id = ops.id AND
6279    addrs.worker_id = ops.worker_id AND
6280    mz_catalog.list_length(addrs.address) = 1",
6281    access: vec![PUBLIC_SELECT],
6282});
6283
6284pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6285    name: "mz_dataflows",
6286    schema: MZ_INTROSPECTION_SCHEMA,
6287    oid: oid::VIEW_MZ_DATAFLOWS_OID,
6288    desc: RelationDesc::builder()
6289        .with_column("id", SqlScalarType::UInt64.nullable(true))
6290        .with_column("name", SqlScalarType::String.nullable(false))
6291        .finish(),
6292    column_comments: BTreeMap::from_iter([
6293        ("id", "The ID of the dataflow."),
6294        ("name", "The internal name of the dataflow."),
6295    ]),
6296    sql: "
6297SELECT id, name
6298FROM mz_introspection.mz_dataflows_per_worker
6299WHERE worker_id = 0",
6300    access: vec![PUBLIC_SELECT],
6301});
6302
6303pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6304    name: "mz_dataflow_addresses",
6305    schema: MZ_INTROSPECTION_SCHEMA,
6306    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
6307    desc: RelationDesc::builder()
6308        .with_column("id", SqlScalarType::UInt64.nullable(false))
6309        .with_column(
6310            "address",
6311            SqlScalarType::List {
6312                element_type: Box::new(SqlScalarType::UInt64),
6313                custom_id: None,
6314            }
6315            .nullable(false),
6316        )
6317        .finish(),
6318    column_comments: BTreeMap::from_iter([
6319        (
6320            "id",
6321            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
6322        ),
6323        (
6324            "address",
6325            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
6326        ),
6327    ]),
6328    sql: "
6329SELECT id, address
6330FROM mz_introspection.mz_dataflow_addresses_per_worker
6331WHERE worker_id = 0",
6332    access: vec![PUBLIC_SELECT],
6333});
6334
6335pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6336    name: "mz_dataflow_channels",
6337    schema: MZ_INTROSPECTION_SCHEMA,
6338    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
6339    desc: RelationDesc::builder()
6340        .with_column("id", SqlScalarType::UInt64.nullable(false))
6341        .with_column("from_index", SqlScalarType::UInt64.nullable(false))
6342        .with_column("from_port", SqlScalarType::UInt64.nullable(false))
6343        .with_column("to_index", SqlScalarType::UInt64.nullable(false))
6344        .with_column("to_port", SqlScalarType::UInt64.nullable(false))
6345        .with_column("type", SqlScalarType::String.nullable(false))
6346        .finish(),
6347    column_comments: BTreeMap::from_iter([
6348        ("id", "The ID of the channel."),
6349        (
6350            "from_index",
6351            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
6352        ),
6353        ("from_port", "The source operator's output port."),
6354        (
6355            "to_index",
6356            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
6357        ),
6358        ("to_port", "The target operator's input port."),
6359        ("type", "The container type of the channel."),
6360    ]),
6361    sql: "
6362SELECT id, from_index, from_port, to_index, to_port, type
6363FROM mz_introspection.mz_dataflow_channels_per_worker
6364WHERE worker_id = 0",
6365    access: vec![PUBLIC_SELECT],
6366});
6367
6368pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6369    name: "mz_dataflow_operators",
6370    schema: MZ_INTROSPECTION_SCHEMA,
6371    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6372    desc: RelationDesc::builder()
6373        .with_column("id", SqlScalarType::UInt64.nullable(false))
6374        .with_column("name", SqlScalarType::String.nullable(false))
6375        .finish(),
6376    column_comments: BTreeMap::from_iter([
6377        ("id", "The ID of the operator."),
6378        ("name", "The internal name of the operator."),
6379    ]),
6380    sql: "
6381SELECT id, name
6382FROM mz_introspection.mz_dataflow_operators_per_worker
6383WHERE worker_id = 0",
6384    access: vec![PUBLIC_SELECT],
6385});
6386
6387pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6388    name: "mz_dataflow_global_ids",
6389    schema: MZ_INTROSPECTION_SCHEMA,
6390    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6391    desc: RelationDesc::builder()
6392        .with_column("id", SqlScalarType::UInt64.nullable(false))
6393        .with_column("global_id", SqlScalarType::String.nullable(false))
6394        .finish(),
6395    column_comments: BTreeMap::from_iter([
6396        ("id", "The dataflow ID."),
6397        ("global_id", "A global ID associated with that dataflow."),
6398    ]),
6399    sql: "
6400SELECT id, global_id
6401FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6402WHERE worker_id = 0",
6403    access: vec![PUBLIC_SELECT],
6404});
6405
6406pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6407    name: "mz_mappable_objects",
6408    schema: MZ_INTROSPECTION_SCHEMA,
6409    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6410    desc: RelationDesc::builder()
6411        .with_column("name", SqlScalarType::String.nullable(false))
6412        .with_column("global_id", SqlScalarType::String.nullable(false))
6413        .finish(),
6414    column_comments: BTreeMap::from_iter([
6415        (
6416            "name",
6417            "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.",
6418        ),
6419        ("global_id", "The global ID of the object."),
6420    ]),
6421    sql: "
6422SELECT COALESCE(md.name || '.', '') || ms.name || '.' || mo.name AS name, mgi.global_id AS global_id
6423FROM      mz_catalog.mz_objects mo
6424          JOIN mz_introspection.mz_compute_exports mce ON (mo.id = mce.export_id)
6425          JOIN mz_catalog.mz_schemas ms ON (mo.schema_id = ms.id)
6426          JOIN mz_introspection.mz_dataflow_global_ids mgi ON (mce.dataflow_id = mgi.id)
6427     LEFT JOIN mz_catalog.mz_databases md ON (ms.database_id = md.id);",
6428    access: vec![PUBLIC_SELECT],
6429});
6430
6431pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6432    name: "mz_lir_mapping",
6433    schema: MZ_INTROSPECTION_SCHEMA,
6434    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6435    desc: RelationDesc::builder()
6436        .with_column("global_id", SqlScalarType::String.nullable(false))
6437        .with_column("lir_id", SqlScalarType::UInt64.nullable(false))
6438        .with_column("operator", SqlScalarType::String.nullable(false))
6439        .with_column("parent_lir_id", SqlScalarType::UInt64.nullable(true))
6440        .with_column("nesting", SqlScalarType::UInt16.nullable(false))
6441        .with_column("operator_id_start", SqlScalarType::UInt64.nullable(false))
6442        .with_column("operator_id_end", SqlScalarType::UInt64.nullable(false))
6443        .finish(),
6444    column_comments: BTreeMap::from_iter([
6445        ("global_id", "The global ID."),
6446        ("lir_id", "The LIR node ID."),
6447        (
6448            "operator",
6449            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6450        ),
6451        (
6452            "parent_lir_id",
6453            "The parent of this LIR node. May be `NULL`.",
6454        ),
6455        ("nesting", "The nesting level of this LIR node."),
6456        (
6457            "operator_id_start",
6458            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6459        ),
6460        (
6461            "operator_id_end",
6462            "The first dataflow operator ID _after_ this LIR operator (exclusive).",
6463        ),
6464    ]),
6465    sql: "
6466SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6467FROM mz_introspection.mz_compute_lir_mapping_per_worker
6468WHERE worker_id = 0",
6469    access: vec![PUBLIC_SELECT],
6470});
6471
6472pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6473    LazyLock::new(|| BuiltinView {
6474        name: "mz_dataflow_operator_dataflows_per_worker",
6475        schema: MZ_INTROSPECTION_SCHEMA,
6476        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6477        desc: RelationDesc::builder()
6478            .with_column("id", SqlScalarType::UInt64.nullable(false))
6479            .with_column("name", SqlScalarType::String.nullable(false))
6480            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6481            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6482            .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6483            .finish(),
6484        column_comments: BTreeMap::new(),
6485        sql: "SELECT
6486    ops.id,
6487    ops.name,
6488    ops.worker_id,
6489    dfs.id as dataflow_id,
6490    dfs.name as dataflow_name
6491FROM
6492    mz_introspection.mz_dataflow_operators_per_worker ops,
6493    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6494    mz_introspection.mz_dataflows_per_worker dfs
6495WHERE
6496    ops.id = addrs.id AND
6497    ops.worker_id = addrs.worker_id AND
6498    dfs.id = addrs.address[1] AND
6499    dfs.worker_id = addrs.worker_id",
6500        access: vec![PUBLIC_SELECT],
6501    });
6502
6503pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6504    name: "mz_dataflow_operator_dataflows",
6505    schema: MZ_INTROSPECTION_SCHEMA,
6506    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6507    desc: RelationDesc::builder()
6508        .with_column("id", SqlScalarType::UInt64.nullable(false))
6509        .with_column("name", SqlScalarType::String.nullable(false))
6510        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6511        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6512        .finish(),
6513    column_comments: BTreeMap::from_iter([
6514        (
6515            "id",
6516            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6517        ),
6518        ("name", "The internal name of the operator."),
6519        (
6520            "dataflow_id",
6521            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6522        ),
6523        (
6524            "dataflow_name",
6525            "The internal name of the dataflow hosting the operator.",
6526        ),
6527    ]),
6528    sql: "
6529SELECT id, name, dataflow_id, dataflow_name
6530FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6531WHERE worker_id = 0",
6532    access: vec![PUBLIC_SELECT],
6533});
6534
6535pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6536    BuiltinView {
6537        name: "mz_object_transitive_dependencies",
6538        schema: MZ_INTERNAL_SCHEMA,
6539        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6540        desc: RelationDesc::builder()
6541            .with_column("object_id", SqlScalarType::String.nullable(false))
6542            .with_column(
6543                "referenced_object_id",
6544                SqlScalarType::String.nullable(false),
6545            )
6546            .with_key(vec![0, 1])
6547            .finish(),
6548        column_comments: BTreeMap::from_iter([
6549            (
6550                "object_id",
6551                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6552            ),
6553            (
6554                "referenced_object_id",
6555                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6556            ),
6557        ]),
6558        sql: "
6559WITH MUTUALLY RECURSIVE
6560  reach(object_id text, referenced_object_id text) AS (
6561    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6562    UNION
6563    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6564  )
6565SELECT object_id, referenced_object_id FROM reach;",
6566        access: vec![PUBLIC_SELECT],
6567    }
6568});
6569
6570pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6571    name: "mz_compute_exports",
6572    schema: MZ_INTROSPECTION_SCHEMA,
6573    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6574    desc: RelationDesc::builder()
6575        .with_column("export_id", SqlScalarType::String.nullable(false))
6576        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6577        .finish(),
6578    column_comments: BTreeMap::from_iter([
6579        (
6580            "export_id",
6581            "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`.",
6582        ),
6583        (
6584            "dataflow_id",
6585            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6586        ),
6587    ]),
6588    sql: "
6589SELECT export_id, dataflow_id
6590FROM mz_introspection.mz_compute_exports_per_worker
6591WHERE worker_id = 0",
6592    access: vec![PUBLIC_SELECT],
6593});
6594
6595pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6596    name: "mz_compute_frontiers",
6597    schema: MZ_INTROSPECTION_SCHEMA,
6598    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6599    desc: RelationDesc::builder()
6600        .with_column("export_id", SqlScalarType::String.nullable(false))
6601        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6602        .with_key(vec![0])
6603        .finish(),
6604    column_comments: BTreeMap::from_iter([
6605        (
6606            "export_id",
6607            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6608        ),
6609        (
6610            "time",
6611            "The next timestamp at which the dataflow output may change.",
6612        ),
6613    ]),
6614    sql: "SELECT
6615    export_id, pg_catalog.min(time) AS time
6616FROM mz_introspection.mz_compute_frontiers_per_worker
6617GROUP BY export_id",
6618    access: vec![PUBLIC_SELECT],
6619});
6620
6621pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6622    LazyLock::new(|| BuiltinView {
6623        name: "mz_dataflow_channel_operators_per_worker",
6624        schema: MZ_INTROSPECTION_SCHEMA,
6625        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6626        desc: RelationDesc::builder()
6627            .with_column("id", SqlScalarType::UInt64.nullable(false))
6628            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6629            .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6630            .with_column(
6631                "from_operator_address",
6632                SqlScalarType::List {
6633                    element_type: Box::new(SqlScalarType::UInt64),
6634                    custom_id: None,
6635                }
6636                .nullable(false),
6637            )
6638            .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6639            .with_column(
6640                "to_operator_address",
6641                SqlScalarType::List {
6642                    element_type: Box::new(SqlScalarType::UInt64),
6643                    custom_id: None,
6644                }
6645                .nullable(false),
6646            )
6647            .with_column("type", SqlScalarType::String.nullable(false))
6648            .finish(),
6649        column_comments: BTreeMap::new(),
6650        sql: "
6651WITH
6652channel_addresses(id, worker_id, address, from_index, to_index, type) AS (
6653     SELECT id, worker_id, address, from_index, to_index, type
6654     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6655     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6656     USING (id, worker_id)
6657),
6658channel_operator_addresses(id, worker_id, from_address, to_address, type) AS (
6659     SELECT id, worker_id,
6660            address || from_index AS from_address,
6661            address || to_index AS to_address,
6662            type
6663     FROM channel_addresses
6664),
6665operator_addresses(id, worker_id, address) AS (
6666     SELECT id, worker_id, address
6667     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6668     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6669     USING (id, worker_id)
6670)
6671SELECT coa.id,
6672       coa.worker_id,
6673       from_ops.id AS from_operator_id,
6674       coa.from_address AS from_operator_address,
6675       to_ops.id AS to_operator_id,
6676       coa.to_address AS to_operator_address,
6677       coa.type
6678FROM channel_operator_addresses coa
6679     LEFT OUTER JOIN operator_addresses from_ops
6680          ON coa.from_address = from_ops.address AND
6681             coa.worker_id = from_ops.worker_id
6682     LEFT OUTER JOIN operator_addresses to_ops
6683          ON coa.to_address = to_ops.address AND
6684             coa.worker_id = to_ops.worker_id
6685",
6686        access: vec![PUBLIC_SELECT],
6687    });
6688
6689pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6690    name: "mz_dataflow_channel_operators",
6691    schema: MZ_INTROSPECTION_SCHEMA,
6692    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6693    desc: RelationDesc::builder()
6694        .with_column("id", SqlScalarType::UInt64.nullable(false))
6695        .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6696        .with_column(
6697            "from_operator_address",
6698            SqlScalarType::List {
6699                element_type: Box::new(SqlScalarType::UInt64),
6700                custom_id: None,
6701            }
6702            .nullable(false),
6703        )
6704        .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6705        .with_column(
6706            "to_operator_address",
6707            SqlScalarType::List {
6708                element_type: Box::new(SqlScalarType::UInt64),
6709                custom_id: None,
6710            }
6711            .nullable(false),
6712        )
6713        .with_column("type", SqlScalarType::String.nullable(false))
6714        .finish(),
6715    column_comments: BTreeMap::from_iter([
6716        (
6717            "id",
6718            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6719        ),
6720        (
6721            "from_operator_id",
6722            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6723        ),
6724        (
6725            "from_operator_address",
6726            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6727        ),
6728        (
6729            "to_operator_id",
6730            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6731        ),
6732        (
6733            "to_operator_address",
6734            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6735        ),
6736        ("type", "The container type of the channel."),
6737    ]),
6738    sql: "
6739SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address, type
6740FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6741WHERE worker_id = 0",
6742    access: vec![PUBLIC_SELECT],
6743});
6744
6745pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6746    name: "mz_compute_import_frontiers",
6747    schema: MZ_INTROSPECTION_SCHEMA,
6748    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6749    desc: RelationDesc::builder()
6750        .with_column("export_id", SqlScalarType::String.nullable(false))
6751        .with_column("import_id", SqlScalarType::String.nullable(false))
6752        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6753        .with_key(vec![0, 1])
6754        .finish(),
6755    column_comments: BTreeMap::from_iter([
6756        (
6757            "export_id",
6758            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6759        ),
6760        (
6761            "import_id",
6762            "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`.",
6763        ),
6764        (
6765            "time",
6766            "The next timestamp at which the dataflow input may change.",
6767        ),
6768    ]),
6769    sql: "SELECT
6770    export_id, import_id, pg_catalog.min(time) AS time
6771FROM mz_introspection.mz_compute_import_frontiers_per_worker
6772GROUP BY export_id, import_id",
6773    access: vec![PUBLIC_SELECT],
6774});
6775
6776pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6777    LazyLock::new(|| BuiltinView {
6778        name: "mz_records_per_dataflow_operator_per_worker",
6779        schema: MZ_INTROSPECTION_SCHEMA,
6780        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6781        desc: RelationDesc::builder()
6782            .with_column("id", SqlScalarType::UInt64.nullable(false))
6783            .with_column("name", SqlScalarType::String.nullable(false))
6784            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6785            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6786            .with_column("records", SqlScalarType::Int64.nullable(true))
6787            .with_column("batches", SqlScalarType::Int64.nullable(true))
6788            .with_column("size", SqlScalarType::Int64.nullable(true))
6789            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6790            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6791            .finish(),
6792        column_comments: BTreeMap::new(),
6793        sql: "
6794SELECT
6795    dod.id,
6796    dod.name,
6797    dod.worker_id,
6798    dod.dataflow_id,
6799    ar_size.records AS records,
6800    ar_size.batches AS batches,
6801    ar_size.size AS size,
6802    ar_size.capacity AS capacity,
6803    ar_size.allocations AS allocations
6804FROM
6805    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6806    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6807        dod.id = ar_size.operator_id AND
6808        dod.worker_id = ar_size.worker_id",
6809        access: vec![PUBLIC_SELECT],
6810    });
6811
6812pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6813    LazyLock::new(|| BuiltinView {
6814        name: "mz_records_per_dataflow_operator",
6815        schema: MZ_INTROSPECTION_SCHEMA,
6816        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6817        desc: RelationDesc::builder()
6818            .with_column("id", SqlScalarType::UInt64.nullable(false))
6819            .with_column("name", SqlScalarType::String.nullable(false))
6820            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6821            .with_column("records", SqlScalarType::Int64.nullable(true))
6822            .with_column("batches", SqlScalarType::Int64.nullable(true))
6823            .with_column("size", SqlScalarType::Int64.nullable(true))
6824            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6825            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6826            .with_key(vec![0, 1, 2])
6827            .finish(),
6828        column_comments: BTreeMap::from_iter([
6829            (
6830                "id",
6831                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6832            ),
6833            ("name", "The internal name of the operator."),
6834            (
6835                "dataflow_id",
6836                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6837            ),
6838            ("records", "The number of records in the operator."),
6839            ("batches", "The number of batches in the dataflow."),
6840            ("size", "The utilized size in bytes of the arrangement."),
6841            (
6842                "capacity",
6843                "The capacity in bytes of the arrangement. Can be larger than the size.",
6844            ),
6845            (
6846                "allocations",
6847                "The number of separate memory allocations backing the arrangement.",
6848            ),
6849        ]),
6850        sql: "
6851SELECT
6852    id,
6853    name,
6854    dataflow_id,
6855    SUM(records)::int8 AS records,
6856    SUM(batches)::int8 AS batches,
6857    SUM(size)::int8 AS size,
6858    SUM(capacity)::int8 AS capacity,
6859    SUM(allocations)::int8 AS allocations
6860FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
6861GROUP BY id, name, dataflow_id",
6862        access: vec![PUBLIC_SELECT],
6863    });
6864
6865pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
6866    LazyLock::new(|| BuiltinView {
6867        name: "mz_records_per_dataflow_per_worker",
6868        schema: MZ_INTROSPECTION_SCHEMA,
6869        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
6870        desc: RelationDesc::builder()
6871            .with_column("id", SqlScalarType::UInt64.nullable(false))
6872            .with_column("name", SqlScalarType::String.nullable(false))
6873            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6874            .with_column("records", SqlScalarType::Int64.nullable(true))
6875            .with_column("batches", SqlScalarType::Int64.nullable(true))
6876            .with_column("size", SqlScalarType::Int64.nullable(true))
6877            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6878            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6879            .with_key(vec![0, 1, 2])
6880            .finish(),
6881        column_comments: BTreeMap::new(),
6882        sql: "
6883SELECT
6884    rdo.dataflow_id as id,
6885    dfs.name,
6886    rdo.worker_id,
6887    SUM(rdo.records)::int8 as records,
6888    SUM(rdo.batches)::int8 as batches,
6889    SUM(rdo.size)::int8 as size,
6890    SUM(rdo.capacity)::int8 as capacity,
6891    SUM(rdo.allocations)::int8 as allocations
6892FROM
6893    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
6894    mz_introspection.mz_dataflows_per_worker dfs
6895WHERE
6896    rdo.dataflow_id = dfs.id AND
6897    rdo.worker_id = dfs.worker_id
6898GROUP BY
6899    rdo.dataflow_id,
6900    dfs.name,
6901    rdo.worker_id",
6902        access: vec![PUBLIC_SELECT],
6903    });
6904
6905pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6906    name: "mz_records_per_dataflow",
6907    schema: MZ_INTROSPECTION_SCHEMA,
6908    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
6909    desc: RelationDesc::builder()
6910        .with_column("id", SqlScalarType::UInt64.nullable(false))
6911        .with_column("name", SqlScalarType::String.nullable(false))
6912        .with_column("records", SqlScalarType::Int64.nullable(true))
6913        .with_column("batches", SqlScalarType::Int64.nullable(true))
6914        .with_column("size", SqlScalarType::Int64.nullable(true))
6915        .with_column("capacity", SqlScalarType::Int64.nullable(true))
6916        .with_column("allocations", SqlScalarType::Int64.nullable(true))
6917        .with_key(vec![0, 1])
6918        .finish(),
6919    column_comments: BTreeMap::from_iter([
6920        (
6921            "id",
6922            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6923        ),
6924        ("name", "The internal name of the dataflow."),
6925        ("records", "The number of records in the dataflow."),
6926        ("batches", "The number of batches in the dataflow."),
6927        ("size", "The utilized size in bytes of the arrangements."),
6928        (
6929            "capacity",
6930            "The capacity in bytes of the arrangements. Can be larger than the size.",
6931        ),
6932        (
6933            "allocations",
6934            "The number of separate memory allocations backing the arrangements.",
6935        ),
6936    ]),
6937    sql: "
6938SELECT
6939    id,
6940    name,
6941    SUM(records)::int8 as records,
6942    SUM(batches)::int8 as batches,
6943    SUM(size)::int8 as size,
6944    SUM(capacity)::int8 as capacity,
6945    SUM(allocations)::int8 as allocations
6946FROM
6947    mz_introspection.mz_records_per_dataflow_per_worker
6948GROUP BY
6949    id,
6950    name",
6951    access: vec![PUBLIC_SELECT],
6952});
6953
6954/// Peeled version of `PG_NAMESPACE`:
6955/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6956///   in order to make this view indexable.
6957/// - This has the database name as an extra column, so that downstream views can check it against
6958///  `current_database()`.
6959pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6960    name: "pg_namespace_all_databases",
6961    schema: MZ_INTERNAL_SCHEMA,
6962    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
6963    desc: RelationDesc::builder()
6964        .with_column("oid", SqlScalarType::Oid.nullable(false))
6965        .with_column("nspname", SqlScalarType::String.nullable(false))
6966        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6967        .with_column(
6968            "nspacl",
6969            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6970        )
6971        .with_column("database_name", SqlScalarType::String.nullable(true))
6972        .finish(),
6973    column_comments: BTreeMap::new(),
6974    sql: "
6975SELECT
6976    s.oid AS oid,
6977    s.name AS nspname,
6978    role_owner.oid AS nspowner,
6979    NULL::pg_catalog.text[] AS nspacl,
6980    d.name as database_name
6981FROM mz_catalog.mz_schemas s
6982LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
6983JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
6984    access: vec![PUBLIC_SELECT],
6985});
6986
6987pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6988    name: "pg_namespace_all_databases_ind",
6989    schema: MZ_INTERNAL_SCHEMA,
6990    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
6991    sql: "IN CLUSTER mz_catalog_server
6992ON mz_internal.pg_namespace_all_databases (nspname)",
6993    is_retained_metrics_object: false,
6994};
6995
6996pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6997    name: "pg_namespace",
6998    schema: PG_CATALOG_SCHEMA,
6999    oid: oid::VIEW_PG_NAMESPACE_OID,
7000    desc: RelationDesc::builder()
7001        .with_column("oid", SqlScalarType::Oid.nullable(false))
7002        .with_column("nspname", SqlScalarType::String.nullable(false))
7003        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
7004        .with_column(
7005            "nspacl",
7006            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7007        )
7008        .finish(),
7009    column_comments: BTreeMap::new(),
7010    sql: "
7011SELECT
7012    oid, nspname, nspowner, nspacl
7013FROM mz_internal.pg_namespace_all_databases
7014WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7015    access: vec![PUBLIC_SELECT],
7016});
7017
7018/// Peeled version of `PG_CLASS`:
7019/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7020///   in order to make this view indexable.
7021/// - This has the database name as an extra column, so that downstream views can check it against
7022///  `current_database()`.
7023pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7024    BuiltinView {
7025        name: "pg_class_all_databases",
7026        schema: MZ_INTERNAL_SCHEMA,
7027        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
7028        desc: RelationDesc::builder()
7029            .with_column("oid", SqlScalarType::Oid.nullable(false))
7030            .with_column("relname", SqlScalarType::String.nullable(false))
7031            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
7032            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
7033            .with_column("relowner", SqlScalarType::Oid.nullable(false))
7034            .with_column("relam", SqlScalarType::Oid.nullable(false))
7035            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
7036            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
7037            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
7038            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
7039            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
7040            .with_column("relkind", SqlScalarType::String.nullable(true))
7041            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
7042            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
7043            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
7044            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
7045            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
7046            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
7047            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
7048            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
7049            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
7050            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
7051            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
7052            .with_column("database_name", SqlScalarType::String.nullable(true))
7053            .finish(),
7054        column_comments: BTreeMap::new(),
7055        sql: "
7056SELECT
7057    class_objects.oid,
7058    class_objects.name AS relname,
7059    mz_schemas.oid AS relnamespace,
7060    -- MZ doesn't support typed tables so reloftype is filled with 0
7061    0::pg_catalog.oid AS reloftype,
7062    role_owner.oid AS relowner,
7063    0::pg_catalog.oid AS relam,
7064    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
7065    0::pg_catalog.oid AS reltablespace,
7066    -- MZ doesn't support (estimated) row counts currently.
7067    -- Postgres defines a value of -1 as unknown.
7068    -1::float4 as reltuples,
7069    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
7070    0::pg_catalog.oid AS reltoastrelid,
7071    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
7072    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
7073    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
7074    -- TODO(jkosh44): update this column when issue is resolved.
7075    'p'::pg_catalog.\"char\" AS relpersistence,
7076    CASE
7077        WHEN class_objects.type = 'table' THEN 'r'
7078        WHEN class_objects.type = 'source' THEN 'r'
7079        WHEN class_objects.type = 'index' THEN 'i'
7080        WHEN class_objects.type = 'view' THEN 'v'
7081        WHEN class_objects.type = 'materialized-view' THEN 'm'
7082    END relkind,
7083    COALESCE(
7084        (
7085            SELECT count(*)::pg_catalog.int2
7086            FROM mz_catalog.mz_columns
7087            WHERE mz_columns.id = class_objects.id
7088        ),
7089        0::pg_catalog.int2
7090    ) AS relnatts,
7091    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
7092    0::pg_catalog.int2 AS relchecks,
7093    -- MZ doesn't support creating rules so relhasrules is filled with false
7094    false AS relhasrules,
7095    -- MZ doesn't support creating triggers so relhastriggers is filled with false
7096    false AS relhastriggers,
7097    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
7098    false AS relhassubclass,
7099    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
7100    false AS relrowsecurity,
7101    false AS relforcerowsecurity,
7102    -- MZ doesn't support replication so relreplident is filled with 'd' for default
7103    'd'::pg_catalog.\"char\" AS relreplident,
7104    -- MZ doesn't support table partitioning so relispartition is filled with false
7105    false AS relispartition,
7106    -- PG removed relhasoids in v12 so it's filled with false
7107    false AS relhasoids,
7108    -- MZ doesn't support options for relations
7109    NULL::pg_catalog.text[] as reloptions,
7110    d.name as database_name
7111FROM (
7112    -- pg_class catalogs relations and indexes
7113    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
7114    UNION ALL
7115        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
7116        FROM mz_catalog.mz_indexes
7117        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7118) AS class_objects
7119JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7120LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7121JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
7122        access: vec![PUBLIC_SELECT],
7123    }
7124});
7125
7126pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7127    name: "pg_class_all_databases_ind",
7128    schema: MZ_INTERNAL_SCHEMA,
7129    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
7130    sql: "IN CLUSTER mz_catalog_server
7131ON mz_internal.pg_class_all_databases (relname)",
7132    is_retained_metrics_object: false,
7133};
7134
7135pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| {
7136    BuiltinView {
7137    name: "pg_class",
7138    schema: PG_CATALOG_SCHEMA,
7139    oid: oid::VIEW_PG_CLASS_OID,
7140    desc: RelationDesc::builder()
7141        .with_column("oid", SqlScalarType::Oid.nullable(false))
7142        .with_column("relname", SqlScalarType::String.nullable(false))
7143        .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
7144        .with_column("reloftype", SqlScalarType::Oid.nullable(false))
7145        .with_column("relowner", SqlScalarType::Oid.nullable(false))
7146        .with_column("relam", SqlScalarType::Oid.nullable(false))
7147        .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
7148        .with_column("reltuples", SqlScalarType::Float32.nullable(false))
7149        .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
7150        .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
7151        .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
7152        .with_column("relkind", SqlScalarType::String.nullable(true))
7153        .with_column("relnatts", SqlScalarType::Int16.nullable(false))
7154        .with_column("relchecks", SqlScalarType::Int16.nullable(false))
7155        .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
7156        .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
7157        .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
7158        .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
7159        .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
7160        .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
7161        .with_column("relispartition", SqlScalarType::Bool.nullable(false))
7162        .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
7163        .with_column(
7164            "reloptions",
7165            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7166        )
7167        .finish(),
7168    column_comments: BTreeMap::new(),
7169    sql: "
7170SELECT
7171    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
7172    relhasindex, relpersistence, relkind, relnatts, relchecks, relhasrules, relhastriggers, relhassubclass,
7173    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
7174FROM mz_internal.pg_class_all_databases
7175WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
7176",
7177    access: vec![PUBLIC_SELECT],
7178}
7179});
7180
7181pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7182    name: "pg_depend",
7183    schema: PG_CATALOG_SCHEMA,
7184    oid: oid::VIEW_PG_DEPEND_OID,
7185    desc: RelationDesc::builder()
7186        .with_column("classid", SqlScalarType::Oid.nullable(true))
7187        .with_column("objid", SqlScalarType::Oid.nullable(false))
7188        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7189        .with_column("refclassid", SqlScalarType::Oid.nullable(true))
7190        .with_column("refobjid", SqlScalarType::Oid.nullable(false))
7191        .with_column("refobjsubid", SqlScalarType::Int32.nullable(false))
7192        .with_column("deptype", SqlScalarType::PgLegacyChar.nullable(false))
7193        .finish(),
7194    column_comments: BTreeMap::new(),
7195    sql: "
7196WITH class_objects AS (
7197    SELECT
7198        CASE
7199            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
7200            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
7201            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
7202            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
7203        END classid,
7204        id,
7205        oid,
7206        schema_id
7207    FROM mz_catalog.mz_relations
7208    UNION ALL
7209    SELECT
7210        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
7211        i.id,
7212        i.oid,
7213        r.schema_id
7214    FROM mz_catalog.mz_indexes i
7215    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7216),
7217
7218current_objects AS (
7219    SELECT class_objects.*
7220    FROM class_objects
7221    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7222    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7223    -- This filter is tricky, as it filters out not just objects outside the
7224    -- database, but *dependencies* on objects outside this database. It's not
7225    -- clear that this is the right choice, but because PostgreSQL doesn't
7226    -- support cross-database references, it's not clear that the other choice
7227    -- is better.
7228    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7229)
7230
7231SELECT
7232    objects.classid::pg_catalog.oid,
7233    objects.oid::pg_catalog.oid AS objid,
7234    0::pg_catalog.int4 AS objsubid,
7235    dependents.classid::pg_catalog.oid AS refclassid,
7236    dependents.oid::pg_catalog.oid AS refobjid,
7237    0::pg_catalog.int4 AS refobjsubid,
7238    'n'::pg_catalog.char AS deptype
7239FROM mz_internal.mz_object_dependencies
7240JOIN current_objects objects ON object_id = objects.id
7241JOIN current_objects dependents ON referenced_object_id = dependents.id",
7242    access: vec![PUBLIC_SELECT],
7243});
7244
7245pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7246    name: "pg_database",
7247    schema: PG_CATALOG_SCHEMA,
7248    oid: oid::VIEW_PG_DATABASE_OID,
7249    desc: RelationDesc::builder()
7250        .with_column("oid", SqlScalarType::Oid.nullable(false))
7251        .with_column("datname", SqlScalarType::String.nullable(false))
7252        .with_column("datdba", SqlScalarType::Oid.nullable(false))
7253        .with_column("encoding", SqlScalarType::Int32.nullable(false))
7254        .with_column("datistemplate", SqlScalarType::Bool.nullable(false))
7255        .with_column("datallowconn", SqlScalarType::Bool.nullable(false))
7256        .with_column("datcollate", SqlScalarType::String.nullable(false))
7257        .with_column("datctype", SqlScalarType::String.nullable(false))
7258        .with_column(
7259            "datacl",
7260            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7261        )
7262        .with_key(vec![0])
7263        .finish(),
7264    column_comments: BTreeMap::new(),
7265    sql: "SELECT
7266    d.oid as oid,
7267    d.name as datname,
7268    role_owner.oid as datdba,
7269    6 as encoding,
7270    -- Materialize doesn't support database cloning.
7271    FALSE AS datistemplate,
7272    TRUE AS datallowconn,
7273    'C' as datcollate,
7274    'C' as datctype,
7275    NULL::pg_catalog.text[] as datacl
7276FROM mz_catalog.mz_databases d
7277JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
7278    access: vec![PUBLIC_SELECT],
7279});
7280
7281pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
7282    BuiltinView {
7283        name: "pg_index",
7284        schema: PG_CATALOG_SCHEMA,
7285        oid: oid::VIEW_PG_INDEX_OID,
7286        desc: RelationDesc::builder()
7287            .with_column("indexrelid", SqlScalarType::Oid.nullable(false))
7288            .with_column("indrelid", SqlScalarType::Oid.nullable(false))
7289            .with_column("indnatts", SqlScalarType::Int16.nullable(false))
7290            .with_column("indisunique", SqlScalarType::Bool.nullable(false))
7291            .with_column("indisprimary", SqlScalarType::Bool.nullable(false))
7292            .with_column("indimmediate", SqlScalarType::Bool.nullable(false))
7293            .with_column("indisclustered", SqlScalarType::Bool.nullable(false))
7294            .with_column("indisvalid", SqlScalarType::Bool.nullable(false))
7295            .with_column("indisreplident", SqlScalarType::Bool.nullable(false))
7296            .with_column("indkey", SqlScalarType::Int2Vector.nullable(false))
7297            .with_column("indoption", SqlScalarType::Int2Vector.nullable(false))
7298            .with_column("indexprs", SqlScalarType::String.nullable(true))
7299            .with_column("indpred", SqlScalarType::String.nullable(true))
7300            .with_key(vec![0, 1])
7301            .finish(),
7302        column_comments: BTreeMap::new(),
7303        sql: "SELECT
7304    mz_indexes.oid AS indexrelid,
7305    mz_relations.oid AS indrelid,
7306    COALESCE(
7307        (
7308            SELECT count(*)::pg_catalog.int2
7309            FROM mz_catalog.mz_columns
7310            JOIN mz_catalog.mz_relations mri ON mz_columns.id = mri.id
7311            WHERE mri.oid = mz_catalog.mz_relations.oid
7312        ),
7313        0::pg_catalog.int2
7314    ) AS indnatts,
7315    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7316    false::pg_catalog.bool AS indisunique,
7317    false::pg_catalog.bool AS indisprimary,
7318    -- MZ doesn't support unique indexes so indimmediate is filled with false
7319    false::pg_catalog.bool AS indimmediate,
7320    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7321    false::pg_catalog.bool AS indisclustered,
7322    -- MZ never creates invalid indexes so indisvalid is filled with true
7323    true::pg_catalog.bool AS indisvalid,
7324    -- MZ doesn't support replication so indisreplident is filled with false
7325    false::pg_catalog.bool AS indisreplident,
7326    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7327    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,
7328    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7329    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7330    -- Index expressions are returned in MZ format
7331    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7332    WHEN NULL THEN NULL
7333    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7334    END AS indexprs,
7335    -- MZ doesn't support indexes with predicates
7336    NULL::pg_catalog.text AS indpred
7337FROM mz_catalog.mz_indexes
7338JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7339JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7340JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7341LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7342WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7343GROUP BY mz_indexes.oid, mz_relations.oid",
7344        access: vec![PUBLIC_SELECT],
7345    }
7346});
7347
7348pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7349    name: "pg_indexes",
7350    schema: PG_CATALOG_SCHEMA,
7351    oid: oid::VIEW_PG_INDEXES_OID,
7352    desc: RelationDesc::builder()
7353        .with_column("table_catalog", SqlScalarType::String.nullable(false))
7354        .with_column("schemaname", SqlScalarType::String.nullable(false))
7355        .with_column("tablename", SqlScalarType::String.nullable(false))
7356        .with_column("indexname", SqlScalarType::String.nullable(false))
7357        .with_column("tablespace", SqlScalarType::String.nullable(true))
7358        .with_column("indexdef", SqlScalarType::String.nullable(true))
7359        .finish(),
7360    column_comments: BTreeMap::new(),
7361    sql: "SELECT
7362    current_database() as table_catalog,
7363    s.name AS schemaname,
7364    r.name AS tablename,
7365    i.name AS indexname,
7366    NULL::text AS tablespace,
7367    -- TODO(jkosh44) Fill in with actual index definition.
7368    NULL::text AS indexdef
7369FROM mz_catalog.mz_indexes i
7370JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7371JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7372LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7373WHERE s.database_id IS NULL OR d.name = current_database()",
7374    access: vec![PUBLIC_SELECT],
7375});
7376
7377/// Peeled version of `PG_DESCRIPTION`:
7378/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7379///   in order to make this view indexable.
7380/// - This has 2 extra columns for the database names, so that downstream views can check them
7381///   against `current_database()`.
7382pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7383    BuiltinView {
7384        name: "pg_description_all_databases",
7385        schema: MZ_INTERNAL_SCHEMA,
7386        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7387        desc: RelationDesc::builder()
7388            .with_column("objoid", SqlScalarType::Oid.nullable(false))
7389            .with_column("classoid", SqlScalarType::Oid.nullable(true))
7390            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7391            .with_column("description", SqlScalarType::String.nullable(false))
7392            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
7393            .with_column("class_database_name", SqlScalarType::String.nullable(true))
7394            .finish(),
7395        column_comments: BTreeMap::new(),
7396        sql: "
7397(
7398    -- Gather all of the class oid's for objects that can have comments.
7399    WITH pg_classoids AS (
7400        SELECT oid, database_name as oid_database_name,
7401          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7402          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7403        FROM mz_internal.pg_class_all_databases
7404        UNION ALL
7405        SELECT oid, database_name as oid_database_name,
7406          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7407          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7408        FROM mz_internal.pg_type_all_databases
7409        UNION ALL
7410        SELECT oid, database_name as oid_database_name,
7411          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7412          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7413        FROM mz_internal.pg_namespace_all_databases
7414    ),
7415
7416    -- Gather all of the MZ ids for objects that can have comments.
7417    mz_objects AS (
7418        SELECT id, oid, type FROM mz_catalog.mz_objects
7419        UNION ALL
7420        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7421    )
7422    SELECT
7423        pg_classoids.oid AS objoid,
7424        pg_classoids.classoid as classoid,
7425        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7426        cmt.comment AS description,
7427        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7428        oid_database_name,
7429        class_database_name
7430    FROM
7431        pg_classoids
7432    JOIN
7433        mz_objects ON pg_classoids.oid = mz_objects.oid
7434    JOIN
7435        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7436)",
7437        access: vec![PUBLIC_SELECT],
7438    }
7439});
7440
7441pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7442    name: "pg_description_all_databases_ind",
7443    schema: MZ_INTERNAL_SCHEMA,
7444    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7445    sql: "IN CLUSTER mz_catalog_server
7446ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7447    is_retained_metrics_object: false,
7448};
7449
7450/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7451/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7452/// which is required for this view.
7453pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7454    name: "pg_description",
7455    schema: PG_CATALOG_SCHEMA,
7456    oid: oid::VIEW_PG_DESCRIPTION_OID,
7457    desc: RelationDesc::builder()
7458        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7459        .with_column("classoid", SqlScalarType::Oid.nullable(true))
7460        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7461        .with_column("description", SqlScalarType::String.nullable(false))
7462        .finish(),
7463    column_comments: BTreeMap::new(),
7464    sql: "
7465SELECT
7466    objoid,
7467    classoid,
7468    objsubid,
7469    description
7470FROM
7471    mz_internal.pg_description_all_databases
7472WHERE
7473    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7474    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7475    access: vec![PUBLIC_SELECT],
7476});
7477
7478/// Peeled version of `PG_TYPE`:
7479/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7480///   in order to make this view indexable.
7481/// - This has the database name as an extra column, so that downstream views can check it against
7482///  `current_database()`.
7483pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7484    BuiltinView {
7485        name: "pg_type_all_databases",
7486        schema: MZ_INTERNAL_SCHEMA,
7487        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7488        desc: RelationDesc::builder()
7489            .with_column("oid", SqlScalarType::Oid.nullable(false))
7490            .with_column("typname", SqlScalarType::String.nullable(false))
7491            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7492            .with_column("typowner", SqlScalarType::Oid.nullable(false))
7493            .with_column("typlen", SqlScalarType::Int16.nullable(true))
7494            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7495            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7496            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7497            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7498            .with_column("typelem", SqlScalarType::Oid.nullable(false))
7499            .with_column("typarray", SqlScalarType::Oid.nullable(false))
7500            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7501            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7502            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7503            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7504            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7505            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7506            .with_column("typdefault", SqlScalarType::String.nullable(true))
7507            .with_column("database_name", SqlScalarType::String.nullable(true))
7508            .finish(),
7509        column_comments: BTreeMap::new(),
7510        sql: "
7511SELECT
7512    mz_types.oid,
7513    mz_types.name AS typname,
7514    mz_schemas.oid AS typnamespace,
7515    role_owner.oid AS typowner,
7516    NULL::pg_catalog.int2 AS typlen,
7517    -- 'a' is used internally to denote an array type, but in postgres they show up
7518    -- as 'b'.
7519    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7520    (CASE category
7521        WHEN 'array' THEN 'A'
7522        WHEN 'bit-string' THEN 'V'
7523        WHEN 'boolean' THEN 'B'
7524        WHEN 'composite' THEN 'C'
7525        WHEN 'date-time' THEN 'D'
7526        WHEN 'enum' THEN 'E'
7527        WHEN 'geometric' THEN 'G'
7528        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7529        WHEN 'network-address' THEN 'I'
7530        WHEN 'numeric' THEN 'N'
7531        WHEN 'pseudo' THEN 'P'
7532        WHEN 'string' THEN 'S'
7533        WHEN 'timespan' THEN 'T'
7534        WHEN 'user-defined' THEN 'U'
7535        WHEN 'unknown' THEN 'X'
7536    END)::pg_catalog.char AS typcategory,
7537    -- In pg only the 'box' type is not ','.
7538    ','::pg_catalog.char AS typdelim,
7539    0::pg_catalog.oid AS typrelid,
7540    coalesce(
7541        (
7542            SELECT t.oid
7543            FROM mz_catalog.mz_array_types a
7544            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7545            WHERE a.id = mz_types.id
7546        ),
7547        (
7548            SELECT t.oid
7549            FROM mz_catalog.mz_list_types l
7550            JOIN mz_catalog.mz_types t ON l.element_id = t.id
7551            WHERE l.id = mz_types.id
7552        ),
7553        0
7554    ) AS typelem,
7555    coalesce(
7556        (
7557            SELECT
7558                t.oid
7559            FROM
7560                mz_catalog.mz_array_types AS a
7561                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7562            WHERE
7563                a.element_id = mz_types.id
7564        ),
7565        0
7566    )
7567        AS typarray,
7568    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7569    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7570    false::pg_catalog.bool AS typnotnull,
7571    0::pg_catalog.oid AS typbasetype,
7572    -1::pg_catalog.int4 AS typtypmod,
7573    -- MZ doesn't support COLLATE so typcollation is filled with 0
7574    0::pg_catalog.oid AS typcollation,
7575    NULL::pg_catalog.text AS typdefault,
7576    d.name as database_name
7577FROM
7578    mz_catalog.mz_types
7579    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7580    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7581    JOIN (
7582            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7583            -- converted to the correct value above.
7584            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7585            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7586            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7587            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7588            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7589        )
7590            AS t ON mz_types.id = t.id
7591    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7592    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7593        access: vec![PUBLIC_SELECT],
7594    }
7595});
7596
7597pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7598    name: "pg_type_all_databases_ind",
7599    schema: MZ_INTERNAL_SCHEMA,
7600    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7601    sql: "IN CLUSTER mz_catalog_server
7602ON mz_internal.pg_type_all_databases (oid)",
7603    is_retained_metrics_object: false,
7604};
7605
7606pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7607    name: "pg_type",
7608    schema: PG_CATALOG_SCHEMA,
7609    oid: oid::VIEW_PG_TYPE_OID,
7610    desc: RelationDesc::builder()
7611        .with_column("oid", SqlScalarType::Oid.nullable(false))
7612        .with_column("typname", SqlScalarType::String.nullable(false))
7613        .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7614        .with_column("typowner", SqlScalarType::Oid.nullable(false))
7615        .with_column("typlen", SqlScalarType::Int16.nullable(true))
7616        .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7617        .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7618        .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7619        .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7620        .with_column("typelem", SqlScalarType::Oid.nullable(false))
7621        .with_column("typarray", SqlScalarType::Oid.nullable(false))
7622        .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7623        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7624        .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7625        .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7626        .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7627        .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7628        .with_column("typdefault", SqlScalarType::String.nullable(true))
7629        .finish(),
7630    column_comments: BTreeMap::new(),
7631    sql: "SELECT
7632    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7633    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7634FROM mz_internal.pg_type_all_databases
7635WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7636    access: vec![PUBLIC_SELECT],
7637});
7638
7639/// Peeled version of `PG_ATTRIBUTE`:
7640/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7641///   in order to make this view indexable.
7642/// - This has 2 extra columns for the database names, so that downstream views can check them
7643///   against `current_database()`.
7644pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7645    BuiltinView {
7646        name: "pg_attribute_all_databases",
7647        schema: MZ_INTERNAL_SCHEMA,
7648        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7649        desc: RelationDesc::builder()
7650            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7651            .with_column("attname", SqlScalarType::String.nullable(false))
7652            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7653            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7654            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7655            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7656            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7657            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7658            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7659            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7660            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7661            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7662            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7663            .with_column("database_name", SqlScalarType::String.nullable(true))
7664            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
7665            .finish(),
7666        column_comments: BTreeMap::new(),
7667        sql: "
7668SELECT
7669    class_objects.oid as attrelid,
7670    mz_columns.name as attname,
7671    mz_columns.type_oid AS atttypid,
7672    pg_type_all_databases.typlen AS attlen,
7673    position::int8::int2 as attnum,
7674    mz_columns.type_mod as atttypmod,
7675    -- dummy value, just to make go-jet's workaround work for now. Discussion:
7676    -- https://github.com/MaterializeInc/materialize/pull/34649#issuecomment-3714291409
7677    0::int2 as attndims,
7678    NOT nullable as attnotnull,
7679    mz_columns.default IS NOT NULL as atthasdef,
7680    ''::pg_catalog.\"char\" as attidentity,
7681    -- MZ doesn't support generated columns so attgenerated is filled with ''
7682    ''::pg_catalog.\"char\" as attgenerated,
7683    FALSE as attisdropped,
7684    -- MZ doesn't support COLLATE so attcollation is filled with 0
7685    0::pg_catalog.oid as attcollation,
7686    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7687    d.name as database_name,
7688    pg_type_all_databases.database_name as pg_type_database_name
7689FROM (
7690    -- pg_attribute catalogs columns on relations and indexes
7691    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7692    UNION ALL
7693        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7694        FROM mz_catalog.mz_indexes
7695        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7696) AS class_objects
7697JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7698JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7699JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7700LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7701        // Since this depends on pg_type, its id must be higher due to initialization
7702        // ordering.
7703        access: vec![PUBLIC_SELECT],
7704    }
7705});
7706
7707pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7708    name: "pg_attribute_all_databases_ind",
7709    schema: MZ_INTERNAL_SCHEMA,
7710    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7711    sql: "IN CLUSTER mz_catalog_server
7712ON mz_internal.pg_attribute_all_databases (
7713    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7714    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7715)",
7716    is_retained_metrics_object: false,
7717};
7718
7719/// <https://www.postgresql.org/docs/current/catalog-pg-attribute.html>
7720pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7721    BuiltinView {
7722        name: "pg_attribute",
7723        schema: PG_CATALOG_SCHEMA,
7724        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7725        desc: RelationDesc::builder()
7726            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7727            .with_column("attname", SqlScalarType::String.nullable(false))
7728            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7729            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7730            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7731            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7732            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7733            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7734            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7735            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7736            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7737            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7738            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7739            .finish(),
7740        column_comments: BTreeMap::new(),
7741        sql: "
7742SELECT
7743    attrelid, attname, atttypid, attlen, attnum, atttypmod, attndims, attnotnull, atthasdef,
7744    attidentity, attgenerated, attisdropped, attcollation
7745FROM mz_internal.pg_attribute_all_databases
7746WHERE
7747  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7748  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7749        // Since this depends on pg_type, its id must be higher due to initialization
7750        // ordering.
7751        access: vec![PUBLIC_SELECT],
7752    }
7753});
7754
7755pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7756    name: "pg_proc",
7757    schema: PG_CATALOG_SCHEMA,
7758    oid: oid::VIEW_PG_PROC_OID,
7759    desc: RelationDesc::builder()
7760        .with_column("oid", SqlScalarType::Oid.nullable(false))
7761        .with_column("proname", SqlScalarType::String.nullable(false))
7762        .with_column("pronamespace", SqlScalarType::Oid.nullable(false))
7763        .with_column("proowner", SqlScalarType::Oid.nullable(false))
7764        .with_column("proargdefaults", SqlScalarType::String.nullable(true))
7765        .with_column("prorettype", SqlScalarType::Oid.nullable(false))
7766        .finish(),
7767    column_comments: BTreeMap::new(),
7768    sql: "SELECT
7769    mz_functions.oid,
7770    mz_functions.name AS proname,
7771    mz_schemas.oid AS pronamespace,
7772    role_owner.oid AS proowner,
7773    NULL::pg_catalog.text AS proargdefaults,
7774    ret_type.oid AS prorettype
7775FROM mz_catalog.mz_functions
7776JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7777LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7778JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7779JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7780WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7781    access: vec![PUBLIC_SELECT],
7782});
7783
7784pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7785    name: "pg_operator",
7786    schema: PG_CATALOG_SCHEMA,
7787    oid: oid::VIEW_PG_OPERATOR_OID,
7788    desc: RelationDesc::builder()
7789        .with_column("oid", SqlScalarType::Oid.nullable(false))
7790        .with_column("oprname", SqlScalarType::String.nullable(false))
7791        .with_column("oprresult", SqlScalarType::Oid.nullable(false))
7792        .with_column("oprleft", SqlScalarType::Oid.nullable(false))
7793        .with_column("oprright", SqlScalarType::Oid.nullable(false))
7794        .with_key(vec![0, 1, 2, 3, 4])
7795        .finish(),
7796    column_comments: BTreeMap::new(),
7797    sql: "SELECT
7798    mz_operators.oid,
7799    mz_operators.name AS oprname,
7800    ret_type.oid AS oprresult,
7801    left_type.oid as oprleft,
7802    right_type.oid as oprright
7803FROM mz_catalog.mz_operators
7804JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7805JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7806JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7807WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7808UNION SELECT
7809    mz_operators.oid,
7810    mz_operators.name AS oprname,
7811    ret_type.oid AS oprresult,
7812    0 as oprleft,
7813    right_type.oid as oprright
7814FROM mz_catalog.mz_operators
7815JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7816JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7817WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7818    access: vec![PUBLIC_SELECT],
7819});
7820
7821pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7822    name: "pg_range",
7823    schema: PG_CATALOG_SCHEMA,
7824    oid: oid::VIEW_PG_RANGE_OID,
7825    desc: RelationDesc::builder()
7826        .with_column("rngtypid", SqlScalarType::Oid.nullable(false))
7827        .with_column("rngsubtype", SqlScalarType::Oid.nullable(false))
7828        .with_key(vec![])
7829        .finish(),
7830    column_comments: BTreeMap::new(),
7831    sql: "SELECT
7832    NULL::pg_catalog.oid AS rngtypid,
7833    NULL::pg_catalog.oid AS rngsubtype
7834WHERE false",
7835    access: vec![PUBLIC_SELECT],
7836});
7837
7838pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7839    name: "pg_enum",
7840    schema: PG_CATALOG_SCHEMA,
7841    oid: oid::VIEW_PG_ENUM_OID,
7842    desc: RelationDesc::builder()
7843        .with_column("oid", SqlScalarType::Oid.nullable(false))
7844        .with_column("enumtypid", SqlScalarType::Oid.nullable(false))
7845        .with_column("enumsortorder", SqlScalarType::Float32.nullable(false))
7846        .with_column("enumlabel", SqlScalarType::String.nullable(false))
7847        .with_key(vec![])
7848        .finish(),
7849    column_comments: BTreeMap::new(),
7850    sql: "SELECT
7851    NULL::pg_catalog.oid AS oid,
7852    NULL::pg_catalog.oid AS enumtypid,
7853    NULL::pg_catalog.float4 AS enumsortorder,
7854    NULL::pg_catalog.text AS enumlabel
7855WHERE false",
7856    access: vec![PUBLIC_SELECT],
7857});
7858
7859/// Peeled version of `PG_ATTRDEF`:
7860/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7861///   in order to make this view indexable.
7862pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7863    name: "pg_attrdef_all_databases",
7864    schema: MZ_INTERNAL_SCHEMA,
7865    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
7866    desc: RelationDesc::builder()
7867        .with_column("oid", SqlScalarType::Oid.nullable(true))
7868        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7869        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7870        .with_column("adbin", SqlScalarType::String.nullable(false))
7871        .with_column("adsrc", SqlScalarType::String.nullable(false))
7872        .finish(),
7873    column_comments: BTreeMap::new(),
7874    sql: "
7875SELECT
7876    NULL::pg_catalog.oid AS oid,
7877    mz_objects.oid AS adrelid,
7878    mz_columns.position::int8 AS adnum,
7879    mz_columns.default AS adbin,
7880    mz_columns.default AS adsrc
7881FROM mz_catalog.mz_columns
7882    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
7883WHERE default IS NOT NULL",
7884    access: vec![PUBLIC_SELECT],
7885});
7886
7887pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7888    name: "pg_attrdef_all_databases_ind",
7889    schema: MZ_INTERNAL_SCHEMA,
7890    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
7891    sql: "IN CLUSTER mz_catalog_server
7892ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
7893    is_retained_metrics_object: false,
7894};
7895
7896pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7897    name: "pg_attrdef",
7898    schema: PG_CATALOG_SCHEMA,
7899    oid: oid::VIEW_PG_ATTRDEF_OID,
7900    desc: RelationDesc::builder()
7901        .with_column("oid", SqlScalarType::Oid.nullable(true))
7902        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7903        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7904        .with_column("adbin", SqlScalarType::String.nullable(false))
7905        .with_column("adsrc", SqlScalarType::String.nullable(false))
7906        .finish(),
7907    column_comments: BTreeMap::new(),
7908    sql: "
7909SELECT
7910    pg_attrdef_all_databases.oid as oid,
7911    adrelid,
7912    adnum,
7913    adbin,
7914    adsrc
7915FROM mz_internal.pg_attrdef_all_databases
7916    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
7917    access: vec![PUBLIC_SELECT],
7918});
7919
7920pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7921    name: "pg_settings",
7922    schema: PG_CATALOG_SCHEMA,
7923    oid: oid::VIEW_PG_SETTINGS_OID,
7924    desc: RelationDesc::builder()
7925        .with_column("name", SqlScalarType::String.nullable(false))
7926        .with_column("setting", SqlScalarType::String.nullable(false))
7927        .with_key(vec![])
7928        .finish(),
7929    column_comments: BTreeMap::new(),
7930    sql: "SELECT
7931    name, setting
7932FROM (VALUES
7933    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
7934) AS _ (name, setting)",
7935    access: vec![PUBLIC_SELECT],
7936});
7937
7938pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7939    name: "pg_auth_members",
7940    schema: PG_CATALOG_SCHEMA,
7941    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
7942    desc: RelationDesc::builder()
7943        .with_column("roleid", SqlScalarType::Oid.nullable(false))
7944        .with_column("member", SqlScalarType::Oid.nullable(false))
7945        .with_column("grantor", SqlScalarType::Oid.nullable(false))
7946        .with_column("admin_option", SqlScalarType::Bool.nullable(false))
7947        .finish(),
7948    column_comments: BTreeMap::new(),
7949    sql: "SELECT
7950    role.oid AS roleid,
7951    member.oid AS member,
7952    grantor.oid AS grantor,
7953    -- Materialize hasn't implemented admin_option.
7954    false as admin_option
7955FROM mz_catalog.mz_role_members membership
7956JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
7957JOIN mz_catalog.mz_roles member ON membership.member = member.id
7958JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
7959    access: vec![PUBLIC_SELECT],
7960});
7961
7962pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7963    name: "pg_event_trigger",
7964    schema: PG_CATALOG_SCHEMA,
7965    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
7966    desc: RelationDesc::builder()
7967        .with_column("oid", SqlScalarType::Oid.nullable(false))
7968        .with_column("evtname", SqlScalarType::String.nullable(false))
7969        .with_column("evtevent", SqlScalarType::String.nullable(false))
7970        .with_column("evtowner", SqlScalarType::Oid.nullable(false))
7971        .with_column("evtfoid", SqlScalarType::Oid.nullable(false))
7972        .with_column("evtenabled", SqlScalarType::PgLegacyChar.nullable(false))
7973        .with_column(
7974            "evttags",
7975            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7976        )
7977        .with_key(vec![])
7978        .finish(),
7979    column_comments: BTreeMap::new(),
7980    sql: "SELECT
7981        NULL::pg_catalog.oid AS oid,
7982        NULL::pg_catalog.text AS evtname,
7983        NULL::pg_catalog.text AS evtevent,
7984        NULL::pg_catalog.oid AS evtowner,
7985        NULL::pg_catalog.oid AS evtfoid,
7986        NULL::pg_catalog.char AS evtenabled,
7987        NULL::pg_catalog.text[] AS evttags
7988    WHERE false",
7989    access: vec![PUBLIC_SELECT],
7990});
7991
7992pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7993    name: "pg_language",
7994    schema: PG_CATALOG_SCHEMA,
7995    oid: oid::VIEW_PG_LANGUAGE_OID,
7996    desc: RelationDesc::builder()
7997        .with_column("oid", SqlScalarType::Oid.nullable(false))
7998        .with_column("lanname", SqlScalarType::String.nullable(false))
7999        .with_column("lanowner", SqlScalarType::Oid.nullable(false))
8000        .with_column("lanispl", SqlScalarType::Bool.nullable(false))
8001        .with_column("lanpltrusted", SqlScalarType::Bool.nullable(false))
8002        .with_column("lanplcallfoid", SqlScalarType::Oid.nullable(false))
8003        .with_column("laninline", SqlScalarType::Oid.nullable(false))
8004        .with_column("lanvalidator", SqlScalarType::Oid.nullable(false))
8005        .with_column(
8006            "lanacl",
8007            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
8008        )
8009        .with_key(vec![])
8010        .finish(),
8011    column_comments: BTreeMap::new(),
8012    sql: "SELECT
8013        NULL::pg_catalog.oid  AS oid,
8014        NULL::pg_catalog.text AS lanname,
8015        NULL::pg_catalog.oid  AS lanowner,
8016        NULL::pg_catalog.bool AS lanispl,
8017        NULL::pg_catalog.bool AS lanpltrusted,
8018        NULL::pg_catalog.oid  AS lanplcallfoid,
8019        NULL::pg_catalog.oid  AS laninline,
8020        NULL::pg_catalog.oid  AS lanvalidator,
8021        NULL::pg_catalog.text[] AS lanacl
8022    WHERE false",
8023    access: vec![PUBLIC_SELECT],
8024});
8025
8026pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8027    name: "pg_shdescription",
8028    schema: PG_CATALOG_SCHEMA,
8029    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
8030    desc: RelationDesc::builder()
8031        .with_column("objoid", SqlScalarType::Oid.nullable(false))
8032        .with_column("classoid", SqlScalarType::Oid.nullable(false))
8033        .with_column("description", SqlScalarType::String.nullable(false))
8034        .with_key(vec![])
8035        .finish(),
8036    column_comments: BTreeMap::new(),
8037    sql: "SELECT
8038        NULL::pg_catalog.oid AS objoid,
8039        NULL::pg_catalog.oid AS classoid,
8040        NULL::pg_catalog.text AS description
8041    WHERE false",
8042    access: vec![PUBLIC_SELECT],
8043});
8044
8045pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
8046    BuiltinView {
8047        name: "pg_timezone_abbrevs",
8048        schema: PG_CATALOG_SCHEMA,
8049        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
8050        desc: RelationDesc::builder()
8051            .with_column("abbrev", SqlScalarType::String.nullable(false))
8052            .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8053            .with_column("is_dst", SqlScalarType::Bool.nullable(true))
8054            .with_key(vec![0])
8055            .finish(),
8056        column_comments: BTreeMap::new(),
8057        sql: "SELECT
8058    abbreviation AS abbrev,
8059    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
8060        AS utc_offset,
8061    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
8062        AS is_dst
8063FROM mz_catalog.mz_timezone_abbreviations",
8064        access: vec![PUBLIC_SELECT],
8065    }
8066});
8067
8068pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8069    name: "pg_timezone_names",
8070    schema: PG_CATALOG_SCHEMA,
8071    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
8072    desc: RelationDesc::builder()
8073        .with_column("name", SqlScalarType::String.nullable(false))
8074        .with_column("abbrev", SqlScalarType::String.nullable(true))
8075        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8076        .with_column("is_dst", SqlScalarType::Bool.nullable(true))
8077        .with_key(vec![0])
8078        .finish(),
8079    column_comments: BTreeMap::new(),
8080    sql: "SELECT
8081    name,
8082    timezone_offset(name, now()).abbrev AS abbrev,
8083    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
8084        AS utc_offset,
8085    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
8086        AS is_dst
8087FROM mz_catalog.mz_timezone_names",
8088    access: vec![PUBLIC_SELECT],
8089});
8090
8091pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8092    name: "mz_timezone_abbreviations",
8093    schema: MZ_CATALOG_SCHEMA,
8094    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
8095    desc: RelationDesc::builder()
8096        .with_column("abbreviation", SqlScalarType::String.nullable(false))
8097        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8098        .with_column("dst", SqlScalarType::Bool.nullable(true))
8099        .with_column("timezone_name", SqlScalarType::String.nullable(true))
8100        .with_key(vec![0])
8101        .finish(),
8102    column_comments: BTreeMap::from_iter([
8103        ("abbreviation", "The timezone abbreviation."),
8104        (
8105            "utc_offset",
8106            "The UTC offset of the timezone or `NULL` if fixed.",
8107        ),
8108        (
8109            "dst",
8110            "Whether the timezone is in daylight savings or `NULL` if fixed.",
8111        ),
8112        (
8113            "timezone_name",
8114            "The full name of the non-fixed timezone or `NULL` if not fixed.",
8115        ),
8116    ]),
8117    sql: format!(
8118        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
8119        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
8120    )
8121    .leak(),
8122    access: vec![PUBLIC_SELECT],
8123});
8124
8125pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8126    name: "mz_timezone_names",
8127    schema: MZ_CATALOG_SCHEMA,
8128    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
8129    desc: RelationDesc::builder()
8130        .with_column("name", SqlScalarType::String.nullable(false))
8131        .with_key(vec![0])
8132        .finish(),
8133    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
8134    sql: format!(
8135        "SELECT * FROM ({}) _ (name)",
8136        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
8137    )
8138    .leak(),
8139    access: vec![PUBLIC_SELECT],
8140});
8141
8142pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8143    LazyLock::new(|| BuiltinView {
8144        name: "mz_peek_durations_histogram_per_worker",
8145        schema: MZ_INTROSPECTION_SCHEMA,
8146        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8147        desc: RelationDesc::builder()
8148            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8149            .with_column("type", SqlScalarType::String.nullable(false))
8150            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8151            .with_column("count", SqlScalarType::Int64.nullable(false))
8152            .with_key(vec![0, 1, 2])
8153            .finish(),
8154        column_comments: BTreeMap::new(),
8155        sql: "SELECT
8156    worker_id, type, duration_ns, pg_catalog.count(*) AS count
8157FROM
8158    mz_introspection.mz_peek_durations_histogram_raw
8159GROUP BY
8160    worker_id, type, duration_ns",
8161        access: vec![PUBLIC_SELECT],
8162    });
8163
8164pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8165    name: "mz_peek_durations_histogram",
8166    schema: MZ_INTROSPECTION_SCHEMA,
8167    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
8168    desc: RelationDesc::builder()
8169        .with_column("type", SqlScalarType::String.nullable(false))
8170        .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8171        .with_column(
8172            "count",
8173            SqlScalarType::Numeric {
8174                max_scale: Some(NumericMaxScale::ZERO),
8175            }
8176            .nullable(false),
8177        )
8178        .with_key(vec![0, 1])
8179        .finish(),
8180    column_comments: BTreeMap::from_iter([
8181        ("type", "The peek variant: `index` or `persist`."),
8182        (
8183            "duration_ns",
8184            "The upper bound of the bucket in nanoseconds.",
8185        ),
8186        (
8187            "count",
8188            "The (noncumulative) count of peeks in this bucket.",
8189        ),
8190    ]),
8191    sql: "
8192SELECT
8193    type, duration_ns,
8194    pg_catalog.sum(count) AS count
8195FROM mz_introspection.mz_peek_durations_histogram_per_worker
8196GROUP BY type, duration_ns",
8197    access: vec![PUBLIC_SELECT],
8198});
8199
8200pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
8201    LazyLock::new(|| BuiltinView {
8202        name: "mz_scheduling_elapsed_per_worker",
8203        schema: MZ_INTROSPECTION_SCHEMA,
8204        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
8205        desc: RelationDesc::builder()
8206            .with_column("id", SqlScalarType::UInt64.nullable(false))
8207            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8208            .with_column("elapsed_ns", SqlScalarType::Int64.nullable(false))
8209            .with_key(vec![0, 1])
8210            .finish(),
8211        column_comments: BTreeMap::new(),
8212        sql: "SELECT
8213    id, worker_id, pg_catalog.count(*) AS elapsed_ns
8214FROM
8215    mz_introspection.mz_scheduling_elapsed_raw
8216GROUP BY
8217    id, worker_id",
8218        access: vec![PUBLIC_SELECT],
8219    });
8220
8221pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8222    name: "mz_scheduling_elapsed",
8223    schema: MZ_INTROSPECTION_SCHEMA,
8224    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
8225    desc: RelationDesc::builder()
8226        .with_column("id", SqlScalarType::UInt64.nullable(false))
8227        .with_column(
8228            "elapsed_ns",
8229            SqlScalarType::Numeric {
8230                max_scale: Some(NumericMaxScale::ZERO),
8231            }
8232            .nullable(false),
8233        )
8234        .with_key(vec![0])
8235        .finish(),
8236    column_comments: BTreeMap::from_iter([
8237        (
8238            "id",
8239            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8240        ),
8241        (
8242            "elapsed_ns",
8243            "The total elapsed time spent in the operator in nanoseconds.",
8244        ),
8245    ]),
8246    sql: "
8247SELECT
8248    id,
8249    pg_catalog.sum(elapsed_ns) AS elapsed_ns
8250FROM mz_introspection.mz_scheduling_elapsed_per_worker
8251GROUP BY id",
8252    access: vec![PUBLIC_SELECT],
8253});
8254
8255pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8256    LazyLock::new(|| BuiltinView {
8257        name: "mz_compute_operator_durations_histogram_per_worker",
8258        schema: MZ_INTROSPECTION_SCHEMA,
8259        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8260        desc: RelationDesc::builder()
8261            .with_column("id", SqlScalarType::UInt64.nullable(false))
8262            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8263            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8264            .with_column("count", SqlScalarType::Int64.nullable(false))
8265            .with_key(vec![0, 1, 2])
8266            .finish(),
8267        column_comments: BTreeMap::new(),
8268        sql: "SELECT
8269    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8270FROM
8271    mz_introspection.mz_compute_operator_durations_histogram_raw
8272GROUP BY
8273    id, worker_id, duration_ns",
8274        access: vec![PUBLIC_SELECT],
8275    });
8276
8277pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8278    LazyLock::new(|| BuiltinView {
8279        name: "mz_compute_operator_durations_histogram",
8280        schema: MZ_INTROSPECTION_SCHEMA,
8281        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8282        desc: RelationDesc::builder()
8283            .with_column("id", SqlScalarType::UInt64.nullable(false))
8284            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8285            .with_column(
8286                "count",
8287                SqlScalarType::Numeric {
8288                    max_scale: Some(NumericMaxScale::ZERO),
8289                }
8290                .nullable(false),
8291            )
8292            .with_key(vec![0, 1])
8293            .finish(),
8294        column_comments: BTreeMap::from_iter([
8295            (
8296                "id",
8297                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8298            ),
8299            (
8300                "duration_ns",
8301                "The upper bound of the duration bucket in nanoseconds.",
8302            ),
8303            (
8304                "count",
8305                "The (noncumulative) count of invocations in the bucket.",
8306            ),
8307        ]),
8308        sql: "
8309SELECT
8310    id,
8311    duration_ns,
8312    pg_catalog.sum(count) AS count
8313FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8314GROUP BY id, duration_ns",
8315        access: vec![PUBLIC_SELECT],
8316    });
8317
8318pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8319    LazyLock::new(|| BuiltinView {
8320        name: "mz_scheduling_parks_histogram_per_worker",
8321        schema: MZ_INTROSPECTION_SCHEMA,
8322        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8323        desc: RelationDesc::builder()
8324            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8325            .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8326            .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8327            .with_column("count", SqlScalarType::Int64.nullable(false))
8328            .with_key(vec![0, 1, 2])
8329            .finish(),
8330        column_comments: BTreeMap::new(),
8331        sql: "SELECT
8332    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8333FROM
8334    mz_introspection.mz_scheduling_parks_histogram_raw
8335GROUP BY
8336    worker_id, slept_for_ns, requested_ns",
8337        access: vec![PUBLIC_SELECT],
8338    });
8339
8340pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8341    name: "mz_scheduling_parks_histogram",
8342    schema: MZ_INTROSPECTION_SCHEMA,
8343    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8344    desc: RelationDesc::builder()
8345        .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8346        .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8347        .with_column(
8348            "count",
8349            SqlScalarType::Numeric {
8350                max_scale: Some(NumericMaxScale::ZERO),
8351            }
8352            .nullable(false),
8353        )
8354        .with_key(vec![0, 1])
8355        .finish(),
8356    column_comments: BTreeMap::from_iter([
8357        (
8358            "slept_for_ns",
8359            "The actual length of the park event in nanoseconds.",
8360        ),
8361        (
8362            "requested_ns",
8363            "The requested length of the park event in nanoseconds.",
8364        ),
8365        (
8366            "count",
8367            "The (noncumulative) count of park events in this bucket.",
8368        ),
8369    ]),
8370    sql: "
8371SELECT
8372    slept_for_ns,
8373    requested_ns,
8374    pg_catalog.sum(count) AS count
8375FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8376GROUP BY slept_for_ns, requested_ns",
8377    access: vec![PUBLIC_SELECT],
8378});
8379
8380pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8381    LazyLock::new(|| BuiltinView {
8382        name: "mz_compute_error_counts_per_worker",
8383        schema: MZ_INTROSPECTION_SCHEMA,
8384        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8385        desc: RelationDesc::builder()
8386            .with_column("export_id", SqlScalarType::String.nullable(false))
8387            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8388            .with_column("count", SqlScalarType::Int64.nullable(false))
8389            .with_key(vec![0, 1, 2])
8390            .finish(),
8391        column_comments: BTreeMap::new(),
8392        sql: "
8393WITH MUTUALLY RECURSIVE
8394    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8395    -- For these we don't log error counts separately, so we need to forward the error counts from
8396    -- their dependencies instead.
8397    index_reuses(reuse_id text, index_id text) AS (
8398        SELECT d.object_id, d.dependency_id
8399        FROM mz_internal.mz_compute_dependencies d
8400        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8401        WHERE NOT EXISTS (
8402            SELECT 1 FROM mz_introspection.mz_dataflows
8403            WHERE id = e.dataflow_id
8404        )
8405    ),
8406    -- Error counts that were directly logged on compute exports.
8407    direct_errors(export_id text, worker_id uint8, count int8) AS (
8408        SELECT export_id, worker_id, count
8409        FROM mz_introspection.mz_compute_error_counts_raw
8410    ),
8411    -- Error counts propagated to index reused.
8412    all_errors(export_id text, worker_id uint8, count int8) AS (
8413        SELECT * FROM direct_errors
8414        UNION
8415        SELECT r.reuse_id, e.worker_id, e.count
8416        FROM all_errors e
8417        JOIN index_reuses r ON (r.index_id = e.export_id)
8418    )
8419SELECT * FROM all_errors",
8420        access: vec![PUBLIC_SELECT],
8421    });
8422
8423pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8424    name: "mz_compute_error_counts",
8425    schema: MZ_INTROSPECTION_SCHEMA,
8426    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8427    desc: RelationDesc::builder()
8428        .with_column("export_id", SqlScalarType::String.nullable(false))
8429        .with_column(
8430            "count",
8431            SqlScalarType::Numeric {
8432                max_scale: Some(NumericMaxScale::ZERO),
8433            }
8434            .nullable(false),
8435        )
8436        .with_key(vec![0])
8437        .finish(),
8438    column_comments: BTreeMap::from_iter([
8439        (
8440            "export_id",
8441            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8442        ),
8443        (
8444            "count",
8445            "The count of errors present in this dataflow export.",
8446        ),
8447    ]),
8448    sql: "
8449SELECT
8450    export_id,
8451    pg_catalog.sum(count) AS count
8452FROM mz_introspection.mz_compute_error_counts_per_worker
8453GROUP BY export_id
8454HAVING pg_catalog.sum(count) != 0",
8455    access: vec![PUBLIC_SELECT],
8456});
8457
8458pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8459    LazyLock::new(|| BuiltinSource {
8460        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8461        // naming conflict because the resolver stumbles over the source with the same name in
8462        // `mz_introspection` due to the automatic schema translation.
8463        name: "mz_compute_error_counts_raw_unified",
8464        schema: MZ_INTERNAL_SCHEMA,
8465        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8466        desc: RelationDesc::builder()
8467            .with_column("replica_id", SqlScalarType::String.nullable(false))
8468            .with_column("object_id", SqlScalarType::String.nullable(false))
8469            .with_column(
8470                "count",
8471                SqlScalarType::Numeric { max_scale: None }.nullable(false),
8472            )
8473            .finish(),
8474        data_source: IntrospectionType::ComputeErrorCounts.into(),
8475        column_comments: BTreeMap::new(),
8476        is_retained_metrics_object: false,
8477        access: vec![PUBLIC_SELECT],
8478    });
8479
8480pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8481    name: "mz_compute_hydration_times",
8482    schema: MZ_INTERNAL_SCHEMA,
8483    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8484    desc: RelationDesc::builder()
8485        .with_column("replica_id", SqlScalarType::String.nullable(false))
8486        .with_column("object_id", SqlScalarType::String.nullable(false))
8487        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
8488        .finish(),
8489    data_source: IntrospectionType::ComputeHydrationTimes.into(),
8490    column_comments: BTreeMap::new(),
8491    is_retained_metrics_object: true,
8492    access: vec![PUBLIC_SELECT],
8493});
8494
8495pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8496    LazyLock::new(|| BuiltinIndex {
8497        name: "mz_compute_hydration_times_ind",
8498        schema: MZ_INTERNAL_SCHEMA,
8499        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8500        sql: "IN CLUSTER mz_catalog_server
8501    ON mz_internal.mz_compute_hydration_times (replica_id)",
8502        is_retained_metrics_object: true,
8503    });
8504
8505pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8506    name: "mz_compute_hydration_statuses",
8507    schema: MZ_INTERNAL_SCHEMA,
8508    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8509    desc: RelationDesc::builder()
8510        .with_column("object_id", SqlScalarType::String.nullable(false))
8511        .with_column("replica_id", SqlScalarType::String.nullable(false))
8512        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8513        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
8514        .finish(),
8515    column_comments: BTreeMap::from_iter([
8516        (
8517            "object_id",
8518            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8519        ),
8520        ("replica_id", "The ID of a cluster replica."),
8521        (
8522            "hydrated",
8523            "Whether the compute object is hydrated on the replica.",
8524        ),
8525        (
8526            "hydration_time",
8527            "The amount of time it took for the replica to hydrate the compute object.",
8528        ),
8529    ]),
8530    sql: "
8531WITH
8532    dataflows AS (
8533        SELECT
8534            object_id,
8535            replica_id,
8536            time_ns IS NOT NULL AS hydrated,
8537            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8538        FROM mz_internal.mz_compute_hydration_times
8539    ),
8540    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8541    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8542    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8543    -- blue-green readiness query does), so we include them as 'hydrated'.
8544    complete_mvs AS (
8545        SELECT
8546            mv.id,
8547            f.replica_id,
8548            true AS hydrated,
8549            NULL::interval AS hydration_time
8550        FROM mz_materialized_views mv
8551        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8552        WHERE f.write_frontier IS NULL
8553    ),
8554    -- Ditto CTs
8555    complete_cts AS (
8556        SELECT
8557            ct.id,
8558            f.replica_id,
8559            true AS hydrated,
8560            NULL::interval AS hydration_time
8561        FROM mz_internal.mz_continual_tasks ct
8562        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = ct.id
8563        WHERE f.write_frontier IS NULL
8564    )
8565SELECT * FROM dataflows
8566UNION ALL
8567SELECT * FROM complete_mvs
8568UNION ALL
8569SELECT * FROM complete_cts",
8570    access: vec![PUBLIC_SELECT],
8571});
8572
8573pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
8574    BuiltinSource {
8575        name: "mz_compute_operator_hydration_statuses",
8576        schema: MZ_INTERNAL_SCHEMA,
8577        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8578        desc: RelationDesc::builder()
8579            .with_column("replica_id", SqlScalarType::String.nullable(false))
8580            .with_column("object_id", SqlScalarType::String.nullable(false))
8581            .with_column(
8582                "physical_plan_node_id",
8583                SqlScalarType::UInt64.nullable(false),
8584            )
8585            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8586            .with_key(vec![0, 1, 2])
8587            .finish(),
8588        data_source: IntrospectionType::ComputeOperatorHydrationStatus.into(),
8589        column_comments: BTreeMap::from_iter([
8590            ("replica_id", "The ID of a cluster replica."),
8591            (
8592                "object_id",
8593                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8594            ),
8595            (
8596                "physical_plan_node_id",
8597                "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)`.",
8598            ),
8599            ("hydrated", "Whether the node is hydrated on the replica."),
8600        ]),
8601        is_retained_metrics_object: false,
8602        access: vec![PUBLIC_SELECT],
8603    }
8604});
8605
8606pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8607    name: "mz_message_counts_per_worker",
8608    schema: MZ_INTROSPECTION_SCHEMA,
8609    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8610    desc: RelationDesc::builder()
8611        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8612        .with_column("from_worker_id", SqlScalarType::UInt64.nullable(false))
8613        .with_column("to_worker_id", SqlScalarType::UInt64.nullable(false))
8614        .with_column("sent", SqlScalarType::Int64.nullable(false))
8615        .with_column("received", SqlScalarType::Int64.nullable(false))
8616        .with_column("batch_sent", SqlScalarType::Int64.nullable(false))
8617        .with_column("batch_received", SqlScalarType::Int64.nullable(false))
8618        .with_key(vec![0, 1, 2])
8619        .finish(),
8620    column_comments: BTreeMap::new(),
8621    sql: "
8622WITH batch_sent_cte AS (
8623    SELECT
8624        channel_id,
8625        from_worker_id,
8626        to_worker_id,
8627        pg_catalog.count(*) AS sent
8628    FROM
8629        mz_introspection.mz_message_batch_counts_sent_raw
8630    GROUP BY
8631        channel_id, from_worker_id, to_worker_id
8632),
8633batch_received_cte AS (
8634    SELECT
8635        channel_id,
8636        from_worker_id,
8637        to_worker_id,
8638        pg_catalog.count(*) AS received
8639    FROM
8640        mz_introspection.mz_message_batch_counts_received_raw
8641    GROUP BY
8642        channel_id, from_worker_id, to_worker_id
8643),
8644sent_cte AS (
8645    SELECT
8646        channel_id,
8647        from_worker_id,
8648        to_worker_id,
8649        pg_catalog.count(*) AS sent
8650    FROM
8651        mz_introspection.mz_message_counts_sent_raw
8652    GROUP BY
8653        channel_id, from_worker_id, to_worker_id
8654),
8655received_cte AS (
8656    SELECT
8657        channel_id,
8658        from_worker_id,
8659        to_worker_id,
8660        pg_catalog.count(*) AS received
8661    FROM
8662        mz_introspection.mz_message_counts_received_raw
8663    GROUP BY
8664        channel_id, from_worker_id, to_worker_id
8665)
8666SELECT
8667    sent_cte.channel_id,
8668    sent_cte.from_worker_id,
8669    sent_cte.to_worker_id,
8670    sent_cte.sent,
8671    received_cte.received,
8672    batch_sent_cte.sent AS batch_sent,
8673    batch_received_cte.received AS batch_received
8674FROM sent_cte
8675JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8676JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8677JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8678    access: vec![PUBLIC_SELECT],
8679});
8680
8681pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8682    name: "mz_message_counts",
8683    schema: MZ_INTROSPECTION_SCHEMA,
8684    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8685    desc: RelationDesc::builder()
8686        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8687        .with_column(
8688            "sent",
8689            SqlScalarType::Numeric {
8690                max_scale: Some(NumericMaxScale::ZERO),
8691            }
8692            .nullable(false),
8693        )
8694        .with_column(
8695            "received",
8696            SqlScalarType::Numeric {
8697                max_scale: Some(NumericMaxScale::ZERO),
8698            }
8699            .nullable(false),
8700        )
8701        .with_column(
8702            "batch_sent",
8703            SqlScalarType::Numeric {
8704                max_scale: Some(NumericMaxScale::ZERO),
8705            }
8706            .nullable(false),
8707        )
8708        .with_column(
8709            "batch_received",
8710            SqlScalarType::Numeric {
8711                max_scale: Some(NumericMaxScale::ZERO),
8712            }
8713            .nullable(false),
8714        )
8715        .with_key(vec![0])
8716        .finish(),
8717    column_comments: BTreeMap::from_iter([
8718        (
8719            "channel_id",
8720            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8721        ),
8722        ("sent", "The number of messages sent."),
8723        ("received", "The number of messages received."),
8724        ("batch_sent", "The number of batches sent."),
8725        ("batch_received", "The number of batches received."),
8726    ]),
8727    sql: "
8728SELECT
8729    channel_id,
8730    pg_catalog.sum(sent) AS sent,
8731    pg_catalog.sum(received) AS received,
8732    pg_catalog.sum(batch_sent) AS batch_sent,
8733    pg_catalog.sum(batch_received) AS batch_received
8734FROM mz_introspection.mz_message_counts_per_worker
8735GROUP BY channel_id",
8736    access: vec![PUBLIC_SELECT],
8737});
8738
8739pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8740    name: "mz_active_peeks",
8741    schema: MZ_INTROSPECTION_SCHEMA,
8742    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8743    desc: RelationDesc::builder()
8744        .with_column("id", SqlScalarType::Uuid.nullable(false))
8745        .with_column("object_id", SqlScalarType::String.nullable(false))
8746        .with_column("type", SqlScalarType::String.nullable(false))
8747        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
8748        .finish(),
8749    column_comments: BTreeMap::from_iter([
8750        ("id", "The ID of the peek request."),
8751        (
8752            "object_id",
8753            "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`.",
8754        ),
8755        (
8756            "type",
8757            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8758        ),
8759        ("time", "The timestamp the peek has requested."),
8760    ]),
8761    sql: "
8762SELECT id, object_id, type, time
8763FROM mz_introspection.mz_active_peeks_per_worker
8764WHERE worker_id = 0",
8765    access: vec![PUBLIC_SELECT],
8766});
8767
8768pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8769    LazyLock::new(|| BuiltinView {
8770        name: "mz_dataflow_operator_reachability_per_worker",
8771        schema: MZ_INTROSPECTION_SCHEMA,
8772        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8773        desc: RelationDesc::builder()
8774            .with_column("id", SqlScalarType::UInt64.nullable(false))
8775            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8776            .with_column("port", SqlScalarType::UInt64.nullable(false))
8777            .with_column("update_type", SqlScalarType::String.nullable(false))
8778            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8779            .with_column("count", SqlScalarType::Int64.nullable(false))
8780            .with_key(vec![0, 1, 2, 3, 4])
8781            .finish(),
8782        column_comments: BTreeMap::new(),
8783        sql: "SELECT
8784    addr2.id,
8785    reachability.worker_id,
8786    port,
8787    update_type,
8788    time,
8789    pg_catalog.count(*) as count
8790FROM
8791    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8792    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8793    mz_introspection.mz_dataflow_addresses_per_worker addr2
8794WHERE
8795    addr2.address =
8796    CASE
8797        WHEN source = 0 THEN addr1.address
8798        ELSE addr1.address || reachability.source
8799    END
8800    AND addr1.id = reachability.id
8801    AND addr1.worker_id = reachability.worker_id
8802    AND addr2.worker_id = reachability.worker_id
8803GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8804        access: vec![PUBLIC_SELECT],
8805    });
8806
8807pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8808    LazyLock::new(|| BuiltinView {
8809        name: "mz_dataflow_operator_reachability",
8810        schema: MZ_INTROSPECTION_SCHEMA,
8811        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8812        desc: RelationDesc::builder()
8813            .with_column("id", SqlScalarType::UInt64.nullable(false))
8814            .with_column("port", SqlScalarType::UInt64.nullable(false))
8815            .with_column("update_type", SqlScalarType::String.nullable(false))
8816            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8817            .with_column(
8818                "count",
8819                SqlScalarType::Numeric {
8820                    max_scale: Some(NumericMaxScale::ZERO),
8821                }
8822                .nullable(false),
8823            )
8824            .with_key(vec![0, 1, 2, 3])
8825            .finish(),
8826        column_comments: BTreeMap::new(),
8827        sql: "
8828SELECT
8829    id,
8830    port,
8831    update_type,
8832    time,
8833    pg_catalog.sum(count) as count
8834FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8835GROUP BY id, port, update_type, time",
8836        access: vec![PUBLIC_SELECT],
8837    });
8838
8839pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8840    BuiltinView {
8841        name: "mz_arrangement_sizes_per_worker",
8842        schema: MZ_INTROSPECTION_SCHEMA,
8843        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8844        desc: RelationDesc::builder()
8845            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8846            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8847            .with_column("records", SqlScalarType::Int64.nullable(true))
8848            .with_column("batches", SqlScalarType::Int64.nullable(true))
8849            .with_column("size", SqlScalarType::Int64.nullable(true))
8850            .with_column("capacity", SqlScalarType::Int64.nullable(true))
8851            .with_column("allocations", SqlScalarType::Int64.nullable(true))
8852            .finish(),
8853        column_comments: BTreeMap::new(),
8854        sql: "
8855WITH operators_per_worker_cte AS (
8856    SELECT
8857        id AS operator_id,
8858        worker_id
8859    FROM
8860        mz_introspection.mz_dataflow_operators_per_worker
8861),
8862batches_cte AS (
8863    SELECT
8864        operator_id,
8865        worker_id,
8866        COUNT(*) AS batches
8867    FROM
8868        mz_introspection.mz_arrangement_batches_raw
8869    GROUP BY
8870        operator_id, worker_id
8871),
8872records_cte AS (
8873    SELECT
8874        operator_id,
8875        worker_id,
8876        COUNT(*) AS records
8877    FROM
8878        mz_introspection.mz_arrangement_records_raw
8879    GROUP BY
8880        operator_id, worker_id
8881),
8882heap_size_cte AS (
8883    SELECT
8884        operator_id,
8885        worker_id,
8886        COUNT(*) AS size
8887    FROM
8888        mz_introspection.mz_arrangement_heap_size_raw
8889    GROUP BY
8890        operator_id, worker_id
8891),
8892heap_capacity_cte AS (
8893    SELECT
8894        operator_id,
8895        worker_id,
8896        COUNT(*) AS capacity
8897    FROM
8898        mz_introspection.mz_arrangement_heap_capacity_raw
8899    GROUP BY
8900        operator_id, worker_id
8901),
8902heap_allocations_cte AS (
8903    SELECT
8904        operator_id,
8905        worker_id,
8906        COUNT(*) AS allocations
8907    FROM
8908        mz_introspection.mz_arrangement_heap_allocations_raw
8909    GROUP BY
8910        operator_id, worker_id
8911),
8912batcher_records_cte AS (
8913    SELECT
8914        operator_id,
8915        worker_id,
8916        COUNT(*) AS records
8917    FROM
8918        mz_introspection.mz_arrangement_batcher_records_raw
8919    GROUP BY
8920        operator_id, worker_id
8921),
8922batcher_size_cte AS (
8923    SELECT
8924        operator_id,
8925        worker_id,
8926        COUNT(*) AS size
8927    FROM
8928        mz_introspection.mz_arrangement_batcher_size_raw
8929    GROUP BY
8930        operator_id, worker_id
8931),
8932batcher_capacity_cte AS (
8933    SELECT
8934        operator_id,
8935        worker_id,
8936        COUNT(*) AS capacity
8937    FROM
8938        mz_introspection.mz_arrangement_batcher_capacity_raw
8939    GROUP BY
8940        operator_id, worker_id
8941),
8942batcher_allocations_cte AS (
8943    SELECT
8944        operator_id,
8945        worker_id,
8946        COUNT(*) AS allocations
8947    FROM
8948        mz_introspection.mz_arrangement_batcher_allocations_raw
8949    GROUP BY
8950        operator_id, worker_id
8951),
8952combined AS (
8953    SELECT
8954        opw.operator_id,
8955        opw.worker_id,
8956        CASE
8957            WHEN records_cte.records IS NULL AND batcher_records_cte.records IS NULL THEN NULL
8958            ELSE COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0)
8959        END AS records,
8960        batches_cte.batches AS batches,
8961        CASE
8962            WHEN heap_size_cte.size IS NULL AND batcher_size_cte.size IS NULL THEN NULL
8963            ELSE COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0)
8964        END AS size,
8965        CASE
8966            WHEN heap_capacity_cte.capacity IS NULL AND batcher_capacity_cte.capacity IS NULL THEN NULL
8967            ELSE COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0)
8968        END AS capacity,
8969        CASE
8970            WHEN heap_allocations_cte.allocations IS NULL AND batcher_allocations_cte.allocations IS NULL THEN NULL
8971            ELSE COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0)
8972        END AS allocations
8973    FROM
8974                    operators_per_worker_cte opw
8975    LEFT OUTER JOIN batches_cte USING (operator_id, worker_id)
8976    LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
8977    LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
8978    LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
8979    LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
8980    LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
8981    LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
8982    LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
8983    LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)
8984)
8985SELECT
8986    operator_id, worker_id, records, batches, size, capacity, allocations
8987FROM combined
8988WHERE
8989       records     IS NOT NULL
8990    OR batches     IS NOT NULL
8991    OR size        IS NOT NULL
8992    OR capacity    IS NOT NULL
8993    OR allocations IS NOT NULL
8994",
8995        access: vec![PUBLIC_SELECT],
8996    }
8997});
8998
8999pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9000    name: "mz_arrangement_sizes",
9001    schema: MZ_INTROSPECTION_SCHEMA,
9002    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
9003    desc: RelationDesc::builder()
9004        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9005        .with_column("records", SqlScalarType::Int64.nullable(true))
9006        .with_column("batches", SqlScalarType::Int64.nullable(true))
9007        .with_column("size", SqlScalarType::Int64.nullable(true))
9008        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9009        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9010        .with_key(vec![0])
9011        .finish(),
9012    column_comments: BTreeMap::from_iter([
9013        (
9014            "operator_id",
9015            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
9016        ),
9017        ("records", "The number of records in the arrangement."),
9018        ("batches", "The number of batches in the arrangement."),
9019        ("size", "The utilized size in bytes of the arrangement."),
9020        (
9021            "capacity",
9022            "The capacity in bytes of the arrangement. Can be larger than the size.",
9023        ),
9024        (
9025            "allocations",
9026            "The number of separate memory allocations backing the arrangement.",
9027        ),
9028    ]),
9029    sql: "
9030SELECT
9031    operator_id,
9032    SUM(records)::int8 AS records,
9033    SUM(batches)::int8 AS batches,
9034    SUM(size)::int8 AS size,
9035    SUM(capacity)::int8 AS capacity,
9036    SUM(allocations)::int8 AS allocations
9037FROM mz_introspection.mz_arrangement_sizes_per_worker
9038GROUP BY operator_id",
9039    access: vec![PUBLIC_SELECT],
9040});
9041
9042pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
9043    LazyLock::new(|| BuiltinView {
9044        name: "mz_arrangement_sharing_per_worker",
9045        schema: MZ_INTROSPECTION_SCHEMA,
9046        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
9047        desc: RelationDesc::builder()
9048            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9049            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
9050            .with_column("count", SqlScalarType::Int64.nullable(false))
9051            .with_key(vec![0, 1])
9052            .finish(),
9053        column_comments: BTreeMap::new(),
9054        sql: "
9055SELECT
9056    operator_id,
9057    worker_id,
9058    pg_catalog.count(*) AS count
9059FROM mz_introspection.mz_arrangement_sharing_raw
9060GROUP BY operator_id, worker_id",
9061        access: vec![PUBLIC_SELECT],
9062    });
9063
9064pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9065    name: "mz_arrangement_sharing",
9066    schema: MZ_INTROSPECTION_SCHEMA,
9067    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
9068    desc: RelationDesc::builder()
9069        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9070        .with_column("count", SqlScalarType::Int64.nullable(false))
9071        .finish(),
9072    column_comments: BTreeMap::from_iter([
9073        (
9074            "operator_id",
9075            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
9076        ),
9077        (
9078            "count",
9079            "The number of operators that share the arrangement.",
9080        ),
9081    ]),
9082    sql: "
9083SELECT operator_id, count
9084FROM mz_introspection.mz_arrangement_sharing_per_worker
9085WHERE worker_id = 0",
9086    access: vec![PUBLIC_SELECT],
9087});
9088
9089pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9090    name: "mz_cluster_replica_utilization",
9091    schema: MZ_INTERNAL_SCHEMA,
9092    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
9093    desc: RelationDesc::builder()
9094        .with_column("replica_id", SqlScalarType::String.nullable(false))
9095        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
9096        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
9097        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
9098        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
9099        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
9100        .finish(),
9101    column_comments: BTreeMap::from_iter([
9102        ("replica_id", "The ID of a cluster replica."),
9103        ("process_id", "The ID of a process within the replica."),
9104        (
9105            "cpu_percent",
9106            "Approximate CPU usage, in percent of the total allocation.",
9107        ),
9108        (
9109            "memory_percent",
9110            "Approximate RAM usage, in percent of the total allocation.",
9111        ),
9112        (
9113            "disk_percent",
9114            "Approximate disk usage, in percent of the total allocation.",
9115        ),
9116        (
9117            "heap_percent",
9118            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
9119        ),
9120    ]),
9121    sql: "
9122SELECT
9123    r.id AS replica_id,
9124    m.process_id,
9125    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
9126    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
9127    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
9128    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent
9129FROM
9130    mz_catalog.mz_cluster_replicas AS r
9131        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
9132        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
9133    access: vec![PUBLIC_SELECT],
9134});
9135
9136pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
9137    LazyLock::new(|| BuiltinView {
9138        name: "mz_cluster_replica_utilization_history",
9139        schema: MZ_INTERNAL_SCHEMA,
9140        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
9141        desc: RelationDesc::builder()
9142            .with_column("replica_id", SqlScalarType::String.nullable(false))
9143            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
9144            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
9145            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
9146            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
9147            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
9148            .with_column(
9149                "occurred_at",
9150                SqlScalarType::TimestampTz { precision: None }.nullable(false),
9151            )
9152            .finish(),
9153        column_comments: BTreeMap::from_iter([
9154            ("replica_id", "The ID of a cluster replica."),
9155            ("process_id", "The ID of a process within the replica."),
9156            (
9157                "cpu_percent",
9158                "Approximate CPU usage, in percent of the total allocation.",
9159            ),
9160            (
9161                "memory_percent",
9162                "Approximate RAM usage, in percent of the total allocation.",
9163            ),
9164            (
9165                "disk_percent",
9166                "Approximate disk usage, in percent of the total allocation.",
9167            ),
9168            (
9169                "heap_percent",
9170                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
9171            ),
9172            (
9173                "occurred_at",
9174                "Wall-clock timestamp at which the event occurred.",
9175            ),
9176        ]),
9177        sql: "
9178SELECT
9179    r.id AS replica_id,
9180    m.process_id,
9181    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
9182    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
9183    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
9184    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
9185    m.occurred_at
9186FROM
9187    mz_catalog.mz_cluster_replicas AS r
9188        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
9189        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
9190        access: vec![PUBLIC_SELECT],
9191    });
9192
9193pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
9194    LazyLock::new(|| BuiltinView {
9195        name: "mz_dataflow_operator_parents_per_worker",
9196        schema: MZ_INTROSPECTION_SCHEMA,
9197        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
9198        desc: RelationDesc::builder()
9199            .with_column("id", SqlScalarType::UInt64.nullable(false))
9200            .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9201            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
9202            .finish(),
9203        column_comments: BTreeMap::new(),
9204        sql: "
9205WITH operator_addrs AS(
9206    SELECT
9207        id, address, worker_id
9208    FROM mz_introspection.mz_dataflow_addresses_per_worker
9209        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
9210            USING (id, worker_id)
9211),
9212parent_addrs AS (
9213    SELECT
9214        id,
9215        address[1:list_length(address) - 1] AS parent_address,
9216        worker_id
9217    FROM operator_addrs
9218)
9219SELECT pa.id, oa.id AS parent_id, pa.worker_id
9220FROM parent_addrs AS pa
9221    INNER JOIN operator_addrs AS oa
9222        ON pa.parent_address = oa.address
9223        AND pa.worker_id = oa.worker_id",
9224        access: vec![PUBLIC_SELECT],
9225    });
9226
9227pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9228    name: "mz_dataflow_operator_parents",
9229    schema: MZ_INTROSPECTION_SCHEMA,
9230    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
9231    desc: RelationDesc::builder()
9232        .with_column("id", SqlScalarType::UInt64.nullable(false))
9233        .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9234        .finish(),
9235    column_comments: BTreeMap::from_iter([
9236        (
9237            "id",
9238            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
9239        ),
9240        (
9241            "parent_id",
9242            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
9243        ),
9244    ]),
9245    sql: "
9246SELECT id, parent_id
9247FROM mz_introspection.mz_dataflow_operator_parents_per_worker
9248WHERE worker_id = 0",
9249    access: vec![PUBLIC_SELECT],
9250});
9251
9252pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9253    name: "mz_dataflow_arrangement_sizes",
9254    schema: MZ_INTROSPECTION_SCHEMA,
9255    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
9256    desc: RelationDesc::builder()
9257        .with_column("id", SqlScalarType::UInt64.nullable(false))
9258        .with_column("name", SqlScalarType::String.nullable(false))
9259        .with_column("records", SqlScalarType::Int64.nullable(true))
9260        .with_column("batches", SqlScalarType::Int64.nullable(true))
9261        .with_column("size", SqlScalarType::Int64.nullable(true))
9262        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9263        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9264        .with_key(vec![0, 1])
9265        .finish(),
9266    column_comments: BTreeMap::from_iter([
9267        (
9268            "id",
9269            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9270        ),
9271        ("name", "The name of the [dataflow]."),
9272        (
9273            "records",
9274            "The number of records in all arrangements in the dataflow.",
9275        ),
9276        (
9277            "batches",
9278            "The number of batches in all arrangements in the dataflow.",
9279        ),
9280        ("size", "The utilized size in bytes of the arrangements."),
9281        (
9282            "capacity",
9283            "The capacity in bytes of the arrangements. Can be larger than the size.",
9284        ),
9285        (
9286            "allocations",
9287            "The number of separate memory allocations backing the arrangements.",
9288        ),
9289    ]),
9290    sql: "
9291SELECT
9292    mdod.dataflow_id AS id,
9293    mdod.dataflow_name AS name,
9294    SUM(mas.records)::int8 AS records,
9295    SUM(mas.batches)::int8 AS batches,
9296    SUM(mas.size)::int8 AS size,
9297    SUM(mas.capacity)::int8 AS capacity,
9298    SUM(mas.allocations)::int8 AS allocations
9299FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9300LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9301    ON mdod.id = mas.operator_id
9302GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9303    access: vec![PUBLIC_SELECT],
9304});
9305
9306pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9307    name: "mz_expected_group_size_advice",
9308    schema: MZ_INTROSPECTION_SCHEMA,
9309    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9310    desc: RelationDesc::builder()
9311        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
9312        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
9313        .with_column("region_id", SqlScalarType::UInt64.nullable(false))
9314        .with_column("region_name", SqlScalarType::String.nullable(false))
9315        .with_column("levels", SqlScalarType::Int64.nullable(false))
9316        .with_column("to_cut", SqlScalarType::Int64.nullable(false))
9317        .with_column(
9318            "savings",
9319            SqlScalarType::Numeric {
9320                max_scale: Some(NumericMaxScale::ZERO),
9321            }
9322            .nullable(true),
9323        )
9324        .with_column("hint", SqlScalarType::Float64.nullable(false))
9325        .finish(),
9326    column_comments: BTreeMap::from_iter([
9327        (
9328            "dataflow_id",
9329            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9330        ),
9331        (
9332            "dataflow_name",
9333            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9334        ),
9335        (
9336            "region_id",
9337            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9338        ),
9339        (
9340            "region_name",
9341            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9342        ),
9343        (
9344            "levels",
9345            "The number of levels in the hierarchical scheme implemented by the region.",
9346        ),
9347        (
9348            "to_cut",
9349            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9350        ),
9351        (
9352            "savings",
9353            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9354        ),
9355        (
9356            "hint",
9357            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9358        ),
9359    ]),
9360    sql: "
9361        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9362        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9363        -- of arrangements must be built. For each dataflow and region corresponding to one
9364        -- such pattern, we look for how many levels can be eliminated without hitting a level
9365        -- that actually substantially filters the input. The advice is constructed so that
9366        -- setting the hint for the affected region will eliminate these redundant levels of
9367        -- the hierarchical rendering.
9368        --
9369        -- A number of helper CTEs are used for the view definition. The first one, operators,
9370        -- looks for operator names that comprise arrangements of inputs to each level of a
9371        -- min/max/top-k hierarchy.
9372        WITH operators AS (
9373            SELECT
9374                dod.dataflow_id,
9375                dor.id AS region_id,
9376                dod.id,
9377                ars.records,
9378                ars.size
9379            FROM
9380                mz_introspection.mz_dataflow_operator_dataflows dod
9381                JOIN mz_introspection.mz_dataflow_addresses doa
9382                    ON dod.id = doa.id
9383                JOIN mz_introspection.mz_dataflow_addresses dra
9384                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9385                JOIN mz_introspection.mz_dataflow_operators dor
9386                    ON dor.id = dra.id
9387                JOIN mz_introspection.mz_arrangement_sizes ars
9388                    ON ars.operator_id = dod.id
9389            WHERE
9390                dod.name = 'Arranged TopK input'
9391                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9392                OR dod.name = 'Arrange ReduceMinsMaxes'
9393            ),
9394        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9395        -- identified in operators above.
9396        levels AS (
9397            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9398            FROM operators o
9399            GROUP BY o.dataflow_id, o.region_id
9400        ),
9401        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9402        -- operator. This operator is crucially important, as it records the number of records
9403        -- that was given as input to the gadget as a whole.
9404        pivot AS (
9405            SELECT
9406                o1.dataflow_id,
9407                o1.region_id,
9408                o1.id,
9409                o1.records
9410            FROM operators o1
9411            WHERE
9412                o1.id = (
9413                    SELECT MIN(o2.id)
9414                    FROM operators o2
9415                    WHERE
9416                        o2.dataflow_id = o1.dataflow_id
9417                        AND o2.region_id = o1.region_id
9418                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9419                )
9420        ),
9421        -- The fourth CTE, candidates, will look for operators where the number of records
9422        -- maintained is not significantly different from the number at the pivot (excluding
9423        -- the pivot itself). These are the candidates for being cut from the dataflow region
9424        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9425        -- load generator data, to give some room for small deviations in number of records.
9426        -- The intuition for allowing for this deviation is that we are looking for a strongly
9427        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9428        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9429        -- among groups where the min/max/top-k computation is (partially) applied. If the
9430        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9431        -- groups might be empty or contain only one row. Each subsequent level will have a number
9432        -- of groups that is reduced exponentially. So at some point, we will find the level where
9433        -- we actually start having a few rows per group. That's where we will see the row counts
9434        -- significantly drop off.
9435        candidates AS (
9436            SELECT
9437                o.dataflow_id,
9438                o.region_id,
9439                o.id,
9440                o.records,
9441                o.size
9442            FROM
9443                operators o
9444                JOIN pivot p
9445                    ON o.dataflow_id = p.dataflow_id
9446                        AND o.region_id = p.region_id
9447                        AND o.id <> p.id
9448            WHERE o.records >= p.records * (1 - 0.15)
9449        ),
9450        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9451        -- candidate levels that should be cut. We only return here dataflow regions where at
9452        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9453        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9454        -- cutting the height of the hierarchy further. This is because we will have way less
9455        -- groups in the next level, so there should be even further reduction happening or there
9456        -- is some substantial skew in the data. But if the latter is the case, then we should not
9457        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9458        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9459        -- compute a conservative estimate of the memory savings in bytes that will result from
9460        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9461        -- input arrangements for each level to be cut. These arrangements should dominate the
9462        -- size of each level that can be cut, since the reduction gadget internal to the level
9463        -- does not remove much data at these levels.
9464        cuts AS (
9465            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9466            FROM candidates c
9467            GROUP BY c.dataflow_id, c.region_id
9468            HAVING COUNT(*) > 0
9469        )
9470        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9471        -- levels and the number of candidates to be cut. The hint is computed taking into account
9472        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9473        -- currently equal to 16.
9474        SELECT
9475            dod.dataflow_id,
9476            dod.dataflow_name,
9477            dod.id AS region_id,
9478            dod.name AS region_name,
9479            l.levels,
9480            c.to_cut,
9481            c.savings,
9482            pow(16, l.levels - c.to_cut) - 1 AS hint
9483        FROM cuts c
9484            JOIN levels l
9485                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9486            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9487                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9488    access: vec![PUBLIC_SELECT],
9489});
9490
9491pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9492    BuiltinView {
9493        name: "mz_index_advice",
9494        schema: MZ_INTERNAL_SCHEMA,
9495        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9496        desc: RelationDesc::builder()
9497            .with_column("object_id", SqlScalarType::String.nullable(true))
9498            .with_column("hint", SqlScalarType::String.nullable(false))
9499            .with_column("details", SqlScalarType::String.nullable(false))
9500            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
9501            .finish(),
9502        column_comments: BTreeMap::from_iter([
9503            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9504            ("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."),
9505            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9506            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9507        ]),
9508        sql: "
9509-- To avoid confusion with sources and sinks in the materialize sense,
9510-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9511-- when referring to the object dependency graph.
9512--
9513-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9514-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9515-- that are not depended on by other maintained objects and have a justification why they must
9516-- be maintained (e.g. a materialized view that is depended on by a sink).
9517-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9518-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9519-- downstream objects, that node is marked to be converted into a maintained object and this
9520-- node is then propagated further up. Once completed, the list of objects that are marked as
9521-- maintained is checked against all objects to generate appropriate recommendations.
9522--
9523-- Note that the recommendations only incorporate dependencies between objects.
9524-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9525-- a sink if an index is added in between the sink and the filter. For very selective filters,
9526-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9527-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9528-- dependencies.
9529WITH MUTUALLY RECURSIVE
9530    -- for all objects, understand if they have an index on them and on which cluster they are running
9531    -- this avoids having different cases for views with an index and materialized views later on
9532    objects(id text, type text, cluster_id text, indexes text list) AS (
9533        -- views and materialized views without an index
9534        SELECT
9535            o.id,
9536            o.type,
9537            o.cluster_id,
9538            '{}'::text list AS indexes
9539        FROM mz_catalog.mz_objects o
9540        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9541            SELECT FROM mz_internal.mz_object_dependencies d
9542            JOIN mz_catalog.mz_objects AS i
9543                ON (i.id = d.object_id AND i.type = 'index')
9544            WHERE (o.id = d.referenced_object_id)
9545        )
9546
9547        UNION ALL
9548
9549        -- views and materialized views with an index
9550        SELECT
9551            o.id,
9552            o.type,
9553            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9554            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9555            list_agg(i.id) AS indexes
9556        FROM mz_catalog.mz_objects o
9557        JOIN mz_internal.mz_object_dependencies AS d
9558            ON (o.id = d.referenced_object_id)
9559        JOIN mz_catalog.mz_objects AS i
9560            ON (i.id = d.object_id AND i.type = 'index')
9561        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9562        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9563    ),
9564
9565    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9566    maintained_leafs(id text, justification text) AS (
9567        -- materialized views that are connected to a sink
9568        SELECT
9569            m.id,
9570            s.id AS justification
9571        FROM objects AS m
9572        JOIN mz_internal.mz_object_dependencies AS d
9573            ON (m.id = d.referenced_object_id)
9574        JOIN mz_catalog.mz_objects AS s
9575            ON (s.id = d.object_id AND s.type = 'sink')
9576        WHERE m.type = 'materialized-view'
9577
9578        UNION ALL
9579
9580        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9581        SELECT
9582            v.id,
9583            unnest(v.indexes) AS justification
9584        FROM objects AS v
9585        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9586            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9587            INNER JOIN mz_catalog.mz_objects AS child
9588                ON (d.object_id = child.id)
9589            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]
9590        )
9591    ),
9592
9593    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9594    agg_maintained_children(id text, maintained_children text list) AS (
9595        SELECT
9596            parent_id AS id,
9597            list_agg(maintained_child) AS maintained_leafs
9598        FROM (
9599            SELECT DISTINCT
9600                d.referenced_object_id AS parent_id,
9601                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9602                unnest(child.maintained_children) AS maintained_child
9603            FROM propagate_dependencies AS child
9604            INNER JOIN mz_internal.mz_object_dependencies AS d
9605                ON (child.id = d.object_id)
9606        )
9607        GROUP BY parent_id
9608    ),
9609
9610    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9611    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9612    -- 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
9613    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9614        -- base case: start with the leafs
9615        SELECT DISTINCT
9616            id,
9617            LIST[id] AS maintained_children,
9618            list_agg(justification) AS justification
9619        FROM maintained_leafs
9620        GROUP BY id
9621
9622        UNION
9623
9624        -- recursive case: if there is a child with the same dependencies as the parent,
9625        -- the parent is only reused by a single child
9626        SELECT
9627            parent.id,
9628            child.maintained_children,
9629            NULL::text list AS justification
9630        FROM agg_maintained_children AS parent
9631        INNER JOIN mz_internal.mz_object_dependencies AS d
9632            ON (parent.id = d.referenced_object_id)
9633        INNER JOIN propagate_dependencies AS child
9634            ON (d.object_id = child.id)
9635        WHERE parent.maintained_children = child.maintained_children
9636
9637        UNION
9638
9639        -- recursive case: if there is NO child with the same dependencies as the parent,
9640        -- different children are reusing the parent so maintaining the object is justified by itself
9641        SELECT DISTINCT
9642            parent.id,
9643            LIST[parent.id] AS maintained_children,
9644            parent.maintained_children AS justification
9645        FROM agg_maintained_children AS parent
9646        WHERE NOT EXISTS (
9647            SELECT FROM mz_internal.mz_object_dependencies AS d
9648            INNER JOIN propagate_dependencies AS child
9649                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9650            WHERE parent.maintained_children = child.maintained_children
9651        )
9652    ),
9653
9654    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9655        SELECT
9656            p.id,
9657            o.type,
9658            o.cluster_id,
9659            p.maintained_children,
9660            p.justification,
9661            o.indexes
9662        FROM propagate_dependencies p
9663        JOIN objects AS o
9664            ON (p.id = o.id)
9665    ),
9666
9667    hints(id text, hint text, details text, justification text list) AS (
9668        -- materialized views that are not required
9669        SELECT
9670            id,
9671            'convert to a view' AS hint,
9672            'no dependencies from sinks nor from objects on different clusters' AS details,
9673            justification
9674        FROM objects_with_justification
9675        WHERE type = 'materialized-view' AND justification IS NULL
9676
9677        UNION ALL
9678
9679        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9680        SELECT
9681            id,
9682            'keep' AS hint,
9683            'dependencies from sinks or objects on different clusters: ' AS details,
9684            justification
9685        FROM objects_with_justification AS m
9686        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9687            SELECT FROM unnest(justification) AS dependency
9688            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9689
9690            UNION ALL
9691
9692            SELECT FROM unnest(justification) AS dependency
9693            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9694            WHERE d.cluster_id != m.cluster_id
9695        )
9696
9697        UNION ALL
9698
9699        -- 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
9700        SELECT
9701            id,
9702            'convert to a view with an index' AS hint,
9703            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9704            justification
9705        FROM objects_with_justification AS m
9706        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT 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        -- views that have indexes on different clusters should be a materialized view
9720        SELECT
9721            o.id,
9722            'convert to materialized view' AS hint,
9723            'dependencies on multiple clusters: ' AS details,
9724            o.justification
9725        FROM objects_with_justification o,
9726            LATERAL unnest(o.justification) j
9727        LEFT JOIN mz_catalog.mz_objects AS m
9728            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9729        WHERE o.type = 'view' AND o.justification IS NOT NULL
9730        GROUP BY o.id, o.justification
9731        HAVING count(DISTINCT m.cluster_id) >= 2
9732
9733        UNION ALL
9734
9735        -- views without an index that should be maintained
9736        SELECT
9737            id,
9738            'add index' AS hint,
9739            'multiple downstream dependencies: ' AS details,
9740            justification
9741        FROM objects_with_justification
9742        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9743
9744        UNION ALL
9745
9746        -- index inside the dependency graph (not a leaf)
9747        SELECT
9748            unnest(indexes) AS id,
9749            'drop unless queried directly' AS hint,
9750            'fewer than two downstream dependencies: ' AS details,
9751            maintained_children AS justification
9752        FROM objects_with_justification
9753        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9754
9755        UNION ALL
9756
9757        -- index on a leaf of the dependency graph
9758        SELECT
9759            unnest(indexes) AS id,
9760            'drop unless queried directly' AS hint,
9761            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9762            NULL::text list AS justification
9763        FROM objects_with_justification
9764        -- indexes can only be part of justification for leaf nodes
9765        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9766
9767        UNION ALL
9768
9769        -- index on a source
9770        SELECT
9771            unnest(indexes) AS id,
9772            'drop unless queried directly' AS hint,
9773            'sources do not transform data and can expose data directly' AS details,
9774            NULL::text list AS justification
9775        FROM objects_with_justification
9776        -- indexes can only be part of justification for leaf nodes
9777        WHERE type = 'source' AND NOT indexes = '{}'::text list
9778
9779        UNION ALL
9780
9781        -- indexes on views inside the dependency graph
9782        SELECT
9783            unnest(indexes) AS id,
9784            'keep' AS hint,
9785            'multiple downstream dependencies: ' AS details,
9786            justification
9787        FROM objects_with_justification
9788        -- indexes can only be part of justification for leaf nodes
9789        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9790    ),
9791
9792    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9793        SELECT
9794            h.id,
9795            h.hint,
9796            h.details || list_agg(o.name)::text AS details,
9797            h.justification
9798        FROM hints AS h,
9799            LATERAL unnest(h.justification) j
9800        JOIN mz_catalog.mz_objects AS o
9801            ON (o.id = j)
9802        GROUP BY h.id, h.hint, h.details, h.justification
9803
9804        UNION ALL
9805
9806        SELECT
9807            id,
9808            hint,
9809            details,
9810            justification
9811        FROM hints
9812        WHERE justification IS NULL
9813    )
9814
9815SELECT
9816    h.id AS object_id,
9817    h.hint AS hint,
9818    h.details,
9819    h.justification AS referenced_object_ids
9820FROM hints_resolved_ids AS h",
9821        access: vec![PUBLIC_SELECT],
9822    }
9823});
9824
9825// NOTE: If you add real data to this implementation, then please update
9826// the related `pg_` function implementations (like `pg_get_constraintdef`)
9827pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9828    name: "pg_constraint",
9829    schema: PG_CATALOG_SCHEMA,
9830    oid: oid::VIEW_PG_CONSTRAINT_OID,
9831    desc: RelationDesc::builder()
9832        .with_column("oid", SqlScalarType::Oid.nullable(false))
9833        .with_column("conname", SqlScalarType::String.nullable(false))
9834        .with_column("connamespace", SqlScalarType::Oid.nullable(false))
9835        .with_column("contype", SqlScalarType::PgLegacyChar.nullable(false))
9836        .with_column("condeferrable", SqlScalarType::Bool.nullable(false))
9837        .with_column("condeferred", SqlScalarType::Bool.nullable(false))
9838        .with_column("convalidated", SqlScalarType::Bool.nullable(false))
9839        .with_column("conrelid", SqlScalarType::Oid.nullable(false))
9840        .with_column("contypid", SqlScalarType::Oid.nullable(false))
9841        .with_column("conindid", SqlScalarType::Oid.nullable(false))
9842        .with_column("conparentid", SqlScalarType::Oid.nullable(false))
9843        .with_column("confrelid", SqlScalarType::Oid.nullable(false))
9844        .with_column("confupdtype", SqlScalarType::PgLegacyChar.nullable(false))
9845        .with_column("confdeltype", SqlScalarType::PgLegacyChar.nullable(false))
9846        .with_column("confmatchtype", SqlScalarType::PgLegacyChar.nullable(false))
9847        .with_column("conislocal", SqlScalarType::Bool.nullable(false))
9848        .with_column("coninhcount", SqlScalarType::Int32.nullable(false))
9849        .with_column("connoinherit", SqlScalarType::Bool.nullable(false))
9850        .with_column(
9851            "conkey",
9852            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9853        )
9854        .with_column(
9855            "confkey",
9856            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9857        )
9858        .with_column(
9859            "conpfeqop",
9860            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9861        )
9862        .with_column(
9863            "conppeqop",
9864            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9865        )
9866        .with_column(
9867            "conffeqop",
9868            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9869        )
9870        .with_column(
9871            "conexclop",
9872            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9873        )
9874        .with_column("conbin", SqlScalarType::String.nullable(false))
9875        .with_key(vec![])
9876        .finish(),
9877    column_comments: BTreeMap::new(),
9878    sql: "SELECT
9879    NULL::pg_catalog.oid as oid,
9880    NULL::pg_catalog.text as conname,
9881    NULL::pg_catalog.oid as connamespace,
9882    NULL::pg_catalog.\"char\" as contype,
9883    NULL::pg_catalog.bool as condeferrable,
9884    NULL::pg_catalog.bool as condeferred,
9885    NULL::pg_catalog.bool as convalidated,
9886    NULL::pg_catalog.oid as conrelid,
9887    NULL::pg_catalog.oid as contypid,
9888    NULL::pg_catalog.oid as conindid,
9889    NULL::pg_catalog.oid as conparentid,
9890    NULL::pg_catalog.oid as confrelid,
9891    NULL::pg_catalog.\"char\" as confupdtype,
9892    NULL::pg_catalog.\"char\" as confdeltype,
9893    NULL::pg_catalog.\"char\" as confmatchtype,
9894    NULL::pg_catalog.bool as conislocal,
9895    NULL::pg_catalog.int4 as coninhcount,
9896    NULL::pg_catalog.bool as connoinherit,
9897    NULL::pg_catalog.int2[] as conkey,
9898    NULL::pg_catalog.int2[] as confkey,
9899    NULL::pg_catalog.oid[] as conpfeqop,
9900    NULL::pg_catalog.oid[] as conppeqop,
9901    NULL::pg_catalog.oid[] as conffeqop,
9902    NULL::pg_catalog.oid[] as conexclop,
9903    NULL::pg_catalog.text as conbin
9904WHERE false",
9905    access: vec![PUBLIC_SELECT],
9906});
9907
9908pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9909    name: "pg_tables",
9910    schema: PG_CATALOG_SCHEMA,
9911    oid: oid::VIEW_PG_TABLES_OID,
9912    desc: RelationDesc::builder()
9913        .with_column("schemaname", SqlScalarType::String.nullable(true))
9914        .with_column("tablename", SqlScalarType::String.nullable(false))
9915        .with_column("tableowner", SqlScalarType::String.nullable(false))
9916        .finish(),
9917    column_comments: BTreeMap::new(),
9918    sql: "
9919SELECT n.nspname AS schemaname,
9920    c.relname AS tablename,
9921    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
9922FROM pg_catalog.pg_class c
9923LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
9924WHERE c.relkind IN ('r', 'p')",
9925    access: vec![PUBLIC_SELECT],
9926});
9927
9928pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9929    name: "pg_tablespace",
9930    schema: PG_CATALOG_SCHEMA,
9931    oid: oid::VIEW_PG_TABLESPACE_OID,
9932    desc: RelationDesc::builder()
9933        .with_column("oid", SqlScalarType::Oid.nullable(false))
9934        .with_column("spcname", SqlScalarType::String.nullable(false))
9935        .with_column("spcowner", SqlScalarType::Oid.nullable(true))
9936        .with_column(
9937            "spcacl",
9938            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9939        )
9940        .with_column(
9941            "spcoptions",
9942            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9943        )
9944        .with_key(vec![])
9945        .finish(),
9946    column_comments: BTreeMap::new(),
9947    sql: "
9948    SELECT oid, spcname, spcowner, spcacl, spcoptions
9949    FROM (
9950        VALUES (
9951            --These are the same defaults CockroachDB uses.
9952            0::pg_catalog.oid,
9953            'pg_default'::pg_catalog.text,
9954            NULL::pg_catalog.oid,
9955            NULL::pg_catalog.text[],
9956            NULL::pg_catalog.text[]
9957        )
9958    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
9959",
9960    access: vec![PUBLIC_SELECT],
9961});
9962
9963pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9964    name: "pg_am",
9965    schema: PG_CATALOG_SCHEMA,
9966    oid: oid::VIEW_PG_AM_OID,
9967    desc: RelationDesc::builder()
9968        .with_column("oid", SqlScalarType::Oid.nullable(false))
9969        .with_column("amname", SqlScalarType::String.nullable(false))
9970        .with_column("amhandler", SqlScalarType::RegProc.nullable(false))
9971        .with_column("amtype", SqlScalarType::PgLegacyChar.nullable(false))
9972        .with_key(vec![])
9973        .finish(),
9974    column_comments: BTreeMap::new(),
9975    sql: "
9976SELECT NULL::pg_catalog.oid AS oid,
9977    NULL::pg_catalog.text AS amname,
9978    NULL::pg_catalog.regproc AS amhandler,
9979    NULL::pg_catalog.\"char\" AS amtype
9980WHERE false",
9981    access: vec![PUBLIC_SELECT],
9982});
9983
9984pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9985    name: "pg_roles",
9986    schema: PG_CATALOG_SCHEMA,
9987    oid: oid::VIEW_PG_ROLES_OID,
9988    desc: RelationDesc::builder()
9989        .with_column("rolname", SqlScalarType::String.nullable(false))
9990        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
9991        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
9992        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
9993        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
9994        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
9995        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
9996        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
9997        .with_column("rolpassword", SqlScalarType::String.nullable(false))
9998        .with_column(
9999            "rolvaliduntil",
10000            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10001        )
10002        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10003        .with_column(
10004            "rolconfig",
10005            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10006        )
10007        .with_column("oid", SqlScalarType::Oid.nullable(false))
10008        .finish(),
10009    column_comments: BTreeMap::new(),
10010    sql: "SELECT
10011    rolname,
10012    rolsuper,
10013    rolinherit,
10014    rolcreaterole,
10015    rolcreatedb,
10016    COALESCE(rolcanlogin, false) AS rolcanlogin,
10017    rolreplication,
10018    rolconnlimit,
10019    '********' as rolpassword,
10020    rolvaliduntil,
10021    rolbypassrls,
10022    (
10023        SELECT array_agg(parameter_name || '=' || parameter_value)
10024        FROM mz_catalog.mz_role_parameters rp
10025        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
10026        WHERE ai.oid = r.oid
10027    ) AS rolconfig,
10028    oid
10029FROM pg_catalog.pg_authid ai",
10030    access: vec![PUBLIC_SELECT],
10031});
10032
10033pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10034    name: "pg_user",
10035    schema: PG_CATALOG_SCHEMA,
10036    oid: oid::VIEW_PG_USER_OID,
10037    desc: RelationDesc::builder()
10038        .with_column("usename", SqlScalarType::String.nullable(false))
10039        .with_column("usesysid", SqlScalarType::Oid.nullable(false))
10040        .with_column("usecreatedb", SqlScalarType::Bool.nullable(true))
10041        .with_column("usesuper", SqlScalarType::Bool.nullable(true))
10042        .with_column("userepl", SqlScalarType::Bool.nullable(false))
10043        .with_column("usebypassrls", SqlScalarType::Bool.nullable(false))
10044        .with_column("passwd", SqlScalarType::String.nullable(true))
10045        .with_column(
10046            "valuntil",
10047            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10048        )
10049        .with_column(
10050            "useconfig",
10051            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10052        )
10053        .finish(),
10054    column_comments: BTreeMap::new(),
10055    sql: "
10056SELECT
10057    rolname as usename,
10058    ai.oid as usesysid,
10059    rolcreatedb AS usecreatedb,
10060    rolsuper AS usesuper,
10061    rolreplication AS userepl,
10062    rolbypassrls AS usebypassrls,
10063    rolpassword as passwd,
10064    rolvaliduntil as valuntil,
10065    (
10066        SELECT array_agg(parameter_name || '=' || parameter_value)
10067        FROM mz_catalog.mz_role_parameters rp
10068        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
10069        WHERE ai.oid = r.oid
10070    ) AS useconfig
10071FROM pg_catalog.pg_authid ai
10072WHERE rolcanlogin",
10073    access: vec![PUBLIC_SELECT],
10074});
10075
10076pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10077    name: "pg_views",
10078    schema: PG_CATALOG_SCHEMA,
10079    oid: oid::VIEW_PG_VIEWS_OID,
10080    desc: RelationDesc::builder()
10081        .with_column("schemaname", SqlScalarType::String.nullable(true))
10082        .with_column("viewname", SqlScalarType::String.nullable(false))
10083        .with_column("viewowner", SqlScalarType::Oid.nullable(false))
10084        .with_column("definition", SqlScalarType::String.nullable(false))
10085        .finish(),
10086    column_comments: BTreeMap::new(),
10087    sql: "SELECT
10088    s.name AS schemaname,
10089    v.name AS viewname,
10090    role_owner.oid AS viewowner,
10091    v.definition AS definition
10092FROM mz_catalog.mz_views v
10093LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10094LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10095JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
10096WHERE s.database_id IS NULL OR d.name = current_database()",
10097    access: vec![PUBLIC_SELECT],
10098});
10099
10100pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10101    name: "pg_matviews",
10102    schema: PG_CATALOG_SCHEMA,
10103    oid: oid::VIEW_PG_MATVIEWS_OID,
10104    desc: RelationDesc::builder()
10105        .with_column("schemaname", SqlScalarType::String.nullable(true))
10106        .with_column("matviewname", SqlScalarType::String.nullable(false))
10107        .with_column("matviewowner", SqlScalarType::Oid.nullable(false))
10108        .with_column("definition", SqlScalarType::String.nullable(false))
10109        .finish(),
10110    column_comments: BTreeMap::new(),
10111    sql: "SELECT
10112    s.name AS schemaname,
10113    m.name AS matviewname,
10114    role_owner.oid AS matviewowner,
10115    m.definition AS definition
10116FROM mz_catalog.mz_materialized_views m
10117LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
10118LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10119JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
10120WHERE s.database_id IS NULL OR d.name = current_database()",
10121    access: vec![PUBLIC_SELECT],
10122});
10123
10124pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
10125    LazyLock::new(|| BuiltinView {
10126        name: "applicable_roles",
10127        schema: INFORMATION_SCHEMA,
10128        oid: oid::VIEW_APPLICABLE_ROLES_OID,
10129        desc: RelationDesc::builder()
10130            .with_column("grantee", SqlScalarType::String.nullable(false))
10131            .with_column("role_name", SqlScalarType::String.nullable(false))
10132            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10133            .finish(),
10134        column_comments: BTreeMap::new(),
10135        sql: "
10136SELECT
10137    member.name AS grantee,
10138    role.name AS role_name,
10139    -- ADMIN OPTION isn't implemented.
10140    'NO' AS is_grantable
10141FROM mz_catalog.mz_role_members membership
10142JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
10143JOIN mz_catalog.mz_roles member ON membership.member = member.id
10144WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
10145        access: vec![PUBLIC_SELECT],
10146    });
10147
10148pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10149    name: "columns",
10150    schema: INFORMATION_SCHEMA,
10151    oid: oid::VIEW_COLUMNS_OID,
10152    desc: RelationDesc::builder()
10153        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10154        .with_column("table_schema", SqlScalarType::String.nullable(false))
10155        .with_column("table_name", SqlScalarType::String.nullable(false))
10156        .with_column("column_name", SqlScalarType::String.nullable(false))
10157        .with_column("ordinal_position", SqlScalarType::Int64.nullable(false))
10158        .with_column("column_default", SqlScalarType::String.nullable(true))
10159        .with_column("is_nullable", SqlScalarType::String.nullable(false))
10160        .with_column("data_type", SqlScalarType::String.nullable(false))
10161        .with_column(
10162            "character_maximum_length",
10163            SqlScalarType::Int32.nullable(true),
10164        )
10165        .with_column("numeric_precision", SqlScalarType::Int32.nullable(true))
10166        .with_column("numeric_scale", SqlScalarType::Int32.nullable(true))
10167        .finish(),
10168    column_comments: BTreeMap::new(),
10169    sql: "
10170SELECT
10171    current_database() as table_catalog,
10172    s.name AS table_schema,
10173    o.name AS table_name,
10174    c.name AS column_name,
10175    c.position::int8 AS ordinal_position,
10176    c.default AS column_default,
10177    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
10178    c.type AS data_type,
10179    NULL::pg_catalog.int4 AS character_maximum_length,
10180    NULL::pg_catalog.int4 AS numeric_precision,
10181    NULL::pg_catalog.int4 AS numeric_scale
10182FROM mz_catalog.mz_columns c
10183JOIN mz_catalog.mz_objects o ON o.id = c.id
10184JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
10185LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10186WHERE s.database_id IS NULL OR d.name = current_database()",
10187    access: vec![PUBLIC_SELECT],
10188});
10189
10190pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
10191    LazyLock::new(|| BuiltinView {
10192        name: "enabled_roles",
10193        schema: INFORMATION_SCHEMA,
10194        oid: oid::VIEW_ENABLED_ROLES_OID,
10195        desc: RelationDesc::builder()
10196            .with_column("role_name", SqlScalarType::String.nullable(false))
10197            .finish(),
10198        column_comments: BTreeMap::new(),
10199        sql: "
10200SELECT name AS role_name
10201FROM mz_catalog.mz_roles
10202WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
10203        access: vec![PUBLIC_SELECT],
10204    });
10205
10206pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
10207    BuiltinView {
10208        name: "role_table_grants",
10209        schema: INFORMATION_SCHEMA,
10210        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
10211        desc: RelationDesc::builder()
10212            .with_column("grantor", SqlScalarType::String.nullable(false))
10213            .with_column("grantee", SqlScalarType::String.nullable(true))
10214            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10215            .with_column("table_schema", SqlScalarType::String.nullable(false))
10216            .with_column("table_name", SqlScalarType::String.nullable(false))
10217            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10218            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10219            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10220            .finish(),
10221        column_comments: BTreeMap::new(),
10222        sql: "
10223SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
10224FROM information_schema.table_privileges
10225WHERE
10226    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
10227    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
10228        access: vec![PUBLIC_SELECT],
10229    }
10230});
10231
10232pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
10233    LazyLock::new(|| BuiltinView {
10234        name: "key_column_usage",
10235        schema: INFORMATION_SCHEMA,
10236        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
10237        desc: RelationDesc::builder()
10238            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10239            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10240            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10241            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10242            .with_column("table_schema", SqlScalarType::String.nullable(false))
10243            .with_column("table_name", SqlScalarType::String.nullable(false))
10244            .with_column("column_name", SqlScalarType::String.nullable(false))
10245            .with_column("ordinal_position", SqlScalarType::Int32.nullable(false))
10246            .with_column(
10247                "position_in_unique_constraint",
10248                SqlScalarType::Int32.nullable(false),
10249            )
10250            .with_key(vec![])
10251            .finish(),
10252        column_comments: BTreeMap::new(),
10253        sql: "SELECT
10254    NULL::text AS constraint_catalog,
10255    NULL::text AS constraint_schema,
10256    NULL::text AS constraint_name,
10257    NULL::text AS table_catalog,
10258    NULL::text AS table_schema,
10259    NULL::text AS table_name,
10260    NULL::text AS column_name,
10261    NULL::integer AS ordinal_position,
10262    NULL::integer AS position_in_unique_constraint
10263WHERE false",
10264        access: vec![PUBLIC_SELECT],
10265    });
10266
10267pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10268    LazyLock::new(|| BuiltinView {
10269        name: "referential_constraints",
10270        schema: INFORMATION_SCHEMA,
10271        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10272        desc: RelationDesc::builder()
10273            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10274            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10275            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10276            .with_column(
10277                "unique_constraint_catalog",
10278                SqlScalarType::String.nullable(false),
10279            )
10280            .with_column(
10281                "unique_constraint_schema",
10282                SqlScalarType::String.nullable(false),
10283            )
10284            .with_column(
10285                "unique_constraint_name",
10286                SqlScalarType::String.nullable(false),
10287            )
10288            .with_column("match_option", SqlScalarType::String.nullable(false))
10289            .with_column("update_rule", SqlScalarType::String.nullable(false))
10290            .with_column("delete_rule", SqlScalarType::String.nullable(false))
10291            .with_key(vec![])
10292            .finish(),
10293        column_comments: BTreeMap::new(),
10294        sql: "SELECT
10295    NULL::text AS constraint_catalog,
10296    NULL::text AS constraint_schema,
10297    NULL::text AS constraint_name,
10298    NULL::text AS unique_constraint_catalog,
10299    NULL::text AS unique_constraint_schema,
10300    NULL::text AS unique_constraint_name,
10301    NULL::text AS match_option,
10302    NULL::text AS update_rule,
10303    NULL::text AS delete_rule
10304WHERE false",
10305        access: vec![PUBLIC_SELECT],
10306    });
10307
10308pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10309    name: "routines",
10310    schema: INFORMATION_SCHEMA,
10311    oid: oid::VIEW_ROUTINES_OID,
10312    desc: RelationDesc::builder()
10313        .with_column("routine_catalog", SqlScalarType::String.nullable(false))
10314        .with_column("routine_schema", SqlScalarType::String.nullable(false))
10315        .with_column("routine_name", SqlScalarType::String.nullable(false))
10316        .with_column("routine_type", SqlScalarType::String.nullable(false))
10317        .with_column("routine_definition", SqlScalarType::String.nullable(true))
10318        .finish(),
10319    column_comments: BTreeMap::new(),
10320    sql: "SELECT
10321    current_database() as routine_catalog,
10322    s.name AS routine_schema,
10323    f.name AS routine_name,
10324    'FUNCTION' AS routine_type,
10325    NULL::text AS routine_definition
10326FROM mz_catalog.mz_functions f
10327JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10328LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10329WHERE s.database_id IS NULL OR d.name = current_database()",
10330    access: vec![PUBLIC_SELECT],
10331});
10332
10333pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10334    name: "schemata",
10335    schema: INFORMATION_SCHEMA,
10336    oid: oid::VIEW_SCHEMATA_OID,
10337    desc: RelationDesc::builder()
10338        .with_column("catalog_name", SqlScalarType::String.nullable(false))
10339        .with_column("schema_name", SqlScalarType::String.nullable(false))
10340        .finish(),
10341    column_comments: BTreeMap::new(),
10342    sql: "
10343SELECT
10344    current_database() as catalog_name,
10345    s.name AS schema_name
10346FROM mz_catalog.mz_schemas s
10347LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10348WHERE s.database_id IS NULL OR d.name = current_database()",
10349    access: vec![PUBLIC_SELECT],
10350});
10351
10352pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10353    name: "tables",
10354    schema: INFORMATION_SCHEMA,
10355    oid: oid::VIEW_TABLES_OID,
10356    desc: RelationDesc::builder()
10357        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10358        .with_column("table_schema", SqlScalarType::String.nullable(false))
10359        .with_column("table_name", SqlScalarType::String.nullable(false))
10360        .with_column("table_type", SqlScalarType::String.nullable(false))
10361        .finish(),
10362    column_comments: BTreeMap::new(),
10363    sql: "SELECT
10364    current_database() as table_catalog,
10365    s.name AS table_schema,
10366    r.name AS table_name,
10367    CASE r.type
10368        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10369        WHEN 'table' THEN 'BASE TABLE'
10370        ELSE pg_catalog.upper(r.type)
10371    END AS table_type
10372FROM mz_catalog.mz_relations r
10373JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10374LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10375WHERE s.database_id IS NULL OR d.name = current_database()",
10376    access: vec![PUBLIC_SELECT],
10377});
10378
10379pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10380    LazyLock::new(|| BuiltinView {
10381        name: "table_constraints",
10382        schema: INFORMATION_SCHEMA,
10383        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10384        desc: RelationDesc::builder()
10385            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10386            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10387            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10388            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10389            .with_column("table_schema", SqlScalarType::String.nullable(false))
10390            .with_column("table_name", SqlScalarType::String.nullable(false))
10391            .with_column("constraint_type", SqlScalarType::String.nullable(false))
10392            .with_column("is_deferrable", SqlScalarType::String.nullable(false))
10393            .with_column("initially_deferred", SqlScalarType::String.nullable(false))
10394            .with_column("enforced", SqlScalarType::String.nullable(false))
10395            .with_column("nulls_distinct", SqlScalarType::String.nullable(false))
10396            .with_key(vec![])
10397            .finish(),
10398        column_comments: BTreeMap::new(),
10399        sql: "SELECT
10400    NULL::text AS constraint_catalog,
10401    NULL::text AS constraint_schema,
10402    NULL::text AS constraint_name,
10403    NULL::text AS table_catalog,
10404    NULL::text AS table_schema,
10405    NULL::text AS table_name,
10406    NULL::text AS constraint_type,
10407    NULL::text AS is_deferrable,
10408    NULL::text AS initially_deferred,
10409    NULL::text AS enforced,
10410    NULL::text AS nulls_distinct
10411WHERE false",
10412        access: vec![PUBLIC_SELECT],
10413    });
10414
10415pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10416    BuiltinView {
10417        name: "table_privileges",
10418        schema: INFORMATION_SCHEMA,
10419        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10420        desc: RelationDesc::builder()
10421            .with_column("grantor", SqlScalarType::String.nullable(false))
10422            .with_column("grantee", SqlScalarType::String.nullable(true))
10423            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10424            .with_column("table_schema", SqlScalarType::String.nullable(false))
10425            .with_column("table_name", SqlScalarType::String.nullable(false))
10426            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10427            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10428            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10429            .finish(),
10430        column_comments: BTreeMap::new(),
10431        sql: "
10432SELECT
10433    grantor,
10434    grantee,
10435    table_catalog,
10436    table_schema,
10437    table_name,
10438    privilege_type,
10439    is_grantable,
10440    CASE privilege_type
10441        WHEN 'SELECT' THEN 'YES'
10442        ELSE 'NO'
10443    END AS with_hierarchy
10444FROM
10445    (SELECT
10446        grantor.name AS grantor,
10447        CASE mz_internal.mz_aclitem_grantee(privileges)
10448            WHEN 'p' THEN 'PUBLIC'
10449            ELSE grantee.name
10450        END AS grantee,
10451        table_catalog,
10452        table_schema,
10453        table_name,
10454        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10455        -- ADMIN OPTION isn't implemented.
10456        'NO' AS is_grantable
10457    FROM
10458        (SELECT
10459            unnest(relations.privileges) AS privileges,
10460            CASE
10461                WHEN schemas.database_id IS NULL THEN current_database()
10462                ELSE databases.name
10463            END AS table_catalog,
10464            schemas.name AS table_schema,
10465            relations.name AS table_name
10466        FROM mz_catalog.mz_relations AS relations
10467        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10468        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10469        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10470    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10471    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10472WHERE
10473    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10474    -- to pg_has_role. Therefore we need to use a CASE statement.
10475    CASE
10476        WHEN grantee = 'PUBLIC' THEN true
10477        ELSE mz_catalog.mz_is_superuser()
10478            OR pg_has_role(current_role, grantee, 'USAGE')
10479            OR pg_has_role(current_role, grantor, 'USAGE')
10480    END",
10481        access: vec![PUBLIC_SELECT],
10482    }
10483});
10484
10485pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10486    name: "triggers",
10487    schema: INFORMATION_SCHEMA,
10488    oid: oid::VIEW_TRIGGERS_OID,
10489    desc: RelationDesc::builder()
10490        .with_column("trigger_catalog", SqlScalarType::String.nullable(false))
10491        .with_column("trigger_schema", SqlScalarType::String.nullable(false))
10492        .with_column("trigger_name", SqlScalarType::String.nullable(false))
10493        .with_column("event_manipulation", SqlScalarType::String.nullable(false))
10494        .with_column(
10495            "event_object_catalog",
10496            SqlScalarType::String.nullable(false),
10497        )
10498        .with_column("event_object_schema", SqlScalarType::String.nullable(false))
10499        .with_column("event_object_table", SqlScalarType::String.nullable(false))
10500        .with_column("action_order", SqlScalarType::Int32.nullable(false))
10501        .with_column("action_condition", SqlScalarType::String.nullable(false))
10502        .with_column("action_statement", SqlScalarType::String.nullable(false))
10503        .with_column("action_orientation", SqlScalarType::String.nullable(false))
10504        .with_column("action_timing", SqlScalarType::String.nullable(false))
10505        .with_column(
10506            "action_reference_old_table",
10507            SqlScalarType::String.nullable(false),
10508        )
10509        .with_column(
10510            "action_reference_new_table",
10511            SqlScalarType::String.nullable(false),
10512        )
10513        .with_key(vec![])
10514        .finish(),
10515    column_comments: BTreeMap::new(),
10516    sql: "SELECT
10517    NULL::text as trigger_catalog,
10518    NULL::text AS trigger_schema,
10519    NULL::text AS trigger_name,
10520    NULL::text AS event_manipulation,
10521    NULL::text AS event_object_catalog,
10522    NULL::text AS event_object_schema,
10523    NULL::text AS event_object_table,
10524    NULL::integer AS action_order,
10525    NULL::text AS action_condition,
10526    NULL::text AS action_statement,
10527    NULL::text AS action_orientation,
10528    NULL::text AS action_timing,
10529    NULL::text AS action_reference_old_table,
10530    NULL::text AS action_reference_new_table
10531WHERE FALSE",
10532    access: vec![PUBLIC_SELECT],
10533});
10534
10535pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10536    name: "views",
10537    schema: INFORMATION_SCHEMA,
10538    oid: oid::VIEW_VIEWS_OID,
10539    desc: RelationDesc::builder()
10540        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10541        .with_column("table_schema", SqlScalarType::String.nullable(false))
10542        .with_column("table_name", SqlScalarType::String.nullable(false))
10543        .with_column("view_definition", SqlScalarType::String.nullable(false))
10544        .finish(),
10545    column_comments: BTreeMap::new(),
10546    sql: "SELECT
10547    current_database() as table_catalog,
10548    s.name AS table_schema,
10549    v.name AS table_name,
10550    v.definition AS view_definition
10551FROM mz_catalog.mz_views v
10552JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10553LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10554WHERE s.database_id IS NULL OR d.name = current_database()",
10555    access: vec![PUBLIC_SELECT],
10556});
10557
10558pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10559    LazyLock::new(|| BuiltinView {
10560        name: "character_sets",
10561        schema: INFORMATION_SCHEMA,
10562        oid: oid::VIEW_CHARACTER_SETS_OID,
10563        desc: RelationDesc::builder()
10564            .with_column(
10565                "character_set_catalog",
10566                SqlScalarType::String.nullable(true),
10567            )
10568            .with_column("character_set_schema", SqlScalarType::String.nullable(true))
10569            .with_column("character_set_name", SqlScalarType::String.nullable(false))
10570            .with_column(
10571                "character_repertoire",
10572                SqlScalarType::String.nullable(false),
10573            )
10574            .with_column("form_of_use", SqlScalarType::String.nullable(false))
10575            .with_column(
10576                "default_collate_catalog",
10577                SqlScalarType::String.nullable(false),
10578            )
10579            .with_column(
10580                "default_collate_schema",
10581                SqlScalarType::String.nullable(false),
10582            )
10583            .with_column(
10584                "default_collate_name",
10585                SqlScalarType::String.nullable(false),
10586            )
10587            .with_key(vec![])
10588            .finish(),
10589        column_comments: BTreeMap::new(),
10590        sql: "SELECT
10591    NULL as character_set_catalog,
10592    NULL as character_set_schema,
10593    'UTF8' as character_set_name,
10594    'UCS' as character_repertoire,
10595    'UTF8' as form_of_use,
10596    current_database() as default_collate_catalog,
10597    'pg_catalog' as default_collate_schema,
10598    'en_US.utf8' as default_collate_name",
10599        access: vec![PUBLIC_SELECT],
10600    });
10601
10602// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10603// codes a collation of 'C' for every database, so we could copy that here.
10604pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10605    name: "pg_collation",
10606    schema: PG_CATALOG_SCHEMA,
10607    oid: oid::VIEW_PG_COLLATION_OID,
10608    desc: RelationDesc::builder()
10609        .with_column("oid", SqlScalarType::Oid.nullable(false))
10610        .with_column("collname", SqlScalarType::String.nullable(false))
10611        .with_column("collnamespace", SqlScalarType::Oid.nullable(false))
10612        .with_column("collowner", SqlScalarType::Oid.nullable(false))
10613        .with_column("collprovider", SqlScalarType::PgLegacyChar.nullable(false))
10614        .with_column("collisdeterministic", SqlScalarType::Bool.nullable(false))
10615        .with_column("collencoding", SqlScalarType::Int32.nullable(false))
10616        .with_column("collcollate", SqlScalarType::String.nullable(false))
10617        .with_column("collctype", SqlScalarType::String.nullable(false))
10618        .with_column("collversion", SqlScalarType::String.nullable(false))
10619        .with_key(vec![])
10620        .finish(),
10621    column_comments: BTreeMap::new(),
10622    sql: "
10623SELECT
10624    NULL::pg_catalog.oid AS oid,
10625    NULL::pg_catalog.text AS collname,
10626    NULL::pg_catalog.oid AS collnamespace,
10627    NULL::pg_catalog.oid AS collowner,
10628    NULL::pg_catalog.\"char\" AS collprovider,
10629    NULL::pg_catalog.bool AS collisdeterministic,
10630    NULL::pg_catalog.int4 AS collencoding,
10631    NULL::pg_catalog.text AS collcollate,
10632    NULL::pg_catalog.text AS collctype,
10633    NULL::pg_catalog.text AS collversion
10634WHERE false",
10635    access: vec![PUBLIC_SELECT],
10636});
10637
10638// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10639pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10640    name: "pg_policy",
10641    schema: PG_CATALOG_SCHEMA,
10642    oid: oid::VIEW_PG_POLICY_OID,
10643    desc: RelationDesc::builder()
10644        .with_column("oid", SqlScalarType::Oid.nullable(false))
10645        .with_column("polname", SqlScalarType::String.nullable(false))
10646        .with_column("polrelid", SqlScalarType::Oid.nullable(false))
10647        .with_column("polcmd", SqlScalarType::PgLegacyChar.nullable(false))
10648        .with_column("polpermissive", SqlScalarType::Bool.nullable(false))
10649        .with_column(
10650            "polroles",
10651            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10652        )
10653        .with_column("polqual", SqlScalarType::String.nullable(false))
10654        .with_column("polwithcheck", SqlScalarType::String.nullable(false))
10655        .with_key(vec![])
10656        .finish(),
10657    column_comments: BTreeMap::new(),
10658    sql: "
10659SELECT
10660    NULL::pg_catalog.oid AS oid,
10661    NULL::pg_catalog.text AS polname,
10662    NULL::pg_catalog.oid AS polrelid,
10663    NULL::pg_catalog.\"char\" AS polcmd,
10664    NULL::pg_catalog.bool AS polpermissive,
10665    NULL::pg_catalog.oid[] AS polroles,
10666    NULL::pg_catalog.text AS polqual,
10667    NULL::pg_catalog.text AS polwithcheck
10668WHERE false",
10669    access: vec![PUBLIC_SELECT],
10670});
10671
10672// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10673pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10674    name: "pg_inherits",
10675    schema: PG_CATALOG_SCHEMA,
10676    oid: oid::VIEW_PG_INHERITS_OID,
10677    desc: RelationDesc::builder()
10678        .with_column("inhrelid", SqlScalarType::Oid.nullable(false))
10679        .with_column("inhparent", SqlScalarType::Oid.nullable(false))
10680        .with_column("inhseqno", SqlScalarType::Int32.nullable(false))
10681        .with_column("inhdetachpending", SqlScalarType::Bool.nullable(false))
10682        .with_key(vec![])
10683        .finish(),
10684    column_comments: BTreeMap::new(),
10685    sql: "
10686SELECT
10687    NULL::pg_catalog.oid AS inhrelid,
10688    NULL::pg_catalog.oid AS inhparent,
10689    NULL::pg_catalog.int4 AS inhseqno,
10690    NULL::pg_catalog.bool AS inhdetachpending
10691WHERE false",
10692    access: vec![PUBLIC_SELECT],
10693});
10694
10695pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10696    name: "pg_locks",
10697    schema: PG_CATALOG_SCHEMA,
10698    oid: oid::VIEW_PG_LOCKS_OID,
10699    desc: RelationDesc::builder()
10700        .with_column("locktype", SqlScalarType::String.nullable(false))
10701        .with_column("database", SqlScalarType::Oid.nullable(false))
10702        .with_column("relation", SqlScalarType::Oid.nullable(false))
10703        .with_column("page", SqlScalarType::Int32.nullable(false))
10704        .with_column("tuple", SqlScalarType::Int16.nullable(false))
10705        .with_column("virtualxid", SqlScalarType::String.nullable(false))
10706        .with_column("transactionid", SqlScalarType::String.nullable(false))
10707        .with_column("classid", SqlScalarType::Oid.nullable(false))
10708        .with_column("objid", SqlScalarType::Oid.nullable(false))
10709        .with_column("objsubid", SqlScalarType::Int16.nullable(false))
10710        .with_column("virtualtransaction", SqlScalarType::String.nullable(false))
10711        .with_column("pid", SqlScalarType::Int32.nullable(false))
10712        .with_column("mode", SqlScalarType::String.nullable(false))
10713        .with_column("granted", SqlScalarType::Bool.nullable(false))
10714        .with_column("fastpath", SqlScalarType::Bool.nullable(false))
10715        .with_column(
10716            "waitstart",
10717            SqlScalarType::TimestampTz { precision: None }.nullable(false),
10718        )
10719        .with_key(vec![])
10720        .finish(),
10721    column_comments: BTreeMap::new(),
10722    sql: "
10723SELECT
10724-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10725    NULL::pg_catalog.text AS locktype,
10726    NULL::pg_catalog.oid AS database,
10727    NULL::pg_catalog.oid AS relation,
10728    NULL::pg_catalog.int4 AS page,
10729    NULL::pg_catalog.int2 AS tuple,
10730    NULL::pg_catalog.text AS virtualxid,
10731    NULL::pg_catalog.text AS transactionid,
10732    NULL::pg_catalog.oid AS classid,
10733    NULL::pg_catalog.oid AS objid,
10734    NULL::pg_catalog.int2 AS objsubid,
10735    NULL::pg_catalog.text AS virtualtransaction,
10736    NULL::pg_catalog.int4 AS pid,
10737    NULL::pg_catalog.text AS mode,
10738    NULL::pg_catalog.bool AS granted,
10739    NULL::pg_catalog.bool AS fastpath,
10740    NULL::pg_catalog.timestamptz AS waitstart
10741WHERE false",
10742    access: vec![PUBLIC_SELECT],
10743});
10744
10745/// Peeled version of `PG_AUTHID`: Excludes the columns rolcreaterole and rolcreatedb, to make this
10746/// view indexable.
10747pub static PG_AUTHID_CORE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10748    name: "pg_authid_core",
10749    schema: MZ_INTERNAL_SCHEMA,
10750    oid: oid::VIEW_PG_AUTHID_CORE_OID,
10751    desc: RelationDesc::builder()
10752        .with_column("oid", SqlScalarType::Oid.nullable(false))
10753        .with_column("rolname", SqlScalarType::String.nullable(false))
10754        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10755        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10756        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10757        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10758        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10759        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10760        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10761        .with_column(
10762            "rolvaliduntil",
10763            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10764        )
10765        .finish(),
10766    column_comments: BTreeMap::new(),
10767    sql: r#"
10768SELECT
10769    r.oid AS oid,
10770    r.name AS rolname,
10771    rolsuper,
10772    inherit AS rolinherit,
10773    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
10774    -- MZ doesn't support replication in the same way Postgres does
10775    false AS rolreplication,
10776    -- MZ doesn't how row level security
10777    false AS rolbypassrls,
10778    -- MZ doesn't have a connection limit
10779    -1 AS rolconnlimit,
10780    a.password_hash AS rolpassword,
10781    NULL::pg_catalog.timestamptz AS rolvaliduntil
10782FROM mz_catalog.mz_roles r
10783LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
10784    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10785});
10786
10787pub const PG_AUTHID_CORE_IND: BuiltinIndex = BuiltinIndex {
10788    name: "pg_authid_core_ind",
10789    schema: MZ_INTERNAL_SCHEMA,
10790    oid: oid::INDEX_PG_AUTHID_CORE_IND_OID,
10791    sql: "IN CLUSTER mz_catalog_server
10792ON mz_internal.pg_authid_core (rolname)",
10793    is_retained_metrics_object: false,
10794};
10795
10796pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10797    name: "pg_authid",
10798    schema: PG_CATALOG_SCHEMA,
10799    oid: oid::VIEW_PG_AUTHID_OID,
10800    desc: RelationDesc::builder()
10801        .with_column("oid", SqlScalarType::Oid.nullable(false))
10802        .with_column("rolname", SqlScalarType::String.nullable(false))
10803        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10804        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10805        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10806        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10807        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10808        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10809        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10810        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10811        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10812        .with_column(
10813            "rolvaliduntil",
10814            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10815        )
10816        .finish(),
10817    column_comments: BTreeMap::new(),
10818    // The `has_system_privilege` invocations for `rolcreaterole` and `rolcreatedb` get expanded
10819    // into very complex subqueries. If we put them into the SELECT clause directly, decorrelation
10820    // produces a very complex plan that the optimizer has a hard time dealing with. In particular,
10821    // the optimizer fails to reduce a query like `SELECT oid FROM pg_authid` to a simple lookup on
10822    // the `pg_authid_core` index and instead produces a large plan that contains a bunch of
10823    // expensive joins and arrangements.
10824    //
10825    // The proper fix is likely to implement `has_system_privileges` in Rust, but for now we work
10826    // around the issue by manually decorrelating `rolcreaterole` and `rolcreatedb`. Note that to
10827    // get the desired behavior we need to make sure that the join with `extra` doesn't change the
10828    // cardinality of `pg_authid_core` (otherwise it can never be optimized away). We ensure this
10829    // by:
10830    //  * using a `LEFT JOIN`, so the optimizer knows that left elements are never filtered
10831    //  * applying a `DISTINCT ON` to the CTE, so the optimizer knows that left elements are never
10832    //    duplicated
10833    sql: r#"
10834WITH extra AS (
10835    SELECT
10836        DISTINCT ON (oid)
10837        oid,
10838        mz_catalog.has_system_privilege(oid, 'CREATEROLE') AS rolcreaterole,
10839        mz_catalog.has_system_privilege(oid, 'CREATEDB') AS rolcreatedb
10840    FROM mz_internal.pg_authid_core
10841)
10842SELECT
10843    oid,
10844    rolname,
10845    rolsuper,
10846    rolinherit,
10847    extra.rolcreaterole,
10848    extra.rolcreatedb,
10849    rolcanlogin,
10850    rolreplication,
10851    rolbypassrls,
10852    rolconnlimit,
10853    rolpassword,
10854    rolvaliduntil
10855FROM mz_internal.pg_authid_core
10856LEFT JOIN extra USING (oid)"#,
10857    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10858});
10859
10860pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10861    name: "pg_aggregate",
10862    schema: PG_CATALOG_SCHEMA,
10863    oid: oid::VIEW_PG_AGGREGATE_OID,
10864    desc: RelationDesc::builder()
10865        .with_column("aggfnoid", SqlScalarType::Oid.nullable(false))
10866        .with_column("aggkind", SqlScalarType::String.nullable(false))
10867        .with_column("aggnumdirectargs", SqlScalarType::Int16.nullable(false))
10868        .with_column("aggtransfn", SqlScalarType::RegProc.nullable(true))
10869        .with_column("aggfinalfn", SqlScalarType::RegProc.nullable(false))
10870        .with_column("aggcombinefn", SqlScalarType::RegProc.nullable(false))
10871        .with_column("aggserialfn", SqlScalarType::RegProc.nullable(false))
10872        .with_column("aggdeserialfn", SqlScalarType::RegProc.nullable(false))
10873        .with_column("aggmtransfn", SqlScalarType::RegProc.nullable(false))
10874        .with_column("aggminvtransfn", SqlScalarType::RegProc.nullable(false))
10875        .with_column("aggmfinalfn", SqlScalarType::RegProc.nullable(false))
10876        .with_column("aggfinalextra", SqlScalarType::Bool.nullable(false))
10877        .with_column("aggmfinalextra", SqlScalarType::Bool.nullable(false))
10878        .with_column("aggfinalmodify", SqlScalarType::PgLegacyChar.nullable(true))
10879        .with_column(
10880            "aggmfinalmodify",
10881            SqlScalarType::PgLegacyChar.nullable(true),
10882        )
10883        .with_column("aggsortop", SqlScalarType::Oid.nullable(false))
10884        .with_column("aggtranstype", SqlScalarType::Oid.nullable(true))
10885        .with_column("aggtransspace", SqlScalarType::Int32.nullable(true))
10886        .with_column("aggmtranstype", SqlScalarType::Oid.nullable(false))
10887        .with_column("aggmtransspace", SqlScalarType::Int32.nullable(true))
10888        .with_column("agginitval", SqlScalarType::String.nullable(true))
10889        .with_column("aggminitval", SqlScalarType::String.nullable(true))
10890        .finish(),
10891    column_comments: BTreeMap::new(),
10892    sql: "SELECT
10893    a.oid as aggfnoid,
10894    -- Currently Materialize only support 'normal' aggregate functions.
10895    a.agg_kind as aggkind,
10896    a.agg_num_direct_args as aggnumdirectargs,
10897    -- Materialize doesn't support these fields.
10898    NULL::pg_catalog.regproc as aggtransfn,
10899    '0'::pg_catalog.regproc as aggfinalfn,
10900    '0'::pg_catalog.regproc as aggcombinefn,
10901    '0'::pg_catalog.regproc as aggserialfn,
10902    '0'::pg_catalog.regproc as aggdeserialfn,
10903    '0'::pg_catalog.regproc as aggmtransfn,
10904    '0'::pg_catalog.regproc as aggminvtransfn,
10905    '0'::pg_catalog.regproc as aggmfinalfn,
10906    false as aggfinalextra,
10907    false as aggmfinalextra,
10908    NULL::pg_catalog.\"char\" AS aggfinalmodify,
10909    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
10910    '0'::pg_catalog.oid as aggsortop,
10911    NULL::pg_catalog.oid as aggtranstype,
10912    NULL::pg_catalog.int4 as aggtransspace,
10913    '0'::pg_catalog.oid as aggmtranstype,
10914    NULL::pg_catalog.int4 as aggmtransspace,
10915    NULL::pg_catalog.text as agginitval,
10916    NULL::pg_catalog.text as aggminitval
10917FROM mz_internal.mz_aggregates a",
10918    access: vec![PUBLIC_SELECT],
10919});
10920
10921pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10922    name: "pg_trigger",
10923    schema: PG_CATALOG_SCHEMA,
10924    oid: oid::VIEW_PG_TRIGGER_OID,
10925    desc: RelationDesc::builder()
10926        .with_column("oid", SqlScalarType::Oid.nullable(false))
10927        .with_column("tgrelid", SqlScalarType::Oid.nullable(false))
10928        .with_column("tgparentid", SqlScalarType::Oid.nullable(false))
10929        .with_column("tgname", SqlScalarType::String.nullable(false))
10930        .with_column("tgfoid", SqlScalarType::Oid.nullable(false))
10931        .with_column("tgtype", SqlScalarType::Int16.nullable(false))
10932        .with_column("tgenabled", SqlScalarType::PgLegacyChar.nullable(false))
10933        .with_column("tgisinternal", SqlScalarType::Bool.nullable(false))
10934        .with_column("tgconstrrelid", SqlScalarType::Oid.nullable(false))
10935        .with_column("tgconstrindid", SqlScalarType::Oid.nullable(false))
10936        .with_column("tgconstraint", SqlScalarType::Oid.nullable(false))
10937        .with_column("tgdeferrable", SqlScalarType::Bool.nullable(false))
10938        .with_column("tginitdeferred", SqlScalarType::Bool.nullable(false))
10939        .with_column("tgnargs", SqlScalarType::Int16.nullable(false))
10940        .with_column("tgattr", SqlScalarType::Int2Vector.nullable(false))
10941        .with_column("tgargs", SqlScalarType::Bytes.nullable(false))
10942        .with_column("tgqual", SqlScalarType::String.nullable(false))
10943        .with_column("tgoldtable", SqlScalarType::String.nullable(false))
10944        .with_column("tgnewtable", SqlScalarType::String.nullable(false))
10945        .with_key(vec![])
10946        .finish(),
10947    column_comments: BTreeMap::new(),
10948    sql: "SELECT
10949    -- MZ doesn't support triggers so all of these fields are NULL.
10950    NULL::pg_catalog.oid AS oid,
10951    NULL::pg_catalog.oid AS tgrelid,
10952    NULL::pg_catalog.oid AS tgparentid,
10953    NULL::pg_catalog.text AS tgname,
10954    NULL::pg_catalog.oid AS tgfoid,
10955    NULL::pg_catalog.int2 AS tgtype,
10956    NULL::pg_catalog.\"char\" AS tgenabled,
10957    NULL::pg_catalog.bool AS tgisinternal,
10958    NULL::pg_catalog.oid AS tgconstrrelid,
10959    NULL::pg_catalog.oid AS tgconstrindid,
10960    NULL::pg_catalog.oid AS tgconstraint,
10961    NULL::pg_catalog.bool AS tgdeferrable,
10962    NULL::pg_catalog.bool AS tginitdeferred,
10963    NULL::pg_catalog.int2 AS tgnargs,
10964    NULL::pg_catalog.int2vector AS tgattr,
10965    NULL::pg_catalog.bytea AS tgargs,
10966    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
10967    -- uses text as a placeholder, so we'll follow their lead here.
10968    NULL::pg_catalog.text AS tgqual,
10969    NULL::pg_catalog.text AS tgoldtable,
10970    NULL::pg_catalog.text AS tgnewtable
10971WHERE false
10972    ",
10973    access: vec![PUBLIC_SELECT],
10974});
10975
10976pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10977    name: "pg_rewrite",
10978    schema: PG_CATALOG_SCHEMA,
10979    oid: oid::VIEW_PG_REWRITE_OID,
10980    desc: RelationDesc::builder()
10981        .with_column("oid", SqlScalarType::Oid.nullable(false))
10982        .with_column("rulename", SqlScalarType::String.nullable(false))
10983        .with_column("ev_class", SqlScalarType::Oid.nullable(false))
10984        .with_column("ev_type", SqlScalarType::PgLegacyChar.nullable(false))
10985        .with_column("ev_enabled", SqlScalarType::PgLegacyChar.nullable(false))
10986        .with_column("is_instead", SqlScalarType::Bool.nullable(false))
10987        .with_column("ev_qual", SqlScalarType::String.nullable(false))
10988        .with_column("ev_action", SqlScalarType::String.nullable(false))
10989        .with_key(vec![])
10990        .finish(),
10991    column_comments: BTreeMap::new(),
10992    sql: "SELECT
10993    -- MZ doesn't support rewrite rules so all of these fields are NULL.
10994    NULL::pg_catalog.oid AS oid,
10995    NULL::pg_catalog.text AS rulename,
10996    NULL::pg_catalog.oid AS ev_class,
10997    NULL::pg_catalog.\"char\" AS ev_type,
10998    NULL::pg_catalog.\"char\" AS ev_enabled,
10999    NULL::pg_catalog.bool AS is_instead,
11000    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
11001    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
11002    NULL::pg_catalog.text AS ev_qual,
11003    NULL::pg_catalog.text AS ev_action
11004WHERE false
11005    ",
11006    access: vec![PUBLIC_SELECT],
11007});
11008
11009pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11010    name: "pg_extension",
11011    schema: PG_CATALOG_SCHEMA,
11012    oid: oid::VIEW_PG_EXTENSION_OID,
11013    desc: RelationDesc::builder()
11014        .with_column("oid", SqlScalarType::Oid.nullable(false))
11015        .with_column("extname", SqlScalarType::String.nullable(false))
11016        .with_column("extowner", SqlScalarType::Oid.nullable(false))
11017        .with_column("extnamespace", SqlScalarType::Oid.nullable(false))
11018        .with_column("extrelocatable", SqlScalarType::Bool.nullable(false))
11019        .with_column("extversion", SqlScalarType::String.nullable(false))
11020        .with_column(
11021            "extconfig",
11022            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
11023        )
11024        .with_column(
11025            "extcondition",
11026            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11027        )
11028        .with_key(vec![])
11029        .finish(),
11030    column_comments: BTreeMap::new(),
11031    sql: "SELECT
11032    -- MZ doesn't support extensions so all of these fields are NULL.
11033    NULL::pg_catalog.oid AS oid,
11034    NULL::pg_catalog.text AS extname,
11035    NULL::pg_catalog.oid AS extowner,
11036    NULL::pg_catalog.oid AS extnamespace,
11037    NULL::pg_catalog.bool AS extrelocatable,
11038    NULL::pg_catalog.text AS extversion,
11039    NULL::pg_catalog.oid[] AS extconfig,
11040    NULL::pg_catalog.text[] AS extcondition
11041WHERE false
11042    ",
11043    access: vec![PUBLIC_SELECT],
11044});
11045
11046pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11047    name: "mz_show_all_objects",
11048    schema: MZ_INTERNAL_SCHEMA,
11049    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
11050    desc: RelationDesc::builder()
11051        .with_column("schema_id", SqlScalarType::String.nullable(false))
11052        .with_column("name", SqlScalarType::String.nullable(false))
11053        .with_column("type", SqlScalarType::String.nullable(false))
11054        .with_column("comment", SqlScalarType::String.nullable(false))
11055        .finish(),
11056    column_comments: BTreeMap::new(),
11057    sql: "WITH comments AS (
11058        SELECT id, object_type, comment
11059        FROM mz_internal.mz_comments
11060        WHERE object_sub_id IS NULL
11061    )
11062    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
11063    FROM mz_catalog.mz_objects AS objs
11064    LEFT JOIN comments ON objs.id = comments.id
11065    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
11066    access: vec![PUBLIC_SELECT],
11067});
11068
11069pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
11070    BuiltinView {
11071    name: "mz_show_clusters",
11072    schema: MZ_INTERNAL_SCHEMA,
11073    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
11074    desc: RelationDesc::builder()
11075        .with_column("name", SqlScalarType::String.nullable(false))
11076        .with_column("replicas", SqlScalarType::String.nullable(true))
11077        .with_column("comment", SqlScalarType::String.nullable(false))
11078        .finish(),
11079    column_comments: BTreeMap::new(),
11080    sql: "
11081    WITH clusters AS (
11082        SELECT
11083            mc.id,
11084            mc.name,
11085            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
11086        FROM mz_catalog.mz_clusters mc
11087        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
11088        ON mc.id = mcr.cluster_id
11089        GROUP BY mc.id, mc.name
11090    ),
11091    comments AS (
11092        SELECT id, comment
11093        FROM mz_internal.mz_comments
11094        WHERE object_type = 'cluster' AND object_sub_id IS NULL
11095    )
11096    SELECT name, replicas, COALESCE(comment, '') as comment
11097    FROM clusters
11098    LEFT JOIN comments ON clusters.id = comments.id",
11099    access: vec![PUBLIC_SELECT],
11100}
11101});
11102
11103pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11104    name: "mz_show_secrets",
11105    schema: MZ_INTERNAL_SCHEMA,
11106    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
11107    desc: RelationDesc::builder()
11108        .with_column("schema_id", SqlScalarType::String.nullable(false))
11109        .with_column("name", SqlScalarType::String.nullable(false))
11110        .with_column("comment", SqlScalarType::String.nullable(false))
11111        .finish(),
11112    column_comments: BTreeMap::new(),
11113    sql: "WITH comments AS (
11114        SELECT id, comment
11115        FROM mz_internal.mz_comments
11116        WHERE object_type = 'secret' AND object_sub_id IS NULL
11117    )
11118    SELECT schema_id, name, COALESCE(comment, '') as comment
11119    FROM mz_catalog.mz_secrets secrets
11120    LEFT JOIN comments ON secrets.id = comments.id",
11121    access: vec![PUBLIC_SELECT],
11122});
11123
11124pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11125    name: "mz_show_columns",
11126    schema: MZ_INTERNAL_SCHEMA,
11127    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
11128    desc: RelationDesc::builder()
11129        .with_column("id", SqlScalarType::String.nullable(false))
11130        .with_column("name", SqlScalarType::String.nullable(false))
11131        .with_column("nullable", SqlScalarType::Bool.nullable(false))
11132        .with_column("type", SqlScalarType::String.nullable(false))
11133        .with_column("position", SqlScalarType::UInt64.nullable(false))
11134        .with_column("comment", SqlScalarType::String.nullable(false))
11135        .finish(),
11136    column_comments: BTreeMap::new(),
11137    sql: "
11138    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
11139    FROM mz_catalog.mz_columns columns
11140    LEFT JOIN mz_internal.mz_comments comments
11141    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
11142    access: vec![PUBLIC_SELECT],
11143});
11144
11145pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11146    name: "mz_show_databases",
11147    schema: MZ_INTERNAL_SCHEMA,
11148    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
11149    desc: RelationDesc::builder()
11150        .with_column("name", SqlScalarType::String.nullable(false))
11151        .with_column("comment", SqlScalarType::String.nullable(false))
11152        .finish(),
11153    column_comments: BTreeMap::new(),
11154    sql: "WITH comments AS (
11155        SELECT id, comment
11156        FROM mz_internal.mz_comments
11157        WHERE object_type = 'database' AND object_sub_id IS NULL
11158    )
11159    SELECT name, COALESCE(comment, '') as comment
11160    FROM mz_catalog.mz_databases databases
11161    LEFT JOIN comments ON databases.id = comments.id",
11162    access: vec![PUBLIC_SELECT],
11163});
11164
11165pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11166    name: "mz_show_schemas",
11167    schema: MZ_INTERNAL_SCHEMA,
11168    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
11169    desc: RelationDesc::builder()
11170        .with_column("database_id", SqlScalarType::String.nullable(true))
11171        .with_column("name", SqlScalarType::String.nullable(false))
11172        .with_column("comment", SqlScalarType::String.nullable(false))
11173        .finish(),
11174    column_comments: BTreeMap::new(),
11175    sql: "WITH comments AS (
11176        SELECT id, comment
11177        FROM mz_internal.mz_comments
11178        WHERE object_type = 'schema' AND object_sub_id IS NULL
11179    )
11180    SELECT database_id, name, COALESCE(comment, '') as comment
11181    FROM mz_catalog.mz_schemas schemas
11182    LEFT JOIN comments ON schemas.id = comments.id",
11183    access: vec![PUBLIC_SELECT],
11184});
11185
11186pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11187    name: "mz_show_roles",
11188    schema: MZ_INTERNAL_SCHEMA,
11189    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
11190    desc: RelationDesc::builder()
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 = 'role' AND object_sub_id IS NULL
11199    )
11200    SELECT name, COALESCE(comment, '') as comment
11201    FROM mz_catalog.mz_roles roles
11202    LEFT JOIN comments ON roles.id = comments.id
11203    WHERE roles.id NOT LIKE 's%'
11204      AND roles.id NOT LIKE 'g%'",
11205    access: vec![PUBLIC_SELECT],
11206});
11207
11208pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11209    name: "mz_show_tables",
11210    schema: MZ_INTERNAL_SCHEMA,
11211    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
11212    desc: RelationDesc::builder()
11213        .with_column("schema_id", SqlScalarType::String.nullable(false))
11214        .with_column("name", SqlScalarType::String.nullable(false))
11215        .with_column("comment", SqlScalarType::String.nullable(false))
11216        .with_column("source_id", SqlScalarType::String.nullable(true))
11217        .finish(),
11218    column_comments: BTreeMap::new(),
11219    sql: "WITH comments AS (
11220        SELECT id, comment
11221        FROM mz_internal.mz_comments
11222        WHERE object_type = 'table' AND object_sub_id IS NULL
11223    )
11224    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
11225    FROM mz_catalog.mz_tables tables
11226    LEFT JOIN comments ON tables.id = comments.id",
11227    access: vec![PUBLIC_SELECT],
11228});
11229
11230pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11231    name: "mz_show_views",
11232    schema: MZ_INTERNAL_SCHEMA,
11233    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
11234    desc: RelationDesc::builder()
11235        .with_column("schema_id", SqlScalarType::String.nullable(false))
11236        .with_column("name", SqlScalarType::String.nullable(false))
11237        .with_column("comment", SqlScalarType::String.nullable(false))
11238        .finish(),
11239    column_comments: BTreeMap::new(),
11240    sql: "WITH comments AS (
11241        SELECT id, comment
11242        FROM mz_internal.mz_comments
11243        WHERE object_type = 'view' AND object_sub_id IS NULL
11244    )
11245    SELECT schema_id, name, COALESCE(comment, '') as comment
11246    FROM mz_catalog.mz_views views
11247    LEFT JOIN comments ON views.id = comments.id",
11248    access: vec![PUBLIC_SELECT],
11249});
11250
11251pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11252    name: "mz_show_types",
11253    schema: MZ_INTERNAL_SCHEMA,
11254    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
11255    desc: RelationDesc::builder()
11256        .with_column("schema_id", SqlScalarType::String.nullable(false))
11257        .with_column("name", SqlScalarType::String.nullable(false))
11258        .with_column("comment", SqlScalarType::String.nullable(false))
11259        .finish(),
11260    column_comments: BTreeMap::new(),
11261    sql: "WITH comments AS (
11262        SELECT id, comment
11263        FROM mz_internal.mz_comments
11264        WHERE object_type = 'type' AND object_sub_id IS NULL
11265    )
11266    SELECT schema_id, name, COALESCE(comment, '') as comment
11267    FROM mz_catalog.mz_types types
11268    LEFT JOIN comments ON types.id = comments.id",
11269    access: vec![PUBLIC_SELECT],
11270});
11271
11272pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11273    name: "mz_show_connections",
11274    schema: MZ_INTERNAL_SCHEMA,
11275    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
11276    desc: RelationDesc::builder()
11277        .with_column("schema_id", SqlScalarType::String.nullable(false))
11278        .with_column("name", SqlScalarType::String.nullable(false))
11279        .with_column("type", SqlScalarType::String.nullable(false))
11280        .with_column("comment", SqlScalarType::String.nullable(false))
11281        .finish(),
11282    column_comments: BTreeMap::new(),
11283    sql: "WITH comments AS (
11284        SELECT id, comment
11285        FROM mz_internal.mz_comments
11286        WHERE object_type = 'connection' AND object_sub_id IS NULL
11287    )
11288    SELECT schema_id, name, type, COALESCE(comment, '') as comment
11289    FROM mz_catalog.mz_connections connections
11290    LEFT JOIN comments ON connections.id = comments.id",
11291    access: vec![PUBLIC_SELECT],
11292});
11293
11294pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11295    name: "mz_show_sources",
11296    schema: MZ_INTERNAL_SCHEMA,
11297    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
11298    desc: RelationDesc::builder()
11299        .with_column("id", SqlScalarType::String.nullable(false))
11300        .with_column("name", SqlScalarType::String.nullable(false))
11301        .with_column("type", SqlScalarType::String.nullable(false))
11302        .with_column("cluster", SqlScalarType::String.nullable(true))
11303        .with_column("schema_id", SqlScalarType::String.nullable(false))
11304        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11305        .with_column("comment", SqlScalarType::String.nullable(false))
11306        .finish(),
11307    column_comments: BTreeMap::new(),
11308    sql: "
11309WITH comments AS (
11310    SELECT id, comment
11311    FROM mz_internal.mz_comments
11312    WHERE object_type = 'source' AND object_sub_id IS NULL
11313)
11314SELECT
11315    sources.id,
11316    sources.name,
11317    sources.type,
11318    clusters.name AS cluster,
11319    schema_id,
11320    cluster_id,
11321    COALESCE(comments.comment, '') as comment
11322FROM
11323    mz_catalog.mz_sources AS sources
11324        LEFT JOIN
11325            mz_catalog.mz_clusters AS clusters
11326            ON clusters.id = sources.cluster_id
11327        LEFT JOIN comments ON sources.id = comments.id",
11328    access: vec![PUBLIC_SELECT],
11329});
11330
11331pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11332    name: "mz_show_sinks",
11333    schema: MZ_INTERNAL_SCHEMA,
11334    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11335    desc: RelationDesc::builder()
11336        .with_column("id", SqlScalarType::String.nullable(false))
11337        .with_column("name", SqlScalarType::String.nullable(false))
11338        .with_column("type", SqlScalarType::String.nullable(false))
11339        .with_column("cluster", SqlScalarType::String.nullable(false))
11340        .with_column("schema_id", SqlScalarType::String.nullable(false))
11341        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11342        .with_column("comment", SqlScalarType::String.nullable(false))
11343        .finish(),
11344    column_comments: BTreeMap::new(),
11345    sql: "
11346WITH comments AS (
11347    SELECT id, comment
11348    FROM mz_internal.mz_comments
11349    WHERE object_type = 'sink' AND object_sub_id IS NULL
11350)
11351SELECT
11352    sinks.id,
11353    sinks.name,
11354    sinks.type,
11355    clusters.name AS cluster,
11356    schema_id,
11357    cluster_id,
11358    COALESCE(comments.comment, '') as comment
11359FROM
11360    mz_catalog.mz_sinks AS sinks
11361    JOIN
11362        mz_catalog.mz_clusters AS clusters
11363        ON clusters.id = sinks.cluster_id
11364    LEFT JOIN comments ON sinks.id = comments.id",
11365    access: vec![PUBLIC_SELECT],
11366});
11367
11368pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11369    name: "mz_show_materialized_views",
11370    schema: MZ_INTERNAL_SCHEMA,
11371    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11372    desc: RelationDesc::builder()
11373        .with_column("id", SqlScalarType::String.nullable(false))
11374        .with_column("name", SqlScalarType::String.nullable(false))
11375        .with_column("cluster", SqlScalarType::String.nullable(false))
11376        .with_column("schema_id", SqlScalarType::String.nullable(false))
11377        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11378        .with_column("comment", SqlScalarType::String.nullable(false))
11379        .finish(),
11380    column_comments: BTreeMap::new(),
11381    sql: "
11382WITH
11383    comments AS (
11384        SELECT id, comment
11385        FROM mz_internal.mz_comments
11386        WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11387    )
11388SELECT
11389    mviews.id as id,
11390    mviews.name,
11391    clusters.name AS cluster,
11392    schema_id,
11393    cluster_id,
11394    COALESCE(comments.comment, '') as comment
11395FROM
11396    mz_catalog.mz_materialized_views AS mviews
11397    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11398    LEFT JOIN comments ON mviews.id = comments.id",
11399    access: vec![PUBLIC_SELECT],
11400});
11401
11402pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11403    name: "mz_show_indexes",
11404    schema: MZ_INTERNAL_SCHEMA,
11405    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11406    desc: RelationDesc::builder()
11407        .with_column("id", SqlScalarType::String.nullable(false))
11408        .with_column("name", SqlScalarType::String.nullable(false))
11409        .with_column("on", SqlScalarType::String.nullable(false))
11410        .with_column("cluster", SqlScalarType::String.nullable(false))
11411        .with_column(
11412            "key",
11413            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11414        )
11415        .with_column("on_id", SqlScalarType::String.nullable(false))
11416        .with_column("schema_id", SqlScalarType::String.nullable(false))
11417        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11418        .with_column("comment", SqlScalarType::String.nullable(false))
11419        .finish(),
11420    column_comments: BTreeMap::new(),
11421    sql: "
11422WITH comments AS (
11423    SELECT id, comment
11424    FROM mz_internal.mz_comments
11425    WHERE object_type = 'index' AND object_sub_id IS NULL
11426)
11427SELECT
11428    idxs.id AS id,
11429    idxs.name AS name,
11430    objs.name AS on,
11431    clusters.name AS cluster,
11432    COALESCE(keys.key, '{}'::_text) AS key,
11433    idxs.on_id AS on_id,
11434    objs.schema_id AS schema_id,
11435    clusters.id AS cluster_id,
11436    COALESCE(comments.comment, '') as comment
11437FROM
11438    mz_catalog.mz_indexes AS idxs
11439    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11440    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11441    LEFT JOIN
11442        (SELECT
11443            idxs.id,
11444            ARRAY_AGG(
11445                CASE
11446                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11447                    ELSE idx_cols.on_expression
11448                END
11449                ORDER BY idx_cols.index_position ASC
11450            ) AS key
11451        FROM
11452            mz_catalog.mz_indexes AS idxs
11453            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11454            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11455                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11456        GROUP BY idxs.id) AS keys
11457    ON idxs.id = keys.id
11458    LEFT JOIN comments ON idxs.id = comments.id",
11459    access: vec![PUBLIC_SELECT],
11460});
11461
11462pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11463    name: "mz_show_cluster_replicas",
11464    schema: MZ_INTERNAL_SCHEMA,
11465    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11466    desc: RelationDesc::builder()
11467        .with_column("cluster", SqlScalarType::String.nullable(false))
11468        .with_column("replica", SqlScalarType::String.nullable(false))
11469        .with_column("replica_id", SqlScalarType::String.nullable(false))
11470        .with_column("size", SqlScalarType::String.nullable(true))
11471        .with_column("ready", SqlScalarType::Bool.nullable(false))
11472        .with_column("comment", SqlScalarType::String.nullable(false))
11473        .finish(),
11474    column_comments: BTreeMap::new(),
11475    sql: r#"SELECT
11476    mz_catalog.mz_clusters.name AS cluster,
11477    mz_catalog.mz_cluster_replicas.name AS replica,
11478    mz_catalog.mz_cluster_replicas.id as replica_id,
11479    mz_catalog.mz_cluster_replicas.size AS size,
11480    coalesce(statuses.ready, FALSE) AS ready,
11481    coalesce(comments.comment, '') as comment
11482FROM
11483    mz_catalog.mz_cluster_replicas
11484        JOIN mz_catalog.mz_clusters
11485            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11486        LEFT JOIN
11487            (
11488                SELECT
11489                    replica_id,
11490                    bool_and(hydrated) AS ready
11491                FROM mz_internal.mz_hydration_statuses
11492                WHERE replica_id is not null
11493                GROUP BY replica_id
11494            ) AS statuses
11495            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11496        LEFT JOIN mz_internal.mz_comments comments
11497            ON mz_catalog.mz_cluster_replicas.id = comments.id
11498WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11499ORDER BY 1, 2"#,
11500    access: vec![PUBLIC_SELECT],
11501});
11502
11503pub static MZ_SHOW_CONTINUAL_TASKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11504    name: "mz_show_continual_tasks",
11505    schema: MZ_INTERNAL_SCHEMA,
11506    oid: oid::VIEW_MZ_SHOW_CONTINUAL_TASKS_OID,
11507    desc: RelationDesc::builder()
11508        .with_column("id", SqlScalarType::String.nullable(false))
11509        .with_column("name", SqlScalarType::String.nullable(false))
11510        .with_column("cluster", SqlScalarType::String.nullable(false))
11511        .with_column("schema_id", SqlScalarType::String.nullable(false))
11512        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11513        .with_column("comment", SqlScalarType::String.nullable(false))
11514        .finish(),
11515    column_comments: BTreeMap::new(),
11516    sql: "
11517WITH comments AS (
11518    SELECT id, comment
11519    FROM mz_internal.mz_comments
11520    WHERE object_type = 'continual-task' AND object_sub_id IS NULL
11521)
11522SELECT
11523    cts.id as id,
11524    cts.name,
11525    clusters.name AS cluster,
11526    schema_id,
11527    cluster_id,
11528    COALESCE(comments.comment, '') as comment
11529FROM
11530    mz_internal.mz_continual_tasks AS cts
11531    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = cts.cluster_id
11532    LEFT JOIN comments ON cts.id = comments.id",
11533    access: vec![PUBLIC_SELECT],
11534});
11535
11536/// Lightweight data product discovery for MCP (Model Context Protocol).
11537///
11538/// Lists indexed views with comments that the current user has privileges on.
11539/// Used by the `get_data_products` and `read_data_product` MCP tools.
11540/// Does not include schema details — use `mz_mcp_data_product_details` for that.
11541pub static MZ_MCP_DATA_PRODUCTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11542    name: "mz_mcp_data_products",
11543    schema: MZ_INTERNAL_SCHEMA,
11544    oid: oid::VIEW_MZ_MCP_DATA_PRODUCTS_OID,
11545    desc: RelationDesc::builder()
11546        .with_column("object_name", SqlScalarType::String.nullable(false))
11547        .with_column("cluster", SqlScalarType::String.nullable(false))
11548        .with_column("description", SqlScalarType::String.nullable(true))
11549        .with_key(vec![0, 1, 2])
11550        .finish(),
11551    column_comments: BTreeMap::from_iter([
11552        (
11553            "object_name",
11554            "Fully qualified object name (database.schema.name).",
11555        ),
11556        ("cluster", "Cluster where the index is hosted."),
11557        (
11558            "description",
11559            "Index comment (used as data product description).",
11560        ),
11561    ]),
11562    sql: r#"
11563SELECT DISTINCT
11564    '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
11565    c.name AS cluster,
11566    cts.comment AS description
11567FROM mz_internal.mz_show_my_object_privileges op
11568JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
11569JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
11570JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
11571JOIN mz_indexes i ON i.on_id = o.id
11572JOIN mz_clusters c ON c.id = i.cluster_id
11573JOIN mz_internal.mz_show_my_cluster_privileges cp ON cp.name = c.name
11574LEFT JOIN mz_internal.mz_comments cts ON cts.id = i.id AND cts.object_sub_id IS NULL
11575WHERE op.privilege_type = 'SELECT'
11576  AND cp.privilege_type = 'USAGE'
11577"#,
11578    access: vec![PUBLIC_SELECT],
11579});
11580
11581/// Full data product details with JSON Schema for MCP agents.
11582///
11583/// Extends `mz_mcp_data_products` with column types, index keys, and column
11584/// comments, formatted as a JSON Schema object. Used by the
11585/// `get_data_product_details` MCP tool.
11586pub static MZ_MCP_DATA_PRODUCT_DETAILS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11587    name: "mz_mcp_data_product_details",
11588    schema: MZ_INTERNAL_SCHEMA,
11589    oid: oid::VIEW_MZ_MCP_DATA_PRODUCT_DETAILS_OID,
11590    desc: RelationDesc::builder()
11591        .with_column("object_name", SqlScalarType::String.nullable(false))
11592        .with_column("cluster", SqlScalarType::String.nullable(false))
11593        .with_column("description", SqlScalarType::String.nullable(true))
11594        .with_column("schema", SqlScalarType::Jsonb.nullable(false))
11595        .with_key(vec![0, 1, 2])
11596        .finish(),
11597    column_comments: BTreeMap::from_iter([
11598        (
11599            "object_name",
11600            "Fully qualified object name (database.schema.name).",
11601        ),
11602        ("cluster", "Cluster where the index is hosted."),
11603        (
11604            "description",
11605            "Index comment (used as data product description).",
11606        ),
11607        (
11608            "schema",
11609            "JSON Schema describing the object's columns and types.",
11610        ),
11611    ]),
11612    sql: r#"
11613SELECT * FROM (
11614    SELECT
11615        '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
11616        c.name AS cluster,
11617        cts.comment AS description,
11618        COALESCE(jsonb_build_object(
11619        'type', 'object',
11620        'required', jsonb_agg(distinct ccol.name) FILTER (WHERE ccol.position = ic.on_position),
11621        'properties', jsonb_strip_nulls(jsonb_object_agg(
11622            ccol.name,
11623            CASE
11624                WHEN ccol.type IN (
11625                    'uint2', 'uint4','uint8', 'int', 'integer', 'smallint',
11626                    'double', 'double precision', 'bigint', 'float',
11627                    'numeric', 'real'
11628                ) THEN jsonb_build_object(
11629                    'type', 'number',
11630                    'description', cts_col.comment
11631                )
11632                WHEN ccol.type = 'boolean' THEN jsonb_build_object(
11633                    'type', 'boolean',
11634                    'description', cts_col.comment
11635                )
11636                WHEN ccol.type = 'bytea' THEN jsonb_build_object(
11637                    'type', 'string',
11638                    'description', cts_col.comment,
11639                    'contentEncoding', 'base64',
11640                    'contentMediaType', 'application/octet-stream'
11641                )
11642                WHEN ccol.type = 'date' THEN jsonb_build_object(
11643                    'type', 'string',
11644                    'format', 'date',
11645                    'description', cts_col.comment
11646                )
11647                WHEN ccol.type = 'time' THEN jsonb_build_object(
11648                    'type', 'string',
11649                    'format', 'time',
11650                    'description', cts_col.comment
11651                )
11652                WHEN ccol.type ilike 'timestamp%%' THEN jsonb_build_object(
11653                    'type', 'string',
11654                    'format', 'date-time',
11655                    'description', cts_col.comment
11656                )
11657                WHEN ccol.type = 'jsonb' THEN jsonb_build_object(
11658                    'type', 'object',
11659                    'description', cts_col.comment
11660                )
11661                WHEN ccol.type = 'uuid' THEN jsonb_build_object(
11662                    'type', 'string',
11663                    'format', 'uuid',
11664                    'description', cts_col.comment
11665                )
11666                ELSE jsonb_build_object(
11667                    'type', 'string',
11668                    'description', cts_col.comment
11669                )
11670            END
11671        ))
11672    ), '{"type": "object", "properties": {}}'::jsonb) AS schema
11673FROM mz_internal.mz_show_my_object_privileges op
11674JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
11675JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
11676JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
11677JOIN mz_indexes i ON i.on_id = o.id
11678JOIN mz_index_columns ic ON i.id = ic.index_id
11679JOIN mz_columns ccol ON ccol.id = o.id
11680JOIN mz_clusters c ON c.id = i.cluster_id
11681JOIN mz_internal.mz_show_my_cluster_privileges cp ON cp.name = c.name
11682LEFT JOIN mz_internal.mz_comments cts ON cts.id = i.id AND cts.object_sub_id IS NULL
11683LEFT JOIN mz_internal.mz_comments cts_col ON cts_col.id = o.id AND cts_col.object_sub_id = ccol.position
11684WHERE op.privilege_type = 'SELECT'
11685  AND cp.privilege_type = 'USAGE'
11686GROUP BY 1, 2, 3
11687)
11688"#,
11689    access: vec![PUBLIC_SELECT],
11690});
11691
11692pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11693    name: "mz_show_role_members",
11694    schema: MZ_INTERNAL_SCHEMA,
11695    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11696    desc: RelationDesc::builder()
11697        .with_column("role", SqlScalarType::String.nullable(false))
11698        .with_column("member", SqlScalarType::String.nullable(false))
11699        .with_column("grantor", SqlScalarType::String.nullable(false))
11700        .finish(),
11701    column_comments: BTreeMap::from_iter([
11702        ("role", "The role that `member` is a member of."),
11703        ("member", "The role that is a member of `role`."),
11704        (
11705            "grantor",
11706            "The role that granted membership of `member` to `role`.",
11707        ),
11708    ]),
11709    sql: r#"SELECT
11710    r1.name AS role,
11711    r2.name AS member,
11712    r3.name AS grantor
11713FROM mz_catalog.mz_role_members rm
11714JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11715JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11716JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11717ORDER BY role"#,
11718    access: vec![PUBLIC_SELECT],
11719});
11720
11721pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11722    name: "mz_show_my_role_members",
11723    schema: MZ_INTERNAL_SCHEMA,
11724    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11725    desc: RelationDesc::builder()
11726        .with_column("role", SqlScalarType::String.nullable(false))
11727        .with_column("member", SqlScalarType::String.nullable(false))
11728        .with_column("grantor", SqlScalarType::String.nullable(false))
11729        .finish(),
11730    column_comments: BTreeMap::from_iter([
11731        ("role", "The role that `member` is a member of."),
11732        ("member", "The role that is a member of `role`."),
11733        (
11734            "grantor",
11735            "The role that granted membership of `member` to `role`.",
11736        ),
11737    ]),
11738    sql: r#"SELECT role, member, grantor
11739FROM mz_internal.mz_show_role_members
11740WHERE pg_has_role(member, 'USAGE')"#,
11741    access: vec![PUBLIC_SELECT],
11742});
11743
11744pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11745    name: "mz_show_system_privileges",
11746    schema: MZ_INTERNAL_SCHEMA,
11747    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11748    desc: RelationDesc::builder()
11749        .with_column("grantor", SqlScalarType::String.nullable(true))
11750        .with_column("grantee", SqlScalarType::String.nullable(true))
11751        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11752        .finish(),
11753    column_comments: BTreeMap::from_iter([
11754        ("grantor", "The role that granted the privilege."),
11755        ("grantee", "The role that the privilege was granted to."),
11756        ("privilege_type", "They type of privilege granted."),
11757    ]),
11758    sql: r#"SELECT
11759    grantor.name AS grantor,
11760    CASE privileges.grantee
11761        WHEN 'p' THEN 'PUBLIC'
11762        ELSE grantee.name
11763    END AS grantee,
11764    privileges.privilege_type AS privilege_type
11765FROM
11766    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11767    FROM mz_catalog.mz_system_privileges) AS privileges
11768LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11769LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11770WHERE privileges.grantee NOT LIKE 's%'"#,
11771    access: vec![PUBLIC_SELECT],
11772});
11773
11774pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11775    name: "mz_show_my_system_privileges",
11776    schema: MZ_INTERNAL_SCHEMA,
11777    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11778    desc: RelationDesc::builder()
11779        .with_column("grantor", SqlScalarType::String.nullable(true))
11780        .with_column("grantee", SqlScalarType::String.nullable(true))
11781        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11782        .finish(),
11783    column_comments: BTreeMap::from_iter([
11784        ("grantor", "The role that granted the privilege."),
11785        ("grantee", "The role that the privilege was granted to."),
11786        ("privilege_type", "They type of privilege granted."),
11787    ]),
11788    sql: r#"SELECT grantor, grantee, privilege_type
11789FROM mz_internal.mz_show_system_privileges
11790WHERE
11791    CASE
11792        WHEN grantee = 'PUBLIC' THEN true
11793        ELSE pg_has_role(grantee, 'USAGE')
11794    END"#,
11795    access: vec![PUBLIC_SELECT],
11796});
11797
11798pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11799    name: "mz_show_cluster_privileges",
11800    schema: MZ_INTERNAL_SCHEMA,
11801    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11802    desc: RelationDesc::builder()
11803        .with_column("grantor", SqlScalarType::String.nullable(true))
11804        .with_column("grantee", SqlScalarType::String.nullable(true))
11805        .with_column("name", SqlScalarType::String.nullable(false))
11806        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11807        .finish(),
11808    column_comments: BTreeMap::from_iter([
11809        ("grantor", "The role that granted the privilege."),
11810        ("grantee", "The role that the privilege was granted to."),
11811        ("name", "The name of the cluster."),
11812        ("privilege_type", "They type of privilege granted."),
11813    ]),
11814    sql: r#"SELECT
11815    grantor.name AS grantor,
11816    CASE privileges.grantee
11817        WHEN 'p' THEN 'PUBLIC'
11818        ELSE grantee.name
11819    END AS grantee,
11820    privileges.name AS name,
11821    privileges.privilege_type AS privilege_type
11822FROM
11823    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11824    FROM mz_catalog.mz_clusters
11825    WHERE id NOT LIKE 's%') AS privileges
11826LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11827LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11828WHERE privileges.grantee NOT LIKE 's%'"#,
11829    access: vec![PUBLIC_SELECT],
11830});
11831
11832pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11833    name: "mz_show_my_cluster_privileges",
11834    schema: MZ_INTERNAL_SCHEMA,
11835    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11836    desc: RelationDesc::builder()
11837        .with_column("grantor", SqlScalarType::String.nullable(true))
11838        .with_column("grantee", SqlScalarType::String.nullable(true))
11839        .with_column("name", SqlScalarType::String.nullable(false))
11840        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11841        .finish(),
11842    column_comments: BTreeMap::from_iter([
11843        ("grantor", "The role that granted the privilege."),
11844        ("grantee", "The role that the privilege was granted to."),
11845        ("name", "The name of the cluster."),
11846        ("privilege_type", "They type of privilege granted."),
11847    ]),
11848    sql: r#"SELECT grantor, grantee, name, privilege_type
11849FROM mz_internal.mz_show_cluster_privileges
11850WHERE
11851    CASE
11852        WHEN grantee = 'PUBLIC' THEN true
11853        ELSE pg_has_role(grantee, 'USAGE')
11854    END"#,
11855    access: vec![PUBLIC_SELECT],
11856});
11857
11858pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11859    name: "mz_show_database_privileges",
11860    schema: MZ_INTERNAL_SCHEMA,
11861    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
11862    desc: RelationDesc::builder()
11863        .with_column("grantor", SqlScalarType::String.nullable(true))
11864        .with_column("grantee", SqlScalarType::String.nullable(true))
11865        .with_column("name", SqlScalarType::String.nullable(false))
11866        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11867        .finish(),
11868    column_comments: BTreeMap::from_iter([
11869        ("grantor", "The role that granted the privilege."),
11870        ("grantee", "The role that the privilege was granted to."),
11871        ("name", "The name of the database."),
11872        ("privilege_type", "They type of privilege granted."),
11873    ]),
11874    sql: r#"SELECT
11875    grantor.name AS grantor,
11876    CASE privileges.grantee
11877        WHEN 'p' THEN 'PUBLIC'
11878        ELSE grantee.name
11879    END AS grantee,
11880    privileges.name AS name,
11881    privileges.privilege_type AS privilege_type
11882FROM
11883    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11884    FROM mz_catalog.mz_databases
11885    WHERE id NOT LIKE 's%') AS privileges
11886LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11887LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11888WHERE privileges.grantee NOT LIKE 's%'"#,
11889    access: vec![PUBLIC_SELECT],
11890});
11891
11892pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11893    name: "mz_show_my_database_privileges",
11894    schema: MZ_INTERNAL_SCHEMA,
11895    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
11896    desc: RelationDesc::builder()
11897        .with_column("grantor", SqlScalarType::String.nullable(true))
11898        .with_column("grantee", SqlScalarType::String.nullable(true))
11899        .with_column("name", SqlScalarType::String.nullable(false))
11900        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11901        .finish(),
11902    column_comments: BTreeMap::from_iter([
11903        ("grantor", "The role that granted the privilege."),
11904        ("grantee", "The role that the privilege was granted to."),
11905        ("name", "The name of the cluster."),
11906        ("privilege_type", "They type of privilege granted."),
11907    ]),
11908    sql: r#"SELECT grantor, grantee, name, privilege_type
11909FROM mz_internal.mz_show_database_privileges
11910WHERE
11911    CASE
11912        WHEN grantee = 'PUBLIC' THEN true
11913        ELSE pg_has_role(grantee, 'USAGE')
11914    END"#,
11915    access: vec![PUBLIC_SELECT],
11916});
11917
11918pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11919    name: "mz_show_schema_privileges",
11920    schema: MZ_INTERNAL_SCHEMA,
11921    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
11922    desc: RelationDesc::builder()
11923        .with_column("grantor", SqlScalarType::String.nullable(true))
11924        .with_column("grantee", SqlScalarType::String.nullable(true))
11925        .with_column("database", SqlScalarType::String.nullable(true))
11926        .with_column("name", SqlScalarType::String.nullable(false))
11927        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11928        .finish(),
11929    column_comments: BTreeMap::from_iter([
11930        ("grantor", "The role that granted the privilege."),
11931        ("grantee", "The role that the privilege was granted to."),
11932        (
11933            "database",
11934            "The name of the database containing the schema.",
11935        ),
11936        ("name", "The name of the schema."),
11937        ("privilege_type", "They type of privilege granted."),
11938    ]),
11939    sql: r#"SELECT
11940    grantor.name AS grantor,
11941    CASE privileges.grantee
11942        WHEN 'p' THEN 'PUBLIC'
11943        ELSE grantee.name
11944    END AS grantee,
11945    databases.name AS database,
11946    privileges.name AS name,
11947    privileges.privilege_type AS privilege_type
11948FROM
11949    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
11950    FROM mz_catalog.mz_schemas
11951    WHERE id NOT LIKE 's%') AS privileges
11952LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11953LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11954LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
11955WHERE privileges.grantee NOT LIKE 's%'"#,
11956    access: vec![PUBLIC_SELECT],
11957});
11958
11959pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11960    name: "mz_show_my_schema_privileges",
11961    schema: MZ_INTERNAL_SCHEMA,
11962    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
11963    desc: RelationDesc::builder()
11964        .with_column("grantor", SqlScalarType::String.nullable(true))
11965        .with_column("grantee", SqlScalarType::String.nullable(true))
11966        .with_column("database", SqlScalarType::String.nullable(true))
11967        .with_column("name", SqlScalarType::String.nullable(false))
11968        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11969        .finish(),
11970    column_comments: BTreeMap::from_iter([
11971        ("grantor", "The role that granted the privilege."),
11972        ("grantee", "The role that the privilege was granted to."),
11973        (
11974            "database",
11975            "The name of the database containing the schema.",
11976        ),
11977        ("name", "The name of the schema."),
11978        ("privilege_type", "They type of privilege granted."),
11979    ]),
11980    sql: r#"SELECT grantor, grantee, database, name, privilege_type
11981FROM mz_internal.mz_show_schema_privileges
11982WHERE
11983    CASE
11984        WHEN grantee = 'PUBLIC' THEN true
11985        ELSE pg_has_role(grantee, 'USAGE')
11986    END"#,
11987    access: vec![PUBLIC_SELECT],
11988});
11989
11990pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11991    name: "mz_show_object_privileges",
11992    schema: MZ_INTERNAL_SCHEMA,
11993    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
11994    desc: RelationDesc::builder()
11995        .with_column("grantor", SqlScalarType::String.nullable(true))
11996        .with_column("grantee", SqlScalarType::String.nullable(true))
11997        .with_column("database", SqlScalarType::String.nullable(true))
11998        .with_column("schema", SqlScalarType::String.nullable(true))
11999        .with_column("name", SqlScalarType::String.nullable(false))
12000        .with_column("object_type", SqlScalarType::String.nullable(false))
12001        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12002        .finish(),
12003    column_comments: BTreeMap::from_iter([
12004        ("grantor", "The role that granted the privilege."),
12005        ("grantee", "The role that the privilege was granted to."),
12006        (
12007            "database",
12008            "The name of the database containing the object.",
12009        ),
12010        ("schema", "The name of the schema containing the object."),
12011        ("name", "The name of the object."),
12012        (
12013            "object_type",
12014            "The type of object the privilege is granted on.",
12015        ),
12016        ("privilege_type", "They type of privilege granted."),
12017    ]),
12018    sql: r#"SELECT
12019    grantor.name AS grantor,
12020    CASE privileges.grantee
12021            WHEN 'p' THEN 'PUBLIC'
12022            ELSE grantee.name
12023        END AS grantee,
12024    databases.name AS database,
12025    schemas.name AS schema,
12026    privileges.name AS name,
12027    privileges.type AS object_type,
12028    privileges.privilege_type AS privilege_type
12029FROM
12030    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
12031    FROM mz_catalog.mz_objects
12032    WHERE id NOT LIKE 's%') AS privileges
12033LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
12034LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
12035LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
12036LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
12037WHERE privileges.grantee NOT LIKE 's%'"#,
12038    access: vec![PUBLIC_SELECT],
12039});
12040
12041pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12042    name: "mz_show_my_object_privileges",
12043    schema: MZ_INTERNAL_SCHEMA,
12044    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
12045    desc: RelationDesc::builder()
12046        .with_column("grantor", SqlScalarType::String.nullable(true))
12047        .with_column("grantee", SqlScalarType::String.nullable(true))
12048        .with_column("database", SqlScalarType::String.nullable(true))
12049        .with_column("schema", SqlScalarType::String.nullable(true))
12050        .with_column("name", SqlScalarType::String.nullable(false))
12051        .with_column("object_type", SqlScalarType::String.nullable(false))
12052        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12053        .finish(),
12054    column_comments: BTreeMap::from_iter([
12055        ("grantor", "The role that granted the privilege."),
12056        ("grantee", "The role that the privilege was granted to."),
12057        (
12058            "database",
12059            "The name of the database containing the object.",
12060        ),
12061        ("schema", "The name of the schema containing the object."),
12062        ("name", "The name of the object."),
12063        (
12064            "object_type",
12065            "The type of object the privilege is granted on.",
12066        ),
12067        ("privilege_type", "They type of privilege granted."),
12068    ]),
12069    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12070FROM mz_internal.mz_show_object_privileges
12071WHERE
12072    CASE
12073        WHEN grantee = 'PUBLIC' THEN true
12074        ELSE pg_has_role(grantee, 'USAGE')
12075    END"#,
12076    access: vec![PUBLIC_SELECT],
12077});
12078
12079pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12080    name: "mz_show_all_privileges",
12081    schema: MZ_INTERNAL_SCHEMA,
12082    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
12083    desc: RelationDesc::builder()
12084        .with_column("grantor", SqlScalarType::String.nullable(true))
12085        .with_column("grantee", SqlScalarType::String.nullable(true))
12086        .with_column("database", SqlScalarType::String.nullable(true))
12087        .with_column("schema", SqlScalarType::String.nullable(true))
12088        .with_column("name", SqlScalarType::String.nullable(true))
12089        .with_column("object_type", SqlScalarType::String.nullable(false))
12090        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12091        .finish(),
12092    column_comments: BTreeMap::from_iter([
12093        ("grantor", "The role that granted the privilege."),
12094        ("grantee", "The role that the privilege was granted to."),
12095        (
12096            "database",
12097            "The name of the database containing the object.",
12098        ),
12099        ("schema", "The name of the schema containing the object."),
12100        ("name", "The name of the privilege target."),
12101        (
12102            "object_type",
12103            "The type of object the privilege is granted on.",
12104        ),
12105        ("privilege_type", "They type of privilege granted."),
12106    ]),
12107    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
12108FROM mz_internal.mz_show_system_privileges
12109UNION ALL
12110SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
12111FROM mz_internal.mz_show_cluster_privileges
12112UNION ALL
12113SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
12114FROM mz_internal.mz_show_database_privileges
12115UNION ALL
12116SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
12117FROM mz_internal.mz_show_schema_privileges
12118UNION ALL
12119SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12120FROM mz_internal.mz_show_object_privileges"#,
12121    access: vec![PUBLIC_SELECT],
12122});
12123
12124pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12125    name: "mz_show_all_my_privileges",
12126    schema: MZ_INTERNAL_SCHEMA,
12127    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
12128    desc: RelationDesc::builder()
12129        .with_column("grantor", SqlScalarType::String.nullable(true))
12130        .with_column("grantee", SqlScalarType::String.nullable(true))
12131        .with_column("database", SqlScalarType::String.nullable(true))
12132        .with_column("schema", SqlScalarType::String.nullable(true))
12133        .with_column("name", SqlScalarType::String.nullable(true))
12134        .with_column("object_type", SqlScalarType::String.nullable(false))
12135        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12136        .finish(),
12137    column_comments: BTreeMap::from_iter([
12138        ("grantor", "The role that granted the privilege."),
12139        ("grantee", "The role that the privilege was granted to."),
12140        (
12141            "database",
12142            "The name of the database containing the object.",
12143        ),
12144        ("schema", "The name of the schema containing the object."),
12145        ("name", "The name of the privilege target."),
12146        (
12147            "object_type",
12148            "The type of object the privilege is granted on.",
12149        ),
12150        ("privilege_type", "They type of privilege granted."),
12151    ]),
12152    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12153FROM mz_internal.mz_show_all_privileges
12154WHERE
12155    CASE
12156        WHEN grantee = 'PUBLIC' THEN true
12157        ELSE pg_has_role(grantee, 'USAGE')
12158    END"#,
12159    access: vec![PUBLIC_SELECT],
12160});
12161
12162pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12163    name: "mz_show_default_privileges",
12164    schema: MZ_INTERNAL_SCHEMA,
12165    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
12166    desc: RelationDesc::builder()
12167        .with_column("object_owner", SqlScalarType::String.nullable(true))
12168        .with_column("database", SqlScalarType::String.nullable(true))
12169        .with_column("schema", SqlScalarType::String.nullable(true))
12170        .with_column("object_type", SqlScalarType::String.nullable(false))
12171        .with_column("grantee", SqlScalarType::String.nullable(true))
12172        .with_column("privilege_type", SqlScalarType::String.nullable(true))
12173        .finish(),
12174    column_comments: BTreeMap::from_iter([
12175        (
12176            "object_owner",
12177            "Privileges described in this row will be granted on objects created by `object_owner`.",
12178        ),
12179        (
12180            "database",
12181            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
12182        ),
12183        (
12184            "schema",
12185            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
12186        ),
12187        (
12188            "object_type",
12189            "Privileges described in this row will be granted only on objects of type `object_type`.",
12190        ),
12191        (
12192            "grantee",
12193            "Privileges described in this row will be granted to `grantee`.",
12194        ),
12195        ("privilege_type", "They type of privilege to be granted."),
12196    ]),
12197    sql: r#"SELECT
12198    CASE defaults.role_id
12199        WHEN 'p' THEN 'PUBLIC'
12200        ELSE object_owner.name
12201    END AS object_owner,
12202    databases.name AS database,
12203    schemas.name AS schema,
12204    object_type,
12205    CASE defaults.grantee
12206        WHEN 'p' THEN 'PUBLIC'
12207        ELSE grantee.name
12208    END AS grantee,
12209    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
12210FROM mz_catalog.mz_default_privileges defaults
12211LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
12212LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
12213LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
12214LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
12215WHERE defaults.grantee NOT LIKE 's%'
12216    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
12217    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
12218    access: vec![PUBLIC_SELECT],
12219});
12220
12221pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12222    name: "mz_show_my_default_privileges",
12223    schema: MZ_INTERNAL_SCHEMA,
12224    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
12225    desc: RelationDesc::builder()
12226        .with_column("object_owner", SqlScalarType::String.nullable(true))
12227        .with_column("database", SqlScalarType::String.nullable(true))
12228        .with_column("schema", SqlScalarType::String.nullable(true))
12229        .with_column("object_type", SqlScalarType::String.nullable(false))
12230        .with_column("grantee", SqlScalarType::String.nullable(true))
12231        .with_column("privilege_type", SqlScalarType::String.nullable(true))
12232        .finish(),
12233    column_comments: BTreeMap::from_iter([
12234        (
12235            "object_owner",
12236            "Privileges described in this row will be granted on objects created by `object_owner`.",
12237        ),
12238        (
12239            "database",
12240            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
12241        ),
12242        (
12243            "schema",
12244            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
12245        ),
12246        (
12247            "object_type",
12248            "Privileges described in this row will be granted only on objects of type `object_type`.",
12249        ),
12250        (
12251            "grantee",
12252            "Privileges described in this row will be granted to `grantee`.",
12253        ),
12254        ("privilege_type", "They type of privilege to be granted."),
12255    ]),
12256    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
12257FROM mz_internal.mz_show_default_privileges
12258WHERE
12259    CASE
12260        WHEN grantee = 'PUBLIC' THEN true
12261        ELSE pg_has_role(grantee, 'USAGE')
12262    END"#,
12263    access: vec![PUBLIC_SELECT],
12264});
12265
12266pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12267    name: "mz_show_network_policies",
12268    schema: MZ_INTERNAL_SCHEMA,
12269    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
12270    desc: RelationDesc::builder()
12271        .with_column("name", SqlScalarType::String.nullable(false))
12272        .with_column("rules", SqlScalarType::String.nullable(true))
12273        .with_column("comment", SqlScalarType::String.nullable(false))
12274        .finish(),
12275    column_comments: BTreeMap::new(),
12276    sql: "
12277WITH comments AS (
12278    SELECT id, comment
12279    FROM mz_internal.mz_comments
12280    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
12281)
12282SELECT
12283    policy.name,
12284    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
12285    COALESCE(comment, '') as comment
12286FROM
12287    mz_internal.mz_network_policies as policy
12288LEFT JOIN
12289    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
12290LEFT JOIN
12291    comments ON policy.id = comments.id
12292WHERE
12293    policy.id NOT LIKE 's%'
12294AND
12295    policy.id NOT LIKE 'g%'
12296GROUP BY policy.name, comments.comment;",
12297    access: vec![PUBLIC_SELECT],
12298});
12299
12300pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12301    name: "mz_cluster_replica_history",
12302    schema: MZ_INTERNAL_SCHEMA,
12303    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
12304    desc: RelationDesc::builder()
12305        .with_column("replica_id", SqlScalarType::String.nullable(true))
12306        .with_column("size", SqlScalarType::String.nullable(true))
12307        .with_column("cluster_id", SqlScalarType::String.nullable(true))
12308        .with_column("cluster_name", SqlScalarType::String.nullable(true))
12309        .with_column("replica_name", SqlScalarType::String.nullable(true))
12310        .with_column(
12311            "created_at",
12312            SqlScalarType::TimestampTz { precision: None }.nullable(false),
12313        )
12314        .with_column(
12315            "dropped_at",
12316            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12317        )
12318        .with_column(
12319            "credits_per_hour",
12320            SqlScalarType::Numeric { max_scale: None }.nullable(true),
12321        )
12322        .finish(),
12323    column_comments: BTreeMap::from_iter([
12324        ("replica_id", "The ID of a cluster replica."),
12325        (
12326            "size",
12327            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
12328        ),
12329        (
12330            "cluster_id",
12331            "The ID of the cluster associated with the replica.",
12332        ),
12333        (
12334            "cluster_name",
12335            "The name of the cluster associated with the replica.",
12336        ),
12337        ("replica_name", "The name of the replica."),
12338        ("created_at", "The time at which the replica was created."),
12339        (
12340            "dropped_at",
12341            "The time at which the replica was dropped, or `NULL` if it still exists.",
12342        ),
12343        (
12344            "credits_per_hour",
12345            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
12346        ),
12347    ]),
12348    sql: r#"
12349        WITH
12350            creates AS
12351            (
12352                SELECT
12353                    details ->> 'logical_size' AS size,
12354                    details ->> 'replica_id' AS replica_id,
12355                    details ->> 'replica_name' AS replica_name,
12356                    details ->> 'cluster_name' AS cluster_name,
12357                    details ->> 'cluster_id' AS cluster_id,
12358                    occurred_at
12359                FROM mz_catalog.mz_audit_events
12360                WHERE
12361                    object_type = 'cluster-replica' AND event_type = 'create'
12362                        AND
12363                    details ->> 'replica_id' IS NOT NULL
12364                        AND
12365                    details ->> 'cluster_id' !~~ 's%'
12366            ),
12367            drops AS
12368            (
12369                SELECT details ->> 'replica_id' AS replica_id, occurred_at
12370                FROM mz_catalog.mz_audit_events
12371                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
12372            )
12373        SELECT
12374            creates.replica_id,
12375            creates.size,
12376            creates.cluster_id,
12377            creates.cluster_name,
12378            creates.replica_name,
12379            creates.occurred_at AS created_at,
12380            drops.occurred_at AS dropped_at,
12381            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
12382        FROM
12383            creates
12384                LEFT JOIN drops ON creates.replica_id = drops.replica_id
12385                LEFT JOIN
12386                    mz_catalog.mz_cluster_replica_sizes
12387                    ON mz_cluster_replica_sizes.size = creates.size"#,
12388    access: vec![PUBLIC_SELECT],
12389});
12390
12391pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12392    name: "mz_cluster_replica_name_history",
12393    schema: MZ_INTERNAL_SCHEMA,
12394    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
12395    desc: RelationDesc::builder()
12396        .with_column(
12397            "occurred_at",
12398            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12399        )
12400        .with_column("id", SqlScalarType::String.nullable(true))
12401        .with_column("previous_name", SqlScalarType::String.nullable(true))
12402        .with_column("new_name", SqlScalarType::String.nullable(true))
12403        .finish(),
12404    column_comments: BTreeMap::from_iter([
12405        (
12406            "occurred_at",
12407            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
12408        ),
12409        ("id", "The ID of the cluster replica."),
12410        (
12411            "previous_name",
12412            "The previous name of the cluster replica. `NULL` if there was no previous name.",
12413        ),
12414        ("new_name", "The new name of the cluster replica."),
12415    ]),
12416    sql: r#"WITH user_replica_alter_history AS (
12417  SELECT occurred_at,
12418    audit_events.details->>'replica_id' AS id,
12419    audit_events.details->>'old_name' AS previous_name,
12420    audit_events.details->>'new_name' AS new_name
12421  FROM mz_catalog.mz_audit_events AS audit_events
12422  WHERE object_type = 'cluster-replica'
12423    AND audit_events.event_type = 'alter'
12424    AND audit_events.details->>'replica_id' like 'u%'
12425),
12426user_replica_create_history AS (
12427  SELECT occurred_at,
12428    audit_events.details->>'replica_id' AS id,
12429    NULL AS previous_name,
12430    audit_events.details->>'replica_name' AS new_name
12431  FROM mz_catalog.mz_audit_events AS audit_events
12432  WHERE object_type = 'cluster-replica'
12433    AND audit_events.event_type = 'create'
12434    AND audit_events.details->>'replica_id' like 'u%'
12435),
12436-- Because built in system cluster replicas don't have audit events, we need to manually add them
12437system_replicas AS (
12438  -- We assume that the system cluster replicas were created at the beginning of time
12439  SELECT NULL::timestamptz AS occurred_at,
12440    id,
12441    NULL AS previous_name,
12442    name AS new_name
12443  FROM mz_catalog.mz_cluster_replicas
12444  WHERE id LIKE 's%'
12445)
12446SELECT *
12447FROM user_replica_alter_history
12448UNION ALL
12449SELECT *
12450FROM user_replica_create_history
12451UNION ALL
12452SELECT *
12453FROM system_replicas"#,
12454    access: vec![PUBLIC_SELECT],
12455});
12456
12457pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12458    name: "mz_hydration_statuses",
12459    schema: MZ_INTERNAL_SCHEMA,
12460    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
12461    desc: RelationDesc::builder()
12462        .with_column("object_id", SqlScalarType::String.nullable(false))
12463        .with_column("replica_id", SqlScalarType::String.nullable(true))
12464        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
12465        .finish(),
12466    column_comments: BTreeMap::from_iter([
12467        (
12468            "object_id",
12469            "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`.",
12470        ),
12471        ("replica_id", "The ID of a cluster replica."),
12472        ("hydrated", "Whether the object is hydrated on the replica."),
12473    ]),
12474    sql: r#"WITH
12475-- Joining against the linearizable catalog tables ensures that this view
12476-- always contains the set of installed objects, even when it depends
12477-- on introspection relations that may received delayed updates.
12478--
12479-- Note that this view only includes objects that are maintained by dataflows.
12480-- In particular, some source types (webhook, introspection, ...) are not and
12481-- are therefore omitted.
12482indexes AS (
12483    SELECT
12484        i.id AS object_id,
12485        h.replica_id,
12486        COALESCE(h.hydrated, false) AS hydrated
12487    FROM mz_catalog.mz_indexes i
12488    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12489        ON (h.object_id = i.id)
12490),
12491materialized_views AS (
12492    SELECT
12493        i.id AS object_id,
12494        h.replica_id,
12495        COALESCE(h.hydrated, false) AS hydrated
12496    FROM mz_catalog.mz_materialized_views i
12497    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12498        ON (h.object_id = i.id)
12499),
12500continual_tasks AS (
12501    SELECT
12502        i.id AS object_id,
12503        h.replica_id,
12504        COALESCE(h.hydrated, false) AS hydrated
12505    FROM mz_internal.mz_continual_tasks i
12506    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12507        ON (h.object_id = i.id)
12508),
12509-- Hydration is a dataflow concept and not all sources are maintained by
12510-- dataflows, so we need to find the ones that are. Generally, sources that
12511-- have a cluster ID are maintained by a dataflow running on that cluster.
12512-- Webhook sources are an exception to this rule.
12513sources_with_clusters AS (
12514    SELECT id, cluster_id
12515    FROM mz_catalog.mz_sources
12516    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12517),
12518sources AS (
12519    SELECT
12520        s.id AS object_id,
12521        ss.replica_id AS replica_id,
12522        ss.rehydration_latency IS NOT NULL AS hydrated
12523    FROM sources_with_clusters s
12524    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12525),
12526-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12527-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12528-- There is likely still a possibility of FPs.
12529sinks AS (
12530    SELECT
12531        s.id AS object_id,
12532        r.id AS replica_id,
12533        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12534    FROM mz_catalog.mz_sinks s
12535    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12536    JOIN mz_catalog.mz_cluster_replicas r
12537        ON (r.cluster_id = s.cluster_id)
12538    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12539        ON (f.object_id = s.id AND f.replica_id = r.id)
12540)
12541SELECT * FROM indexes
12542UNION ALL
12543SELECT * FROM materialized_views
12544UNION ALL
12545SELECT * FROM continual_tasks
12546UNION ALL
12547SELECT * FROM sources
12548UNION ALL
12549SELECT * FROM sinks"#,
12550    access: vec![PUBLIC_SELECT],
12551});
12552
12553pub const MZ_HYDRATION_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12554    name: "mz_hydration_statuses_ind",
12555    schema: MZ_INTERNAL_SCHEMA,
12556    oid: oid::INDEX_MZ_HYDRATION_STATUSES_IND_OID,
12557    sql: "IN CLUSTER mz_catalog_server
12558ON mz_internal.mz_hydration_statuses (object_id, replica_id)",
12559    is_retained_metrics_object: false,
12560};
12561
12562pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12563    name: "mz_materialization_dependencies",
12564    schema: MZ_INTERNAL_SCHEMA,
12565    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12566    desc: RelationDesc::builder()
12567        .with_column("object_id", SqlScalarType::String.nullable(false))
12568        .with_column("dependency_id", SqlScalarType::String.nullable(false))
12569        .finish(),
12570    column_comments: BTreeMap::from_iter([
12571        (
12572            "object_id",
12573            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12574        ),
12575        (
12576            "dependency_id",
12577            "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`.",
12578        ),
12579    ]),
12580    sql: "
12581SELECT object_id, dependency_id
12582FROM mz_internal.mz_compute_dependencies
12583UNION ALL
12584SELECT s.id, d.referenced_object_id AS dependency_id
12585FROM mz_internal.mz_object_dependencies d
12586JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12587JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12588    access: vec![PUBLIC_SELECT],
12589});
12590
12591pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12592    name: "mz_materialization_lag",
12593    schema: MZ_INTERNAL_SCHEMA,
12594    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12595    desc: RelationDesc::builder()
12596        .with_column("object_id", SqlScalarType::String.nullable(false))
12597        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
12598        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
12599        .with_column(
12600            "slowest_local_input_id",
12601            SqlScalarType::String.nullable(false),
12602        )
12603        .with_column(
12604            "slowest_global_input_id",
12605            SqlScalarType::String.nullable(false),
12606        )
12607        .finish(),
12608    column_comments: BTreeMap::from_iter([
12609        (
12610            "object_id",
12611            "The ID of the materialized view, index, or sink.",
12612        ),
12613        (
12614            "local_lag",
12615            "The amount of time the materialization lags behind its direct inputs.",
12616        ),
12617        (
12618            "global_lag",
12619            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12620        ),
12621        (
12622            "slowest_local_input_id",
12623            "The ID of the slowest direct input.",
12624        ),
12625        (
12626            "slowest_global_input_id",
12627            "The ID of the slowest root input.",
12628        ),
12629    ]),
12630    sql: "
12631WITH MUTUALLY RECURSIVE
12632    -- IDs of objects for which we want to know the lag.
12633    materializations (id text) AS (
12634        SELECT id FROM mz_catalog.mz_indexes
12635        UNION ALL
12636        SELECT id FROM mz_catalog.mz_materialized_views
12637        UNION ALL
12638        SELECT id FROM mz_internal.mz_continual_tasks
12639        UNION ALL
12640        SELECT id FROM mz_catalog.mz_sinks
12641    ),
12642    -- Direct dependencies of materializations.
12643    direct_dependencies (id text, dep_id text) AS (
12644        SELECT m.id, d.dependency_id
12645        FROM materializations m
12646        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12647    ),
12648    -- All transitive dependencies of materializations.
12649    transitive_dependencies (id text, dep_id text) AS (
12650        SELECT id, dep_id FROM direct_dependencies
12651        UNION
12652        SELECT td.id, dd.dep_id
12653        FROM transitive_dependencies td
12654        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12655    ),
12656    -- Root dependencies of materializations (sources and tables).
12657    root_dependencies (id text, dep_id text) AS (
12658        SELECT *
12659        FROM transitive_dependencies td
12660        WHERE NOT EXISTS (
12661            SELECT 1
12662            FROM direct_dependencies dd
12663            WHERE dd.id = td.dep_id
12664        )
12665    ),
12666    -- Write progress times of materializations.
12667    materialization_times (id text, time timestamptz) AS (
12668        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12669        FROM materializations m
12670        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12671    ),
12672    -- Write progress times of direct dependencies of materializations.
12673    input_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 direct_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    ),
12682    -- Write progress times of root dependencies of materializations.
12683    root_times (id text, slowest_dep text, time timestamptz) AS (
12684        SELECT DISTINCT ON (d.id)
12685            d.id,
12686            d.dep_id,
12687            to_timestamp(f.write_frontier::text::double / 1000)
12688        FROM root_dependencies d
12689        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12690        ORDER BY d.id, f.write_frontier ASC
12691    )
12692SELECT
12693    id AS object_id,
12694    -- Ensure that lag values are always NULL for materializations that have reached the empty
12695    -- frontier, as those have processed all their input data.
12696    -- Also make sure that lag values are never negative, even when input frontiers are before
12697    -- output frontiers (as can happen during hydration).
12698    CASE
12699        WHEN m.time IS NULL THEN INTERVAL '0'
12700        WHEN i.time IS NULL THEN NULL
12701        ELSE greatest(i.time - m.time, INTERVAL '0')
12702    END AS local_lag,
12703    CASE
12704        WHEN m.time IS NULL THEN INTERVAL '0'
12705        WHEN r.time IS NULL THEN NULL
12706        ELSE greatest(r.time - m.time, INTERVAL '0')
12707    END AS global_lag,
12708    i.slowest_dep AS slowest_local_input_id,
12709    r.slowest_dep AS slowest_global_input_id
12710FROM materialization_times m
12711JOIN input_times i USING (id)
12712JOIN root_times r USING (id)",
12713    access: vec![PUBLIC_SELECT],
12714});
12715
12716/**
12717 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12718 * It's specifically for the Console's environment overview page to speed up load times.
12719 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12720 */
12721pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12722    BuiltinView {
12723        name: "mz_console_cluster_utilization_overview",
12724        schema: MZ_INTERNAL_SCHEMA,
12725        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12726        desc: RelationDesc::builder()
12727            .with_column(
12728                "bucket_start",
12729                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12730            )
12731            .with_column("replica_id", SqlScalarType::String.nullable(false))
12732            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
12733            .with_column(
12734                "max_memory_at",
12735                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12736            )
12737            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
12738            .with_column(
12739                "max_disk_at",
12740                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12741            )
12742            .with_column(
12743                "memory_and_disk_percent",
12744                SqlScalarType::Float64.nullable(true),
12745            )
12746            .with_column(
12747                "max_memory_and_disk_memory_percent",
12748                SqlScalarType::Float64.nullable(true),
12749            )
12750            .with_column(
12751                "max_memory_and_disk_disk_percent",
12752                SqlScalarType::Float64.nullable(true),
12753            )
12754            .with_column(
12755                "max_memory_and_disk_at",
12756                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12757            )
12758            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
12759            .with_column(
12760                "max_heap_at",
12761                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12762            )
12763            .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
12764            .with_column(
12765                "max_cpu_at",
12766                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12767            )
12768            .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
12769            .with_column(
12770                "bucket_end",
12771                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12772            )
12773            .with_column("name", SqlScalarType::String.nullable(true))
12774            .with_column("cluster_id", SqlScalarType::String.nullable(true))
12775            .with_column("size", SqlScalarType::String.nullable(true))
12776            .finish(),
12777        column_comments: BTreeMap::new(),
12778        sql: r#"WITH replica_history AS (
12779  SELECT replica_id,
12780    size,
12781    cluster_id
12782  FROM mz_internal.mz_cluster_replica_history
12783  UNION
12784  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12785  SELECT id AS replica_id,
12786    size,
12787    cluster_id
12788  FROM mz_catalog.mz_cluster_replicas
12789),
12790replica_metrics_history AS (
12791  SELECT
12792    m.occurred_at,
12793    m.replica_id,
12794    r.size,
12795    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0)) / NULLIF(s.processes, 0) AS cpu_percent,
12796    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0)) / NULLIF(s.processes, 0) AS memory_percent,
12797    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0)) / NULLIF(s.processes, 0) AS disk_percent,
12798    (SUM(m.heap_bytes::float8) / NULLIF(m.heap_limit, 0)) / NULLIF(s.processes, 0) AS heap_percent,
12799    SUM(m.disk_bytes::float8) AS disk_bytes,
12800    SUM(m.memory_bytes::float8) AS memory_bytes,
12801    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12802    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12803  FROM
12804    replica_history AS r
12805    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12806    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12807  GROUP BY
12808    m.occurred_at,
12809    m.replica_id,
12810    r.size,
12811    s.cpu_nano_cores,
12812    s.memory_bytes,
12813    s.disk_bytes,
12814    m.heap_limit,
12815    s.processes
12816),
12817replica_utilization_history_binned AS (
12818  SELECT m.occurred_at,
12819    m.replica_id,
12820    m.cpu_percent,
12821    m.memory_percent,
12822    m.memory_bytes,
12823    m.disk_percent,
12824    m.disk_bytes,
12825    m.heap_percent,
12826    m.total_disk_bytes,
12827    m.total_memory_bytes,
12828    m.size,
12829    date_bin(
12830      '8 HOURS',
12831      occurred_at,
12832      '1970-01-01'::timestamp
12833    ) AS bucket_start
12834  FROM replica_history AS r
12835    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12836  WHERE mz_now() <= date_bin(
12837      '8 HOURS',
12838      occurred_at,
12839      '1970-01-01'::timestamp
12840    ) + INTERVAL '14 DAYS'
12841),
12842-- For each (replica, bucket), take the (replica, bucket) with the highest memory
12843max_memory AS (
12844  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12845    replica_id,
12846    memory_percent,
12847    occurred_at
12848  FROM replica_utilization_history_binned
12849  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12850  ORDER BY bucket_start,
12851    replica_id,
12852    COALESCE(memory_bytes, 0) DESC
12853),
12854max_disk AS (
12855  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12856    replica_id,
12857    disk_percent,
12858    occurred_at
12859  FROM replica_utilization_history_binned
12860  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12861  ORDER BY bucket_start,
12862    replica_id,
12863    COALESCE(disk_bytes, 0) DESC
12864),
12865max_cpu AS (
12866  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12867    replica_id,
12868    cpu_percent,
12869    occurred_at
12870  FROM replica_utilization_history_binned
12871  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12872  ORDER BY bucket_start,
12873    replica_id,
12874    COALESCE(cpu_percent, 0) DESC
12875),
12876/*
12877 This is different
12878 from adding max_memory
12879 and max_disk per bucket because both
12880 values may not occur at the same time if the bucket interval is large.
12881 */
12882max_memory_and_disk AS (
12883  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12884    replica_id,
12885    memory_percent,
12886    disk_percent,
12887    memory_and_disk_percent,
12888    occurred_at
12889  FROM (
12890      SELECT *,
12891        CASE
12892          WHEN disk_bytes IS NULL
12893          AND memory_bytes IS NULL THEN NULL
12894          ELSE (COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0))
12895               / (total_disk_bytes::numeric + total_memory_bytes::numeric)
12896        END AS memory_and_disk_percent
12897      FROM replica_utilization_history_binned
12898    ) AS max_memory_and_disk_inner
12899  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12900  ORDER BY bucket_start,
12901    replica_id,
12902    COALESCE(memory_and_disk_percent, 0) DESC
12903),
12904max_heap AS (
12905  SELECT DISTINCT ON (bucket_start, replica_id)
12906    bucket_start,
12907    replica_id,
12908    heap_percent,
12909    occurred_at
12910  FROM replica_utilization_history_binned
12911  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12912  ORDER BY bucket_start, replica_id, COALESCE(heap_percent, 0) DESC
12913),
12914-- For each (replica, bucket), get its offline events at that time
12915replica_offline_event_history AS (
12916  SELECT date_bin(
12917      '8 HOURS',
12918      occurred_at,
12919      '1970-01-01'::timestamp
12920    ) AS bucket_start,
12921    replica_id,
12922    jsonb_agg(
12923      jsonb_build_object(
12924        'replicaId',
12925        rsh.replica_id,
12926        'occurredAt',
12927        rsh.occurred_at,
12928        'status',
12929        rsh.status,
12930        'reason',
12931        rsh.reason
12932      )
12933    ) AS offline_events
12934  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
12935  WHERE process_id = '0'
12936    AND status = 'offline'
12937    AND mz_now() <= date_bin(
12938      '8 HOURS',
12939      occurred_at,
12940      '1970-01-01'::timestamp
12941    ) + INTERVAL '14 DAYS'
12942  GROUP BY bucket_start,
12943    replica_id
12944)
12945SELECT
12946  bucket_start,
12947  replica_id,
12948  max_memory.memory_percent,
12949  max_memory.occurred_at as max_memory_at,
12950  max_disk.disk_percent,
12951  max_disk.occurred_at as max_disk_at,
12952  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
12953  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
12954  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
12955  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
12956  max_heap.heap_percent,
12957  max_heap.occurred_at as max_heap_at,
12958  max_cpu.cpu_percent as max_cpu_percent,
12959  max_cpu.occurred_at as max_cpu_at,
12960  replica_offline_event_history.offline_events,
12961  bucket_start + INTERVAL '8 HOURS' as bucket_end,
12962  replica_name_history.new_name AS name,
12963  replica_history.cluster_id,
12964  replica_history.size
12965FROM max_memory
12966JOIN max_disk USING (bucket_start, replica_id)
12967JOIN max_cpu USING (bucket_start, replica_id)
12968JOIN max_memory_and_disk USING (bucket_start, replica_id)
12969JOIN max_heap USING (bucket_start, replica_id)
12970JOIN replica_history USING (replica_id)
12971CROSS JOIN LATERAL (
12972  SELECT new_name
12973  FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
12974  WHERE replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
12975    AND bucket_start + INTERVAL '8 HOURS' >= COALESCE(
12976      replica_name_history.occurred_at,
12977      '1970-01-01'::timestamp
12978    )
12979  ORDER BY replica_name_history.occurred_at DESC
12980  LIMIT '1'
12981) AS replica_name_history
12982LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
12983        access: vec![PUBLIC_SELECT],
12984    }
12985});
12986
12987/**
12988 * Traces the blue/green deployment lineage in the audit log to determine all cluster
12989 * IDs that are logically the same cluster.
12990 * cluster_id: The ID of a cluster.
12991 * current_deployment_cluster_id: The cluster ID of the last cluster in
12992 *   cluster_id's blue/green lineage.
12993 * cluster_name: The name of the cluster.
12994 * The approach taken is as follows. First, find all extant clusters and add them
12995 * to the result set. Per cluster, we do the following:
12996 * 1. Find the most recent create or rename event. This moment represents when the
12997 *    cluster took on its final logical identity.
12998 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
12999 *    appended) that was dropped within one minute of that moment. That cluster is
13000 *    almost certainly the logical predecessor of the current cluster. Add the cluster
13001 *    to the result set.
13002 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
13003 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
13004 * but one that's likely to be pretty good one. If a name is reused after more
13005 * than one minute, that's a good sign that it wasn't an automatic blue/green
13006 * process, but someone turning on a new use case that happens to have the same
13007 * name as a previous but logically distinct use case.
13008 */
13009pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13010    name: "mz_cluster_deployment_lineage",
13011    schema: MZ_INTERNAL_SCHEMA,
13012    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
13013    desc: RelationDesc::builder()
13014        .with_column("cluster_id", SqlScalarType::String.nullable(true))
13015        .with_column(
13016            "current_deployment_cluster_id",
13017            SqlScalarType::String.nullable(false),
13018        )
13019        .with_column("cluster_name", SqlScalarType::String.nullable(false))
13020        .with_key(vec![0, 1, 2])
13021        .finish(),
13022    column_comments: BTreeMap::from_iter([
13023        (
13024            "cluster_id",
13025            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
13026        ),
13027        (
13028            "current_deployment_cluster_id",
13029            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
13030        ),
13031        ("cluster_name", "The name of the cluster"),
13032    ]),
13033    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
13034  cluster_id text,
13035  cluster_name text,
13036  event_type text,
13037  occurred_at timestamptz
13038) AS (
13039  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
13040    coalesce(details->>'name', details->>'new_name') AS cluster_name,
13041    event_type,
13042    occurred_at
13043  FROM mz_audit_events
13044  WHERE (
13045      event_type IN ('create', 'drop')
13046      OR (
13047        event_type = 'alter'
13048        AND details ? 'new_name'
13049      )
13050    )
13051    AND object_type = 'cluster'
13052    AND mz_now() < occurred_at + INTERVAL '30 days'
13053),
13054mz_cluster_deployment_lineage (
13055  cluster_id text,
13056  current_deployment_cluster_id text,
13057  cluster_name text
13058) AS (
13059  SELECT c.id,
13060    c.id,
13061    c.name
13062  FROM mz_clusters c
13063  WHERE c.id LIKE 'u%'
13064  UNION
13065  SELECT *
13066  FROM dropped_clusters
13067),
13068-- Closest create or rename event based on the current clusters in the result set
13069most_recent_create_or_rename (
13070  cluster_id text,
13071  current_deployment_cluster_id text,
13072  cluster_name text,
13073  occurred_at timestamptz
13074) AS (
13075  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
13076    c.current_deployment_cluster_id,
13077    e.cluster_name,
13078    e.occurred_at
13079  FROM mz_cluster_deployment_lineage c
13080    JOIN cluster_events e ON c.cluster_id = e.cluster_id
13081    AND c.cluster_name = e.cluster_name
13082  WHERE e.event_type <> 'drop'
13083  ORDER BY e.cluster_id,
13084    e.occurred_at DESC
13085),
13086-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
13087dropped_clusters (
13088  cluster_id text,
13089  current_deployment_cluster_id text,
13090  cluster_name text
13091) AS (
13092  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
13093    cr.current_deployment_cluster_id,
13094    cr.cluster_name
13095  FROM most_recent_create_or_rename cr
13096    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
13097    AND cr.occurred_at + interval '1 minute'
13098    AND (
13099      e.cluster_name = cr.cluster_name
13100      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
13101    )
13102  WHERE e.event_type = 'drop'
13103  ORDER BY cr.cluster_id,
13104    abs(
13105      extract(
13106        epoch
13107        FROM cr.occurred_at - e.occurred_at
13108      )
13109    )
13110)
13111SELECT *
13112FROM mz_cluster_deployment_lineage"#,
13113    access: vec![PUBLIC_SELECT],
13114});
13115
13116pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
13117    name: "mz_show_databases_ind",
13118    schema: MZ_INTERNAL_SCHEMA,
13119    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
13120    sql: "IN CLUSTER mz_catalog_server
13121ON mz_internal.mz_show_databases (name)",
13122    is_retained_metrics_object: false,
13123};
13124
13125pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
13126    name: "mz_show_schemas_ind",
13127    schema: MZ_INTERNAL_SCHEMA,
13128    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
13129    sql: "IN CLUSTER mz_catalog_server
13130ON mz_internal.mz_show_schemas (database_id)",
13131    is_retained_metrics_object: false,
13132};
13133
13134pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
13135    name: "mz_show_connections_ind",
13136    schema: MZ_INTERNAL_SCHEMA,
13137    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
13138    sql: "IN CLUSTER mz_catalog_server
13139ON mz_internal.mz_show_connections (schema_id)",
13140    is_retained_metrics_object: false,
13141};
13142
13143pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
13144    name: "mz_show_tables_ind",
13145    schema: MZ_INTERNAL_SCHEMA,
13146    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
13147    sql: "IN CLUSTER mz_catalog_server
13148ON mz_internal.mz_show_tables (schema_id)",
13149    is_retained_metrics_object: false,
13150};
13151
13152pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13153    name: "mz_show_sources_ind",
13154    schema: MZ_INTERNAL_SCHEMA,
13155    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
13156    sql: "IN CLUSTER mz_catalog_server
13157ON mz_internal.mz_show_sources (schema_id)",
13158    is_retained_metrics_object: false,
13159};
13160
13161pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13162    name: "mz_show_views_ind",
13163    schema: MZ_INTERNAL_SCHEMA,
13164    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
13165    sql: "IN CLUSTER mz_catalog_server
13166ON mz_internal.mz_show_views (schema_id)",
13167    is_retained_metrics_object: false,
13168};
13169
13170pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13171    name: "mz_show_materialized_views_ind",
13172    schema: MZ_INTERNAL_SCHEMA,
13173    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
13174    sql: "IN CLUSTER mz_catalog_server
13175ON mz_internal.mz_show_materialized_views (schema_id)",
13176    is_retained_metrics_object: false,
13177};
13178
13179pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
13180    name: "mz_show_sinks_ind",
13181    schema: MZ_INTERNAL_SCHEMA,
13182    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
13183    sql: "IN CLUSTER mz_catalog_server
13184ON mz_internal.mz_show_sinks (schema_id)",
13185    is_retained_metrics_object: false,
13186};
13187
13188pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
13189    name: "mz_show_types_ind",
13190    schema: MZ_INTERNAL_SCHEMA,
13191    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
13192    sql: "IN CLUSTER mz_catalog_server
13193ON mz_internal.mz_show_types (schema_id)",
13194    is_retained_metrics_object: false,
13195};
13196
13197pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
13198    name: "mz_show_roles_ind",
13199    schema: MZ_INTERNAL_SCHEMA,
13200    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
13201    sql: "IN CLUSTER mz_catalog_server
13202ON mz_internal.mz_show_roles (name)",
13203    is_retained_metrics_object: false,
13204};
13205
13206pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
13207    name: "mz_show_all_objects_ind",
13208    schema: MZ_INTERNAL_SCHEMA,
13209    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
13210    sql: "IN CLUSTER mz_catalog_server
13211ON mz_internal.mz_show_all_objects (schema_id)",
13212    is_retained_metrics_object: false,
13213};
13214
13215pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
13216    name: "mz_show_indexes_ind",
13217    schema: MZ_INTERNAL_SCHEMA,
13218    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
13219    sql: "IN CLUSTER mz_catalog_server
13220ON mz_internal.mz_show_indexes (schema_id)",
13221    is_retained_metrics_object: false,
13222};
13223
13224pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
13225    name: "mz_show_columns_ind",
13226    schema: MZ_INTERNAL_SCHEMA,
13227    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
13228    sql: "IN CLUSTER mz_catalog_server
13229ON mz_internal.mz_show_columns (id)",
13230    is_retained_metrics_object: false,
13231};
13232
13233pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
13234    name: "mz_show_clusters_ind",
13235    schema: MZ_INTERNAL_SCHEMA,
13236    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
13237    sql: "IN CLUSTER mz_catalog_server
13238ON mz_internal.mz_show_clusters (name)",
13239    is_retained_metrics_object: false,
13240};
13241
13242pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13243    name: "mz_show_cluster_replicas_ind",
13244    schema: MZ_INTERNAL_SCHEMA,
13245    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
13246    sql: "IN CLUSTER mz_catalog_server
13247ON mz_internal.mz_show_cluster_replicas (cluster)",
13248    is_retained_metrics_object: false,
13249};
13250
13251pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
13252    name: "mz_show_secrets_ind",
13253    schema: MZ_INTERNAL_SCHEMA,
13254    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
13255    sql: "IN CLUSTER mz_catalog_server
13256ON mz_internal.mz_show_secrets (schema_id)",
13257    is_retained_metrics_object: false,
13258};
13259
13260pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
13261    name: "mz_databases_ind",
13262    schema: MZ_CATALOG_SCHEMA,
13263    oid: oid::INDEX_MZ_DATABASES_IND_OID,
13264    sql: "IN CLUSTER mz_catalog_server
13265ON mz_catalog.mz_databases (name)",
13266    is_retained_metrics_object: false,
13267};
13268
13269pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
13270    name: "mz_schemas_ind",
13271    schema: MZ_CATALOG_SCHEMA,
13272    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
13273    sql: "IN CLUSTER mz_catalog_server
13274ON mz_catalog.mz_schemas (database_id)",
13275    is_retained_metrics_object: false,
13276};
13277
13278pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
13279    name: "mz_connections_ind",
13280    schema: MZ_CATALOG_SCHEMA,
13281    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
13282    sql: "IN CLUSTER mz_catalog_server
13283ON mz_catalog.mz_connections (schema_id)",
13284    is_retained_metrics_object: false,
13285};
13286
13287pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
13288    name: "mz_tables_ind",
13289    schema: MZ_CATALOG_SCHEMA,
13290    oid: oid::INDEX_MZ_TABLES_IND_OID,
13291    sql: "IN CLUSTER mz_catalog_server
13292ON mz_catalog.mz_tables (schema_id)",
13293    is_retained_metrics_object: false,
13294};
13295
13296pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
13297    name: "mz_types_ind",
13298    schema: MZ_CATALOG_SCHEMA,
13299    oid: oid::INDEX_MZ_TYPES_IND_OID,
13300    sql: "IN CLUSTER mz_catalog_server
13301ON mz_catalog.mz_types (schema_id)",
13302    is_retained_metrics_object: false,
13303};
13304
13305pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
13306    name: "mz_objects_ind",
13307    schema: MZ_CATALOG_SCHEMA,
13308    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
13309    sql: "IN CLUSTER mz_catalog_server
13310ON mz_catalog.mz_objects (schema_id)",
13311    is_retained_metrics_object: false,
13312};
13313
13314pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
13315    name: "mz_columns_ind",
13316    schema: MZ_CATALOG_SCHEMA,
13317    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
13318    sql: "IN CLUSTER mz_catalog_server
13319ON mz_catalog.mz_columns (name)",
13320    is_retained_metrics_object: false,
13321};
13322
13323pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
13324    name: "mz_secrets_ind",
13325    schema: MZ_CATALOG_SCHEMA,
13326    oid: oid::INDEX_MZ_SECRETS_IND_OID,
13327    sql: "IN CLUSTER mz_catalog_server
13328ON mz_catalog.mz_secrets (name)",
13329    is_retained_metrics_object: false,
13330};
13331
13332pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13333    name: "mz_views_ind",
13334    schema: MZ_CATALOG_SCHEMA,
13335    oid: oid::INDEX_MZ_VIEWS_IND_OID,
13336    sql: "IN CLUSTER mz_catalog_server
13337ON mz_catalog.mz_views (schema_id)",
13338    is_retained_metrics_object: false,
13339};
13340
13341pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
13342    name: "mz_console_cluster_utilization_overview_ind",
13343    schema: MZ_INTERNAL_SCHEMA,
13344    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
13345    sql: "IN CLUSTER mz_catalog_server
13346ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
13347    is_retained_metrics_object: false,
13348};
13349
13350pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
13351    name: "mz_cluster_deployment_lineage_ind",
13352    schema: MZ_INTERNAL_SCHEMA,
13353    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
13354    sql: "IN CLUSTER mz_catalog_server
13355ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
13356    is_retained_metrics_object: false,
13357};
13358
13359pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
13360    name: "mz_clusters_ind",
13361    schema: MZ_CATALOG_SCHEMA,
13362    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
13363    sql: "IN CLUSTER mz_catalog_server
13364ON mz_catalog.mz_clusters (id)",
13365    is_retained_metrics_object: false,
13366};
13367
13368pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
13369    name: "mz_indexes_ind",
13370    schema: MZ_CATALOG_SCHEMA,
13371    oid: oid::INDEX_MZ_INDEXES_IND_OID,
13372    sql: "IN CLUSTER mz_catalog_server
13373ON mz_catalog.mz_indexes (id)",
13374    is_retained_metrics_object: false,
13375};
13376
13377pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
13378    name: "mz_roles_ind",
13379    schema: MZ_CATALOG_SCHEMA,
13380    oid: oid::INDEX_MZ_ROLES_IND_OID,
13381    sql: "IN CLUSTER mz_catalog_server
13382ON mz_catalog.mz_roles (id)",
13383    is_retained_metrics_object: false,
13384};
13385
13386pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13387    name: "mz_sources_ind",
13388    schema: MZ_CATALOG_SCHEMA,
13389    oid: oid::INDEX_MZ_SOURCES_IND_OID,
13390    sql: "IN CLUSTER mz_catalog_server
13391ON mz_catalog.mz_sources (id)",
13392    is_retained_metrics_object: true,
13393};
13394
13395pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
13396    name: "mz_sinks_ind",
13397    schema: MZ_CATALOG_SCHEMA,
13398    oid: oid::INDEX_MZ_SINKS_IND_OID,
13399    sql: "IN CLUSTER mz_catalog_server
13400ON mz_catalog.mz_sinks (id)",
13401    is_retained_metrics_object: true,
13402};
13403
13404pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13405    name: "mz_materialized_views_ind",
13406    schema: MZ_CATALOG_SCHEMA,
13407    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
13408    sql: "IN CLUSTER mz_catalog_server
13409ON mz_catalog.mz_materialized_views (id)",
13410    is_retained_metrics_object: false,
13411};
13412
13413pub const MZ_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13414    name: "mz_continual_tasks_ind",
13415    schema: MZ_INTERNAL_SCHEMA,
13416    oid: oid::INDEX_MZ_CONTINUAL_TASKS_IND_OID,
13417    sql: "IN CLUSTER mz_catalog_server
13418ON mz_internal.mz_continual_tasks (id)",
13419    is_retained_metrics_object: false,
13420};
13421
13422pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13423    name: "mz_source_statuses_ind",
13424    schema: MZ_INTERNAL_SCHEMA,
13425    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
13426    sql: "IN CLUSTER mz_catalog_server
13427ON mz_internal.mz_source_statuses (id)",
13428    is_retained_metrics_object: false,
13429};
13430
13431pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13432    name: "mz_sink_statuses_ind",
13433    schema: MZ_INTERNAL_SCHEMA,
13434    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
13435    sql: "IN CLUSTER mz_catalog_server
13436ON mz_internal.mz_sink_statuses (id)",
13437    is_retained_metrics_object: false,
13438};
13439
13440pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13441    name: "mz_source_status_history_ind",
13442    schema: MZ_INTERNAL_SCHEMA,
13443    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
13444    sql: "IN CLUSTER mz_catalog_server
13445ON mz_internal.mz_source_status_history (source_id)",
13446    is_retained_metrics_object: false,
13447};
13448
13449pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13450    name: "mz_sink_status_history_ind",
13451    schema: MZ_INTERNAL_SCHEMA,
13452    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
13453    sql: "IN CLUSTER mz_catalog_server
13454ON mz_internal.mz_sink_status_history (sink_id)",
13455    is_retained_metrics_object: false,
13456};
13457
13458pub const MZ_SHOW_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13459    name: "mz_show_continual_tasks_ind",
13460    schema: MZ_INTERNAL_SCHEMA,
13461    oid: oid::INDEX_MZ_SHOW_CONTINUAL_TASKS_OID,
13462    sql: "IN CLUSTER mz_catalog_server
13463ON mz_internal.mz_show_continual_tasks (id)",
13464    is_retained_metrics_object: false,
13465};
13466
13467// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
13468// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
13469// save index space, and we don't expect the sum to be > 2^63
13470// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
13471//
13472//
13473// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
13474// underlying relation.
13475//
13476// We append WITH_HISTORY because we want to build a separate view + index that doesn't
13477// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
13478// to hold all records/updates, which causes CPU and latency of querying it to spike.
13479pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
13480    LazyLock::new(|| BuiltinView {
13481        name: "mz_source_statistics_with_history",
13482        schema: MZ_INTERNAL_SCHEMA,
13483        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
13484        desc: RelationDesc::builder()
13485            .with_column("id", SqlScalarType::String.nullable(false))
13486            .with_column("replica_id", SqlScalarType::String.nullable(true))
13487            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13488            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13489            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13490            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13491            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13492            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13493            .with_column(
13494                "rehydration_latency",
13495                SqlScalarType::Interval.nullable(true),
13496            )
13497            .with_column(
13498                "snapshot_records_known",
13499                SqlScalarType::UInt64.nullable(true),
13500            )
13501            .with_column(
13502                "snapshot_records_staged",
13503                SqlScalarType::UInt64.nullable(true),
13504            )
13505            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13506            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13507            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13508            .with_key(vec![0, 1])
13509            .finish(),
13510        column_comments: BTreeMap::new(),
13511        sql: "
13512WITH
13513    -- For each subsource, statistics are reported as its parent source
13514    subsource_to_parent AS
13515    (
13516        SELECT subsource.id AS id, parent.id AS report_id
13517        FROM mz_catalog.mz_sources AS subsource
13518            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
13519            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
13520        WHERE subsource.type = 'subsource'
13521    ),
13522    -- For each table from source, statistics are reported as its parent source
13523    table_to_parent AS
13524    (
13525        SELECT id, source_id AS report_id
13526        FROM mz_catalog.mz_tables
13527        WHERE source_id IS NOT NULL
13528    ),
13529    -- For each source and subsource, statistics are reported as itself
13530    source_refl AS
13531    (
13532        SELECT id, id AS report_id
13533        FROM mz_catalog.mz_sources
13534        WHERE type NOT IN ('progress', 'log')
13535    ),
13536    -- For each table from source, statistics are reported as itself
13537    table_refl AS
13538    (
13539        SELECT id, id AS report_id
13540        FROM mz_catalog.mz_tables
13541        WHERE source_id IS NOT NULL
13542    ),
13543    report_paths AS
13544    (
13545        SELECT id, report_id FROM subsource_to_parent
13546        UNION ALL SELECT id, report_id FROM table_to_parent
13547        UNION ALL SELECT id, report_id FROM source_refl
13548        UNION ALL SELECT id, report_id FROM table_refl
13549    )
13550SELECT
13551    report_paths.report_id AS id,
13552    replica_id,
13553    -- Counters
13554    SUM(messages_received)::uint8 AS messages_received,
13555    SUM(bytes_received)::uint8 AS bytes_received,
13556    SUM(updates_staged)::uint8 AS updates_staged,
13557    SUM(updates_committed)::uint8 AS updates_committed,
13558    -- Resetting Gauges
13559    SUM(records_indexed)::uint8 AS records_indexed,
13560    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13561    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13562    CASE
13563        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13564        ELSE MAX(rehydration_latency)::interval
13565    END AS rehydration_latency,
13566    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13567    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13568    bool_and(snapshot_committed) as snapshot_committed,
13569    -- Gauges
13570    MAX(offset_known)::uint8 AS offset_known,
13571    MIN(offset_committed)::uint8 AS offset_committed
13572FROM mz_internal.mz_source_statistics_raw
13573    JOIN report_paths USING (id)
13574GROUP BY report_paths.report_id, replica_id",
13575        access: vec![PUBLIC_SELECT],
13576    });
13577
13578pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13579    name: "mz_source_statistics_with_history_ind",
13580    schema: MZ_INTERNAL_SCHEMA,
13581    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13582    sql: "IN CLUSTER mz_catalog_server
13583ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
13584    is_retained_metrics_object: true,
13585};
13586
13587// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13588// Used to query MZ_SOURCE_STATISTICS at the current time.
13589pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13590    BuiltinView {
13591        name: "mz_source_statistics",
13592        schema: MZ_INTERNAL_SCHEMA,
13593        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13594        // We need to add a redundant where clause for a new dataflow to be created.
13595        desc: RelationDesc::builder()
13596            .with_column("id", SqlScalarType::String.nullable(false))
13597            .with_column("replica_id", SqlScalarType::String.nullable(true))
13598            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13599            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13600            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13601            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13602            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13603            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13604            .with_column(
13605                "rehydration_latency",
13606                SqlScalarType::Interval.nullable(true),
13607            )
13608            .with_column(
13609                "snapshot_records_known",
13610                SqlScalarType::UInt64.nullable(true),
13611            )
13612            .with_column(
13613                "snapshot_records_staged",
13614                SqlScalarType::UInt64.nullable(true),
13615            )
13616            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13617            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13618            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13619            .with_key(vec![0, 1])
13620            .finish(),
13621        column_comments: BTreeMap::from_iter([
13622            (
13623                "id",
13624                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13625            ),
13626            (
13627                "replica_id",
13628                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13629            ),
13630            (
13631                "messages_received",
13632                "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.",
13633            ),
13634            (
13635                "bytes_received",
13636                "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.",
13637            ),
13638            (
13639                "updates_staged",
13640                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13641            ),
13642            (
13643                "updates_committed",
13644                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13645            ),
13646            (
13647                "records_indexed",
13648                "The number of individual records indexed in the source envelope state.",
13649            ),
13650            (
13651                "bytes_indexed",
13652                "The number of bytes stored in the source's internal index, if any.",
13653            ),
13654            (
13655                "rehydration_latency",
13656                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13657            ),
13658            (
13659                "snapshot_records_known",
13660                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13661            ),
13662            (
13663                "snapshot_records_staged",
13664                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13665            ),
13666            (
13667                "snapshot_committed",
13668                "Whether the source has committed the initial snapshot for a source.",
13669            ),
13670            (
13671                "offset_known",
13672                "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.",
13673            ),
13674            (
13675                "offset_committed",
13676                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13677            ),
13678        ]),
13679        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13680        access: vec![PUBLIC_SELECT],
13681    }
13682});
13683
13684pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13685    name: "mz_source_statistics_ind",
13686    schema: MZ_INTERNAL_SCHEMA,
13687    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13688    sql: "IN CLUSTER mz_catalog_server
13689ON mz_internal.mz_source_statistics (id, replica_id)",
13690    is_retained_metrics_object: false,
13691};
13692
13693pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13694    name: "mz_sink_statistics",
13695    schema: MZ_INTERNAL_SCHEMA,
13696    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13697    desc: RelationDesc::builder()
13698        .with_column("id", SqlScalarType::String.nullable(false))
13699        .with_column("replica_id", SqlScalarType::String.nullable(true))
13700        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
13701        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
13702        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
13703        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
13704        .with_key(vec![0, 1])
13705        .finish(),
13706    column_comments: BTreeMap::from_iter([
13707        (
13708            "id",
13709            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
13710        ),
13711        (
13712            "replica_id",
13713            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13714        ),
13715        (
13716            "messages_staged",
13717            "The number of messages staged but possibly not committed to the sink.",
13718        ),
13719        (
13720            "messages_committed",
13721            "The number of messages committed to the sink.",
13722        ),
13723        (
13724            "bytes_staged",
13725            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13726        ),
13727        (
13728            "bytes_committed",
13729            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13730        ),
13731    ]),
13732    sql: "
13733SELECT
13734    id,
13735    replica_id,
13736    SUM(messages_staged)::uint8 AS messages_staged,
13737    SUM(messages_committed)::uint8 AS messages_committed,
13738    SUM(bytes_staged)::uint8 AS bytes_staged,
13739    SUM(bytes_committed)::uint8 AS bytes_committed
13740FROM mz_internal.mz_sink_statistics_raw
13741GROUP BY id, replica_id",
13742    access: vec![PUBLIC_SELECT],
13743});
13744
13745pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13746    name: "mz_sink_statistics_ind",
13747    schema: MZ_INTERNAL_SCHEMA,
13748    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13749    sql: "IN CLUSTER mz_catalog_server
13750ON mz_internal.mz_sink_statistics (id, replica_id)",
13751    is_retained_metrics_object: true,
13752};
13753
13754pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13755    name: "mz_cluster_replicas_ind",
13756    schema: MZ_CATALOG_SCHEMA,
13757    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13758    sql: "IN CLUSTER mz_catalog_server
13759ON mz_catalog.mz_cluster_replicas (id)",
13760    is_retained_metrics_object: true,
13761};
13762
13763pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13764    name: "mz_cluster_replica_sizes_ind",
13765    schema: MZ_CATALOG_SCHEMA,
13766    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13767    sql: "IN CLUSTER mz_catalog_server
13768ON mz_catalog.mz_cluster_replica_sizes (size)",
13769    is_retained_metrics_object: true,
13770};
13771
13772pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13773    name: "mz_cluster_replica_statuses_ind",
13774    schema: MZ_INTERNAL_SCHEMA,
13775    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13776    sql: "IN CLUSTER mz_catalog_server
13777ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13778    is_retained_metrics_object: false,
13779};
13780
13781pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13782    name: "mz_cluster_replica_status_history_ind",
13783    schema: MZ_INTERNAL_SCHEMA,
13784    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13785    sql: "IN CLUSTER mz_catalog_server
13786ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13787    is_retained_metrics_object: false,
13788};
13789
13790pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13791    name: "mz_cluster_replica_metrics_ind",
13792    schema: MZ_INTERNAL_SCHEMA,
13793    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13794    sql: "IN CLUSTER mz_catalog_server
13795ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13796    is_retained_metrics_object: false,
13797};
13798
13799pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13800    name: "mz_cluster_replica_metrics_history_ind",
13801    schema: MZ_INTERNAL_SCHEMA,
13802    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13803    sql: "IN CLUSTER mz_catalog_server
13804ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13805    is_retained_metrics_object: false,
13806};
13807
13808pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13809    name: "mz_cluster_replica_history_ind",
13810    schema: MZ_INTERNAL_SCHEMA,
13811    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13812    sql: "IN CLUSTER mz_catalog_server
13813ON mz_internal.mz_cluster_replica_history (dropped_at)",
13814    is_retained_metrics_object: true,
13815};
13816
13817pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13818    name: "mz_cluster_replica_name_history_ind",
13819    schema: MZ_INTERNAL_SCHEMA,
13820    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13821    sql: "IN CLUSTER mz_catalog_server
13822ON mz_internal.mz_cluster_replica_name_history (id)",
13823    is_retained_metrics_object: false,
13824};
13825
13826pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13827    name: "mz_object_lifetimes_ind",
13828    schema: MZ_INTERNAL_SCHEMA,
13829    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13830    sql: "IN CLUSTER mz_catalog_server
13831ON mz_internal.mz_object_lifetimes (id)",
13832    is_retained_metrics_object: false,
13833};
13834
13835pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13836    name: "mz_object_history_ind",
13837    schema: MZ_INTERNAL_SCHEMA,
13838    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13839    sql: "IN CLUSTER mz_catalog_server
13840ON mz_internal.mz_object_history (id)",
13841    is_retained_metrics_object: false,
13842};
13843
13844pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13845    name: "mz_object_dependencies_ind",
13846    schema: MZ_INTERNAL_SCHEMA,
13847    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
13848    sql: "IN CLUSTER mz_catalog_server
13849ON mz_internal.mz_object_dependencies (object_id)",
13850    is_retained_metrics_object: true,
13851};
13852
13853pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13854    name: "mz_compute_dependencies_ind",
13855    schema: MZ_INTERNAL_SCHEMA,
13856    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
13857    sql: "IN CLUSTER mz_catalog_server
13858ON mz_internal.mz_compute_dependencies (dependency_id)",
13859    is_retained_metrics_object: false,
13860};
13861
13862pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13863    name: "mz_object_transitive_dependencies_ind",
13864    schema: MZ_INTERNAL_SCHEMA,
13865    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
13866    sql: "IN CLUSTER mz_catalog_server
13867ON mz_internal.mz_object_transitive_dependencies (object_id)",
13868    is_retained_metrics_object: false,
13869};
13870
13871pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
13872    name: "mz_frontiers_ind",
13873    schema: MZ_INTERNAL_SCHEMA,
13874    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
13875    sql: "IN CLUSTER mz_catalog_server
13876ON mz_internal.mz_frontiers (object_id)",
13877    is_retained_metrics_object: false,
13878};
13879
13880pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13881    name: "mz_wallclock_global_lag_recent_history_ind",
13882    schema: MZ_INTERNAL_SCHEMA,
13883    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
13884    sql: "IN CLUSTER mz_catalog_server
13885ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
13886    is_retained_metrics_object: false,
13887};
13888
13889pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
13890    name: "mz_recent_activity_log_thinned_ind",
13891    schema: MZ_INTERNAL_SCHEMA,
13892    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
13893    sql: "IN CLUSTER mz_catalog_server
13894-- sql_hash because we plan to join
13895-- this against mz_internal.mz_sql_text
13896ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
13897    is_retained_metrics_object: false,
13898};
13899
13900pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13901    name: "mz_kafka_sources_ind",
13902    schema: MZ_CATALOG_SCHEMA,
13903    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
13904    sql: "IN CLUSTER mz_catalog_server
13905ON mz_catalog.mz_kafka_sources (id)",
13906    is_retained_metrics_object: true,
13907};
13908
13909pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13910    name: "mz_webhook_sources_ind",
13911    schema: MZ_INTERNAL_SCHEMA,
13912    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
13913    sql: "IN CLUSTER mz_catalog_server
13914ON mz_internal.mz_webhook_sources (id)",
13915    is_retained_metrics_object: true,
13916};
13917
13918pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
13919    name: "mz_comments_ind",
13920    schema: MZ_INTERNAL_SCHEMA,
13921    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
13922    sql: "IN CLUSTER mz_catalog_server
13923ON mz_internal.mz_comments (id)",
13924    is_retained_metrics_object: true,
13925};
13926
13927pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
13928    name: "mz_analytics",
13929    schema: MZ_INTERNAL_SCHEMA,
13930    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
13931    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
13932    access: &[MzAclItem {
13933        grantee: MZ_SYSTEM_ROLE_ID,
13934        grantor: MZ_ANALYTICS_ROLE_ID,
13935        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
13936    }],
13937    owner_id: &MZ_ANALYTICS_ROLE_ID,
13938    runtime_alterable: true,
13939};
13940
13941pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
13942    id: MZ_SYSTEM_ROLE_ID,
13943    name: SYSTEM_USER_NAME,
13944    oid: oid::ROLE_MZ_SYSTEM_OID,
13945    attributes: RoleAttributesRaw::new().with_all(),
13946};
13947
13948pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
13949    id: MZ_SUPPORT_ROLE_ID,
13950    name: SUPPORT_USER_NAME,
13951    oid: oid::ROLE_MZ_SUPPORT_OID,
13952    attributes: RoleAttributesRaw::new(),
13953};
13954
13955pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
13956    id: MZ_ANALYTICS_ROLE_ID,
13957    name: ANALYTICS_USER_NAME,
13958    oid: oid::ROLE_MZ_ANALYTICS_OID,
13959    attributes: RoleAttributesRaw::new(),
13960};
13961
13962/// This role can `SELECT` from various query history objects,
13963/// e.g. `mz_prepared_statement_history`.
13964pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
13965    id: MZ_MONITOR_ROLE_ID,
13966    name: "mz_monitor",
13967    oid: oid::ROLE_MZ_MONITOR_OID,
13968    attributes: RoleAttributesRaw::new(),
13969};
13970
13971/// This role is like [`MZ_MONITOR_ROLE`], but can only query
13972/// the redacted versions of the objects.
13973pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
13974    id: MZ_MONITOR_REDACTED_ROLE_ID,
13975    name: "mz_monitor_redacted",
13976    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
13977    attributes: RoleAttributesRaw::new(),
13978};
13979
13980pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
13981    name: SYSTEM_USER_NAME,
13982    owner_id: &MZ_SYSTEM_ROLE_ID,
13983    privileges: &[
13984        MzAclItem {
13985            grantee: MZ_SUPPORT_ROLE_ID,
13986            grantor: MZ_SYSTEM_ROLE_ID,
13987            acl_mode: AclMode::USAGE,
13988        },
13989        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13990    ],
13991};
13992
13993pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13994    name: BUILTIN_CLUSTER_REPLICA_NAME,
13995    cluster_name: MZ_SYSTEM_CLUSTER.name,
13996};
13997
13998pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
13999    name: "mz_catalog_server",
14000    owner_id: &MZ_SYSTEM_ROLE_ID,
14001    privileges: &[
14002        MzAclItem {
14003            grantee: RoleId::Public,
14004            grantor: MZ_SYSTEM_ROLE_ID,
14005            acl_mode: AclMode::USAGE,
14006        },
14007        MzAclItem {
14008            grantee: MZ_SUPPORT_ROLE_ID,
14009            grantor: MZ_SYSTEM_ROLE_ID,
14010            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
14011        },
14012        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
14013    ],
14014};
14015
14016pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
14017    name: BUILTIN_CLUSTER_REPLICA_NAME,
14018    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
14019};
14020
14021pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
14022    name: "mz_probe",
14023    owner_id: &MZ_SYSTEM_ROLE_ID,
14024    privileges: &[
14025        MzAclItem {
14026            grantee: MZ_SUPPORT_ROLE_ID,
14027            grantor: MZ_SYSTEM_ROLE_ID,
14028            acl_mode: AclMode::USAGE,
14029        },
14030        MzAclItem {
14031            grantee: MZ_MONITOR_ROLE_ID,
14032            grantor: MZ_SYSTEM_ROLE_ID,
14033            acl_mode: AclMode::USAGE,
14034        },
14035        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
14036    ],
14037};
14038pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
14039    name: BUILTIN_CLUSTER_REPLICA_NAME,
14040    cluster_name: MZ_PROBE_CLUSTER.name,
14041};
14042
14043pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
14044    name: "mz_support",
14045    owner_id: &MZ_SUPPORT_ROLE_ID,
14046    privileges: &[
14047        MzAclItem {
14048            grantee: MZ_SYSTEM_ROLE_ID,
14049            grantor: MZ_SUPPORT_ROLE_ID,
14050            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
14051        },
14052        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
14053    ],
14054};
14055
14056pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
14057    name: "mz_analytics",
14058    owner_id: &MZ_ANALYTICS_ROLE_ID,
14059    privileges: &[
14060        MzAclItem {
14061            grantee: MZ_SYSTEM_ROLE_ID,
14062            grantor: MZ_ANALYTICS_ROLE_ID,
14063            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
14064        },
14065        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
14066    ],
14067};
14068
14069/// List of all builtin objects sorted topologically by dependency.
14070pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
14071    let mut builtins = vec![
14072        Builtin::Type(&TYPE_ANY),
14073        Builtin::Type(&TYPE_ANYARRAY),
14074        Builtin::Type(&TYPE_ANYELEMENT),
14075        Builtin::Type(&TYPE_ANYNONARRAY),
14076        Builtin::Type(&TYPE_ANYRANGE),
14077        Builtin::Type(&TYPE_BOOL),
14078        Builtin::Type(&TYPE_BOOL_ARRAY),
14079        Builtin::Type(&TYPE_BYTEA),
14080        Builtin::Type(&TYPE_BYTEA_ARRAY),
14081        Builtin::Type(&TYPE_BPCHAR),
14082        Builtin::Type(&TYPE_BPCHAR_ARRAY),
14083        Builtin::Type(&TYPE_CHAR),
14084        Builtin::Type(&TYPE_CHAR_ARRAY),
14085        Builtin::Type(&TYPE_DATE),
14086        Builtin::Type(&TYPE_DATE_ARRAY),
14087        Builtin::Type(&TYPE_FLOAT4),
14088        Builtin::Type(&TYPE_FLOAT4_ARRAY),
14089        Builtin::Type(&TYPE_FLOAT8),
14090        Builtin::Type(&TYPE_FLOAT8_ARRAY),
14091        Builtin::Type(&TYPE_INT4),
14092        Builtin::Type(&TYPE_INT4_ARRAY),
14093        Builtin::Type(&TYPE_INT8),
14094        Builtin::Type(&TYPE_INT8_ARRAY),
14095        Builtin::Type(&TYPE_INTERVAL),
14096        Builtin::Type(&TYPE_INTERVAL_ARRAY),
14097        Builtin::Type(&TYPE_JSONB),
14098        Builtin::Type(&TYPE_JSONB_ARRAY),
14099        Builtin::Type(&TYPE_LIST),
14100        Builtin::Type(&TYPE_MAP),
14101        Builtin::Type(&TYPE_NAME),
14102        Builtin::Type(&TYPE_NAME_ARRAY),
14103        Builtin::Type(&TYPE_NUMERIC),
14104        Builtin::Type(&TYPE_NUMERIC_ARRAY),
14105        Builtin::Type(&TYPE_OID),
14106        Builtin::Type(&TYPE_OID_ARRAY),
14107        Builtin::Type(&TYPE_RECORD),
14108        Builtin::Type(&TYPE_RECORD_ARRAY),
14109        Builtin::Type(&TYPE_REGCLASS),
14110        Builtin::Type(&TYPE_REGCLASS_ARRAY),
14111        Builtin::Type(&TYPE_REGPROC),
14112        Builtin::Type(&TYPE_REGPROC_ARRAY),
14113        Builtin::Type(&TYPE_REGTYPE),
14114        Builtin::Type(&TYPE_REGTYPE_ARRAY),
14115        Builtin::Type(&TYPE_INT2),
14116        Builtin::Type(&TYPE_INT2_ARRAY),
14117        Builtin::Type(&TYPE_TEXT),
14118        Builtin::Type(&TYPE_TEXT_ARRAY),
14119        Builtin::Type(&TYPE_TIME),
14120        Builtin::Type(&TYPE_TIME_ARRAY),
14121        Builtin::Type(&TYPE_TIMESTAMP),
14122        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
14123        Builtin::Type(&TYPE_TIMESTAMPTZ),
14124        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
14125        Builtin::Type(&TYPE_UUID),
14126        Builtin::Type(&TYPE_UUID_ARRAY),
14127        Builtin::Type(&TYPE_VARCHAR),
14128        Builtin::Type(&TYPE_VARCHAR_ARRAY),
14129        Builtin::Type(&TYPE_INT2_VECTOR),
14130        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
14131        Builtin::Type(&TYPE_ANYCOMPATIBLE),
14132        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
14133        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
14134        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
14135        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
14136        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
14137        Builtin::Type(&TYPE_UINT2),
14138        Builtin::Type(&TYPE_UINT2_ARRAY),
14139        Builtin::Type(&TYPE_UINT4),
14140        Builtin::Type(&TYPE_UINT4_ARRAY),
14141        Builtin::Type(&TYPE_UINT8),
14142        Builtin::Type(&TYPE_UINT8_ARRAY),
14143        Builtin::Type(&TYPE_MZ_TIMESTAMP),
14144        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
14145        Builtin::Type(&TYPE_INT4_RANGE),
14146        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
14147        Builtin::Type(&TYPE_INT8_RANGE),
14148        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
14149        Builtin::Type(&TYPE_DATE_RANGE),
14150        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
14151        Builtin::Type(&TYPE_NUM_RANGE),
14152        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
14153        Builtin::Type(&TYPE_TS_RANGE),
14154        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
14155        Builtin::Type(&TYPE_TSTZ_RANGE),
14156        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
14157        Builtin::Type(&TYPE_MZ_ACL_ITEM),
14158        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
14159        Builtin::Type(&TYPE_ACL_ITEM),
14160        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
14161        Builtin::Type(&TYPE_INTERNAL),
14162    ];
14163    for (schema, funcs) in &[
14164        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
14165        (
14166            INFORMATION_SCHEMA,
14167            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
14168        ),
14169        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
14170        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
14171        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
14172    ] {
14173        for (name, func) in funcs.iter() {
14174            builtins.push(Builtin::Func(BuiltinFunc {
14175                name,
14176                schema,
14177                inner: func,
14178            }));
14179        }
14180    }
14181    builtins.append(&mut vec![
14182        Builtin::Source(&MZ_CATALOG_RAW),
14183        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
14184        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
14185        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
14186        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
14187        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
14188        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
14189        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
14190        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
14191        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
14192        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
14193        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
14194        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
14195        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
14196        Builtin::Log(&MZ_CLUSTER_PROMETHEUS_METRICS),
14197        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
14198        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
14199        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
14200        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
14201        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
14202        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
14203        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
14204        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
14205        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
14206        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
14207        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
14208        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
14209        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
14210        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
14211        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
14212        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
14213        Builtin::Log(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
14214        Builtin::Table(&MZ_KAFKA_SINKS),
14215        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
14216        Builtin::Table(&MZ_KAFKA_SOURCES),
14217        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
14218        Builtin::Table(&MZ_ICEBERG_SINKS),
14219        Builtin::MaterializedView(&MZ_DATABASES),
14220        Builtin::MaterializedView(&MZ_SCHEMAS),
14221        Builtin::Table(&MZ_COLUMNS),
14222        Builtin::Table(&MZ_INDEXES),
14223        Builtin::Table(&MZ_INDEX_COLUMNS),
14224        Builtin::Table(&MZ_TABLES),
14225        Builtin::Table(&MZ_SOURCES),
14226        Builtin::Table(&MZ_SOURCE_REFERENCES),
14227        Builtin::Table(&MZ_POSTGRES_SOURCES),
14228        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
14229        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
14230        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
14231        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
14232        Builtin::Table(&MZ_SINKS),
14233        Builtin::Table(&MZ_VIEWS),
14234        Builtin::Table(&MZ_MATERIALIZED_VIEWS),
14235        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
14236        Builtin::Table(&MZ_TYPES),
14237        Builtin::Table(&MZ_TYPE_PG_METADATA),
14238        Builtin::Table(&MZ_ARRAY_TYPES),
14239        Builtin::Table(&MZ_BASE_TYPES),
14240        Builtin::Table(&MZ_LIST_TYPES),
14241        Builtin::Table(&MZ_MAP_TYPES),
14242        Builtin::Table(&MZ_ROLES),
14243        Builtin::Table(&MZ_ROLE_AUTH),
14244        Builtin::MaterializedView(&MZ_ROLE_MEMBERS),
14245        Builtin::Table(&MZ_ROLE_PARAMETERS),
14246        Builtin::Table(&MZ_PSEUDO_TYPES),
14247        Builtin::Table(&MZ_FUNCTIONS),
14248        Builtin::Table(&MZ_OPERATORS),
14249        Builtin::Table(&MZ_AGGREGATES),
14250        Builtin::Table(&MZ_CLUSTERS),
14251        Builtin::MaterializedView(&MZ_CLUSTER_WORKLOAD_CLASSES),
14252        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
14253        Builtin::Table(&MZ_SECRETS),
14254        Builtin::Table(&MZ_CONNECTIONS),
14255        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
14256        Builtin::Table(&MZ_CLUSTER_REPLICAS),
14257        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
14258        Builtin::View(&MZ_CLUSTER_REPLICA_METRICS),
14259        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
14260        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
14261        Builtin::View(&MZ_CLUSTER_REPLICA_STATUSES),
14262        Builtin::MaterializedView(&MZ_INTERNAL_CLUSTER_REPLICAS),
14263        Builtin::MaterializedView(&MZ_PENDING_CLUSTER_REPLICAS),
14264        Builtin::Table(&MZ_AUDIT_EVENTS),
14265        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
14266        Builtin::Table(&MZ_EGRESS_IPS),
14267        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
14268        Builtin::Table(&MZ_AWS_CONNECTIONS),
14269        Builtin::Table(&MZ_SUBSCRIPTIONS),
14270        Builtin::Table(&MZ_SESSIONS),
14271        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
14272        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
14273        Builtin::Table(&MZ_COMMENTS),
14274        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
14275        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
14276        Builtin::Table(&MZ_CONTINUAL_TASKS),
14277        Builtin::MaterializedView(&MZ_NETWORK_POLICIES),
14278        Builtin::MaterializedView(&MZ_NETWORK_POLICY_RULES),
14279        Builtin::Table(&MZ_LICENSE_KEYS),
14280        Builtin::Table(&MZ_REPLACEMENTS),
14281        Builtin::View(&MZ_RELATIONS),
14282        Builtin::View(&MZ_OBJECT_OID_ALIAS),
14283        Builtin::View(&MZ_OBJECTS),
14284        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
14285        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
14286        Builtin::View(&MZ_OBJECT_HISTORY),
14287        Builtin::View(&MZ_OBJECT_LIFETIMES),
14288        Builtin::Table(&MZ_OBJECT_GLOBAL_IDS),
14289        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
14290        Builtin::View(&MZ_ARRANGEMENT_SHARING),
14291        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
14292        Builtin::View(&MZ_ARRANGEMENT_SIZES),
14293        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
14294        Builtin::View(&MZ_DATAFLOWS),
14295        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
14296        Builtin::View(&MZ_DATAFLOW_CHANNELS),
14297        Builtin::View(&MZ_DATAFLOW_OPERATORS),
14298        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
14299        Builtin::View(&MZ_MAPPABLE_OBJECTS),
14300        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
14301        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
14302        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
14303        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
14304        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
14305        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
14306        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
14307        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
14308        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
14309        Builtin::View(&MZ_COMPUTE_EXPORTS),
14310        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
14311        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
14312        Builtin::View(&MZ_COMPUTE_FRONTIERS),
14313        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
14314        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
14315        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
14316        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
14317        Builtin::View(&MZ_MESSAGE_COUNTS),
14318        Builtin::View(&MZ_ACTIVE_PEEKS),
14319        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
14320        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
14321        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
14322        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
14323        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
14324        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
14325        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
14326        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
14327        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
14328        Builtin::View(&MZ_SCHEDULING_ELAPSED),
14329        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
14330        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
14331        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
14332        Builtin::View(&MZ_SHOW_COLUMNS),
14333        Builtin::View(&MZ_SHOW_CLUSTERS),
14334        Builtin::View(&MZ_SHOW_SECRETS),
14335        Builtin::View(&MZ_SHOW_DATABASES),
14336        Builtin::View(&MZ_SHOW_SCHEMAS),
14337        Builtin::View(&MZ_SHOW_TABLES),
14338        Builtin::View(&MZ_SHOW_VIEWS),
14339        Builtin::View(&MZ_SHOW_TYPES),
14340        Builtin::View(&MZ_SHOW_ROLES),
14341        Builtin::View(&MZ_SHOW_CONNECTIONS),
14342        Builtin::View(&MZ_SHOW_SOURCES),
14343        Builtin::View(&MZ_SHOW_SINKS),
14344        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
14345        Builtin::View(&MZ_SHOW_INDEXES),
14346        Builtin::View(&MZ_SHOW_CONTINUAL_TASKS),
14347        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
14348        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
14349        Builtin::View(&MZ_TIMEZONE_NAMES),
14350        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
14351        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
14352        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
14353        Builtin::View(&PG_NAMESPACE),
14354        Builtin::View(&PG_CLASS_ALL_DATABASES),
14355        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
14356        Builtin::View(&PG_CLASS),
14357        Builtin::View(&PG_DEPEND),
14358        Builtin::View(&PG_DATABASE),
14359        Builtin::View(&PG_INDEX),
14360        Builtin::View(&PG_TYPE_ALL_DATABASES),
14361        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
14362        Builtin::View(&PG_TYPE),
14363        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
14364        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
14365        Builtin::View(&PG_DESCRIPTION),
14366        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
14367        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
14368        Builtin::View(&PG_ATTRIBUTE),
14369        Builtin::View(&PG_PROC),
14370        Builtin::View(&PG_OPERATOR),
14371        Builtin::View(&PG_RANGE),
14372        Builtin::View(&PG_ENUM),
14373        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
14374        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
14375        Builtin::View(&PG_ATTRDEF),
14376        Builtin::View(&PG_SETTINGS),
14377        Builtin::View(&PG_AUTH_MEMBERS),
14378        Builtin::View(&PG_CONSTRAINT),
14379        Builtin::View(&PG_TABLES),
14380        Builtin::View(&PG_TABLESPACE),
14381        Builtin::View(&PG_ACCESS_METHODS),
14382        Builtin::View(&PG_LOCKS),
14383        Builtin::View(&PG_AUTHID_CORE),
14384        Builtin::Index(&PG_AUTHID_CORE_IND),
14385        Builtin::View(&PG_AUTHID),
14386        Builtin::View(&PG_ROLES),
14387        Builtin::View(&PG_USER),
14388        Builtin::View(&PG_VIEWS),
14389        Builtin::View(&PG_MATVIEWS),
14390        Builtin::View(&PG_COLLATION),
14391        Builtin::View(&PG_POLICY),
14392        Builtin::View(&PG_INHERITS),
14393        Builtin::View(&PG_AGGREGATE),
14394        Builtin::View(&PG_TRIGGER),
14395        Builtin::View(&PG_REWRITE),
14396        Builtin::View(&PG_EXTENSION),
14397        Builtin::View(&PG_EVENT_TRIGGER),
14398        Builtin::View(&PG_LANGUAGE),
14399        Builtin::View(&PG_SHDESCRIPTION),
14400        Builtin::View(&PG_INDEXES),
14401        Builtin::View(&PG_TIMEZONE_ABBREVS),
14402        Builtin::View(&PG_TIMEZONE_NAMES),
14403        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
14404        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
14405        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
14406        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
14407        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
14408        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
14409        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
14410        Builtin::View(&INFORMATION_SCHEMA_TABLES),
14411        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
14412        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
14413        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
14414        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
14415        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
14416        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
14417        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
14418        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
14419        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
14420        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
14421        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
14422        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
14423        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
14424        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
14425        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
14426        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
14427        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
14428        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
14429        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
14430        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
14431        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
14432        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
14433        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
14434        Builtin::View(&MZ_SINK_STATUSES),
14435        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
14436        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
14437        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
14438        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
14439        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
14440        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
14441        Builtin::Source(&MZ_SESSION_HISTORY),
14442        Builtin::Source(&MZ_SQL_TEXT),
14443        Builtin::View(&MZ_SQL_TEXT_REDACTED),
14444        Builtin::View(&MZ_RECENT_SQL_TEXT),
14445        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
14446        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
14447        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
14448        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
14449        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
14450        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
14451        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
14452        Builtin::View(&MZ_SOURCE_STATUSES),
14453        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
14454        Builtin::Source(&MZ_STORAGE_SHARDS),
14455        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
14456        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
14457        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
14458        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
14459        Builtin::View(&MZ_SOURCE_STATISTICS),
14460        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
14461        Builtin::View(&MZ_SINK_STATISTICS),
14462        Builtin::Index(&MZ_SINK_STATISTICS_IND),
14463        Builtin::View(&MZ_STORAGE_USAGE),
14464        Builtin::Source(&MZ_FRONTIERS),
14465        Builtin::View(&MZ_GLOBAL_FRONTIERS),
14466        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
14467        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
14468        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
14469        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
14470        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
14471        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
14472        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
14473        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
14474        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
14475        Builtin::View(&MZ_MATERIALIZATION_LAG),
14476        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
14477        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
14478        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
14479        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
14480        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
14481        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
14482        Builtin::View(&MZ_LIR_MAPPING),
14483        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
14484        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
14485        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
14486        Builtin::View(&MZ_HYDRATION_STATUSES),
14487        Builtin::Index(&MZ_HYDRATION_STATUSES_IND),
14488        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
14489        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
14490        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
14491        Builtin::Index(&MZ_SHOW_DATABASES_IND),
14492        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
14493        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
14494        Builtin::Index(&MZ_SHOW_TABLES_IND),
14495        Builtin::Index(&MZ_SHOW_SOURCES_IND),
14496        Builtin::Index(&MZ_SHOW_VIEWS_IND),
14497        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
14498        Builtin::Index(&MZ_SHOW_SINKS_IND),
14499        Builtin::Index(&MZ_SHOW_TYPES_IND),
14500        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
14501        Builtin::Index(&MZ_SHOW_INDEXES_IND),
14502        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
14503        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
14504        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
14505        Builtin::Index(&MZ_SHOW_SECRETS_IND),
14506        Builtin::Index(&MZ_SHOW_ROLES_IND),
14507        Builtin::Index(&MZ_CLUSTERS_IND),
14508        Builtin::Index(&MZ_INDEXES_IND),
14509        Builtin::Index(&MZ_ROLES_IND),
14510        Builtin::Index(&MZ_SOURCES_IND),
14511        Builtin::Index(&MZ_SINKS_IND),
14512        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
14513        Builtin::Index(&MZ_CONTINUAL_TASKS_IND),
14514        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
14515        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
14516        Builtin::Index(&MZ_SINK_STATUSES_IND),
14517        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
14518        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
14519        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
14520        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
14521        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
14522        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
14523        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
14524        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
14525        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
14526        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
14527        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
14528        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
14529        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
14530        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
14531        Builtin::Index(&MZ_FRONTIERS_IND),
14532        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
14533        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
14534        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
14535        Builtin::Index(&MZ_COMMENTS_IND),
14536        Builtin::Index(&MZ_DATABASES_IND),
14537        Builtin::Index(&MZ_SCHEMAS_IND),
14538        Builtin::Index(&MZ_CONNECTIONS_IND),
14539        Builtin::Index(&MZ_TABLES_IND),
14540        Builtin::Index(&MZ_TYPES_IND),
14541        Builtin::Index(&MZ_OBJECTS_IND),
14542        Builtin::Index(&MZ_COLUMNS_IND),
14543        Builtin::Index(&MZ_SECRETS_IND),
14544        Builtin::Index(&MZ_VIEWS_IND),
14545        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
14546        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
14547        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
14548        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
14549        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
14550        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
14551        Builtin::Connection(&MZ_ANALYTICS),
14552        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT),
14553        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT),
14554        Builtin::ContinualTask(&MZ_WALLCLOCK_LAG_HISTORY_CT),
14555        Builtin::View(&MZ_INDEX_ADVICE),
14556        Builtin::View(&MZ_MCP_DATA_PRODUCTS),
14557        Builtin::View(&MZ_MCP_DATA_PRODUCT_DETAILS),
14558    ]);
14559
14560    builtins.extend(notice::builtins());
14561
14562    builtins
14563});
14564pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
14565    &MZ_SYSTEM_ROLE,
14566    &MZ_SUPPORT_ROLE,
14567    &MZ_ANALYTICS_ROLE,
14568    &MZ_MONITOR_ROLE,
14569    &MZ_MONITOR_REDACTED,
14570];
14571pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
14572    &MZ_SYSTEM_CLUSTER,
14573    &MZ_CATALOG_SERVER_CLUSTER,
14574    &MZ_PROBE_CLUSTER,
14575    &MZ_SUPPORT_CLUSTER,
14576    &MZ_ANALYTICS_CLUSTER,
14577];
14578pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
14579    &MZ_SYSTEM_CLUSTER_REPLICA,
14580    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14581    &MZ_PROBE_CLUSTER_REPLICA,
14582];
14583
14584#[allow(non_snake_case)]
14585pub mod BUILTINS {
14586    use mz_sql::catalog::BuiltinsConfig;
14587
14588    use super::*;
14589
14590    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14591        BUILTINS_STATIC.iter().filter_map(|b| match b {
14592            Builtin::Log(log) => Some(*log),
14593            _ => None,
14594        })
14595    }
14596
14597    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14598        BUILTINS_STATIC.iter().filter_map(|b| match b {
14599            Builtin::Type(typ) => Some(*typ),
14600            _ => None,
14601        })
14602    }
14603
14604    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14605        BUILTINS_STATIC.iter().filter_map(|b| match b {
14606            Builtin::View(view) => Some(*view),
14607            _ => None,
14608        })
14609    }
14610
14611    pub fn materialized_views() -> impl Iterator<Item = &'static BuiltinMaterializedView> {
14612        BUILTINS_STATIC.iter().filter_map(|b| match b {
14613            Builtin::MaterializedView(mv) => Some(*mv),
14614            _ => None,
14615        })
14616    }
14617
14618    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14619        BUILTINS_STATIC.iter().filter_map(|b| match b {
14620            Builtin::Func(func) => Some(func),
14621            _ => None,
14622        })
14623    }
14624
14625    pub fn iter(cfg: &BuiltinsConfig) -> impl Iterator<Item = &'static Builtin<NameReference>> {
14626        let include_continual_tasks = cfg.include_continual_tasks;
14627        BUILTINS_STATIC.iter().filter(move |x| match x {
14628            Builtin::ContinualTask(_) if !include_continual_tasks => false,
14629            _ => true,
14630        })
14631    }
14632}
14633
14634pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14635    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14636/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14637/// the builtin itself.
14638pub static BUILTIN_LOOKUP: LazyLock<
14639    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14640> = LazyLock::new(|| {
14641    // BUILTIN_LOOKUP is only ever used for lookups by key, it's not iterated,
14642    // so it's safe to include all of them, regardless of BuiltinConfig. We
14643    // enforce this statically by using the mz_ore HashMap which disallows
14644    // iteration.
14645    BUILTINS_STATIC
14646        .iter()
14647        .enumerate()
14648        .map(|(idx, builtin)| {
14649            (
14650                SystemObjectDescription {
14651                    schema_name: builtin.schema().to_string(),
14652                    object_type: builtin.catalog_item_type(),
14653                    object_name: builtin.name().to_string(),
14654                },
14655                (idx, builtin),
14656            )
14657        })
14658        .collect()
14659});
14660
14661#[mz_ore::test]
14662#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14663fn test_builtin_type_schema() {
14664    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14665
14666    for typ in BUILTINS::types() {
14667        if typ.oid < FIRST_MATERIALIZE_OID {
14668            assert_eq!(
14669                typ.schema, PG_CATALOG_SCHEMA,
14670                "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14671            );
14672        } else {
14673            // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the mz_catalog
14674            // schema.
14675            assert_eq!(
14676                typ.schema, MZ_CATALOG_SCHEMA,
14677                "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14678            );
14679        }
14680    }
14681}