mz_catalog/
builtin.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Built-in catalog items.
11//!
12//! Builtins exist in the `mz_catalog` ambient schema. They are automatically
13//! installed into the catalog when it is opened. Their definitions are not
14//! persisted in the catalog, but hardcoded in this module. This makes it easy
15//! to add new builtins, or change the definition of existing builtins, in new
16//! versions of Materialize.
17//!
18//! Builtin's names, columns, and types are part of the stable API of
19//! Materialize. Be careful to maintain backwards compatibility when changing
20//! definitions of existing builtins!
21//!
22//! More information about builtin system tables and types can be found in
23//! <https://materialize.com/docs/sql/system-catalog/>.
24
25pub mod notice;
26
27use std::collections::BTreeMap;
28use std::hash::Hash;
29use std::string::ToString;
30use std::sync::LazyLock;
31
32use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
33use mz_ore::collections::HashMap;
34use mz_pgrepr::oid;
35use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
36use mz_repr::adt::numeric::NumericMaxScale;
37use mz_repr::namespaces::{
38    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_INTROSPECTION_SCHEMA,
39    MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA,
40};
41use mz_repr::role_id::RoleId;
42use mz_repr::{RelationDesc, SqlRelationType, SqlScalarType};
43use mz_sql::catalog::RoleAttributesRaw;
44use mz_sql::catalog::{
45    CatalogItemType, CatalogType, CatalogTypeDetails, CatalogTypePgMetadata, NameReference,
46    ObjectType, SystemObjectType, TypeReference,
47};
48use mz_sql::rbac;
49use mz_sql::session::user::{
50    ANALYTICS_USER_NAME, MZ_ANALYTICS_ROLE_ID, MZ_MONITOR_REDACTED_ROLE_ID, MZ_MONITOR_ROLE_ID,
51    MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID, SUPPORT_USER_NAME, SYSTEM_USER_NAME,
52};
53use mz_storage_client::controller::IntrospectionType;
54use mz_storage_client::healthcheck::WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC;
55use mz_storage_client::healthcheck::{
56    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_PREPARED_STATEMENT_HISTORY_DESC,
57    MZ_SESSION_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC, MZ_SOURCE_STATUS_HISTORY_DESC,
58    MZ_SQL_TEXT_DESC, MZ_STATEMENT_EXECUTION_HISTORY_DESC, REPLICA_METRICS_HISTORY_DESC,
59    REPLICA_STATUS_HISTORY_DESC, WALLCLOCK_LAG_HISTORY_DESC,
60};
61use mz_storage_client::statistics::{MZ_SINK_STATISTICS_RAW_DESC, MZ_SOURCE_STATISTICS_RAW_DESC};
62use serde::Serialize;
63
64use crate::durable::objects::SystemObjectDescription;
65
66pub const BUILTIN_PREFIXES: &[&str] = &["mz_", "pg_", "external_"];
67const BUILTIN_CLUSTER_REPLICA_NAME: &str = "r1";
68
69/// A sentinel used in place of a fingerprint that indicates that a builtin
70/// object is runtime alterable. Runtime alterable objects don't have meaningful
71/// fingerprints because they may have been intentionally changed by the user
72/// after creation.
73// NOTE(benesch): ideally we'd use a fingerprint type that used a sum type
74// rather than a loosely typed string to represent the runtime alterable
75// state like so:
76//
77//     enum Fingerprint {
78//         SqlText(String),
79//         RuntimeAlterable,
80//     }
81//
82// However, that would entail a complicated migration for the existing system object
83// mapping collection stored on disk.
84pub const RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL: &str = "<RUNTIME-ALTERABLE>";
85
86#[derive(Debug)]
87pub enum Builtin<T: 'static + TypeReference> {
88    Log(&'static BuiltinLog),
89    Table(&'static BuiltinTable),
90    View(&'static BuiltinView),
91    Type(&'static BuiltinType<T>),
92    Func(BuiltinFunc),
93    Source(&'static BuiltinSource),
94    ContinualTask(&'static BuiltinContinualTask),
95    Index(&'static BuiltinIndex),
96    Connection(&'static BuiltinConnection),
97}
98
99impl<T: TypeReference> Builtin<T> {
100    pub fn name(&self) -> &'static str {
101        match self {
102            Builtin::Log(log) => log.name,
103            Builtin::Table(table) => table.name,
104            Builtin::View(view) => view.name,
105            Builtin::Type(typ) => typ.name,
106            Builtin::Func(func) => func.name,
107            Builtin::Source(coll) => coll.name,
108            Builtin::ContinualTask(ct) => ct.name,
109            Builtin::Index(index) => index.name,
110            Builtin::Connection(connection) => connection.name,
111        }
112    }
113
114    pub fn schema(&self) -> &'static str {
115        match self {
116            Builtin::Log(log) => log.schema,
117            Builtin::Table(table) => table.schema,
118            Builtin::View(view) => view.schema,
119            Builtin::Type(typ) => typ.schema,
120            Builtin::Func(func) => func.schema,
121            Builtin::Source(coll) => coll.schema,
122            Builtin::ContinualTask(ct) => ct.schema,
123            Builtin::Index(index) => index.schema,
124            Builtin::Connection(connection) => connection.schema,
125        }
126    }
127
128    pub fn catalog_item_type(&self) -> CatalogItemType {
129        match self {
130            Builtin::Log(_) => CatalogItemType::Source,
131            Builtin::Source(_) => CatalogItemType::Source,
132            Builtin::ContinualTask(_) => CatalogItemType::ContinualTask,
133            Builtin::Table(_) => CatalogItemType::Table,
134            Builtin::View(_) => CatalogItemType::View,
135            Builtin::Type(_) => CatalogItemType::Type,
136            Builtin::Func(_) => CatalogItemType::Func,
137            Builtin::Index(_) => CatalogItemType::Index,
138            Builtin::Connection(_) => CatalogItemType::Connection,
139        }
140    }
141
142    /// Whether the object can be altered at runtime by its owner.
143    pub fn runtime_alterable(&self) -> bool {
144        match self {
145            Builtin::Connection(c) => c.runtime_alterable,
146            _ => false,
147        }
148    }
149}
150
151#[derive(Clone, Debug, Hash, Serialize)]
152pub struct BuiltinLog {
153    pub variant: LogVariant,
154    pub name: &'static str,
155    pub schema: &'static str,
156    pub oid: u32,
157    /// ACL items to apply to the object
158    pub access: Vec<MzAclItem>,
159}
160
161#[derive(Hash, Debug, PartialEq, Eq)]
162pub struct BuiltinTable {
163    pub name: &'static str,
164    pub schema: &'static str,
165    pub oid: u32,
166    pub desc: RelationDesc,
167    pub column_comments: BTreeMap<&'static str, &'static str>,
168    /// Whether the table's retention policy is controlled by
169    /// the system variable `METRICS_RETENTION`
170    pub is_retained_metrics_object: bool,
171    /// ACL items to apply to the object
172    pub access: Vec<MzAclItem>,
173}
174
175#[derive(Clone, Debug, Hash, Serialize)]
176pub struct BuiltinSource {
177    pub name: &'static str,
178    pub schema: &'static str,
179    pub oid: u32,
180    pub desc: RelationDesc,
181    pub column_comments: BTreeMap<&'static str, &'static str>,
182    pub data_source: IntrospectionType,
183    /// Whether the source's retention policy is controlled by
184    /// the system variable `METRICS_RETENTION`
185    pub is_retained_metrics_object: bool,
186    /// ACL items to apply to the object
187    pub access: Vec<MzAclItem>,
188}
189
190#[derive(Hash, Debug, PartialEq, Eq)]
191pub struct BuiltinContinualTask {
192    pub name: &'static str,
193    pub schema: &'static str,
194    pub oid: u32,
195    pub desc: RelationDesc,
196    pub sql: &'static str,
197    /// ACL items to apply to the object
198    pub access: Vec<MzAclItem>,
199}
200
201#[derive(Hash, Debug)]
202pub struct BuiltinView {
203    pub name: &'static str,
204    pub schema: &'static str,
205    pub oid: u32,
206    pub desc: RelationDesc,
207    pub column_comments: BTreeMap<&'static str, &'static str>,
208    pub sql: &'static str,
209    /// ACL items to apply to the object
210    pub access: Vec<MzAclItem>,
211}
212
213impl BuiltinView {
214    pub fn create_sql(&self) -> String {
215        format!("CREATE VIEW {}.{} AS {}", self.schema, self.name, self.sql)
216    }
217}
218
219#[derive(Debug)]
220pub struct BuiltinType<T: TypeReference> {
221    pub name: &'static str,
222    pub schema: &'static str,
223    pub oid: u32,
224    pub details: CatalogTypeDetails<T>,
225}
226
227#[derive(Debug)]
228pub struct BuiltinFunc {
229    pub schema: &'static str,
230    pub name: &'static str,
231    pub inner: &'static mz_sql::func::Func,
232}
233
234/// Note: When creating a built-in index, it's usually best to choose a key that has only one
235/// component. For example, if you created an index
236/// `ON mz_internal.mz_object_lifetimes (id, object_type)`, then this index couldn't be used for a
237/// lookup for `WHERE object_type = ...`, and neither for joins keyed on just `id`.
238/// See <https://materialize.com/docs/transform-data/optimization/#matching-multi-column-indexes-to-multi-column-where-clauses>
239#[derive(Debug)]
240pub struct BuiltinIndex {
241    pub name: &'static str,
242    pub schema: &'static str,
243    pub oid: u32,
244    /// SQL fragment for the index, following `CREATE INDEX [name]`
245    ///
246    /// Format: `IN CLUSTER [cluster_name] ON [table_name] ([column_exprs])`
247    pub sql: &'static str,
248    pub is_retained_metrics_object: bool,
249}
250
251impl BuiltinIndex {
252    pub fn create_sql(&self) -> String {
253        format!("CREATE INDEX {}\n{}", self.name, self.sql)
254    }
255}
256
257impl BuiltinContinualTask {
258    pub fn create_sql(&self) -> String {
259        format!(
260            "CREATE CONTINUAL TASK {}.{}\n{}",
261            self.schema, self.name, self.sql
262        )
263    }
264}
265
266#[derive(Hash, Debug)]
267pub struct BuiltinConnection {
268    pub name: &'static str,
269    pub schema: &'static str,
270    pub oid: u32,
271    pub sql: &'static str,
272    pub access: &'static [MzAclItem],
273    pub owner_id: &'static RoleId,
274    /// Whether the object can be altered at runtime by its owner.
275    ///
276    /// Note that when `runtime_alterable` is true, changing the `sql` in future
277    /// versions does not trigger a migration.
278    pub runtime_alterable: bool,
279}
280
281#[derive(Clone, Debug)]
282pub struct BuiltinRole {
283    pub id: RoleId,
284    /// Name of the builtin role.
285    ///
286    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
287    pub name: &'static str,
288    pub oid: u32,
289    pub attributes: RoleAttributesRaw,
290}
291
292#[derive(Clone, Debug)]
293pub struct BuiltinCluster {
294    /// Name of the cluster.
295    ///
296    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
297    pub name: &'static str,
298    pub privileges: &'static [MzAclItem],
299    pub owner_id: &'static RoleId,
300}
301
302#[derive(Clone, Debug, PartialEq, Eq)]
303pub struct BuiltinClusterReplica {
304    /// Name of the compute replica.
305    pub name: &'static str,
306    /// Name of the cluster that this replica belongs to.
307    pub cluster_name: &'static str,
308}
309
310/// Uniquely identifies the definition of a builtin object.
311pub trait Fingerprint {
312    fn fingerprint(&self) -> String;
313}
314
315impl<T: TypeReference> Fingerprint for &Builtin<T> {
316    fn fingerprint(&self) -> String {
317        match self {
318            Builtin::Log(log) => log.fingerprint(),
319            Builtin::Table(table) => table.fingerprint(),
320            Builtin::View(view) => view.fingerprint(),
321            Builtin::Type(typ) => typ.fingerprint(),
322            Builtin::Func(func) => func.fingerprint(),
323            Builtin::Source(coll) => coll.fingerprint(),
324            Builtin::ContinualTask(ct) => ct.fingerprint(),
325            Builtin::Index(index) => index.fingerprint(),
326            Builtin::Connection(connection) => connection.fingerprint(),
327        }
328    }
329}
330
331// Types and Funcs never change fingerprints so we just return constant 0
332impl<T: TypeReference> Fingerprint for &BuiltinType<T> {
333    fn fingerprint(&self) -> String {
334        "".to_string()
335    }
336}
337
338impl Fingerprint for &BuiltinFunc {
339    fn fingerprint(&self) -> String {
340        "".to_string()
341    }
342}
343
344impl Fingerprint for &BuiltinLog {
345    fn fingerprint(&self) -> String {
346        self.variant.desc().fingerprint()
347    }
348}
349
350impl Fingerprint for &BuiltinTable {
351    fn fingerprint(&self) -> String {
352        self.desc.fingerprint()
353    }
354}
355
356impl Fingerprint for &BuiltinView {
357    fn fingerprint(&self) -> String {
358        self.sql.to_string()
359    }
360}
361
362impl Fingerprint for &BuiltinSource {
363    fn fingerprint(&self) -> String {
364        self.desc.fingerprint()
365    }
366}
367
368impl Fingerprint for &BuiltinContinualTask {
369    fn fingerprint(&self) -> String {
370        self.create_sql()
371    }
372}
373
374impl Fingerprint for &BuiltinIndex {
375    fn fingerprint(&self) -> String {
376        self.create_sql()
377    }
378}
379
380impl Fingerprint for &BuiltinConnection {
381    fn fingerprint(&self) -> String {
382        self.sql.to_string()
383    }
384}
385
386impl Fingerprint for RelationDesc {
387    fn fingerprint(&self) -> String {
388        self.typ().fingerprint()
389    }
390}
391
392impl Fingerprint for SqlRelationType {
393    fn fingerprint(&self) -> String {
394        serde_json::to_string(self).expect("serialization cannot fail")
395    }
396}
397
398// Builtin definitions below. Ensure you add new builtins to the `BUILTINS` map.
399//
400// You SHOULD NOT delete a builtin. If you do, you will break any downstream
401// user objects that depended on the builtin.
402//
403// Builtins are loaded in dependency order, so a builtin must appear in `BUILTINS`
404// before any items it depends upon.
405//
406// WARNING: if you change the definition of an existing builtin item, you must
407// be careful to maintain backwards compatibility! Adding new columns is safe.
408// Removing a column, changing the name of a column, or changing the type of a
409// column is not safe, as persisted user views may depend upon that column.
410
411// The following types are the list of builtin data types available
412// in Materialize. This list is derived from the `pg_type` table in PostgreSQL.
413//
414// Builtin types cannot be created, updated, or deleted. Their OIDs
415// are static, unlike other objects, to match the type OIDs defined by Postgres.
416
417pub const TYPE_BOOL: BuiltinType<NameReference> = BuiltinType {
418    name: "bool",
419    schema: PG_CATALOG_SCHEMA,
420    oid: oid::TYPE_BOOL_OID,
421    details: CatalogTypeDetails {
422        typ: CatalogType::Bool,
423        array_id: None,
424        pg_metadata: Some(CatalogTypePgMetadata {
425            typinput_oid: 1242,
426            typreceive_oid: 2436,
427        }),
428    },
429};
430
431pub const TYPE_BYTEA: BuiltinType<NameReference> = BuiltinType {
432    name: "bytea",
433    schema: PG_CATALOG_SCHEMA,
434    oid: oid::TYPE_BYTEA_OID,
435    details: CatalogTypeDetails {
436        typ: CatalogType::Bytes,
437        array_id: None,
438        pg_metadata: Some(CatalogTypePgMetadata {
439            typinput_oid: 1244,
440            typreceive_oid: 2412,
441        }),
442    },
443};
444
445pub const TYPE_INT8: BuiltinType<NameReference> = BuiltinType {
446    name: "int8",
447    schema: PG_CATALOG_SCHEMA,
448    oid: oid::TYPE_INT8_OID,
449    details: CatalogTypeDetails {
450        typ: CatalogType::Int64,
451        array_id: None,
452        pg_metadata: Some(CatalogTypePgMetadata {
453            typinput_oid: 460,
454            typreceive_oid: 2408,
455        }),
456    },
457};
458
459pub const TYPE_INT4: BuiltinType<NameReference> = BuiltinType {
460    name: "int4",
461    schema: PG_CATALOG_SCHEMA,
462    oid: oid::TYPE_INT4_OID,
463    details: CatalogTypeDetails {
464        typ: CatalogType::Int32,
465        array_id: None,
466        pg_metadata: Some(CatalogTypePgMetadata {
467            typinput_oid: 42,
468            typreceive_oid: 2406,
469        }),
470    },
471};
472
473pub const TYPE_TEXT: BuiltinType<NameReference> = BuiltinType {
474    name: "text",
475    schema: PG_CATALOG_SCHEMA,
476    oid: oid::TYPE_TEXT_OID,
477    details: CatalogTypeDetails {
478        typ: CatalogType::String,
479        array_id: None,
480        pg_metadata: Some(CatalogTypePgMetadata {
481            typinput_oid: 46,
482            typreceive_oid: 2414,
483        }),
484    },
485};
486
487pub const TYPE_OID: BuiltinType<NameReference> = BuiltinType {
488    name: "oid",
489    schema: PG_CATALOG_SCHEMA,
490    oid: oid::TYPE_OID_OID,
491    details: CatalogTypeDetails {
492        typ: CatalogType::Oid,
493        array_id: None,
494        pg_metadata: Some(CatalogTypePgMetadata {
495            typinput_oid: 1798,
496            typreceive_oid: 2418,
497        }),
498    },
499};
500
501pub const TYPE_FLOAT4: BuiltinType<NameReference> = BuiltinType {
502    name: "float4",
503    schema: PG_CATALOG_SCHEMA,
504    oid: oid::TYPE_FLOAT4_OID,
505    details: CatalogTypeDetails {
506        typ: CatalogType::Float32,
507        array_id: None,
508        pg_metadata: Some(CatalogTypePgMetadata {
509            typinput_oid: 200,
510            typreceive_oid: 2424,
511        }),
512    },
513};
514
515pub const TYPE_FLOAT8: BuiltinType<NameReference> = BuiltinType {
516    name: "float8",
517    schema: PG_CATALOG_SCHEMA,
518    oid: oid::TYPE_FLOAT8_OID,
519    details: CatalogTypeDetails {
520        typ: CatalogType::Float64,
521        array_id: None,
522        pg_metadata: Some(CatalogTypePgMetadata {
523            typinput_oid: 214,
524            typreceive_oid: 2426,
525        }),
526    },
527};
528
529pub const TYPE_BOOL_ARRAY: BuiltinType<NameReference> = BuiltinType {
530    name: "_bool",
531    schema: PG_CATALOG_SCHEMA,
532    oid: oid::TYPE_BOOL_ARRAY_OID,
533    details: CatalogTypeDetails {
534        typ: CatalogType::Array {
535            element_reference: TYPE_BOOL.name,
536        },
537        array_id: None,
538        pg_metadata: Some(CatalogTypePgMetadata {
539            typinput_oid: 750,
540            typreceive_oid: 2400,
541        }),
542    },
543};
544
545pub const TYPE_BYTEA_ARRAY: BuiltinType<NameReference> = BuiltinType {
546    name: "_bytea",
547    schema: PG_CATALOG_SCHEMA,
548    oid: oid::TYPE_BYTEA_ARRAY_OID,
549    details: CatalogTypeDetails {
550        typ: CatalogType::Array {
551            element_reference: TYPE_BYTEA.name,
552        },
553        array_id: None,
554        pg_metadata: Some(CatalogTypePgMetadata {
555            typinput_oid: 750,
556            typreceive_oid: 2400,
557        }),
558    },
559};
560
561pub const TYPE_INT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
562    name: "_int4",
563    schema: PG_CATALOG_SCHEMA,
564    oid: oid::TYPE_INT4_ARRAY_OID,
565    details: CatalogTypeDetails {
566        typ: CatalogType::Array {
567            element_reference: TYPE_INT4.name,
568        },
569        array_id: None,
570        pg_metadata: Some(CatalogTypePgMetadata {
571            typinput_oid: 750,
572            typreceive_oid: 2400,
573        }),
574    },
575};
576
577pub const TYPE_TEXT_ARRAY: BuiltinType<NameReference> = BuiltinType {
578    name: "_text",
579    schema: PG_CATALOG_SCHEMA,
580    oid: oid::TYPE_TEXT_ARRAY_OID,
581    details: CatalogTypeDetails {
582        typ: CatalogType::Array {
583            element_reference: TYPE_TEXT.name,
584        },
585        array_id: None,
586        pg_metadata: Some(CatalogTypePgMetadata {
587            typinput_oid: 750,
588            typreceive_oid: 2400,
589        }),
590    },
591};
592
593pub const TYPE_INT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
594    name: "_int8",
595    schema: PG_CATALOG_SCHEMA,
596    oid: oid::TYPE_INT8_ARRAY_OID,
597    details: CatalogTypeDetails {
598        typ: CatalogType::Array {
599            element_reference: TYPE_INT8.name,
600        },
601        array_id: None,
602        pg_metadata: Some(CatalogTypePgMetadata {
603            typinput_oid: 750,
604            typreceive_oid: 2400,
605        }),
606    },
607};
608
609pub const TYPE_FLOAT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
610    name: "_float4",
611    schema: PG_CATALOG_SCHEMA,
612    oid: oid::TYPE_FLOAT4_ARRAY_OID,
613    details: CatalogTypeDetails {
614        typ: CatalogType::Array {
615            element_reference: TYPE_FLOAT4.name,
616        },
617        array_id: None,
618        pg_metadata: Some(CatalogTypePgMetadata {
619            typinput_oid: 750,
620            typreceive_oid: 2400,
621        }),
622    },
623};
624
625pub const TYPE_FLOAT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
626    name: "_float8",
627    schema: PG_CATALOG_SCHEMA,
628    oid: oid::TYPE_FLOAT8_ARRAY_OID,
629    details: CatalogTypeDetails {
630        typ: CatalogType::Array {
631            element_reference: TYPE_FLOAT8.name,
632        },
633        array_id: None,
634        pg_metadata: Some(CatalogTypePgMetadata {
635            typinput_oid: 750,
636            typreceive_oid: 2400,
637        }),
638    },
639};
640
641pub const TYPE_OID_ARRAY: BuiltinType<NameReference> = BuiltinType {
642    name: "_oid",
643    schema: PG_CATALOG_SCHEMA,
644    oid: oid::TYPE_OID_ARRAY_OID,
645    details: CatalogTypeDetails {
646        typ: CatalogType::Array {
647            element_reference: TYPE_OID.name,
648        },
649        array_id: None,
650        pg_metadata: Some(CatalogTypePgMetadata {
651            typinput_oid: 750,
652            typreceive_oid: 2400,
653        }),
654    },
655};
656
657pub const TYPE_DATE: BuiltinType<NameReference> = BuiltinType {
658    name: "date",
659    schema: PG_CATALOG_SCHEMA,
660    oid: oid::TYPE_DATE_OID,
661    details: CatalogTypeDetails {
662        typ: CatalogType::Date,
663        array_id: None,
664        pg_metadata: Some(CatalogTypePgMetadata {
665            typinput_oid: 1084,
666            typreceive_oid: 2468,
667        }),
668    },
669};
670
671pub const TYPE_TIME: BuiltinType<NameReference> = BuiltinType {
672    name: "time",
673    schema: PG_CATALOG_SCHEMA,
674    oid: oid::TYPE_TIME_OID,
675    details: CatalogTypeDetails {
676        typ: CatalogType::Time,
677        array_id: None,
678        pg_metadata: Some(CatalogTypePgMetadata {
679            typinput_oid: 1143,
680            typreceive_oid: 2470,
681        }),
682    },
683};
684
685pub const TYPE_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
686    name: "timestamp",
687    schema: PG_CATALOG_SCHEMA,
688    oid: oid::TYPE_TIMESTAMP_OID,
689    details: CatalogTypeDetails {
690        typ: CatalogType::Timestamp,
691        array_id: None,
692        pg_metadata: Some(CatalogTypePgMetadata {
693            typinput_oid: 1312,
694            typreceive_oid: 2474,
695        }),
696    },
697};
698
699pub const TYPE_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
700    name: "_timestamp",
701    schema: PG_CATALOG_SCHEMA,
702    oid: oid::TYPE_TIMESTAMP_ARRAY_OID,
703    details: CatalogTypeDetails {
704        typ: CatalogType::Array {
705            element_reference: TYPE_TIMESTAMP.name,
706        },
707        array_id: None,
708        pg_metadata: Some(CatalogTypePgMetadata {
709            typinput_oid: 750,
710            typreceive_oid: 2400,
711        }),
712    },
713};
714
715pub const TYPE_DATE_ARRAY: BuiltinType<NameReference> = BuiltinType {
716    name: "_date",
717    schema: PG_CATALOG_SCHEMA,
718    oid: oid::TYPE_DATE_ARRAY_OID,
719    details: CatalogTypeDetails {
720        typ: CatalogType::Array {
721            element_reference: TYPE_DATE.name,
722        },
723        array_id: None,
724        pg_metadata: Some(CatalogTypePgMetadata {
725            typinput_oid: 750,
726            typreceive_oid: 2400,
727        }),
728    },
729};
730
731pub const TYPE_TIME_ARRAY: BuiltinType<NameReference> = BuiltinType {
732    name: "_time",
733    schema: PG_CATALOG_SCHEMA,
734    oid: oid::TYPE_TIME_ARRAY_OID,
735    details: CatalogTypeDetails {
736        typ: CatalogType::Array {
737            element_reference: TYPE_TIME.name,
738        },
739        array_id: None,
740        pg_metadata: Some(CatalogTypePgMetadata {
741            typinput_oid: 750,
742            typreceive_oid: 2400,
743        }),
744    },
745};
746
747pub const TYPE_TIMESTAMPTZ: BuiltinType<NameReference> = BuiltinType {
748    name: "timestamptz",
749    schema: PG_CATALOG_SCHEMA,
750    oid: oid::TYPE_TIMESTAMPTZ_OID,
751    details: CatalogTypeDetails {
752        typ: CatalogType::TimestampTz,
753        array_id: None,
754        pg_metadata: Some(CatalogTypePgMetadata {
755            typinput_oid: 1150,
756            typreceive_oid: 2476,
757        }),
758    },
759};
760
761pub const TYPE_TIMESTAMPTZ_ARRAY: BuiltinType<NameReference> = BuiltinType {
762    name: "_timestamptz",
763    schema: PG_CATALOG_SCHEMA,
764    oid: oid::TYPE_TIMESTAMPTZ_ARRAY_OID,
765    details: CatalogTypeDetails {
766        typ: CatalogType::Array {
767            element_reference: TYPE_TIMESTAMPTZ.name,
768        },
769        array_id: None,
770        pg_metadata: Some(CatalogTypePgMetadata {
771            typinput_oid: 750,
772            typreceive_oid: 2400,
773        }),
774    },
775};
776
777pub const TYPE_INTERVAL: BuiltinType<NameReference> = BuiltinType {
778    name: "interval",
779    schema: PG_CATALOG_SCHEMA,
780    oid: oid::TYPE_INTERVAL_OID,
781    details: CatalogTypeDetails {
782        typ: CatalogType::Interval,
783        array_id: None,
784        pg_metadata: Some(CatalogTypePgMetadata {
785            typinput_oid: 1160,
786            typreceive_oid: 2478,
787        }),
788    },
789};
790
791pub const TYPE_INTERVAL_ARRAY: BuiltinType<NameReference> = BuiltinType {
792    name: "_interval",
793    schema: PG_CATALOG_SCHEMA,
794    oid: oid::TYPE_INTERVAL_ARRAY_OID,
795    details: CatalogTypeDetails {
796        typ: CatalogType::Array {
797            element_reference: TYPE_INTERVAL.name,
798        },
799        array_id: None,
800        pg_metadata: Some(CatalogTypePgMetadata {
801            typinput_oid: 750,
802            typreceive_oid: 2400,
803        }),
804    },
805};
806
807pub const TYPE_NAME: BuiltinType<NameReference> = BuiltinType {
808    name: "name",
809    schema: PG_CATALOG_SCHEMA,
810    oid: oid::TYPE_NAME_OID,
811    details: CatalogTypeDetails {
812        typ: CatalogType::PgLegacyName,
813        array_id: None,
814        pg_metadata: Some(CatalogTypePgMetadata {
815            typinput_oid: 34,
816            typreceive_oid: 2422,
817        }),
818    },
819};
820
821pub const TYPE_NAME_ARRAY: BuiltinType<NameReference> = BuiltinType {
822    name: "_name",
823    schema: PG_CATALOG_SCHEMA,
824    oid: oid::TYPE_NAME_ARRAY_OID,
825    details: CatalogTypeDetails {
826        typ: CatalogType::Array {
827            element_reference: TYPE_NAME.name,
828        },
829        array_id: None,
830        pg_metadata: Some(CatalogTypePgMetadata {
831            typinput_oid: 750,
832            typreceive_oid: 2400,
833        }),
834    },
835};
836
837pub const TYPE_NUMERIC: BuiltinType<NameReference> = BuiltinType {
838    name: "numeric",
839    schema: PG_CATALOG_SCHEMA,
840    oid: oid::TYPE_NUMERIC_OID,
841    details: CatalogTypeDetails {
842        typ: CatalogType::Numeric,
843        array_id: None,
844        pg_metadata: Some(CatalogTypePgMetadata {
845            typinput_oid: 1701,
846            typreceive_oid: 2460,
847        }),
848    },
849};
850
851pub const TYPE_NUMERIC_ARRAY: BuiltinType<NameReference> = BuiltinType {
852    name: "_numeric",
853    schema: PG_CATALOG_SCHEMA,
854    oid: oid::TYPE_NUMERIC_ARRAY_OID,
855    details: CatalogTypeDetails {
856        typ: CatalogType::Array {
857            element_reference: TYPE_NUMERIC.name,
858        },
859        array_id: None,
860        pg_metadata: Some(CatalogTypePgMetadata {
861            typinput_oid: 750,
862            typreceive_oid: 2400,
863        }),
864    },
865};
866
867pub const TYPE_RECORD: BuiltinType<NameReference> = BuiltinType {
868    name: "record",
869    schema: PG_CATALOG_SCHEMA,
870    oid: oid::TYPE_RECORD_OID,
871    details: CatalogTypeDetails {
872        typ: CatalogType::Pseudo,
873        array_id: None,
874        pg_metadata: Some(CatalogTypePgMetadata {
875            typinput_oid: 2290,
876            typreceive_oid: 2402,
877        }),
878    },
879};
880
881pub const TYPE_RECORD_ARRAY: BuiltinType<NameReference> = BuiltinType {
882    name: "_record",
883    schema: PG_CATALOG_SCHEMA,
884    oid: oid::TYPE_RECORD_ARRAY_OID,
885    details: CatalogTypeDetails {
886        typ: CatalogType::Array {
887            element_reference: TYPE_RECORD.name,
888        },
889        array_id: None,
890        pg_metadata: Some(CatalogTypePgMetadata {
891            typinput_oid: 750,
892            typreceive_oid: 2400,
893        }),
894    },
895};
896
897pub const TYPE_UUID: BuiltinType<NameReference> = BuiltinType {
898    name: "uuid",
899    schema: PG_CATALOG_SCHEMA,
900    oid: oid::TYPE_UUID_OID,
901    details: CatalogTypeDetails {
902        typ: CatalogType::Uuid,
903        array_id: None,
904        pg_metadata: Some(CatalogTypePgMetadata {
905            typinput_oid: 2952,
906            typreceive_oid: 2961,
907        }),
908    },
909};
910
911pub const TYPE_UUID_ARRAY: BuiltinType<NameReference> = BuiltinType {
912    name: "_uuid",
913    schema: PG_CATALOG_SCHEMA,
914    oid: oid::TYPE_UUID_ARRAY_OID,
915    details: CatalogTypeDetails {
916        typ: CatalogType::Array {
917            element_reference: TYPE_UUID.name,
918        },
919        array_id: None,
920        pg_metadata: Some(CatalogTypePgMetadata {
921            typinput_oid: 750,
922            typreceive_oid: 2400,
923        }),
924    },
925};
926
927pub const TYPE_JSONB: BuiltinType<NameReference> = BuiltinType {
928    name: "jsonb",
929    schema: PG_CATALOG_SCHEMA,
930    oid: oid::TYPE_JSONB_OID,
931    details: CatalogTypeDetails {
932        typ: CatalogType::Jsonb,
933        array_id: None,
934        pg_metadata: Some(CatalogTypePgMetadata {
935            typinput_oid: 3806,
936            typreceive_oid: 3805,
937        }),
938    },
939};
940
941pub const TYPE_JSONB_ARRAY: BuiltinType<NameReference> = BuiltinType {
942    name: "_jsonb",
943    schema: PG_CATALOG_SCHEMA,
944    oid: oid::TYPE_JSONB_ARRAY_OID,
945    details: CatalogTypeDetails {
946        typ: CatalogType::Array {
947            element_reference: TYPE_JSONB.name,
948        },
949        array_id: None,
950        pg_metadata: Some(CatalogTypePgMetadata {
951            typinput_oid: 750,
952            typreceive_oid: 2400,
953        }),
954    },
955};
956
957pub const TYPE_ANY: BuiltinType<NameReference> = BuiltinType {
958    name: "any",
959    schema: PG_CATALOG_SCHEMA,
960    oid: oid::TYPE_ANY_OID,
961    details: CatalogTypeDetails {
962        typ: CatalogType::Pseudo,
963        array_id: None,
964        pg_metadata: Some(CatalogTypePgMetadata {
965            typinput_oid: 2294,
966            typreceive_oid: 0,
967        }),
968    },
969};
970
971pub const TYPE_ANYARRAY: BuiltinType<NameReference> = BuiltinType {
972    name: "anyarray",
973    schema: PG_CATALOG_SCHEMA,
974    oid: oid::TYPE_ANYARRAY_OID,
975    details: CatalogTypeDetails {
976        typ: CatalogType::Pseudo,
977        array_id: None,
978        pg_metadata: Some(CatalogTypePgMetadata {
979            typinput_oid: 2296,
980            typreceive_oid: 2502,
981        }),
982    },
983};
984
985pub const TYPE_ANYELEMENT: BuiltinType<NameReference> = BuiltinType {
986    name: "anyelement",
987    schema: PG_CATALOG_SCHEMA,
988    oid: oid::TYPE_ANYELEMENT_OID,
989    details: CatalogTypeDetails {
990        typ: CatalogType::Pseudo,
991        array_id: None,
992        pg_metadata: Some(CatalogTypePgMetadata {
993            typinput_oid: 2312,
994            typreceive_oid: 0,
995        }),
996    },
997};
998
999pub const TYPE_ANYNONARRAY: BuiltinType<NameReference> = BuiltinType {
1000    name: "anynonarray",
1001    schema: PG_CATALOG_SCHEMA,
1002    oid: oid::TYPE_ANYNONARRAY_OID,
1003    details: CatalogTypeDetails {
1004        typ: CatalogType::Pseudo,
1005        array_id: None,
1006        pg_metadata: Some(CatalogTypePgMetadata {
1007            typinput_oid: 2777,
1008            typreceive_oid: 0,
1009        }),
1010    },
1011};
1012
1013pub const TYPE_ANYRANGE: BuiltinType<NameReference> = BuiltinType {
1014    name: "anyrange",
1015    schema: PG_CATALOG_SCHEMA,
1016    oid: oid::TYPE_ANYRANGE_OID,
1017    details: CatalogTypeDetails {
1018        typ: CatalogType::Pseudo,
1019        array_id: None,
1020        pg_metadata: Some(CatalogTypePgMetadata {
1021            typinput_oid: 3832,
1022            typreceive_oid: 0,
1023        }),
1024    },
1025};
1026
1027pub const TYPE_CHAR: BuiltinType<NameReference> = BuiltinType {
1028    name: "char",
1029    schema: PG_CATALOG_SCHEMA,
1030    oid: oid::TYPE_CHAR_OID,
1031    details: CatalogTypeDetails {
1032        typ: CatalogType::PgLegacyChar,
1033        array_id: None,
1034        pg_metadata: Some(CatalogTypePgMetadata {
1035            typinput_oid: 1245,
1036            typreceive_oid: 2434,
1037        }),
1038    },
1039};
1040
1041pub const TYPE_VARCHAR: BuiltinType<NameReference> = BuiltinType {
1042    name: "varchar",
1043    schema: PG_CATALOG_SCHEMA,
1044    oid: oid::TYPE_VARCHAR_OID,
1045    details: CatalogTypeDetails {
1046        typ: CatalogType::VarChar,
1047        array_id: None,
1048        pg_metadata: Some(CatalogTypePgMetadata {
1049            typinput_oid: 1046,
1050            typreceive_oid: 2432,
1051        }),
1052    },
1053};
1054
1055pub const TYPE_INT2: BuiltinType<NameReference> = BuiltinType {
1056    name: "int2",
1057    schema: PG_CATALOG_SCHEMA,
1058    oid: oid::TYPE_INT2_OID,
1059    details: CatalogTypeDetails {
1060        typ: CatalogType::Int16,
1061        array_id: None,
1062        pg_metadata: Some(CatalogTypePgMetadata {
1063            typinput_oid: 38,
1064            typreceive_oid: 2404,
1065        }),
1066    },
1067};
1068
1069pub const TYPE_INT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1070    name: "_int2",
1071    schema: PG_CATALOG_SCHEMA,
1072    oid: oid::TYPE_INT2_ARRAY_OID,
1073    details: CatalogTypeDetails {
1074        typ: CatalogType::Array {
1075            element_reference: TYPE_INT2.name,
1076        },
1077        array_id: None,
1078        pg_metadata: Some(CatalogTypePgMetadata {
1079            typinput_oid: 750,
1080            typreceive_oid: 2400,
1081        }),
1082    },
1083};
1084
1085pub const TYPE_BPCHAR: BuiltinType<NameReference> = BuiltinType {
1086    name: "bpchar",
1087    schema: PG_CATALOG_SCHEMA,
1088    oid: oid::TYPE_BPCHAR_OID,
1089    details: CatalogTypeDetails {
1090        typ: CatalogType::Char,
1091        array_id: None,
1092        pg_metadata: Some(CatalogTypePgMetadata {
1093            typinput_oid: 1044,
1094            typreceive_oid: 2430,
1095        }),
1096    },
1097};
1098
1099pub const TYPE_CHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1100    name: "_char",
1101    schema: PG_CATALOG_SCHEMA,
1102    oid: oid::TYPE_CHAR_ARRAY_OID,
1103    details: CatalogTypeDetails {
1104        typ: CatalogType::Array {
1105            element_reference: TYPE_CHAR.name,
1106        },
1107        array_id: None,
1108        pg_metadata: Some(CatalogTypePgMetadata {
1109            typinput_oid: 750,
1110            typreceive_oid: 2400,
1111        }),
1112    },
1113};
1114
1115pub const TYPE_VARCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1116    name: "_varchar",
1117    schema: PG_CATALOG_SCHEMA,
1118    oid: oid::TYPE_VARCHAR_ARRAY_OID,
1119    details: CatalogTypeDetails {
1120        typ: CatalogType::Array {
1121            element_reference: TYPE_VARCHAR.name,
1122        },
1123        array_id: None,
1124        pg_metadata: Some(CatalogTypePgMetadata {
1125            typinput_oid: 750,
1126            typreceive_oid: 2400,
1127        }),
1128    },
1129};
1130
1131pub const TYPE_BPCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1132    name: "_bpchar",
1133    schema: PG_CATALOG_SCHEMA,
1134    oid: oid::TYPE_BPCHAR_ARRAY_OID,
1135    details: CatalogTypeDetails {
1136        typ: CatalogType::Array {
1137            element_reference: TYPE_BPCHAR.name,
1138        },
1139        array_id: None,
1140        pg_metadata: Some(CatalogTypePgMetadata {
1141            typinput_oid: 750,
1142            typreceive_oid: 2400,
1143        }),
1144    },
1145};
1146
1147pub const TYPE_REGPROC: BuiltinType<NameReference> = BuiltinType {
1148    name: "regproc",
1149    schema: PG_CATALOG_SCHEMA,
1150    oid: oid::TYPE_REGPROC_OID,
1151    details: CatalogTypeDetails {
1152        typ: CatalogType::RegProc,
1153        array_id: None,
1154        pg_metadata: Some(CatalogTypePgMetadata {
1155            typinput_oid: 44,
1156            typreceive_oid: 2444,
1157        }),
1158    },
1159};
1160
1161pub const TYPE_REGPROC_ARRAY: BuiltinType<NameReference> = BuiltinType {
1162    name: "_regproc",
1163    schema: PG_CATALOG_SCHEMA,
1164    oid: oid::TYPE_REGPROC_ARRAY_OID,
1165    details: CatalogTypeDetails {
1166        typ: CatalogType::Array {
1167            element_reference: TYPE_REGPROC.name,
1168        },
1169        array_id: None,
1170        pg_metadata: Some(CatalogTypePgMetadata {
1171            typinput_oid: 750,
1172            typreceive_oid: 2400,
1173        }),
1174    },
1175};
1176
1177pub const TYPE_REGTYPE: BuiltinType<NameReference> = BuiltinType {
1178    name: "regtype",
1179    schema: PG_CATALOG_SCHEMA,
1180    oid: oid::TYPE_REGTYPE_OID,
1181    details: CatalogTypeDetails {
1182        typ: CatalogType::RegType,
1183        array_id: None,
1184        pg_metadata: Some(CatalogTypePgMetadata {
1185            typinput_oid: 2220,
1186            typreceive_oid: 2454,
1187        }),
1188    },
1189};
1190
1191pub const TYPE_REGTYPE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1192    name: "_regtype",
1193    schema: PG_CATALOG_SCHEMA,
1194    oid: oid::TYPE_REGTYPE_ARRAY_OID,
1195    details: CatalogTypeDetails {
1196        typ: CatalogType::Array {
1197            element_reference: TYPE_REGTYPE.name,
1198        },
1199        array_id: None,
1200        pg_metadata: Some(CatalogTypePgMetadata {
1201            typinput_oid: 750,
1202            typreceive_oid: 2400,
1203        }),
1204    },
1205};
1206
1207pub const TYPE_REGCLASS: BuiltinType<NameReference> = BuiltinType {
1208    name: "regclass",
1209    schema: PG_CATALOG_SCHEMA,
1210    oid: oid::TYPE_REGCLASS_OID,
1211    details: CatalogTypeDetails {
1212        typ: CatalogType::RegClass,
1213        array_id: None,
1214        pg_metadata: Some(CatalogTypePgMetadata {
1215            typinput_oid: 2218,
1216            typreceive_oid: 2452,
1217        }),
1218    },
1219};
1220
1221pub const TYPE_REGCLASS_ARRAY: BuiltinType<NameReference> = BuiltinType {
1222    name: "_regclass",
1223    schema: PG_CATALOG_SCHEMA,
1224    oid: oid::TYPE_REGCLASS_ARRAY_OID,
1225    details: CatalogTypeDetails {
1226        typ: CatalogType::Array {
1227            element_reference: TYPE_REGCLASS.name,
1228        },
1229        array_id: None,
1230        pg_metadata: Some(CatalogTypePgMetadata {
1231            typinput_oid: 750,
1232            typreceive_oid: 2400,
1233        }),
1234    },
1235};
1236
1237pub const TYPE_INT2_VECTOR: BuiltinType<NameReference> = BuiltinType {
1238    name: "int2vector",
1239    schema: PG_CATALOG_SCHEMA,
1240    oid: oid::TYPE_INT2_VECTOR_OID,
1241    details: CatalogTypeDetails {
1242        typ: CatalogType::Int2Vector,
1243        array_id: None,
1244        pg_metadata: Some(CatalogTypePgMetadata {
1245            typinput_oid: 40,
1246            typreceive_oid: 2410,
1247        }),
1248    },
1249};
1250
1251pub const TYPE_INT2_VECTOR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1252    name: "_int2vector",
1253    schema: PG_CATALOG_SCHEMA,
1254    oid: oid::TYPE_INT2_VECTOR_ARRAY_OID,
1255    details: CatalogTypeDetails {
1256        typ: CatalogType::Array {
1257            element_reference: TYPE_INT2_VECTOR.name,
1258        },
1259        array_id: None,
1260        pg_metadata: Some(CatalogTypePgMetadata {
1261            typinput_oid: 750,
1262            typreceive_oid: 2400,
1263        }),
1264    },
1265};
1266
1267pub const TYPE_ANYCOMPATIBLE: BuiltinType<NameReference> = BuiltinType {
1268    name: "anycompatible",
1269    schema: PG_CATALOG_SCHEMA,
1270    oid: oid::TYPE_ANYCOMPATIBLE_OID,
1271    details: CatalogTypeDetails {
1272        typ: CatalogType::Pseudo,
1273        array_id: None,
1274        pg_metadata: Some(CatalogTypePgMetadata {
1275            typinput_oid: 5086,
1276            typreceive_oid: 0,
1277        }),
1278    },
1279};
1280
1281pub const TYPE_ANYCOMPATIBLEARRAY: BuiltinType<NameReference> = BuiltinType {
1282    name: "anycompatiblearray",
1283    schema: PG_CATALOG_SCHEMA,
1284    oid: oid::TYPE_ANYCOMPATIBLEARRAY_OID,
1285    details: CatalogTypeDetails {
1286        typ: CatalogType::Pseudo,
1287        array_id: None,
1288        pg_metadata: Some(CatalogTypePgMetadata {
1289            typinput_oid: 5088,
1290            typreceive_oid: 5090,
1291        }),
1292    },
1293};
1294
1295pub const TYPE_ANYCOMPATIBLENONARRAY: BuiltinType<NameReference> = BuiltinType {
1296    name: "anycompatiblenonarray",
1297    schema: PG_CATALOG_SCHEMA,
1298    oid: oid::TYPE_ANYCOMPATIBLENONARRAY_OID,
1299    details: CatalogTypeDetails {
1300        typ: CatalogType::Pseudo,
1301        array_id: None,
1302        pg_metadata: Some(CatalogTypePgMetadata {
1303            typinput_oid: 5092,
1304            typreceive_oid: 0,
1305        }),
1306    },
1307};
1308
1309pub const TYPE_ANYCOMPATIBLERANGE: BuiltinType<NameReference> = BuiltinType {
1310    name: "anycompatiblerange",
1311    schema: PG_CATALOG_SCHEMA,
1312    oid: oid::TYPE_ANYCOMPATIBLERANGE_OID,
1313    details: CatalogTypeDetails {
1314        typ: CatalogType::Pseudo,
1315        array_id: None,
1316        pg_metadata: Some(CatalogTypePgMetadata {
1317            typinput_oid: 5094,
1318            typreceive_oid: 0,
1319        }),
1320    },
1321};
1322
1323pub const TYPE_LIST: BuiltinType<NameReference> = BuiltinType {
1324    name: "list",
1325    schema: MZ_CATALOG_SCHEMA,
1326    oid: mz_pgrepr::oid::TYPE_LIST_OID,
1327    details: CatalogTypeDetails {
1328        typ: CatalogType::Pseudo,
1329        array_id: None,
1330        pg_metadata: None,
1331    },
1332};
1333
1334pub const TYPE_MAP: BuiltinType<NameReference> = BuiltinType {
1335    name: "map",
1336    schema: MZ_CATALOG_SCHEMA,
1337    oid: mz_pgrepr::oid::TYPE_MAP_OID,
1338    details: CatalogTypeDetails {
1339        typ: CatalogType::Pseudo,
1340        array_id: None,
1341        pg_metadata: None,
1342    },
1343};
1344
1345pub const TYPE_ANYCOMPATIBLELIST: BuiltinType<NameReference> = BuiltinType {
1346    name: "anycompatiblelist",
1347    schema: MZ_CATALOG_SCHEMA,
1348    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLELIST_OID,
1349    details: CatalogTypeDetails {
1350        typ: CatalogType::Pseudo,
1351        array_id: None,
1352        pg_metadata: None,
1353    },
1354};
1355
1356pub const TYPE_ANYCOMPATIBLEMAP: BuiltinType<NameReference> = BuiltinType {
1357    name: "anycompatiblemap",
1358    schema: MZ_CATALOG_SCHEMA,
1359    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLEMAP_OID,
1360    details: CatalogTypeDetails {
1361        typ: CatalogType::Pseudo,
1362        array_id: None,
1363        pg_metadata: None,
1364    },
1365};
1366
1367pub const TYPE_UINT2: BuiltinType<NameReference> = BuiltinType {
1368    name: "uint2",
1369    schema: MZ_CATALOG_SCHEMA,
1370    oid: mz_pgrepr::oid::TYPE_UINT2_OID,
1371    details: CatalogTypeDetails {
1372        typ: CatalogType::UInt16,
1373        array_id: None,
1374        pg_metadata: None,
1375    },
1376};
1377
1378pub const TYPE_UINT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1379    name: "_uint2",
1380    schema: MZ_CATALOG_SCHEMA,
1381    oid: mz_pgrepr::oid::TYPE_UINT2_ARRAY_OID,
1382    details: CatalogTypeDetails {
1383        typ: CatalogType::Array {
1384            element_reference: TYPE_UINT2.name,
1385        },
1386        array_id: None,
1387        pg_metadata: None,
1388    },
1389};
1390
1391pub const TYPE_UINT4: BuiltinType<NameReference> = BuiltinType {
1392    name: "uint4",
1393    schema: MZ_CATALOG_SCHEMA,
1394    oid: mz_pgrepr::oid::TYPE_UINT4_OID,
1395    details: CatalogTypeDetails {
1396        typ: CatalogType::UInt32,
1397        array_id: None,
1398        pg_metadata: None,
1399    },
1400};
1401
1402pub const TYPE_UINT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
1403    name: "_uint4",
1404    schema: MZ_CATALOG_SCHEMA,
1405    oid: mz_pgrepr::oid::TYPE_UINT4_ARRAY_OID,
1406    details: CatalogTypeDetails {
1407        typ: CatalogType::Array {
1408            element_reference: TYPE_UINT4.name,
1409        },
1410        array_id: None,
1411        pg_metadata: None,
1412    },
1413};
1414
1415pub const TYPE_UINT8: BuiltinType<NameReference> = BuiltinType {
1416    name: "uint8",
1417    schema: MZ_CATALOG_SCHEMA,
1418    oid: mz_pgrepr::oid::TYPE_UINT8_OID,
1419    details: CatalogTypeDetails {
1420        typ: CatalogType::UInt64,
1421        array_id: None,
1422        pg_metadata: None,
1423    },
1424};
1425
1426pub const TYPE_UINT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
1427    name: "_uint8",
1428    schema: MZ_CATALOG_SCHEMA,
1429    oid: mz_pgrepr::oid::TYPE_UINT8_ARRAY_OID,
1430    details: CatalogTypeDetails {
1431        typ: CatalogType::Array {
1432            element_reference: TYPE_UINT8.name,
1433        },
1434        array_id: None,
1435        pg_metadata: None,
1436    },
1437};
1438
1439pub const TYPE_MZ_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
1440    name: "mz_timestamp",
1441    schema: MZ_CATALOG_SCHEMA,
1442    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_OID,
1443    details: CatalogTypeDetails {
1444        typ: CatalogType::MzTimestamp,
1445        array_id: None,
1446        pg_metadata: None,
1447    },
1448};
1449
1450pub const TYPE_MZ_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
1451    name: "_mz_timestamp",
1452    schema: MZ_CATALOG_SCHEMA,
1453    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_ARRAY_OID,
1454    details: CatalogTypeDetails {
1455        typ: CatalogType::Array {
1456            element_reference: TYPE_MZ_TIMESTAMP.name,
1457        },
1458        array_id: None,
1459        pg_metadata: None,
1460    },
1461};
1462
1463pub const TYPE_INT4_RANGE: BuiltinType<NameReference> = BuiltinType {
1464    name: "int4range",
1465    schema: PG_CATALOG_SCHEMA,
1466    oid: mz_pgrepr::oid::TYPE_INT4RANGE_OID,
1467    details: CatalogTypeDetails {
1468        typ: CatalogType::Range {
1469            element_reference: TYPE_INT4.name,
1470        },
1471        array_id: None,
1472        pg_metadata: Some(CatalogTypePgMetadata {
1473            typinput_oid: 3834,
1474            typreceive_oid: 3836,
1475        }),
1476    },
1477};
1478
1479pub const TYPE_INT4_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1480    name: "_int4range",
1481    schema: PG_CATALOG_SCHEMA,
1482    oid: mz_pgrepr::oid::TYPE_INT4RANGE_ARRAY_OID,
1483    details: CatalogTypeDetails {
1484        typ: CatalogType::Array {
1485            element_reference: TYPE_INT4_RANGE.name,
1486        },
1487        array_id: None,
1488        pg_metadata: Some(CatalogTypePgMetadata {
1489            typinput_oid: 750,
1490            typreceive_oid: 2400,
1491        }),
1492    },
1493};
1494
1495pub const TYPE_INT8_RANGE: BuiltinType<NameReference> = BuiltinType {
1496    name: "int8range",
1497    schema: PG_CATALOG_SCHEMA,
1498    oid: mz_pgrepr::oid::TYPE_INT8RANGE_OID,
1499    details: CatalogTypeDetails {
1500        typ: CatalogType::Range {
1501            element_reference: TYPE_INT8.name,
1502        },
1503        array_id: None,
1504        pg_metadata: Some(CatalogTypePgMetadata {
1505            typinput_oid: 3834,
1506            typreceive_oid: 3836,
1507        }),
1508    },
1509};
1510
1511pub const TYPE_INT8_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1512    name: "_int8range",
1513    schema: PG_CATALOG_SCHEMA,
1514    oid: mz_pgrepr::oid::TYPE_INT8RANGE_ARRAY_OID,
1515    details: CatalogTypeDetails {
1516        typ: CatalogType::Array {
1517            element_reference: TYPE_INT8_RANGE.name,
1518        },
1519        array_id: None,
1520        pg_metadata: Some(CatalogTypePgMetadata {
1521            typinput_oid: 750,
1522            typreceive_oid: 2400,
1523        }),
1524    },
1525};
1526
1527pub const TYPE_DATE_RANGE: BuiltinType<NameReference> = BuiltinType {
1528    name: "daterange",
1529    schema: PG_CATALOG_SCHEMA,
1530    oid: mz_pgrepr::oid::TYPE_DATERANGE_OID,
1531    details: CatalogTypeDetails {
1532        typ: CatalogType::Range {
1533            element_reference: TYPE_DATE.name,
1534        },
1535        array_id: None,
1536        pg_metadata: Some(CatalogTypePgMetadata {
1537            typinput_oid: 3834,
1538            typreceive_oid: 3836,
1539        }),
1540    },
1541};
1542
1543pub const TYPE_DATE_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1544    name: "_daterange",
1545    schema: PG_CATALOG_SCHEMA,
1546    oid: mz_pgrepr::oid::TYPE_DATERANGE_ARRAY_OID,
1547    details: CatalogTypeDetails {
1548        typ: CatalogType::Array {
1549            element_reference: TYPE_DATE_RANGE.name,
1550        },
1551        array_id: None,
1552        pg_metadata: Some(CatalogTypePgMetadata {
1553            typinput_oid: 750,
1554            typreceive_oid: 2400,
1555        }),
1556    },
1557};
1558
1559pub const TYPE_NUM_RANGE: BuiltinType<NameReference> = BuiltinType {
1560    name: "numrange",
1561    schema: PG_CATALOG_SCHEMA,
1562    oid: mz_pgrepr::oid::TYPE_NUMRANGE_OID,
1563    details: CatalogTypeDetails {
1564        typ: CatalogType::Range {
1565            element_reference: TYPE_NUMERIC.name,
1566        },
1567        array_id: None,
1568        pg_metadata: Some(CatalogTypePgMetadata {
1569            typinput_oid: 3834,
1570            typreceive_oid: 3836,
1571        }),
1572    },
1573};
1574
1575pub const TYPE_NUM_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1576    name: "_numrange",
1577    schema: PG_CATALOG_SCHEMA,
1578    oid: mz_pgrepr::oid::TYPE_NUMRANGE_ARRAY_OID,
1579    details: CatalogTypeDetails {
1580        typ: CatalogType::Array {
1581            element_reference: TYPE_NUM_RANGE.name,
1582        },
1583        array_id: None,
1584        pg_metadata: Some(CatalogTypePgMetadata {
1585            typinput_oid: 750,
1586            typreceive_oid: 2400,
1587        }),
1588    },
1589};
1590
1591pub const TYPE_TS_RANGE: BuiltinType<NameReference> = BuiltinType {
1592    name: "tsrange",
1593    schema: PG_CATALOG_SCHEMA,
1594    oid: mz_pgrepr::oid::TYPE_TSRANGE_OID,
1595    details: CatalogTypeDetails {
1596        typ: CatalogType::Range {
1597            element_reference: TYPE_TIMESTAMP.name,
1598        },
1599        array_id: None,
1600        pg_metadata: Some(CatalogTypePgMetadata {
1601            typinput_oid: 3834,
1602            typreceive_oid: 3836,
1603        }),
1604    },
1605};
1606
1607pub const TYPE_TS_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1608    name: "_tsrange",
1609    schema: PG_CATALOG_SCHEMA,
1610    oid: mz_pgrepr::oid::TYPE_TSRANGE_ARRAY_OID,
1611    details: CatalogTypeDetails {
1612        typ: CatalogType::Array {
1613            element_reference: TYPE_TS_RANGE.name,
1614        },
1615        array_id: None,
1616        pg_metadata: Some(CatalogTypePgMetadata {
1617            typinput_oid: 750,
1618            typreceive_oid: 2400,
1619        }),
1620    },
1621};
1622
1623pub const TYPE_TSTZ_RANGE: BuiltinType<NameReference> = BuiltinType {
1624    name: "tstzrange",
1625    schema: PG_CATALOG_SCHEMA,
1626    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_OID,
1627    details: CatalogTypeDetails {
1628        typ: CatalogType::Range {
1629            element_reference: TYPE_TIMESTAMPTZ.name,
1630        },
1631        array_id: None,
1632        pg_metadata: Some(CatalogTypePgMetadata {
1633            typinput_oid: 3834,
1634            typreceive_oid: 3836,
1635        }),
1636    },
1637};
1638
1639pub const TYPE_TSTZ_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1640    name: "_tstzrange",
1641    schema: PG_CATALOG_SCHEMA,
1642    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_ARRAY_OID,
1643    details: CatalogTypeDetails {
1644        typ: CatalogType::Array {
1645            element_reference: TYPE_TSTZ_RANGE.name,
1646        },
1647        array_id: None,
1648        pg_metadata: Some(CatalogTypePgMetadata {
1649            typinput_oid: 750,
1650            typreceive_oid: 2400,
1651        }),
1652    },
1653};
1654
1655pub const TYPE_MZ_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1656    name: "mz_aclitem",
1657    schema: MZ_CATALOG_SCHEMA,
1658    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_OID,
1659    details: CatalogTypeDetails {
1660        typ: CatalogType::MzAclItem,
1661        array_id: None,
1662        pg_metadata: None,
1663    },
1664};
1665
1666pub const TYPE_MZ_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1667    name: "_mz_aclitem",
1668    schema: MZ_CATALOG_SCHEMA,
1669    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_ARRAY_OID,
1670    details: CatalogTypeDetails {
1671        typ: CatalogType::Array {
1672            element_reference: TYPE_MZ_ACL_ITEM.name,
1673        },
1674        array_id: None,
1675        pg_metadata: Some(CatalogTypePgMetadata {
1676            typinput_oid: 750,
1677            typreceive_oid: 2400,
1678        }),
1679    },
1680};
1681
1682pub const TYPE_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1683    name: "aclitem",
1684    schema: PG_CATALOG_SCHEMA,
1685    oid: 1033,
1686    details: CatalogTypeDetails {
1687        typ: CatalogType::AclItem,
1688        array_id: None,
1689        pg_metadata: Some(CatalogTypePgMetadata {
1690            typinput_oid: 1031,
1691            typreceive_oid: 0,
1692        }),
1693    },
1694};
1695
1696pub const TYPE_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1697    name: "_aclitem",
1698    schema: PG_CATALOG_SCHEMA,
1699    oid: 1034,
1700    details: CatalogTypeDetails {
1701        typ: CatalogType::Array {
1702            element_reference: TYPE_ACL_ITEM.name,
1703        },
1704        array_id: None,
1705        pg_metadata: Some(CatalogTypePgMetadata {
1706            typinput_oid: 750,
1707            typreceive_oid: 2400,
1708        }),
1709    },
1710};
1711
1712pub const TYPE_INTERNAL: BuiltinType<NameReference> = BuiltinType {
1713    name: "internal",
1714    schema: PG_CATALOG_SCHEMA,
1715    oid: 2281,
1716    details: CatalogTypeDetails {
1717        typ: CatalogType::Pseudo,
1718        array_id: None,
1719        pg_metadata: Some(CatalogTypePgMetadata {
1720            typinput_oid: 2304,
1721            typreceive_oid: 0,
1722        }),
1723    },
1724};
1725
1726const PUBLIC_SELECT: MzAclItem = MzAclItem {
1727    grantee: RoleId::Public,
1728    grantor: MZ_SYSTEM_ROLE_ID,
1729    acl_mode: AclMode::SELECT,
1730};
1731
1732const SUPPORT_SELECT: MzAclItem = MzAclItem {
1733    grantee: MZ_SUPPORT_ROLE_ID,
1734    grantor: MZ_SYSTEM_ROLE_ID,
1735    acl_mode: AclMode::SELECT,
1736};
1737
1738const ANALYTICS_SELECT: MzAclItem = MzAclItem {
1739    grantee: MZ_ANALYTICS_ROLE_ID,
1740    grantor: MZ_SYSTEM_ROLE_ID,
1741    acl_mode: AclMode::SELECT,
1742};
1743
1744const MONITOR_SELECT: MzAclItem = MzAclItem {
1745    grantee: MZ_MONITOR_ROLE_ID,
1746    grantor: MZ_SYSTEM_ROLE_ID,
1747    acl_mode: AclMode::SELECT,
1748};
1749
1750const MONITOR_REDACTED_SELECT: MzAclItem = MzAclItem {
1751    grantee: MZ_MONITOR_REDACTED_ROLE_ID,
1752    grantor: MZ_SYSTEM_ROLE_ID,
1753    acl_mode: AclMode::SELECT,
1754};
1755
1756pub static MZ_DATAFLOW_OPERATORS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1757    name: "mz_dataflow_operators_per_worker",
1758    schema: MZ_INTROSPECTION_SCHEMA,
1759    oid: oid::LOG_MZ_DATAFLOW_OPERATORS_PER_WORKER_OID,
1760    variant: LogVariant::Timely(TimelyLog::Operates),
1761    access: vec![PUBLIC_SELECT],
1762});
1763
1764pub static MZ_DATAFLOW_ADDRESSES_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1765    name: "mz_dataflow_addresses_per_worker",
1766    schema: MZ_INTROSPECTION_SCHEMA,
1767    oid: oid::LOG_MZ_DATAFLOW_ADDRESSES_PER_WORKER_OID,
1768    variant: LogVariant::Timely(TimelyLog::Addresses),
1769    access: vec![PUBLIC_SELECT],
1770});
1771
1772pub static MZ_DATAFLOW_CHANNELS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1773    name: "mz_dataflow_channels_per_worker",
1774    schema: MZ_INTROSPECTION_SCHEMA,
1775    oid: oid::LOG_MZ_DATAFLOW_CHANNELS_PER_WORKER_OID,
1776    variant: LogVariant::Timely(TimelyLog::Channels),
1777    access: vec![PUBLIC_SELECT],
1778});
1779
1780pub static MZ_SCHEDULING_ELAPSED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1781    name: "mz_scheduling_elapsed_raw",
1782    schema: MZ_INTROSPECTION_SCHEMA,
1783    oid: oid::LOG_MZ_SCHEDULING_ELAPSED_RAW_OID,
1784    variant: LogVariant::Timely(TimelyLog::Elapsed),
1785    access: vec![PUBLIC_SELECT],
1786});
1787
1788pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1789    LazyLock::new(|| BuiltinLog {
1790        name: "mz_compute_operator_durations_histogram_raw",
1791        schema: MZ_INTROSPECTION_SCHEMA,
1792        oid: oid::LOG_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW_OID,
1793        variant: LogVariant::Timely(TimelyLog::Histogram),
1794        access: vec![PUBLIC_SELECT],
1795    });
1796
1797pub static MZ_SCHEDULING_PARKS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1798    name: "mz_scheduling_parks_histogram_raw",
1799    schema: MZ_INTROSPECTION_SCHEMA,
1800    oid: oid::LOG_MZ_SCHEDULING_PARKS_HISTOGRAM_RAW_OID,
1801    variant: LogVariant::Timely(TimelyLog::Parks),
1802    access: vec![PUBLIC_SELECT],
1803});
1804
1805pub static MZ_ARRANGEMENT_RECORDS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1806    name: "mz_arrangement_records_raw",
1807    schema: MZ_INTROSPECTION_SCHEMA,
1808    oid: oid::LOG_MZ_ARRANGEMENT_RECORDS_RAW_OID,
1809    variant: LogVariant::Differential(DifferentialLog::ArrangementRecords),
1810    access: vec![PUBLIC_SELECT],
1811});
1812
1813pub static MZ_ARRANGEMENT_BATCHES_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1814    name: "mz_arrangement_batches_raw",
1815    schema: MZ_INTROSPECTION_SCHEMA,
1816    oid: oid::LOG_MZ_ARRANGEMENT_BATCHES_RAW_OID,
1817    variant: LogVariant::Differential(DifferentialLog::ArrangementBatches),
1818    access: vec![PUBLIC_SELECT],
1819});
1820
1821pub static MZ_ARRANGEMENT_SHARING_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1822    name: "mz_arrangement_sharing_raw",
1823    schema: MZ_INTROSPECTION_SCHEMA,
1824    oid: oid::LOG_MZ_ARRANGEMENT_SHARING_RAW_OID,
1825    variant: LogVariant::Differential(DifferentialLog::Sharing),
1826    access: vec![PUBLIC_SELECT],
1827});
1828
1829pub static MZ_ARRANGEMENT_BATCHER_RECORDS_RAW: LazyLock<BuiltinLog> =
1830    LazyLock::new(|| BuiltinLog {
1831        name: "mz_arrangement_batcher_records_raw",
1832        schema: MZ_INTROSPECTION_SCHEMA,
1833        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_RECORDS_RAW_OID,
1834        variant: LogVariant::Differential(DifferentialLog::BatcherRecords),
1835        access: vec![PUBLIC_SELECT],
1836    });
1837
1838pub static MZ_ARRANGEMENT_BATCHER_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1839    name: "mz_arrangement_batcher_size_raw",
1840    schema: MZ_INTROSPECTION_SCHEMA,
1841    oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_SIZE_RAW_OID,
1842    variant: LogVariant::Differential(DifferentialLog::BatcherSize),
1843    access: vec![PUBLIC_SELECT],
1844});
1845
1846pub static MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW: LazyLock<BuiltinLog> =
1847    LazyLock::new(|| BuiltinLog {
1848        name: "mz_arrangement_batcher_capacity_raw",
1849        schema: MZ_INTROSPECTION_SCHEMA,
1850        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW_OID,
1851        variant: LogVariant::Differential(DifferentialLog::BatcherCapacity),
1852        access: vec![PUBLIC_SELECT],
1853    });
1854
1855pub static MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1856    LazyLock::new(|| BuiltinLog {
1857        name: "mz_arrangement_batcher_allocations_raw",
1858        schema: MZ_INTROSPECTION_SCHEMA,
1859        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW_OID,
1860        variant: LogVariant::Differential(DifferentialLog::BatcherAllocations),
1861        access: vec![PUBLIC_SELECT],
1862    });
1863
1864pub static MZ_COMPUTE_EXPORTS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1865    name: "mz_compute_exports_per_worker",
1866    schema: MZ_INTROSPECTION_SCHEMA,
1867    oid: oid::LOG_MZ_COMPUTE_EXPORTS_PER_WORKER_OID,
1868    variant: LogVariant::Compute(ComputeLog::DataflowCurrent),
1869    access: vec![PUBLIC_SELECT],
1870});
1871
1872pub static MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER: LazyLock<BuiltinLog> =
1873    LazyLock::new(|| BuiltinLog {
1874        name: "mz_compute_dataflow_global_ids_per_worker",
1875        schema: MZ_INTROSPECTION_SCHEMA,
1876        oid: oid::LOG_MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER_OID,
1877        variant: LogVariant::Compute(ComputeLog::DataflowGlobal),
1878        access: vec![PUBLIC_SELECT],
1879    });
1880
1881pub static MZ_COMPUTE_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1882    name: "mz_compute_frontiers_per_worker",
1883    schema: MZ_INTROSPECTION_SCHEMA,
1884    oid: oid::LOG_MZ_COMPUTE_FRONTIERS_PER_WORKER_OID,
1885    variant: LogVariant::Compute(ComputeLog::FrontierCurrent),
1886    access: vec![PUBLIC_SELECT],
1887});
1888
1889pub static MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> =
1890    LazyLock::new(|| BuiltinLog {
1891        name: "mz_compute_import_frontiers_per_worker",
1892        schema: MZ_INTROSPECTION_SCHEMA,
1893        oid: oid::LOG_MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER_OID,
1894        variant: LogVariant::Compute(ComputeLog::ImportFrontierCurrent),
1895        access: vec![PUBLIC_SELECT],
1896    });
1897
1898pub static MZ_COMPUTE_ERROR_COUNTS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1899    name: "mz_compute_error_counts_raw",
1900    schema: MZ_INTROSPECTION_SCHEMA,
1901    oid: oid::LOG_MZ_COMPUTE_ERROR_COUNTS_RAW_OID,
1902    variant: LogVariant::Compute(ComputeLog::ErrorCount),
1903    access: vec![PUBLIC_SELECT],
1904});
1905
1906pub static MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER: LazyLock<BuiltinLog> =
1907    LazyLock::new(|| BuiltinLog {
1908        name: "mz_compute_hydration_times_per_worker",
1909        schema: MZ_INTROSPECTION_SCHEMA,
1910        oid: oid::LOG_MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER_OID,
1911        variant: LogVariant::Compute(ComputeLog::HydrationTime),
1912        access: vec![PUBLIC_SELECT],
1913    });
1914
1915pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER: LazyLock<BuiltinLog> =
1916    LazyLock::new(|| BuiltinLog {
1917        name: "mz_compute_operator_hydration_statuses_per_worker",
1918        schema: MZ_INTROSPECTION_SCHEMA,
1919        oid: oid::LOG_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER_OID,
1920        variant: LogVariant::Compute(ComputeLog::OperatorHydrationStatus),
1921        access: vec![PUBLIC_SELECT],
1922    });
1923
1924pub static MZ_ACTIVE_PEEKS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1925    name: "mz_active_peeks_per_worker",
1926    schema: MZ_INTROSPECTION_SCHEMA,
1927    oid: oid::LOG_MZ_ACTIVE_PEEKS_PER_WORKER_OID,
1928    variant: LogVariant::Compute(ComputeLog::PeekCurrent),
1929    access: vec![PUBLIC_SELECT],
1930});
1931
1932pub static MZ_COMPUTE_LIR_MAPPING_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1933    name: "mz_compute_lir_mapping_per_worker",
1934    schema: MZ_INTROSPECTION_SCHEMA,
1935    oid: oid::LOG_MZ_COMPUTE_LIR_MAPPING_PER_WORKER_OID,
1936    variant: LogVariant::Compute(ComputeLog::LirMapping),
1937    access: vec![PUBLIC_SELECT],
1938});
1939
1940pub static MZ_PEEK_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1941    name: "mz_peek_durations_histogram_raw",
1942    schema: MZ_INTROSPECTION_SCHEMA,
1943    oid: oid::LOG_MZ_PEEK_DURATIONS_HISTOGRAM_RAW_OID,
1944    variant: LogVariant::Compute(ComputeLog::PeekDuration),
1945    access: vec![PUBLIC_SELECT],
1946});
1947
1948pub static MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1949    LazyLock::new(|| BuiltinLog {
1950        name: "mz_dataflow_shutdown_durations_histogram_raw",
1951        schema: MZ_INTROSPECTION_SCHEMA,
1952        oid: oid::LOG_MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_RAW_OID,
1953        variant: LogVariant::Compute(ComputeLog::ShutdownDuration),
1954        access: vec![PUBLIC_SELECT],
1955    });
1956
1957pub static MZ_ARRANGEMENT_HEAP_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1958    name: "mz_arrangement_heap_size_raw",
1959    schema: MZ_INTROSPECTION_SCHEMA,
1960    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_SIZE_RAW_OID,
1961    variant: LogVariant::Compute(ComputeLog::ArrangementHeapSize),
1962    access: vec![PUBLIC_SELECT],
1963});
1964
1965pub static MZ_ARRANGEMENT_HEAP_CAPACITY_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1966    name: "mz_arrangement_heap_capacity_raw",
1967    schema: MZ_INTROSPECTION_SCHEMA,
1968    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_CAPACITY_RAW_OID,
1969    variant: LogVariant::Compute(ComputeLog::ArrangementHeapCapacity),
1970    access: vec![PUBLIC_SELECT],
1971});
1972
1973pub static MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1974    LazyLock::new(|| BuiltinLog {
1975        name: "mz_arrangement_heap_allocations_raw",
1976        schema: MZ_INTROSPECTION_SCHEMA,
1977        oid: oid::LOG_MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW_OID,
1978        variant: LogVariant::Compute(ComputeLog::ArrangementHeapAllocations),
1979        access: vec![PUBLIC_SELECT],
1980    });
1981
1982pub static MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> =
1983    LazyLock::new(|| BuiltinLog {
1984        name: "mz_message_batch_counts_received_raw",
1985        schema: MZ_INTROSPECTION_SCHEMA,
1986        oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW_OID,
1987        variant: LogVariant::Timely(TimelyLog::BatchesReceived),
1988        access: vec![PUBLIC_SELECT],
1989    });
1990
1991pub static MZ_MESSAGE_BATCH_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1992    name: "mz_message_batch_counts_sent_raw",
1993    schema: MZ_INTROSPECTION_SCHEMA,
1994    oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_SENT_RAW_OID,
1995    variant: LogVariant::Timely(TimelyLog::BatchesSent),
1996    access: vec![PUBLIC_SELECT],
1997});
1998
1999pub static MZ_MESSAGE_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2000    name: "mz_message_counts_received_raw",
2001    schema: MZ_INTROSPECTION_SCHEMA,
2002    oid: oid::LOG_MZ_MESSAGE_COUNTS_RECEIVED_RAW_OID,
2003    variant: LogVariant::Timely(TimelyLog::MessagesReceived),
2004    access: vec![PUBLIC_SELECT],
2005});
2006
2007pub static MZ_MESSAGE_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2008    name: "mz_message_counts_sent_raw",
2009    schema: MZ_INTROSPECTION_SCHEMA,
2010    oid: oid::LOG_MZ_MESSAGE_COUNTS_SENT_RAW_OID,
2011    variant: LogVariant::Timely(TimelyLog::MessagesSent),
2012    access: vec![PUBLIC_SELECT],
2013});
2014
2015pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW: LazyLock<BuiltinLog> =
2016    LazyLock::new(|| BuiltinLog {
2017        name: "mz_dataflow_operator_reachability_raw",
2018        schema: MZ_INTROSPECTION_SCHEMA,
2019        oid: oid::LOG_MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW_OID,
2020        variant: LogVariant::Timely(TimelyLog::Reachability),
2021        access: vec![PUBLIC_SELECT],
2022    });
2023
2024pub static MZ_ICEBERG_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2025    name: "mz_iceberg_sinks",
2026    schema: MZ_CATALOG_SCHEMA,
2027    oid: oid::TABLE_MZ_ICEBERG_SINKS_OID,
2028    desc: RelationDesc::builder()
2029        .with_column("id", SqlScalarType::String.nullable(false))
2030        .with_column("namespace", SqlScalarType::String.nullable(false))
2031        .with_column("table", SqlScalarType::String.nullable(false))
2032        .finish(),
2033    column_comments: BTreeMap::from_iter([
2034        ("id", "The ID of the sink."),
2035        ("namespace", "The namespace of the sink."),
2036        ("table", "The table the sink is writing to."),
2037    ]),
2038    is_retained_metrics_object: false,
2039    access: vec![PUBLIC_SELECT],
2040});
2041
2042pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2043    name: "mz_kafka_sinks",
2044    schema: MZ_CATALOG_SCHEMA,
2045    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2046    desc: RelationDesc::builder()
2047        .with_column("id", SqlScalarType::String.nullable(false))
2048        .with_column("topic", SqlScalarType::String.nullable(false))
2049        .with_key(vec![0])
2050        .finish(),
2051    column_comments: BTreeMap::from_iter([
2052        ("id", "The ID of the sink."),
2053        (
2054            "topic",
2055            "The name of the Kafka topic into which the sink is writing.",
2056        ),
2057    ]),
2058    is_retained_metrics_object: false,
2059    access: vec![PUBLIC_SELECT],
2060});
2061pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2062    name: "mz_kafka_connections",
2063    schema: MZ_CATALOG_SCHEMA,
2064    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2065    desc: RelationDesc::builder()
2066        .with_column("id", SqlScalarType::String.nullable(false))
2067        .with_column(
2068            "brokers",
2069            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2070        )
2071        .with_column("sink_progress_topic", SqlScalarType::String.nullable(false))
2072        .finish(),
2073    column_comments: BTreeMap::from_iter([
2074        ("id", "The ID of the connection."),
2075        (
2076            "brokers",
2077            "The addresses of the Kafka brokers to connect to.",
2078        ),
2079        (
2080            "sink_progress_topic",
2081            "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.",
2082        ),
2083    ]),
2084    is_retained_metrics_object: false,
2085    access: vec![PUBLIC_SELECT],
2086});
2087pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2088    name: "mz_kafka_sources",
2089    schema: MZ_CATALOG_SCHEMA,
2090    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2091    desc: RelationDesc::builder()
2092        .with_column("id", SqlScalarType::String.nullable(false))
2093        .with_column("group_id_prefix", SqlScalarType::String.nullable(false))
2094        .with_column("topic", SqlScalarType::String.nullable(false))
2095        .finish(),
2096    column_comments: BTreeMap::from_iter([
2097        (
2098            "id",
2099            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2100        ),
2101        (
2102            "group_id_prefix",
2103            "The value of the `GROUP ID PREFIX` connection option.",
2104        ),
2105        (
2106            "topic",
2107            "The name of the Kafka topic the source is reading from.",
2108        ),
2109    ]),
2110    is_retained_metrics_object: false,
2111    access: vec![PUBLIC_SELECT],
2112});
2113pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2114    name: "mz_postgres_sources",
2115    schema: MZ_INTERNAL_SCHEMA,
2116    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2117    desc: RelationDesc::builder()
2118        .with_column("id", SqlScalarType::String.nullable(false))
2119        .with_column("replication_slot", SqlScalarType::String.nullable(false))
2120        .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
2121        .finish(),
2122    column_comments: BTreeMap::from_iter([
2123        (
2124            "id",
2125            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2126        ),
2127        (
2128            "replication_slot",
2129            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2130        ),
2131        (
2132            "timeline_id",
2133            "The PostgreSQL timeline ID determined on source creation.",
2134        ),
2135    ]),
2136    is_retained_metrics_object: false,
2137    access: vec![PUBLIC_SELECT],
2138});
2139pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2140    name: "mz_postgres_source_tables",
2141    schema: MZ_INTERNAL_SCHEMA,
2142    oid: oid::TABLE_MZ_POSTGRES_SOURCE_TABLES_OID,
2143    desc: RelationDesc::builder()
2144        .with_column("id", SqlScalarType::String.nullable(false))
2145        .with_column("schema_name", SqlScalarType::String.nullable(false))
2146        .with_column("table_name", SqlScalarType::String.nullable(false))
2147        .finish(),
2148    column_comments: BTreeMap::from_iter([
2149        (
2150            "id",
2151            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2152        ),
2153        (
2154            "schema_name",
2155            "The schema of the upstream table being ingested.",
2156        ),
2157        (
2158            "table_name",
2159            "The name of the upstream table being ingested.",
2160        ),
2161    ]),
2162    is_retained_metrics_object: true,
2163    access: vec![PUBLIC_SELECT],
2164});
2165pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2166    name: "mz_mysql_source_tables",
2167    schema: MZ_INTERNAL_SCHEMA,
2168    oid: oid::TABLE_MZ_MYSQL_SOURCE_TABLES_OID,
2169    desc: RelationDesc::builder()
2170        .with_column("id", SqlScalarType::String.nullable(false))
2171        .with_column("schema_name", SqlScalarType::String.nullable(false))
2172        .with_column("table_name", SqlScalarType::String.nullable(false))
2173        .finish(),
2174    column_comments: BTreeMap::from_iter([
2175        (
2176            "id",
2177            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2178        ),
2179        (
2180            "schema_name",
2181            "The schema (or, database) of the upstream table being ingested.",
2182        ),
2183        (
2184            "table_name",
2185            "The name of the upstream table being ingested.",
2186        ),
2187    ]),
2188    is_retained_metrics_object: true,
2189    access: vec![PUBLIC_SELECT],
2190});
2191pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2192    name: "mz_sql_server_source_tables",
2193    schema: MZ_INTERNAL_SCHEMA,
2194    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2195    desc: RelationDesc::builder()
2196        .with_column("id", SqlScalarType::String.nullable(false))
2197        .with_column("schema_name", SqlScalarType::String.nullable(false))
2198        .with_column("table_name", SqlScalarType::String.nullable(false))
2199        .finish(),
2200    column_comments: BTreeMap::from_iter([
2201        (
2202            "id",
2203            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2204        ),
2205        (
2206            "schema_name",
2207            "The schema (or, database) of the upstream table being ingested.",
2208        ),
2209        (
2210            "table_name",
2211            "The name of the upstream table being ingested.",
2212        ),
2213    ]),
2214    is_retained_metrics_object: true,
2215    access: vec![PUBLIC_SELECT],
2216});
2217pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2218    name: "mz_kafka_source_tables",
2219    schema: MZ_INTERNAL_SCHEMA,
2220    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2221    desc: RelationDesc::builder()
2222        .with_column("id", SqlScalarType::String.nullable(false))
2223        .with_column("topic", SqlScalarType::String.nullable(false))
2224        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2225        .with_column("key_format", SqlScalarType::String.nullable(true))
2226        .with_column("value_format", SqlScalarType::String.nullable(true))
2227        .finish(),
2228    column_comments: BTreeMap::from_iter([
2229        (
2230            "id",
2231            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2232        ),
2233        ("topic", "The topic being ingested."),
2234        (
2235            "envelope_type",
2236            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2237        ),
2238        (
2239            "key_format",
2240            "The format of the Kafka message key: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2241        ),
2242        (
2243            "value_format",
2244            "The format of the Kafka message value: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2245        ),
2246    ]),
2247    is_retained_metrics_object: true,
2248    access: vec![PUBLIC_SELECT],
2249});
2250pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2251    name: "mz_object_dependencies",
2252    schema: MZ_INTERNAL_SCHEMA,
2253    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2254    desc: RelationDesc::builder()
2255        .with_column("object_id", SqlScalarType::String.nullable(false))
2256        .with_column(
2257            "referenced_object_id",
2258            SqlScalarType::String.nullable(false),
2259        )
2260        .finish(),
2261    column_comments: BTreeMap::from_iter([
2262        (
2263            "object_id",
2264            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2265        ),
2266        (
2267            "referenced_object_id",
2268            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2269        ),
2270    ]),
2271    is_retained_metrics_object: true,
2272    access: vec![PUBLIC_SELECT],
2273});
2274pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2275    name: "mz_compute_dependencies",
2276    schema: MZ_INTERNAL_SCHEMA,
2277    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2278    data_source: IntrospectionType::ComputeDependencies,
2279    desc: RelationDesc::builder()
2280        .with_column("object_id", SqlScalarType::String.nullable(false))
2281        .with_column("dependency_id", SqlScalarType::String.nullable(false))
2282        .finish(),
2283    column_comments: BTreeMap::from_iter([
2284        (
2285            "object_id",
2286            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2287        ),
2288        (
2289            "dependency_id",
2290            "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`.",
2291        ),
2292    ]),
2293    is_retained_metrics_object: false,
2294    access: vec![PUBLIC_SELECT],
2295});
2296
2297pub static MZ_DATABASES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2298    name: "mz_databases",
2299    schema: MZ_CATALOG_SCHEMA,
2300    oid: oid::TABLE_MZ_DATABASES_OID,
2301    desc: RelationDesc::builder()
2302        .with_column("id", SqlScalarType::String.nullable(false))
2303        .with_column("oid", SqlScalarType::Oid.nullable(false))
2304        .with_column("name", SqlScalarType::String.nullable(false))
2305        .with_column("owner_id", SqlScalarType::String.nullable(false))
2306        .with_column(
2307            "privileges",
2308            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2309        )
2310        .with_key(vec![0])
2311        .with_key(vec![1])
2312        .finish(),
2313    column_comments: BTreeMap::from_iter([
2314        ("id", "Materialize's unique ID for the database."),
2315        (
2316            "oid",
2317            "A [PostgreSQL-compatible OID][`oid`] for the database.",
2318        ),
2319        ("name", "The name of the database."),
2320        (
2321            "owner_id",
2322            "The role ID of the owner of the database. Corresponds to `mz_roles.id`.",
2323        ),
2324        ("privileges", "The privileges belonging to the database."),
2325    ]),
2326    is_retained_metrics_object: false,
2327    access: vec![PUBLIC_SELECT],
2328});
2329pub static MZ_SCHEMAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2330    name: "mz_schemas",
2331    schema: MZ_CATALOG_SCHEMA,
2332    oid: oid::TABLE_MZ_SCHEMAS_OID,
2333    desc: RelationDesc::builder()
2334        .with_column("id", SqlScalarType::String.nullable(false))
2335        .with_column("oid", SqlScalarType::Oid.nullable(false))
2336        .with_column("database_id", SqlScalarType::String.nullable(true))
2337        .with_column("name", SqlScalarType::String.nullable(false))
2338        .with_column("owner_id", SqlScalarType::String.nullable(false))
2339        .with_column(
2340            "privileges",
2341            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2342        )
2343        .with_key(vec![0])
2344        .with_key(vec![1])
2345        .finish(),
2346    column_comments: BTreeMap::from_iter([
2347        ("id", "Materialize's unique ID for the schema."),
2348        (
2349            "oid",
2350            "A [PostgreSQL-compatible oid][`oid`] for the schema.",
2351        ),
2352        (
2353            "database_id",
2354            "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2355        ),
2356        ("name", "The name of the schema."),
2357        (
2358            "owner_id",
2359            "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2360        ),
2361        ("privileges", "The privileges belonging to the schema."),
2362    ]),
2363    is_retained_metrics_object: false,
2364    access: vec![PUBLIC_SELECT],
2365});
2366pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2367    name: "mz_columns",
2368    schema: MZ_CATALOG_SCHEMA,
2369    oid: oid::TABLE_MZ_COLUMNS_OID,
2370    desc: RelationDesc::builder()
2371        .with_column("id", SqlScalarType::String.nullable(false)) // not a key
2372        .with_column("name", SqlScalarType::String.nullable(false))
2373        .with_column("position", SqlScalarType::UInt64.nullable(false))
2374        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2375        .with_column("type", SqlScalarType::String.nullable(false))
2376        .with_column("default", SqlScalarType::String.nullable(true))
2377        .with_column("type_oid", SqlScalarType::Oid.nullable(false))
2378        .with_column("type_mod", SqlScalarType::Int32.nullable(false))
2379        .finish(),
2380    column_comments: BTreeMap::from_iter([
2381        (
2382            "id",
2383            "The unique ID of the table, source, or view containing the column.",
2384        ),
2385        ("name", "The name of the column."),
2386        (
2387            "position",
2388            "The 1-indexed position of the column in its containing table, source, or view.",
2389        ),
2390        ("nullable", "Can the column contain a `NULL` value?"),
2391        ("type", "The data type of the column."),
2392        ("default", "The default expression of the column."),
2393        (
2394            "type_oid",
2395            "The OID of the type of the column (references `mz_types`).",
2396        ),
2397        ("type_mod", "The packed type identifier of the column."),
2398    ]),
2399    is_retained_metrics_object: false,
2400    access: vec![PUBLIC_SELECT],
2401});
2402pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2403    name: "mz_indexes",
2404    schema: MZ_CATALOG_SCHEMA,
2405    oid: oid::TABLE_MZ_INDEXES_OID,
2406    desc: RelationDesc::builder()
2407        .with_column("id", SqlScalarType::String.nullable(false))
2408        .with_column("oid", SqlScalarType::Oid.nullable(false))
2409        .with_column("name", SqlScalarType::String.nullable(false))
2410        .with_column("on_id", SqlScalarType::String.nullable(false))
2411        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2412        .with_column("owner_id", SqlScalarType::String.nullable(false))
2413        .with_column("create_sql", SqlScalarType::String.nullable(false))
2414        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2415        .with_key(vec![0])
2416        .with_key(vec![1])
2417        .finish(),
2418    column_comments: BTreeMap::from_iter([
2419        ("id", "Materialize's unique ID for the index."),
2420        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the index."),
2421        ("name", "The name of the index."),
2422        (
2423            "on_id",
2424            "The ID of the relation on which the index is built.",
2425        ),
2426        (
2427            "cluster_id",
2428            "The ID of the cluster in which the index is built.",
2429        ),
2430        (
2431            "owner_id",
2432            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2433        ),
2434        ("create_sql", "The `CREATE` SQL statement for the index."),
2435        (
2436            "redacted_create_sql",
2437            "The redacted `CREATE` SQL statement for the index.",
2438        ),
2439    ]),
2440    is_retained_metrics_object: false,
2441    access: vec![PUBLIC_SELECT],
2442});
2443pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2444    name: "mz_index_columns",
2445    schema: MZ_CATALOG_SCHEMA,
2446    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2447    desc: RelationDesc::builder()
2448        .with_column("index_id", SqlScalarType::String.nullable(false))
2449        .with_column("index_position", SqlScalarType::UInt64.nullable(false))
2450        .with_column("on_position", SqlScalarType::UInt64.nullable(true))
2451        .with_column("on_expression", SqlScalarType::String.nullable(true))
2452        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2453        .finish(),
2454    column_comments: BTreeMap::from_iter([
2455        (
2456            "index_id",
2457            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2458        ),
2459        (
2460            "index_position",
2461            "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.)",
2462        ),
2463        (
2464            "on_position",
2465            "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.",
2466        ),
2467        (
2468            "on_expression",
2469            "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.",
2470        ),
2471        (
2472            "nullable",
2473            "Can this column of the index evaluate to `NULL`?",
2474        ),
2475    ]),
2476    is_retained_metrics_object: false,
2477    access: vec![PUBLIC_SELECT],
2478});
2479pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2480    name: "mz_tables",
2481    schema: MZ_CATALOG_SCHEMA,
2482    oid: oid::TABLE_MZ_TABLES_OID,
2483    desc: RelationDesc::builder()
2484        .with_column("id", SqlScalarType::String.nullable(false))
2485        .with_column("oid", SqlScalarType::Oid.nullable(false))
2486        .with_column("schema_id", SqlScalarType::String.nullable(false))
2487        .with_column("name", SqlScalarType::String.nullable(false))
2488        .with_column("owner_id", SqlScalarType::String.nullable(false))
2489        .with_column(
2490            "privileges",
2491            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2492        )
2493        .with_column("create_sql", SqlScalarType::String.nullable(true))
2494        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2495        .with_column("source_id", SqlScalarType::String.nullable(true))
2496        .with_key(vec![0])
2497        .with_key(vec![1])
2498        .finish(),
2499    column_comments: BTreeMap::from_iter([
2500        ("id", "Materialize's unique ID for the table."),
2501        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the table."),
2502        (
2503            "schema_id",
2504            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2505        ),
2506        ("name", "The name of the table."),
2507        (
2508            "owner_id",
2509            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2510        ),
2511        ("privileges", "The privileges belonging to the table."),
2512        ("create_sql", "The `CREATE` SQL statement for the table."),
2513        (
2514            "redacted_create_sql",
2515            "The redacted `CREATE` SQL statement for the table.",
2516        ),
2517        (
2518            "source_id",
2519            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2520        ),
2521    ]),
2522    is_retained_metrics_object: true,
2523    access: vec![PUBLIC_SELECT],
2524});
2525pub static MZ_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2526    name: "mz_connections",
2527    schema: MZ_CATALOG_SCHEMA,
2528    oid: oid::TABLE_MZ_CONNECTIONS_OID,
2529    desc: RelationDesc::builder()
2530        .with_column("id", SqlScalarType::String.nullable(false))
2531        .with_column("oid", SqlScalarType::Oid.nullable(false))
2532        .with_column("schema_id", SqlScalarType::String.nullable(false))
2533        .with_column("name", SqlScalarType::String.nullable(false))
2534        .with_column("type", SqlScalarType::String.nullable(false))
2535        .with_column("owner_id", SqlScalarType::String.nullable(false))
2536        .with_column(
2537            "privileges",
2538            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2539        )
2540        .with_column("create_sql", SqlScalarType::String.nullable(false))
2541        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2542        .with_key(vec![0])
2543        .with_key(vec![1])
2544        .finish(),
2545    column_comments: BTreeMap::from_iter([
2546        ("id", "The unique ID of the connection."),
2547        (
2548            "oid",
2549            "A [PostgreSQL-compatible OID][`oid`] for the connection.",
2550        ),
2551        (
2552            "schema_id",
2553            "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2554        ),
2555        ("name", "The name of the connection."),
2556        (
2557            "type",
2558            "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2559        ),
2560        (
2561            "owner_id",
2562            "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2563        ),
2564        ("privileges", "The privileges belonging to the connection."),
2565        (
2566            "create_sql",
2567            "The `CREATE` SQL statement for the connection.",
2568        ),
2569        (
2570            "redacted_create_sql",
2571            "The redacted `CREATE` SQL statement for the connection.",
2572        ),
2573    ]),
2574    is_retained_metrics_object: false,
2575    access: vec![PUBLIC_SELECT],
2576});
2577pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2578    name: "mz_ssh_tunnel_connections",
2579    schema: MZ_CATALOG_SCHEMA,
2580    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2581    desc: RelationDesc::builder()
2582        .with_column("id", SqlScalarType::String.nullable(false))
2583        .with_column("public_key_1", SqlScalarType::String.nullable(false))
2584        .with_column("public_key_2", SqlScalarType::String.nullable(false))
2585        .finish(),
2586    column_comments: BTreeMap::from_iter([
2587        ("id", "The ID of the connection."),
2588        (
2589            "public_key_1",
2590            "The first public key associated with the SSH tunnel.",
2591        ),
2592        (
2593            "public_key_2",
2594            "The second public key associated with the SSH tunnel.",
2595        ),
2596    ]),
2597    is_retained_metrics_object: false,
2598    access: vec![PUBLIC_SELECT],
2599});
2600pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2601    name: "mz_sources",
2602    schema: MZ_CATALOG_SCHEMA,
2603    oid: oid::TABLE_MZ_SOURCES_OID,
2604    desc: RelationDesc::builder()
2605        .with_column("id", SqlScalarType::String.nullable(false))
2606        .with_column("oid", SqlScalarType::Oid.nullable(false))
2607        .with_column("schema_id", SqlScalarType::String.nullable(false))
2608        .with_column("name", SqlScalarType::String.nullable(false))
2609        .with_column("type", SqlScalarType::String.nullable(false))
2610        .with_column("connection_id", SqlScalarType::String.nullable(true))
2611        .with_column("size", SqlScalarType::String.nullable(true))
2612        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2613        .with_column("key_format", SqlScalarType::String.nullable(true))
2614        .with_column("value_format", SqlScalarType::String.nullable(true))
2615        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2616        .with_column("owner_id", SqlScalarType::String.nullable(false))
2617        .with_column(
2618            "privileges",
2619            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2620        )
2621        .with_column("create_sql", SqlScalarType::String.nullable(true))
2622        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2623        .with_key(vec![0])
2624        .with_key(vec![1])
2625        .finish(),
2626    column_comments: BTreeMap::from_iter([
2627        ("id", "Materialize's unique ID for the source."),
2628        (
2629            "oid",
2630            "A [PostgreSQL-compatible OID][`oid`] for the source.",
2631        ),
2632        (
2633            "schema_id",
2634            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2635        ),
2636        ("name", "The name of the source."),
2637        (
2638            "type",
2639            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2640        ),
2641        (
2642            "connection_id",
2643            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2644        ),
2645        ("size", "Deprecated The size of the source."),
2646        (
2647            "envelope_type",
2648            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2649        ),
2650        (
2651            "key_format",
2652            "For Kafka sources, the format of the Kafka message key: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2653        ),
2654        (
2655            "value_format",
2656            "For Kafka sources, the format of the Kafka message value: `avro`, `protobuf`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2657        ),
2658        (
2659            "cluster_id",
2660            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2661        ),
2662        (
2663            "owner_id",
2664            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2665        ),
2666        ("privileges", "The privileges granted on the source."),
2667        ("create_sql", "The `CREATE` SQL statement for the source."),
2668        (
2669            "redacted_create_sql",
2670            "The redacted `CREATE` SQL statement for the source.",
2671        ),
2672    ]),
2673    is_retained_metrics_object: true,
2674    access: vec![PUBLIC_SELECT],
2675});
2676pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2677    BuiltinTable {
2678        name: "mz_sinks",
2679        schema: MZ_CATALOG_SCHEMA,
2680        oid: oid::TABLE_MZ_SINKS_OID,
2681        desc: RelationDesc::builder()
2682            .with_column("id", SqlScalarType::String.nullable(false))
2683            .with_column("oid", SqlScalarType::Oid.nullable(false))
2684            .with_column("schema_id", SqlScalarType::String.nullable(false))
2685            .with_column("name", SqlScalarType::String.nullable(false))
2686            .with_column("type", SqlScalarType::String.nullable(false))
2687            .with_column("connection_id", SqlScalarType::String.nullable(true))
2688            .with_column("size", SqlScalarType::String.nullable(true))
2689            .with_column("envelope_type", SqlScalarType::String.nullable(true))
2690            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2691            // below. This should be removed in the future.
2692            .with_column("format", SqlScalarType::String.nullable(true))
2693            .with_column("key_format", SqlScalarType::String.nullable(true))
2694            .with_column("value_format", SqlScalarType::String.nullable(true))
2695            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2696            .with_column("owner_id", SqlScalarType::String.nullable(false))
2697            .with_column("create_sql", SqlScalarType::String.nullable(false))
2698            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2699            .with_key(vec![0])
2700            .with_key(vec![1])
2701            .finish(),
2702        column_comments: BTreeMap::from_iter([
2703            ("id", "Materialize's unique ID for the sink."),
2704            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the sink."),
2705            (
2706                "schema_id",
2707                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2708            ),
2709            ("name", "The name of the sink."),
2710            ("type", "The type of the sink: `kafka`."),
2711            (
2712                "connection_id",
2713                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2714            ),
2715            ("size", "The size of the sink."),
2716            (
2717                "envelope_type",
2718                "The envelope of the sink: `upsert`, or `debezium`.",
2719            ),
2720            (
2721                "format",
2722                "Deprecated The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2723            ),
2724            (
2725                "key_format",
2726                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2727            ),
2728            (
2729                "value_format",
2730                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2731            ),
2732            (
2733                "cluster_id",
2734                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2735            ),
2736            (
2737                "owner_id",
2738                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2739            ),
2740            ("create_sql", "The `CREATE` SQL statement for the sink."),
2741            (
2742                "redacted_create_sql",
2743                "The redacted `CREATE` SQL statement for the sink.",
2744            ),
2745        ]),
2746        is_retained_metrics_object: true,
2747        access: vec![PUBLIC_SELECT],
2748    }
2749});
2750pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2751    name: "mz_views",
2752    schema: MZ_CATALOG_SCHEMA,
2753    oid: oid::TABLE_MZ_VIEWS_OID,
2754    desc: RelationDesc::builder()
2755        .with_column("id", SqlScalarType::String.nullable(false))
2756        .with_column("oid", SqlScalarType::Oid.nullable(false))
2757        .with_column("schema_id", SqlScalarType::String.nullable(false))
2758        .with_column("name", SqlScalarType::String.nullable(false))
2759        .with_column("definition", SqlScalarType::String.nullable(false))
2760        .with_column("owner_id", SqlScalarType::String.nullable(false))
2761        .with_column(
2762            "privileges",
2763            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2764        )
2765        .with_column("create_sql", SqlScalarType::String.nullable(false))
2766        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2767        .with_key(vec![0])
2768        .with_key(vec![1])
2769        .finish(),
2770    column_comments: BTreeMap::from_iter([
2771        ("id", "Materialize's unique ID for the view."),
2772        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the view."),
2773        (
2774            "schema_id",
2775            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2776        ),
2777        ("name", "The name of the view."),
2778        ("definition", "The view definition (a `SELECT` query)."),
2779        (
2780            "owner_id",
2781            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2782        ),
2783        ("privileges", "The privileges belonging to the view."),
2784        ("create_sql", "The `CREATE` SQL statement for the view."),
2785        (
2786            "redacted_create_sql",
2787            "The redacted `CREATE` SQL statement for the view.",
2788        ),
2789    ]),
2790    is_retained_metrics_object: false,
2791    access: vec![PUBLIC_SELECT],
2792});
2793pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2794    name: "mz_materialized_views",
2795    schema: MZ_CATALOG_SCHEMA,
2796    oid: oid::TABLE_MZ_MATERIALIZED_VIEWS_OID,
2797    desc: RelationDesc::builder()
2798        .with_column("id", SqlScalarType::String.nullable(false))
2799        .with_column("oid", SqlScalarType::Oid.nullable(false))
2800        .with_column("schema_id", SqlScalarType::String.nullable(false))
2801        .with_column("name", SqlScalarType::String.nullable(false))
2802        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2803        .with_column("definition", SqlScalarType::String.nullable(false))
2804        .with_column("owner_id", SqlScalarType::String.nullable(false))
2805        .with_column(
2806            "privileges",
2807            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2808        )
2809        .with_column("create_sql", SqlScalarType::String.nullable(false))
2810        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2811        .with_key(vec![0])
2812        .with_key(vec![1])
2813        .finish(),
2814    column_comments: BTreeMap::from_iter([
2815        ("id", "Materialize's unique ID for the materialized view."),
2816        (
2817            "oid",
2818            "A [PostgreSQL-compatible OID][`oid`] for the materialized view.",
2819        ),
2820        (
2821            "schema_id",
2822            "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2823        ),
2824        ("name", "The name of the materialized view."),
2825        (
2826            "cluster_id",
2827            "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2828        ),
2829        (
2830            "definition",
2831            "The materialized view definition (a `SELECT` query).",
2832        ),
2833        (
2834            "owner_id",
2835            "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2836        ),
2837        (
2838            "privileges",
2839            "The privileges belonging to the materialized view.",
2840        ),
2841        (
2842            "create_sql",
2843            "The `CREATE` SQL statement for the materialized view.",
2844        ),
2845        (
2846            "redacted_create_sql",
2847            "The redacted `CREATE` SQL statement for the materialized view.",
2848        ),
2849    ]),
2850    is_retained_metrics_object: false,
2851    access: vec![PUBLIC_SELECT],
2852});
2853pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
2854    BuiltinTable {
2855        name: "mz_materialized_view_refresh_strategies",
2856        schema: MZ_INTERNAL_SCHEMA,
2857        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
2858        desc: RelationDesc::builder()
2859            .with_column(
2860                "materialized_view_id",
2861                SqlScalarType::String.nullable(false),
2862            )
2863            .with_column("type", SqlScalarType::String.nullable(false))
2864            .with_column("interval", SqlScalarType::Interval.nullable(true))
2865            .with_column(
2866                "aligned_to",
2867                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2868            )
2869            .with_column(
2870                "at",
2871                SqlScalarType::TimestampTz { precision: None }.nullable(true),
2872            )
2873            .finish(),
2874        column_comments: BTreeMap::from_iter([
2875            (
2876                "materialized_view_id",
2877                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
2878            ),
2879            (
2880                "type",
2881                "`at`, `every`, or `on-commit`. Default: `on-commit`",
2882            ),
2883            (
2884                "interval",
2885                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2886            ),
2887            (
2888                "aligned_to",
2889                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
2890            ),
2891            (
2892                "at",
2893                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
2894            ),
2895        ]),
2896        is_retained_metrics_object: false,
2897        access: vec![PUBLIC_SELECT],
2898    }
2899});
2900pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2901    name: "mz_types",
2902    schema: MZ_CATALOG_SCHEMA,
2903    oid: oid::TABLE_MZ_TYPES_OID,
2904    desc: RelationDesc::builder()
2905        .with_column("id", SqlScalarType::String.nullable(false))
2906        .with_column("oid", SqlScalarType::Oid.nullable(false))
2907        .with_column("schema_id", SqlScalarType::String.nullable(false))
2908        .with_column("name", SqlScalarType::String.nullable(false))
2909        .with_column("category", SqlScalarType::String.nullable(false))
2910        .with_column("owner_id", SqlScalarType::String.nullable(false))
2911        .with_column(
2912            "privileges",
2913            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2914        )
2915        .with_column("create_sql", SqlScalarType::String.nullable(true))
2916        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2917        .with_key(vec![0])
2918        .with_key(vec![1])
2919        .finish(),
2920    column_comments: BTreeMap::from_iter([
2921        ("id", "Materialize's unique ID for the type."),
2922        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the type."),
2923        (
2924            "schema_id",
2925            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
2926        ),
2927        ("name", "The name of the type."),
2928        ("category", "The category of the type."),
2929        (
2930            "owner_id",
2931            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
2932        ),
2933        ("privileges", "The privileges belonging to the type."),
2934        ("create_sql", "The `CREATE` SQL statement for the type."),
2935        (
2936            "redacted_create_sql",
2937            "The redacted `CREATE` SQL statement for the type.",
2938        ),
2939    ]),
2940    is_retained_metrics_object: false,
2941    access: vec![PUBLIC_SELECT],
2942});
2943pub static MZ_CONTINUAL_TASKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2944    name: "mz_continual_tasks",
2945    schema: MZ_INTERNAL_SCHEMA,
2946    oid: oid::TABLE_MZ_CONTINUAL_TASKS_OID,
2947    desc: RelationDesc::builder()
2948        .with_column("id", SqlScalarType::String.nullable(false))
2949        .with_column("oid", SqlScalarType::Oid.nullable(false))
2950        .with_column("schema_id", SqlScalarType::String.nullable(false))
2951        .with_column("name", SqlScalarType::String.nullable(false))
2952        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2953        .with_column("definition", SqlScalarType::String.nullable(false))
2954        .with_column("owner_id", SqlScalarType::String.nullable(false))
2955        .with_column(
2956            "privileges",
2957            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2958        )
2959        .with_column("create_sql", SqlScalarType::String.nullable(false))
2960        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2961        .with_key(vec![0])
2962        .with_key(vec![1])
2963        .finish(),
2964    column_comments: BTreeMap::new(),
2965    is_retained_metrics_object: false,
2966    access: vec![PUBLIC_SELECT],
2967});
2968pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2969    name: "mz_network_policies",
2970    schema: MZ_INTERNAL_SCHEMA,
2971    oid: oid::TABLE_MZ_NETWORK_POLICIES_OID,
2972    desc: RelationDesc::builder()
2973        .with_column("id", SqlScalarType::String.nullable(false))
2974        .with_column("name", SqlScalarType::String.nullable(false))
2975        .with_column("owner_id", SqlScalarType::String.nullable(false))
2976        .with_column(
2977            "privileges",
2978            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2979        )
2980        .with_column("oid", SqlScalarType::Oid.nullable(false))
2981        .finish(),
2982    column_comments: BTreeMap::from_iter([
2983        ("id", "The ID of the network policy."),
2984        ("name", "The name of the network policy."),
2985        (
2986            "owner_id",
2987            "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
2988        ),
2989        (
2990            "privileges",
2991            "The privileges belonging to the network policy.",
2992        ),
2993        (
2994            "oid",
2995            "A [PostgreSQL-compatible OID][`oid`] for the network policy.",
2996        ),
2997    ]),
2998    is_retained_metrics_object: false,
2999    access: vec![PUBLIC_SELECT],
3000});
3001pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3002    name: "mz_network_policy_rules",
3003    schema: MZ_INTERNAL_SCHEMA,
3004    oid: oid::TABLE_MZ_NETWORK_POLICY_RULES_OID,
3005    desc: RelationDesc::builder()
3006        .with_column("name", SqlScalarType::String.nullable(false))
3007        .with_column("policy_id", SqlScalarType::String.nullable(false))
3008        .with_column("action", SqlScalarType::String.nullable(false))
3009        .with_column("address", SqlScalarType::String.nullable(false))
3010        .with_column("direction", SqlScalarType::String.nullable(false))
3011        .finish(),
3012    column_comments: BTreeMap::from_iter([
3013        (
3014            "name",
3015            "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
3016        ),
3017        (
3018            "policy_id",
3019            "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
3020        ),
3021        (
3022            "action",
3023            "The action of the rule. `allow` is the only supported action.",
3024        ),
3025        ("address", "The address the rule will take action on."),
3026        (
3027            "direction",
3028            "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3029        ),
3030    ]),
3031    is_retained_metrics_object: false,
3032    access: vec![PUBLIC_SELECT],
3033});
3034/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3035/// in the `mz_types` table as part of our public, stable API.
3036pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3037    name: "mz_type_pg_metadata",
3038    schema: MZ_INTERNAL_SCHEMA,
3039    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3040    desc: RelationDesc::builder()
3041        .with_column("id", SqlScalarType::String.nullable(false))
3042        .with_column("typinput", SqlScalarType::Oid.nullable(false))
3043        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
3044        .finish(),
3045    column_comments: BTreeMap::new(),
3046    is_retained_metrics_object: false,
3047    access: vec![PUBLIC_SELECT],
3048});
3049pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3050    name: "mz_array_types",
3051    schema: MZ_CATALOG_SCHEMA,
3052    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3053    desc: RelationDesc::builder()
3054        .with_column("id", SqlScalarType::String.nullable(false))
3055        .with_column("element_id", SqlScalarType::String.nullable(false))
3056        .finish(),
3057    column_comments: BTreeMap::from_iter([
3058        ("id", "The ID of the array type."),
3059        ("element_id", "The ID of the array's element type."),
3060    ]),
3061    is_retained_metrics_object: false,
3062    access: vec![PUBLIC_SELECT],
3063});
3064pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3065    name: "mz_base_types",
3066    schema: MZ_CATALOG_SCHEMA,
3067    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3068    desc: RelationDesc::builder()
3069        .with_column("id", SqlScalarType::String.nullable(false))
3070        .finish(),
3071    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3072    is_retained_metrics_object: false,
3073    access: vec![PUBLIC_SELECT],
3074});
3075pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3076    name: "mz_list_types",
3077    schema: MZ_CATALOG_SCHEMA,
3078    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3079    desc: RelationDesc::builder()
3080        .with_column("id", SqlScalarType::String.nullable(false))
3081        .with_column("element_id", SqlScalarType::String.nullable(false))
3082        .with_column(
3083            "element_modifiers",
3084            SqlScalarType::List {
3085                element_type: Box::new(SqlScalarType::Int64),
3086                custom_id: None,
3087            }
3088            .nullable(true),
3089        )
3090        .finish(),
3091    column_comments: BTreeMap::from_iter([
3092        ("id", "The ID of the list type."),
3093        ("element_id", "The IID of the list's element type."),
3094        (
3095            "element_modifiers",
3096            "The element type modifiers, or `NULL` if none.",
3097        ),
3098    ]),
3099    is_retained_metrics_object: false,
3100    access: vec![PUBLIC_SELECT],
3101});
3102pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3103    name: "mz_map_types",
3104    schema: MZ_CATALOG_SCHEMA,
3105    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3106    desc: RelationDesc::builder()
3107        .with_column("id", SqlScalarType::String.nullable(false))
3108        .with_column("key_id", SqlScalarType::String.nullable(false))
3109        .with_column("value_id", SqlScalarType::String.nullable(false))
3110        .with_column(
3111            "key_modifiers",
3112            SqlScalarType::List {
3113                element_type: Box::new(SqlScalarType::Int64),
3114                custom_id: None,
3115            }
3116            .nullable(true),
3117        )
3118        .with_column(
3119            "value_modifiers",
3120            SqlScalarType::List {
3121                element_type: Box::new(SqlScalarType::Int64),
3122                custom_id: None,
3123            }
3124            .nullable(true),
3125        )
3126        .finish(),
3127    column_comments: BTreeMap::from_iter([
3128        ("id", "The ID of the map type."),
3129        ("key_id", "The ID of the map's key type."),
3130        ("value_id", "The ID of the map's value type."),
3131        (
3132            "key_modifiers",
3133            "The key type modifiers, or `NULL` if none.",
3134        ),
3135        (
3136            "value_modifiers",
3137            "The value type modifiers, or `NULL` if none.",
3138        ),
3139    ]),
3140    is_retained_metrics_object: false,
3141    access: vec![PUBLIC_SELECT],
3142});
3143pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3144    name: "mz_roles",
3145    schema: MZ_CATALOG_SCHEMA,
3146    oid: oid::TABLE_MZ_ROLES_OID,
3147    desc: RelationDesc::builder()
3148        .with_column("id", SqlScalarType::String.nullable(false))
3149        .with_column("oid", SqlScalarType::Oid.nullable(false))
3150        .with_column("name", SqlScalarType::String.nullable(false))
3151        .with_column("inherit", SqlScalarType::Bool.nullable(false))
3152        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(true))
3153        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
3154        .with_key(vec![0])
3155        .with_key(vec![1])
3156        .finish(),
3157    column_comments: BTreeMap::from_iter([
3158        ("id", "Materialize's unique ID for the role."),
3159        ("oid", "A [PostgreSQL-compatible OID][`oid`] for the role."),
3160        ("name", "The name of the role."),
3161        (
3162            "inherit",
3163            "Indicates whether the role has inheritance of privileges.",
3164        ),
3165        (
3166            "rolcanlogin",
3167            "Indicates whether the role can log in (i.e., is a user).",
3168        ),
3169        ("rolsuper", "Indicates whether the role is a superuser."),
3170    ]),
3171    is_retained_metrics_object: false,
3172    access: vec![PUBLIC_SELECT],
3173});
3174pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3175    name: "mz_role_members",
3176    schema: MZ_CATALOG_SCHEMA,
3177    oid: oid::TABLE_MZ_ROLE_MEMBERS_OID,
3178    desc: RelationDesc::builder()
3179        .with_column("role_id", SqlScalarType::String.nullable(false))
3180        .with_column("member", SqlScalarType::String.nullable(false))
3181        .with_column("grantor", SqlScalarType::String.nullable(false))
3182        .finish(),
3183    column_comments: BTreeMap::from_iter([
3184        (
3185            "role_id",
3186            "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3187        ),
3188        (
3189            "member",
3190            "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3191        ),
3192        (
3193            "grantor",
3194            "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3195        ),
3196    ]),
3197    is_retained_metrics_object: false,
3198    access: vec![PUBLIC_SELECT],
3199});
3200pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3201    name: "mz_role_parameters",
3202    schema: MZ_CATALOG_SCHEMA,
3203    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3204    desc: RelationDesc::builder()
3205        .with_column("role_id", SqlScalarType::String.nullable(false))
3206        .with_column("parameter_name", SqlScalarType::String.nullable(false))
3207        .with_column("parameter_value", SqlScalarType::String.nullable(false))
3208        .finish(),
3209    column_comments: BTreeMap::from_iter([
3210        (
3211            "role_id",
3212            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3213        ),
3214        (
3215            "parameter_name",
3216            "The configuration parameter name. One of the supported configuration parameters.",
3217        ),
3218        (
3219            "parameter_value",
3220            "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.",
3221        ),
3222    ]),
3223    is_retained_metrics_object: false,
3224    access: vec![PUBLIC_SELECT],
3225});
3226pub static MZ_ROLE_AUTH: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3227    name: "mz_role_auth",
3228    schema: MZ_CATALOG_SCHEMA,
3229    oid: oid::TABLE_MZ_ROLE_AUTH_OID,
3230    desc: RelationDesc::builder()
3231        .with_column("role_id", SqlScalarType::String.nullable(false))
3232        .with_column("role_oid", SqlScalarType::Oid.nullable(false))
3233        .with_column("password_hash", SqlScalarType::String.nullable(true))
3234        .with_column(
3235            "updated_at",
3236            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3237        )
3238        .finish(),
3239    column_comments: BTreeMap::from_iter([
3240        (
3241            "role_id",
3242            "The ID of the role. Corresponds to `mz_roles.id`.",
3243        ),
3244        (
3245            "role_oid",
3246            "The OID of the role whose configuration parameter default is set. Corresponds to `mz_roles.oid`.",
3247        ),
3248        ("password_hash", "The hashed password for the role"),
3249        (
3250            "updated_at",
3251            "The timestamp when the password was last updated.",
3252        ),
3253    ]),
3254    is_retained_metrics_object: false,
3255    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
3256});
3257pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3258    name: "mz_pseudo_types",
3259    schema: MZ_CATALOG_SCHEMA,
3260    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3261    desc: RelationDesc::builder()
3262        .with_column("id", SqlScalarType::String.nullable(false))
3263        .finish(),
3264    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3265    is_retained_metrics_object: false,
3266    access: vec![PUBLIC_SELECT],
3267});
3268pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3269    BuiltinTable {
3270        name: "mz_functions",
3271        schema: MZ_CATALOG_SCHEMA,
3272        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3273        desc: RelationDesc::builder()
3274            .with_column("id", SqlScalarType::String.nullable(false)) // not a key!
3275            .with_column("oid", SqlScalarType::Oid.nullable(false))
3276            .with_column("schema_id", SqlScalarType::String.nullable(false))
3277            .with_column("name", SqlScalarType::String.nullable(false))
3278            .with_column(
3279                "argument_type_ids",
3280                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3281            )
3282            .with_column(
3283                "variadic_argument_type_id",
3284                SqlScalarType::String.nullable(true),
3285            )
3286            .with_column("return_type_id", SqlScalarType::String.nullable(true))
3287            .with_column("returns_set", SqlScalarType::Bool.nullable(false))
3288            .with_column("owner_id", SqlScalarType::String.nullable(false))
3289            .finish(),
3290        column_comments: BTreeMap::from_iter([
3291            ("id", "Materialize's unique ID for the function."),
3292            (
3293                "oid",
3294                "A [PostgreSQL-compatible OID][`oid`] for the function.",
3295            ),
3296            (
3297                "schema_id",
3298                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3299            ),
3300            ("name", "The name of the function."),
3301            (
3302                "argument_type_ids",
3303                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3304            ),
3305            (
3306                "variadic_argument_type_id",
3307                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3308            ),
3309            (
3310                "return_type_id",
3311                "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`].",
3312            ),
3313            (
3314                "returns_set",
3315                "Whether the function returns a set, i.e. the function is a table function.",
3316            ),
3317            (
3318                "owner_id",
3319                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3320            ),
3321        ]),
3322        is_retained_metrics_object: false,
3323        access: vec![PUBLIC_SELECT],
3324    }
3325});
3326pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3327    name: "mz_operators",
3328    schema: MZ_CATALOG_SCHEMA,
3329    oid: oid::TABLE_MZ_OPERATORS_OID,
3330    desc: RelationDesc::builder()
3331        .with_column("oid", SqlScalarType::Oid.nullable(false))
3332        .with_column("name", SqlScalarType::String.nullable(false))
3333        .with_column(
3334            "argument_type_ids",
3335            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3336        )
3337        .with_column("return_type_id", SqlScalarType::String.nullable(true))
3338        .finish(),
3339    column_comments: BTreeMap::new(),
3340    is_retained_metrics_object: false,
3341    access: vec![PUBLIC_SELECT],
3342});
3343pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3344    name: "mz_aggregates",
3345    schema: MZ_INTERNAL_SCHEMA,
3346    oid: oid::TABLE_MZ_AGGREGATES_OID,
3347    desc: RelationDesc::builder()
3348        .with_column("oid", SqlScalarType::Oid.nullable(false))
3349        .with_column("agg_kind", SqlScalarType::String.nullable(false))
3350        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
3351        .finish(),
3352    column_comments: BTreeMap::new(),
3353    is_retained_metrics_object: false,
3354    access: vec![PUBLIC_SELECT],
3355});
3356
3357pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3358    name: "mz_clusters",
3359    schema: MZ_CATALOG_SCHEMA,
3360    oid: oid::TABLE_MZ_CLUSTERS_OID,
3361    desc: RelationDesc::builder()
3362        .with_column("id", SqlScalarType::String.nullable(false))
3363        .with_column("name", SqlScalarType::String.nullable(false))
3364        .with_column("owner_id", SqlScalarType::String.nullable(false))
3365        .with_column(
3366            "privileges",
3367            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3368        )
3369        .with_column("managed", SqlScalarType::Bool.nullable(false))
3370        .with_column("size", SqlScalarType::String.nullable(true))
3371        .with_column("replication_factor", SqlScalarType::UInt32.nullable(true))
3372        .with_column("disk", SqlScalarType::Bool.nullable(true))
3373        .with_column(
3374            "availability_zones",
3375            SqlScalarType::List {
3376                element_type: Box::new(SqlScalarType::String),
3377                custom_id: None,
3378            }
3379            .nullable(true),
3380        )
3381        .with_column(
3382            "introspection_debugging",
3383            SqlScalarType::Bool.nullable(true),
3384        )
3385        .with_column(
3386            "introspection_interval",
3387            SqlScalarType::Interval.nullable(true),
3388        )
3389        .with_key(vec![0])
3390        .finish(),
3391    column_comments: BTreeMap::from_iter([
3392        ("id", "Materialize's unique ID for the cluster."),
3393        ("name", "The name of the cluster."),
3394        (
3395            "owner_id",
3396            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3397        ),
3398        ("privileges", "The privileges belonging to the cluster."),
3399        (
3400            "managed",
3401            "Whether the cluster is a managed cluster with automatically managed replicas.",
3402        ),
3403        (
3404            "size",
3405            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3406        ),
3407        (
3408            "replication_factor",
3409            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3410        ),
3411        (
3412            "disk",
3413            "Unstable If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3414        ),
3415        (
3416            "availability_zones",
3417            "Unstable If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3418        ),
3419        (
3420            "introspection_debugging",
3421            "Whether introspection of the gathering of the introspection data is enabled.",
3422        ),
3423        (
3424            "introspection_interval",
3425            "The interval at which to collect introspection data.",
3426        ),
3427    ]),
3428    is_retained_metrics_object: false,
3429    access: vec![PUBLIC_SELECT],
3430});
3431
3432pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3433    name: "mz_cluster_workload_classes",
3434    schema: MZ_INTERNAL_SCHEMA,
3435    oid: oid::TABLE_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3436    desc: RelationDesc::builder()
3437        .with_column("id", SqlScalarType::String.nullable(false))
3438        .with_column("workload_class", SqlScalarType::String.nullable(true))
3439        .with_key(vec![0])
3440        .finish(),
3441    column_comments: BTreeMap::new(),
3442    is_retained_metrics_object: false,
3443    access: vec![PUBLIC_SELECT],
3444});
3445
3446pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3447    name: "mz_cluster_workload_classes_ind",
3448    schema: MZ_INTERNAL_SCHEMA,
3449    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3450    sql: "IN CLUSTER mz_catalog_server
3451ON mz_internal.mz_cluster_workload_classes (id)",
3452    is_retained_metrics_object: false,
3453};
3454
3455pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3456    name: "mz_cluster_schedules",
3457    schema: MZ_INTERNAL_SCHEMA,
3458    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3459    desc: RelationDesc::builder()
3460        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3461        .with_column("type", SqlScalarType::String.nullable(false))
3462        .with_column(
3463            "refresh_hydration_time_estimate",
3464            SqlScalarType::Interval.nullable(true),
3465        )
3466        .finish(),
3467    column_comments: BTreeMap::from_iter([
3468        (
3469            "cluster_id",
3470            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3471        ),
3472        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3473        (
3474            "refresh_hydration_time_estimate",
3475            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3476        ),
3477    ]),
3478    is_retained_metrics_object: false,
3479    access: vec![PUBLIC_SELECT],
3480});
3481
3482pub static MZ_SECRETS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3483    name: "mz_secrets",
3484    schema: MZ_CATALOG_SCHEMA,
3485    oid: oid::TABLE_MZ_SECRETS_OID,
3486    desc: RelationDesc::builder()
3487        .with_column("id", SqlScalarType::String.nullable(false))
3488        .with_column("oid", SqlScalarType::Oid.nullable(false))
3489        .with_column("schema_id", SqlScalarType::String.nullable(false))
3490        .with_column("name", SqlScalarType::String.nullable(false))
3491        .with_column("owner_id", SqlScalarType::String.nullable(false))
3492        .with_column(
3493            "privileges",
3494            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3495        )
3496        .finish(),
3497    column_comments: BTreeMap::from_iter([
3498        ("id", "The unique ID of the secret."),
3499        (
3500            "oid",
3501            "A [PostgreSQL-compatible oid][`oid`] for the secret.",
3502        ),
3503        (
3504            "schema_id",
3505            "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3506        ),
3507        ("name", "The name of the secret."),
3508        (
3509            "owner_id",
3510            "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3511        ),
3512        ("privileges", "The privileges belonging to the secret."),
3513    ]),
3514    is_retained_metrics_object: false,
3515    access: vec![PUBLIC_SELECT],
3516});
3517
3518pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3519    name: "mz_cluster_replicas",
3520    schema: MZ_CATALOG_SCHEMA,
3521    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3522    desc: RelationDesc::builder()
3523        .with_column("id", SqlScalarType::String.nullable(false))
3524        .with_column("name", SqlScalarType::String.nullable(false))
3525        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3526        .with_column("size", SqlScalarType::String.nullable(true))
3527        // `NULL` for un-orchestrated clusters and for replicas where the user
3528        // hasn't specified them.
3529        .with_column("availability_zone", SqlScalarType::String.nullable(true))
3530        .with_column("owner_id", SqlScalarType::String.nullable(false))
3531        .with_column("disk", SqlScalarType::Bool.nullable(true))
3532        .finish(),
3533    column_comments: BTreeMap::from_iter([
3534        ("id", "Materialize's unique ID for the cluster replica."),
3535        ("name", "The name of the cluster replica."),
3536        (
3537            "cluster_id",
3538            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3539        ),
3540        (
3541            "size",
3542            "The cluster replica's size, selected during creation.",
3543        ),
3544        (
3545            "availability_zone",
3546            "The availability zone in which the cluster is running.",
3547        ),
3548        (
3549            "owner_id",
3550            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3551        ),
3552        ("disk", "If the replica has a local disk."),
3553    ]),
3554    is_retained_metrics_object: true,
3555    access: vec![PUBLIC_SELECT],
3556});
3557
3558pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3559    name: "mz_internal_cluster_replicas",
3560    schema: MZ_INTERNAL_SCHEMA,
3561    oid: oid::TABLE_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3562    desc: RelationDesc::builder()
3563        .with_column("id", SqlScalarType::String.nullable(false))
3564        .finish(),
3565    column_comments: BTreeMap::from_iter([(
3566        "id",
3567        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3568    )]),
3569    is_retained_metrics_object: false,
3570    access: vec![PUBLIC_SELECT],
3571});
3572
3573pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3574    name: "mz_pending_cluster_replicas",
3575    schema: MZ_INTERNAL_SCHEMA,
3576    oid: oid::TABLE_MZ_PENDING_CLUSTER_REPLICAS_OID,
3577    desc: RelationDesc::builder()
3578        .with_column("id", SqlScalarType::String.nullable(false))
3579        .finish(),
3580    column_comments: BTreeMap::from_iter([(
3581        "id",
3582        "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3583    )]),
3584    is_retained_metrics_object: false,
3585    access: vec![PUBLIC_SELECT],
3586});
3587
3588pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3589    BuiltinSource {
3590        name: "mz_cluster_replica_status_history",
3591        schema: MZ_INTERNAL_SCHEMA,
3592        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3593        data_source: IntrospectionType::ReplicaStatusHistory,
3594        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3595        column_comments: BTreeMap::from_iter([
3596            ("replica_id", "The ID of a cluster replica."),
3597            ("process_id", "The ID of a process within the replica."),
3598            (
3599                "status",
3600                "The status of the cluster replica: `online` or `offline`.",
3601            ),
3602            (
3603                "reason",
3604                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3605            ),
3606            (
3607                "occurred_at",
3608                "Wall-clock timestamp at which the event occurred.",
3609            ),
3610        ]),
3611        is_retained_metrics_object: false,
3612        access: vec![PUBLIC_SELECT],
3613    }
3614});
3615
3616pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
3617    || {
3618        BuiltinContinualTask {
3619            name: "mz_cluster_replica_status_history_ct",
3620            schema: MZ_INTERNAL_SCHEMA,
3621            oid: oid::CT_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3622            desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3623            sql: "
3624IN CLUSTER mz_catalog_server
3625ON INPUT mz_internal.mz_cluster_replica_status_history AS (
3626    DELETE FROM mz_internal.mz_cluster_replica_status_history_ct WHERE occurred_at + '30d' < mz_now();
3627    INSERT INTO mz_internal.mz_cluster_replica_status_history_ct SELECT * FROM mz_internal.mz_cluster_replica_status_history;
3628)",
3629            access: vec![PUBLIC_SELECT],
3630        }
3631    },
3632);
3633
3634pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3635    name: "mz_cluster_replica_statuses",
3636    schema: MZ_INTERNAL_SCHEMA,
3637    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
3638    desc: RelationDesc::builder()
3639        .with_column("replica_id", SqlScalarType::String.nullable(false))
3640        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3641        .with_column("status", SqlScalarType::String.nullable(false))
3642        .with_column("reason", SqlScalarType::String.nullable(true))
3643        .with_column(
3644            "updated_at",
3645            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3646        )
3647        .with_key(vec![0, 1])
3648        .finish(),
3649    column_comments: BTreeMap::from_iter([
3650        (
3651            "replica_id",
3652            "Materialize's unique ID for the cluster replica.",
3653        ),
3654        (
3655            "process_id",
3656            "The ID of the process within the cluster replica.",
3657        ),
3658        (
3659            "status",
3660            "The status of the cluster replica: `online` or `offline`.",
3661        ),
3662        (
3663            "reason",
3664            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3665        ),
3666        (
3667            "updated_at",
3668            "The time at which the status was last updated.",
3669        ),
3670    ]),
3671    sql: "
3672SELECT
3673    DISTINCT ON (replica_id, process_id)
3674    replica_id,
3675    process_id,
3676    status,
3677    reason,
3678    occurred_at as updated_at
3679FROM mz_internal.mz_cluster_replica_status_history
3680JOIN mz_cluster_replicas r ON r.id = replica_id
3681ORDER BY replica_id, process_id, occurred_at DESC",
3682    access: vec![PUBLIC_SELECT],
3683});
3684
3685pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3686    name: "mz_cluster_replica_sizes",
3687    schema: MZ_CATALOG_SCHEMA,
3688    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3689    desc: RelationDesc::builder()
3690        .with_column("size", SqlScalarType::String.nullable(false))
3691        .with_column("processes", SqlScalarType::UInt64.nullable(false))
3692        .with_column("workers", SqlScalarType::UInt64.nullable(false))
3693        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(false))
3694        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(false))
3695        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3696        .with_column(
3697            "credits_per_hour",
3698            SqlScalarType::Numeric { max_scale: None }.nullable(false),
3699        )
3700        .finish(),
3701    column_comments: BTreeMap::from_iter([
3702        ("size", "The human-readable replica size."),
3703        ("processes", "The number of processes in the replica."),
3704        (
3705            "workers",
3706            "The number of Timely Dataflow workers per process.",
3707        ),
3708        (
3709            "cpu_nano_cores",
3710            "The CPU allocation per process, in billionths of a vCPU core.",
3711        ),
3712        (
3713            "memory_bytes",
3714            "The RAM allocation per process, in billionths of a vCPU core.",
3715        ),
3716        ("disk_bytes", "The disk allocation per process."),
3717        (
3718            "credits_per_hour",
3719            "The number of compute credits consumed per hour.",
3720        ),
3721    ]),
3722    is_retained_metrics_object: true,
3723    access: vec![PUBLIC_SELECT],
3724});
3725
3726pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3727    name: "mz_audit_events",
3728    schema: MZ_CATALOG_SCHEMA,
3729    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
3730    desc: RelationDesc::builder()
3731        .with_column("id", SqlScalarType::UInt64.nullable(false))
3732        .with_column("event_type", SqlScalarType::String.nullable(false))
3733        .with_column("object_type", SqlScalarType::String.nullable(false))
3734        .with_column("details", SqlScalarType::Jsonb.nullable(false))
3735        .with_column("user", SqlScalarType::String.nullable(true))
3736        .with_column(
3737            "occurred_at",
3738            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3739        )
3740        .with_key(vec![0])
3741        .finish(),
3742    column_comments: BTreeMap::from_iter([
3743        (
3744            "id",
3745            "Materialize's unique, monotonically increasing ID for the event.",
3746        ),
3747        (
3748            "event_type",
3749            "The type of the event: `create`, `drop`, or `alter`.",
3750        ),
3751        (
3752            "object_type",
3753            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
3754        ),
3755        (
3756            "details",
3757            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
3758        ),
3759        (
3760            "user",
3761            "The user who triggered the event, or `NULL` if triggered by the system.",
3762        ),
3763        (
3764            "occurred_at",
3765            "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.",
3766        ),
3767    ]),
3768    is_retained_metrics_object: false,
3769    access: vec![PUBLIC_SELECT],
3770});
3771
3772pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3773    name: "mz_source_status_history",
3774    schema: MZ_INTERNAL_SCHEMA,
3775    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
3776    data_source: IntrospectionType::SourceStatusHistory,
3777    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
3778    column_comments: BTreeMap::from_iter([
3779        (
3780            "occurred_at",
3781            "Wall-clock timestamp of the source status change.",
3782        ),
3783        (
3784            "source_id",
3785            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
3786        ),
3787        (
3788            "status",
3789            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
3790        ),
3791        (
3792            "error",
3793            "If the source is in an error state, the error message.",
3794        ),
3795        (
3796            "details",
3797            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
3798        ),
3799        (
3800            "replica_id",
3801            "The ID of the replica that an instance of a source is running on.",
3802        ),
3803    ]),
3804    is_retained_metrics_object: false,
3805    access: vec![PUBLIC_SELECT],
3806});
3807
3808pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
3809    || BuiltinSource {
3810        name: "mz_aws_privatelink_connection_status_history",
3811        schema: MZ_INTERNAL_SCHEMA,
3812        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
3813        data_source: IntrospectionType::PrivatelinkConnectionStatusHistory,
3814        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
3815        column_comments: BTreeMap::from_iter([
3816            ("occurred_at", "Wall-clock timestamp of the status change."),
3817            (
3818                "connection_id",
3819                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
3820            ),
3821            (
3822                "status",
3823                "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`.",
3824            ),
3825        ]),
3826        is_retained_metrics_object: false,
3827        access: vec![PUBLIC_SELECT],
3828    },
3829);
3830
3831pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> =
3832    LazyLock::new(|| BuiltinView {
3833        name: "mz_aws_privatelink_connection_statuses",
3834        schema: MZ_INTERNAL_SCHEMA,
3835        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
3836        desc: RelationDesc::builder()
3837            .with_column("id", SqlScalarType::String.nullable(false))
3838            .with_column("name", SqlScalarType::String.nullable(false))
3839            .with_column(
3840                "last_status_change_at",
3841                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3842            )
3843            .with_column("status", SqlScalarType::String.nullable(true))
3844            .with_key(vec![0])
3845            .finish(),
3846        column_comments: BTreeMap::from_iter([
3847            (
3848                "id",
3849                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
3850            ),
3851            ("name", "The name of the connection."),
3852            (
3853                "last_status_change_at",
3854                "Wall-clock timestamp of the connection status change.",
3855            ),
3856            ("status", ""),
3857        ]),
3858        sql: "
3859    WITH statuses_w_last_status AS (
3860        SELECT
3861            connection_id,
3862            occurred_at,
3863            status,
3864            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
3865        FROM mz_internal.mz_aws_privatelink_connection_status_history
3866    ),
3867    latest_events AS (
3868        -- Only take the most recent transition for each ID
3869        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
3870        FROM statuses_w_last_status
3871        -- Only keep first status transitions
3872        WHERE status <> last_status OR last_status IS NULL
3873        ORDER BY connection_id, occurred_at DESC
3874    )
3875    SELECT
3876        conns.id,
3877        name,
3878        occurred_at as last_status_change_at,
3879        status
3880    FROM latest_events
3881    JOIN mz_catalog.mz_connections AS conns
3882    ON conns.id = latest_events.connection_id",
3883        access: vec![PUBLIC_SELECT],
3884    });
3885
3886pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
3887    LazyLock::new(|| BuiltinSource {
3888        name: "mz_statement_execution_history",
3889        schema: MZ_INTERNAL_SCHEMA,
3890        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
3891        data_source: IntrospectionType::StatementExecutionHistory,
3892        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
3893        column_comments: BTreeMap::new(),
3894        is_retained_metrics_object: false,
3895        access: vec![MONITOR_SELECT],
3896    });
3897
3898pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
3899    BuiltinView {
3900    name: "mz_statement_execution_history_redacted",
3901    schema: MZ_INTERNAL_SCHEMA,
3902    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
3903    // everything but `params` and `error_message`
3904    desc: RelationDesc::builder()
3905        .with_column("id", SqlScalarType::Uuid.nullable(false))
3906        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
3907        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
3908        .with_column("cluster_id", SqlScalarType::String.nullable(true))
3909        .with_column("application_name", SqlScalarType::String.nullable(false))
3910        .with_column("cluster_name", SqlScalarType::String.nullable(true))
3911        .with_column("database_name", SqlScalarType::String.nullable(false))
3912        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
3913        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
3914        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
3915        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
3916        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
3917        .with_column("mz_version", SqlScalarType::String.nullable(false))
3918        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
3919        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
3920        .with_column("finished_status", SqlScalarType::String.nullable(true))
3921        .with_column("result_size", SqlScalarType::Int64.nullable(true))
3922        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
3923        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
3924        .finish(),
3925    column_comments: BTreeMap::new(),
3926    sql: "
3927SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
3928cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
3929transient_index_id, mz_version, began_at, finished_at, finished_status,
3930result_size, rows_returned, execution_strategy
3931FROM mz_internal.mz_statement_execution_history",
3932    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
3933}
3934});
3935
3936pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
3937    LazyLock::new(|| BuiltinSource {
3938        name: "mz_prepared_statement_history",
3939        schema: MZ_INTERNAL_SCHEMA,
3940        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
3941        data_source: IntrospectionType::PreparedStatementHistory,
3942        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
3943        column_comments: BTreeMap::new(),
3944        is_retained_metrics_object: false,
3945        access: vec![
3946            SUPPORT_SELECT,
3947            ANALYTICS_SELECT,
3948            MONITOR_REDACTED_SELECT,
3949            MONITOR_SELECT,
3950        ],
3951    });
3952
3953pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3954    name: "mz_sql_text",
3955    schema: MZ_INTERNAL_SCHEMA,
3956    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
3957    desc: MZ_SQL_TEXT_DESC.clone(),
3958    data_source: IntrospectionType::SqlText,
3959    column_comments: BTreeMap::new(),
3960    is_retained_metrics_object: false,
3961    access: vec![MONITOR_SELECT],
3962});
3963
3964pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3965    name: "mz_sql_text_redacted",
3966    schema: MZ_INTERNAL_SCHEMA,
3967    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
3968    desc: RelationDesc::builder()
3969        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3970        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3971        .finish(),
3972    column_comments: BTreeMap::new(),
3973    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
3974    access: vec![
3975        MONITOR_SELECT,
3976        MONITOR_REDACTED_SELECT,
3977        SUPPORT_SELECT,
3978        ANALYTICS_SELECT,
3979    ],
3980});
3981
3982pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
3983    BuiltinView {
3984        name: "mz_recent_sql_text",
3985        schema: MZ_INTERNAL_SCHEMA,
3986        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
3987        // This should always be 1 day more than the interval in
3988        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
3989        // is rounded down to the nearest day.  Thus something that actually happened three days ago
3990        // could have a `prepared day` anywhere from 3 to 4 days back.
3991        desc: RelationDesc::builder()
3992            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
3993            .with_column("sql", SqlScalarType::String.nullable(false))
3994            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
3995            .with_key(vec![0, 1, 2])
3996            .finish(),
3997        column_comments: BTreeMap::new(),
3998        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
3999        access: vec![MONITOR_SELECT],
4000    }
4001});
4002
4003pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4004    name: "mz_recent_sql_text_redacted",
4005    schema: MZ_INTERNAL_SCHEMA,
4006    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
4007    desc: RelationDesc::builder()
4008        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4009        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4010        .finish(),
4011    column_comments: BTreeMap::new(),
4012    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
4013    access: vec![
4014        MONITOR_SELECT,
4015        MONITOR_REDACTED_SELECT,
4016        SUPPORT_SELECT,
4017        ANALYTICS_SELECT,
4018    ],
4019});
4020
4021pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
4022    name: "mz_recent_sql_text_ind",
4023    schema: MZ_INTERNAL_SCHEMA,
4024    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
4025    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4026    is_retained_metrics_object: false,
4027});
4028
4029pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4030    name: "mz_session_history",
4031    schema: MZ_INTERNAL_SCHEMA,
4032    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4033    data_source: IntrospectionType::SessionHistory,
4034    desc: MZ_SESSION_HISTORY_DESC.clone(),
4035    column_comments: BTreeMap::new(),
4036    is_retained_metrics_object: false,
4037    access: vec![PUBLIC_SELECT],
4038});
4039
4040pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4041    BuiltinView {
4042        name: "mz_activity_log_thinned",
4043        schema: MZ_INTERNAL_SCHEMA,
4044        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
4045        desc: RelationDesc::builder()
4046            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4047            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4048            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4049            .with_column("application_name", SqlScalarType::String.nullable(false))
4050            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4051            .with_column("database_name", SqlScalarType::String.nullable(false))
4052            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4053            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4054            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4055            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4056            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4057            .with_column("mz_version", SqlScalarType::String.nullable(false))
4058            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4059            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4060            .with_column("finished_status", SqlScalarType::String.nullable(true))
4061            .with_column("error_message", SqlScalarType::String.nullable(true))
4062            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4063            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4064            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4065            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4066            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4067            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4068            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4069            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4070            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4071            .with_column("statement_type", SqlScalarType::String.nullable(true))
4072            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4073            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4074            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4075            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4076            .finish(),
4077        column_comments: BTreeMap::new(),
4078        sql: "
4079SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
4080transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
4081error_message, result_size, rows_returned, execution_strategy, transaction_id,
4082mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
4083mpsh.session_id, prepared_at, statement_type, throttled_count,
4084connected_at, initial_application_name, authenticated_user
4085FROM mz_internal.mz_statement_execution_history mseh,
4086     mz_internal.mz_prepared_statement_history mpsh,
4087     mz_internal.mz_session_history msh
4088WHERE mseh.prepared_statement_id = mpsh.id
4089AND mpsh.session_id = msh.session_id",
4090        access: vec![MONITOR_SELECT],
4091    }
4092});
4093
4094pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4095    BuiltinView {
4096        name: "mz_recent_activity_log_thinned",
4097        schema: MZ_INTERNAL_SCHEMA,
4098        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
4099        desc: RelationDesc::builder()
4100            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4101            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4102            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4103            .with_column("application_name", SqlScalarType::String.nullable(false))
4104            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4105            .with_column("database_name", SqlScalarType::String.nullable(false))
4106            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4107            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4108            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4109            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4110            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4111            .with_column("mz_version", SqlScalarType::String.nullable(false))
4112            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4113            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4114            .with_column("finished_status", SqlScalarType::String.nullable(true))
4115            .with_column("error_message", SqlScalarType::String.nullable(true))
4116            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4117            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4118            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4119            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4120            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4121            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4122            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4123            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4124            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4125            .with_column("statement_type", SqlScalarType::String.nullable(true))
4126            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4127            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4128            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4129            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4130            .finish(),
4131        column_comments: BTreeMap::new(),
4132        // We use a temporal window of 2 days rather than 1 day for `mz_session_history`'s `connected_at` since a statement execution at
4133        // 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.
4134        sql:
4135        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
4136AND began_at + INTERVAL '1 day' > mz_now() AND connected_at + INTERVAL '2 days' > mz_now()",
4137        access: vec![MONITOR_SELECT],
4138    }
4139});
4140
4141pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4142    name: "mz_recent_activity_log",
4143    schema: MZ_INTERNAL_SCHEMA,
4144    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
4145    desc: RelationDesc::builder()
4146        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4147        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4148        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4149        .with_column("application_name", SqlScalarType::String.nullable(false))
4150        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4151        .with_column("database_name", SqlScalarType::String.nullable(false))
4152        .with_column(
4153            "search_path",
4154            SqlScalarType::List {
4155                element_type: Box::new(SqlScalarType::String),
4156                custom_id: None,
4157            }
4158            .nullable(false),
4159        )
4160        .with_column(
4161            "transaction_isolation",
4162            SqlScalarType::String.nullable(false),
4163        )
4164        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4165        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4166        .with_column(
4167            "params",
4168            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
4169        )
4170        .with_column("mz_version", SqlScalarType::String.nullable(false))
4171        .with_column(
4172            "began_at",
4173            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4174        )
4175        .with_column(
4176            "finished_at",
4177            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4178        )
4179        .with_column("finished_status", SqlScalarType::String.nullable(true))
4180        .with_column("error_message", SqlScalarType::String.nullable(true))
4181        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4182        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4183        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4184        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4185        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4186        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4187        .with_column(
4188            "prepared_statement_name",
4189            SqlScalarType::String.nullable(false),
4190        )
4191        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4192        .with_column(
4193            "prepared_at",
4194            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4195        )
4196        .with_column("statement_type", SqlScalarType::String.nullable(true))
4197        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4198        .with_column(
4199            "connected_at",
4200            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4201        )
4202        .with_column(
4203            "initial_application_name",
4204            SqlScalarType::String.nullable(false),
4205        )
4206        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4207        .with_column("sql", SqlScalarType::String.nullable(false))
4208        .finish(),
4209    column_comments: BTreeMap::from_iter([
4210        (
4211            "execution_id",
4212            "An ID that is unique for each executed statement.",
4213        ),
4214        (
4215            "sample_rate",
4216            "The actual rate at which the statement was sampled.",
4217        ),
4218        (
4219            "cluster_id",
4220            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
4221        ),
4222        (
4223            "application_name",
4224            "The value of the `application_name` configuration parameter at execution time.",
4225        ),
4226        (
4227            "cluster_name",
4228            "The name of the cluster with ID `cluster_id` at execution time.",
4229        ),
4230        (
4231            "database_name",
4232            "The value of the `database` configuration parameter at execution time.",
4233        ),
4234        (
4235            "search_path",
4236            "The value of the `search_path` configuration parameter at execution time.",
4237        ),
4238        (
4239            "transaction_isolation",
4240            "The value of the `transaction_isolation` configuration parameter at execution time.",
4241        ),
4242        (
4243            "execution_timestamp",
4244            "The logical timestamp at which execution was scheduled.",
4245        ),
4246        (
4247            "transient_index_id",
4248            "The internal index of the compute dataflow created for the query, if any.",
4249        ),
4250        (
4251            "params",
4252            "The parameters with which the statement was executed.",
4253        ),
4254        (
4255            "mz_version",
4256            "The version of Materialize that was running when the statement was executed.",
4257        ),
4258        (
4259            "began_at",
4260            "The wall-clock time at which the statement began executing.",
4261        ),
4262        (
4263            "finished_at",
4264            "The wall-clock time at which the statement finished executing.",
4265        ),
4266        (
4267            "finished_status",
4268            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). `aborted` means that Materialize exited before the statement finished executing.",
4269        ),
4270        (
4271            "error_message",
4272            "The error message, if the statement failed.",
4273        ),
4274        (
4275            "result_size",
4276            "The size in bytes of the result, for statements that return rows.",
4277        ),
4278        (
4279            "rows_returned",
4280            "The number of rows returned, for statements that return rows.",
4281        ),
4282        (
4283            "execution_strategy",
4284            "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.",
4285        ),
4286        (
4287            "transaction_id",
4288            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
4289        ),
4290        (
4291            "prepared_statement_id",
4292            "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`).",
4293        ),
4294        (
4295            "sql_hash",
4296            "An opaque value uniquely identifying the text of the query.",
4297        ),
4298        (
4299            "prepared_statement_name",
4300            "The name given by the client library to the prepared statement.",
4301        ),
4302        (
4303            "session_id",
4304            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
4305        ),
4306        (
4307            "prepared_at",
4308            "The time at which the statement was prepared.",
4309        ),
4310        (
4311            "statement_type",
4312            "The type of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
4313        ),
4314        (
4315            "throttled_count",
4316            "The number of statements that were dropped due to throttling before the current one was seen. If you have a very high volume of queries and need to log them without throttling, contact our team.",
4317        ),
4318        (
4319            "connected_at",
4320            "The time at which the session was established.",
4321        ),
4322        (
4323            "initial_application_name",
4324            "The initial value of `application_name` at the beginning of the session.",
4325        ),
4326        (
4327            "authenticated_user",
4328            "The name of the user for which the session was established.",
4329        ),
4330        ("sql", "The SQL text of the statement."),
4331    ]),
4332    sql: "SELECT mralt.*, mrst.sql
4333FROM mz_internal.mz_recent_activity_log_thinned mralt,
4334     mz_internal.mz_recent_sql_text mrst
4335WHERE mralt.sql_hash = mrst.sql_hash",
4336    access: vec![MONITOR_SELECT],
4337});
4338
4339pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4340    BuiltinView {
4341    name: "mz_recent_activity_log_redacted",
4342    schema: MZ_INTERNAL_SCHEMA,
4343    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
4344    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
4345    desc: RelationDesc::builder()
4346        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4347        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4348        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4349        .with_column("application_name", SqlScalarType::String.nullable(false))
4350        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4351        .with_column("database_name", SqlScalarType::String.nullable(false))
4352        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4353        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4354        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4355        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4356        .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4357        .with_column("mz_version", SqlScalarType::String.nullable(false))
4358        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4359        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4360        .with_column("finished_status", SqlScalarType::String.nullable(true))
4361        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4362        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4363        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4364        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4365        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4366        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4367        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4368        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4369        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4370        .with_column("statement_type", SqlScalarType::String.nullable(true))
4371        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4372        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4373        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4374        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4375        .finish(),
4376    column_comments: BTreeMap::new(),
4377    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4378    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4379    mralt.transient_index_id, mralt.params, mralt.mz_version, mralt.began_at, mralt.finished_at,
4380    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4381    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4382    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4383    mralt.initial_application_name, mralt.authenticated_user,
4384    mrst.redacted_sql
4385FROM mz_internal.mz_recent_activity_log_thinned mralt,
4386     mz_internal.mz_recent_sql_text mrst
4387WHERE mralt.sql_hash = mrst.sql_hash",
4388    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4389}
4390});
4391
4392pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4393    BuiltinSource {
4394        name: "mz_statement_lifecycle_history",
4395        schema: MZ_INTERNAL_SCHEMA,
4396        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4397        desc: RelationDesc::builder()
4398            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
4399            .with_column("event_type", SqlScalarType::String.nullable(false))
4400            .with_column(
4401                "occurred_at",
4402                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4403            )
4404            .finish(),
4405        data_source: IntrospectionType::StatementLifecycleHistory,
4406        column_comments: BTreeMap::from_iter([
4407            (
4408                "statement_id",
4409                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4410            ),
4411            (
4412                "event_type",
4413                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4414            ),
4415            ("occurred_at", "The time at which the event took place."),
4416        ]),
4417        is_retained_metrics_object: false,
4418        // TODO[btv]: Maybe this should be public instead of
4419        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4420        // change, we probably don't need to worry about it now.
4421        access: vec![
4422            SUPPORT_SELECT,
4423            ANALYTICS_SELECT,
4424            MONITOR_REDACTED_SELECT,
4425            MONITOR_SELECT,
4426        ],
4427    }
4428});
4429
4430pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4431    name: "mz_source_statuses",
4432    schema: MZ_INTERNAL_SCHEMA,
4433    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4434    desc: RelationDesc::builder()
4435        .with_column("id", SqlScalarType::String.nullable(false))
4436        .with_column("name", SqlScalarType::String.nullable(false))
4437        .with_column("type", SqlScalarType::String.nullable(false))
4438        .with_column(
4439            "last_status_change_at",
4440            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4441        )
4442        .with_column("status", SqlScalarType::String.nullable(false))
4443        .with_column("error", SqlScalarType::String.nullable(true))
4444        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4445        .finish(),
4446    column_comments: BTreeMap::from_iter([
4447        (
4448            "id",
4449            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4450        ),
4451        ("name", "The name of the source."),
4452        ("type", "The type of the source."),
4453        (
4454            "last_status_change_at",
4455            "Wall-clock timestamp of the source status change.",
4456        ),
4457        (
4458            "status",
4459            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4460        ),
4461        (
4462            "error",
4463            "If the source is in an error state, the error message.",
4464        ),
4465        (
4466            "details",
4467            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4468        ),
4469    ]),
4470    sql: "
4471    WITH
4472    -- The status history contains per-replica events and source-global events.
4473    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4474    -- we can treat them uniformly below.
4475    uniform_status_history AS
4476    (
4477        SELECT
4478            s.source_id,
4479            COALESCE(s.replica_id, '<source>') as replica_id,
4480            s.occurred_at,
4481            s.status,
4482            s.error,
4483            s.details
4484        FROM mz_internal.mz_source_status_history s
4485    ),
4486    -- For getting the latest events, we first determine the latest per-replica
4487    -- events here and then apply precedence rules below.
4488    latest_per_replica_events AS
4489    (
4490        SELECT DISTINCT ON (source_id, replica_id)
4491            occurred_at, source_id, replica_id, status, error, details
4492        FROM uniform_status_history
4493        ORDER BY source_id, replica_id, occurred_at DESC
4494    ),
4495    -- We have a precedence list that determines the overall status in case
4496    -- there is differing per-replica (including source-global) statuses. If
4497    -- there is no 'dropped' status, and any replica reports 'running', the
4498    -- overall status is 'running' even if there might be some replica that has
4499    -- errors or is paused.
4500    latest_events AS
4501    (
4502       SELECT DISTINCT ON (source_id)
4503            source_id,
4504            occurred_at,
4505            status,
4506            error,
4507            details
4508        FROM latest_per_replica_events
4509        ORDER BY source_id, CASE status
4510                    WHEN 'dropped' THEN 1
4511                    WHEN 'running' THEN 2
4512                    WHEN 'stalled' THEN 3
4513                    WHEN 'starting' THEN 4
4514                    WHEN 'paused' THEN 5
4515                    WHEN 'ceased' THEN 6
4516                    ELSE 7  -- For any other status values
4517                END
4518    ),
4519    -- Determine which sources are subsources and which are parent sources
4520    subsources AS
4521    (
4522        SELECT subsources.id AS self, sources.id AS parent
4523        FROM
4524            mz_catalog.mz_sources AS subsources
4525                JOIN
4526                    mz_internal.mz_object_dependencies AS deps
4527                    ON subsources.id = deps.object_id
4528                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4529    ),
4530    -- Determine which sources are source tables
4531    tables AS
4532    (
4533        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4534        FROM mz_catalog.mz_tables AS tables
4535        WHERE tables.source_id IS NOT NULL
4536    ),
4537    -- Determine which collection's ID to use for the status
4538    id_of_status_to_use AS
4539    (
4540        SELECT
4541            self_events.source_id,
4542            -- If self not errored, but parent is, use parent; else self
4543            CASE
4544                WHEN
4545                    self_events.status <> 'ceased' AND
4546                    parent_events.status = 'stalled'
4547                THEN parent_events.source_id
4548                ELSE self_events.source_id
4549            END AS id_to_use
4550        FROM
4551            latest_events AS self_events
4552                LEFT JOIN subsources ON self_events.source_id = subsources.self
4553                LEFT JOIN tables ON self_events.source_id = tables.self
4554                LEFT JOIN
4555                    latest_events AS parent_events
4556                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4557    ),
4558    -- Swap out events for the ID of the event we plan to use instead
4559    latest_events_to_use AS
4560    (
4561        SELECT occurred_at, s.source_id, status, error, details
4562        FROM
4563            id_of_status_to_use AS s
4564                JOIN latest_events AS e ON e.source_id = s.id_to_use
4565    ),
4566    combined AS (
4567        SELECT
4568            mz_sources.id,
4569            mz_sources.name,
4570            mz_sources.type,
4571            occurred_at,
4572            status,
4573            error,
4574            details
4575        FROM
4576            mz_catalog.mz_sources
4577            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4578        UNION ALL
4579        SELECT
4580            tables.self AS id,
4581            tables.name,
4582            'table' AS type,
4583            occurred_at,
4584            status,
4585            error,
4586            details
4587        FROM
4588            tables
4589            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4590    )
4591SELECT
4592    id,
4593    name,
4594    type,
4595    occurred_at AS last_status_change_at,
4596    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4597    CASE
4598        WHEN
4599            type = 'webhook' OR
4600            type = 'progress'
4601        THEN 'running'
4602        ELSE COALESCE(status, 'created')
4603    END AS status,
4604    error,
4605    details
4606FROM combined
4607WHERE id NOT LIKE 's%';",
4608    access: vec![PUBLIC_SELECT],
4609});
4610
4611pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4612    name: "mz_sink_status_history",
4613    schema: MZ_INTERNAL_SCHEMA,
4614    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4615    data_source: IntrospectionType::SinkStatusHistory,
4616    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4617    column_comments: BTreeMap::from_iter([
4618        (
4619            "occurred_at",
4620            "Wall-clock timestamp of the sink status change.",
4621        ),
4622        (
4623            "sink_id",
4624            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4625        ),
4626        (
4627            "status",
4628            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4629        ),
4630        (
4631            "error",
4632            "If the sink is in an error state, the error message.",
4633        ),
4634        (
4635            "details",
4636            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4637        ),
4638        (
4639            "replica_id",
4640            "The ID of the replica that an instance of a sink is running on.",
4641        ),
4642    ]),
4643    is_retained_metrics_object: false,
4644    access: vec![PUBLIC_SELECT],
4645});
4646
4647pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4648    name: "mz_sink_statuses",
4649    schema: MZ_INTERNAL_SCHEMA,
4650    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4651    desc: RelationDesc::builder()
4652        .with_column("id", SqlScalarType::String.nullable(false))
4653        .with_column("name", SqlScalarType::String.nullable(false))
4654        .with_column("type", SqlScalarType::String.nullable(false))
4655        .with_column(
4656            "last_status_change_at",
4657            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4658        )
4659        .with_column("status", SqlScalarType::String.nullable(false))
4660        .with_column("error", SqlScalarType::String.nullable(true))
4661        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4662        .finish(),
4663    column_comments: BTreeMap::from_iter([
4664        (
4665            "id",
4666            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4667        ),
4668        ("name", "The name of the sink."),
4669        ("type", "The type of the sink."),
4670        (
4671            "last_status_change_at",
4672            "Wall-clock timestamp of the sink status change.",
4673        ),
4674        (
4675            "status",
4676            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4677        ),
4678        (
4679            "error",
4680            "If the sink is in an error state, the error message.",
4681        ),
4682        (
4683            "details",
4684            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4685        ),
4686    ]),
4687    sql: "
4688WITH
4689-- The status history contains per-replica events and sink-global events.
4690-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
4691-- we can treat them uniformly below.
4692uniform_status_history AS
4693(
4694    SELECT
4695        s.sink_id,
4696        COALESCE(s.replica_id, '<sink>') as replica_id,
4697        s.occurred_at,
4698        s.status,
4699        s.error,
4700        s.details
4701    FROM mz_internal.mz_sink_status_history s
4702),
4703-- For getting the latest events, we first determine the latest per-replica
4704-- events here and then apply precedence rules below.
4705latest_per_replica_events AS
4706(
4707    SELECT DISTINCT ON (sink_id, replica_id)
4708        occurred_at, sink_id, replica_id, status, error, details
4709    FROM uniform_status_history
4710    ORDER BY sink_id, replica_id, occurred_at DESC
4711),
4712-- We have a precedence list that determines the overall status in case
4713-- there is differing per-replica (including sink-global) statuses. If
4714-- there is no 'dropped' status, and any replica reports 'running', the
4715-- overall status is 'running' even if there might be some replica that has
4716-- errors or is paused.
4717latest_events AS
4718(
4719    SELECT DISTINCT ON (sink_id)
4720        sink_id,
4721        occurred_at,
4722        status,
4723        error,
4724        details
4725    FROM latest_per_replica_events
4726    ORDER BY sink_id, CASE status
4727                WHEN 'dropped' THEN 1
4728                WHEN 'running' THEN 2
4729                WHEN 'stalled' THEN 3
4730                WHEN 'starting' THEN 4
4731                WHEN 'paused' THEN 5
4732                WHEN 'ceased' THEN 6
4733                ELSE 7  -- For any other status values
4734            END
4735)
4736SELECT
4737    mz_sinks.id,
4738    name,
4739    mz_sinks.type,
4740    occurred_at as last_status_change_at,
4741    coalesce(status, 'created') as status,
4742    error,
4743    details
4744FROM mz_catalog.mz_sinks
4745LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
4746WHERE
4747    -- This is a convenient way to filter out system sinks, like the status_history table itself.
4748    mz_sinks.id NOT LIKE 's%'",
4749    access: vec![PUBLIC_SELECT],
4750});
4751
4752pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
4753    LazyLock::new(|| SystemObjectDescription {
4754        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
4755        object_type: CatalogItemType::Table,
4756        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
4757    });
4758
4759pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4760    name: "mz_storage_usage_by_shard",
4761    schema: MZ_INTERNAL_SCHEMA,
4762    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
4763    desc: RelationDesc::builder()
4764        .with_column("id", SqlScalarType::UInt64.nullable(false))
4765        .with_column("shard_id", SqlScalarType::String.nullable(true))
4766        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
4767        .with_column(
4768            "collection_timestamp",
4769            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4770        )
4771        .finish(),
4772    column_comments: BTreeMap::new(),
4773    is_retained_metrics_object: false,
4774    access: vec![PUBLIC_SELECT],
4775});
4776
4777pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4778    name: "mz_egress_ips",
4779    schema: MZ_CATALOG_SCHEMA,
4780    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
4781    desc: RelationDesc::builder()
4782        .with_column("egress_ip", SqlScalarType::String.nullable(false))
4783        .with_column("prefix_length", SqlScalarType::Int32.nullable(false))
4784        .with_column("cidr", SqlScalarType::String.nullable(false))
4785        .finish(),
4786    column_comments: BTreeMap::from_iter([
4787        ("egress_ip", "The start of the range of IP addresses."),
4788        (
4789            "prefix_length",
4790            "The number of leading bits in the CIDR netmask.",
4791        ),
4792        ("cidr", "The CIDR representation."),
4793    ]),
4794    is_retained_metrics_object: false,
4795    access: vec![PUBLIC_SELECT],
4796});
4797
4798pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
4799    LazyLock::new(|| BuiltinTable {
4800        name: "mz_aws_privatelink_connections",
4801        schema: MZ_CATALOG_SCHEMA,
4802        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
4803        desc: RelationDesc::builder()
4804            .with_column("id", SqlScalarType::String.nullable(false))
4805            .with_column("principal", SqlScalarType::String.nullable(false))
4806            .finish(),
4807        column_comments: BTreeMap::from_iter([
4808            ("id", "The ID of the connection."),
4809            (
4810                "principal",
4811                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
4812            ),
4813        ]),
4814        is_retained_metrics_object: false,
4815        access: vec![PUBLIC_SELECT],
4816    });
4817
4818pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4819    name: "mz_aws_connections",
4820    schema: MZ_INTERNAL_SCHEMA,
4821    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
4822    desc: RelationDesc::builder()
4823        .with_column("id", SqlScalarType::String.nullable(false))
4824        .with_column("endpoint", SqlScalarType::String.nullable(true))
4825        .with_column("region", SqlScalarType::String.nullable(true))
4826        .with_column("access_key_id", SqlScalarType::String.nullable(true))
4827        .with_column(
4828            "access_key_id_secret_id",
4829            SqlScalarType::String.nullable(true),
4830        )
4831        .with_column(
4832            "secret_access_key_secret_id",
4833            SqlScalarType::String.nullable(true),
4834        )
4835        .with_column("session_token", SqlScalarType::String.nullable(true))
4836        .with_column(
4837            "session_token_secret_id",
4838            SqlScalarType::String.nullable(true),
4839        )
4840        .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
4841        .with_column(
4842            "assume_role_session_name",
4843            SqlScalarType::String.nullable(true),
4844        )
4845        .with_column("principal", SqlScalarType::String.nullable(true))
4846        .with_column("external_id", SqlScalarType::String.nullable(true))
4847        .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
4848        .finish(),
4849    column_comments: BTreeMap::from_iter([
4850        ("id", "The ID of the connection."),
4851        ("endpoint", "The value of the `ENDPOINT` option, if set."),
4852        ("region", "The value of the `REGION` option, if set."),
4853        (
4854            "access_key_id",
4855            "The value of the `ACCESS KEY ID` option, if provided in line.",
4856        ),
4857        (
4858            "access_key_id_secret_id",
4859            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
4860        ),
4861        (
4862            "secret_access_key_secret_id",
4863            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
4864        ),
4865        (
4866            "session_token",
4867            "The value of the `SESSION TOKEN` option, if provided in line.",
4868        ),
4869        (
4870            "session_token_secret_id",
4871            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
4872        ),
4873        (
4874            "assume_role_arn",
4875            "The value of the `ASSUME ROLE ARN` option, if set.",
4876        ),
4877        (
4878            "assume_role_session_name",
4879            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
4880        ),
4881        (
4882            "principal",
4883            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4884        ),
4885        (
4886            "external_id",
4887            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
4888        ),
4889        (
4890            "example_trust_policy",
4891            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
4892        ),
4893    ]),
4894    is_retained_metrics_object: false,
4895    access: vec![PUBLIC_SELECT],
4896});
4897
4898pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
4899    LazyLock::new(|| BuiltinSource {
4900        name: "mz_cluster_replica_metrics_history",
4901        schema: MZ_INTERNAL_SCHEMA,
4902        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4903        data_source: IntrospectionType::ReplicaMetricsHistory,
4904        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4905        column_comments: BTreeMap::from_iter([
4906            ("replica_id", "The ID of a cluster replica."),
4907            ("process_id", "The ID of a process within the replica."),
4908            (
4909                "cpu_nano_cores",
4910                "Approximate CPU usage, in billionths of a vCPU core.",
4911            ),
4912            ("memory_bytes", "Approximate memory usage, in bytes."),
4913            ("disk_bytes", "Approximate disk usage, in bytes."),
4914            (
4915                "occurred_at",
4916                "Wall-clock timestamp at which the event occurred.",
4917            ),
4918            (
4919                "heap_bytes",
4920                "Approximate heap (RAM + swap) usage, in bytes.",
4921            ),
4922            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
4923        ]),
4924        is_retained_metrics_object: false,
4925        access: vec![PUBLIC_SELECT],
4926    });
4927
4928pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
4929    || {
4930        BuiltinContinualTask {
4931            name: "mz_cluster_replica_metrics_history_ct",
4932            schema: MZ_INTERNAL_SCHEMA,
4933            oid: oid::CT_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
4934            desc: REPLICA_METRICS_HISTORY_DESC.clone(),
4935            sql: "
4936IN CLUSTER mz_catalog_server
4937ON INPUT mz_internal.mz_cluster_replica_metrics_history AS (
4938    DELETE FROM mz_internal.mz_cluster_replica_metrics_history_ct WHERE occurred_at + '30d' < mz_now();
4939    INSERT INTO mz_internal.mz_cluster_replica_metrics_history_ct SELECT * FROM mz_internal.mz_cluster_replica_metrics_history;
4940)",
4941            access: vec![PUBLIC_SELECT],
4942        }
4943    },
4944);
4945
4946pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4947    name: "mz_cluster_replica_metrics",
4948    schema: MZ_INTERNAL_SCHEMA,
4949    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
4950    desc: RelationDesc::builder()
4951        .with_column("replica_id", SqlScalarType::String.nullable(false))
4952        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
4953        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
4954        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
4955        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
4956        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
4957        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
4958        .with_key(vec![0, 1])
4959        .finish(),
4960    column_comments: BTreeMap::from_iter([
4961        ("replica_id", "The ID of a cluster replica."),
4962        ("process_id", "The ID of a process within the replica."),
4963        (
4964            "cpu_nano_cores",
4965            "Approximate CPU usage, in billionths of a vCPU core.",
4966        ),
4967        ("memory_bytes", "Approximate RAM usage, in bytes."),
4968        ("disk_bytes", "Approximate disk usage, in bytes."),
4969        (
4970            "heap_bytes",
4971            "Approximate heap (RAM + swap) usage, in bytes.",
4972        ),
4973        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
4974    ]),
4975    sql: "
4976SELECT
4977    DISTINCT ON (replica_id, process_id)
4978    replica_id,
4979    process_id,
4980    cpu_nano_cores,
4981    memory_bytes,
4982    disk_bytes,
4983    heap_bytes,
4984    heap_limit
4985FROM mz_internal.mz_cluster_replica_metrics_history
4986JOIN mz_cluster_replicas r ON r.id = replica_id
4987ORDER BY replica_id, process_id, occurred_at DESC",
4988    access: vec![PUBLIC_SELECT],
4989});
4990
4991pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
4992    LazyLock::new(|| BuiltinSource {
4993        name: "mz_cluster_replica_frontiers",
4994        schema: MZ_CATALOG_SCHEMA,
4995        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
4996        data_source: IntrospectionType::ReplicaFrontiers,
4997        desc: RelationDesc::builder()
4998            .with_column("object_id", SqlScalarType::String.nullable(false))
4999            .with_column("replica_id", SqlScalarType::String.nullable(false))
5000            .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5001            .finish(),
5002        column_comments: BTreeMap::from_iter([
5003            (
5004                "object_id",
5005                "The ID of the source, sink, index, materialized view, or subscription.",
5006            ),
5007            ("replica_id", "The ID of a cluster replica."),
5008            (
5009                "write_frontier",
5010                "The next timestamp at which the output may change.",
5011            ),
5012        ]),
5013        is_retained_metrics_object: false,
5014        access: vec![PUBLIC_SELECT],
5015    });
5016
5017pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
5018    LazyLock::new(|| BuiltinIndex {
5019        name: "mz_cluster_replica_frontiers_ind",
5020        schema: MZ_CATALOG_SCHEMA,
5021        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
5022        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
5023        is_retained_metrics_object: false,
5024    });
5025
5026pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5027    name: "mz_frontiers",
5028    schema: MZ_INTERNAL_SCHEMA,
5029    oid: oid::SOURCE_MZ_FRONTIERS_OID,
5030    data_source: IntrospectionType::Frontiers,
5031    desc: RelationDesc::builder()
5032        .with_column("object_id", SqlScalarType::String.nullable(false))
5033        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
5034        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5035        .finish(),
5036    column_comments: BTreeMap::from_iter([
5037        (
5038            "object_id",
5039            "The ID of the source, sink, table, index, materialized view, or subscription.",
5040        ),
5041        (
5042            "read_frontier",
5043            "The earliest timestamp at which the output is still readable.",
5044        ),
5045        (
5046            "write_frontier",
5047            "The next timestamp at which the output may change.",
5048        ),
5049    ]),
5050    is_retained_metrics_object: false,
5051    access: vec![PUBLIC_SELECT],
5052});
5053
5054/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
5055pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5056    name: "mz_global_frontiers",
5057    schema: MZ_INTERNAL_SCHEMA,
5058    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5059    desc: RelationDesc::builder()
5060        .with_column("object_id", SqlScalarType::String.nullable(false))
5061        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
5062        .finish(),
5063    column_comments: BTreeMap::new(),
5064    sql: "
5065SELECT object_id, write_frontier AS time
5066FROM mz_internal.mz_frontiers
5067WHERE write_frontier IS NOT NULL",
5068    access: vec![PUBLIC_SELECT],
5069});
5070
5071pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5072    name: "mz_wallclock_lag_history",
5073    schema: MZ_INTERNAL_SCHEMA,
5074    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5075    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5076    data_source: IntrospectionType::WallclockLagHistory,
5077    column_comments: BTreeMap::from_iter([
5078        (
5079            "object_id",
5080            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5081        ),
5082        (
5083            "replica_id",
5084            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5085        ),
5086        (
5087            "lag",
5088            "The amount of time the object's write frontier lags behind wallclock time.",
5089        ),
5090        (
5091            "occurred_at",
5092            "Wall-clock timestamp at which the event occurred.",
5093        ),
5094    ]),
5095    is_retained_metrics_object: false,
5096    access: vec![PUBLIC_SELECT],
5097});
5098
5099pub static MZ_WALLCLOCK_LAG_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(|| {
5100    BuiltinContinualTask {
5101    name: "mz_wallclock_lag_history_ct",
5102    schema: MZ_INTERNAL_SCHEMA,
5103    oid: oid::CT_MZ_WALLCLOCK_LAG_HISTORY_OID,
5104    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5105    sql: "
5106IN CLUSTER mz_catalog_server
5107ON INPUT mz_internal.mz_wallclock_lag_history AS (
5108    DELETE FROM mz_internal.mz_wallclock_lag_history_ct WHERE occurred_at + '30d' < mz_now();
5109    INSERT INTO mz_internal.mz_wallclock_lag_history_ct SELECT * FROM mz_internal.mz_wallclock_lag_history;
5110)",
5111            access: vec![PUBLIC_SELECT],
5112        }
5113});
5114
5115pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5116    name: "mz_wallclock_global_lag_history",
5117    schema: MZ_INTERNAL_SCHEMA,
5118    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5119    desc: RelationDesc::builder()
5120        .with_column("object_id", SqlScalarType::String.nullable(false))
5121        .with_column("lag", SqlScalarType::Interval.nullable(true))
5122        .with_column(
5123            "occurred_at",
5124            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5125        )
5126        .with_key(vec![0, 2])
5127        .finish(),
5128    column_comments: BTreeMap::new(),
5129    sql: "
5130WITH times_binned AS (
5131    SELECT
5132        object_id,
5133        lag,
5134        date_trunc('minute', occurred_at) AS occurred_at
5135    FROM mz_internal.mz_wallclock_lag_history
5136)
5137SELECT
5138    object_id,
5139    min(lag) AS lag,
5140    occurred_at
5141FROM times_binned
5142GROUP BY object_id, occurred_at
5143OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5144    access: vec![PUBLIC_SELECT],
5145});
5146
5147pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> =
5148    LazyLock::new(|| BuiltinView {
5149        name: "mz_wallclock_global_lag_recent_history",
5150        schema: MZ_INTERNAL_SCHEMA,
5151        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5152        desc: RelationDesc::builder()
5153            .with_column("object_id", SqlScalarType::String.nullable(false))
5154            .with_column("lag", SqlScalarType::Interval.nullable(true))
5155            .with_column(
5156                "occurred_at",
5157                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5158            )
5159            .with_key(vec![0, 2])
5160            .finish(),
5161        column_comments: BTreeMap::new(),
5162        sql: "
5163SELECT object_id, lag, occurred_at
5164FROM mz_internal.mz_wallclock_global_lag_history
5165WHERE occurred_at + '1 day' > mz_now()",
5166        access: vec![PUBLIC_SELECT],
5167    });
5168
5169pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5170    name: "mz_wallclock_global_lag",
5171    schema: MZ_INTERNAL_SCHEMA,
5172    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5173    desc: RelationDesc::builder()
5174        .with_column("object_id", SqlScalarType::String.nullable(false))
5175        .with_column("lag", SqlScalarType::Interval.nullable(true))
5176        .with_key(vec![0])
5177        .finish(),
5178    column_comments: BTreeMap::from_iter([
5179        (
5180            "object_id",
5181            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5182        ),
5183        (
5184            "lag",
5185            "The amount of time the object's write frontier lags behind wallclock time.",
5186        ),
5187    ]),
5188    sql: "
5189SELECT DISTINCT ON (object_id) object_id, lag
5190FROM mz_internal.mz_wallclock_global_lag_recent_history
5191WHERE occurred_at + '5 minutes' > mz_now()
5192ORDER BY object_id, occurred_at DESC",
5193    access: vec![PUBLIC_SELECT],
5194});
5195
5196pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5197    LazyLock::new(|| BuiltinSource {
5198        name: "mz_wallclock_global_lag_histogram_raw",
5199        schema: MZ_INTERNAL_SCHEMA,
5200        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5201        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5202        column_comments: BTreeMap::new(),
5203        data_source: IntrospectionType::WallclockLagHistogram,
5204        is_retained_metrics_object: false,
5205        access: vec![PUBLIC_SELECT],
5206    });
5207
5208pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5209    LazyLock::new(|| BuiltinView {
5210        name: "mz_wallclock_global_lag_histogram",
5211        schema: MZ_INTERNAL_SCHEMA,
5212        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5213        desc: RelationDesc::builder()
5214            .with_column(
5215                "period_start",
5216                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5217            )
5218            .with_column(
5219                "period_end",
5220                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5221            )
5222            .with_column("object_id", SqlScalarType::String.nullable(false))
5223            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
5224            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
5225            .with_column("count", SqlScalarType::Int64.nullable(false))
5226            .with_key(vec![0, 1, 2, 3, 4])
5227            .finish(),
5228        column_comments: BTreeMap::new(),
5229        sql: "
5230SELECT *, count(*) AS count
5231FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5232GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5233        access: vec![PUBLIC_SELECT],
5234    });
5235
5236pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5237    BuiltinSource {
5238        name: "mz_materialized_view_refreshes",
5239        schema: MZ_INTERNAL_SCHEMA,
5240        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5241        data_source: IntrospectionType::ComputeMaterializedViewRefreshes,
5242        desc: RelationDesc::builder()
5243            .with_column(
5244                "materialized_view_id",
5245                SqlScalarType::String.nullable(false),
5246            )
5247            .with_column(
5248                "last_completed_refresh",
5249                SqlScalarType::MzTimestamp.nullable(true),
5250            )
5251            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
5252            .finish(),
5253        column_comments: BTreeMap::from_iter([
5254            (
5255                "materialized_view_id",
5256                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5257            ),
5258            (
5259                "last_completed_refresh",
5260                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5261            ),
5262            (
5263                "next_refresh",
5264                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5265            ),
5266        ]),
5267        is_retained_metrics_object: false,
5268        access: vec![PUBLIC_SELECT],
5269    }
5270});
5271
5272pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5273    name: "mz_subscriptions",
5274    schema: MZ_INTERNAL_SCHEMA,
5275    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5276    desc: RelationDesc::builder()
5277        .with_column("id", SqlScalarType::String.nullable(false))
5278        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
5279        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5280        .with_column(
5281            "created_at",
5282            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5283        )
5284        .with_column(
5285            "referenced_object_ids",
5286            SqlScalarType::List {
5287                element_type: Box::new(SqlScalarType::String),
5288                custom_id: None,
5289            }
5290            .nullable(false),
5291        )
5292        .finish(),
5293    column_comments: BTreeMap::from_iter([
5294        ("id", "The ID of the subscription."),
5295        (
5296            "session_id",
5297            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5298        ),
5299        (
5300            "cluster_id",
5301            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5302        ),
5303        (
5304            "created_at",
5305            "The time at which the subscription was created.",
5306        ),
5307        (
5308            "referenced_object_ids",
5309            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5310        ),
5311    ]),
5312    is_retained_metrics_object: false,
5313    access: vec![PUBLIC_SELECT],
5314});
5315
5316pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5317    name: "mz_sessions",
5318    schema: MZ_INTERNAL_SCHEMA,
5319    oid: oid::TABLE_MZ_SESSIONS_OID,
5320    desc: RelationDesc::builder()
5321        .with_column("id", SqlScalarType::Uuid.nullable(false))
5322        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
5323        .with_column("role_id", SqlScalarType::String.nullable(false))
5324        .with_column("client_ip", SqlScalarType::String.nullable(true))
5325        .with_column(
5326            "connected_at",
5327            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5328        )
5329        .finish(),
5330    column_comments: BTreeMap::from_iter([
5331        ("id", "The globally unique ID of the session."),
5332        (
5333            "connection_id",
5334            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5335        ),
5336        (
5337            "role_id",
5338            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5339        ),
5340        (
5341            "client_ip",
5342            "The IP address of the client that initiated the session.",
5343        ),
5344        (
5345            "connected_at",
5346            "The time at which the session connected to the system.",
5347        ),
5348    ]),
5349    is_retained_metrics_object: false,
5350    access: vec![PUBLIC_SELECT],
5351});
5352
5353pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5354    name: "mz_default_privileges",
5355    schema: MZ_CATALOG_SCHEMA,
5356    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5357    desc: RelationDesc::builder()
5358        .with_column("role_id", SqlScalarType::String.nullable(false))
5359        .with_column("database_id", SqlScalarType::String.nullable(true))
5360        .with_column("schema_id", SqlScalarType::String.nullable(true))
5361        .with_column("object_type", SqlScalarType::String.nullable(false))
5362        .with_column("grantee", SqlScalarType::String.nullable(false))
5363        .with_column("privileges", SqlScalarType::String.nullable(false))
5364        .finish(),
5365    column_comments: BTreeMap::from_iter([
5366        (
5367            "role_id",
5368            "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.",
5369        ),
5370        (
5371            "database_id",
5372            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5373        ),
5374        (
5375            "schema_id",
5376            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5377        ),
5378        (
5379            "object_type",
5380            "Privileges described in this row will be granted only on objects of type `object_type`.",
5381        ),
5382        (
5383            "grantee",
5384            "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.",
5385        ),
5386        ("privileges", "The set of privileges that will be granted."),
5387    ]),
5388    is_retained_metrics_object: false,
5389    access: vec![PUBLIC_SELECT],
5390});
5391
5392pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5393    name: "mz_system_privileges",
5394    schema: MZ_CATALOG_SCHEMA,
5395    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5396    desc: RelationDesc::builder()
5397        .with_column("privileges", SqlScalarType::MzAclItem.nullable(false))
5398        .finish(),
5399    column_comments: BTreeMap::from_iter([(
5400        "privileges",
5401        "The privileges belonging to the system.",
5402    )]),
5403    is_retained_metrics_object: false,
5404    access: vec![PUBLIC_SELECT],
5405});
5406
5407pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5408    name: "mz_comments",
5409    schema: MZ_INTERNAL_SCHEMA,
5410    oid: oid::TABLE_MZ_COMMENTS_OID,
5411    desc: RelationDesc::builder()
5412        .with_column("id", SqlScalarType::String.nullable(false))
5413        .with_column("object_type", SqlScalarType::String.nullable(false))
5414        .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
5415        .with_column("comment", SqlScalarType::String.nullable(false))
5416        .finish(),
5417    column_comments: BTreeMap::from_iter([
5418        (
5419            "id",
5420            "The ID of the object. Corresponds to `mz_objects.id`.",
5421        ),
5422        (
5423            "object_type",
5424            "The type of object the comment is associated with.",
5425        ),
5426        (
5427            "object_sub_id",
5428            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5429        ),
5430        ("comment", "The comment itself."),
5431    ]),
5432    is_retained_metrics_object: false,
5433    access: vec![PUBLIC_SELECT],
5434});
5435
5436pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5437    name: "mz_source_references",
5438    schema: MZ_INTERNAL_SCHEMA,
5439    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5440    desc: RelationDesc::builder()
5441        .with_column("source_id", SqlScalarType::String.nullable(false))
5442        .with_column("namespace", SqlScalarType::String.nullable(true))
5443        .with_column("name", SqlScalarType::String.nullable(false))
5444        .with_column(
5445            "updated_at",
5446            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5447        )
5448        .with_column(
5449            "columns",
5450            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5451        )
5452        .finish(),
5453    column_comments: BTreeMap::new(),
5454    is_retained_metrics_object: false,
5455    access: vec![PUBLIC_SELECT],
5456});
5457
5458pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5459    name: "mz_webhook_sources",
5460    schema: MZ_INTERNAL_SCHEMA,
5461    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5462    desc: RelationDesc::builder()
5463        .with_column("id", SqlScalarType::String.nullable(false))
5464        .with_column("name", SqlScalarType::String.nullable(false))
5465        .with_column("url", SqlScalarType::String.nullable(false))
5466        .finish(),
5467    column_comments: BTreeMap::from_iter([
5468        (
5469            "id",
5470            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5471        ),
5472        ("name", "The name of the webhook source."),
5473        (
5474            "url",
5475            "The URL which can be used to send events to the source.",
5476        ),
5477    ]),
5478    is_retained_metrics_object: false,
5479    access: vec![PUBLIC_SELECT],
5480});
5481
5482pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5483    BuiltinTable {
5484        name: "mz_history_retention_strategies",
5485        schema: MZ_INTERNAL_SCHEMA,
5486        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5487        desc: RelationDesc::builder()
5488            .with_column("id", SqlScalarType::String.nullable(false))
5489            .with_column("strategy", SqlScalarType::String.nullable(false))
5490            .with_column("value", SqlScalarType::Jsonb.nullable(false))
5491            .finish(),
5492        column_comments: BTreeMap::from_iter([
5493            ("id", "The ID of the object."),
5494            (
5495                "strategy",
5496                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5497            ),
5498            (
5499                "value",
5500                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5501            ),
5502        ]),
5503        is_retained_metrics_object: false,
5504        access: vec![PUBLIC_SELECT],
5505    }
5506});
5507
5508pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5509    name: "mz_license_keys",
5510    schema: MZ_INTERNAL_SCHEMA,
5511    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
5512    desc: RelationDesc::builder()
5513        .with_column("id", SqlScalarType::String.nullable(false))
5514        .with_column("organization", SqlScalarType::String.nullable(false))
5515        .with_column("environment_id", SqlScalarType::String.nullable(false))
5516        .with_column(
5517            "expiration",
5518            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5519        )
5520        .with_column(
5521            "not_before",
5522            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5523        )
5524        .finish(),
5525    column_comments: BTreeMap::from_iter([
5526        ("id", "The identifier of the license key."),
5527        (
5528            "organization",
5529            "The name of the organization that this license key was issued to.",
5530        ),
5531        (
5532            "environment_id",
5533            "The environment ID that this license key was issued for.",
5534        ),
5535        (
5536            "expiration",
5537            "The date and time when this license key expires.",
5538        ),
5539        (
5540            "not_before",
5541            "The start of the validity period for this license key.",
5542        ),
5543    ]),
5544    is_retained_metrics_object: false,
5545    access: vec![PUBLIC_SELECT],
5546});
5547
5548// These will be replaced with per-replica tables once source/sink multiplexing on
5549// a single cluster is supported.
5550pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5551    name: "mz_source_statistics_raw",
5552    schema: MZ_INTERNAL_SCHEMA,
5553    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5554    data_source: IntrospectionType::StorageSourceStatistics,
5555    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5556    column_comments: BTreeMap::new(),
5557    is_retained_metrics_object: true,
5558    access: vec![PUBLIC_SELECT],
5559});
5560pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5561    name: "mz_sink_statistics_raw",
5562    schema: MZ_INTERNAL_SCHEMA,
5563    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5564    data_source: IntrospectionType::StorageSinkStatistics,
5565    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5566    column_comments: BTreeMap::new(),
5567    is_retained_metrics_object: true,
5568    access: vec![PUBLIC_SELECT],
5569});
5570
5571pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5572    name: "mz_storage_shards",
5573    schema: MZ_INTERNAL_SCHEMA,
5574    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5575    data_source: IntrospectionType::ShardMapping,
5576    desc: RelationDesc::builder()
5577        .with_column("object_id", SqlScalarType::String.nullable(false))
5578        .with_column("shard_id", SqlScalarType::String.nullable(false))
5579        .finish(),
5580    column_comments: BTreeMap::new(),
5581    is_retained_metrics_object: false,
5582    access: vec![PUBLIC_SELECT],
5583});
5584
5585pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5586    name: "mz_storage_usage",
5587    schema: MZ_CATALOG_SCHEMA,
5588    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5589    desc: RelationDesc::builder()
5590        .with_column("object_id", SqlScalarType::String.nullable(false))
5591        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5592        .with_column(
5593            "collection_timestamp",
5594            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5595        )
5596        .with_key(vec![0, 2])
5597        .finish(),
5598    column_comments: BTreeMap::from_iter([
5599        (
5600            "object_id",
5601            "The ID of the table, source, or materialized view.",
5602        ),
5603        (
5604            "size_bytes",
5605            "The number of storage bytes used by the object.",
5606        ),
5607        (
5608            "collection_timestamp",
5609            "The time at which storage usage of the object was assessed.",
5610        ),
5611    ]),
5612    sql: "
5613SELECT
5614    object_id,
5615    sum(size_bytes)::uint8 AS size_bytes,
5616    collection_timestamp
5617FROM
5618    mz_internal.mz_storage_shards
5619    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5620GROUP BY object_id, collection_timestamp",
5621    access: vec![PUBLIC_SELECT],
5622});
5623
5624pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5625    BuiltinView {
5626    name: "mz_recent_storage_usage",
5627    schema: MZ_CATALOG_SCHEMA,
5628    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
5629    desc: RelationDesc::builder()
5630        .with_column("object_id", SqlScalarType::String.nullable(false))
5631        .with_column("size_bytes", SqlScalarType::UInt64.nullable(true))
5632        .with_key(vec![0])
5633        .finish(),
5634    column_comments: BTreeMap::from_iter([
5635        ("object_id", "The ID of the table, source, or materialized view."),
5636        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
5637    ]),
5638    sql: "
5639WITH
5640
5641recent_storage_usage_by_shard AS (
5642    SELECT shard_id, size_bytes, collection_timestamp
5643    FROM mz_internal.mz_storage_usage_by_shard
5644    -- Restricting to the last 6 hours makes it feasible to index the view.
5645    WHERE collection_timestamp + '6 hours' >= mz_now()
5646),
5647
5648most_recent_collection_timestamp_by_shard AS (
5649    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
5650    FROM recent_storage_usage_by_shard
5651    GROUP BY shard_id
5652)
5653
5654SELECT
5655    object_id,
5656    sum(size_bytes)::uint8 AS size_bytes
5657FROM
5658    mz_internal.mz_storage_shards
5659    LEFT JOIN most_recent_collection_timestamp_by_shard
5660        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
5661    LEFT JOIN recent_storage_usage_by_shard
5662        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
5663        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
5664GROUP BY object_id",
5665    access: vec![PUBLIC_SELECT],
5666}
5667});
5668
5669pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
5670    name: "mz_recent_storage_usage_ind",
5671    schema: MZ_CATALOG_SCHEMA,
5672    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
5673    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
5674    is_retained_metrics_object: false,
5675});
5676
5677pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
5678    BuiltinView {
5679        name: "mz_relations",
5680        schema: MZ_CATALOG_SCHEMA,
5681        oid: oid::VIEW_MZ_RELATIONS_OID,
5682        desc: RelationDesc::builder()
5683            .with_column("id", SqlScalarType::String.nullable(false))
5684            .with_column("oid", SqlScalarType::Oid.nullable(false))
5685            .with_column("schema_id", SqlScalarType::String.nullable(false))
5686            .with_column("name", SqlScalarType::String.nullable(false))
5687            .with_column("type", SqlScalarType::String.nullable(false))
5688            .with_column("owner_id", SqlScalarType::String.nullable(false))
5689            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5690            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false))
5691            .finish(),
5692        column_comments: BTreeMap::from_iter([
5693            ("id", "Materialize's unique ID for the relation."),
5694            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the relation."),
5695            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
5696            ("name", "The name of the relation."),
5697            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
5698            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
5699            ("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."),
5700            ("privileges", "The privileges belonging to the relation."),
5701        ]),
5702        sql: "
5703      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
5704UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
5705UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
5706UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views
5707UNION ALL SELECT id, oid, schema_id, name, 'continual-task', owner_id, cluster_id, privileges FROM mz_internal.mz_continual_tasks",
5708        access: vec![PUBLIC_SELECT],
5709    }
5710});
5711
5712pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5713    name: "mz_objects_id_namespace_types",
5714    schema: MZ_INTERNAL_SCHEMA,
5715    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
5716    desc: RelationDesc::builder()
5717        .with_column("object_type", SqlScalarType::String.nullable(false))
5718        .with_key(vec![0])
5719        .finish(),
5720    column_comments: BTreeMap::new(),
5721    sql: r#"SELECT *
5722    FROM (
5723        VALUES
5724            ('table'),
5725            ('view'),
5726            ('materialized-view'),
5727            ('source'),
5728            ('sink'),
5729            ('index'),
5730            ('connection'),
5731            ('type'),
5732            ('function'),
5733            ('secret')
5734    )
5735    AS _ (object_type)"#,
5736    access: vec![PUBLIC_SELECT],
5737});
5738
5739pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5740    name: "mz_object_oid_alias",
5741    schema: MZ_INTERNAL_SCHEMA,
5742    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
5743    desc: RelationDesc::builder()
5744        .with_column("object_type", SqlScalarType::String.nullable(false))
5745        .with_column("oid_alias", SqlScalarType::String.nullable(false))
5746        .with_key(vec![0])
5747        .finish(),
5748    column_comments: BTreeMap::new(),
5749    sql: "SELECT object_type, oid_alias
5750    FROM (
5751        VALUES
5752            (
5753                'table'::pg_catalog.text,
5754                'regclass'::pg_catalog.text
5755            ),
5756            ('source', 'regclass'),
5757            ('view', 'regclass'),
5758            ('materialized-view', 'regclass'),
5759            ('index', 'regclass'),
5760            ('type', 'regtype'),
5761            ('function', 'regproc')
5762    )
5763    AS _ (object_type, oid_alias);",
5764    access: vec![PUBLIC_SELECT],
5765});
5766
5767pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
5768    BuiltinView {
5769        name: "mz_objects",
5770        schema: MZ_CATALOG_SCHEMA,
5771        oid: oid::VIEW_MZ_OBJECTS_OID,
5772        desc: RelationDesc::builder()
5773            .with_column("id", SqlScalarType::String.nullable(false))
5774            .with_column("oid", SqlScalarType::Oid.nullable(false))
5775            .with_column("schema_id", SqlScalarType::String.nullable(false))
5776            .with_column("name", SqlScalarType::String.nullable(false))
5777            .with_column("type", SqlScalarType::String.nullable(false))
5778            .with_column("owner_id", SqlScalarType::String.nullable(false))
5779            .with_column("cluster_id", SqlScalarType::String.nullable(true))
5780            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(true))
5781            .finish(),
5782        column_comments: BTreeMap::from_iter([
5783            ("id", "Materialize's unique ID for the object."),
5784            ("oid", "A [PostgreSQL-compatible OID][`oid`] for the object."),
5785            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
5786            ("name", "The name of the object."),
5787            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
5788            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
5789            ("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."),
5790            ("privileges", "The privileges belonging to the object."),
5791        ]),
5792        sql:
5793        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
5794UNION ALL
5795    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
5796UNION ALL
5797    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[]
5798    FROM mz_catalog.mz_indexes
5799    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
5800UNION ALL
5801    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
5802UNION ALL
5803    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
5804UNION ALL
5805    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
5806UNION ALL
5807    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
5808        access: vec![PUBLIC_SELECT],
5809    }
5810});
5811
5812pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5813    name: "mz_object_fully_qualified_names",
5814    schema: MZ_INTERNAL_SCHEMA,
5815    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
5816    desc: RelationDesc::builder()
5817        .with_column("id", SqlScalarType::String.nullable(false))
5818        .with_column("name", SqlScalarType::String.nullable(false))
5819        .with_column("object_type", SqlScalarType::String.nullable(false))
5820        .with_column("schema_id", SqlScalarType::String.nullable(false))
5821        .with_column("schema_name", SqlScalarType::String.nullable(false))
5822        .with_column("database_id", SqlScalarType::String.nullable(true))
5823        .with_column("database_name", SqlScalarType::String.nullable(true))
5824        .with_column("cluster_id", SqlScalarType::String.nullable(true))
5825        .finish(),
5826    column_comments: BTreeMap::from_iter([
5827        ("id", "Materialize's unique ID for the object."),
5828        ("name", "The name of the object."),
5829        (
5830            "object_type",
5831            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5832        ),
5833        (
5834            "schema_id",
5835            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
5836        ),
5837        (
5838            "schema_name",
5839            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
5840        ),
5841        (
5842            "database_id",
5843            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
5844        ),
5845        (
5846            "database_name",
5847            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
5848        ),
5849        (
5850            "cluster_id",
5851            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
5852        ),
5853    ]),
5854    sql: "
5855    SELECT o.id,
5856        o.name,
5857        o.type as object_type,
5858        sc.id as schema_id,
5859        sc.name as schema_name,
5860        db.id as database_id,
5861        db.name as database_name,
5862        o.cluster_id
5863    FROM mz_catalog.mz_objects o
5864    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
5865    -- LEFT JOIN accounts for objects in the ambient database.
5866    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
5867    access: vec![PUBLIC_SELECT],
5868});
5869
5870// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
5871pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5872    name: "mz_object_lifetimes",
5873    schema: MZ_INTERNAL_SCHEMA,
5874    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
5875    desc: RelationDesc::builder()
5876        .with_column("id", SqlScalarType::String.nullable(true))
5877        .with_column("previous_id", SqlScalarType::String.nullable(true))
5878        .with_column("object_type", SqlScalarType::String.nullable(false))
5879        .with_column("event_type", SqlScalarType::String.nullable(false))
5880        .with_column(
5881            "occurred_at",
5882            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5883        )
5884        .finish(),
5885    column_comments: BTreeMap::from_iter([
5886        ("id", "Materialize's unique ID for the object."),
5887        ("previous_id", "The object's previous ID, if one exists."),
5888        (
5889            "object_type",
5890            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5891        ),
5892        (
5893            "event_type",
5894            "The lifetime event, either `create` or `drop`.",
5895        ),
5896        (
5897            "occurred_at",
5898            "Wall-clock timestamp of when the event occurred.",
5899        ),
5900    ]),
5901    sql: "
5902    SELECT
5903        CASE
5904            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
5905            ELSE a.details ->> 'id'
5906        END id,
5907        a.details ->> 'previous_id' as previous_id,
5908        a.object_type,
5909        a.event_type,
5910        a.occurred_at
5911    FROM mz_catalog.mz_audit_events a
5912    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
5913    access: vec![PUBLIC_SELECT],
5914});
5915
5916pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5917    name: "mz_object_history",
5918    schema: MZ_INTERNAL_SCHEMA,
5919    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
5920    desc: RelationDesc::builder()
5921        .with_column("id", SqlScalarType::String.nullable(true))
5922        .with_column("cluster_id", SqlScalarType::String.nullable(true))
5923        .with_column("object_type", SqlScalarType::String.nullable(false))
5924        .with_column(
5925            "created_at",
5926            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5927        )
5928        .with_column(
5929            "dropped_at",
5930            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5931        )
5932        .finish(),
5933    column_comments: BTreeMap::from_iter([
5934        ("id", "Materialize's unique ID for the object."),
5935        (
5936            "cluster_id",
5937            "The object's cluster ID. `NULL` if the object has no associated cluster.",
5938        ),
5939        (
5940            "object_type",
5941            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
5942        ),
5943        (
5944            "created_at",
5945            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
5946        ),
5947        (
5948            "dropped_at",
5949            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
5950        ),
5951    ]),
5952    sql: r#"
5953    WITH
5954        creates AS
5955        (
5956            SELECT
5957                details ->> 'id' AS id,
5958                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
5959                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
5960                object_type,
5961                occurred_at
5962            FROM
5963                mz_catalog.mz_audit_events AS events
5964                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
5965            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
5966        ),
5967        drops AS
5968        (
5969            SELECT details ->> 'id' AS id, occurred_at
5970            FROM mz_catalog.mz_audit_events
5971            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
5972        ),
5973        user_object_history AS
5974        (
5975            SELECT
5976                creates.id,
5977                creates.cluster_id,
5978                creates.object_type,
5979                creates.occurred_at AS created_at,
5980                drops.occurred_at AS dropped_at
5981            FROM creates LEFT JOIN drops ON creates.id = drops.id
5982            WHERE creates.id LIKE 'u%'
5983        ),
5984        -- We need to union built in objects since they aren't in the audit log
5985        built_in_objects AS
5986        (
5987            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
5988            SELECT DISTINCT ON (objects.id)
5989                objects.id,
5990                objects.cluster_id,
5991                objects.type AS object_type,
5992                NULL::timestamptz AS created_at,
5993                NULL::timestamptz AS dropped_at
5994            FROM mz_catalog.mz_objects AS objects
5995            WHERE objects.id LIKE 's%'
5996        )
5997    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
5998    access: vec![PUBLIC_SELECT],
5999});
6000
6001pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6002    name: "mz_dataflows_per_worker",
6003    schema: MZ_INTROSPECTION_SCHEMA,
6004    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
6005    desc: RelationDesc::builder()
6006        .with_column("id", SqlScalarType::UInt64.nullable(true))
6007        .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6008        .with_column("name", SqlScalarType::String.nullable(false))
6009        .finish(),
6010    column_comments: BTreeMap::new(),
6011    sql: "SELECT
6012    addrs.address[1] AS id,
6013    ops.worker_id,
6014    ops.name
6015FROM
6016    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6017    mz_introspection.mz_dataflow_operators_per_worker ops
6018WHERE
6019    addrs.id = ops.id AND
6020    addrs.worker_id = ops.worker_id AND
6021    mz_catalog.list_length(addrs.address) = 1",
6022    access: vec![PUBLIC_SELECT],
6023});
6024
6025pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6026    name: "mz_dataflows",
6027    schema: MZ_INTROSPECTION_SCHEMA,
6028    oid: oid::VIEW_MZ_DATAFLOWS_OID,
6029    desc: RelationDesc::builder()
6030        .with_column("id", SqlScalarType::UInt64.nullable(true))
6031        .with_column("name", SqlScalarType::String.nullable(false))
6032        .finish(),
6033    column_comments: BTreeMap::from_iter([
6034        ("id", "The ID of the dataflow."),
6035        ("name", "The internal name of the dataflow."),
6036    ]),
6037    sql: "
6038SELECT id, name
6039FROM mz_introspection.mz_dataflows_per_worker
6040WHERE worker_id = 0",
6041    access: vec![PUBLIC_SELECT],
6042});
6043
6044pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6045    name: "mz_dataflow_addresses",
6046    schema: MZ_INTROSPECTION_SCHEMA,
6047    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
6048    desc: RelationDesc::builder()
6049        .with_column("id", SqlScalarType::UInt64.nullable(false))
6050        .with_column(
6051            "address",
6052            SqlScalarType::List {
6053                element_type: Box::new(SqlScalarType::UInt64),
6054                custom_id: None,
6055            }
6056            .nullable(false),
6057        )
6058        .finish(),
6059    column_comments: BTreeMap::from_iter([
6060        (
6061            "id",
6062            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
6063        ),
6064        (
6065            "address",
6066            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
6067        ),
6068    ]),
6069    sql: "
6070SELECT id, address
6071FROM mz_introspection.mz_dataflow_addresses_per_worker
6072WHERE worker_id = 0",
6073    access: vec![PUBLIC_SELECT],
6074});
6075
6076pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6077    name: "mz_dataflow_channels",
6078    schema: MZ_INTROSPECTION_SCHEMA,
6079    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
6080    desc: RelationDesc::builder()
6081        .with_column("id", SqlScalarType::UInt64.nullable(false))
6082        .with_column("from_index", SqlScalarType::UInt64.nullable(false))
6083        .with_column("from_port", SqlScalarType::UInt64.nullable(false))
6084        .with_column("to_index", SqlScalarType::UInt64.nullable(false))
6085        .with_column("to_port", SqlScalarType::UInt64.nullable(false))
6086        .with_column("type", SqlScalarType::String.nullable(false))
6087        .finish(),
6088    column_comments: BTreeMap::from_iter([
6089        ("id", "The ID of the channel."),
6090        (
6091            "from_index",
6092            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
6093        ),
6094        ("from_port", "The source operator's output port."),
6095        (
6096            "to_index",
6097            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
6098        ),
6099        ("to_port", "The target operator's input port."),
6100        ("type", "The container type of the channel."),
6101    ]),
6102    sql: "
6103SELECT id, from_index, from_port, to_index, to_port, type
6104FROM mz_introspection.mz_dataflow_channels_per_worker
6105WHERE worker_id = 0",
6106    access: vec![PUBLIC_SELECT],
6107});
6108
6109pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6110    name: "mz_dataflow_operators",
6111    schema: MZ_INTROSPECTION_SCHEMA,
6112    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6113    desc: RelationDesc::builder()
6114        .with_column("id", SqlScalarType::UInt64.nullable(false))
6115        .with_column("name", SqlScalarType::String.nullable(false))
6116        .finish(),
6117    column_comments: BTreeMap::from_iter([
6118        ("id", "The ID of the operator."),
6119        ("name", "The internal name of the operator."),
6120    ]),
6121    sql: "
6122SELECT id, name
6123FROM mz_introspection.mz_dataflow_operators_per_worker
6124WHERE worker_id = 0",
6125    access: vec![PUBLIC_SELECT],
6126});
6127
6128pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6129    name: "mz_dataflow_global_ids",
6130    schema: MZ_INTROSPECTION_SCHEMA,
6131    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6132    desc: RelationDesc::builder()
6133        .with_column("id", SqlScalarType::UInt64.nullable(false))
6134        .with_column("global_id", SqlScalarType::String.nullable(false))
6135        .finish(),
6136    column_comments: BTreeMap::from_iter([
6137        ("id", "The dataflow ID."),
6138        ("global_id", "A global ID associated with that dataflow."),
6139    ]),
6140    sql: "
6141SELECT id, global_id
6142FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6143WHERE worker_id = 0",
6144    access: vec![PUBLIC_SELECT],
6145});
6146
6147pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6148    BuiltinView {
6149    name: "mz_mappable_objects",
6150    schema: MZ_INTROSPECTION_SCHEMA,
6151    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6152    desc: RelationDesc::builder()
6153        .with_column("name", SqlScalarType::String.nullable(false))
6154        .with_column("global_id", SqlScalarType::String.nullable(false))
6155        .finish(),
6156    column_comments: BTreeMap::from_iter([
6157        ("name", "The name of the object."),
6158        ("global_id", "The global ID of the object."),
6159    ]),
6160    sql: "
6161SELECT quote_ident(md.name) || '.' || quote_ident(ms.name) || '.' || quote_ident(mo.name) AS name, mgi.global_id AS global_id
6162FROM      mz_catalog.mz_objects mo
6163     JOIN mz_introspection.mz_compute_exports mce ON (mo.id = mce.export_id)
6164     JOIN mz_catalog.mz_schemas ms ON (mo.schema_id = ms.id)
6165     JOIN mz_catalog.mz_databases md ON (ms.database_id = md.id)
6166     JOIN mz_introspection.mz_dataflow_global_ids mgi ON (mce.dataflow_id = mgi.id);",
6167    access: vec![PUBLIC_SELECT],
6168}
6169});
6170
6171pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6172    name: "mz_lir_mapping",
6173    schema: MZ_INTROSPECTION_SCHEMA,
6174    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6175    desc: RelationDesc::builder()
6176        .with_column("global_id", SqlScalarType::String.nullable(false))
6177        .with_column("lir_id", SqlScalarType::UInt64.nullable(false))
6178        .with_column("operator", SqlScalarType::String.nullable(false))
6179        .with_column("parent_lir_id", SqlScalarType::UInt64.nullable(true))
6180        .with_column("nesting", SqlScalarType::UInt16.nullable(false))
6181        .with_column("operator_id_start", SqlScalarType::UInt64.nullable(false))
6182        .with_column("operator_id_end", SqlScalarType::UInt64.nullable(false))
6183        .finish(),
6184    column_comments: BTreeMap::from_iter([
6185        ("global_id", "The global ID."),
6186        ("lir_id", "The LIR node ID."),
6187        (
6188            "operator",
6189            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6190        ),
6191        (
6192            "parent_lir_id",
6193            "The parent of this LIR node. May be `NULL`.",
6194        ),
6195        ("nesting", "The nesting level of this LIR node."),
6196        (
6197            "operator_id_start",
6198            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6199        ),
6200        (
6201            "operator_id_end",
6202            "The first dataflow operator ID after this LIR operator (exclusive).",
6203        ),
6204    ]),
6205    sql: "
6206SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6207FROM mz_introspection.mz_compute_lir_mapping_per_worker
6208WHERE worker_id = 0",
6209    access: vec![PUBLIC_SELECT],
6210});
6211
6212pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6213    LazyLock::new(|| BuiltinView {
6214        name: "mz_dataflow_operator_dataflows_per_worker",
6215        schema: MZ_INTROSPECTION_SCHEMA,
6216        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6217        desc: RelationDesc::builder()
6218            .with_column("id", SqlScalarType::UInt64.nullable(false))
6219            .with_column("name", SqlScalarType::String.nullable(false))
6220            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6221            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6222            .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6223            .finish(),
6224        column_comments: BTreeMap::new(),
6225        sql: "SELECT
6226    ops.id,
6227    ops.name,
6228    ops.worker_id,
6229    dfs.id as dataflow_id,
6230    dfs.name as dataflow_name
6231FROM
6232    mz_introspection.mz_dataflow_operators_per_worker ops,
6233    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6234    mz_introspection.mz_dataflows_per_worker dfs
6235WHERE
6236    ops.id = addrs.id AND
6237    ops.worker_id = addrs.worker_id AND
6238    dfs.id = addrs.address[1] AND
6239    dfs.worker_id = addrs.worker_id",
6240        access: vec![PUBLIC_SELECT],
6241    });
6242
6243pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6244    name: "mz_dataflow_operator_dataflows",
6245    schema: MZ_INTROSPECTION_SCHEMA,
6246    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6247    desc: RelationDesc::builder()
6248        .with_column("id", SqlScalarType::UInt64.nullable(false))
6249        .with_column("name", SqlScalarType::String.nullable(false))
6250        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6251        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6252        .finish(),
6253    column_comments: BTreeMap::from_iter([
6254        (
6255            "id",
6256            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6257        ),
6258        ("name", "The internal name of the operator."),
6259        (
6260            "dataflow_id",
6261            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6262        ),
6263        (
6264            "dataflow_name",
6265            "The internal name of the dataflow hosting the operator.",
6266        ),
6267    ]),
6268    sql: "
6269SELECT id, name, dataflow_id, dataflow_name
6270FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6271WHERE worker_id = 0",
6272    access: vec![PUBLIC_SELECT],
6273});
6274
6275pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6276    BuiltinView {
6277        name: "mz_object_transitive_dependencies",
6278        schema: MZ_INTERNAL_SCHEMA,
6279        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6280        desc: RelationDesc::builder()
6281            .with_column("object_id", SqlScalarType::String.nullable(false))
6282            .with_column(
6283                "referenced_object_id",
6284                SqlScalarType::String.nullable(false),
6285            )
6286            .with_key(vec![0, 1])
6287            .finish(),
6288        column_comments: BTreeMap::from_iter([
6289            (
6290                "object_id",
6291                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6292            ),
6293            (
6294                "referenced_object_id",
6295                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6296            ),
6297        ]),
6298        sql: "
6299WITH MUTUALLY RECURSIVE
6300  reach(object_id text, referenced_object_id text) AS (
6301    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6302    UNION
6303    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6304  )
6305SELECT object_id, referenced_object_id FROM reach;",
6306        access: vec![PUBLIC_SELECT],
6307    }
6308});
6309
6310pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6311    name: "mz_compute_exports",
6312    schema: MZ_INTROSPECTION_SCHEMA,
6313    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6314    desc: RelationDesc::builder()
6315        .with_column("export_id", SqlScalarType::String.nullable(false))
6316        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6317        .finish(),
6318    column_comments: BTreeMap::from_iter([
6319        (
6320            "export_id",
6321            "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`.",
6322        ),
6323        (
6324            "dataflow_id",
6325            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6326        ),
6327    ]),
6328    sql: "
6329SELECT export_id, dataflow_id
6330FROM mz_introspection.mz_compute_exports_per_worker
6331WHERE worker_id = 0",
6332    access: vec![PUBLIC_SELECT],
6333});
6334
6335pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6336    name: "mz_compute_frontiers",
6337    schema: MZ_INTROSPECTION_SCHEMA,
6338    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6339    desc: RelationDesc::builder()
6340        .with_column("export_id", SqlScalarType::String.nullable(false))
6341        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6342        .with_key(vec![0])
6343        .finish(),
6344    column_comments: BTreeMap::from_iter([
6345        (
6346            "export_id",
6347            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6348        ),
6349        (
6350            "time",
6351            "The next timestamp at which the dataflow output may change.",
6352        ),
6353    ]),
6354    sql: "SELECT
6355    export_id, pg_catalog.min(time) AS time
6356FROM mz_introspection.mz_compute_frontiers_per_worker
6357GROUP BY export_id",
6358    access: vec![PUBLIC_SELECT],
6359});
6360
6361pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6362    LazyLock::new(|| BuiltinView {
6363        name: "mz_dataflow_channel_operators_per_worker",
6364        schema: MZ_INTROSPECTION_SCHEMA,
6365        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6366        desc: RelationDesc::builder()
6367            .with_column("id", SqlScalarType::UInt64.nullable(false))
6368            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6369            .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6370            .with_column(
6371                "from_operator_address",
6372                SqlScalarType::List {
6373                    element_type: Box::new(SqlScalarType::UInt64),
6374                    custom_id: None,
6375                }
6376                .nullable(true),
6377            )
6378            .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6379            .with_column(
6380                "to_operator_address",
6381                SqlScalarType::List {
6382                    element_type: Box::new(SqlScalarType::UInt64),
6383                    custom_id: None,
6384                }
6385                .nullable(true),
6386            )
6387            .with_column("type", SqlScalarType::String.nullable(false))
6388            .finish(),
6389        column_comments: BTreeMap::new(),
6390        sql: "
6391WITH
6392channel_addresses(id, worker_id, address, from_index, to_index, type) AS (
6393     SELECT id, worker_id, address, from_index, to_index, type
6394     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6395     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6396     USING (id, worker_id)
6397),
6398channel_operator_addresses(id, worker_id, from_address, to_address, type) AS (
6399     SELECT id, worker_id,
6400            address || from_index AS from_address,
6401            address || to_index AS to_address,
6402            type
6403     FROM channel_addresses
6404),
6405operator_addresses(id, worker_id, address) AS (
6406     SELECT id, worker_id, address
6407     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6408     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6409     USING (id, worker_id)
6410)
6411SELECT coa.id,
6412       coa.worker_id,
6413       from_ops.id AS from_operator_id,
6414       coa.from_address AS from_operator_address,
6415       to_ops.id AS to_operator_id,
6416       coa.to_address AS to_operator_address,
6417       coa.type
6418FROM channel_operator_addresses coa
6419     LEFT OUTER JOIN operator_addresses from_ops
6420          ON coa.from_address = from_ops.address AND
6421             coa.worker_id = from_ops.worker_id
6422     LEFT OUTER JOIN operator_addresses to_ops
6423          ON coa.to_address = to_ops.address AND
6424             coa.worker_id = to_ops.worker_id
6425",
6426        access: vec![PUBLIC_SELECT],
6427    });
6428
6429pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6430    name: "mz_dataflow_channel_operators",
6431    schema: MZ_INTROSPECTION_SCHEMA,
6432    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6433    desc: RelationDesc::builder()
6434        .with_column("id", SqlScalarType::UInt64.nullable(false))
6435        .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6436        .with_column(
6437            "from_operator_address",
6438            SqlScalarType::List {
6439                element_type: Box::new(SqlScalarType::UInt64),
6440                custom_id: None,
6441            }
6442            .nullable(true),
6443        )
6444        .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6445        .with_column(
6446            "to_operator_address",
6447            SqlScalarType::List {
6448                element_type: Box::new(SqlScalarType::UInt64),
6449                custom_id: None,
6450            }
6451            .nullable(true),
6452        )
6453        .with_column("type", SqlScalarType::String.nullable(false))
6454        .finish(),
6455    column_comments: BTreeMap::from_iter([
6456        (
6457            "id",
6458            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6459        ),
6460        (
6461            "from_operator_id",
6462            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6463        ),
6464        (
6465            "from_operator_address",
6466            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6467        ),
6468        (
6469            "to_operator_id",
6470            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6471        ),
6472        (
6473            "to_operator_address",
6474            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6475        ),
6476        ("type", "The container type of the channel."),
6477    ]),
6478    sql: "
6479SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address, type
6480FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6481WHERE worker_id = 0",
6482    access: vec![PUBLIC_SELECT],
6483});
6484
6485pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6486    name: "mz_compute_import_frontiers",
6487    schema: MZ_INTROSPECTION_SCHEMA,
6488    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6489    desc: RelationDesc::builder()
6490        .with_column("export_id", SqlScalarType::String.nullable(false))
6491        .with_column("import_id", SqlScalarType::String.nullable(false))
6492        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6493        .with_key(vec![0, 1])
6494        .finish(),
6495    column_comments: BTreeMap::from_iter([
6496        (
6497            "export_id",
6498            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6499        ),
6500        (
6501            "import_id",
6502            "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`.",
6503        ),
6504        (
6505            "time",
6506            "The next timestamp at which the dataflow input may change.",
6507        ),
6508    ]),
6509    sql: "SELECT
6510    export_id, import_id, pg_catalog.min(time) AS time
6511FROM mz_introspection.mz_compute_import_frontiers_per_worker
6512GROUP BY export_id, import_id",
6513    access: vec![PUBLIC_SELECT],
6514});
6515
6516pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6517    LazyLock::new(|| BuiltinView {
6518        name: "mz_records_per_dataflow_operator_per_worker",
6519        schema: MZ_INTROSPECTION_SCHEMA,
6520        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6521        desc: RelationDesc::builder()
6522            .with_column("id", SqlScalarType::UInt64.nullable(false))
6523            .with_column("name", SqlScalarType::String.nullable(false))
6524            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6525            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6526            .with_column("records", SqlScalarType::Int64.nullable(true))
6527            .with_column("batches", SqlScalarType::Int64.nullable(true))
6528            .with_column("size", SqlScalarType::Int64.nullable(true))
6529            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6530            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6531            .finish(),
6532        column_comments: BTreeMap::new(),
6533        sql: "
6534SELECT
6535    dod.id,
6536    dod.name,
6537    dod.worker_id,
6538    dod.dataflow_id,
6539    ar_size.records AS records,
6540    ar_size.batches AS batches,
6541    ar_size.size AS size,
6542    ar_size.capacity AS capacity,
6543    ar_size.allocations AS allocations
6544FROM
6545    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6546    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6547        dod.id = ar_size.operator_id AND
6548        dod.worker_id = ar_size.worker_id",
6549        access: vec![PUBLIC_SELECT],
6550    });
6551
6552pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6553    LazyLock::new(|| BuiltinView {
6554        name: "mz_records_per_dataflow_operator",
6555        schema: MZ_INTROSPECTION_SCHEMA,
6556        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6557        desc: RelationDesc::builder()
6558            .with_column("id", SqlScalarType::UInt64.nullable(false))
6559            .with_column("name", SqlScalarType::String.nullable(false))
6560            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6561            .with_column("records", SqlScalarType::Int64.nullable(true))
6562            .with_column("batches", SqlScalarType::Int64.nullable(true))
6563            .with_column("size", SqlScalarType::Int64.nullable(true))
6564            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6565            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6566            .with_key(vec![0, 1, 2])
6567            .finish(),
6568        column_comments: BTreeMap::from_iter([
6569            (
6570                "id",
6571                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6572            ),
6573            ("name", "The internal name of the operator."),
6574            (
6575                "dataflow_id",
6576                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6577            ),
6578            ("records", "The number of records in the operator."),
6579            ("batches", "The number of batches in the dataflow."),
6580            ("size", "The utilized size in bytes of the arrangement."),
6581            (
6582                "capacity",
6583                "The capacity in bytes of the arrangement. Can be larger than the size.",
6584            ),
6585            (
6586                "allocations",
6587                "The number of separate memory allocations backing the arrangement.",
6588            ),
6589        ]),
6590        sql: "
6591SELECT
6592    id,
6593    name,
6594    dataflow_id,
6595    SUM(records)::int8 AS records,
6596    SUM(batches)::int8 AS batches,
6597    SUM(size)::int8 AS size,
6598    SUM(capacity)::int8 AS capacity,
6599    SUM(allocations)::int8 AS allocations
6600FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
6601GROUP BY id, name, dataflow_id",
6602        access: vec![PUBLIC_SELECT],
6603    });
6604
6605pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
6606    LazyLock::new(|| BuiltinView {
6607        name: "mz_records_per_dataflow_per_worker",
6608        schema: MZ_INTROSPECTION_SCHEMA,
6609        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
6610        desc: RelationDesc::builder()
6611            .with_column("id", SqlScalarType::UInt64.nullable(false))
6612            .with_column("name", SqlScalarType::String.nullable(false))
6613            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6614            .with_column("records", SqlScalarType::Int64.nullable(true))
6615            .with_column("batches", SqlScalarType::Int64.nullable(true))
6616            .with_column("size", SqlScalarType::Int64.nullable(true))
6617            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6618            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6619            .with_key(vec![0, 1, 2])
6620            .finish(),
6621        column_comments: BTreeMap::new(),
6622        sql: "
6623SELECT
6624    rdo.dataflow_id as id,
6625    dfs.name,
6626    rdo.worker_id,
6627    SUM(rdo.records)::int8 as records,
6628    SUM(rdo.batches)::int8 as batches,
6629    SUM(rdo.size)::int8 as size,
6630    SUM(rdo.capacity)::int8 as capacity,
6631    SUM(rdo.allocations)::int8 as allocations
6632FROM
6633    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
6634    mz_introspection.mz_dataflows_per_worker dfs
6635WHERE
6636    rdo.dataflow_id = dfs.id AND
6637    rdo.worker_id = dfs.worker_id
6638GROUP BY
6639    rdo.dataflow_id,
6640    dfs.name,
6641    rdo.worker_id",
6642        access: vec![PUBLIC_SELECT],
6643    });
6644
6645pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6646    name: "mz_records_per_dataflow",
6647    schema: MZ_INTROSPECTION_SCHEMA,
6648    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
6649    desc: RelationDesc::builder()
6650        .with_column("id", SqlScalarType::UInt64.nullable(false))
6651        .with_column("name", SqlScalarType::String.nullable(false))
6652        .with_column("records", SqlScalarType::Int64.nullable(true))
6653        .with_column("batches", SqlScalarType::Int64.nullable(true))
6654        .with_column("size", SqlScalarType::Int64.nullable(true))
6655        .with_column("capacity", SqlScalarType::Int64.nullable(true))
6656        .with_column("allocations", SqlScalarType::Int64.nullable(true))
6657        .with_key(vec![0, 1])
6658        .finish(),
6659    column_comments: BTreeMap::from_iter([
6660        (
6661            "id",
6662            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6663        ),
6664        ("name", "The internal name of the dataflow."),
6665        ("records", "The number of records in the dataflow."),
6666        ("batches", "The number of batches in the dataflow."),
6667        ("size", "The utilized size in bytes of the arrangements."),
6668        (
6669            "capacity",
6670            "The capacity in bytes of the arrangements. Can be larger than the size.",
6671        ),
6672        (
6673            "allocations",
6674            "The number of separate memory allocations backing the arrangements.",
6675        ),
6676    ]),
6677    sql: "
6678SELECT
6679    id,
6680    name,
6681    SUM(records)::int8 as records,
6682    SUM(batches)::int8 as batches,
6683    SUM(size)::int8 as size,
6684    SUM(capacity)::int8 as capacity,
6685    SUM(allocations)::int8 as allocations
6686FROM
6687    mz_introspection.mz_records_per_dataflow_per_worker
6688GROUP BY
6689    id,
6690    name",
6691    access: vec![PUBLIC_SELECT],
6692});
6693
6694/// Peeled version of `PG_NAMESPACE`:
6695/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6696///   in order to make this view indexable.
6697/// - This has the database name as an extra column, so that downstream views can check it against
6698///  `current_database()`.
6699pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6700    name: "pg_namespace_all_databases",
6701    schema: MZ_INTERNAL_SCHEMA,
6702    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
6703    desc: RelationDesc::builder()
6704        .with_column("oid", SqlScalarType::Oid.nullable(false))
6705        .with_column("nspname", SqlScalarType::String.nullable(false))
6706        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6707        .with_column(
6708            "nspacl",
6709            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6710        )
6711        .with_column("database_name", SqlScalarType::String.nullable(true))
6712        .finish(),
6713    column_comments: BTreeMap::new(),
6714    sql: "
6715SELECT
6716    s.oid AS oid,
6717    s.name AS nspname,
6718    role_owner.oid AS nspowner,
6719    NULL::pg_catalog.text[] AS nspacl,
6720    d.name as database_name
6721FROM mz_catalog.mz_schemas s
6722LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
6723JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
6724    access: vec![PUBLIC_SELECT],
6725});
6726
6727pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6728    name: "pg_namespace_all_databases_ind",
6729    schema: MZ_INTERNAL_SCHEMA,
6730    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
6731    sql: "IN CLUSTER mz_catalog_server
6732ON mz_internal.pg_namespace_all_databases (nspname)",
6733    is_retained_metrics_object: false,
6734};
6735
6736pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6737    name: "pg_namespace",
6738    schema: PG_CATALOG_SCHEMA,
6739    oid: oid::VIEW_PG_NAMESPACE_OID,
6740    desc: RelationDesc::builder()
6741        .with_column("oid", SqlScalarType::Oid.nullable(false))
6742        .with_column("nspname", SqlScalarType::String.nullable(false))
6743        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
6744        .with_column(
6745            "nspacl",
6746            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6747        )
6748        .finish(),
6749    column_comments: BTreeMap::new(),
6750    sql: "
6751SELECT
6752    oid, nspname, nspowner, nspacl
6753FROM mz_internal.pg_namespace_all_databases
6754WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
6755    access: vec![PUBLIC_SELECT],
6756});
6757
6758/// Peeled version of `PG_CLASS`:
6759/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
6760///   in order to make this view indexable.
6761/// - This has the database name as an extra column, so that downstream views can check it against
6762///  `current_database()`.
6763pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
6764    BuiltinView {
6765        name: "pg_class_all_databases",
6766        schema: MZ_INTERNAL_SCHEMA,
6767        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
6768        desc: RelationDesc::builder()
6769            .with_column("oid", SqlScalarType::Oid.nullable(false))
6770            .with_column("relname", SqlScalarType::String.nullable(false))
6771            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
6772            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
6773            .with_column("relowner", SqlScalarType::Oid.nullable(false))
6774            .with_column("relam", SqlScalarType::Oid.nullable(false))
6775            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
6776            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
6777            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
6778            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
6779            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
6780            .with_column("relkind", SqlScalarType::String.nullable(true))
6781            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
6782            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
6783            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
6784            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
6785            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
6786            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
6787            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
6788            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
6789            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
6790            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
6791            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
6792            .with_column("database_name", SqlScalarType::String.nullable(true))
6793            .finish(),
6794        column_comments: BTreeMap::new(),
6795        sql: "
6796SELECT
6797    class_objects.oid,
6798    class_objects.name AS relname,
6799    mz_schemas.oid AS relnamespace,
6800    -- MZ doesn't support typed tables so reloftype is filled with 0
6801    0::pg_catalog.oid AS reloftype,
6802    role_owner.oid AS relowner,
6803    0::pg_catalog.oid AS relam,
6804    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
6805    0::pg_catalog.oid AS reltablespace,
6806    -- MZ doesn't support (estimated) row counts currently.
6807    -- Postgres defines a value of -1 as unknown.
6808    -1::float4 as reltuples,
6809    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
6810    0::pg_catalog.oid AS reltoastrelid,
6811    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
6812    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
6813    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
6814    -- TODO(jkosh44): update this column when issue is resolved.
6815    'p'::pg_catalog.\"char\" AS relpersistence,
6816    CASE
6817        WHEN class_objects.type = 'table' THEN 'r'
6818        WHEN class_objects.type = 'source' THEN 'r'
6819        WHEN class_objects.type = 'index' THEN 'i'
6820        WHEN class_objects.type = 'view' THEN 'v'
6821        WHEN class_objects.type = 'materialized-view' THEN 'm'
6822    END relkind,
6823    COALESCE(
6824        (
6825            SELECT count(*)::pg_catalog.int2
6826            FROM mz_catalog.mz_columns
6827            WHERE mz_columns.id = class_objects.id
6828        ),
6829        0::pg_catalog.int2
6830    ) AS relnatts,
6831    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
6832    0::pg_catalog.int2 AS relchecks,
6833    -- MZ doesn't support creating rules so relhasrules is filled with false
6834    false AS relhasrules,
6835    -- MZ doesn't support creating triggers so relhastriggers is filled with false
6836    false AS relhastriggers,
6837    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
6838    false AS relhassubclass,
6839    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
6840    false AS relrowsecurity,
6841    false AS relforcerowsecurity,
6842    -- MZ doesn't support replication so relreplident is filled with 'd' for default
6843    'd'::pg_catalog.\"char\" AS relreplident,
6844    -- MZ doesn't support table partitioning so relispartition is filled with false
6845    false AS relispartition,
6846    -- PG removed relhasoids in v12 so it's filled with false
6847    false AS relhasoids,
6848    -- MZ doesn't support options for relations
6849    NULL::pg_catalog.text[] as reloptions,
6850    d.name as database_name
6851FROM (
6852    -- pg_class catalogs relations and indexes
6853    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
6854    UNION ALL
6855        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
6856        FROM mz_catalog.mz_indexes
6857        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6858) AS class_objects
6859JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6860LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6861JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
6862        access: vec![PUBLIC_SELECT],
6863    }
6864});
6865
6866pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
6867    name: "pg_class_all_databases_ind",
6868    schema: MZ_INTERNAL_SCHEMA,
6869    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
6870    sql: "IN CLUSTER mz_catalog_server
6871ON mz_internal.pg_class_all_databases (relname)",
6872    is_retained_metrics_object: false,
6873};
6874
6875pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| {
6876    BuiltinView {
6877    name: "pg_class",
6878    schema: PG_CATALOG_SCHEMA,
6879    oid: oid::VIEW_PG_CLASS_OID,
6880    desc: RelationDesc::builder()
6881        .with_column("oid", SqlScalarType::Oid.nullable(false))
6882        .with_column("relname", SqlScalarType::String.nullable(false))
6883        .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
6884        .with_column("reloftype", SqlScalarType::Oid.nullable(false))
6885        .with_column("relowner", SqlScalarType::Oid.nullable(false))
6886        .with_column("relam", SqlScalarType::Oid.nullable(false))
6887        .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
6888        .with_column("reltuples", SqlScalarType::Float32.nullable(false))
6889        .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
6890        .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
6891        .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
6892        .with_column("relkind", SqlScalarType::String.nullable(true))
6893        .with_column("relnatts", SqlScalarType::Int16.nullable(false))
6894        .with_column("relchecks", SqlScalarType::Int16.nullable(false))
6895        .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
6896        .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
6897        .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
6898        .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
6899        .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
6900        .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
6901        .with_column("relispartition", SqlScalarType::Bool.nullable(false))
6902        .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
6903        .with_column(
6904            "reloptions",
6905            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
6906        )
6907        .finish(),
6908    column_comments: BTreeMap::new(),
6909    sql: "
6910SELECT
6911    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
6912    relhasindex, relpersistence, relkind, relnatts, relchecks, relhasrules, relhastriggers, relhassubclass,
6913    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
6914FROM mz_internal.pg_class_all_databases
6915WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
6916",
6917    access: vec![PUBLIC_SELECT],
6918}
6919});
6920
6921pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6922    name: "pg_depend",
6923    schema: PG_CATALOG_SCHEMA,
6924    oid: oid::VIEW_PG_DEPEND_OID,
6925    desc: RelationDesc::builder()
6926        .with_column("classid", SqlScalarType::Oid.nullable(true))
6927        .with_column("objid", SqlScalarType::Oid.nullable(false))
6928        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
6929        .with_column("refclassid", SqlScalarType::Oid.nullable(true))
6930        .with_column("refobjid", SqlScalarType::Oid.nullable(false))
6931        .with_column("refobjsubid", SqlScalarType::Int32.nullable(false))
6932        .with_column("deptype", SqlScalarType::PgLegacyChar.nullable(false))
6933        .finish(),
6934    column_comments: BTreeMap::new(),
6935    sql: "
6936WITH class_objects AS (
6937    SELECT
6938        CASE
6939            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6940            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
6941            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
6942            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
6943        END classid,
6944        id,
6945        oid,
6946        schema_id
6947    FROM mz_catalog.mz_relations
6948    UNION ALL
6949    SELECT
6950        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
6951        i.id,
6952        i.oid,
6953        r.schema_id
6954    FROM mz_catalog.mz_indexes i
6955    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
6956),
6957
6958current_objects AS (
6959    SELECT class_objects.*
6960    FROM class_objects
6961    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
6962    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
6963    -- This filter is tricky, as it filters out not just objects outside the
6964    -- database, but *dependencies* on objects outside this database. It's not
6965    -- clear that this is the right choice, but because PostgreSQL doesn't
6966    -- support cross-database references, it's not clear that the other choice
6967    -- is better.
6968    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
6969)
6970
6971SELECT
6972    objects.classid::pg_catalog.oid,
6973    objects.oid::pg_catalog.oid AS objid,
6974    0::pg_catalog.int4 AS objsubid,
6975    dependents.classid::pg_catalog.oid AS refclassid,
6976    dependents.oid::pg_catalog.oid AS refobjid,
6977    0::pg_catalog.int4 AS refobjsubid,
6978    'n'::pg_catalog.char AS deptype
6979FROM mz_internal.mz_object_dependencies
6980JOIN current_objects objects ON object_id = objects.id
6981JOIN current_objects dependents ON referenced_object_id = dependents.id",
6982    access: vec![PUBLIC_SELECT],
6983});
6984
6985pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6986    name: "pg_database",
6987    schema: PG_CATALOG_SCHEMA,
6988    oid: oid::VIEW_PG_DATABASE_OID,
6989    desc: RelationDesc::builder()
6990        .with_column("oid", SqlScalarType::Oid.nullable(false))
6991        .with_column("datname", SqlScalarType::String.nullable(false))
6992        .with_column("datdba", SqlScalarType::Oid.nullable(false))
6993        .with_column("encoding", SqlScalarType::Int32.nullable(false))
6994        .with_column("datistemplate", SqlScalarType::Bool.nullable(false))
6995        .with_column("datallowconn", SqlScalarType::Bool.nullable(false))
6996        .with_column("datcollate", SqlScalarType::String.nullable(false))
6997        .with_column("datctype", SqlScalarType::String.nullable(false))
6998        .with_column(
6999            "datacl",
7000            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7001        )
7002        .with_key(vec![0])
7003        .finish(),
7004    column_comments: BTreeMap::new(),
7005    sql: "SELECT
7006    d.oid as oid,
7007    d.name as datname,
7008    role_owner.oid as datdba,
7009    6 as encoding,
7010    -- Materialize doesn't support database cloning.
7011    FALSE AS datistemplate,
7012    TRUE AS datallowconn,
7013    'C' as datcollate,
7014    'C' as datctype,
7015    NULL::pg_catalog.text[] as datacl
7016FROM mz_catalog.mz_databases d
7017JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
7018    access: vec![PUBLIC_SELECT],
7019});
7020
7021pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
7022    BuiltinView {
7023        name: "pg_index",
7024        schema: PG_CATALOG_SCHEMA,
7025        oid: oid::VIEW_PG_INDEX_OID,
7026        desc: RelationDesc::builder()
7027            .with_column("indexrelid", SqlScalarType::Oid.nullable(false))
7028            .with_column("indrelid", SqlScalarType::Oid.nullable(false))
7029            .with_column("indnatts", SqlScalarType::Int16.nullable(false))
7030            .with_column("indisunique", SqlScalarType::Bool.nullable(false))
7031            .with_column("indisprimary", SqlScalarType::Bool.nullable(false))
7032            .with_column("indimmediate", SqlScalarType::Bool.nullable(false))
7033            .with_column("indisclustered", SqlScalarType::Bool.nullable(false))
7034            .with_column("indisvalid", SqlScalarType::Bool.nullable(false))
7035            .with_column("indisreplident", SqlScalarType::Bool.nullable(false))
7036            .with_column("indkey", SqlScalarType::Int2Vector.nullable(false))
7037            .with_column("indoption", SqlScalarType::Int2Vector.nullable(false))
7038            .with_column("indexprs", SqlScalarType::String.nullable(true))
7039            .with_column("indpred", SqlScalarType::String.nullable(true))
7040            .with_key(vec![0, 1])
7041            .finish(),
7042        column_comments: BTreeMap::new(),
7043        sql: "SELECT
7044    mz_indexes.oid AS indexrelid,
7045    mz_relations.oid AS indrelid,
7046    COALESCE(
7047        (
7048            SELECT count(*)::pg_catalog.int2
7049            FROM mz_catalog.mz_columns
7050            JOIN mz_catalog.mz_relations mri ON mz_columns.id = mri.id
7051            WHERE mri.oid = mz_catalog.mz_relations.oid
7052        ),
7053        0::pg_catalog.int2
7054    ) AS indnatts,
7055    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7056    false::pg_catalog.bool AS indisunique,
7057    false::pg_catalog.bool AS indisprimary,
7058    -- MZ doesn't support unique indexes so indimmediate is filled with false
7059    false::pg_catalog.bool AS indimmediate,
7060    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7061    false::pg_catalog.bool AS indisclustered,
7062    -- MZ never creates invalid indexes so indisvalid is filled with true
7063    true::pg_catalog.bool AS indisvalid,
7064    -- MZ doesn't support replication so indisreplident is filled with false
7065    false::pg_catalog.bool AS indisreplident,
7066    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7067    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,
7068    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7069    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7070    -- Index expressions are returned in MZ format
7071    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7072    WHEN NULL THEN NULL
7073    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7074    END AS indexprs,
7075    -- MZ doesn't support indexes with predicates
7076    NULL::pg_catalog.text AS indpred
7077FROM mz_catalog.mz_indexes
7078JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7079JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7080JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7081LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7082WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7083GROUP BY mz_indexes.oid, mz_relations.oid",
7084        access: vec![PUBLIC_SELECT],
7085    }
7086});
7087
7088pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7089    name: "pg_indexes",
7090    schema: PG_CATALOG_SCHEMA,
7091    oid: oid::VIEW_PG_INDEXES_OID,
7092    desc: RelationDesc::builder()
7093        .with_column("table_catalog", SqlScalarType::String.nullable(false))
7094        .with_column("schemaname", SqlScalarType::String.nullable(false))
7095        .with_column("tablename", SqlScalarType::String.nullable(false))
7096        .with_column("indexname", SqlScalarType::String.nullable(false))
7097        .with_column("tablespace", SqlScalarType::String.nullable(true))
7098        .with_column("indexdef", SqlScalarType::String.nullable(true))
7099        .finish(),
7100    column_comments: BTreeMap::new(),
7101    sql: "SELECT
7102    current_database() as table_catalog,
7103    s.name AS schemaname,
7104    r.name AS tablename,
7105    i.name AS indexname,
7106    NULL::text AS tablespace,
7107    -- TODO(jkosh44) Fill in with actual index definition.
7108    NULL::text AS indexdef
7109FROM mz_catalog.mz_indexes i
7110JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7111JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7112LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7113WHERE s.database_id IS NULL OR d.name = current_database()",
7114    access: vec![PUBLIC_SELECT],
7115});
7116
7117/// Peeled version of `PG_DESCRIPTION`:
7118/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7119///   in order to make this view indexable.
7120/// - This has 2 extra columns for the database names, so that downstream views can check them
7121///   against `current_database()`.
7122pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7123    BuiltinView {
7124        name: "pg_description_all_databases",
7125        schema: MZ_INTERNAL_SCHEMA,
7126        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7127        desc: RelationDesc::builder()
7128            .with_column("objoid", SqlScalarType::Oid.nullable(false))
7129            .with_column("classoid", SqlScalarType::Oid.nullable(true))
7130            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7131            .with_column("description", SqlScalarType::String.nullable(false))
7132            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
7133            .with_column("class_database_name", SqlScalarType::String.nullable(true))
7134            .finish(),
7135        column_comments: BTreeMap::new(),
7136        sql: "
7137(
7138    -- Gather all of the class oid's for objects that can have comments.
7139    WITH pg_classoids AS (
7140        SELECT oid, database_name as oid_database_name,
7141          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7142          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7143        FROM mz_internal.pg_class_all_databases
7144        UNION ALL
7145        SELECT oid, database_name as oid_database_name,
7146          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7147          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7148        FROM mz_internal.pg_type_all_databases
7149        UNION ALL
7150        SELECT oid, database_name as oid_database_name,
7151          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7152          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7153        FROM mz_internal.pg_namespace_all_databases
7154    ),
7155
7156    -- Gather all of the MZ ids for objects that can have comments.
7157    mz_objects AS (
7158        SELECT id, oid, type FROM mz_catalog.mz_objects
7159        UNION ALL
7160        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7161    )
7162    SELECT
7163        pg_classoids.oid AS objoid,
7164        pg_classoids.classoid as classoid,
7165        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7166        cmt.comment AS description,
7167        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7168        oid_database_name,
7169        class_database_name
7170    FROM
7171        pg_classoids
7172    JOIN
7173        mz_objects ON pg_classoids.oid = mz_objects.oid
7174    JOIN
7175        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7176)",
7177        access: vec![PUBLIC_SELECT],
7178    }
7179});
7180
7181pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7182    name: "pg_description_all_databases_ind",
7183    schema: MZ_INTERNAL_SCHEMA,
7184    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7185    sql: "IN CLUSTER mz_catalog_server
7186ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7187    is_retained_metrics_object: false,
7188};
7189
7190/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7191/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7192/// which is required for this view.
7193pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7194    name: "pg_description",
7195    schema: PG_CATALOG_SCHEMA,
7196    oid: oid::VIEW_PG_DESCRIPTION_OID,
7197    desc: RelationDesc::builder()
7198        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7199        .with_column("classoid", SqlScalarType::Oid.nullable(true))
7200        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7201        .with_column("description", SqlScalarType::String.nullable(false))
7202        .finish(),
7203    column_comments: BTreeMap::new(),
7204    sql: "
7205SELECT
7206    objoid,
7207    classoid,
7208    objsubid,
7209    description
7210FROM
7211    mz_internal.pg_description_all_databases
7212WHERE
7213    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7214    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7215    access: vec![PUBLIC_SELECT],
7216});
7217
7218/// Peeled version of `PG_TYPE`:
7219/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7220///   in order to make this view indexable.
7221/// - This has the database name as an extra column, so that downstream views can check it against
7222///  `current_database()`.
7223pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7224    BuiltinView {
7225        name: "pg_type_all_databases",
7226        schema: MZ_INTERNAL_SCHEMA,
7227        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7228        desc: RelationDesc::builder()
7229            .with_column("oid", SqlScalarType::Oid.nullable(false))
7230            .with_column("typname", SqlScalarType::String.nullable(false))
7231            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7232            .with_column("typowner", SqlScalarType::Oid.nullable(false))
7233            .with_column("typlen", SqlScalarType::Int16.nullable(true))
7234            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7235            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7236            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7237            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7238            .with_column("typelem", SqlScalarType::Oid.nullable(false))
7239            .with_column("typarray", SqlScalarType::Oid.nullable(false))
7240            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7241            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7242            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7243            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7244            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7245            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7246            .with_column("typdefault", SqlScalarType::String.nullable(true))
7247            .with_column("database_name", SqlScalarType::String.nullable(true))
7248            .finish(),
7249        column_comments: BTreeMap::new(),
7250        sql: "
7251SELECT
7252    mz_types.oid,
7253    mz_types.name AS typname,
7254    mz_schemas.oid AS typnamespace,
7255    role_owner.oid AS typowner,
7256    NULL::pg_catalog.int2 AS typlen,
7257    -- 'a' is used internally to denote an array type, but in postgres they show up
7258    -- as 'b'.
7259    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7260    (CASE category
7261        WHEN 'array' THEN 'A'
7262        WHEN 'bit-string' THEN 'V'
7263        WHEN 'boolean' THEN 'B'
7264        WHEN 'composite' THEN 'C'
7265        WHEN 'date-time' THEN 'D'
7266        WHEN 'enum' THEN 'E'
7267        WHEN 'geometric' THEN 'G'
7268        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7269        WHEN 'network-address' THEN 'I'
7270        WHEN 'numeric' THEN 'N'
7271        WHEN 'pseudo' THEN 'P'
7272        WHEN 'string' THEN 'S'
7273        WHEN 'timespan' THEN 'T'
7274        WHEN 'user-defined' THEN 'U'
7275        WHEN 'unknown' THEN 'X'
7276    END)::pg_catalog.char AS typcategory,
7277    -- In pg only the 'box' type is not ','.
7278    ','::pg_catalog.char AS typdelim,
7279    0::pg_catalog.oid AS typrelid,
7280    coalesce(
7281        (
7282            SELECT t.oid
7283            FROM mz_catalog.mz_array_types a
7284            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7285            WHERE a.id = mz_types.id
7286        ),
7287        0
7288    ) AS typelem,
7289    coalesce(
7290        (
7291            SELECT
7292                t.oid
7293            FROM
7294                mz_catalog.mz_array_types AS a
7295                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7296            WHERE
7297                a.element_id = mz_types.id
7298        ),
7299        0
7300    )
7301        AS typarray,
7302    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7303    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7304    false::pg_catalog.bool AS typnotnull,
7305    0::pg_catalog.oid AS typbasetype,
7306    -1::pg_catalog.int4 AS typtypmod,
7307    -- MZ doesn't support COLLATE so typcollation is filled with 0
7308    0::pg_catalog.oid AS typcollation,
7309    NULL::pg_catalog.text AS typdefault,
7310    d.name as database_name
7311FROM
7312    mz_catalog.mz_types
7313    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7314    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7315    JOIN (
7316            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7317            -- converted to the correct value above.
7318            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7319            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7320            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7321            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7322            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7323        )
7324            AS t ON mz_types.id = t.id
7325    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7326    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7327        access: vec![PUBLIC_SELECT],
7328    }
7329});
7330
7331pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7332    name: "pg_type_all_databases_ind",
7333    schema: MZ_INTERNAL_SCHEMA,
7334    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7335    sql: "IN CLUSTER mz_catalog_server
7336ON mz_internal.pg_type_all_databases (oid)",
7337    is_retained_metrics_object: false,
7338};
7339
7340pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7341    name: "pg_type",
7342    schema: PG_CATALOG_SCHEMA,
7343    oid: oid::VIEW_PG_TYPE_OID,
7344    desc: RelationDesc::builder()
7345        .with_column("oid", SqlScalarType::Oid.nullable(false))
7346        .with_column("typname", SqlScalarType::String.nullable(false))
7347        .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7348        .with_column("typowner", SqlScalarType::Oid.nullable(false))
7349        .with_column("typlen", SqlScalarType::Int16.nullable(true))
7350        .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7351        .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7352        .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7353        .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7354        .with_column("typelem", SqlScalarType::Oid.nullable(false))
7355        .with_column("typarray", SqlScalarType::Oid.nullable(false))
7356        .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7357        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7358        .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7359        .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7360        .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7361        .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7362        .with_column("typdefault", SqlScalarType::String.nullable(true))
7363        .finish(),
7364    column_comments: BTreeMap::new(),
7365    sql: "SELECT
7366    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7367    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7368FROM mz_internal.pg_type_all_databases
7369WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7370    access: vec![PUBLIC_SELECT],
7371});
7372
7373/// Peeled version of `PG_ATTRIBUTE`:
7374/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7375///   in order to make this view indexable.
7376/// - This has 2 extra columns for the database names, so that downstream views can check them
7377///   against `current_database()`.
7378pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7379    BuiltinView {
7380        name: "pg_attribute_all_databases",
7381        schema: MZ_INTERNAL_SCHEMA,
7382        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7383        desc: RelationDesc::builder()
7384            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7385            .with_column("attname", SqlScalarType::String.nullable(false))
7386            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7387            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7388            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7389            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7390            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7391            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7392            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7393            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7394            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7395            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7396            .with_column("database_name", SqlScalarType::String.nullable(true))
7397            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
7398            .finish(),
7399        column_comments: BTreeMap::new(),
7400        sql: "
7401SELECT
7402    class_objects.oid as attrelid,
7403    mz_columns.name as attname,
7404    mz_columns.type_oid AS atttypid,
7405    pg_type_all_databases.typlen AS attlen,
7406    position::int8::int2 as attnum,
7407    mz_columns.type_mod as atttypmod,
7408    NOT nullable as attnotnull,
7409    mz_columns.default IS NOT NULL as atthasdef,
7410    ''::pg_catalog.\"char\" as attidentity,
7411    -- MZ doesn't support generated columns so attgenerated is filled with ''
7412    ''::pg_catalog.\"char\" as attgenerated,
7413    FALSE as attisdropped,
7414    -- MZ doesn't support COLLATE so attcollation is filled with 0
7415    0::pg_catalog.oid as attcollation,
7416    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7417    d.name as database_name,
7418    pg_type_all_databases.database_name as pg_type_database_name
7419FROM (
7420    -- pg_attribute catalogs columns on relations and indexes
7421    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7422    UNION ALL
7423        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7424        FROM mz_catalog.mz_indexes
7425        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7426) AS class_objects
7427JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7428JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7429JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7430LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7431        // Since this depends on pg_type, its id must be higher due to initialization
7432        // ordering.
7433        access: vec![PUBLIC_SELECT],
7434    }
7435});
7436
7437pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7438    name: "pg_attribute_all_databases_ind",
7439    schema: MZ_INTERNAL_SCHEMA,
7440    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7441    sql: "IN CLUSTER mz_catalog_server
7442ON mz_internal.pg_attribute_all_databases (
7443    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7444    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7445)",
7446    is_retained_metrics_object: false,
7447};
7448
7449pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7450    BuiltinView {
7451        name: "pg_attribute",
7452        schema: PG_CATALOG_SCHEMA,
7453        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7454        desc: RelationDesc::builder()
7455            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7456            .with_column("attname", SqlScalarType::String.nullable(false))
7457            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7458            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7459            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7460            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7461            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7462            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7463            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7464            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7465            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7466            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7467            .finish(),
7468        column_comments: BTreeMap::new(),
7469        sql: "
7470SELECT
7471    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7472    attgenerated, attisdropped, attcollation
7473FROM mz_internal.pg_attribute_all_databases
7474WHERE
7475  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7476  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7477        // Since this depends on pg_type, its id must be higher due to initialization
7478        // ordering.
7479        access: vec![PUBLIC_SELECT],
7480    }
7481});
7482
7483pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7484    name: "pg_proc",
7485    schema: PG_CATALOG_SCHEMA,
7486    oid: oid::VIEW_PG_PROC_OID,
7487    desc: RelationDesc::builder()
7488        .with_column("oid", SqlScalarType::Oid.nullable(false))
7489        .with_column("proname", SqlScalarType::String.nullable(false))
7490        .with_column("pronamespace", SqlScalarType::Oid.nullable(false))
7491        .with_column("proowner", SqlScalarType::Oid.nullable(false))
7492        .with_column("proargdefaults", SqlScalarType::String.nullable(true))
7493        .with_column("prorettype", SqlScalarType::Oid.nullable(false))
7494        .finish(),
7495    column_comments: BTreeMap::new(),
7496    sql: "SELECT
7497    mz_functions.oid,
7498    mz_functions.name AS proname,
7499    mz_schemas.oid AS pronamespace,
7500    role_owner.oid AS proowner,
7501    NULL::pg_catalog.text AS proargdefaults,
7502    ret_type.oid AS prorettype
7503FROM mz_catalog.mz_functions
7504JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7505LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7506JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7507JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7508WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7509    access: vec![PUBLIC_SELECT],
7510});
7511
7512pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7513    name: "pg_operator",
7514    schema: PG_CATALOG_SCHEMA,
7515    oid: oid::VIEW_PG_OPERATOR_OID,
7516    desc: RelationDesc::builder()
7517        .with_column("oid", SqlScalarType::Oid.nullable(false))
7518        .with_column("oprname", SqlScalarType::String.nullable(false))
7519        .with_column("oprresult", SqlScalarType::Oid.nullable(false))
7520        .with_column("oprleft", SqlScalarType::Oid.nullable(false))
7521        .with_column("oprright", SqlScalarType::Oid.nullable(false))
7522        .with_key(vec![0, 1, 2, 3, 4])
7523        .finish(),
7524    column_comments: BTreeMap::new(),
7525    sql: "SELECT
7526    mz_operators.oid,
7527    mz_operators.name AS oprname,
7528    ret_type.oid AS oprresult,
7529    left_type.oid as oprleft,
7530    right_type.oid as oprright
7531FROM mz_catalog.mz_operators
7532JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7533JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7534JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7535WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7536UNION SELECT
7537    mz_operators.oid,
7538    mz_operators.name AS oprname,
7539    ret_type.oid AS oprresult,
7540    0 as oprleft,
7541    right_type.oid as oprright
7542FROM mz_catalog.mz_operators
7543JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7544JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7545WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7546    access: vec![PUBLIC_SELECT],
7547});
7548
7549pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7550    name: "pg_range",
7551    schema: PG_CATALOG_SCHEMA,
7552    oid: oid::VIEW_PG_RANGE_OID,
7553    desc: RelationDesc::builder()
7554        .with_column("rngtypid", SqlScalarType::Oid.nullable(false))
7555        .with_column("rngsubtype", SqlScalarType::Oid.nullable(false))
7556        .with_key(vec![])
7557        .finish(),
7558    column_comments: BTreeMap::new(),
7559    sql: "SELECT
7560    NULL::pg_catalog.oid AS rngtypid,
7561    NULL::pg_catalog.oid AS rngsubtype
7562WHERE false",
7563    access: vec![PUBLIC_SELECT],
7564});
7565
7566pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7567    name: "pg_enum",
7568    schema: PG_CATALOG_SCHEMA,
7569    oid: oid::VIEW_PG_ENUM_OID,
7570    desc: RelationDesc::builder()
7571        .with_column("oid", SqlScalarType::Oid.nullable(false))
7572        .with_column("enumtypid", SqlScalarType::Oid.nullable(false))
7573        .with_column("enumsortorder", SqlScalarType::Float32.nullable(false))
7574        .with_column("enumlabel", SqlScalarType::String.nullable(false))
7575        .with_key(vec![])
7576        .finish(),
7577    column_comments: BTreeMap::new(),
7578    sql: "SELECT
7579    NULL::pg_catalog.oid AS oid,
7580    NULL::pg_catalog.oid AS enumtypid,
7581    NULL::pg_catalog.float4 AS enumsortorder,
7582    NULL::pg_catalog.text AS enumlabel
7583WHERE false",
7584    access: vec![PUBLIC_SELECT],
7585});
7586
7587/// Peeled version of `PG_ATTRDEF`:
7588/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7589///   in order to make this view indexable.
7590pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7591    name: "pg_attrdef_all_databases",
7592    schema: MZ_INTERNAL_SCHEMA,
7593    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
7594    desc: RelationDesc::builder()
7595        .with_column("oid", SqlScalarType::Oid.nullable(true))
7596        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7597        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7598        .with_column("adbin", SqlScalarType::String.nullable(false))
7599        .with_column("adsrc", SqlScalarType::String.nullable(false))
7600        .finish(),
7601    column_comments: BTreeMap::new(),
7602    sql: "
7603SELECT
7604    NULL::pg_catalog.oid AS oid,
7605    mz_objects.oid AS adrelid,
7606    mz_columns.position::int8 AS adnum,
7607    mz_columns.default AS adbin,
7608    mz_columns.default AS adsrc
7609FROM mz_catalog.mz_columns
7610    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
7611WHERE default IS NOT NULL",
7612    access: vec![PUBLIC_SELECT],
7613});
7614
7615pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7616    name: "pg_attrdef_all_databases_ind",
7617    schema: MZ_INTERNAL_SCHEMA,
7618    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
7619    sql: "IN CLUSTER mz_catalog_server
7620ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
7621    is_retained_metrics_object: false,
7622};
7623
7624pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7625    name: "pg_attrdef",
7626    schema: PG_CATALOG_SCHEMA,
7627    oid: oid::VIEW_PG_ATTRDEF_OID,
7628    desc: RelationDesc::builder()
7629        .with_column("oid", SqlScalarType::Oid.nullable(true))
7630        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
7631        .with_column("adnum", SqlScalarType::Int64.nullable(false))
7632        .with_column("adbin", SqlScalarType::String.nullable(false))
7633        .with_column("adsrc", SqlScalarType::String.nullable(false))
7634        .finish(),
7635    column_comments: BTreeMap::new(),
7636    sql: "
7637SELECT
7638    pg_attrdef_all_databases.oid as oid,
7639    adrelid,
7640    adnum,
7641    adbin,
7642    adsrc
7643FROM mz_internal.pg_attrdef_all_databases
7644    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
7645    access: vec![PUBLIC_SELECT],
7646});
7647
7648pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7649    name: "pg_settings",
7650    schema: PG_CATALOG_SCHEMA,
7651    oid: oid::VIEW_PG_SETTINGS_OID,
7652    desc: RelationDesc::builder()
7653        .with_column("name", SqlScalarType::String.nullable(false))
7654        .with_column("setting", SqlScalarType::String.nullable(false))
7655        .with_key(vec![])
7656        .finish(),
7657    column_comments: BTreeMap::new(),
7658    sql: "SELECT
7659    name, setting
7660FROM (VALUES
7661    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
7662) AS _ (name, setting)",
7663    access: vec![PUBLIC_SELECT],
7664});
7665
7666pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7667    name: "pg_auth_members",
7668    schema: PG_CATALOG_SCHEMA,
7669    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
7670    desc: RelationDesc::builder()
7671        .with_column("roleid", SqlScalarType::Oid.nullable(false))
7672        .with_column("member", SqlScalarType::Oid.nullable(false))
7673        .with_column("grantor", SqlScalarType::Oid.nullable(false))
7674        .with_column("admin_option", SqlScalarType::Bool.nullable(false))
7675        .finish(),
7676    column_comments: BTreeMap::new(),
7677    sql: "SELECT
7678    role.oid AS roleid,
7679    member.oid AS member,
7680    grantor.oid AS grantor,
7681    -- Materialize hasn't implemented admin_option.
7682    false as admin_option
7683FROM mz_catalog.mz_role_members membership
7684JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
7685JOIN mz_catalog.mz_roles member ON membership.member = member.id
7686JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
7687    access: vec![PUBLIC_SELECT],
7688});
7689
7690pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7691    name: "pg_event_trigger",
7692    schema: PG_CATALOG_SCHEMA,
7693    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
7694    desc: RelationDesc::builder()
7695        .with_column("oid", SqlScalarType::Oid.nullable(false))
7696        .with_column("evtname", SqlScalarType::String.nullable(false))
7697        .with_column("evtevent", SqlScalarType::String.nullable(false))
7698        .with_column("evtowner", SqlScalarType::Oid.nullable(false))
7699        .with_column("evtfoid", SqlScalarType::Oid.nullable(false))
7700        .with_column("evtenabled", SqlScalarType::PgLegacyChar.nullable(false))
7701        .with_column(
7702            "evttags",
7703            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7704        )
7705        .with_key(vec![])
7706        .finish(),
7707    column_comments: BTreeMap::new(),
7708    sql: "SELECT
7709        NULL::pg_catalog.oid AS oid,
7710        NULL::pg_catalog.text AS evtname,
7711        NULL::pg_catalog.text AS evtevent,
7712        NULL::pg_catalog.oid AS evtowner,
7713        NULL::pg_catalog.oid AS evtfoid,
7714        NULL::pg_catalog.char AS evtenabled,
7715        NULL::pg_catalog.text[] AS evttags
7716    WHERE false",
7717    access: vec![PUBLIC_SELECT],
7718});
7719
7720pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7721    name: "pg_language",
7722    schema: PG_CATALOG_SCHEMA,
7723    oid: oid::VIEW_PG_LANGUAGE_OID,
7724    desc: RelationDesc::builder()
7725        .with_column("oid", SqlScalarType::Oid.nullable(false))
7726        .with_column("lanname", SqlScalarType::String.nullable(false))
7727        .with_column("lanowner", SqlScalarType::Oid.nullable(false))
7728        .with_column("lanispl", SqlScalarType::Bool.nullable(false))
7729        .with_column("lanpltrusted", SqlScalarType::Bool.nullable(false))
7730        .with_column("lanplcallfoid", SqlScalarType::Oid.nullable(false))
7731        .with_column("laninline", SqlScalarType::Oid.nullable(false))
7732        .with_column("lanvalidator", SqlScalarType::Oid.nullable(false))
7733        .with_column(
7734            "lanacl",
7735            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7736        )
7737        .with_key(vec![])
7738        .finish(),
7739    column_comments: BTreeMap::new(),
7740    sql: "SELECT
7741        NULL::pg_catalog.oid  AS oid,
7742        NULL::pg_catalog.text AS lanname,
7743        NULL::pg_catalog.oid  AS lanowner,
7744        NULL::pg_catalog.bool AS lanispl,
7745        NULL::pg_catalog.bool AS lanpltrusted,
7746        NULL::pg_catalog.oid  AS lanplcallfoid,
7747        NULL::pg_catalog.oid  AS laninline,
7748        NULL::pg_catalog.oid  AS lanvalidator,
7749        NULL::pg_catalog.text[] AS lanacl
7750    WHERE false",
7751    access: vec![PUBLIC_SELECT],
7752});
7753
7754pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7755    name: "pg_shdescription",
7756    schema: PG_CATALOG_SCHEMA,
7757    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
7758    desc: RelationDesc::builder()
7759        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7760        .with_column("classoid", SqlScalarType::Oid.nullable(false))
7761        .with_column("description", SqlScalarType::String.nullable(false))
7762        .with_key(vec![])
7763        .finish(),
7764    column_comments: BTreeMap::new(),
7765    sql: "SELECT
7766        NULL::pg_catalog.oid AS objoid,
7767        NULL::pg_catalog.oid AS classoid,
7768        NULL::pg_catalog.text AS description
7769    WHERE false",
7770    access: vec![PUBLIC_SELECT],
7771});
7772
7773pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
7774    BuiltinView {
7775        name: "pg_timezone_abbrevs",
7776        schema: PG_CATALOG_SCHEMA,
7777        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
7778        desc: RelationDesc::builder()
7779            .with_column("abbrev", SqlScalarType::String.nullable(false))
7780            .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7781            .with_column("is_dst", SqlScalarType::Bool.nullable(true))
7782            .with_key(vec![0])
7783            .finish(),
7784        column_comments: BTreeMap::new(),
7785        sql: "SELECT
7786    abbreviation AS abbrev,
7787    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
7788        AS utc_offset,
7789    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
7790        AS is_dst
7791FROM mz_catalog.mz_timezone_abbreviations",
7792        access: vec![PUBLIC_SELECT],
7793    }
7794});
7795
7796pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7797    name: "pg_timezone_names",
7798    schema: PG_CATALOG_SCHEMA,
7799    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
7800    desc: RelationDesc::builder()
7801        .with_column("name", SqlScalarType::String.nullable(false))
7802        .with_column("abbrev", SqlScalarType::String.nullable(true))
7803        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7804        .with_column("is_dst", SqlScalarType::Bool.nullable(true))
7805        .with_key(vec![0])
7806        .finish(),
7807    column_comments: BTreeMap::new(),
7808    sql: "SELECT
7809    name,
7810    timezone_offset(name, now()).abbrev AS abbrev,
7811    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
7812        AS utc_offset,
7813    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
7814        AS is_dst
7815FROM mz_catalog.mz_timezone_names",
7816    access: vec![PUBLIC_SELECT],
7817});
7818
7819pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7820    name: "mz_timezone_abbreviations",
7821    schema: MZ_CATALOG_SCHEMA,
7822    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
7823    desc: RelationDesc::builder()
7824        .with_column("abbreviation", SqlScalarType::String.nullable(false))
7825        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
7826        .with_column("dst", SqlScalarType::Bool.nullable(true))
7827        .with_column("timezone_name", SqlScalarType::String.nullable(true))
7828        .with_key(vec![0])
7829        .finish(),
7830    column_comments: BTreeMap::from_iter([
7831        ("abbreviation", "The timezone abbreviation."),
7832        (
7833            "utc_offset",
7834            "The UTC offset of the timezone or `NULL` if fixed.",
7835        ),
7836        (
7837            "dst",
7838            "Whether the timezone is in daylight savings or `NULL` if fixed.",
7839        ),
7840        (
7841            "timezone_name",
7842            "The full name of the non-fixed timezone or `NULL` if not fixed.",
7843        ),
7844    ]),
7845    sql: format!(
7846        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
7847        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
7848    )
7849    .leak(),
7850    access: vec![PUBLIC_SELECT],
7851});
7852
7853pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7854    name: "mz_timezone_names",
7855    schema: MZ_CATALOG_SCHEMA,
7856    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
7857    desc: RelationDesc::builder()
7858        .with_column("name", SqlScalarType::String.nullable(false))
7859        .with_key(vec![0])
7860        .finish(),
7861    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
7862    sql: format!(
7863        "SELECT * FROM ({}) _ (name)",
7864        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
7865    )
7866    .leak(),
7867    access: vec![PUBLIC_SELECT],
7868});
7869
7870pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7871    LazyLock::new(|| BuiltinView {
7872        name: "mz_peek_durations_histogram_per_worker",
7873        schema: MZ_INTROSPECTION_SCHEMA,
7874        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
7875        desc: RelationDesc::builder()
7876            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7877            .with_column("type", SqlScalarType::String.nullable(false))
7878            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7879            .with_column("count", SqlScalarType::Int64.nullable(false))
7880            .with_key(vec![0, 1, 2])
7881            .finish(),
7882        column_comments: BTreeMap::new(),
7883        sql: "SELECT
7884    worker_id, type, duration_ns, pg_catalog.count(*) AS count
7885FROM
7886    mz_introspection.mz_peek_durations_histogram_raw
7887GROUP BY
7888    worker_id, type, duration_ns",
7889        access: vec![PUBLIC_SELECT],
7890    });
7891
7892pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7893    name: "mz_peek_durations_histogram",
7894    schema: MZ_INTROSPECTION_SCHEMA,
7895    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
7896    desc: RelationDesc::builder()
7897        .with_column("type", SqlScalarType::String.nullable(false))
7898        .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7899        .with_column(
7900            "count",
7901            SqlScalarType::Numeric {
7902                max_scale: Some(NumericMaxScale::ZERO),
7903            }
7904            .nullable(false),
7905        )
7906        .with_key(vec![0, 1])
7907        .finish(),
7908    column_comments: BTreeMap::from_iter([
7909        ("type", "The peek variant: `index` or `persist`."),
7910        (
7911            "duration_ns",
7912            "The upper bound of the bucket in nanoseconds.",
7913        ),
7914        (
7915            "count",
7916            "The (noncumulative) count of peeks in this bucket.",
7917        ),
7918    ]),
7919    sql: "
7920SELECT
7921    type, duration_ns,
7922    pg_catalog.sum(count) AS count
7923FROM mz_introspection.mz_peek_durations_histogram_per_worker
7924GROUP BY type, duration_ns",
7925    access: vec![PUBLIC_SELECT],
7926});
7927
7928pub static MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
7929    LazyLock::new(|| BuiltinView {
7930        name: "mz_dataflow_shutdown_durations_histogram_per_worker",
7931        schema: MZ_INTROSPECTION_SCHEMA,
7932        oid: oid::VIEW_MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_PER_WORKER_OID,
7933        desc: RelationDesc::builder()
7934            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7935            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7936            .with_column("count", SqlScalarType::Int64.nullable(false))
7937            .with_key(vec![0, 1])
7938            .finish(),
7939        column_comments: BTreeMap::new(),
7940        sql: "SELECT
7941    worker_id, duration_ns, pg_catalog.count(*) AS count
7942FROM
7943    mz_introspection.mz_dataflow_shutdown_durations_histogram_raw
7944GROUP BY
7945    worker_id, duration_ns",
7946        access: vec![PUBLIC_SELECT],
7947    });
7948
7949pub static MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
7950    LazyLock::new(|| BuiltinView {
7951        name: "mz_dataflow_shutdown_durations_histogram",
7952        schema: MZ_INTROSPECTION_SCHEMA,
7953        oid: oid::VIEW_MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_OID,
7954        desc: RelationDesc::builder()
7955            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
7956            .with_column(
7957                "count",
7958                SqlScalarType::Numeric {
7959                    max_scale: Some(NumericMaxScale::ZERO),
7960                }
7961                .nullable(false),
7962            )
7963            .with_key(vec![0])
7964            .finish(),
7965        column_comments: BTreeMap::from_iter([
7966            (
7967                "duration_ns",
7968                "The upper bound of the bucket in nanoseconds.",
7969            ),
7970            (
7971                "count",
7972                "The (noncumulative) count of dataflows in this bucket.",
7973            ),
7974        ]),
7975        sql: "
7976SELECT
7977    duration_ns,
7978    pg_catalog.sum(count) AS count
7979FROM mz_introspection.mz_dataflow_shutdown_durations_histogram_per_worker
7980GROUP BY duration_ns",
7981        access: vec![PUBLIC_SELECT],
7982    });
7983
7984pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
7985    LazyLock::new(|| BuiltinView {
7986        name: "mz_scheduling_elapsed_per_worker",
7987        schema: MZ_INTROSPECTION_SCHEMA,
7988        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
7989        desc: RelationDesc::builder()
7990            .with_column("id", SqlScalarType::UInt64.nullable(false))
7991            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7992            .with_column("elapsed_ns", SqlScalarType::Int64.nullable(false))
7993            .with_key(vec![0, 1])
7994            .finish(),
7995        column_comments: BTreeMap::new(),
7996        sql: "SELECT
7997    id, worker_id, pg_catalog.count(*) AS elapsed_ns
7998FROM
7999    mz_introspection.mz_scheduling_elapsed_raw
8000GROUP BY
8001    id, worker_id",
8002        access: vec![PUBLIC_SELECT],
8003    });
8004
8005pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8006    name: "mz_scheduling_elapsed",
8007    schema: MZ_INTROSPECTION_SCHEMA,
8008    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
8009    desc: RelationDesc::builder()
8010        .with_column("id", SqlScalarType::UInt64.nullable(false))
8011        .with_column(
8012            "elapsed_ns",
8013            SqlScalarType::Numeric {
8014                max_scale: Some(NumericMaxScale::ZERO),
8015            }
8016            .nullable(false),
8017        )
8018        .with_key(vec![0])
8019        .finish(),
8020    column_comments: BTreeMap::from_iter([
8021        (
8022            "id",
8023            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8024        ),
8025        (
8026            "elapsed_ns",
8027            "The total elapsed time spent in the operator in nanoseconds.",
8028        ),
8029    ]),
8030    sql: "
8031SELECT
8032    id,
8033    pg_catalog.sum(elapsed_ns) AS elapsed_ns
8034FROM mz_introspection.mz_scheduling_elapsed_per_worker
8035GROUP BY id",
8036    access: vec![PUBLIC_SELECT],
8037});
8038
8039pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8040    LazyLock::new(|| BuiltinView {
8041        name: "mz_compute_operator_durations_histogram_per_worker",
8042        schema: MZ_INTROSPECTION_SCHEMA,
8043        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8044        desc: RelationDesc::builder()
8045            .with_column("id", SqlScalarType::UInt64.nullable(false))
8046            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8047            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8048            .with_column("count", SqlScalarType::Int64.nullable(false))
8049            .with_key(vec![0, 1, 2])
8050            .finish(),
8051        column_comments: BTreeMap::new(),
8052        sql: "SELECT
8053    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8054FROM
8055    mz_introspection.mz_compute_operator_durations_histogram_raw
8056GROUP BY
8057    id, worker_id, duration_ns",
8058        access: vec![PUBLIC_SELECT],
8059    });
8060
8061pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8062    LazyLock::new(|| BuiltinView {
8063        name: "mz_compute_operator_durations_histogram",
8064        schema: MZ_INTROSPECTION_SCHEMA,
8065        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8066        desc: RelationDesc::builder()
8067            .with_column("id", SqlScalarType::UInt64.nullable(false))
8068            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8069            .with_column(
8070                "count",
8071                SqlScalarType::Numeric {
8072                    max_scale: Some(NumericMaxScale::ZERO),
8073                }
8074                .nullable(false),
8075            )
8076            .with_key(vec![0, 1])
8077            .finish(),
8078        column_comments: BTreeMap::from_iter([
8079            (
8080                "id",
8081                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8082            ),
8083            (
8084                "duration_ns",
8085                "The upper bound of the duration bucket in nanoseconds.",
8086            ),
8087            (
8088                "count",
8089                "The (noncumulative) count of invocations in the bucket.",
8090            ),
8091        ]),
8092        sql: "
8093SELECT
8094    id,
8095    duration_ns,
8096    pg_catalog.sum(count) AS count
8097FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8098GROUP BY id, duration_ns",
8099        access: vec![PUBLIC_SELECT],
8100    });
8101
8102pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8103    LazyLock::new(|| BuiltinView {
8104        name: "mz_scheduling_parks_histogram_per_worker",
8105        schema: MZ_INTROSPECTION_SCHEMA,
8106        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8107        desc: RelationDesc::builder()
8108            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8109            .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8110            .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8111            .with_column("count", SqlScalarType::Int64.nullable(false))
8112            .with_key(vec![0, 1, 2])
8113            .finish(),
8114        column_comments: BTreeMap::new(),
8115        sql: "SELECT
8116    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8117FROM
8118    mz_introspection.mz_scheduling_parks_histogram_raw
8119GROUP BY
8120    worker_id, slept_for_ns, requested_ns",
8121        access: vec![PUBLIC_SELECT],
8122    });
8123
8124pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8125    name: "mz_scheduling_parks_histogram",
8126    schema: MZ_INTROSPECTION_SCHEMA,
8127    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8128    desc: RelationDesc::builder()
8129        .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8130        .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8131        .with_column(
8132            "count",
8133            SqlScalarType::Numeric {
8134                max_scale: Some(NumericMaxScale::ZERO),
8135            }
8136            .nullable(false),
8137        )
8138        .with_key(vec![0, 1])
8139        .finish(),
8140    column_comments: BTreeMap::from_iter([
8141        (
8142            "slept_for_ns",
8143            "The actual length of the park event in nanoseconds.",
8144        ),
8145        (
8146            "requested_ns",
8147            "The requested length of the park event in nanoseconds.",
8148        ),
8149        (
8150            "count",
8151            "The (noncumulative) count of park events in this bucket.",
8152        ),
8153    ]),
8154    sql: "
8155SELECT
8156    slept_for_ns,
8157    requested_ns,
8158    pg_catalog.sum(count) AS count
8159FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8160GROUP BY slept_for_ns, requested_ns",
8161    access: vec![PUBLIC_SELECT],
8162});
8163
8164pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8165    LazyLock::new(|| BuiltinView {
8166        name: "mz_compute_error_counts_per_worker",
8167        schema: MZ_INTROSPECTION_SCHEMA,
8168        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8169        desc: RelationDesc::builder()
8170            .with_column("export_id", SqlScalarType::String.nullable(false))
8171            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8172            .with_column("count", SqlScalarType::Int64.nullable(false))
8173            .with_key(vec![0, 1, 2])
8174            .finish(),
8175        column_comments: BTreeMap::new(),
8176        sql: "
8177WITH MUTUALLY RECURSIVE
8178    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8179    -- For these we don't log error counts separately, so we need to forward the error counts from
8180    -- their dependencies instead.
8181    index_reuses(reuse_id text, index_id text) AS (
8182        SELECT d.object_id, d.dependency_id
8183        FROM mz_internal.mz_compute_dependencies d
8184        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8185        WHERE NOT EXISTS (
8186            SELECT 1 FROM mz_introspection.mz_dataflows
8187            WHERE id = e.dataflow_id
8188        )
8189    ),
8190    -- Error counts that were directly logged on compute exports.
8191    direct_errors(export_id text, worker_id uint8, count int8) AS (
8192        SELECT export_id, worker_id, count
8193        FROM mz_introspection.mz_compute_error_counts_raw
8194    ),
8195    -- Error counts propagated to index reused.
8196    all_errors(export_id text, worker_id uint8, count int8) AS (
8197        SELECT * FROM direct_errors
8198        UNION
8199        SELECT r.reuse_id, e.worker_id, e.count
8200        FROM all_errors e
8201        JOIN index_reuses r ON (r.index_id = e.export_id)
8202    )
8203SELECT * FROM all_errors",
8204        access: vec![PUBLIC_SELECT],
8205    });
8206
8207pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8208    name: "mz_compute_error_counts",
8209    schema: MZ_INTROSPECTION_SCHEMA,
8210    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8211    desc: RelationDesc::builder()
8212        .with_column("export_id", SqlScalarType::String.nullable(false))
8213        .with_column(
8214            "count",
8215            SqlScalarType::Numeric {
8216                max_scale: Some(NumericMaxScale::ZERO),
8217            }
8218            .nullable(false),
8219        )
8220        .with_key(vec![0])
8221        .finish(),
8222    column_comments: BTreeMap::from_iter([
8223        (
8224            "export_id",
8225            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8226        ),
8227        (
8228            "count",
8229            "The count of errors present in this dataflow export.",
8230        ),
8231    ]),
8232    sql: "
8233SELECT
8234    export_id,
8235    pg_catalog.sum(count) AS count
8236FROM mz_introspection.mz_compute_error_counts_per_worker
8237GROUP BY export_id
8238HAVING pg_catalog.sum(count) != 0",
8239    access: vec![PUBLIC_SELECT],
8240});
8241
8242pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8243    LazyLock::new(|| BuiltinSource {
8244        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8245        // naming conflict because the resolver stumbles over the source with the same name in
8246        // `mz_introspection` due to the automatic schema translation.
8247        name: "mz_compute_error_counts_raw_unified",
8248        schema: MZ_INTERNAL_SCHEMA,
8249        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8250        desc: RelationDesc::builder()
8251            .with_column("replica_id", SqlScalarType::String.nullable(false))
8252            .with_column("object_id", SqlScalarType::String.nullable(false))
8253            .with_column(
8254                "count",
8255                SqlScalarType::Numeric { max_scale: None }.nullable(false),
8256            )
8257            .finish(),
8258        data_source: IntrospectionType::ComputeErrorCounts,
8259        column_comments: BTreeMap::new(),
8260        is_retained_metrics_object: false,
8261        access: vec![PUBLIC_SELECT],
8262    });
8263
8264pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8265    name: "mz_compute_hydration_times",
8266    schema: MZ_INTERNAL_SCHEMA,
8267    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8268    desc: RelationDesc::builder()
8269        .with_column("replica_id", SqlScalarType::String.nullable(false))
8270        .with_column("object_id", SqlScalarType::String.nullable(false))
8271        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
8272        .finish(),
8273    data_source: IntrospectionType::ComputeHydrationTimes,
8274    column_comments: BTreeMap::new(),
8275    is_retained_metrics_object: true,
8276    access: vec![PUBLIC_SELECT],
8277});
8278
8279pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8280    LazyLock::new(|| BuiltinIndex {
8281        name: "mz_compute_hydration_times_ind",
8282        schema: MZ_INTERNAL_SCHEMA,
8283        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8284        sql: "IN CLUSTER mz_catalog_server
8285    ON mz_internal.mz_compute_hydration_times (replica_id)",
8286        is_retained_metrics_object: true,
8287    });
8288
8289pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8290    name: "mz_compute_hydration_statuses",
8291    schema: MZ_INTERNAL_SCHEMA,
8292    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8293    desc: RelationDesc::builder()
8294        .with_column("object_id", SqlScalarType::String.nullable(false))
8295        .with_column("replica_id", SqlScalarType::String.nullable(false))
8296        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8297        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
8298        .finish(),
8299    column_comments: BTreeMap::from_iter([
8300        (
8301            "object_id",
8302            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8303        ),
8304        ("replica_id", "The ID of a cluster replica."),
8305        (
8306            "hydrated",
8307            "Whether the compute object is hydrated on the replica.",
8308        ),
8309        (
8310            "hydration_time",
8311            "The amount of time it took for the replica to hydrate the compute object.",
8312        ),
8313    ]),
8314    sql: "
8315WITH
8316    dataflows AS (
8317        SELECT
8318            object_id,
8319            replica_id,
8320            time_ns IS NOT NULL AS hydrated,
8321            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8322        FROM mz_internal.mz_compute_hydration_times
8323    ),
8324    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8325    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8326    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8327    -- blue-green readiness query does), so we include them as 'hydrated'.
8328    complete_mvs AS (
8329        SELECT
8330            mv.id,
8331            f.replica_id,
8332            true AS hydrated,
8333            NULL::interval AS hydration_time
8334        FROM mz_materialized_views mv
8335        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8336        WHERE f.write_frontier IS NULL
8337    ),
8338    -- Ditto CTs
8339    complete_cts AS (
8340        SELECT
8341            ct.id,
8342            f.replica_id,
8343            true AS hydrated,
8344            NULL::interval AS hydration_time
8345        FROM mz_internal.mz_continual_tasks ct
8346        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = ct.id
8347        WHERE f.write_frontier IS NULL
8348    )
8349SELECT * FROM dataflows
8350UNION ALL
8351SELECT * FROM complete_mvs
8352UNION ALL
8353SELECT * FROM complete_cts",
8354    access: vec![PUBLIC_SELECT],
8355});
8356
8357pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
8358    BuiltinSource {
8359        name: "mz_compute_operator_hydration_statuses",
8360        schema: MZ_INTERNAL_SCHEMA,
8361        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8362        desc: RelationDesc::builder()
8363            .with_column("replica_id", SqlScalarType::String.nullable(false))
8364            .with_column("object_id", SqlScalarType::String.nullable(false))
8365            .with_column(
8366                "physical_plan_node_id",
8367                SqlScalarType::UInt64.nullable(false),
8368            )
8369            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8370            .with_key(vec![0, 1, 2])
8371            .finish(),
8372        data_source: IntrospectionType::ComputeOperatorHydrationStatus,
8373        column_comments: BTreeMap::from_iter([
8374            ("replica_id", "The ID of a cluster replica."),
8375            (
8376                "object_id",
8377                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8378            ),
8379            (
8380                "physical_plan_node_id",
8381                "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)`.",
8382            ),
8383            ("hydrated", "Whether the node is hydrated on the replica."),
8384        ]),
8385        is_retained_metrics_object: false,
8386        access: vec![PUBLIC_SELECT],
8387    }
8388});
8389
8390pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8391    name: "mz_message_counts_per_worker",
8392    schema: MZ_INTROSPECTION_SCHEMA,
8393    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8394    desc: RelationDesc::builder()
8395        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8396        .with_column("from_worker_id", SqlScalarType::UInt64.nullable(false))
8397        .with_column("to_worker_id", SqlScalarType::UInt64.nullable(false))
8398        .with_column("sent", SqlScalarType::Int64.nullable(false))
8399        .with_column("received", SqlScalarType::Int64.nullable(false))
8400        .with_column("batch_sent", SqlScalarType::Int64.nullable(false))
8401        .with_column("batch_received", SqlScalarType::Int64.nullable(false))
8402        .with_key(vec![0, 1, 2])
8403        .finish(),
8404    column_comments: BTreeMap::new(),
8405    sql: "
8406WITH batch_sent_cte AS (
8407    SELECT
8408        channel_id,
8409        from_worker_id,
8410        to_worker_id,
8411        pg_catalog.count(*) AS sent
8412    FROM
8413        mz_introspection.mz_message_batch_counts_sent_raw
8414    GROUP BY
8415        channel_id, from_worker_id, to_worker_id
8416),
8417batch_received_cte AS (
8418    SELECT
8419        channel_id,
8420        from_worker_id,
8421        to_worker_id,
8422        pg_catalog.count(*) AS received
8423    FROM
8424        mz_introspection.mz_message_batch_counts_received_raw
8425    GROUP BY
8426        channel_id, from_worker_id, to_worker_id
8427),
8428sent_cte AS (
8429    SELECT
8430        channel_id,
8431        from_worker_id,
8432        to_worker_id,
8433        pg_catalog.count(*) AS sent
8434    FROM
8435        mz_introspection.mz_message_counts_sent_raw
8436    GROUP BY
8437        channel_id, from_worker_id, to_worker_id
8438),
8439received_cte AS (
8440    SELECT
8441        channel_id,
8442        from_worker_id,
8443        to_worker_id,
8444        pg_catalog.count(*) AS received
8445    FROM
8446        mz_introspection.mz_message_counts_received_raw
8447    GROUP BY
8448        channel_id, from_worker_id, to_worker_id
8449)
8450SELECT
8451    sent_cte.channel_id,
8452    sent_cte.from_worker_id,
8453    sent_cte.to_worker_id,
8454    sent_cte.sent,
8455    received_cte.received,
8456    batch_sent_cte.sent AS batch_sent,
8457    batch_received_cte.received AS batch_received
8458FROM sent_cte
8459JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8460JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8461JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8462    access: vec![PUBLIC_SELECT],
8463});
8464
8465pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8466    name: "mz_message_counts",
8467    schema: MZ_INTROSPECTION_SCHEMA,
8468    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8469    desc: RelationDesc::builder()
8470        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8471        .with_column(
8472            "sent",
8473            SqlScalarType::Numeric {
8474                max_scale: Some(NumericMaxScale::ZERO),
8475            }
8476            .nullable(false),
8477        )
8478        .with_column(
8479            "received",
8480            SqlScalarType::Numeric {
8481                max_scale: Some(NumericMaxScale::ZERO),
8482            }
8483            .nullable(false),
8484        )
8485        .with_column(
8486            "batch_sent",
8487            SqlScalarType::Numeric {
8488                max_scale: Some(NumericMaxScale::ZERO),
8489            }
8490            .nullable(false),
8491        )
8492        .with_column(
8493            "batch_received",
8494            SqlScalarType::Numeric {
8495                max_scale: Some(NumericMaxScale::ZERO),
8496            }
8497            .nullable(false),
8498        )
8499        .with_key(vec![0])
8500        .finish(),
8501    column_comments: BTreeMap::from_iter([
8502        (
8503            "channel_id",
8504            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8505        ),
8506        ("sent", "The number of messages sent."),
8507        ("received", "The number of messages received."),
8508        ("batch_sent", "The number of batches sent."),
8509        ("batch_received", "The number of batches received."),
8510    ]),
8511    sql: "
8512SELECT
8513    channel_id,
8514    pg_catalog.sum(sent) AS sent,
8515    pg_catalog.sum(received) AS received,
8516    pg_catalog.sum(batch_sent) AS batch_sent,
8517    pg_catalog.sum(batch_received) AS batch_received
8518FROM mz_introspection.mz_message_counts_per_worker
8519GROUP BY channel_id",
8520    access: vec![PUBLIC_SELECT],
8521});
8522
8523pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8524    name: "mz_active_peeks",
8525    schema: MZ_INTROSPECTION_SCHEMA,
8526    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8527    desc: RelationDesc::builder()
8528        .with_column("id", SqlScalarType::Uuid.nullable(false))
8529        .with_column("object_id", SqlScalarType::String.nullable(false))
8530        .with_column("type", SqlScalarType::String.nullable(false))
8531        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
8532        .finish(),
8533    column_comments: BTreeMap::from_iter([
8534        ("id", "The ID of the peek request."),
8535        (
8536            "object_id",
8537            "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`.",
8538        ),
8539        (
8540            "type",
8541            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8542        ),
8543        ("time", "The timestamp the peek has requested."),
8544    ]),
8545    sql: "
8546SELECT id, object_id, type, time
8547FROM mz_introspection.mz_active_peeks_per_worker
8548WHERE worker_id = 0",
8549    access: vec![PUBLIC_SELECT],
8550});
8551
8552pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8553    LazyLock::new(|| BuiltinView {
8554        name: "mz_dataflow_operator_reachability_per_worker",
8555        schema: MZ_INTROSPECTION_SCHEMA,
8556        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8557        desc: RelationDesc::builder()
8558            .with_column("id", SqlScalarType::UInt64.nullable(false))
8559            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8560            .with_column("port", SqlScalarType::UInt64.nullable(false))
8561            .with_column("update_type", SqlScalarType::String.nullable(false))
8562            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8563            .with_column("count", SqlScalarType::Int64.nullable(false))
8564            .with_key(vec![0, 1, 2, 3, 4])
8565            .finish(),
8566        column_comments: BTreeMap::new(),
8567        sql: "SELECT
8568    addr2.id,
8569    reachability.worker_id,
8570    port,
8571    update_type,
8572    time,
8573    pg_catalog.count(*) as count
8574FROM
8575    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8576    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8577    mz_introspection.mz_dataflow_addresses_per_worker addr2
8578WHERE
8579    addr2.address =
8580    CASE
8581        WHEN source = 0 THEN addr1.address
8582        ELSE addr1.address || reachability.source
8583    END
8584    AND addr1.id = reachability.id
8585    AND addr1.worker_id = reachability.worker_id
8586    AND addr2.worker_id = reachability.worker_id
8587GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8588        access: vec![PUBLIC_SELECT],
8589    });
8590
8591pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8592    LazyLock::new(|| BuiltinView {
8593        name: "mz_dataflow_operator_reachability",
8594        schema: MZ_INTROSPECTION_SCHEMA,
8595        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8596        desc: RelationDesc::builder()
8597            .with_column("id", SqlScalarType::UInt64.nullable(false))
8598            .with_column("port", SqlScalarType::UInt64.nullable(false))
8599            .with_column("update_type", SqlScalarType::String.nullable(false))
8600            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8601            .with_column(
8602                "count",
8603                SqlScalarType::Numeric {
8604                    max_scale: Some(NumericMaxScale::ZERO),
8605                }
8606                .nullable(false),
8607            )
8608            .with_key(vec![0, 1, 2, 3])
8609            .finish(),
8610        column_comments: BTreeMap::new(),
8611        sql: "
8612SELECT
8613    id,
8614    port,
8615    update_type,
8616    time,
8617    pg_catalog.sum(count) as count
8618FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8619GROUP BY id, port, update_type, time",
8620        access: vec![PUBLIC_SELECT],
8621    });
8622
8623pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8624    BuiltinView {
8625        name: "mz_arrangement_sizes_per_worker",
8626        schema: MZ_INTROSPECTION_SCHEMA,
8627        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8628        desc: RelationDesc::builder()
8629            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8630            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8631            .with_column("records", SqlScalarType::Int64.nullable(true))
8632            .with_column("batches", SqlScalarType::Int64.nullable(true))
8633            .with_column("size", SqlScalarType::Int64.nullable(true))
8634            .with_column("capacity", SqlScalarType::Int64.nullable(true))
8635            .with_column("allocations", SqlScalarType::Int64.nullable(true))
8636            .finish(),
8637        column_comments: BTreeMap::new(),
8638        sql: "
8639WITH operators_per_worker_cte AS (
8640    SELECT
8641        id AS operator_id,
8642        worker_id
8643    FROM
8644        mz_introspection.mz_dataflow_operators_per_worker
8645),
8646batches_cte AS (
8647    SELECT
8648        operator_id,
8649        worker_id,
8650        COUNT(*) AS batches
8651    FROM
8652        mz_introspection.mz_arrangement_batches_raw
8653    GROUP BY
8654        operator_id, worker_id
8655),
8656records_cte AS (
8657    SELECT
8658        operator_id,
8659        worker_id,
8660        COUNT(*) AS records
8661    FROM
8662        mz_introspection.mz_arrangement_records_raw
8663    GROUP BY
8664        operator_id, worker_id
8665),
8666heap_size_cte AS (
8667    SELECT
8668        operator_id,
8669        worker_id,
8670        COUNT(*) AS size
8671    FROM
8672        mz_introspection.mz_arrangement_heap_size_raw
8673    GROUP BY
8674        operator_id, worker_id
8675),
8676heap_capacity_cte AS (
8677    SELECT
8678        operator_id,
8679        worker_id,
8680        COUNT(*) AS capacity
8681    FROM
8682        mz_introspection.mz_arrangement_heap_capacity_raw
8683    GROUP BY
8684        operator_id, worker_id
8685),
8686heap_allocations_cte AS (
8687    SELECT
8688        operator_id,
8689        worker_id,
8690        COUNT(*) AS allocations
8691    FROM
8692        mz_introspection.mz_arrangement_heap_allocations_raw
8693    GROUP BY
8694        operator_id, worker_id
8695),
8696batcher_records_cte AS (
8697    SELECT
8698        operator_id,
8699        worker_id,
8700        COUNT(*) AS records
8701    FROM
8702        mz_introspection.mz_arrangement_batcher_records_raw
8703    GROUP BY
8704        operator_id, worker_id
8705),
8706batcher_size_cte AS (
8707    SELECT
8708        operator_id,
8709        worker_id,
8710        COUNT(*) AS size
8711    FROM
8712        mz_introspection.mz_arrangement_batcher_size_raw
8713    GROUP BY
8714        operator_id, worker_id
8715),
8716batcher_capacity_cte AS (
8717    SELECT
8718        operator_id,
8719        worker_id,
8720        COUNT(*) AS capacity
8721    FROM
8722        mz_introspection.mz_arrangement_batcher_capacity_raw
8723    GROUP BY
8724        operator_id, worker_id
8725),
8726batcher_allocations_cte AS (
8727    SELECT
8728        operator_id,
8729        worker_id,
8730        COUNT(*) AS allocations
8731    FROM
8732        mz_introspection.mz_arrangement_batcher_allocations_raw
8733    GROUP BY
8734        operator_id, worker_id
8735),
8736combined AS (
8737    SELECT
8738        opw.operator_id,
8739        opw.worker_id,
8740        CASE
8741            WHEN records_cte.records IS NULL AND batcher_records_cte.records IS NULL THEN NULL
8742            ELSE COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0)
8743        END AS records,
8744        batches_cte.batches AS batches,
8745        CASE
8746            WHEN heap_size_cte.size IS NULL AND batcher_size_cte.size IS NULL THEN NULL
8747            ELSE COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0)
8748        END AS size,
8749        CASE
8750            WHEN heap_capacity_cte.capacity IS NULL AND batcher_capacity_cte.capacity IS NULL THEN NULL
8751            ELSE COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0)
8752        END AS capacity,
8753        CASE
8754            WHEN heap_allocations_cte.allocations IS NULL AND batcher_allocations_cte.allocations IS NULL THEN NULL
8755            ELSE COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0)
8756        END AS allocations
8757    FROM
8758                    operators_per_worker_cte opw
8759    LEFT OUTER JOIN batches_cte USING (operator_id, worker_id)
8760    LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
8761    LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
8762    LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
8763    LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
8764    LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
8765    LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
8766    LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
8767    LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)
8768)
8769SELECT
8770    operator_id, worker_id, records, batches, size, capacity, allocations
8771FROM combined
8772WHERE
8773       records     IS NOT NULL
8774    OR batches     IS NOT NULL
8775    OR size        IS NOT NULL
8776    OR capacity    IS NOT NULL
8777    OR allocations IS NOT NULL
8778",
8779        access: vec![PUBLIC_SELECT],
8780    }
8781});
8782
8783pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8784    name: "mz_arrangement_sizes",
8785    schema: MZ_INTROSPECTION_SCHEMA,
8786    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
8787    desc: RelationDesc::builder()
8788        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8789        .with_column("records", SqlScalarType::Int64.nullable(true))
8790        .with_column("batches", SqlScalarType::Int64.nullable(true))
8791        .with_column("size", SqlScalarType::Int64.nullable(true))
8792        .with_column("capacity", SqlScalarType::Int64.nullable(true))
8793        .with_column("allocations", SqlScalarType::Int64.nullable(true))
8794        .with_key(vec![0])
8795        .finish(),
8796    column_comments: BTreeMap::from_iter([
8797        (
8798            "operator_id",
8799            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8800        ),
8801        ("records", "The number of records in the arrangement."),
8802        ("batches", "The number of batches in the arrangement."),
8803        ("size", "The utilized size in bytes of the arrangement."),
8804        (
8805            "capacity",
8806            "The capacity in bytes of the arrangement. Can be larger than the size.",
8807        ),
8808        (
8809            "allocations",
8810            "The number of separate memory allocations backing the arrangement.",
8811        ),
8812    ]),
8813    sql: "
8814SELECT
8815    operator_id,
8816    SUM(records)::int8 AS records,
8817    SUM(batches)::int8 AS batches,
8818    SUM(size)::int8 AS size,
8819    SUM(capacity)::int8 AS capacity,
8820    SUM(allocations)::int8 AS allocations
8821FROM mz_introspection.mz_arrangement_sizes_per_worker
8822GROUP BY operator_id",
8823    access: vec![PUBLIC_SELECT],
8824});
8825
8826pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
8827    LazyLock::new(|| BuiltinView {
8828        name: "mz_arrangement_sharing_per_worker",
8829        schema: MZ_INTROSPECTION_SCHEMA,
8830        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
8831        desc: RelationDesc::builder()
8832            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8833            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8834            .with_column("count", SqlScalarType::Int64.nullable(false))
8835            .with_key(vec![0, 1])
8836            .finish(),
8837        column_comments: BTreeMap::new(),
8838        sql: "
8839SELECT
8840    operator_id,
8841    worker_id,
8842    pg_catalog.count(*) AS count
8843FROM mz_introspection.mz_arrangement_sharing_raw
8844GROUP BY operator_id, worker_id",
8845        access: vec![PUBLIC_SELECT],
8846    });
8847
8848pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8849    name: "mz_arrangement_sharing",
8850    schema: MZ_INTROSPECTION_SCHEMA,
8851    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
8852    desc: RelationDesc::builder()
8853        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8854        .with_column("count", SqlScalarType::Int64.nullable(false))
8855        .finish(),
8856    column_comments: BTreeMap::from_iter([
8857        (
8858            "operator_id",
8859            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
8860        ),
8861        (
8862            "count",
8863            "The number of operators that share the arrangement.",
8864        ),
8865    ]),
8866    sql: "
8867SELECT operator_id, count
8868FROM mz_introspection.mz_arrangement_sharing_per_worker
8869WHERE worker_id = 0",
8870    access: vec![PUBLIC_SELECT],
8871});
8872
8873pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8874    name: "mz_cluster_replica_utilization",
8875    schema: MZ_INTERNAL_SCHEMA,
8876    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
8877    desc: RelationDesc::builder()
8878        .with_column("replica_id", SqlScalarType::String.nullable(false))
8879        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
8880        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8881        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8882        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8883        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8884        .finish(),
8885    column_comments: BTreeMap::from_iter([
8886        ("replica_id", "The ID of a cluster replica."),
8887        ("process_id", "The ID of a process within the replica."),
8888        (
8889            "cpu_percent",
8890            "Approximate CPU usage, in percent of the total allocation.",
8891        ),
8892        (
8893            "memory_percent",
8894            "Approximate RAM usage, in percent of the total allocation.",
8895        ),
8896        (
8897            "disk_percent",
8898            "Approximate disk usage, in percent of the total allocation.",
8899        ),
8900        (
8901            "heap_percent",
8902            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
8903        ),
8904    ]),
8905    sql: "
8906SELECT
8907    r.id AS replica_id,
8908    m.process_id,
8909    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
8910    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
8911    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
8912    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent
8913FROM
8914    mz_catalog.mz_cluster_replicas AS r
8915        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8916        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
8917    access: vec![PUBLIC_SELECT],
8918});
8919
8920pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
8921    LazyLock::new(|| BuiltinView {
8922        name: "mz_cluster_replica_utilization_history",
8923        schema: MZ_INTERNAL_SCHEMA,
8924        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
8925        desc: RelationDesc::builder()
8926            .with_column("replica_id", SqlScalarType::String.nullable(false))
8927            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
8928            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8929            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8930            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8931            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8932            .with_column(
8933                "occurred_at",
8934                SqlScalarType::TimestampTz { precision: None }.nullable(false),
8935            )
8936            .finish(),
8937        column_comments: BTreeMap::from_iter([
8938            ("replica_id", "The ID of a cluster replica."),
8939            ("process_id", "The ID of a process within the replica."),
8940            (
8941                "cpu_percent",
8942                "Approximate CPU usage, in percent of the total allocation.",
8943            ),
8944            (
8945                "memory_percent",
8946                "Approximate RAM usage, in percent of the total allocation.",
8947            ),
8948            (
8949                "disk_percent",
8950                "Approximate disk usage, in percent of the total allocation.",
8951            ),
8952            (
8953                "heap_percent",
8954                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
8955            ),
8956            (
8957                "occurred_at",
8958                "Wall-clock timestamp at which the event occurred.",
8959            ),
8960        ]),
8961        sql: "
8962SELECT
8963    r.id AS replica_id,
8964    m.process_id,
8965    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
8966    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
8967    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
8968    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
8969    m.occurred_at
8970FROM
8971    mz_catalog.mz_cluster_replicas AS r
8972        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8973        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
8974        access: vec![PUBLIC_SELECT],
8975    });
8976
8977pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
8978    LazyLock::new(|| BuiltinView {
8979        name: "mz_dataflow_operator_parents_per_worker",
8980        schema: MZ_INTROSPECTION_SCHEMA,
8981        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
8982        desc: RelationDesc::builder()
8983            .with_column("id", SqlScalarType::UInt64.nullable(false))
8984            .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
8985            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8986            .finish(),
8987        column_comments: BTreeMap::new(),
8988        sql: "
8989WITH operator_addrs AS(
8990    SELECT
8991        id, address, worker_id
8992    FROM mz_introspection.mz_dataflow_addresses_per_worker
8993        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
8994            USING (id, worker_id)
8995),
8996parent_addrs AS (
8997    SELECT
8998        id,
8999        address[1:list_length(address) - 1] AS parent_address,
9000        worker_id
9001    FROM operator_addrs
9002)
9003SELECT pa.id, oa.id AS parent_id, pa.worker_id
9004FROM parent_addrs AS pa
9005    INNER JOIN operator_addrs AS oa
9006        ON pa.parent_address = oa.address
9007        AND pa.worker_id = oa.worker_id",
9008        access: vec![PUBLIC_SELECT],
9009    });
9010
9011pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9012    name: "mz_dataflow_operator_parents",
9013    schema: MZ_INTROSPECTION_SCHEMA,
9014    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
9015    desc: RelationDesc::builder()
9016        .with_column("id", SqlScalarType::UInt64.nullable(false))
9017        .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9018        .finish(),
9019    column_comments: BTreeMap::from_iter([
9020        (
9021            "id",
9022            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
9023        ),
9024        (
9025            "parent_id",
9026            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
9027        ),
9028    ]),
9029    sql: "
9030SELECT id, parent_id
9031FROM mz_introspection.mz_dataflow_operator_parents_per_worker
9032WHERE worker_id = 0",
9033    access: vec![PUBLIC_SELECT],
9034});
9035
9036pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9037    name: "mz_dataflow_arrangement_sizes",
9038    schema: MZ_INTROSPECTION_SCHEMA,
9039    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
9040    desc: RelationDesc::builder()
9041        .with_column("id", SqlScalarType::UInt64.nullable(false))
9042        .with_column("name", SqlScalarType::String.nullable(false))
9043        .with_column("records", SqlScalarType::Int64.nullable(true))
9044        .with_column("batches", SqlScalarType::Int64.nullable(true))
9045        .with_column("size", SqlScalarType::Int64.nullable(true))
9046        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9047        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9048        .with_key(vec![0, 1])
9049        .finish(),
9050    column_comments: BTreeMap::from_iter([
9051        (
9052            "id",
9053            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9054        ),
9055        ("name", "The name of the [dataflow]."),
9056        (
9057            "records",
9058            "The number of records in all arrangements in the dataflow.",
9059        ),
9060        (
9061            "batches",
9062            "The number of batches in all arrangements in the dataflow.",
9063        ),
9064        ("size", "The utilized size in bytes of the arrangements."),
9065        (
9066            "capacity",
9067            "The capacity in bytes of the arrangements. Can be larger than the size.",
9068        ),
9069        (
9070            "allocations",
9071            "The number of separate memory allocations backing the arrangements.",
9072        ),
9073    ]),
9074    sql: "
9075SELECT
9076    mdod.dataflow_id AS id,
9077    mdod.dataflow_name AS name,
9078    SUM(mas.records)::int8 AS records,
9079    SUM(mas.batches)::int8 AS batches,
9080    SUM(mas.size)::int8 AS size,
9081    SUM(mas.capacity)::int8 AS capacity,
9082    SUM(mas.allocations)::int8 AS allocations
9083FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9084LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9085    ON mdod.id = mas.operator_id
9086GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9087    access: vec![PUBLIC_SELECT],
9088});
9089
9090pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9091    name: "mz_expected_group_size_advice",
9092    schema: MZ_INTROSPECTION_SCHEMA,
9093    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9094    desc: RelationDesc::builder()
9095        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
9096        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
9097        .with_column("region_id", SqlScalarType::UInt64.nullable(false))
9098        .with_column("region_name", SqlScalarType::String.nullable(false))
9099        .with_column("levels", SqlScalarType::Int64.nullable(false))
9100        .with_column("to_cut", SqlScalarType::Int64.nullable(false))
9101        .with_column(
9102            "savings",
9103            SqlScalarType::Numeric {
9104                max_scale: Some(NumericMaxScale::ZERO),
9105            }
9106            .nullable(true),
9107        )
9108        .with_column("hint", SqlScalarType::Float64.nullable(false))
9109        .finish(),
9110    column_comments: BTreeMap::from_iter([
9111        (
9112            "dataflow_id",
9113            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9114        ),
9115        (
9116            "dataflow_name",
9117            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9118        ),
9119        (
9120            "region_id",
9121            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9122        ),
9123        (
9124            "region_name",
9125            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9126        ),
9127        (
9128            "levels",
9129            "The number of levels in the hierarchical scheme implemented by the region.",
9130        ),
9131        (
9132            "to_cut",
9133            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9134        ),
9135        (
9136            "savings",
9137            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9138        ),
9139        (
9140            "hint",
9141            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9142        ),
9143    ]),
9144    sql: "
9145        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9146        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9147        -- of arrangements must be built. For each dataflow and region corresponding to one
9148        -- such pattern, we look for how many levels can be eliminated without hitting a level
9149        -- that actually substantially filters the input. The advice is constructed so that
9150        -- setting the hint for the affected region will eliminate these redundant levels of
9151        -- the hierarchical rendering.
9152        --
9153        -- A number of helper CTEs are used for the view definition. The first one, operators,
9154        -- looks for operator names that comprise arrangements of inputs to each level of a
9155        -- min/max/top-k hierarchy.
9156        WITH operators AS (
9157            SELECT
9158                dod.dataflow_id,
9159                dor.id AS region_id,
9160                dod.id,
9161                ars.records,
9162                ars.size
9163            FROM
9164                mz_introspection.mz_dataflow_operator_dataflows dod
9165                JOIN mz_introspection.mz_dataflow_addresses doa
9166                    ON dod.id = doa.id
9167                JOIN mz_introspection.mz_dataflow_addresses dra
9168                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9169                JOIN mz_introspection.mz_dataflow_operators dor
9170                    ON dor.id = dra.id
9171                JOIN mz_introspection.mz_arrangement_sizes ars
9172                    ON ars.operator_id = dod.id
9173            WHERE
9174                dod.name = 'Arranged TopK input'
9175                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9176                OR dod.name = 'Arrange ReduceMinsMaxes'
9177            ),
9178        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9179        -- identified in operators above.
9180        levels AS (
9181            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9182            FROM operators o
9183            GROUP BY o.dataflow_id, o.region_id
9184        ),
9185        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9186        -- operator. This operator is crucially important, as it records the number of records
9187        -- that was given as input to the gadget as a whole.
9188        pivot AS (
9189            SELECT
9190                o1.dataflow_id,
9191                o1.region_id,
9192                o1.id,
9193                o1.records
9194            FROM operators o1
9195            WHERE
9196                o1.id = (
9197                    SELECT MIN(o2.id)
9198                    FROM operators o2
9199                    WHERE
9200                        o2.dataflow_id = o1.dataflow_id
9201                        AND o2.region_id = o1.region_id
9202                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9203                )
9204        ),
9205        -- The fourth CTE, candidates, will look for operators where the number of records
9206        -- maintained is not significantly different from the number at the pivot (excluding
9207        -- the pivot itself). These are the candidates for being cut from the dataflow region
9208        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9209        -- load generator data, to give some room for small deviations in number of records.
9210        -- The intuition for allowing for this deviation is that we are looking for a strongly
9211        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9212        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9213        -- among groups where the min/max/top-k computation is (partially) applied. If the
9214        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9215        -- groups might be empty or contain only one row. Each subsequent level will have a number
9216        -- of groups that is reduced exponentially. So at some point, we will find the level where
9217        -- we actually start having a few rows per group. That's where we will see the row counts
9218        -- significantly drop off.
9219        candidates AS (
9220            SELECT
9221                o.dataflow_id,
9222                o.region_id,
9223                o.id,
9224                o.records,
9225                o.size
9226            FROM
9227                operators o
9228                JOIN pivot p
9229                    ON o.dataflow_id = p.dataflow_id
9230                        AND o.region_id = p.region_id
9231                        AND o.id <> p.id
9232            WHERE o.records >= p.records * (1 - 0.15)
9233        ),
9234        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9235        -- candidate levels that should be cut. We only return here dataflow regions where at
9236        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9237        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9238        -- cutting the height of the hierarchy further. This is because we will have way less
9239        -- groups in the next level, so there should be even further reduction happening or there
9240        -- is some substantial skew in the data. But if the latter is the case, then we should not
9241        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9242        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9243        -- compute a conservative estimate of the memory savings in bytes that will result from
9244        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9245        -- input arrangements for each level to be cut. These arrangements should dominate the
9246        -- size of each level that can be cut, since the reduction gadget internal to the level
9247        -- does not remove much data at these levels.
9248        cuts AS (
9249            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9250            FROM candidates c
9251            GROUP BY c.dataflow_id, c.region_id
9252            HAVING COUNT(*) > 0
9253        )
9254        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9255        -- levels and the number of candidates to be cut. The hint is computed taking into account
9256        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9257        -- currently equal to 16.
9258        SELECT
9259            dod.dataflow_id,
9260            dod.dataflow_name,
9261            dod.id AS region_id,
9262            dod.name AS region_name,
9263            l.levels,
9264            c.to_cut,
9265            c.savings,
9266            pow(16, l.levels - c.to_cut) - 1 AS hint
9267        FROM cuts c
9268            JOIN levels l
9269                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9270            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9271                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9272    access: vec![PUBLIC_SELECT],
9273});
9274
9275pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9276    BuiltinView {
9277        name: "mz_index_advice",
9278        schema: MZ_INTERNAL_SCHEMA,
9279        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9280        desc: RelationDesc::builder()
9281            .with_column("object_id", SqlScalarType::String.nullable(true))
9282            .with_column("hint", SqlScalarType::String.nullable(false))
9283            .with_column("details", SqlScalarType::String.nullable(false))
9284            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
9285            .finish(),
9286        column_comments: BTreeMap::from_iter([
9287            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9288            ("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."),
9289            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9290            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9291        ]),
9292        sql: "
9293-- To avoid confusion with sources and sinks in the materialize sense,
9294-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9295-- when referring to the object dependency graph.
9296--
9297-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9298-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9299-- that are not depended on by other maintained objects and have a justification why they must
9300-- be maintained (e.g. a materialized view that is depended on by a sink).
9301-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9302-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9303-- downstream objects, that node is marked to be converted into a maintained object and this
9304-- node is then propagated further up. Once completed, the list of objects that are marked as
9305-- maintained is checked against all objects to generate appropriate recommendations.
9306--
9307-- Note that the recommendations only incorporate dependencies between objects.
9308-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9309-- a sink if an index is added in between the sink and the filter. For very selective filters,
9310-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9311-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9312-- dependencies.
9313WITH MUTUALLY RECURSIVE
9314    -- for all objects, understand if they have an index on them and on which cluster they are running
9315    -- this avoids having different cases for views with an index and materialized views later on
9316    objects(id text, type text, cluster_id text, indexes text list) AS (
9317        -- views and materialized views without an index
9318        SELECT
9319            o.id,
9320            o.type,
9321            o.cluster_id,
9322            '{}'::text list AS indexes
9323        FROM mz_catalog.mz_objects o
9324        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9325            SELECT FROM mz_internal.mz_object_dependencies d
9326            JOIN mz_catalog.mz_objects AS i
9327                ON (i.id = d.object_id AND i.type = 'index')
9328            WHERE (o.id = d.referenced_object_id)
9329        )
9330
9331        UNION ALL
9332
9333        -- views and materialized views with an index
9334        SELECT
9335            o.id,
9336            o.type,
9337            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9338            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9339            list_agg(i.id) AS indexes
9340        FROM mz_catalog.mz_objects o
9341        JOIN mz_internal.mz_object_dependencies AS d
9342            ON (o.id = d.referenced_object_id)
9343        JOIN mz_catalog.mz_objects AS i
9344            ON (i.id = d.object_id AND i.type = 'index')
9345        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9346        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9347    ),
9348
9349    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9350    maintained_leafs(id text, justification text) AS (
9351        -- materialized views that are connected to a sink
9352        SELECT
9353            m.id,
9354            s.id AS justification
9355        FROM objects AS m
9356        JOIN mz_internal.mz_object_dependencies AS d
9357            ON (m.id = d.referenced_object_id)
9358        JOIN mz_catalog.mz_objects AS s
9359            ON (s.id = d.object_id AND s.type = 'sink')
9360        WHERE m.type = 'materialized-view'
9361
9362        UNION ALL
9363
9364        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9365        SELECT
9366            v.id,
9367            unnest(v.indexes) AS justification
9368        FROM objects AS v
9369        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9370            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9371            INNER JOIN mz_catalog.mz_objects AS child
9372                ON (d.object_id = child.id)
9373            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]
9374        )
9375    ),
9376
9377    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9378    agg_maintained_children(id text, maintained_children text list) AS (
9379        SELECT
9380            parent_id AS id,
9381            list_agg(maintained_child) AS maintained_leafs
9382        FROM (
9383            SELECT DISTINCT
9384                d.referenced_object_id AS parent_id,
9385                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9386                unnest(child.maintained_children) AS maintained_child
9387            FROM propagate_dependencies AS child
9388            INNER JOIN mz_internal.mz_object_dependencies AS d
9389                ON (child.id = d.object_id)
9390        )
9391        GROUP BY parent_id
9392    ),
9393
9394    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9395    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9396    -- 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
9397    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9398        -- base case: start with the leafs
9399        SELECT DISTINCT
9400            id,
9401            LIST[id] AS maintained_children,
9402            list_agg(justification) AS justification
9403        FROM maintained_leafs
9404        GROUP BY id
9405
9406        UNION
9407
9408        -- recursive case: if there is a child with the same dependencies as the parent,
9409        -- the parent is only reused by a single child
9410        SELECT
9411            parent.id,
9412            child.maintained_children,
9413            NULL::text list AS justification
9414        FROM agg_maintained_children AS parent
9415        INNER JOIN mz_internal.mz_object_dependencies AS d
9416            ON (parent.id = d.referenced_object_id)
9417        INNER JOIN propagate_dependencies AS child
9418            ON (d.object_id = child.id)
9419        WHERE parent.maintained_children = child.maintained_children
9420
9421        UNION
9422
9423        -- recursive case: if there is NO child with the same dependencies as the parent,
9424        -- different children are reusing the parent so maintaining the object is justified by itself
9425        SELECT DISTINCT
9426            parent.id,
9427            LIST[parent.id] AS maintained_children,
9428            parent.maintained_children AS justification
9429        FROM agg_maintained_children AS parent
9430        WHERE NOT EXISTS (
9431            SELECT FROM mz_internal.mz_object_dependencies AS d
9432            INNER JOIN propagate_dependencies AS child
9433                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9434            WHERE parent.maintained_children = child.maintained_children
9435        )
9436    ),
9437
9438    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9439        SELECT
9440            p.id,
9441            o.type,
9442            o.cluster_id,
9443            p.maintained_children,
9444            p.justification,
9445            o.indexes
9446        FROM propagate_dependencies p
9447        JOIN objects AS o
9448            ON (p.id = o.id)
9449    ),
9450
9451    hints(id text, hint text, details text, justification text list) AS (
9452        -- materialized views that are not required
9453        SELECT
9454            id,
9455            'convert to a view' AS hint,
9456            'no dependencies from sinks nor from objects on different clusters' AS details,
9457            justification
9458        FROM objects_with_justification
9459        WHERE type = 'materialized-view' AND justification IS NULL
9460
9461        UNION ALL
9462
9463        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9464        SELECT
9465            id,
9466            'keep' AS hint,
9467            'dependencies from sinks or objects on different clusters: ' AS details,
9468            justification
9469        FROM objects_with_justification AS m
9470        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9471            SELECT FROM unnest(justification) AS dependency
9472            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9473
9474            UNION ALL
9475
9476            SELECT FROM unnest(justification) AS dependency
9477            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9478            WHERE d.cluster_id != m.cluster_id
9479        )
9480
9481        UNION ALL
9482
9483        -- 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
9484        SELECT
9485            id,
9486            'convert to a view with an index' AS hint,
9487            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9488            justification
9489        FROM objects_with_justification AS m
9490        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
9491            SELECT FROM unnest(justification) AS dependency
9492            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9493
9494            UNION ALL
9495
9496            SELECT FROM unnest(justification) AS dependency
9497            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9498            WHERE d.cluster_id != m.cluster_id
9499        )
9500
9501        UNION ALL
9502
9503        -- views that have indexes on different clusters should be a materialized view
9504        SELECT
9505            o.id,
9506            'convert to materialized view' AS hint,
9507            'dependencies on multiple clusters: ' AS details,
9508            o.justification
9509        FROM objects_with_justification o,
9510            LATERAL unnest(o.justification) j
9511        LEFT JOIN mz_catalog.mz_objects AS m
9512            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9513        WHERE o.type = 'view' AND o.justification IS NOT NULL
9514        GROUP BY o.id, o.justification
9515        HAVING count(DISTINCT m.cluster_id) >= 2
9516
9517        UNION ALL
9518
9519        -- views without an index that should be maintained
9520        SELECT
9521            id,
9522            'add index' AS hint,
9523            'multiple downstream dependencies: ' AS details,
9524            justification
9525        FROM objects_with_justification
9526        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9527
9528        UNION ALL
9529
9530        -- index inside the dependency graph (not a leaf)
9531        SELECT
9532            unnest(indexes) AS id,
9533            'drop unless queried directly' AS hint,
9534            'fewer than two downstream dependencies: ' AS details,
9535            maintained_children AS justification
9536        FROM objects_with_justification
9537        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9538
9539        UNION ALL
9540
9541        -- index on a leaf of the dependency graph
9542        SELECT
9543            unnest(indexes) AS id,
9544            'drop unless queried directly' AS hint,
9545            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9546            NULL::text list AS justification
9547        FROM objects_with_justification
9548        -- indexes can only be part of justification for leaf nodes
9549        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9550
9551        UNION ALL
9552
9553        -- index on a source
9554        SELECT
9555            unnest(indexes) AS id,
9556            'drop unless queried directly' AS hint,
9557            'sources do not transform data and can expose data directly' AS details,
9558            NULL::text list AS justification
9559        FROM objects_with_justification
9560        -- indexes can only be part of justification for leaf nodes
9561        WHERE type = 'source' AND NOT indexes = '{}'::text list
9562
9563        UNION ALL
9564
9565        -- indexes on views inside the dependency graph
9566        SELECT
9567            unnest(indexes) AS id,
9568            'keep' AS hint,
9569            'multiple downstream dependencies: ' AS details,
9570            justification
9571        FROM objects_with_justification
9572        -- indexes can only be part of justification for leaf nodes
9573        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9574    ),
9575
9576    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9577        SELECT
9578            h.id,
9579            h.hint,
9580            h.details || list_agg(o.name)::text AS details,
9581            h.justification
9582        FROM hints AS h,
9583            LATERAL unnest(h.justification) j
9584        JOIN mz_catalog.mz_objects AS o
9585            ON (o.id = j)
9586        GROUP BY h.id, h.hint, h.details, h.justification
9587
9588        UNION ALL
9589
9590        SELECT
9591            id,
9592            hint,
9593            details,
9594            justification
9595        FROM hints
9596        WHERE justification IS NULL
9597    )
9598
9599SELECT
9600    h.id AS object_id,
9601    h.hint AS hint,
9602    h.details,
9603    h.justification AS referenced_object_ids
9604FROM hints_resolved_ids AS h",
9605        access: vec![PUBLIC_SELECT],
9606    }
9607});
9608
9609// NOTE: If you add real data to this implementation, then please update
9610// the related `pg_` function implementations (like `pg_get_constraintdef`)
9611pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9612    name: "pg_constraint",
9613    schema: PG_CATALOG_SCHEMA,
9614    oid: oid::VIEW_PG_CONSTRAINT_OID,
9615    desc: RelationDesc::builder()
9616        .with_column("oid", SqlScalarType::Oid.nullable(false))
9617        .with_column("conname", SqlScalarType::String.nullable(false))
9618        .with_column("connamespace", SqlScalarType::Oid.nullable(false))
9619        .with_column("contype", SqlScalarType::PgLegacyChar.nullable(false))
9620        .with_column("condeferrable", SqlScalarType::Bool.nullable(false))
9621        .with_column("condeferred", SqlScalarType::Bool.nullable(false))
9622        .with_column("convalidated", SqlScalarType::Bool.nullable(false))
9623        .with_column("conrelid", SqlScalarType::Oid.nullable(false))
9624        .with_column("contypid", SqlScalarType::Oid.nullable(false))
9625        .with_column("conindid", SqlScalarType::Oid.nullable(false))
9626        .with_column("conparentid", SqlScalarType::Oid.nullable(false))
9627        .with_column("confrelid", SqlScalarType::Oid.nullable(false))
9628        .with_column("confupdtype", SqlScalarType::PgLegacyChar.nullable(false))
9629        .with_column("confdeltype", SqlScalarType::PgLegacyChar.nullable(false))
9630        .with_column("confmatchtype", SqlScalarType::PgLegacyChar.nullable(false))
9631        .with_column("conislocal", SqlScalarType::Bool.nullable(false))
9632        .with_column("coninhcount", SqlScalarType::Int32.nullable(false))
9633        .with_column("connoinherit", SqlScalarType::Bool.nullable(false))
9634        .with_column(
9635            "conkey",
9636            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9637        )
9638        .with_column(
9639            "confkey",
9640            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9641        )
9642        .with_column(
9643            "conpfeqop",
9644            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9645        )
9646        .with_column(
9647            "conppeqop",
9648            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9649        )
9650        .with_column(
9651            "conffeqop",
9652            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9653        )
9654        .with_column(
9655            "conexclop",
9656            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
9657        )
9658        .with_column("conbin", SqlScalarType::String.nullable(false))
9659        .with_key(vec![])
9660        .finish(),
9661    column_comments: BTreeMap::new(),
9662    sql: "SELECT
9663    NULL::pg_catalog.oid as oid,
9664    NULL::pg_catalog.text as conname,
9665    NULL::pg_catalog.oid as connamespace,
9666    NULL::pg_catalog.\"char\" as contype,
9667    NULL::pg_catalog.bool as condeferrable,
9668    NULL::pg_catalog.bool as condeferred,
9669    NULL::pg_catalog.bool as convalidated,
9670    NULL::pg_catalog.oid as conrelid,
9671    NULL::pg_catalog.oid as contypid,
9672    NULL::pg_catalog.oid as conindid,
9673    NULL::pg_catalog.oid as conparentid,
9674    NULL::pg_catalog.oid as confrelid,
9675    NULL::pg_catalog.\"char\" as confupdtype,
9676    NULL::pg_catalog.\"char\" as confdeltype,
9677    NULL::pg_catalog.\"char\" as confmatchtype,
9678    NULL::pg_catalog.bool as conislocal,
9679    NULL::pg_catalog.int4 as coninhcount,
9680    NULL::pg_catalog.bool as connoinherit,
9681    NULL::pg_catalog.int2[] as conkey,
9682    NULL::pg_catalog.int2[] as confkey,
9683    NULL::pg_catalog.oid[] as conpfeqop,
9684    NULL::pg_catalog.oid[] as conppeqop,
9685    NULL::pg_catalog.oid[] as conffeqop,
9686    NULL::pg_catalog.oid[] as conexclop,
9687    NULL::pg_catalog.text as conbin
9688WHERE false",
9689    access: vec![PUBLIC_SELECT],
9690});
9691
9692pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9693    name: "pg_tables",
9694    schema: PG_CATALOG_SCHEMA,
9695    oid: oid::VIEW_PG_TABLES_OID,
9696    desc: RelationDesc::builder()
9697        .with_column("schemaname", SqlScalarType::String.nullable(true))
9698        .with_column("tablename", SqlScalarType::String.nullable(false))
9699        .with_column("tableowner", SqlScalarType::String.nullable(false))
9700        .finish(),
9701    column_comments: BTreeMap::new(),
9702    sql: "
9703SELECT n.nspname AS schemaname,
9704    c.relname AS tablename,
9705    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
9706FROM pg_catalog.pg_class c
9707LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
9708WHERE c.relkind IN ('r', 'p')",
9709    access: vec![PUBLIC_SELECT],
9710});
9711
9712pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9713    name: "pg_tablespace",
9714    schema: PG_CATALOG_SCHEMA,
9715    oid: oid::VIEW_PG_TABLESPACE_OID,
9716    desc: RelationDesc::builder()
9717        .with_column("oid", SqlScalarType::Oid.nullable(false))
9718        .with_column("spcname", SqlScalarType::String.nullable(false))
9719        .with_column("spcowner", SqlScalarType::Oid.nullable(true))
9720        .with_column(
9721            "spcacl",
9722            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9723        )
9724        .with_column(
9725            "spcoptions",
9726            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9727        )
9728        .with_key(vec![])
9729        .finish(),
9730    column_comments: BTreeMap::new(),
9731    sql: "
9732    SELECT oid, spcname, spcowner, spcacl, spcoptions
9733    FROM (
9734        VALUES (
9735            --These are the same defaults CockroachDB uses.
9736            0::pg_catalog.oid,
9737            'pg_default'::pg_catalog.text,
9738            NULL::pg_catalog.oid,
9739            NULL::pg_catalog.text[],
9740            NULL::pg_catalog.text[]
9741        )
9742    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
9743",
9744    access: vec![PUBLIC_SELECT],
9745});
9746
9747pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9748    name: "pg_am",
9749    schema: PG_CATALOG_SCHEMA,
9750    oid: oid::VIEW_PG_AM_OID,
9751    desc: RelationDesc::builder()
9752        .with_column("oid", SqlScalarType::Oid.nullable(false))
9753        .with_column("amname", SqlScalarType::String.nullable(false))
9754        .with_column("amhandler", SqlScalarType::RegProc.nullable(false))
9755        .with_column("amtype", SqlScalarType::PgLegacyChar.nullable(false))
9756        .with_key(vec![])
9757        .finish(),
9758    column_comments: BTreeMap::new(),
9759    sql: "
9760SELECT NULL::pg_catalog.oid AS oid,
9761    NULL::pg_catalog.text AS amname,
9762    NULL::pg_catalog.regproc AS amhandler,
9763    NULL::pg_catalog.\"char\" AS amtype
9764WHERE false",
9765    access: vec![PUBLIC_SELECT],
9766});
9767
9768pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9769    name: "pg_roles",
9770    schema: PG_CATALOG_SCHEMA,
9771    oid: oid::VIEW_PG_ROLES_OID,
9772    desc: RelationDesc::builder()
9773        .with_column("rolname", SqlScalarType::String.nullable(false))
9774        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
9775        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
9776        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
9777        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
9778        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
9779        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
9780        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
9781        .with_column("rolpassword", SqlScalarType::String.nullable(false))
9782        .with_column(
9783            "rolvaliduntil",
9784            SqlScalarType::TimestampTz { precision: None }.nullable(true),
9785        )
9786        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
9787        .with_column(
9788            "rolconfig",
9789            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9790        )
9791        .with_column("oid", SqlScalarType::Oid.nullable(false))
9792        .finish(),
9793    column_comments: BTreeMap::new(),
9794    sql: "SELECT
9795    rolname,
9796    rolsuper,
9797    rolinherit,
9798    rolcreaterole,
9799    rolcreatedb,
9800    COALESCE(rolcanlogin, false) AS rolcanlogin,
9801    rolreplication,
9802    rolconnlimit,
9803    '********' as rolpassword,
9804    rolvaliduntil,
9805    rolbypassrls,
9806    (
9807        SELECT array_agg(parameter_name || '=' || parameter_value)
9808        FROM mz_catalog.mz_role_parameters rp
9809        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9810        WHERE ai.oid = r.oid
9811    ) AS rolconfig,
9812    oid
9813FROM pg_catalog.pg_authid ai",
9814    access: vec![PUBLIC_SELECT],
9815});
9816
9817pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9818    name: "pg_user",
9819    schema: PG_CATALOG_SCHEMA,
9820    oid: oid::VIEW_PG_USER_OID,
9821    desc: RelationDesc::builder()
9822        .with_column("usename", SqlScalarType::String.nullable(false))
9823        .with_column("usesysid", SqlScalarType::Oid.nullable(false))
9824        .with_column("usecreatedb", SqlScalarType::Bool.nullable(true))
9825        .with_column("usesuper", SqlScalarType::Bool.nullable(true))
9826        .with_column("userepl", SqlScalarType::Bool.nullable(false))
9827        .with_column("usebypassrls", SqlScalarType::Bool.nullable(false))
9828        .with_column("passwd", SqlScalarType::String.nullable(true))
9829        .with_column(
9830            "valuntil",
9831            SqlScalarType::TimestampTz { precision: None }.nullable(true),
9832        )
9833        .with_column(
9834            "useconfig",
9835            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
9836        )
9837        .finish(),
9838    column_comments: BTreeMap::new(),
9839    sql: "
9840SELECT
9841    rolname as usename,
9842    ai.oid as usesysid,
9843    rolcreatedb AS usecreatedb,
9844    rolsuper AS usesuper,
9845    rolreplication AS userepl,
9846    rolbypassrls AS usebypassrls,
9847    rolpassword as passwd,
9848    rolvaliduntil as valuntil,
9849    (
9850        SELECT array_agg(parameter_name || '=' || parameter_value)
9851        FROM mz_catalog.mz_role_parameters rp
9852        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
9853        WHERE ai.oid = r.oid
9854    ) AS useconfig
9855FROM pg_catalog.pg_authid ai
9856WHERE rolcanlogin",
9857    access: vec![PUBLIC_SELECT],
9858});
9859
9860pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9861    name: "pg_views",
9862    schema: PG_CATALOG_SCHEMA,
9863    oid: oid::VIEW_PG_VIEWS_OID,
9864    desc: RelationDesc::builder()
9865        .with_column("schemaname", SqlScalarType::String.nullable(true))
9866        .with_column("viewname", SqlScalarType::String.nullable(false))
9867        .with_column("viewowner", SqlScalarType::Oid.nullable(false))
9868        .with_column("definition", SqlScalarType::String.nullable(false))
9869        .finish(),
9870    column_comments: BTreeMap::new(),
9871    sql: "SELECT
9872    s.name AS schemaname,
9873    v.name AS viewname,
9874    role_owner.oid AS viewowner,
9875    v.definition AS definition
9876FROM mz_catalog.mz_views v
9877LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
9878LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9879JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
9880WHERE s.database_id IS NULL OR d.name = current_database()",
9881    access: vec![PUBLIC_SELECT],
9882});
9883
9884pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9885    name: "pg_matviews",
9886    schema: PG_CATALOG_SCHEMA,
9887    oid: oid::VIEW_PG_MATVIEWS_OID,
9888    desc: RelationDesc::builder()
9889        .with_column("schemaname", SqlScalarType::String.nullable(true))
9890        .with_column("matviewname", SqlScalarType::String.nullable(false))
9891        .with_column("matviewowner", SqlScalarType::Oid.nullable(false))
9892        .with_column("definition", SqlScalarType::String.nullable(false))
9893        .finish(),
9894    column_comments: BTreeMap::new(),
9895    sql: "SELECT
9896    s.name AS schemaname,
9897    m.name AS matviewname,
9898    role_owner.oid AS matviewowner,
9899    m.definition AS definition
9900FROM mz_catalog.mz_materialized_views m
9901LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
9902LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9903JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
9904WHERE s.database_id IS NULL OR d.name = current_database()",
9905    access: vec![PUBLIC_SELECT],
9906});
9907
9908pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
9909    LazyLock::new(|| BuiltinView {
9910        name: "applicable_roles",
9911        schema: INFORMATION_SCHEMA,
9912        oid: oid::VIEW_APPLICABLE_ROLES_OID,
9913        desc: RelationDesc::builder()
9914            .with_column("grantee", SqlScalarType::String.nullable(false))
9915            .with_column("role_name", SqlScalarType::String.nullable(false))
9916            .with_column("is_grantable", SqlScalarType::String.nullable(false))
9917            .finish(),
9918        column_comments: BTreeMap::new(),
9919        sql: "
9920SELECT
9921    member.name AS grantee,
9922    role.name AS role_name,
9923    -- ADMIN OPTION isn't implemented.
9924    'NO' AS is_grantable
9925FROM mz_catalog.mz_role_members membership
9926JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
9927JOIN mz_catalog.mz_roles member ON membership.member = member.id
9928WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
9929        access: vec![PUBLIC_SELECT],
9930    });
9931
9932pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9933    name: "columns",
9934    schema: INFORMATION_SCHEMA,
9935    oid: oid::VIEW_COLUMNS_OID,
9936    desc: RelationDesc::builder()
9937        .with_column("table_catalog", SqlScalarType::String.nullable(false))
9938        .with_column("table_schema", SqlScalarType::String.nullable(false))
9939        .with_column("table_name", SqlScalarType::String.nullable(false))
9940        .with_column("column_name", SqlScalarType::String.nullable(false))
9941        .with_column("ordinal_position", SqlScalarType::Int64.nullable(false))
9942        .with_column("column_default", SqlScalarType::String.nullable(true))
9943        .with_column("is_nullable", SqlScalarType::String.nullable(false))
9944        .with_column("data_type", SqlScalarType::String.nullable(false))
9945        .with_column(
9946            "character_maximum_length",
9947            SqlScalarType::Int32.nullable(true),
9948        )
9949        .with_column("numeric_precision", SqlScalarType::Int32.nullable(true))
9950        .with_column("numeric_scale", SqlScalarType::Int32.nullable(true))
9951        .finish(),
9952    column_comments: BTreeMap::new(),
9953    sql: "
9954SELECT
9955    current_database() as table_catalog,
9956    s.name AS table_schema,
9957    o.name AS table_name,
9958    c.name AS column_name,
9959    c.position::int8 AS ordinal_position,
9960    c.default AS column_default,
9961    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
9962    c.type AS data_type,
9963    NULL::pg_catalog.int4 AS character_maximum_length,
9964    NULL::pg_catalog.int4 AS numeric_precision,
9965    NULL::pg_catalog.int4 AS numeric_scale
9966FROM mz_catalog.mz_columns c
9967JOIN mz_catalog.mz_objects o ON o.id = c.id
9968JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
9969LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
9970WHERE s.database_id IS NULL OR d.name = current_database()",
9971    access: vec![PUBLIC_SELECT],
9972});
9973
9974pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
9975    LazyLock::new(|| BuiltinView {
9976        name: "enabled_roles",
9977        schema: INFORMATION_SCHEMA,
9978        oid: oid::VIEW_ENABLED_ROLES_OID,
9979        desc: RelationDesc::builder()
9980            .with_column("role_name", SqlScalarType::String.nullable(false))
9981            .finish(),
9982        column_comments: BTreeMap::new(),
9983        sql: "
9984SELECT name AS role_name
9985FROM mz_catalog.mz_roles
9986WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
9987        access: vec![PUBLIC_SELECT],
9988    });
9989
9990pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
9991    BuiltinView {
9992        name: "role_table_grants",
9993        schema: INFORMATION_SCHEMA,
9994        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
9995        desc: RelationDesc::builder()
9996            .with_column("grantor", SqlScalarType::String.nullable(false))
9997            .with_column("grantee", SqlScalarType::String.nullable(true))
9998            .with_column("table_catalog", SqlScalarType::String.nullable(true))
9999            .with_column("table_schema", SqlScalarType::String.nullable(false))
10000            .with_column("table_name", SqlScalarType::String.nullable(false))
10001            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10002            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10003            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10004            .finish(),
10005        column_comments: BTreeMap::new(),
10006        sql: "
10007SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
10008FROM information_schema.table_privileges
10009WHERE
10010    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
10011    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
10012        access: vec![PUBLIC_SELECT],
10013    }
10014});
10015
10016pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
10017    LazyLock::new(|| BuiltinView {
10018        name: "key_column_usage",
10019        schema: INFORMATION_SCHEMA,
10020        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
10021        desc: RelationDesc::builder()
10022            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10023            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10024            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10025            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10026            .with_column("table_schema", SqlScalarType::String.nullable(false))
10027            .with_column("table_name", SqlScalarType::String.nullable(false))
10028            .with_column("column_name", SqlScalarType::String.nullable(false))
10029            .with_column("ordinal_position", SqlScalarType::Int32.nullable(false))
10030            .with_column(
10031                "position_in_unique_constraint",
10032                SqlScalarType::Int32.nullable(false),
10033            )
10034            .with_key(vec![])
10035            .finish(),
10036        column_comments: BTreeMap::new(),
10037        sql: "SELECT
10038    NULL::text AS constraint_catalog,
10039    NULL::text AS constraint_schema,
10040    NULL::text AS constraint_name,
10041    NULL::text AS table_catalog,
10042    NULL::text AS table_schema,
10043    NULL::text AS table_name,
10044    NULL::text AS column_name,
10045    NULL::integer AS ordinal_position,
10046    NULL::integer AS position_in_unique_constraint
10047WHERE false",
10048        access: vec![PUBLIC_SELECT],
10049    });
10050
10051pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10052    LazyLock::new(|| BuiltinView {
10053        name: "referential_constraints",
10054        schema: INFORMATION_SCHEMA,
10055        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10056        desc: RelationDesc::builder()
10057            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10058            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10059            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10060            .with_column(
10061                "unique_constraint_catalog",
10062                SqlScalarType::String.nullable(false),
10063            )
10064            .with_column(
10065                "unique_constraint_schema",
10066                SqlScalarType::String.nullable(false),
10067            )
10068            .with_column(
10069                "unique_constraint_name",
10070                SqlScalarType::String.nullable(false),
10071            )
10072            .with_column("match_option", SqlScalarType::String.nullable(false))
10073            .with_column("update_rule", SqlScalarType::String.nullable(false))
10074            .with_column("delete_rule", SqlScalarType::String.nullable(false))
10075            .with_key(vec![])
10076            .finish(),
10077        column_comments: BTreeMap::new(),
10078        sql: "SELECT
10079    NULL::text AS constraint_catalog,
10080    NULL::text AS constraint_schema,
10081    NULL::text AS constraint_name,
10082    NULL::text AS unique_constraint_catalog,
10083    NULL::text AS unique_constraint_schema,
10084    NULL::text AS unique_constraint_name,
10085    NULL::text AS match_option,
10086    NULL::text AS update_rule,
10087    NULL::text AS delete_rule
10088WHERE false",
10089        access: vec![PUBLIC_SELECT],
10090    });
10091
10092pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10093    name: "routines",
10094    schema: INFORMATION_SCHEMA,
10095    oid: oid::VIEW_ROUTINES_OID,
10096    desc: RelationDesc::builder()
10097        .with_column("routine_catalog", SqlScalarType::String.nullable(false))
10098        .with_column("routine_schema", SqlScalarType::String.nullable(false))
10099        .with_column("routine_name", SqlScalarType::String.nullable(false))
10100        .with_column("routine_type", SqlScalarType::String.nullable(false))
10101        .with_column("routine_definition", SqlScalarType::String.nullable(true))
10102        .finish(),
10103    column_comments: BTreeMap::new(),
10104    sql: "SELECT
10105    current_database() as routine_catalog,
10106    s.name AS routine_schema,
10107    f.name AS routine_name,
10108    'FUNCTION' AS routine_type,
10109    NULL::text AS routine_definition
10110FROM mz_catalog.mz_functions f
10111JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10112LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10113WHERE s.database_id IS NULL OR d.name = current_database()",
10114    access: vec![PUBLIC_SELECT],
10115});
10116
10117pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10118    name: "schemata",
10119    schema: INFORMATION_SCHEMA,
10120    oid: oid::VIEW_SCHEMATA_OID,
10121    desc: RelationDesc::builder()
10122        .with_column("catalog_name", SqlScalarType::String.nullable(false))
10123        .with_column("schema_name", SqlScalarType::String.nullable(false))
10124        .finish(),
10125    column_comments: BTreeMap::new(),
10126    sql: "
10127SELECT
10128    current_database() as catalog_name,
10129    s.name AS schema_name
10130FROM mz_catalog.mz_schemas s
10131LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10132WHERE s.database_id IS NULL OR d.name = current_database()",
10133    access: vec![PUBLIC_SELECT],
10134});
10135
10136pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10137    name: "tables",
10138    schema: INFORMATION_SCHEMA,
10139    oid: oid::VIEW_TABLES_OID,
10140    desc: RelationDesc::builder()
10141        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10142        .with_column("table_schema", SqlScalarType::String.nullable(false))
10143        .with_column("table_name", SqlScalarType::String.nullable(false))
10144        .with_column("table_type", SqlScalarType::String.nullable(false))
10145        .finish(),
10146    column_comments: BTreeMap::new(),
10147    sql: "SELECT
10148    current_database() as table_catalog,
10149    s.name AS table_schema,
10150    r.name AS table_name,
10151    CASE r.type
10152        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10153        WHEN 'table' THEN 'BASE TABLE'
10154        ELSE pg_catalog.upper(r.type)
10155    END AS table_type
10156FROM mz_catalog.mz_relations r
10157JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10158LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10159WHERE s.database_id IS NULL OR d.name = current_database()",
10160    access: vec![PUBLIC_SELECT],
10161});
10162
10163pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10164    LazyLock::new(|| BuiltinView {
10165        name: "table_constraints",
10166        schema: INFORMATION_SCHEMA,
10167        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10168        desc: RelationDesc::builder()
10169            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10170            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10171            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10172            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10173            .with_column("table_schema", SqlScalarType::String.nullable(false))
10174            .with_column("table_name", SqlScalarType::String.nullable(false))
10175            .with_column("constraint_type", SqlScalarType::String.nullable(false))
10176            .with_column("is_deferrable", SqlScalarType::String.nullable(false))
10177            .with_column("initially_deferred", SqlScalarType::String.nullable(false))
10178            .with_column("enforced", SqlScalarType::String.nullable(false))
10179            .with_column("nulls_distinct", SqlScalarType::String.nullable(false))
10180            .with_key(vec![])
10181            .finish(),
10182        column_comments: BTreeMap::new(),
10183        sql: "SELECT
10184    NULL::text AS constraint_catalog,
10185    NULL::text AS constraint_schema,
10186    NULL::text AS constraint_name,
10187    NULL::text AS table_catalog,
10188    NULL::text AS table_schema,
10189    NULL::text AS table_name,
10190    NULL::text AS constraint_type,
10191    NULL::text AS is_deferrable,
10192    NULL::text AS initially_deferred,
10193    NULL::text AS enforced,
10194    NULL::text AS nulls_distinct
10195WHERE false",
10196        access: vec![PUBLIC_SELECT],
10197    });
10198
10199pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10200    BuiltinView {
10201        name: "table_privileges",
10202        schema: INFORMATION_SCHEMA,
10203        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10204        desc: RelationDesc::builder()
10205            .with_column("grantor", SqlScalarType::String.nullable(false))
10206            .with_column("grantee", SqlScalarType::String.nullable(true))
10207            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10208            .with_column("table_schema", SqlScalarType::String.nullable(false))
10209            .with_column("table_name", SqlScalarType::String.nullable(false))
10210            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10211            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10212            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10213            .finish(),
10214        column_comments: BTreeMap::new(),
10215        sql: "
10216SELECT
10217    grantor,
10218    grantee,
10219    table_catalog,
10220    table_schema,
10221    table_name,
10222    privilege_type,
10223    is_grantable,
10224    CASE privilege_type
10225        WHEN 'SELECT' THEN 'YES'
10226        ELSE 'NO'
10227    END AS with_hierarchy
10228FROM
10229    (SELECT
10230        grantor.name AS grantor,
10231        CASE mz_internal.mz_aclitem_grantee(privileges)
10232            WHEN 'p' THEN 'PUBLIC'
10233            ELSE grantee.name
10234        END AS grantee,
10235        table_catalog,
10236        table_schema,
10237        table_name,
10238        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10239        -- ADMIN OPTION isn't implemented.
10240        'NO' AS is_grantable
10241    FROM
10242        (SELECT
10243            unnest(relations.privileges) AS privileges,
10244            CASE
10245                WHEN schemas.database_id IS NULL THEN current_database()
10246                ELSE databases.name
10247            END AS table_catalog,
10248            schemas.name AS table_schema,
10249            relations.name AS table_name
10250        FROM mz_catalog.mz_relations AS relations
10251        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10252        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10253        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10254    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10255    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10256WHERE
10257    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10258    -- to pg_has_role. Therefore we need to use a CASE statement.
10259    CASE
10260        WHEN grantee = 'PUBLIC' THEN true
10261        ELSE mz_catalog.mz_is_superuser()
10262            OR pg_has_role(current_role, grantee, 'USAGE')
10263            OR pg_has_role(current_role, grantor, 'USAGE')
10264    END",
10265        access: vec![PUBLIC_SELECT],
10266    }
10267});
10268
10269pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10270    name: "triggers",
10271    schema: INFORMATION_SCHEMA,
10272    oid: oid::VIEW_TRIGGERS_OID,
10273    desc: RelationDesc::builder()
10274        .with_column("trigger_catalog", SqlScalarType::String.nullable(false))
10275        .with_column("trigger_schema", SqlScalarType::String.nullable(false))
10276        .with_column("trigger_name", SqlScalarType::String.nullable(false))
10277        .with_column("event_manipulation", SqlScalarType::String.nullable(false))
10278        .with_column(
10279            "event_object_catalog",
10280            SqlScalarType::String.nullable(false),
10281        )
10282        .with_column("event_object_schema", SqlScalarType::String.nullable(false))
10283        .with_column("event_object_table", SqlScalarType::String.nullable(false))
10284        .with_column("action_order", SqlScalarType::Int32.nullable(false))
10285        .with_column("action_condition", SqlScalarType::String.nullable(false))
10286        .with_column("action_statement", SqlScalarType::String.nullable(false))
10287        .with_column("action_orientation", SqlScalarType::String.nullable(false))
10288        .with_column("action_timing", SqlScalarType::String.nullable(false))
10289        .with_column(
10290            "action_reference_old_table",
10291            SqlScalarType::String.nullable(false),
10292        )
10293        .with_column(
10294            "action_reference_new_table",
10295            SqlScalarType::String.nullable(false),
10296        )
10297        .with_key(vec![])
10298        .finish(),
10299    column_comments: BTreeMap::new(),
10300    sql: "SELECT
10301    NULL::text as trigger_catalog,
10302    NULL::text AS trigger_schema,
10303    NULL::text AS trigger_name,
10304    NULL::text AS event_manipulation,
10305    NULL::text AS event_object_catalog,
10306    NULL::text AS event_object_schema,
10307    NULL::text AS event_object_table,
10308    NULL::integer AS action_order,
10309    NULL::text AS action_condition,
10310    NULL::text AS action_statement,
10311    NULL::text AS action_orientation,
10312    NULL::text AS action_timing,
10313    NULL::text AS action_reference_old_table,
10314    NULL::text AS action_reference_new_table
10315WHERE FALSE",
10316    access: vec![PUBLIC_SELECT],
10317});
10318
10319pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10320    name: "views",
10321    schema: INFORMATION_SCHEMA,
10322    oid: oid::VIEW_VIEWS_OID,
10323    desc: RelationDesc::builder()
10324        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10325        .with_column("table_schema", SqlScalarType::String.nullable(false))
10326        .with_column("table_name", SqlScalarType::String.nullable(false))
10327        .with_column("view_definition", SqlScalarType::String.nullable(false))
10328        .finish(),
10329    column_comments: BTreeMap::new(),
10330    sql: "SELECT
10331    current_database() as table_catalog,
10332    s.name AS table_schema,
10333    v.name AS table_name,
10334    v.definition AS view_definition
10335FROM mz_catalog.mz_views v
10336JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10337LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10338WHERE s.database_id IS NULL OR d.name = current_database()",
10339    access: vec![PUBLIC_SELECT],
10340});
10341
10342pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10343    LazyLock::new(|| BuiltinView {
10344        name: "character_sets",
10345        schema: INFORMATION_SCHEMA,
10346        oid: oid::VIEW_CHARACTER_SETS_OID,
10347        desc: RelationDesc::builder()
10348            .with_column(
10349                "character_set_catalog",
10350                SqlScalarType::String.nullable(true),
10351            )
10352            .with_column("character_set_schema", SqlScalarType::String.nullable(true))
10353            .with_column("character_set_name", SqlScalarType::String.nullable(false))
10354            .with_column(
10355                "character_repertoire",
10356                SqlScalarType::String.nullable(false),
10357            )
10358            .with_column("form_of_use", SqlScalarType::String.nullable(false))
10359            .with_column(
10360                "default_collate_catalog",
10361                SqlScalarType::String.nullable(false),
10362            )
10363            .with_column(
10364                "default_collate_schema",
10365                SqlScalarType::String.nullable(false),
10366            )
10367            .with_column(
10368                "default_collate_name",
10369                SqlScalarType::String.nullable(false),
10370            )
10371            .with_key(vec![])
10372            .finish(),
10373        column_comments: BTreeMap::new(),
10374        sql: "SELECT
10375    NULL as character_set_catalog,
10376    NULL as character_set_schema,
10377    'UTF8' as character_set_name,
10378    'UCS' as character_repertoire,
10379    'UTF8' as form_of_use,
10380    current_database() as default_collate_catalog,
10381    'pg_catalog' as default_collate_schema,
10382    'en_US.utf8' as default_collate_name",
10383        access: vec![PUBLIC_SELECT],
10384    });
10385
10386// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10387// codes a collation of 'C' for every database, so we could copy that here.
10388pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10389    name: "pg_collation",
10390    schema: PG_CATALOG_SCHEMA,
10391    oid: oid::VIEW_PG_COLLATION_OID,
10392    desc: RelationDesc::builder()
10393        .with_column("oid", SqlScalarType::Oid.nullable(false))
10394        .with_column("collname", SqlScalarType::String.nullable(false))
10395        .with_column("collnamespace", SqlScalarType::Oid.nullable(false))
10396        .with_column("collowner", SqlScalarType::Oid.nullable(false))
10397        .with_column("collprovider", SqlScalarType::PgLegacyChar.nullable(false))
10398        .with_column("collisdeterministic", SqlScalarType::Bool.nullable(false))
10399        .with_column("collencoding", SqlScalarType::Int32.nullable(false))
10400        .with_column("collcollate", SqlScalarType::String.nullable(false))
10401        .with_column("collctype", SqlScalarType::String.nullable(false))
10402        .with_column("collversion", SqlScalarType::String.nullable(false))
10403        .with_key(vec![])
10404        .finish(),
10405    column_comments: BTreeMap::new(),
10406    sql: "
10407SELECT
10408    NULL::pg_catalog.oid AS oid,
10409    NULL::pg_catalog.text AS collname,
10410    NULL::pg_catalog.oid AS collnamespace,
10411    NULL::pg_catalog.oid AS collowner,
10412    NULL::pg_catalog.\"char\" AS collprovider,
10413    NULL::pg_catalog.bool AS collisdeterministic,
10414    NULL::pg_catalog.int4 AS collencoding,
10415    NULL::pg_catalog.text AS collcollate,
10416    NULL::pg_catalog.text AS collctype,
10417    NULL::pg_catalog.text AS collversion
10418WHERE false",
10419    access: vec![PUBLIC_SELECT],
10420});
10421
10422// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10423pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10424    name: "pg_policy",
10425    schema: PG_CATALOG_SCHEMA,
10426    oid: oid::VIEW_PG_POLICY_OID,
10427    desc: RelationDesc::builder()
10428        .with_column("oid", SqlScalarType::Oid.nullable(false))
10429        .with_column("polname", SqlScalarType::String.nullable(false))
10430        .with_column("polrelid", SqlScalarType::Oid.nullable(false))
10431        .with_column("polcmd", SqlScalarType::PgLegacyChar.nullable(false))
10432        .with_column("polpermissive", SqlScalarType::Bool.nullable(false))
10433        .with_column(
10434            "polroles",
10435            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10436        )
10437        .with_column("polqual", SqlScalarType::String.nullable(false))
10438        .with_column("polwithcheck", SqlScalarType::String.nullable(false))
10439        .with_key(vec![])
10440        .finish(),
10441    column_comments: BTreeMap::new(),
10442    sql: "
10443SELECT
10444    NULL::pg_catalog.oid AS oid,
10445    NULL::pg_catalog.text AS polname,
10446    NULL::pg_catalog.oid AS polrelid,
10447    NULL::pg_catalog.\"char\" AS polcmd,
10448    NULL::pg_catalog.bool AS polpermissive,
10449    NULL::pg_catalog.oid[] AS polroles,
10450    NULL::pg_catalog.text AS polqual,
10451    NULL::pg_catalog.text AS polwithcheck
10452WHERE false",
10453    access: vec![PUBLIC_SELECT],
10454});
10455
10456// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10457pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10458    name: "pg_inherits",
10459    schema: PG_CATALOG_SCHEMA,
10460    oid: oid::VIEW_PG_INHERITS_OID,
10461    desc: RelationDesc::builder()
10462        .with_column("inhrelid", SqlScalarType::Oid.nullable(false))
10463        .with_column("inhparent", SqlScalarType::Oid.nullable(false))
10464        .with_column("inhseqno", SqlScalarType::Int32.nullable(false))
10465        .with_column("inhdetachpending", SqlScalarType::Bool.nullable(false))
10466        .with_key(vec![])
10467        .finish(),
10468    column_comments: BTreeMap::new(),
10469    sql: "
10470SELECT
10471    NULL::pg_catalog.oid AS inhrelid,
10472    NULL::pg_catalog.oid AS inhparent,
10473    NULL::pg_catalog.int4 AS inhseqno,
10474    NULL::pg_catalog.bool AS inhdetachpending
10475WHERE false",
10476    access: vec![PUBLIC_SELECT],
10477});
10478
10479pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10480    name: "pg_locks",
10481    schema: PG_CATALOG_SCHEMA,
10482    oid: oid::VIEW_PG_LOCKS_OID,
10483    desc: RelationDesc::builder()
10484        .with_column("locktype", SqlScalarType::String.nullable(false))
10485        .with_column("database", SqlScalarType::Oid.nullable(false))
10486        .with_column("relation", SqlScalarType::Oid.nullable(false))
10487        .with_column("page", SqlScalarType::Int32.nullable(false))
10488        .with_column("tuple", SqlScalarType::Int16.nullable(false))
10489        .with_column("virtualxid", SqlScalarType::String.nullable(false))
10490        .with_column("transactionid", SqlScalarType::String.nullable(false))
10491        .with_column("classid", SqlScalarType::Oid.nullable(false))
10492        .with_column("objid", SqlScalarType::Oid.nullable(false))
10493        .with_column("objsubid", SqlScalarType::Int16.nullable(false))
10494        .with_column("virtualtransaction", SqlScalarType::String.nullable(false))
10495        .with_column("pid", SqlScalarType::Int32.nullable(false))
10496        .with_column("mode", SqlScalarType::String.nullable(false))
10497        .with_column("granted", SqlScalarType::Bool.nullable(false))
10498        .with_column("fastpath", SqlScalarType::Bool.nullable(false))
10499        .with_column(
10500            "waitstart",
10501            SqlScalarType::TimestampTz { precision: None }.nullable(false),
10502        )
10503        .with_key(vec![])
10504        .finish(),
10505    column_comments: BTreeMap::new(),
10506    sql: "
10507SELECT
10508-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10509    NULL::pg_catalog.text AS locktype,
10510    NULL::pg_catalog.oid AS database,
10511    NULL::pg_catalog.oid AS relation,
10512    NULL::pg_catalog.int4 AS page,
10513    NULL::pg_catalog.int2 AS tuple,
10514    NULL::pg_catalog.text AS virtualxid,
10515    NULL::pg_catalog.text AS transactionid,
10516    NULL::pg_catalog.oid AS classid,
10517    NULL::pg_catalog.oid AS objid,
10518    NULL::pg_catalog.int2 AS objsubid,
10519    NULL::pg_catalog.text AS virtualtransaction,
10520    NULL::pg_catalog.int4 AS pid,
10521    NULL::pg_catalog.text AS mode,
10522    NULL::pg_catalog.bool AS granted,
10523    NULL::pg_catalog.bool AS fastpath,
10524    NULL::pg_catalog.timestamptz AS waitstart
10525WHERE false",
10526    access: vec![PUBLIC_SELECT],
10527});
10528
10529pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10530    name: "pg_authid",
10531    schema: PG_CATALOG_SCHEMA,
10532    oid: oid::VIEW_PG_AUTHID_OID,
10533    desc: RelationDesc::builder()
10534        .with_column("oid", SqlScalarType::Oid.nullable(false))
10535        .with_column("rolname", SqlScalarType::String.nullable(false))
10536        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10537        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10538        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10539        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10540        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10541        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10542        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10543        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10544        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10545        .with_column(
10546            "rolvaliduntil",
10547            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10548        )
10549        .finish(),
10550    column_comments: BTreeMap::new(),
10551    sql: r#"
10552SELECT
10553    r.oid AS oid,
10554    r.name AS rolname,
10555    rolsuper,
10556    inherit AS rolinherit,
10557    mz_catalog.has_system_privilege(r.oid, 'CREATEROLE') AS rolcreaterole,
10558    mz_catalog.has_system_privilege(r.oid, 'CREATEDB') AS rolcreatedb,
10559    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
10560    -- MZ doesn't support replication in the same way Postgres does
10561    false AS rolreplication,
10562    -- MZ doesn't how row level security
10563    false AS rolbypassrls,
10564    -- MZ doesn't have a connection limit
10565    -1 AS rolconnlimit,
10566    a.password_hash AS rolpassword,
10567    NULL::pg_catalog.timestamptz AS rolvaliduntil
10568FROM mz_catalog.mz_roles r
10569LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
10570    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10571});
10572
10573pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10574    name: "pg_aggregate",
10575    schema: PG_CATALOG_SCHEMA,
10576    oid: oid::VIEW_PG_AGGREGATE_OID,
10577    desc: RelationDesc::builder()
10578        .with_column("aggfnoid", SqlScalarType::Oid.nullable(false))
10579        .with_column("aggkind", SqlScalarType::String.nullable(false))
10580        .with_column("aggnumdirectargs", SqlScalarType::Int16.nullable(false))
10581        .with_column("aggtransfn", SqlScalarType::RegProc.nullable(true))
10582        .with_column("aggfinalfn", SqlScalarType::RegProc.nullable(false))
10583        .with_column("aggcombinefn", SqlScalarType::RegProc.nullable(false))
10584        .with_column("aggserialfn", SqlScalarType::RegProc.nullable(false))
10585        .with_column("aggdeserialfn", SqlScalarType::RegProc.nullable(false))
10586        .with_column("aggmtransfn", SqlScalarType::RegProc.nullable(false))
10587        .with_column("aggminvtransfn", SqlScalarType::RegProc.nullable(false))
10588        .with_column("aggmfinalfn", SqlScalarType::RegProc.nullable(false))
10589        .with_column("aggfinalextra", SqlScalarType::Bool.nullable(false))
10590        .with_column("aggmfinalextra", SqlScalarType::Bool.nullable(false))
10591        .with_column("aggfinalmodify", SqlScalarType::PgLegacyChar.nullable(true))
10592        .with_column(
10593            "aggmfinalmodify",
10594            SqlScalarType::PgLegacyChar.nullable(true),
10595        )
10596        .with_column("aggsortop", SqlScalarType::Oid.nullable(false))
10597        .with_column("aggtranstype", SqlScalarType::Oid.nullable(true))
10598        .with_column("aggtransspace", SqlScalarType::Int32.nullable(true))
10599        .with_column("aggmtranstype", SqlScalarType::Oid.nullable(false))
10600        .with_column("aggmtransspace", SqlScalarType::Int32.nullable(true))
10601        .with_column("agginitval", SqlScalarType::String.nullable(true))
10602        .with_column("aggminitval", SqlScalarType::String.nullable(true))
10603        .finish(),
10604    column_comments: BTreeMap::new(),
10605    sql: "SELECT
10606    a.oid as aggfnoid,
10607    -- Currently Materialize only support 'normal' aggregate functions.
10608    a.agg_kind as aggkind,
10609    a.agg_num_direct_args as aggnumdirectargs,
10610    -- Materialize doesn't support these fields.
10611    NULL::pg_catalog.regproc as aggtransfn,
10612    '0'::pg_catalog.regproc as aggfinalfn,
10613    '0'::pg_catalog.regproc as aggcombinefn,
10614    '0'::pg_catalog.regproc as aggserialfn,
10615    '0'::pg_catalog.regproc as aggdeserialfn,
10616    '0'::pg_catalog.regproc as aggmtransfn,
10617    '0'::pg_catalog.regproc as aggminvtransfn,
10618    '0'::pg_catalog.regproc as aggmfinalfn,
10619    false as aggfinalextra,
10620    false as aggmfinalextra,
10621    NULL::pg_catalog.\"char\" AS aggfinalmodify,
10622    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
10623    '0'::pg_catalog.oid as aggsortop,
10624    NULL::pg_catalog.oid as aggtranstype,
10625    NULL::pg_catalog.int4 as aggtransspace,
10626    '0'::pg_catalog.oid as aggmtranstype,
10627    NULL::pg_catalog.int4 as aggmtransspace,
10628    NULL::pg_catalog.text as agginitval,
10629    NULL::pg_catalog.text as aggminitval
10630FROM mz_internal.mz_aggregates a",
10631    access: vec![PUBLIC_SELECT],
10632});
10633
10634pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10635    name: "pg_trigger",
10636    schema: PG_CATALOG_SCHEMA,
10637    oid: oid::VIEW_PG_TRIGGER_OID,
10638    desc: RelationDesc::builder()
10639        .with_column("oid", SqlScalarType::Oid.nullable(false))
10640        .with_column("tgrelid", SqlScalarType::Oid.nullable(false))
10641        .with_column("tgparentid", SqlScalarType::Oid.nullable(false))
10642        .with_column("tgname", SqlScalarType::String.nullable(false))
10643        .with_column("tgfoid", SqlScalarType::Oid.nullable(false))
10644        .with_column("tgtype", SqlScalarType::Int16.nullable(false))
10645        .with_column("tgenabled", SqlScalarType::PgLegacyChar.nullable(false))
10646        .with_column("tgisinternal", SqlScalarType::Bool.nullable(false))
10647        .with_column("tgconstrrelid", SqlScalarType::Oid.nullable(false))
10648        .with_column("tgconstrindid", SqlScalarType::Oid.nullable(false))
10649        .with_column("tgconstraint", SqlScalarType::Oid.nullable(false))
10650        .with_column("tgdeferrable", SqlScalarType::Bool.nullable(false))
10651        .with_column("tginitdeferred", SqlScalarType::Bool.nullable(false))
10652        .with_column("tgnargs", SqlScalarType::Int16.nullable(false))
10653        .with_column("tgattr", SqlScalarType::Int2Vector.nullable(false))
10654        .with_column("tgargs", SqlScalarType::Bytes.nullable(false))
10655        .with_column("tgqual", SqlScalarType::String.nullable(false))
10656        .with_column("tgoldtable", SqlScalarType::String.nullable(false))
10657        .with_column("tgnewtable", SqlScalarType::String.nullable(false))
10658        .with_key(vec![])
10659        .finish(),
10660    column_comments: BTreeMap::new(),
10661    sql: "SELECT
10662    -- MZ doesn't support triggers so all of these fields are NULL.
10663    NULL::pg_catalog.oid AS oid,
10664    NULL::pg_catalog.oid AS tgrelid,
10665    NULL::pg_catalog.oid AS tgparentid,
10666    NULL::pg_catalog.text AS tgname,
10667    NULL::pg_catalog.oid AS tgfoid,
10668    NULL::pg_catalog.int2 AS tgtype,
10669    NULL::pg_catalog.\"char\" AS tgenabled,
10670    NULL::pg_catalog.bool AS tgisinternal,
10671    NULL::pg_catalog.oid AS tgconstrrelid,
10672    NULL::pg_catalog.oid AS tgconstrindid,
10673    NULL::pg_catalog.oid AS tgconstraint,
10674    NULL::pg_catalog.bool AS tgdeferrable,
10675    NULL::pg_catalog.bool AS tginitdeferred,
10676    NULL::pg_catalog.int2 AS tgnargs,
10677    NULL::pg_catalog.int2vector AS tgattr,
10678    NULL::pg_catalog.bytea AS tgargs,
10679    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
10680    -- uses text as a placeholder, so we'll follow their lead here.
10681    NULL::pg_catalog.text AS tgqual,
10682    NULL::pg_catalog.text AS tgoldtable,
10683    NULL::pg_catalog.text AS tgnewtable
10684WHERE false
10685    ",
10686    access: vec![PUBLIC_SELECT],
10687});
10688
10689pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10690    name: "pg_rewrite",
10691    schema: PG_CATALOG_SCHEMA,
10692    oid: oid::VIEW_PG_REWRITE_OID,
10693    desc: RelationDesc::builder()
10694        .with_column("oid", SqlScalarType::Oid.nullable(false))
10695        .with_column("rulename", SqlScalarType::String.nullable(false))
10696        .with_column("ev_class", SqlScalarType::Oid.nullable(false))
10697        .with_column("ev_type", SqlScalarType::PgLegacyChar.nullable(false))
10698        .with_column("ev_enabled", SqlScalarType::PgLegacyChar.nullable(false))
10699        .with_column("is_instead", SqlScalarType::Bool.nullable(false))
10700        .with_column("ev_qual", SqlScalarType::String.nullable(false))
10701        .with_column("ev_action", SqlScalarType::String.nullable(false))
10702        .with_key(vec![])
10703        .finish(),
10704    column_comments: BTreeMap::new(),
10705    sql: "SELECT
10706    -- MZ doesn't support rewrite rules so all of these fields are NULL.
10707    NULL::pg_catalog.oid AS oid,
10708    NULL::pg_catalog.text AS rulename,
10709    NULL::pg_catalog.oid AS ev_class,
10710    NULL::pg_catalog.\"char\" AS ev_type,
10711    NULL::pg_catalog.\"char\" AS ev_enabled,
10712    NULL::pg_catalog.bool AS is_instead,
10713    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
10714    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
10715    NULL::pg_catalog.text AS ev_qual,
10716    NULL::pg_catalog.text AS ev_action
10717WHERE false
10718    ",
10719    access: vec![PUBLIC_SELECT],
10720});
10721
10722pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10723    name: "pg_extension",
10724    schema: PG_CATALOG_SCHEMA,
10725    oid: oid::VIEW_PG_EXTENSION_OID,
10726    desc: RelationDesc::builder()
10727        .with_column("oid", SqlScalarType::Oid.nullable(false))
10728        .with_column("extname", SqlScalarType::String.nullable(false))
10729        .with_column("extowner", SqlScalarType::Oid.nullable(false))
10730        .with_column("extnamespace", SqlScalarType::Oid.nullable(false))
10731        .with_column("extrelocatable", SqlScalarType::Bool.nullable(false))
10732        .with_column("extversion", SqlScalarType::String.nullable(false))
10733        .with_column(
10734            "extconfig",
10735            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10736        )
10737        .with_column(
10738            "extcondition",
10739            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
10740        )
10741        .with_key(vec![])
10742        .finish(),
10743    column_comments: BTreeMap::new(),
10744    sql: "SELECT
10745    -- MZ doesn't support extensions so all of these fields are NULL.
10746    NULL::pg_catalog.oid AS oid,
10747    NULL::pg_catalog.text AS extname,
10748    NULL::pg_catalog.oid AS extowner,
10749    NULL::pg_catalog.oid AS extnamespace,
10750    NULL::pg_catalog.bool AS extrelocatable,
10751    NULL::pg_catalog.text AS extversion,
10752    NULL::pg_catalog.oid[] AS extconfig,
10753    NULL::pg_catalog.text[] AS extcondition
10754WHERE false
10755    ",
10756    access: vec![PUBLIC_SELECT],
10757});
10758
10759pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10760    name: "mz_show_all_objects",
10761    schema: MZ_INTERNAL_SCHEMA,
10762    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
10763    desc: RelationDesc::builder()
10764        .with_column("schema_id", SqlScalarType::String.nullable(false))
10765        .with_column("name", SqlScalarType::String.nullable(false))
10766        .with_column("type", SqlScalarType::String.nullable(false))
10767        .with_column("comment", SqlScalarType::String.nullable(false))
10768        .finish(),
10769    column_comments: BTreeMap::new(),
10770    sql: "WITH comments AS (
10771        SELECT id, object_type, comment
10772        FROM mz_internal.mz_comments
10773        WHERE object_sub_id IS NULL
10774    )
10775    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
10776    FROM mz_catalog.mz_objects AS objs
10777    LEFT JOIN comments ON objs.id = comments.id
10778    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
10779    access: vec![PUBLIC_SELECT],
10780});
10781
10782pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
10783    BuiltinView {
10784    name: "mz_show_clusters",
10785    schema: MZ_INTERNAL_SCHEMA,
10786    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
10787    desc: RelationDesc::builder()
10788        .with_column("name", SqlScalarType::String.nullable(false))
10789        .with_column("replicas", SqlScalarType::String.nullable(true))
10790        .with_column("comment", SqlScalarType::String.nullable(false))
10791        .finish(),
10792    column_comments: BTreeMap::new(),
10793    sql: "
10794    WITH clusters AS (
10795        SELECT
10796            mc.id,
10797            mc.name,
10798            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
10799        FROM mz_catalog.mz_clusters mc
10800        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
10801        ON mc.id = mcr.cluster_id
10802        GROUP BY mc.id, mc.name
10803    ),
10804    comments AS (
10805        SELECT id, comment
10806        FROM mz_internal.mz_comments
10807        WHERE object_type = 'cluster' AND object_sub_id IS NULL
10808    )
10809    SELECT name, replicas, COALESCE(comment, '') as comment
10810    FROM clusters
10811    LEFT JOIN comments ON clusters.id = comments.id",
10812    access: vec![PUBLIC_SELECT],
10813}
10814});
10815
10816pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10817    name: "mz_show_secrets",
10818    schema: MZ_INTERNAL_SCHEMA,
10819    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
10820    desc: RelationDesc::builder()
10821        .with_column("schema_id", SqlScalarType::String.nullable(false))
10822        .with_column("name", SqlScalarType::String.nullable(false))
10823        .with_column("comment", SqlScalarType::String.nullable(false))
10824        .finish(),
10825    column_comments: BTreeMap::new(),
10826    sql: "WITH comments AS (
10827        SELECT id, comment
10828        FROM mz_internal.mz_comments
10829        WHERE object_type = 'secret' AND object_sub_id IS NULL
10830    )
10831    SELECT schema_id, name, COALESCE(comment, '') as comment
10832    FROM mz_catalog.mz_secrets secrets
10833    LEFT JOIN comments ON secrets.id = comments.id",
10834    access: vec![PUBLIC_SELECT],
10835});
10836
10837pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10838    name: "mz_show_columns",
10839    schema: MZ_INTERNAL_SCHEMA,
10840    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
10841    desc: RelationDesc::builder()
10842        .with_column("id", SqlScalarType::String.nullable(false))
10843        .with_column("name", SqlScalarType::String.nullable(false))
10844        .with_column("nullable", SqlScalarType::Bool.nullable(false))
10845        .with_column("type", SqlScalarType::String.nullable(false))
10846        .with_column("position", SqlScalarType::UInt64.nullable(false))
10847        .with_column("comment", SqlScalarType::String.nullable(false))
10848        .finish(),
10849    column_comments: BTreeMap::new(),
10850    sql: "
10851    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
10852    FROM mz_catalog.mz_columns columns
10853    LEFT JOIN mz_internal.mz_comments comments
10854    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
10855    access: vec![PUBLIC_SELECT],
10856});
10857
10858pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10859    name: "mz_show_databases",
10860    schema: MZ_INTERNAL_SCHEMA,
10861    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
10862    desc: RelationDesc::builder()
10863        .with_column("name", SqlScalarType::String.nullable(false))
10864        .with_column("comment", SqlScalarType::String.nullable(false))
10865        .finish(),
10866    column_comments: BTreeMap::new(),
10867    sql: "WITH comments AS (
10868        SELECT id, comment
10869        FROM mz_internal.mz_comments
10870        WHERE object_type = 'database' AND object_sub_id IS NULL
10871    )
10872    SELECT name, COALESCE(comment, '') as comment
10873    FROM mz_catalog.mz_databases databases
10874    LEFT JOIN comments ON databases.id = comments.id",
10875    access: vec![PUBLIC_SELECT],
10876});
10877
10878pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10879    name: "mz_show_schemas",
10880    schema: MZ_INTERNAL_SCHEMA,
10881    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
10882    desc: RelationDesc::builder()
10883        .with_column("database_id", SqlScalarType::String.nullable(true))
10884        .with_column("name", SqlScalarType::String.nullable(false))
10885        .with_column("comment", SqlScalarType::String.nullable(false))
10886        .finish(),
10887    column_comments: BTreeMap::new(),
10888    sql: "WITH comments AS (
10889        SELECT id, comment
10890        FROM mz_internal.mz_comments
10891        WHERE object_type = 'schema' AND object_sub_id IS NULL
10892    )
10893    SELECT database_id, name, COALESCE(comment, '') as comment
10894    FROM mz_catalog.mz_schemas schemas
10895    LEFT JOIN comments ON schemas.id = comments.id",
10896    access: vec![PUBLIC_SELECT],
10897});
10898
10899pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10900    name: "mz_show_roles",
10901    schema: MZ_INTERNAL_SCHEMA,
10902    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
10903    desc: RelationDesc::builder()
10904        .with_column("name", SqlScalarType::String.nullable(false))
10905        .with_column("comment", SqlScalarType::String.nullable(false))
10906        .finish(),
10907    column_comments: BTreeMap::new(),
10908    sql: "WITH comments AS (
10909        SELECT id, comment
10910        FROM mz_internal.mz_comments
10911        WHERE object_type = 'role' AND object_sub_id IS NULL
10912    )
10913    SELECT name, COALESCE(comment, '') as comment
10914    FROM mz_catalog.mz_roles roles
10915    LEFT JOIN comments ON roles.id = comments.id
10916    WHERE roles.id NOT LIKE 's%'
10917      AND roles.id NOT LIKE 'g%'",
10918    access: vec![PUBLIC_SELECT],
10919});
10920
10921pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10922    name: "mz_show_tables",
10923    schema: MZ_INTERNAL_SCHEMA,
10924    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
10925    desc: RelationDesc::builder()
10926        .with_column("schema_id", SqlScalarType::String.nullable(false))
10927        .with_column("name", SqlScalarType::String.nullable(false))
10928        .with_column("comment", SqlScalarType::String.nullable(false))
10929        .with_column("source_id", SqlScalarType::String.nullable(true))
10930        .finish(),
10931    column_comments: BTreeMap::new(),
10932    sql: "WITH comments AS (
10933        SELECT id, comment
10934        FROM mz_internal.mz_comments
10935        WHERE object_type = 'table' AND object_sub_id IS NULL
10936    )
10937    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
10938    FROM mz_catalog.mz_tables tables
10939    LEFT JOIN comments ON tables.id = comments.id",
10940    access: vec![PUBLIC_SELECT],
10941});
10942
10943pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10944    name: "mz_show_views",
10945    schema: MZ_INTERNAL_SCHEMA,
10946    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
10947    desc: RelationDesc::builder()
10948        .with_column("schema_id", SqlScalarType::String.nullable(false))
10949        .with_column("name", SqlScalarType::String.nullable(false))
10950        .with_column("comment", SqlScalarType::String.nullable(false))
10951        .finish(),
10952    column_comments: BTreeMap::new(),
10953    sql: "WITH comments AS (
10954        SELECT id, comment
10955        FROM mz_internal.mz_comments
10956        WHERE object_type = 'view' AND object_sub_id IS NULL
10957    )
10958    SELECT schema_id, name, COALESCE(comment, '') as comment
10959    FROM mz_catalog.mz_views views
10960    LEFT JOIN comments ON views.id = comments.id",
10961    access: vec![PUBLIC_SELECT],
10962});
10963
10964pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10965    name: "mz_show_types",
10966    schema: MZ_INTERNAL_SCHEMA,
10967    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
10968    desc: RelationDesc::builder()
10969        .with_column("schema_id", SqlScalarType::String.nullable(false))
10970        .with_column("name", SqlScalarType::String.nullable(false))
10971        .with_column("comment", SqlScalarType::String.nullable(false))
10972        .finish(),
10973    column_comments: BTreeMap::new(),
10974    sql: "WITH comments AS (
10975        SELECT id, comment
10976        FROM mz_internal.mz_comments
10977        WHERE object_type = 'type' AND object_sub_id IS NULL
10978    )
10979    SELECT schema_id, name, COALESCE(comment, '') as comment
10980    FROM mz_catalog.mz_types types
10981    LEFT JOIN comments ON types.id = comments.id",
10982    access: vec![PUBLIC_SELECT],
10983});
10984
10985pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10986    name: "mz_show_connections",
10987    schema: MZ_INTERNAL_SCHEMA,
10988    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
10989    desc: RelationDesc::builder()
10990        .with_column("schema_id", SqlScalarType::String.nullable(false))
10991        .with_column("name", SqlScalarType::String.nullable(false))
10992        .with_column("type", SqlScalarType::String.nullable(false))
10993        .with_column("comment", SqlScalarType::String.nullable(false))
10994        .finish(),
10995    column_comments: BTreeMap::new(),
10996    sql: "WITH comments AS (
10997        SELECT id, comment
10998        FROM mz_internal.mz_comments
10999        WHERE object_type = 'connection' AND object_sub_id IS NULL
11000    )
11001    SELECT schema_id, name, type, COALESCE(comment, '') as comment
11002    FROM mz_catalog.mz_connections connections
11003    LEFT JOIN comments ON connections.id = comments.id",
11004    access: vec![PUBLIC_SELECT],
11005});
11006
11007pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11008    name: "mz_show_sources",
11009    schema: MZ_INTERNAL_SCHEMA,
11010    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
11011    desc: RelationDesc::builder()
11012        .with_column("id", SqlScalarType::String.nullable(false))
11013        .with_column("name", SqlScalarType::String.nullable(false))
11014        .with_column("type", SqlScalarType::String.nullable(false))
11015        .with_column("cluster", SqlScalarType::String.nullable(true))
11016        .with_column("schema_id", SqlScalarType::String.nullable(false))
11017        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11018        .with_column("comment", SqlScalarType::String.nullable(false))
11019        .finish(),
11020    column_comments: BTreeMap::new(),
11021    sql: "
11022WITH comments AS (
11023    SELECT id, comment
11024    FROM mz_internal.mz_comments
11025    WHERE object_type = 'source' AND object_sub_id IS NULL
11026)
11027SELECT
11028    sources.id,
11029    sources.name,
11030    sources.type,
11031    clusters.name AS cluster,
11032    schema_id,
11033    cluster_id,
11034    COALESCE(comments.comment, '') as comment
11035FROM
11036    mz_catalog.mz_sources AS sources
11037        LEFT JOIN
11038            mz_catalog.mz_clusters AS clusters
11039            ON clusters.id = sources.cluster_id
11040        LEFT JOIN comments ON sources.id = comments.id",
11041    access: vec![PUBLIC_SELECT],
11042});
11043
11044pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11045    name: "mz_show_sinks",
11046    schema: MZ_INTERNAL_SCHEMA,
11047    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11048    desc: RelationDesc::builder()
11049        .with_column("id", SqlScalarType::String.nullable(false))
11050        .with_column("name", SqlScalarType::String.nullable(false))
11051        .with_column("type", SqlScalarType::String.nullable(false))
11052        .with_column("cluster", SqlScalarType::String.nullable(false))
11053        .with_column("schema_id", SqlScalarType::String.nullable(false))
11054        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11055        .with_column("comment", SqlScalarType::String.nullable(false))
11056        .finish(),
11057    column_comments: BTreeMap::new(),
11058    sql: "
11059WITH comments AS (
11060    SELECT id, comment
11061    FROM mz_internal.mz_comments
11062    WHERE object_type = 'sink' AND object_sub_id IS NULL
11063)
11064SELECT
11065    sinks.id,
11066    sinks.name,
11067    sinks.type,
11068    clusters.name AS cluster,
11069    schema_id,
11070    cluster_id,
11071    COALESCE(comments.comment, '') as comment
11072FROM
11073    mz_catalog.mz_sinks AS sinks
11074    JOIN
11075        mz_catalog.mz_clusters AS clusters
11076        ON clusters.id = sinks.cluster_id
11077    LEFT JOIN comments ON sinks.id = comments.id",
11078    access: vec![PUBLIC_SELECT],
11079});
11080
11081pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11082    name: "mz_show_materialized_views",
11083    schema: MZ_INTERNAL_SCHEMA,
11084    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11085    desc: RelationDesc::builder()
11086        .with_column("id", SqlScalarType::String.nullable(false))
11087        .with_column("name", SqlScalarType::String.nullable(false))
11088        .with_column("cluster", SqlScalarType::String.nullable(false))
11089        .with_column("schema_id", SqlScalarType::String.nullable(false))
11090        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11091        .with_column("comment", SqlScalarType::String.nullable(false))
11092        .finish(),
11093    column_comments: BTreeMap::new(),
11094    sql: "
11095WITH comments AS (
11096    SELECT id, comment
11097    FROM mz_internal.mz_comments
11098    WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11099)
11100SELECT
11101    mviews.id as id,
11102    mviews.name,
11103    clusters.name AS cluster,
11104    schema_id,
11105    cluster_id,
11106    COALESCE(comments.comment, '') as comment
11107FROM
11108    mz_catalog.mz_materialized_views AS mviews
11109    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11110    LEFT JOIN comments ON mviews.id = comments.id",
11111    access: vec![PUBLIC_SELECT],
11112});
11113
11114pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11115    name: "mz_show_indexes",
11116    schema: MZ_INTERNAL_SCHEMA,
11117    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11118    desc: RelationDesc::builder()
11119        .with_column("id", SqlScalarType::String.nullable(false))
11120        .with_column("name", SqlScalarType::String.nullable(false))
11121        .with_column("on", SqlScalarType::String.nullable(false))
11122        .with_column("cluster", SqlScalarType::String.nullable(false))
11123        .with_column(
11124            "key",
11125            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11126        )
11127        .with_column("on_id", SqlScalarType::String.nullable(false))
11128        .with_column("schema_id", SqlScalarType::String.nullable(false))
11129        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11130        .with_column("comment", SqlScalarType::String.nullable(false))
11131        .finish(),
11132    column_comments: BTreeMap::new(),
11133    sql: "
11134WITH comments AS (
11135    SELECT id, comment
11136    FROM mz_internal.mz_comments
11137    WHERE object_type = 'index' AND object_sub_id IS NULL
11138)
11139SELECT
11140    idxs.id AS id,
11141    idxs.name AS name,
11142    objs.name AS on,
11143    clusters.name AS cluster,
11144    COALESCE(keys.key, '{}'::_text) AS key,
11145    idxs.on_id AS on_id,
11146    objs.schema_id AS schema_id,
11147    clusters.id AS cluster_id,
11148    COALESCE(comments.comment, '') as comment
11149FROM
11150    mz_catalog.mz_indexes AS idxs
11151    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11152    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11153    LEFT JOIN
11154        (SELECT
11155            idxs.id,
11156            ARRAY_AGG(
11157                CASE
11158                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11159                    ELSE idx_cols.on_expression
11160                END
11161                ORDER BY idx_cols.index_position ASC
11162            ) AS key
11163        FROM
11164            mz_catalog.mz_indexes AS idxs
11165            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11166            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11167                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11168        GROUP BY idxs.id) AS keys
11169    ON idxs.id = keys.id
11170    LEFT JOIN comments ON idxs.id = comments.id",
11171    access: vec![PUBLIC_SELECT],
11172});
11173
11174pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11175    name: "mz_show_cluster_replicas",
11176    schema: MZ_INTERNAL_SCHEMA,
11177    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11178    desc: RelationDesc::builder()
11179        .with_column("cluster", SqlScalarType::String.nullable(false))
11180        .with_column("replica", SqlScalarType::String.nullable(false))
11181        .with_column("replica_id", SqlScalarType::String.nullable(false))
11182        .with_column("size", SqlScalarType::String.nullable(true))
11183        .with_column("ready", SqlScalarType::Bool.nullable(false))
11184        .with_column("comment", SqlScalarType::String.nullable(false))
11185        .finish(),
11186    column_comments: BTreeMap::new(),
11187    sql: r#"SELECT
11188    mz_catalog.mz_clusters.name AS cluster,
11189    mz_catalog.mz_cluster_replicas.name AS replica,
11190    mz_catalog.mz_cluster_replicas.id as replica_id,
11191    mz_catalog.mz_cluster_replicas.size AS size,
11192    coalesce(statuses.ready, FALSE) AS ready,
11193    coalesce(comments.comment, '') as comment
11194FROM
11195    mz_catalog.mz_cluster_replicas
11196        JOIN mz_catalog.mz_clusters
11197            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11198        LEFT JOIN
11199            (
11200                SELECT
11201                    replica_id,
11202                    bool_and(hydrated) AS ready
11203                FROM mz_internal.mz_hydration_statuses
11204                WHERE replica_id is not null
11205                GROUP BY replica_id
11206            ) AS statuses
11207            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11208        LEFT JOIN mz_internal.mz_comments comments
11209            ON mz_catalog.mz_cluster_replicas.id = comments.id
11210WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11211ORDER BY 1, 2"#,
11212    access: vec![PUBLIC_SELECT],
11213});
11214
11215pub static MZ_SHOW_CONTINUAL_TASKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11216    name: "mz_show_continual_tasks",
11217    schema: MZ_INTERNAL_SCHEMA,
11218    oid: oid::VIEW_MZ_SHOW_CONTINUAL_TASKS_OID,
11219    desc: RelationDesc::builder()
11220        .with_column("id", SqlScalarType::String.nullable(false))
11221        .with_column("name", SqlScalarType::String.nullable(false))
11222        .with_column("cluster", SqlScalarType::String.nullable(false))
11223        .with_column("schema_id", SqlScalarType::String.nullable(false))
11224        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11225        .with_column("comment", SqlScalarType::String.nullable(false))
11226        .finish(),
11227    column_comments: BTreeMap::new(),
11228    sql: "
11229WITH comments AS (
11230    SELECT id, comment
11231    FROM mz_internal.mz_comments
11232    WHERE object_type = 'continual-task' AND object_sub_id IS NULL
11233)
11234SELECT
11235    cts.id as id,
11236    cts.name,
11237    clusters.name AS cluster,
11238    schema_id,
11239    cluster_id,
11240    COALESCE(comments.comment, '') as comment
11241FROM
11242    mz_internal.mz_continual_tasks AS cts
11243    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = cts.cluster_id
11244    LEFT JOIN comments ON cts.id = comments.id",
11245    access: vec![PUBLIC_SELECT],
11246});
11247
11248pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11249    name: "mz_show_role_members",
11250    schema: MZ_INTERNAL_SCHEMA,
11251    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11252    desc: RelationDesc::builder()
11253        .with_column("role", SqlScalarType::String.nullable(false))
11254        .with_column("member", SqlScalarType::String.nullable(false))
11255        .with_column("grantor", SqlScalarType::String.nullable(false))
11256        .finish(),
11257    column_comments: BTreeMap::from_iter([
11258        ("role", "The role that `member` is a member of."),
11259        ("member", "The role that is a member of `role`."),
11260        (
11261            "grantor",
11262            "The role that granted membership of `member` to `role`.",
11263        ),
11264    ]),
11265    sql: r#"SELECT
11266    r1.name AS role,
11267    r2.name AS member,
11268    r3.name AS grantor
11269FROM mz_catalog.mz_role_members rm
11270JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11271JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11272JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11273ORDER BY role"#,
11274    access: vec![PUBLIC_SELECT],
11275});
11276
11277pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11278    name: "mz_show_my_role_members",
11279    schema: MZ_INTERNAL_SCHEMA,
11280    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11281    desc: RelationDesc::builder()
11282        .with_column("role", SqlScalarType::String.nullable(false))
11283        .with_column("member", SqlScalarType::String.nullable(false))
11284        .with_column("grantor", SqlScalarType::String.nullable(false))
11285        .finish(),
11286    column_comments: BTreeMap::from_iter([
11287        ("role", "The role that `member` is a member of."),
11288        ("member", "The role that is a member of `role`."),
11289        (
11290            "grantor",
11291            "The role that granted membership of `member` to `role`.",
11292        ),
11293    ]),
11294    sql: r#"SELECT role, member, grantor
11295FROM mz_internal.mz_show_role_members
11296WHERE pg_has_role(member, 'USAGE')"#,
11297    access: vec![PUBLIC_SELECT],
11298});
11299
11300pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11301    name: "mz_show_system_privileges",
11302    schema: MZ_INTERNAL_SCHEMA,
11303    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11304    desc: RelationDesc::builder()
11305        .with_column("grantor", SqlScalarType::String.nullable(true))
11306        .with_column("grantee", SqlScalarType::String.nullable(true))
11307        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11308        .finish(),
11309    column_comments: BTreeMap::from_iter([
11310        ("grantor", "The role that granted the privilege."),
11311        ("grantee", "The role that the privilege was granted to."),
11312        ("privilege_type", "They type of privilege granted."),
11313    ]),
11314    sql: r#"SELECT
11315    grantor.name AS grantor,
11316    CASE privileges.grantee
11317        WHEN 'p' THEN 'PUBLIC'
11318        ELSE grantee.name
11319    END AS grantee,
11320    privileges.privilege_type AS privilege_type
11321FROM
11322    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11323    FROM mz_catalog.mz_system_privileges) AS privileges
11324LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11325LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11326WHERE privileges.grantee NOT LIKE 's%'"#,
11327    access: vec![PUBLIC_SELECT],
11328});
11329
11330pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11331    name: "mz_show_my_system_privileges",
11332    schema: MZ_INTERNAL_SCHEMA,
11333    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11334    desc: RelationDesc::builder()
11335        .with_column("grantor", SqlScalarType::String.nullable(true))
11336        .with_column("grantee", SqlScalarType::String.nullable(true))
11337        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11338        .finish(),
11339    column_comments: BTreeMap::from_iter([
11340        ("grantor", "The role that granted the privilege."),
11341        ("grantee", "The role that the privilege was granted to."),
11342        ("privilege_type", "They type of privilege granted."),
11343    ]),
11344    sql: r#"SELECT grantor, grantee, privilege_type
11345FROM mz_internal.mz_show_system_privileges
11346WHERE
11347    CASE
11348        WHEN grantee = 'PUBLIC' THEN true
11349        ELSE pg_has_role(grantee, 'USAGE')
11350    END"#,
11351    access: vec![PUBLIC_SELECT],
11352});
11353
11354pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11355    name: "mz_show_cluster_privileges",
11356    schema: MZ_INTERNAL_SCHEMA,
11357    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11358    desc: RelationDesc::builder()
11359        .with_column("grantor", SqlScalarType::String.nullable(true))
11360        .with_column("grantee", SqlScalarType::String.nullable(true))
11361        .with_column("name", SqlScalarType::String.nullable(false))
11362        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11363        .finish(),
11364    column_comments: BTreeMap::from_iter([
11365        ("grantor", "The role that granted the privilege."),
11366        ("grantee", "The role that the privilege was granted to."),
11367        ("name", "The name of the cluster."),
11368        ("privilege_type", "They type of privilege granted."),
11369    ]),
11370    sql: r#"SELECT
11371    grantor.name AS grantor,
11372    CASE privileges.grantee
11373        WHEN 'p' THEN 'PUBLIC'
11374        ELSE grantee.name
11375    END AS grantee,
11376    privileges.name AS name,
11377    privileges.privilege_type AS privilege_type
11378FROM
11379    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11380    FROM mz_catalog.mz_clusters
11381    WHERE id NOT LIKE 's%') AS privileges
11382LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11383LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11384WHERE privileges.grantee NOT LIKE 's%'"#,
11385    access: vec![PUBLIC_SELECT],
11386});
11387
11388pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11389    name: "mz_show_my_cluster_privileges",
11390    schema: MZ_INTERNAL_SCHEMA,
11391    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11392    desc: RelationDesc::builder()
11393        .with_column("grantor", SqlScalarType::String.nullable(true))
11394        .with_column("grantee", SqlScalarType::String.nullable(true))
11395        .with_column("name", SqlScalarType::String.nullable(false))
11396        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11397        .finish(),
11398    column_comments: BTreeMap::from_iter([
11399        ("grantor", "The role that granted the privilege."),
11400        ("grantee", "The role that the privilege was granted to."),
11401        ("name", "The name of the cluster."),
11402        ("privilege_type", "They type of privilege granted."),
11403    ]),
11404    sql: r#"SELECT grantor, grantee, name, privilege_type
11405FROM mz_internal.mz_show_cluster_privileges
11406WHERE
11407    CASE
11408        WHEN grantee = 'PUBLIC' THEN true
11409        ELSE pg_has_role(grantee, 'USAGE')
11410    END"#,
11411    access: vec![PUBLIC_SELECT],
11412});
11413
11414pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11415    name: "mz_show_database_privileges",
11416    schema: MZ_INTERNAL_SCHEMA,
11417    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
11418    desc: RelationDesc::builder()
11419        .with_column("grantor", SqlScalarType::String.nullable(true))
11420        .with_column("grantee", SqlScalarType::String.nullable(true))
11421        .with_column("name", SqlScalarType::String.nullable(false))
11422        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11423        .finish(),
11424    column_comments: BTreeMap::from_iter([
11425        ("grantor", "The role that granted the privilege."),
11426        ("grantee", "The role that the privilege was granted to."),
11427        ("name", "The name of the database."),
11428        ("privilege_type", "They type of privilege granted."),
11429    ]),
11430    sql: r#"SELECT
11431    grantor.name AS grantor,
11432    CASE privileges.grantee
11433        WHEN 'p' THEN 'PUBLIC'
11434        ELSE grantee.name
11435    END AS grantee,
11436    privileges.name AS name,
11437    privileges.privilege_type AS privilege_type
11438FROM
11439    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11440    FROM mz_catalog.mz_databases
11441    WHERE id NOT LIKE 's%') AS privileges
11442LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11443LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11444WHERE privileges.grantee NOT LIKE 's%'"#,
11445    access: vec![PUBLIC_SELECT],
11446});
11447
11448pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11449    name: "mz_show_my_database_privileges",
11450    schema: MZ_INTERNAL_SCHEMA,
11451    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
11452    desc: RelationDesc::builder()
11453        .with_column("grantor", SqlScalarType::String.nullable(true))
11454        .with_column("grantee", SqlScalarType::String.nullable(true))
11455        .with_column("name", SqlScalarType::String.nullable(false))
11456        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11457        .finish(),
11458    column_comments: BTreeMap::from_iter([
11459        ("grantor", "The role that granted the privilege."),
11460        ("grantee", "The role that the privilege was granted to."),
11461        ("name", "The name of the cluster."),
11462        ("privilege_type", "They type of privilege granted."),
11463    ]),
11464    sql: r#"SELECT grantor, grantee, name, privilege_type
11465FROM mz_internal.mz_show_database_privileges
11466WHERE
11467    CASE
11468        WHEN grantee = 'PUBLIC' THEN true
11469        ELSE pg_has_role(grantee, 'USAGE')
11470    END"#,
11471    access: vec![PUBLIC_SELECT],
11472});
11473
11474pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11475    name: "mz_show_schema_privileges",
11476    schema: MZ_INTERNAL_SCHEMA,
11477    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
11478    desc: RelationDesc::builder()
11479        .with_column("grantor", SqlScalarType::String.nullable(true))
11480        .with_column("grantee", SqlScalarType::String.nullable(true))
11481        .with_column("database", SqlScalarType::String.nullable(true))
11482        .with_column("name", SqlScalarType::String.nullable(false))
11483        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11484        .finish(),
11485    column_comments: BTreeMap::from_iter([
11486        ("grantor", "The role that granted the privilege."),
11487        ("grantee", "The role that the privilege was granted to."),
11488        (
11489            "database",
11490            "The name of the database containing the schema.",
11491        ),
11492        ("name", "The name of the schema."),
11493        ("privilege_type", "They type of privilege granted."),
11494    ]),
11495    sql: r#"SELECT
11496    grantor.name AS grantor,
11497    CASE privileges.grantee
11498        WHEN 'p' THEN 'PUBLIC'
11499        ELSE grantee.name
11500    END AS grantee,
11501    databases.name AS database,
11502    privileges.name AS name,
11503    privileges.privilege_type AS privilege_type
11504FROM
11505    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
11506    FROM mz_catalog.mz_schemas
11507    WHERE id NOT LIKE 's%') AS privileges
11508LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11509LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11510LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
11511WHERE privileges.grantee NOT LIKE 's%'"#,
11512    access: vec![PUBLIC_SELECT],
11513});
11514
11515pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11516    name: "mz_show_my_schema_privileges",
11517    schema: MZ_INTERNAL_SCHEMA,
11518    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
11519    desc: RelationDesc::builder()
11520        .with_column("grantor", SqlScalarType::String.nullable(true))
11521        .with_column("grantee", SqlScalarType::String.nullable(true))
11522        .with_column("database", SqlScalarType::String.nullable(true))
11523        .with_column("name", SqlScalarType::String.nullable(false))
11524        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11525        .finish(),
11526    column_comments: BTreeMap::from_iter([
11527        ("grantor", "The role that granted the privilege."),
11528        ("grantee", "The role that the privilege was granted to."),
11529        (
11530            "database",
11531            "The name of the database containing the schema.",
11532        ),
11533        ("name", "The name of the schema."),
11534        ("privilege_type", "They type of privilege granted."),
11535    ]),
11536    sql: r#"SELECT grantor, grantee, database, name, privilege_type
11537FROM mz_internal.mz_show_schema_privileges
11538WHERE
11539    CASE
11540        WHEN grantee = 'PUBLIC' THEN true
11541        ELSE pg_has_role(grantee, 'USAGE')
11542    END"#,
11543    access: vec![PUBLIC_SELECT],
11544});
11545
11546pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11547    name: "mz_show_object_privileges",
11548    schema: MZ_INTERNAL_SCHEMA,
11549    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
11550    desc: RelationDesc::builder()
11551        .with_column("grantor", SqlScalarType::String.nullable(true))
11552        .with_column("grantee", SqlScalarType::String.nullable(true))
11553        .with_column("database", SqlScalarType::String.nullable(true))
11554        .with_column("schema", SqlScalarType::String.nullable(true))
11555        .with_column("name", SqlScalarType::String.nullable(false))
11556        .with_column("object_type", SqlScalarType::String.nullable(false))
11557        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11558        .finish(),
11559    column_comments: BTreeMap::from_iter([
11560        ("grantor", "The role that granted the privilege."),
11561        ("grantee", "The role that the privilege was granted to."),
11562        (
11563            "database",
11564            "The name of the database containing the object.",
11565        ),
11566        ("schema", "The name of the schema containing the object."),
11567        ("name", "The name of the object."),
11568        (
11569            "object_type",
11570            "The type of object the privilege is granted on.",
11571        ),
11572        ("privilege_type", "They type of privilege granted."),
11573    ]),
11574    sql: r#"SELECT
11575    grantor.name AS grantor,
11576    CASE privileges.grantee
11577            WHEN 'p' THEN 'PUBLIC'
11578            ELSE grantee.name
11579        END AS grantee,
11580    databases.name AS database,
11581    schemas.name AS schema,
11582    privileges.name AS name,
11583    privileges.type AS object_type,
11584    privileges.privilege_type AS privilege_type
11585FROM
11586    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
11587    FROM mz_catalog.mz_objects
11588    WHERE id NOT LIKE 's%') AS privileges
11589LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11590LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11591LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
11592LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
11593WHERE privileges.grantee NOT LIKE 's%'"#,
11594    access: vec![PUBLIC_SELECT],
11595});
11596
11597pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11598    name: "mz_show_my_object_privileges",
11599    schema: MZ_INTERNAL_SCHEMA,
11600    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
11601    desc: RelationDesc::builder()
11602        .with_column("grantor", SqlScalarType::String.nullable(true))
11603        .with_column("grantee", SqlScalarType::String.nullable(true))
11604        .with_column("database", SqlScalarType::String.nullable(true))
11605        .with_column("schema", SqlScalarType::String.nullable(true))
11606        .with_column("name", SqlScalarType::String.nullable(false))
11607        .with_column("object_type", SqlScalarType::String.nullable(false))
11608        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11609        .finish(),
11610    column_comments: BTreeMap::from_iter([
11611        ("grantor", "The role that granted the privilege."),
11612        ("grantee", "The role that the privilege was granted to."),
11613        (
11614            "database",
11615            "The name of the database containing the object.",
11616        ),
11617        ("schema", "The name of the schema containing the object."),
11618        ("name", "The name of the object."),
11619        (
11620            "object_type",
11621            "The type of object the privilege is granted on.",
11622        ),
11623        ("privilege_type", "They type of privilege granted."),
11624    ]),
11625    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11626FROM mz_internal.mz_show_object_privileges
11627WHERE
11628    CASE
11629        WHEN grantee = 'PUBLIC' THEN true
11630        ELSE pg_has_role(grantee, 'USAGE')
11631    END"#,
11632    access: vec![PUBLIC_SELECT],
11633});
11634
11635pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11636    name: "mz_show_all_privileges",
11637    schema: MZ_INTERNAL_SCHEMA,
11638    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
11639    desc: RelationDesc::builder()
11640        .with_column("grantor", SqlScalarType::String.nullable(true))
11641        .with_column("grantee", SqlScalarType::String.nullable(true))
11642        .with_column("database", SqlScalarType::String.nullable(true))
11643        .with_column("schema", SqlScalarType::String.nullable(true))
11644        .with_column("name", SqlScalarType::String.nullable(true))
11645        .with_column("object_type", SqlScalarType::String.nullable(false))
11646        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11647        .finish(),
11648    column_comments: BTreeMap::from_iter([
11649        ("grantor", "The role that granted the privilege."),
11650        ("grantee", "The role that the privilege was granted to."),
11651        (
11652            "database",
11653            "The name of the database containing the object.",
11654        ),
11655        ("schema", "The name of the schema containing the object."),
11656        ("name", "The name of the privilege target."),
11657        (
11658            "object_type",
11659            "The type of object the privilege is granted on.",
11660        ),
11661        ("privilege_type", "They type of privilege granted."),
11662    ]),
11663    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
11664FROM mz_internal.mz_show_system_privileges
11665UNION ALL
11666SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
11667FROM mz_internal.mz_show_cluster_privileges
11668UNION ALL
11669SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
11670FROM mz_internal.mz_show_database_privileges
11671UNION ALL
11672SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
11673FROM mz_internal.mz_show_schema_privileges
11674UNION ALL
11675SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11676FROM mz_internal.mz_show_object_privileges"#,
11677    access: vec![PUBLIC_SELECT],
11678});
11679
11680pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11681    name: "mz_show_all_my_privileges",
11682    schema: MZ_INTERNAL_SCHEMA,
11683    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
11684    desc: RelationDesc::builder()
11685        .with_column("grantor", SqlScalarType::String.nullable(true))
11686        .with_column("grantee", SqlScalarType::String.nullable(true))
11687        .with_column("database", SqlScalarType::String.nullable(true))
11688        .with_column("schema", SqlScalarType::String.nullable(true))
11689        .with_column("name", SqlScalarType::String.nullable(true))
11690        .with_column("object_type", SqlScalarType::String.nullable(false))
11691        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11692        .finish(),
11693    column_comments: BTreeMap::from_iter([
11694        ("grantor", "The role that granted the privilege."),
11695        ("grantee", "The role that the privilege was granted to."),
11696        (
11697            "database",
11698            "The name of the database containing the object.",
11699        ),
11700        ("schema", "The name of the schema containing the object."),
11701        ("name", "The name of the privilege target."),
11702        (
11703            "object_type",
11704            "The type of object the privilege is granted on.",
11705        ),
11706        ("privilege_type", "They type of privilege granted."),
11707    ]),
11708    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
11709FROM mz_internal.mz_show_all_privileges
11710WHERE
11711    CASE
11712        WHEN grantee = 'PUBLIC' THEN true
11713        ELSE pg_has_role(grantee, 'USAGE')
11714    END"#,
11715    access: vec![PUBLIC_SELECT],
11716});
11717
11718pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11719    name: "mz_show_default_privileges",
11720    schema: MZ_INTERNAL_SCHEMA,
11721    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
11722    desc: RelationDesc::builder()
11723        .with_column("object_owner", SqlScalarType::String.nullable(true))
11724        .with_column("database", SqlScalarType::String.nullable(true))
11725        .with_column("schema", SqlScalarType::String.nullable(true))
11726        .with_column("object_type", SqlScalarType::String.nullable(false))
11727        .with_column("grantee", SqlScalarType::String.nullable(true))
11728        .with_column("privilege_type", SqlScalarType::String.nullable(true))
11729        .finish(),
11730    column_comments: BTreeMap::from_iter([
11731        (
11732            "object_owner",
11733            "Privileges described in this row will be granted on objects created by `object_owner`.",
11734        ),
11735        (
11736            "database",
11737            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11738        ),
11739        (
11740            "schema",
11741            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11742        ),
11743        (
11744            "object_type",
11745            "Privileges described in this row will be granted only on objects of type `object_type`.",
11746        ),
11747        (
11748            "grantee",
11749            "Privileges described in this row will be granted to `grantee`.",
11750        ),
11751        ("privilege_type", "They type of privilege to be granted."),
11752    ]),
11753    sql: r#"SELECT
11754    CASE defaults.role_id
11755        WHEN 'p' THEN 'PUBLIC'
11756        ELSE object_owner.name
11757    END AS object_owner,
11758    databases.name AS database,
11759    schemas.name AS schema,
11760    object_type,
11761    CASE defaults.grantee
11762        WHEN 'p' THEN 'PUBLIC'
11763        ELSE grantee.name
11764    END AS grantee,
11765    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
11766FROM mz_catalog.mz_default_privileges defaults
11767LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
11768LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
11769LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
11770LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
11771WHERE defaults.grantee NOT LIKE 's%'
11772    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
11773    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
11774    access: vec![PUBLIC_SELECT],
11775});
11776
11777pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11778    name: "mz_show_my_default_privileges",
11779    schema: MZ_INTERNAL_SCHEMA,
11780    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
11781    desc: RelationDesc::builder()
11782        .with_column("object_owner", SqlScalarType::String.nullable(true))
11783        .with_column("database", SqlScalarType::String.nullable(true))
11784        .with_column("schema", SqlScalarType::String.nullable(true))
11785        .with_column("object_type", SqlScalarType::String.nullable(false))
11786        .with_column("grantee", SqlScalarType::String.nullable(true))
11787        .with_column("privilege_type", SqlScalarType::String.nullable(true))
11788        .finish(),
11789    column_comments: BTreeMap::from_iter([
11790        (
11791            "object_owner",
11792            "Privileges described in this row will be granted on objects created by `object_owner`.",
11793        ),
11794        (
11795            "database",
11796            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
11797        ),
11798        (
11799            "schema",
11800            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
11801        ),
11802        (
11803            "object_type",
11804            "Privileges described in this row will be granted only on objects of type `object_type`.",
11805        ),
11806        (
11807            "grantee",
11808            "Privileges described in this row will be granted to `grantee`.",
11809        ),
11810        ("privilege_type", "They type of privilege to be granted."),
11811    ]),
11812    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
11813FROM mz_internal.mz_show_default_privileges
11814WHERE
11815    CASE
11816        WHEN grantee = 'PUBLIC' THEN true
11817        ELSE pg_has_role(grantee, 'USAGE')
11818    END"#,
11819    access: vec![PUBLIC_SELECT],
11820});
11821
11822pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11823    name: "mz_show_network_policies",
11824    schema: MZ_INTERNAL_SCHEMA,
11825    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
11826    desc: RelationDesc::builder()
11827        .with_column("name", SqlScalarType::String.nullable(false))
11828        .with_column("rules", SqlScalarType::String.nullable(true))
11829        .with_column("comment", SqlScalarType::String.nullable(false))
11830        .finish(),
11831    column_comments: BTreeMap::new(),
11832    sql: "
11833WITH comments AS (
11834    SELECT id, comment
11835    FROM mz_internal.mz_comments
11836    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
11837)
11838SELECT
11839    policy.name,
11840    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
11841    COALESCE(comment, '') as comment
11842FROM
11843    mz_internal.mz_network_policies as policy
11844LEFT JOIN
11845    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
11846LEFT JOIN
11847    comments ON policy.id = comments.id
11848WHERE
11849    policy.id NOT LIKE 's%'
11850AND
11851    policy.id NOT LIKE 'g%'
11852GROUP BY policy.name, comments.comment;",
11853    access: vec![PUBLIC_SELECT],
11854});
11855
11856pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11857    name: "mz_cluster_replica_history",
11858    schema: MZ_INTERNAL_SCHEMA,
11859    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
11860    desc: RelationDesc::builder()
11861        .with_column("replica_id", SqlScalarType::String.nullable(true))
11862        .with_column("size", SqlScalarType::String.nullable(true))
11863        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11864        .with_column("cluster_name", SqlScalarType::String.nullable(true))
11865        .with_column("replica_name", SqlScalarType::String.nullable(true))
11866        .with_column(
11867            "created_at",
11868            SqlScalarType::TimestampTz { precision: None }.nullable(false),
11869        )
11870        .with_column(
11871            "dropped_at",
11872            SqlScalarType::TimestampTz { precision: None }.nullable(true),
11873        )
11874        .with_column(
11875            "credits_per_hour",
11876            SqlScalarType::Numeric { max_scale: None }.nullable(true),
11877        )
11878        .finish(),
11879    column_comments: BTreeMap::from_iter([
11880        ("replica_id", "The ID of a cluster replica."),
11881        (
11882            "size",
11883            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
11884        ),
11885        (
11886            "cluster_id",
11887            "The ID of the cluster associated with the replica.",
11888        ),
11889        (
11890            "cluster_name",
11891            "The name of the cluster associated with the replica.",
11892        ),
11893        ("replica_name", "The name of the replica."),
11894        ("created_at", "The time at which the replica was created."),
11895        (
11896            "dropped_at",
11897            "The time at which the replica was dropped, or `NULL` if it still exists.",
11898        ),
11899        (
11900            "credits_per_hour",
11901            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
11902        ),
11903    ]),
11904    sql: r#"
11905        WITH
11906            creates AS
11907            (
11908                SELECT
11909                    details ->> 'logical_size' AS size,
11910                    details ->> 'replica_id' AS replica_id,
11911                    details ->> 'replica_name' AS replica_name,
11912                    details ->> 'cluster_name' AS cluster_name,
11913                    details ->> 'cluster_id' AS cluster_id,
11914                    occurred_at
11915                FROM mz_catalog.mz_audit_events
11916                WHERE
11917                    object_type = 'cluster-replica' AND event_type = 'create'
11918                        AND
11919                    details ->> 'replica_id' IS NOT NULL
11920                        AND
11921                    details ->> 'cluster_id' !~~ 's%'
11922            ),
11923            drops AS
11924            (
11925                SELECT details ->> 'replica_id' AS replica_id, occurred_at
11926                FROM mz_catalog.mz_audit_events
11927                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
11928            )
11929        SELECT
11930            creates.replica_id,
11931            creates.size,
11932            creates.cluster_id,
11933            creates.cluster_name,
11934            creates.replica_name,
11935            creates.occurred_at AS created_at,
11936            drops.occurred_at AS dropped_at,
11937            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
11938        FROM
11939            creates
11940                LEFT JOIN drops ON creates.replica_id = drops.replica_id
11941                LEFT JOIN
11942                    mz_catalog.mz_cluster_replica_sizes
11943                    ON mz_cluster_replica_sizes.size = creates.size"#,
11944    access: vec![PUBLIC_SELECT],
11945});
11946
11947pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11948    name: "mz_cluster_replica_name_history",
11949    schema: MZ_INTERNAL_SCHEMA,
11950    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
11951    desc: RelationDesc::builder()
11952        .with_column(
11953            "occurred_at",
11954            SqlScalarType::TimestampTz { precision: None }.nullable(true),
11955        )
11956        .with_column("id", SqlScalarType::String.nullable(true))
11957        .with_column("previous_name", SqlScalarType::String.nullable(true))
11958        .with_column("new_name", SqlScalarType::String.nullable(true))
11959        .finish(),
11960    column_comments: BTreeMap::from_iter([
11961        (
11962            "occurred_at",
11963            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
11964        ),
11965        ("id", "The ID of the cluster replica."),
11966        (
11967            "previous_name",
11968            "The previous name of the cluster replica. `NULL` if there was no previous name.",
11969        ),
11970        ("new_name", "The new name of the cluster replica."),
11971    ]),
11972    sql: r#"WITH user_replica_alter_history AS (
11973  SELECT occurred_at,
11974    audit_events.details->>'replica_id' AS id,
11975    audit_events.details->>'old_name' AS previous_name,
11976    audit_events.details->>'new_name' AS new_name
11977  FROM mz_catalog.mz_audit_events AS audit_events
11978  WHERE object_type = 'cluster-replica'
11979    AND audit_events.event_type = 'alter'
11980    AND audit_events.details->>'replica_id' like 'u%'
11981),
11982user_replica_create_history AS (
11983  SELECT occurred_at,
11984    audit_events.details->>'replica_id' AS id,
11985    NULL AS previous_name,
11986    audit_events.details->>'replica_name' AS new_name
11987  FROM mz_catalog.mz_audit_events AS audit_events
11988  WHERE object_type = 'cluster-replica'
11989    AND audit_events.event_type = 'create'
11990    AND audit_events.details->>'replica_id' like 'u%'
11991),
11992-- Because built in system cluster replicas don't have audit events, we need to manually add them
11993system_replicas AS (
11994  -- We assume that the system cluster replicas were created at the beginning of time
11995  SELECT NULL::timestamptz AS occurred_at,
11996    id,
11997    NULL AS previous_name,
11998    name AS new_name
11999  FROM mz_catalog.mz_cluster_replicas
12000  WHERE id LIKE 's%'
12001)
12002SELECT *
12003FROM user_replica_alter_history
12004UNION ALL
12005SELECT *
12006FROM user_replica_create_history
12007UNION ALL
12008SELECT *
12009FROM system_replicas"#,
12010    access: vec![PUBLIC_SELECT],
12011});
12012
12013pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12014    name: "mz_hydration_statuses",
12015    schema: MZ_INTERNAL_SCHEMA,
12016    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
12017    desc: RelationDesc::builder()
12018        .with_column("object_id", SqlScalarType::String.nullable(false))
12019        .with_column("replica_id", SqlScalarType::String.nullable(true))
12020        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
12021        .finish(),
12022    column_comments: BTreeMap::from_iter([
12023        (
12024            "object_id",
12025            "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`.",
12026        ),
12027        ("replica_id", "The ID of a cluster replica."),
12028        ("hydrated", "Whether the object is hydrated on the replica."),
12029    ]),
12030    sql: r#"WITH
12031-- Joining against the linearizable catalog tables ensures that this view
12032-- always contains the set of installed objects, even when it depends
12033-- on introspection relations that may received delayed updates.
12034--
12035-- Note that this view only includes objects that are maintained by dataflows.
12036-- In particular, some source types (webhook, introspection, ...) are not and
12037-- are therefore omitted.
12038indexes AS (
12039    SELECT
12040        i.id AS object_id,
12041        h.replica_id,
12042        COALESCE(h.hydrated, false) AS hydrated
12043    FROM mz_catalog.mz_indexes i
12044    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12045        ON (h.object_id = i.id)
12046),
12047materialized_views AS (
12048    SELECT
12049        i.id AS object_id,
12050        h.replica_id,
12051        COALESCE(h.hydrated, false) AS hydrated
12052    FROM mz_catalog.mz_materialized_views i
12053    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12054        ON (h.object_id = i.id)
12055),
12056continual_tasks AS (
12057    SELECT
12058        i.id AS object_id,
12059        h.replica_id,
12060        COALESCE(h.hydrated, false) AS hydrated
12061    FROM mz_internal.mz_continual_tasks i
12062    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12063        ON (h.object_id = i.id)
12064),
12065-- Hydration is a dataflow concept and not all sources are maintained by
12066-- dataflows, so we need to find the ones that are. Generally, sources that
12067-- have a cluster ID are maintained by a dataflow running on that cluster.
12068-- Webhook sources are an exception to this rule.
12069sources_with_clusters AS (
12070    SELECT id, cluster_id
12071    FROM mz_catalog.mz_sources
12072    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12073),
12074sources AS (
12075    SELECT
12076        s.id AS object_id,
12077        ss.replica_id AS replica_id,
12078        ss.rehydration_latency IS NOT NULL AS hydrated
12079    FROM sources_with_clusters s
12080    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12081),
12082-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12083-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12084-- There is likely still a possibility of FPs.
12085sinks AS (
12086    SELECT
12087        s.id AS object_id,
12088        r.id AS replica_id,
12089        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12090    FROM mz_catalog.mz_sinks s
12091    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12092    JOIN mz_catalog.mz_cluster_replicas r
12093        ON (r.cluster_id = s.cluster_id)
12094    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12095        ON (f.object_id = s.id AND f.replica_id = r.id)
12096)
12097SELECT * FROM indexes
12098UNION ALL
12099SELECT * FROM materialized_views
12100UNION ALL
12101SELECT * FROM continual_tasks
12102UNION ALL
12103SELECT * FROM sources
12104UNION ALL
12105SELECT * FROM sinks"#,
12106    access: vec![PUBLIC_SELECT],
12107});
12108
12109pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12110    name: "mz_materialization_dependencies",
12111    schema: MZ_INTERNAL_SCHEMA,
12112    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12113    desc: RelationDesc::builder()
12114        .with_column("object_id", SqlScalarType::String.nullable(false))
12115        .with_column("dependency_id", SqlScalarType::String.nullable(false))
12116        .finish(),
12117    column_comments: BTreeMap::from_iter([
12118        (
12119            "object_id",
12120            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12121        ),
12122        (
12123            "dependency_id",
12124            "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`.",
12125        ),
12126    ]),
12127    sql: "
12128SELECT object_id, dependency_id
12129FROM mz_internal.mz_compute_dependencies
12130UNION ALL
12131SELECT s.id, d.referenced_object_id AS dependency_id
12132FROM mz_internal.mz_object_dependencies d
12133JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12134JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12135    access: vec![PUBLIC_SELECT],
12136});
12137
12138pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12139    name: "mz_materialization_lag",
12140    schema: MZ_INTERNAL_SCHEMA,
12141    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12142    desc: RelationDesc::builder()
12143        .with_column("object_id", SqlScalarType::String.nullable(false))
12144        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
12145        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
12146        .with_column(
12147            "slowest_local_input_id",
12148            SqlScalarType::String.nullable(false),
12149        )
12150        .with_column(
12151            "slowest_global_input_id",
12152            SqlScalarType::String.nullable(false),
12153        )
12154        .finish(),
12155    column_comments: BTreeMap::from_iter([
12156        (
12157            "object_id",
12158            "The ID of the materialized view, index, or sink.",
12159        ),
12160        (
12161            "local_lag",
12162            "The amount of time the materialization lags behind its direct inputs.",
12163        ),
12164        (
12165            "global_lag",
12166            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12167        ),
12168        (
12169            "slowest_local_input_id",
12170            "The ID of the slowest direct input.",
12171        ),
12172        (
12173            "slowest_global_input_id",
12174            "The ID of the slowest root input.",
12175        ),
12176    ]),
12177    sql: "
12178WITH MUTUALLY RECURSIVE
12179    -- IDs of objects for which we want to know the lag.
12180    materializations (id text) AS (
12181        SELECT id FROM mz_catalog.mz_indexes
12182        UNION ALL
12183        SELECT id FROM mz_catalog.mz_materialized_views
12184        UNION ALL
12185        SELECT id FROM mz_internal.mz_continual_tasks
12186        UNION ALL
12187        SELECT id FROM mz_catalog.mz_sinks
12188    ),
12189    -- Direct dependencies of materializations.
12190    direct_dependencies (id text, dep_id text) AS (
12191        SELECT m.id, d.dependency_id
12192        FROM materializations m
12193        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12194    ),
12195    -- All transitive dependencies of materializations.
12196    transitive_dependencies (id text, dep_id text) AS (
12197        SELECT id, dep_id FROM direct_dependencies
12198        UNION
12199        SELECT td.id, dd.dep_id
12200        FROM transitive_dependencies td
12201        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12202    ),
12203    -- Root dependencies of materializations (sources and tables).
12204    root_dependencies (id text, dep_id text) AS (
12205        SELECT *
12206        FROM transitive_dependencies td
12207        WHERE NOT EXISTS (
12208            SELECT 1
12209            FROM direct_dependencies dd
12210            WHERE dd.id = td.dep_id
12211        )
12212    ),
12213    -- Write progress times of materializations.
12214    materialization_times (id text, time timestamptz) AS (
12215        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12216        FROM materializations m
12217        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12218    ),
12219    -- Write progress times of direct dependencies of materializations.
12220    input_times (id text, slowest_dep text, time timestamptz) AS (
12221        SELECT DISTINCT ON (d.id)
12222            d.id,
12223            d.dep_id,
12224            to_timestamp(f.write_frontier::text::double / 1000)
12225        FROM direct_dependencies d
12226        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12227        ORDER BY d.id, f.write_frontier ASC
12228    ),
12229    -- Write progress times of root dependencies of materializations.
12230    root_times (id text, slowest_dep text, time timestamptz) AS (
12231        SELECT DISTINCT ON (d.id)
12232            d.id,
12233            d.dep_id,
12234            to_timestamp(f.write_frontier::text::double / 1000)
12235        FROM root_dependencies d
12236        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12237        ORDER BY d.id, f.write_frontier ASC
12238    )
12239SELECT
12240    id AS object_id,
12241    -- Ensure that lag values are always NULL for materializations that have reached the empty
12242    -- frontier, as those have processed all their input data.
12243    -- Also make sure that lag values are never negative, even when input frontiers are before
12244    -- output frontiers (as can happen during hydration).
12245    CASE
12246        WHEN m.time IS NULL THEN INTERVAL '0'
12247        WHEN i.time IS NULL THEN NULL
12248        ELSE greatest(i.time - m.time, INTERVAL '0')
12249    END AS local_lag,
12250    CASE
12251        WHEN m.time IS NULL THEN INTERVAL '0'
12252        WHEN r.time IS NULL THEN NULL
12253        ELSE greatest(r.time - m.time, INTERVAL '0')
12254    END AS global_lag,
12255    i.slowest_dep AS slowest_local_input_id,
12256    r.slowest_dep AS slowest_global_input_id
12257FROM materialization_times m
12258JOIN input_times i USING (id)
12259JOIN root_times r USING (id)",
12260    access: vec![PUBLIC_SELECT],
12261});
12262
12263/**
12264 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12265 * It's specifically for the Console's environment overview page to speed up load times.
12266 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12267 */
12268pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12269    BuiltinView {
12270        name: "mz_console_cluster_utilization_overview",
12271        schema: MZ_INTERNAL_SCHEMA,
12272        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12273        desc: RelationDesc::builder()
12274            .with_column(
12275                "bucket_start",
12276                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12277            )
12278            .with_column("replica_id", SqlScalarType::String.nullable(false))
12279            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
12280            .with_column(
12281                "max_memory_at",
12282                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12283            )
12284            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
12285            .with_column(
12286                "max_disk_at",
12287                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12288            )
12289            .with_column(
12290                "memory_and_disk_percent",
12291                SqlScalarType::Float64.nullable(true),
12292            )
12293            .with_column(
12294                "max_memory_and_disk_memory_percent",
12295                SqlScalarType::Float64.nullable(true),
12296            )
12297            .with_column(
12298                "max_memory_and_disk_disk_percent",
12299                SqlScalarType::Float64.nullable(true),
12300            )
12301            .with_column(
12302                "max_memory_and_disk_at",
12303                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12304            )
12305            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
12306            .with_column(
12307                "max_heap_at",
12308                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12309            )
12310            .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
12311            .with_column(
12312                "max_cpu_at",
12313                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12314            )
12315            .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
12316            .with_column(
12317                "bucket_end",
12318                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12319            )
12320            .with_column("name", SqlScalarType::String.nullable(true))
12321            .with_column("cluster_id", SqlScalarType::String.nullable(true))
12322            .with_column("size", SqlScalarType::String.nullable(true))
12323            .finish(),
12324        column_comments: BTreeMap::new(),
12325        sql: r#"WITH replica_history AS (
12326  SELECT replica_id,
12327    size,
12328    cluster_id
12329  FROM mz_internal.mz_cluster_replica_history
12330  UNION
12331  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12332  SELECT id AS replica_id,
12333    size,
12334    cluster_id
12335  FROM mz_catalog.mz_cluster_replicas
12336),
12337replica_metrics_history AS (
12338  SELECT
12339    m.occurred_at,
12340    m.replica_id,
12341    r.size,
12342    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0)) / s.processes AS cpu_percent,
12343    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0)) / s.processes AS memory_percent,
12344    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0)) / s.processes AS disk_percent,
12345    (SUM(m.heap_bytes::float8) / NULLIF(m.heap_limit, 0)) / s.processes AS heap_percent,
12346    SUM(m.disk_bytes::float8) AS disk_bytes,
12347    SUM(m.memory_bytes::float8) AS memory_bytes,
12348    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12349    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12350  FROM
12351    replica_history AS r
12352    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12353    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12354  GROUP BY
12355    m.occurred_at,
12356    m.replica_id,
12357    r.size,
12358    s.cpu_nano_cores,
12359    s.memory_bytes,
12360    s.disk_bytes,
12361    m.heap_limit,
12362    s.processes
12363),
12364replica_utilization_history_binned AS (
12365  SELECT m.occurred_at,
12366    m.replica_id,
12367    m.cpu_percent,
12368    m.memory_percent,
12369    m.memory_bytes,
12370    m.disk_percent,
12371    m.disk_bytes,
12372    m.heap_percent,
12373    m.total_disk_bytes,
12374    m.total_memory_bytes,
12375    m.size,
12376    date_bin(
12377      '8 HOURS',
12378      occurred_at,
12379      '1970-01-01'::timestamp
12380    ) AS bucket_start
12381  FROM replica_history AS r
12382    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12383  WHERE mz_now() <= date_bin(
12384      '8 HOURS',
12385      occurred_at,
12386      '1970-01-01'::timestamp
12387    ) + INTERVAL '14 DAYS'
12388),
12389-- For each (replica, bucket), take the (replica, bucket) with the highest memory
12390max_memory AS (
12391  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12392    replica_id,
12393    memory_percent,
12394    occurred_at
12395  FROM replica_utilization_history_binned
12396  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12397  ORDER BY bucket_start,
12398    replica_id,
12399    COALESCE(memory_bytes, 0) DESC
12400),
12401max_disk AS (
12402  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12403    replica_id,
12404    disk_percent,
12405    occurred_at
12406  FROM replica_utilization_history_binned
12407  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12408  ORDER BY bucket_start,
12409    replica_id,
12410    COALESCE(disk_bytes, 0) DESC
12411),
12412max_cpu AS (
12413  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12414    replica_id,
12415    cpu_percent,
12416    occurred_at
12417  FROM replica_utilization_history_binned
12418  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12419  ORDER BY bucket_start,
12420    replica_id,
12421    COALESCE(cpu_percent, 0) DESC
12422),
12423/*
12424 This is different
12425 from adding max_memory
12426 and max_disk per bucket because both
12427 values may not occur at the same time if the bucket interval is large.
12428 */
12429max_memory_and_disk AS (
12430  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
12431    replica_id,
12432    memory_percent,
12433    disk_percent,
12434    memory_and_disk_percent,
12435    occurred_at
12436  FROM (
12437      SELECT *,
12438        CASE
12439          WHEN disk_bytes IS NULL
12440          AND memory_bytes IS NULL THEN NULL
12441          ELSE (COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0))
12442               / (total_disk_bytes::numeric + total_memory_bytes::numeric)
12443        END AS memory_and_disk_percent
12444      FROM replica_utilization_history_binned
12445    ) AS max_memory_and_disk_inner
12446  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12447  ORDER BY bucket_start,
12448    replica_id,
12449    COALESCE(memory_and_disk_percent, 0) DESC
12450),
12451max_heap AS (
12452  SELECT DISTINCT ON (bucket_start, replica_id)
12453    bucket_start,
12454    replica_id,
12455    heap_percent,
12456    occurred_at
12457  FROM replica_utilization_history_binned
12458  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
12459  ORDER BY bucket_start, replica_id, COALESCE(heap_percent, 0) DESC
12460),
12461-- For each (replica, bucket), get its offline events at that time
12462replica_offline_event_history AS (
12463  SELECT date_bin(
12464      '8 HOURS',
12465      occurred_at,
12466      '1970-01-01'::timestamp
12467    ) AS bucket_start,
12468    replica_id,
12469    jsonb_agg(
12470      jsonb_build_object(
12471        'replicaId',
12472        rsh.replica_id,
12473        'occurredAt',
12474        rsh.occurred_at,
12475        'status',
12476        rsh.status,
12477        'reason',
12478        rsh.reason
12479      )
12480    ) AS offline_events
12481  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
12482  WHERE process_id = '0'
12483    AND status = 'offline'
12484    AND mz_now() <= date_bin(
12485      '8 HOURS',
12486      occurred_at,
12487      '1970-01-01'::timestamp
12488    ) + INTERVAL '14 DAYS'
12489  GROUP BY bucket_start,
12490    replica_id
12491)
12492SELECT
12493  bucket_start,
12494  replica_id,
12495  max_memory.memory_percent,
12496  max_memory.occurred_at as max_memory_at,
12497  max_disk.disk_percent,
12498  max_disk.occurred_at as max_disk_at,
12499  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
12500  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
12501  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
12502  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
12503  max_heap.heap_percent,
12504  max_heap.occurred_at as max_heap_at,
12505  max_cpu.cpu_percent as max_cpu_percent,
12506  max_cpu.occurred_at as max_cpu_at,
12507  replica_offline_event_history.offline_events,
12508  bucket_start + INTERVAL '8 HOURS' as bucket_end,
12509  replica_name_history.new_name AS name,
12510  replica_history.cluster_id,
12511  replica_history.size
12512FROM max_memory
12513JOIN max_disk USING (bucket_start, replica_id)
12514JOIN max_cpu USING (bucket_start, replica_id)
12515JOIN max_memory_and_disk USING (bucket_start, replica_id)
12516JOIN max_heap USING (bucket_start, replica_id)
12517JOIN replica_history USING (replica_id)
12518CROSS JOIN LATERAL (
12519  SELECT new_name
12520  FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
12521  WHERE replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
12522    AND bucket_start + INTERVAL '8 HOURS' >= COALESCE(
12523      replica_name_history.occurred_at,
12524      '1970-01-01'::timestamp
12525    )
12526  ORDER BY replica_name_history.occurred_at DESC
12527  LIMIT '1'
12528) AS replica_name_history
12529LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
12530        access: vec![PUBLIC_SELECT],
12531    }
12532});
12533
12534/**
12535 * Traces the blue/green deployment lineage in the audit log to determine all cluster
12536 * IDs that are logically the same cluster.
12537 * cluster_id: The ID of a cluster.
12538 * current_deployment_cluster_id: The cluster ID of the last cluster in
12539 *   cluster_id's blue/green lineage.
12540 * cluster_name: The name of the cluster.
12541 * The approach taken is as follows. First, find all extant clusters and add them
12542 * to the result set. Per cluster, we do the following:
12543 * 1. Find the most recent create or rename event. This moment represents when the
12544 *    cluster took on its final logical identity.
12545 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
12546 *    appended) that was dropped within one minute of that moment. That cluster is
12547 *    almost certainly the logical predecessor of the current cluster. Add the cluster
12548 *    to the result set.
12549 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
12550 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
12551 * but one that's likely to be pretty good one. If a name is reused after more
12552 * than one minute, that's a good sign that it wasn't an automatic blue/green
12553 * process, but someone turning on a new use case that happens to have the same
12554 * name as a previous but logically distinct use case.
12555 */
12556pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12557    name: "mz_cluster_deployment_lineage",
12558    schema: MZ_INTERNAL_SCHEMA,
12559    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
12560    desc: RelationDesc::builder()
12561        .with_column("cluster_id", SqlScalarType::String.nullable(true))
12562        .with_column(
12563            "current_deployment_cluster_id",
12564            SqlScalarType::String.nullable(false),
12565        )
12566        .with_column("cluster_name", SqlScalarType::String.nullable(false))
12567        .with_key(vec![0, 1, 2])
12568        .finish(),
12569    column_comments: BTreeMap::from_iter([
12570        (
12571            "cluster_id",
12572            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
12573        ),
12574        (
12575            "current_deployment_cluster_id",
12576            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
12577        ),
12578        ("cluster_name", "The name of the cluster"),
12579    ]),
12580    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
12581  cluster_id text,
12582  cluster_name text,
12583  event_type text,
12584  occurred_at timestamptz
12585) AS (
12586  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
12587    coalesce(details->>'name', details->>'new_name') AS cluster_name,
12588    event_type,
12589    occurred_at
12590  FROM mz_audit_events
12591  WHERE (
12592      event_type IN ('create', 'drop')
12593      OR (
12594        event_type = 'alter'
12595        AND details ? 'new_name'
12596      )
12597    )
12598    AND object_type = 'cluster'
12599    AND mz_now() < occurred_at + INTERVAL '30 days'
12600),
12601mz_cluster_deployment_lineage (
12602  cluster_id text,
12603  current_deployment_cluster_id text,
12604  cluster_name text
12605) AS (
12606  SELECT c.id,
12607    c.id,
12608    c.name
12609  FROM mz_clusters c
12610  WHERE c.id LIKE 'u%'
12611  UNION
12612  SELECT *
12613  FROM dropped_clusters
12614),
12615-- Closest create or rename event based on the current clusters in the result set
12616most_recent_create_or_rename (
12617  cluster_id text,
12618  current_deployment_cluster_id text,
12619  cluster_name text,
12620  occurred_at timestamptz
12621) AS (
12622  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
12623    c.current_deployment_cluster_id,
12624    e.cluster_name,
12625    e.occurred_at
12626  FROM mz_cluster_deployment_lineage c
12627    JOIN cluster_events e ON c.cluster_id = e.cluster_id
12628    AND c.cluster_name = e.cluster_name
12629  WHERE e.event_type <> 'drop'
12630  ORDER BY e.cluster_id,
12631    e.occurred_at DESC
12632),
12633-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
12634dropped_clusters (
12635  cluster_id text,
12636  current_deployment_cluster_id text,
12637  cluster_name text
12638) AS (
12639  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
12640    cr.current_deployment_cluster_id,
12641    cr.cluster_name
12642  FROM most_recent_create_or_rename cr
12643    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
12644    AND cr.occurred_at + interval '1 minute'
12645    AND (
12646      e.cluster_name = cr.cluster_name
12647      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
12648    )
12649  WHERE e.event_type = 'drop'
12650  ORDER BY cr.cluster_id,
12651    abs(
12652      extract(
12653        epoch
12654        FROM cr.occurred_at - e.occurred_at
12655      )
12656    )
12657)
12658SELECT *
12659FROM mz_cluster_deployment_lineage"#,
12660    access: vec![PUBLIC_SELECT],
12661});
12662
12663pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12664    name: "mz_show_databases_ind",
12665    schema: MZ_INTERNAL_SCHEMA,
12666    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
12667    sql: "IN CLUSTER mz_catalog_server
12668ON mz_internal.mz_show_databases (name)",
12669    is_retained_metrics_object: false,
12670};
12671
12672pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12673    name: "mz_show_schemas_ind",
12674    schema: MZ_INTERNAL_SCHEMA,
12675    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
12676    sql: "IN CLUSTER mz_catalog_server
12677ON mz_internal.mz_show_schemas (database_id)",
12678    is_retained_metrics_object: false,
12679};
12680
12681pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12682    name: "mz_show_connections_ind",
12683    schema: MZ_INTERNAL_SCHEMA,
12684    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
12685    sql: "IN CLUSTER mz_catalog_server
12686ON mz_internal.mz_show_connections (schema_id)",
12687    is_retained_metrics_object: false,
12688};
12689
12690pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
12691    name: "mz_show_tables_ind",
12692    schema: MZ_INTERNAL_SCHEMA,
12693    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
12694    sql: "IN CLUSTER mz_catalog_server
12695ON mz_internal.mz_show_tables (schema_id)",
12696    is_retained_metrics_object: false,
12697};
12698
12699pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12700    name: "mz_show_sources_ind",
12701    schema: MZ_INTERNAL_SCHEMA,
12702    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
12703    sql: "IN CLUSTER mz_catalog_server
12704ON mz_internal.mz_show_sources (schema_id)",
12705    is_retained_metrics_object: false,
12706};
12707
12708pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12709    name: "mz_show_views_ind",
12710    schema: MZ_INTERNAL_SCHEMA,
12711    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
12712    sql: "IN CLUSTER mz_catalog_server
12713ON mz_internal.mz_show_views (schema_id)",
12714    is_retained_metrics_object: false,
12715};
12716
12717pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12718    name: "mz_show_materialized_views_ind",
12719    schema: MZ_INTERNAL_SCHEMA,
12720    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
12721    sql: "IN CLUSTER mz_catalog_server
12722ON mz_internal.mz_show_materialized_views (schema_id)",
12723    is_retained_metrics_object: false,
12724};
12725
12726pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
12727    name: "mz_show_sinks_ind",
12728    schema: MZ_INTERNAL_SCHEMA,
12729    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
12730    sql: "IN CLUSTER mz_catalog_server
12731ON mz_internal.mz_show_sinks (schema_id)",
12732    is_retained_metrics_object: false,
12733};
12734
12735pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
12736    name: "mz_show_types_ind",
12737    schema: MZ_INTERNAL_SCHEMA,
12738    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
12739    sql: "IN CLUSTER mz_catalog_server
12740ON mz_internal.mz_show_types (schema_id)",
12741    is_retained_metrics_object: false,
12742};
12743
12744pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
12745    name: "mz_show_roles_ind",
12746    schema: MZ_INTERNAL_SCHEMA,
12747    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
12748    sql: "IN CLUSTER mz_catalog_server
12749ON mz_internal.mz_show_roles (name)",
12750    is_retained_metrics_object: false,
12751};
12752
12753pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12754    name: "mz_show_all_objects_ind",
12755    schema: MZ_INTERNAL_SCHEMA,
12756    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
12757    sql: "IN CLUSTER mz_catalog_server
12758ON mz_internal.mz_show_all_objects (schema_id)",
12759    is_retained_metrics_object: false,
12760};
12761
12762pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12763    name: "mz_show_indexes_ind",
12764    schema: MZ_INTERNAL_SCHEMA,
12765    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
12766    sql: "IN CLUSTER mz_catalog_server
12767ON mz_internal.mz_show_indexes (schema_id)",
12768    is_retained_metrics_object: false,
12769};
12770
12771pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12772    name: "mz_show_columns_ind",
12773    schema: MZ_INTERNAL_SCHEMA,
12774    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
12775    sql: "IN CLUSTER mz_catalog_server
12776ON mz_internal.mz_show_columns (id)",
12777    is_retained_metrics_object: false,
12778};
12779
12780pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12781    name: "mz_show_clusters_ind",
12782    schema: MZ_INTERNAL_SCHEMA,
12783    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
12784    sql: "IN CLUSTER mz_catalog_server
12785ON mz_internal.mz_show_clusters (name)",
12786    is_retained_metrics_object: false,
12787};
12788
12789pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
12790    name: "mz_show_cluster_replicas_ind",
12791    schema: MZ_INTERNAL_SCHEMA,
12792    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
12793    sql: "IN CLUSTER mz_catalog_server
12794ON mz_internal.mz_show_cluster_replicas (cluster)",
12795    is_retained_metrics_object: false,
12796};
12797
12798pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12799    name: "mz_show_secrets_ind",
12800    schema: MZ_INTERNAL_SCHEMA,
12801    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
12802    sql: "IN CLUSTER mz_catalog_server
12803ON mz_internal.mz_show_secrets (schema_id)",
12804    is_retained_metrics_object: false,
12805};
12806
12807pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
12808    name: "mz_databases_ind",
12809    schema: MZ_CATALOG_SCHEMA,
12810    oid: oid::INDEX_MZ_DATABASES_IND_OID,
12811    sql: "IN CLUSTER mz_catalog_server
12812ON mz_catalog.mz_databases (name)",
12813    is_retained_metrics_object: false,
12814};
12815
12816pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
12817    name: "mz_schemas_ind",
12818    schema: MZ_CATALOG_SCHEMA,
12819    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
12820    sql: "IN CLUSTER mz_catalog_server
12821ON mz_catalog.mz_schemas (database_id)",
12822    is_retained_metrics_object: false,
12823};
12824
12825pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
12826    name: "mz_connections_ind",
12827    schema: MZ_CATALOG_SCHEMA,
12828    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
12829    sql: "IN CLUSTER mz_catalog_server
12830ON mz_catalog.mz_connections (schema_id)",
12831    is_retained_metrics_object: false,
12832};
12833
12834pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
12835    name: "mz_tables_ind",
12836    schema: MZ_CATALOG_SCHEMA,
12837    oid: oid::INDEX_MZ_TABLES_IND_OID,
12838    sql: "IN CLUSTER mz_catalog_server
12839ON mz_catalog.mz_tables (schema_id)",
12840    is_retained_metrics_object: false,
12841};
12842
12843pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
12844    name: "mz_types_ind",
12845    schema: MZ_CATALOG_SCHEMA,
12846    oid: oid::INDEX_MZ_TYPES_IND_OID,
12847    sql: "IN CLUSTER mz_catalog_server
12848ON mz_catalog.mz_types (schema_id)",
12849    is_retained_metrics_object: false,
12850};
12851
12852pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
12853    name: "mz_objects_ind",
12854    schema: MZ_CATALOG_SCHEMA,
12855    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
12856    sql: "IN CLUSTER mz_catalog_server
12857ON mz_catalog.mz_objects (schema_id)",
12858    is_retained_metrics_object: false,
12859};
12860
12861pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
12862    name: "mz_columns_ind",
12863    schema: MZ_CATALOG_SCHEMA,
12864    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
12865    sql: "IN CLUSTER mz_catalog_server
12866ON mz_catalog.mz_columns (name)",
12867    is_retained_metrics_object: false,
12868};
12869
12870pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
12871    name: "mz_secrets_ind",
12872    schema: MZ_CATALOG_SCHEMA,
12873    oid: oid::INDEX_MZ_SECRETS_IND_OID,
12874    sql: "IN CLUSTER mz_catalog_server
12875ON mz_catalog.mz_secrets (name)",
12876    is_retained_metrics_object: false,
12877};
12878
12879pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12880    name: "mz_views_ind",
12881    schema: MZ_CATALOG_SCHEMA,
12882    oid: oid::INDEX_MZ_VIEWS_IND_OID,
12883    sql: "IN CLUSTER mz_catalog_server
12884ON mz_catalog.mz_views (schema_id)",
12885    is_retained_metrics_object: false,
12886};
12887
12888pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
12889    name: "mz_console_cluster_utilization_overview_ind",
12890    schema: MZ_INTERNAL_SCHEMA,
12891    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
12892    sql: "IN CLUSTER mz_catalog_server
12893ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
12894    is_retained_metrics_object: false,
12895};
12896
12897pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
12898    name: "mz_cluster_deployment_lineage_ind",
12899    schema: MZ_INTERNAL_SCHEMA,
12900    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
12901    sql: "IN CLUSTER mz_catalog_server
12902ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
12903    is_retained_metrics_object: false,
12904};
12905
12906pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
12907    name: "mz_clusters_ind",
12908    schema: MZ_CATALOG_SCHEMA,
12909    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
12910    sql: "IN CLUSTER mz_catalog_server
12911ON mz_catalog.mz_clusters (id)",
12912    is_retained_metrics_object: false,
12913};
12914
12915pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
12916    name: "mz_indexes_ind",
12917    schema: MZ_CATALOG_SCHEMA,
12918    oid: oid::INDEX_MZ_INDEXES_IND_OID,
12919    sql: "IN CLUSTER mz_catalog_server
12920ON mz_catalog.mz_indexes (id)",
12921    is_retained_metrics_object: false,
12922};
12923
12924pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
12925    name: "mz_roles_ind",
12926    schema: MZ_CATALOG_SCHEMA,
12927    oid: oid::INDEX_MZ_ROLES_IND_OID,
12928    sql: "IN CLUSTER mz_catalog_server
12929ON mz_catalog.mz_roles (id)",
12930    is_retained_metrics_object: false,
12931};
12932
12933pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
12934    name: "mz_sources_ind",
12935    schema: MZ_CATALOG_SCHEMA,
12936    oid: oid::INDEX_MZ_SOURCES_IND_OID,
12937    sql: "IN CLUSTER mz_catalog_server
12938ON mz_catalog.mz_sources (id)",
12939    is_retained_metrics_object: true,
12940};
12941
12942pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
12943    name: "mz_sinks_ind",
12944    schema: MZ_CATALOG_SCHEMA,
12945    oid: oid::INDEX_MZ_SINKS_IND_OID,
12946    sql: "IN CLUSTER mz_catalog_server
12947ON mz_catalog.mz_sinks (id)",
12948    is_retained_metrics_object: true,
12949};
12950
12951pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
12952    name: "mz_materialized_views_ind",
12953    schema: MZ_CATALOG_SCHEMA,
12954    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
12955    sql: "IN CLUSTER mz_catalog_server
12956ON mz_catalog.mz_materialized_views (id)",
12957    is_retained_metrics_object: false,
12958};
12959
12960pub const MZ_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
12961    name: "mz_continual_tasks_ind",
12962    schema: MZ_INTERNAL_SCHEMA,
12963    oid: oid::INDEX_MZ_CONTINUAL_TASKS_IND_OID,
12964    sql: "IN CLUSTER mz_catalog_server
12965ON mz_internal.mz_continual_tasks (id)",
12966    is_retained_metrics_object: false,
12967};
12968
12969pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12970    name: "mz_source_statuses_ind",
12971    schema: MZ_INTERNAL_SCHEMA,
12972    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
12973    sql: "IN CLUSTER mz_catalog_server
12974ON mz_internal.mz_source_statuses (id)",
12975    is_retained_metrics_object: false,
12976};
12977
12978pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12979    name: "mz_sink_statuses_ind",
12980    schema: MZ_INTERNAL_SCHEMA,
12981    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
12982    sql: "IN CLUSTER mz_catalog_server
12983ON mz_internal.mz_sink_statuses (id)",
12984    is_retained_metrics_object: false,
12985};
12986
12987pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
12988    name: "mz_source_status_history_ind",
12989    schema: MZ_INTERNAL_SCHEMA,
12990    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
12991    sql: "IN CLUSTER mz_catalog_server
12992ON mz_internal.mz_source_status_history (source_id)",
12993    is_retained_metrics_object: false,
12994};
12995
12996pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
12997    name: "mz_sink_status_history_ind",
12998    schema: MZ_INTERNAL_SCHEMA,
12999    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
13000    sql: "IN CLUSTER mz_catalog_server
13001ON mz_internal.mz_sink_status_history (sink_id)",
13002    is_retained_metrics_object: false,
13003};
13004
13005pub const MZ_SHOW_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13006    name: "mz_show_continual_tasks_ind",
13007    schema: MZ_INTERNAL_SCHEMA,
13008    oid: oid::INDEX_MZ_SHOW_CONTINUAL_TASKS_OID,
13009    sql: "IN CLUSTER mz_catalog_server
13010ON mz_internal.mz_show_continual_tasks (id)",
13011    is_retained_metrics_object: false,
13012};
13013
13014// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
13015// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
13016// save index space, and we don't expect the sum to be > 2^63
13017// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
13018//
13019//
13020// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
13021// underlying relation.
13022//
13023// We append WITH_HISTORY because we want to build a separate view + index that doesn't
13024// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
13025// to hold all records/updates, which causes CPU and latency of querying it to spike.
13026pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
13027    LazyLock::new(|| BuiltinView {
13028        name: "mz_source_statistics_with_history",
13029        schema: MZ_INTERNAL_SCHEMA,
13030        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
13031        desc: RelationDesc::builder()
13032            .with_column("id", SqlScalarType::String.nullable(false))
13033            .with_column("replica_id", SqlScalarType::String.nullable(true))
13034            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13035            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13036            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13037            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13038            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13039            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13040            .with_column(
13041                "rehydration_latency",
13042                SqlScalarType::Interval.nullable(true),
13043            )
13044            .with_column(
13045                "snapshot_records_known",
13046                SqlScalarType::UInt64.nullable(true),
13047            )
13048            .with_column(
13049                "snapshot_records_staged",
13050                SqlScalarType::UInt64.nullable(true),
13051            )
13052            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13053            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13054            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13055            .with_key(vec![0, 1])
13056            .finish(),
13057        column_comments: BTreeMap::new(),
13058        sql: "
13059WITH
13060    -- For each subsource, statistics are reported as its parent source
13061    subsource_to_parent AS
13062    (
13063        SELECT subsource.id AS id, parent.id AS report_id
13064        FROM mz_catalog.mz_sources AS subsource
13065            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
13066            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
13067        WHERE subsource.type = 'subsource'
13068    ),
13069    -- For each table from source, statistics are reported as its parent source
13070    table_to_parent AS
13071    (
13072        SELECT id, source_id AS report_id
13073        FROM mz_catalog.mz_tables
13074        WHERE source_id IS NOT NULL
13075    ),
13076    -- For each source and subsource, statistics are reported as itself
13077    source_refl AS
13078    (
13079        SELECT id, id AS report_id
13080        FROM mz_catalog.mz_sources
13081        WHERE type NOT IN ('progress', 'log')
13082    ),
13083    -- For each table from source, statistics are reported as itself
13084    table_refl AS
13085    (
13086        SELECT id, id AS report_id
13087        FROM mz_catalog.mz_tables
13088        WHERE source_id IS NOT NULL
13089    ),
13090    report_paths AS
13091    (
13092        SELECT id, report_id FROM subsource_to_parent
13093        UNION ALL SELECT id, report_id FROM table_to_parent
13094        UNION ALL SELECT id, report_id FROM source_refl
13095        UNION ALL SELECT id, report_id FROM table_refl
13096    )
13097SELECT
13098    report_paths.report_id AS id,
13099    replica_id,
13100    -- Counters
13101    SUM(messages_received)::uint8 AS messages_received,
13102    SUM(bytes_received)::uint8 AS bytes_received,
13103    SUM(updates_staged)::uint8 AS updates_staged,
13104    SUM(updates_committed)::uint8 AS updates_committed,
13105    -- Resetting Gauges
13106    SUM(records_indexed)::uint8 AS records_indexed,
13107    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13108    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13109    CASE
13110        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13111        ELSE MAX(rehydration_latency)::interval
13112    END AS rehydration_latency,
13113    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13114    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13115    bool_and(snapshot_committed) as snapshot_committed,
13116    -- Gauges
13117    MAX(offset_known)::uint8 AS offset_known,
13118    MIN(offset_committed)::uint8 AS offset_committed
13119FROM mz_internal.mz_source_statistics_raw
13120    JOIN report_paths USING (id)
13121GROUP BY report_paths.report_id, replica_id",
13122        access: vec![PUBLIC_SELECT],
13123    });
13124
13125pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13126    name: "mz_source_statistics_with_history_ind",
13127    schema: MZ_INTERNAL_SCHEMA,
13128    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13129    sql: "IN CLUSTER mz_catalog_server
13130ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
13131    is_retained_metrics_object: true,
13132};
13133
13134// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13135// Used to query MZ_SOURCE_STATISTICS at the current time.
13136pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13137    BuiltinView {
13138        name: "mz_source_statistics",
13139        schema: MZ_INTERNAL_SCHEMA,
13140        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13141        // We need to add a redundant where clause for a new dataflow to be created.
13142        desc: RelationDesc::builder()
13143            .with_column("id", SqlScalarType::String.nullable(false))
13144            .with_column("replica_id", SqlScalarType::String.nullable(true))
13145            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13146            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13147            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13148            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13149            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13150            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13151            .with_column(
13152                "rehydration_latency",
13153                SqlScalarType::Interval.nullable(true),
13154            )
13155            .with_column(
13156                "snapshot_records_known",
13157                SqlScalarType::UInt64.nullable(true),
13158            )
13159            .with_column(
13160                "snapshot_records_staged",
13161                SqlScalarType::UInt64.nullable(true),
13162            )
13163            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13164            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13165            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13166            .with_key(vec![0, 1])
13167            .finish(),
13168        column_comments: BTreeMap::from_iter([
13169            (
13170                "id",
13171                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13172            ),
13173            (
13174                "replica_id",
13175                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13176            ),
13177            (
13178                "messages_received",
13179                "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.",
13180            ),
13181            (
13182                "bytes_received",
13183                "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.",
13184            ),
13185            (
13186                "updates_staged",
13187                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13188            ),
13189            (
13190                "updates_committed",
13191                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13192            ),
13193            (
13194                "records_indexed",
13195                "The number of individual records indexed in the source envelope state.",
13196            ),
13197            (
13198                "bytes_indexed",
13199                "The number of bytes stored in the source's internal index, if any.",
13200            ),
13201            (
13202                "rehydration_latency",
13203                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13204            ),
13205            (
13206                "snapshot_records_known",
13207                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13208            ),
13209            (
13210                "snapshot_records_staged",
13211                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13212            ),
13213            (
13214                "snapshot_committed",
13215                "Whether the source has committed the initial snapshot for a source.",
13216            ),
13217            (
13218                "offset_known",
13219                "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.",
13220            ),
13221            (
13222                "offset_committed",
13223                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13224            ),
13225        ]),
13226        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13227        access: vec![PUBLIC_SELECT],
13228    }
13229});
13230
13231pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13232    name: "mz_source_statistics_ind",
13233    schema: MZ_INTERNAL_SCHEMA,
13234    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13235    sql: "IN CLUSTER mz_catalog_server
13236ON mz_internal.mz_source_statistics (id, replica_id)",
13237    is_retained_metrics_object: false,
13238};
13239
13240pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13241    name: "mz_sink_statistics",
13242    schema: MZ_INTERNAL_SCHEMA,
13243    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13244    desc: RelationDesc::builder()
13245        .with_column("id", SqlScalarType::String.nullable(false))
13246        .with_column("replica_id", SqlScalarType::String.nullable(true))
13247        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
13248        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
13249        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
13250        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
13251        .with_key(vec![0, 1])
13252        .finish(),
13253    column_comments: BTreeMap::from_iter([
13254        (
13255            "id",
13256            "The ID of the sink. Corresponds to `mz_catalog.mz_sources.id`.",
13257        ),
13258        (
13259            "replica_id",
13260            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13261        ),
13262        (
13263            "messages_staged",
13264            "The number of messages staged but possibly not committed to the sink.",
13265        ),
13266        (
13267            "messages_committed",
13268            "The number of messages committed to the sink.",
13269        ),
13270        (
13271            "bytes_staged",
13272            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13273        ),
13274        (
13275            "bytes_committed",
13276            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13277        ),
13278    ]),
13279    sql: "
13280SELECT
13281    id,
13282    replica_id,
13283    SUM(messages_staged)::uint8 AS messages_staged,
13284    SUM(messages_committed)::uint8 AS messages_committed,
13285    SUM(bytes_staged)::uint8 AS bytes_staged,
13286    SUM(bytes_committed)::uint8 AS bytes_committed
13287FROM mz_internal.mz_sink_statistics_raw
13288GROUP BY id, replica_id",
13289    access: vec![PUBLIC_SELECT],
13290});
13291
13292pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13293    name: "mz_sink_statistics_ind",
13294    schema: MZ_INTERNAL_SCHEMA,
13295    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13296    sql: "IN CLUSTER mz_catalog_server
13297ON mz_internal.mz_sink_statistics (id, replica_id)",
13298    is_retained_metrics_object: true,
13299};
13300
13301pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13302    name: "mz_cluster_replicas_ind",
13303    schema: MZ_CATALOG_SCHEMA,
13304    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13305    sql: "IN CLUSTER mz_catalog_server
13306ON mz_catalog.mz_cluster_replicas (id)",
13307    is_retained_metrics_object: true,
13308};
13309
13310pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13311    name: "mz_cluster_replica_sizes_ind",
13312    schema: MZ_CATALOG_SCHEMA,
13313    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13314    sql: "IN CLUSTER mz_catalog_server
13315ON mz_catalog.mz_cluster_replica_sizes (size)",
13316    is_retained_metrics_object: true,
13317};
13318
13319pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13320    name: "mz_cluster_replica_statuses_ind",
13321    schema: MZ_INTERNAL_SCHEMA,
13322    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13323    sql: "IN CLUSTER mz_catalog_server
13324ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13325    is_retained_metrics_object: false,
13326};
13327
13328pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13329    name: "mz_cluster_replica_status_history_ind",
13330    schema: MZ_INTERNAL_SCHEMA,
13331    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13332    sql: "IN CLUSTER mz_catalog_server
13333ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13334    is_retained_metrics_object: false,
13335};
13336
13337pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13338    name: "mz_cluster_replica_metrics_ind",
13339    schema: MZ_INTERNAL_SCHEMA,
13340    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13341    sql: "IN CLUSTER mz_catalog_server
13342ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13343    is_retained_metrics_object: false,
13344};
13345
13346pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13347    name: "mz_cluster_replica_metrics_history_ind",
13348    schema: MZ_INTERNAL_SCHEMA,
13349    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13350    sql: "IN CLUSTER mz_catalog_server
13351ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13352    is_retained_metrics_object: false,
13353};
13354
13355pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13356    name: "mz_cluster_replica_history_ind",
13357    schema: MZ_INTERNAL_SCHEMA,
13358    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13359    sql: "IN CLUSTER mz_catalog_server
13360ON mz_internal.mz_cluster_replica_history (dropped_at)",
13361    is_retained_metrics_object: true,
13362};
13363
13364pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13365    name: "mz_cluster_replica_name_history_ind",
13366    schema: MZ_INTERNAL_SCHEMA,
13367    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13368    sql: "IN CLUSTER mz_catalog_server
13369ON mz_internal.mz_cluster_replica_name_history (id)",
13370    is_retained_metrics_object: false,
13371};
13372
13373pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13374    name: "mz_object_lifetimes_ind",
13375    schema: MZ_INTERNAL_SCHEMA,
13376    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13377    sql: "IN CLUSTER mz_catalog_server
13378ON mz_internal.mz_object_lifetimes (id)",
13379    is_retained_metrics_object: false,
13380};
13381
13382pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13383    name: "mz_object_history_ind",
13384    schema: MZ_INTERNAL_SCHEMA,
13385    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13386    sql: "IN CLUSTER mz_catalog_server
13387ON mz_internal.mz_object_history (id)",
13388    is_retained_metrics_object: false,
13389};
13390
13391pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13392    name: "mz_object_dependencies_ind",
13393    schema: MZ_INTERNAL_SCHEMA,
13394    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
13395    sql: "IN CLUSTER mz_catalog_server
13396ON mz_internal.mz_object_dependencies (object_id)",
13397    is_retained_metrics_object: true,
13398};
13399
13400pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13401    name: "mz_compute_dependencies_ind",
13402    schema: MZ_INTERNAL_SCHEMA,
13403    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
13404    sql: "IN CLUSTER mz_catalog_server
13405ON mz_internal.mz_compute_dependencies (dependency_id)",
13406    is_retained_metrics_object: false,
13407};
13408
13409pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
13410    name: "mz_object_transitive_dependencies_ind",
13411    schema: MZ_INTERNAL_SCHEMA,
13412    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
13413    sql: "IN CLUSTER mz_catalog_server
13414ON mz_internal.mz_object_transitive_dependencies (object_id)",
13415    is_retained_metrics_object: false,
13416};
13417
13418pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
13419    name: "mz_frontiers_ind",
13420    schema: MZ_INTERNAL_SCHEMA,
13421    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
13422    sql: "IN CLUSTER mz_catalog_server
13423ON mz_internal.mz_frontiers (object_id)",
13424    is_retained_metrics_object: false,
13425};
13426
13427pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13428    name: "mz_wallclock_global_lag_recent_history_ind",
13429    schema: MZ_INTERNAL_SCHEMA,
13430    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
13431    sql: "IN CLUSTER mz_catalog_server
13432ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
13433    is_retained_metrics_object: false,
13434};
13435
13436pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
13437    name: "mz_recent_activity_log_thinned_ind",
13438    schema: MZ_INTERNAL_SCHEMA,
13439    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
13440    sql: "IN CLUSTER mz_catalog_server
13441-- sql_hash because we plan to join
13442-- this against mz_internal.mz_sql_text
13443ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
13444    is_retained_metrics_object: false,
13445};
13446
13447pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13448    name: "mz_kafka_sources_ind",
13449    schema: MZ_CATALOG_SCHEMA,
13450    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
13451    sql: "IN CLUSTER mz_catalog_server
13452ON mz_catalog.mz_kafka_sources (id)",
13453    is_retained_metrics_object: true,
13454};
13455
13456pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13457    name: "mz_webhook_sources_ind",
13458    schema: MZ_INTERNAL_SCHEMA,
13459    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
13460    sql: "IN CLUSTER mz_catalog_server
13461ON mz_internal.mz_webhook_sources (id)",
13462    is_retained_metrics_object: true,
13463};
13464
13465pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
13466    name: "mz_comments_ind",
13467    schema: MZ_INTERNAL_SCHEMA,
13468    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
13469    sql: "IN CLUSTER mz_catalog_server
13470ON mz_internal.mz_comments (id)",
13471    is_retained_metrics_object: true,
13472};
13473
13474pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
13475    name: "mz_analytics",
13476    schema: MZ_INTERNAL_SCHEMA,
13477    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
13478    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
13479    access: &[MzAclItem {
13480        grantee: MZ_SYSTEM_ROLE_ID,
13481        grantor: MZ_ANALYTICS_ROLE_ID,
13482        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
13483    }],
13484    owner_id: &MZ_ANALYTICS_ROLE_ID,
13485    runtime_alterable: true,
13486};
13487
13488pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
13489    id: MZ_SYSTEM_ROLE_ID,
13490    name: SYSTEM_USER_NAME,
13491    oid: oid::ROLE_MZ_SYSTEM_OID,
13492    attributes: RoleAttributesRaw::new().with_all(),
13493};
13494
13495pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
13496    id: MZ_SUPPORT_ROLE_ID,
13497    name: SUPPORT_USER_NAME,
13498    oid: oid::ROLE_MZ_SUPPORT_OID,
13499    attributes: RoleAttributesRaw::new(),
13500};
13501
13502pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
13503    id: MZ_ANALYTICS_ROLE_ID,
13504    name: ANALYTICS_USER_NAME,
13505    oid: oid::ROLE_MZ_ANALYTICS_OID,
13506    attributes: RoleAttributesRaw::new(),
13507};
13508
13509/// This role can `SELECT` from various query history objects,
13510/// e.g. `mz_prepared_statement_history`.
13511pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
13512    id: MZ_MONITOR_ROLE_ID,
13513    name: "mz_monitor",
13514    oid: oid::ROLE_MZ_MONITOR_OID,
13515    attributes: RoleAttributesRaw::new(),
13516};
13517
13518/// This role is like [`MZ_MONITOR_ROLE`], but can only query
13519/// the redacted versions of the objects.
13520pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
13521    id: MZ_MONITOR_REDACTED_ROLE_ID,
13522    name: "mz_monitor_redacted",
13523    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
13524    attributes: RoleAttributesRaw::new(),
13525};
13526
13527pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
13528    name: SYSTEM_USER_NAME,
13529    owner_id: &MZ_SYSTEM_ROLE_ID,
13530    privileges: &[
13531        MzAclItem {
13532            grantee: MZ_SUPPORT_ROLE_ID,
13533            grantor: MZ_SYSTEM_ROLE_ID,
13534            acl_mode: AclMode::USAGE,
13535        },
13536        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13537    ],
13538};
13539
13540pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13541    name: BUILTIN_CLUSTER_REPLICA_NAME,
13542    cluster_name: MZ_SYSTEM_CLUSTER.name,
13543};
13544
13545pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
13546    name: "mz_catalog_server",
13547    owner_id: &MZ_SYSTEM_ROLE_ID,
13548    privileges: &[
13549        MzAclItem {
13550            grantee: RoleId::Public,
13551            grantor: MZ_SYSTEM_ROLE_ID,
13552            acl_mode: AclMode::USAGE,
13553        },
13554        MzAclItem {
13555            grantee: MZ_SUPPORT_ROLE_ID,
13556            grantor: MZ_SYSTEM_ROLE_ID,
13557            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
13558        },
13559        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13560    ],
13561};
13562
13563pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13564    name: BUILTIN_CLUSTER_REPLICA_NAME,
13565    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
13566};
13567
13568pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
13569    name: "mz_probe",
13570    owner_id: &MZ_SYSTEM_ROLE_ID,
13571    privileges: &[
13572        MzAclItem {
13573            grantee: MZ_SUPPORT_ROLE_ID,
13574            grantor: MZ_SYSTEM_ROLE_ID,
13575            acl_mode: AclMode::USAGE,
13576        },
13577        MzAclItem {
13578            grantee: MZ_MONITOR_ROLE_ID,
13579            grantor: MZ_SYSTEM_ROLE_ID,
13580            acl_mode: AclMode::USAGE,
13581        },
13582        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
13583    ],
13584};
13585pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
13586    name: BUILTIN_CLUSTER_REPLICA_NAME,
13587    cluster_name: MZ_PROBE_CLUSTER.name,
13588};
13589
13590pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
13591    name: "mz_support",
13592    owner_id: &MZ_SUPPORT_ROLE_ID,
13593    privileges: &[
13594        MzAclItem {
13595            grantee: MZ_SYSTEM_ROLE_ID,
13596            grantor: MZ_SUPPORT_ROLE_ID,
13597            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13598        },
13599        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
13600    ],
13601};
13602
13603pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
13604    name: "mz_analytics",
13605    owner_id: &MZ_ANALYTICS_ROLE_ID,
13606    privileges: &[
13607        MzAclItem {
13608            grantee: MZ_SYSTEM_ROLE_ID,
13609            grantor: MZ_ANALYTICS_ROLE_ID,
13610            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
13611        },
13612        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
13613    ],
13614};
13615
13616/// List of all builtin objects sorted topologically by dependency.
13617pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
13618    let mut builtins = vec![
13619        Builtin::Type(&TYPE_ANY),
13620        Builtin::Type(&TYPE_ANYARRAY),
13621        Builtin::Type(&TYPE_ANYELEMENT),
13622        Builtin::Type(&TYPE_ANYNONARRAY),
13623        Builtin::Type(&TYPE_ANYRANGE),
13624        Builtin::Type(&TYPE_BOOL),
13625        Builtin::Type(&TYPE_BOOL_ARRAY),
13626        Builtin::Type(&TYPE_BYTEA),
13627        Builtin::Type(&TYPE_BYTEA_ARRAY),
13628        Builtin::Type(&TYPE_BPCHAR),
13629        Builtin::Type(&TYPE_BPCHAR_ARRAY),
13630        Builtin::Type(&TYPE_CHAR),
13631        Builtin::Type(&TYPE_CHAR_ARRAY),
13632        Builtin::Type(&TYPE_DATE),
13633        Builtin::Type(&TYPE_DATE_ARRAY),
13634        Builtin::Type(&TYPE_FLOAT4),
13635        Builtin::Type(&TYPE_FLOAT4_ARRAY),
13636        Builtin::Type(&TYPE_FLOAT8),
13637        Builtin::Type(&TYPE_FLOAT8_ARRAY),
13638        Builtin::Type(&TYPE_INT4),
13639        Builtin::Type(&TYPE_INT4_ARRAY),
13640        Builtin::Type(&TYPE_INT8),
13641        Builtin::Type(&TYPE_INT8_ARRAY),
13642        Builtin::Type(&TYPE_INTERVAL),
13643        Builtin::Type(&TYPE_INTERVAL_ARRAY),
13644        Builtin::Type(&TYPE_JSONB),
13645        Builtin::Type(&TYPE_JSONB_ARRAY),
13646        Builtin::Type(&TYPE_LIST),
13647        Builtin::Type(&TYPE_MAP),
13648        Builtin::Type(&TYPE_NAME),
13649        Builtin::Type(&TYPE_NAME_ARRAY),
13650        Builtin::Type(&TYPE_NUMERIC),
13651        Builtin::Type(&TYPE_NUMERIC_ARRAY),
13652        Builtin::Type(&TYPE_OID),
13653        Builtin::Type(&TYPE_OID_ARRAY),
13654        Builtin::Type(&TYPE_RECORD),
13655        Builtin::Type(&TYPE_RECORD_ARRAY),
13656        Builtin::Type(&TYPE_REGCLASS),
13657        Builtin::Type(&TYPE_REGCLASS_ARRAY),
13658        Builtin::Type(&TYPE_REGPROC),
13659        Builtin::Type(&TYPE_REGPROC_ARRAY),
13660        Builtin::Type(&TYPE_REGTYPE),
13661        Builtin::Type(&TYPE_REGTYPE_ARRAY),
13662        Builtin::Type(&TYPE_INT2),
13663        Builtin::Type(&TYPE_INT2_ARRAY),
13664        Builtin::Type(&TYPE_TEXT),
13665        Builtin::Type(&TYPE_TEXT_ARRAY),
13666        Builtin::Type(&TYPE_TIME),
13667        Builtin::Type(&TYPE_TIME_ARRAY),
13668        Builtin::Type(&TYPE_TIMESTAMP),
13669        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
13670        Builtin::Type(&TYPE_TIMESTAMPTZ),
13671        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
13672        Builtin::Type(&TYPE_UUID),
13673        Builtin::Type(&TYPE_UUID_ARRAY),
13674        Builtin::Type(&TYPE_VARCHAR),
13675        Builtin::Type(&TYPE_VARCHAR_ARRAY),
13676        Builtin::Type(&TYPE_INT2_VECTOR),
13677        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
13678        Builtin::Type(&TYPE_ANYCOMPATIBLE),
13679        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
13680        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
13681        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
13682        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
13683        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
13684        Builtin::Type(&TYPE_UINT2),
13685        Builtin::Type(&TYPE_UINT2_ARRAY),
13686        Builtin::Type(&TYPE_UINT4),
13687        Builtin::Type(&TYPE_UINT4_ARRAY),
13688        Builtin::Type(&TYPE_UINT8),
13689        Builtin::Type(&TYPE_UINT8_ARRAY),
13690        Builtin::Type(&TYPE_MZ_TIMESTAMP),
13691        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
13692        Builtin::Type(&TYPE_INT4_RANGE),
13693        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
13694        Builtin::Type(&TYPE_INT8_RANGE),
13695        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
13696        Builtin::Type(&TYPE_DATE_RANGE),
13697        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
13698        Builtin::Type(&TYPE_NUM_RANGE),
13699        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
13700        Builtin::Type(&TYPE_TS_RANGE),
13701        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
13702        Builtin::Type(&TYPE_TSTZ_RANGE),
13703        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
13704        Builtin::Type(&TYPE_MZ_ACL_ITEM),
13705        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
13706        Builtin::Type(&TYPE_ACL_ITEM),
13707        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
13708        Builtin::Type(&TYPE_INTERNAL),
13709    ];
13710    for (schema, funcs) in &[
13711        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
13712        (
13713            INFORMATION_SCHEMA,
13714            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
13715        ),
13716        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
13717        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
13718        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
13719    ] {
13720        for (name, func) in funcs.iter() {
13721            builtins.push(Builtin::Func(BuiltinFunc {
13722                name,
13723                schema,
13724                inner: func,
13725            }));
13726        }
13727    }
13728    builtins.append(&mut vec![
13729        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
13730        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
13731        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
13732        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
13733        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
13734        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
13735        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
13736        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
13737        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
13738        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
13739        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
13740        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
13741        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
13742        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
13743        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
13744        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
13745        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
13746        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
13747        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
13748        Builtin::Log(&MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_RAW),
13749        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
13750        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
13751        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
13752        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
13753        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
13754        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
13755        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
13756        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
13757        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
13758        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
13759        Builtin::Log(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
13760        Builtin::Table(&MZ_KAFKA_SINKS),
13761        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
13762        Builtin::Table(&MZ_KAFKA_SOURCES),
13763        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
13764        Builtin::Table(&MZ_ICEBERG_SINKS),
13765        Builtin::Table(&MZ_DATABASES),
13766        Builtin::Table(&MZ_SCHEMAS),
13767        Builtin::Table(&MZ_COLUMNS),
13768        Builtin::Table(&MZ_INDEXES),
13769        Builtin::Table(&MZ_INDEX_COLUMNS),
13770        Builtin::Table(&MZ_TABLES),
13771        Builtin::Table(&MZ_SOURCES),
13772        Builtin::Table(&MZ_SOURCE_REFERENCES),
13773        Builtin::Table(&MZ_POSTGRES_SOURCES),
13774        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
13775        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
13776        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
13777        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
13778        Builtin::Table(&MZ_SINKS),
13779        Builtin::Table(&MZ_VIEWS),
13780        Builtin::Table(&MZ_MATERIALIZED_VIEWS),
13781        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
13782        Builtin::Table(&MZ_TYPES),
13783        Builtin::Table(&MZ_TYPE_PG_METADATA),
13784        Builtin::Table(&MZ_ARRAY_TYPES),
13785        Builtin::Table(&MZ_BASE_TYPES),
13786        Builtin::Table(&MZ_LIST_TYPES),
13787        Builtin::Table(&MZ_MAP_TYPES),
13788        Builtin::Table(&MZ_ROLES),
13789        Builtin::Table(&MZ_ROLE_AUTH),
13790        Builtin::Table(&MZ_ROLE_MEMBERS),
13791        Builtin::Table(&MZ_ROLE_PARAMETERS),
13792        Builtin::Table(&MZ_PSEUDO_TYPES),
13793        Builtin::Table(&MZ_FUNCTIONS),
13794        Builtin::Table(&MZ_OPERATORS),
13795        Builtin::Table(&MZ_AGGREGATES),
13796        Builtin::Table(&MZ_CLUSTERS),
13797        Builtin::Table(&MZ_CLUSTER_WORKLOAD_CLASSES),
13798        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
13799        Builtin::Table(&MZ_SECRETS),
13800        Builtin::Table(&MZ_CONNECTIONS),
13801        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
13802        Builtin::Table(&MZ_CLUSTER_REPLICAS),
13803        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
13804        Builtin::View(&MZ_CLUSTER_REPLICA_METRICS),
13805        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
13806        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
13807        Builtin::View(&MZ_CLUSTER_REPLICA_STATUSES),
13808        Builtin::Table(&MZ_INTERNAL_CLUSTER_REPLICAS),
13809        Builtin::Table(&MZ_PENDING_CLUSTER_REPLICAS),
13810        Builtin::Table(&MZ_AUDIT_EVENTS),
13811        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
13812        Builtin::Table(&MZ_EGRESS_IPS),
13813        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
13814        Builtin::Table(&MZ_AWS_CONNECTIONS),
13815        Builtin::Table(&MZ_SUBSCRIPTIONS),
13816        Builtin::Table(&MZ_SESSIONS),
13817        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
13818        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
13819        Builtin::Table(&MZ_COMMENTS),
13820        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
13821        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
13822        Builtin::Table(&MZ_CONTINUAL_TASKS),
13823        Builtin::Table(&MZ_NETWORK_POLICIES),
13824        Builtin::Table(&MZ_NETWORK_POLICY_RULES),
13825        Builtin::Table(&MZ_LICENSE_KEYS),
13826        Builtin::View(&MZ_RELATIONS),
13827        Builtin::View(&MZ_OBJECT_OID_ALIAS),
13828        Builtin::View(&MZ_OBJECTS),
13829        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
13830        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
13831        Builtin::View(&MZ_OBJECT_HISTORY),
13832        Builtin::View(&MZ_OBJECT_LIFETIMES),
13833        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
13834        Builtin::View(&MZ_ARRANGEMENT_SHARING),
13835        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
13836        Builtin::View(&MZ_ARRANGEMENT_SIZES),
13837        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
13838        Builtin::View(&MZ_DATAFLOWS),
13839        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
13840        Builtin::View(&MZ_DATAFLOW_CHANNELS),
13841        Builtin::View(&MZ_DATAFLOW_OPERATORS),
13842        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
13843        Builtin::View(&MZ_MAPPABLE_OBJECTS),
13844        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
13845        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
13846        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
13847        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
13848        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
13849        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
13850        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
13851        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
13852        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
13853        Builtin::View(&MZ_COMPUTE_EXPORTS),
13854        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
13855        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
13856        Builtin::View(&MZ_COMPUTE_FRONTIERS),
13857        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
13858        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
13859        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
13860        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
13861        Builtin::View(&MZ_MESSAGE_COUNTS),
13862        Builtin::View(&MZ_ACTIVE_PEEKS),
13863        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
13864        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
13865        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
13866        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
13867        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
13868        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
13869        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
13870        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
13871        Builtin::View(&MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM_PER_WORKER),
13872        Builtin::View(&MZ_DATAFLOW_SHUTDOWN_DURATIONS_HISTOGRAM),
13873        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
13874        Builtin::View(&MZ_SCHEDULING_ELAPSED),
13875        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
13876        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
13877        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
13878        Builtin::View(&MZ_SHOW_COLUMNS),
13879        Builtin::View(&MZ_SHOW_CLUSTERS),
13880        Builtin::View(&MZ_SHOW_SECRETS),
13881        Builtin::View(&MZ_SHOW_DATABASES),
13882        Builtin::View(&MZ_SHOW_SCHEMAS),
13883        Builtin::View(&MZ_SHOW_TABLES),
13884        Builtin::View(&MZ_SHOW_VIEWS),
13885        Builtin::View(&MZ_SHOW_TYPES),
13886        Builtin::View(&MZ_SHOW_ROLES),
13887        Builtin::View(&MZ_SHOW_CONNECTIONS),
13888        Builtin::View(&MZ_SHOW_SOURCES),
13889        Builtin::View(&MZ_SHOW_SINKS),
13890        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
13891        Builtin::View(&MZ_SHOW_INDEXES),
13892        Builtin::View(&MZ_SHOW_CONTINUAL_TASKS),
13893        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
13894        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
13895        Builtin::View(&MZ_TIMEZONE_NAMES),
13896        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
13897        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
13898        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
13899        Builtin::View(&PG_NAMESPACE),
13900        Builtin::View(&PG_CLASS_ALL_DATABASES),
13901        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
13902        Builtin::View(&PG_CLASS),
13903        Builtin::View(&PG_DEPEND),
13904        Builtin::View(&PG_DATABASE),
13905        Builtin::View(&PG_INDEX),
13906        Builtin::View(&PG_TYPE_ALL_DATABASES),
13907        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
13908        Builtin::View(&PG_TYPE),
13909        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
13910        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
13911        Builtin::View(&PG_DESCRIPTION),
13912        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
13913        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
13914        Builtin::View(&PG_ATTRIBUTE),
13915        Builtin::View(&PG_PROC),
13916        Builtin::View(&PG_OPERATOR),
13917        Builtin::View(&PG_RANGE),
13918        Builtin::View(&PG_ENUM),
13919        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
13920        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
13921        Builtin::View(&PG_ATTRDEF),
13922        Builtin::View(&PG_SETTINGS),
13923        Builtin::View(&PG_AUTH_MEMBERS),
13924        Builtin::View(&PG_CONSTRAINT),
13925        Builtin::View(&PG_TABLES),
13926        Builtin::View(&PG_TABLESPACE),
13927        Builtin::View(&PG_ACCESS_METHODS),
13928        Builtin::View(&PG_LOCKS),
13929        Builtin::View(&PG_AUTHID),
13930        Builtin::View(&PG_ROLES),
13931        Builtin::View(&PG_USER),
13932        Builtin::View(&PG_VIEWS),
13933        Builtin::View(&PG_MATVIEWS),
13934        Builtin::View(&PG_COLLATION),
13935        Builtin::View(&PG_POLICY),
13936        Builtin::View(&PG_INHERITS),
13937        Builtin::View(&PG_AGGREGATE),
13938        Builtin::View(&PG_TRIGGER),
13939        Builtin::View(&PG_REWRITE),
13940        Builtin::View(&PG_EXTENSION),
13941        Builtin::View(&PG_EVENT_TRIGGER),
13942        Builtin::View(&PG_LANGUAGE),
13943        Builtin::View(&PG_SHDESCRIPTION),
13944        Builtin::View(&PG_INDEXES),
13945        Builtin::View(&PG_TIMEZONE_ABBREVS),
13946        Builtin::View(&PG_TIMEZONE_NAMES),
13947        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
13948        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
13949        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
13950        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
13951        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
13952        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
13953        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
13954        Builtin::View(&INFORMATION_SCHEMA_TABLES),
13955        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
13956        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
13957        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
13958        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
13959        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
13960        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
13961        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
13962        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
13963        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
13964        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
13965        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
13966        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
13967        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
13968        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
13969        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
13970        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
13971        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
13972        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
13973        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
13974        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
13975        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
13976        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
13977        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
13978        Builtin::View(&MZ_SINK_STATUSES),
13979        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
13980        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
13981        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
13982        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
13983        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
13984        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
13985        Builtin::Source(&MZ_SESSION_HISTORY),
13986        Builtin::Source(&MZ_SQL_TEXT),
13987        Builtin::View(&MZ_SQL_TEXT_REDACTED),
13988        Builtin::View(&MZ_RECENT_SQL_TEXT),
13989        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
13990        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
13991        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
13992        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
13993        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
13994        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
13995        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
13996        Builtin::View(&MZ_SOURCE_STATUSES),
13997        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
13998        Builtin::Source(&MZ_STORAGE_SHARDS),
13999        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
14000        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
14001        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
14002        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
14003        Builtin::View(&MZ_SOURCE_STATISTICS),
14004        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
14005        Builtin::View(&MZ_SINK_STATISTICS),
14006        Builtin::Index(&MZ_SINK_STATISTICS_IND),
14007        Builtin::View(&MZ_STORAGE_USAGE),
14008        Builtin::Source(&MZ_FRONTIERS),
14009        Builtin::View(&MZ_GLOBAL_FRONTIERS),
14010        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
14011        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
14012        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
14013        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
14014        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
14015        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
14016        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
14017        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
14018        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
14019        Builtin::View(&MZ_MATERIALIZATION_LAG),
14020        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
14021        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
14022        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
14023        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
14024        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
14025        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
14026        Builtin::View(&MZ_LIR_MAPPING),
14027        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
14028        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
14029        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
14030        Builtin::View(&MZ_HYDRATION_STATUSES),
14031        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
14032        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
14033        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
14034        Builtin::Index(&MZ_SHOW_DATABASES_IND),
14035        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
14036        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
14037        Builtin::Index(&MZ_SHOW_TABLES_IND),
14038        Builtin::Index(&MZ_SHOW_SOURCES_IND),
14039        Builtin::Index(&MZ_SHOW_VIEWS_IND),
14040        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
14041        Builtin::Index(&MZ_SHOW_SINKS_IND),
14042        Builtin::Index(&MZ_SHOW_TYPES_IND),
14043        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
14044        Builtin::Index(&MZ_SHOW_INDEXES_IND),
14045        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
14046        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
14047        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
14048        Builtin::Index(&MZ_SHOW_SECRETS_IND),
14049        Builtin::Index(&MZ_SHOW_ROLES_IND),
14050        Builtin::Index(&MZ_CLUSTERS_IND),
14051        Builtin::Index(&MZ_INDEXES_IND),
14052        Builtin::Index(&MZ_ROLES_IND),
14053        Builtin::Index(&MZ_SOURCES_IND),
14054        Builtin::Index(&MZ_SINKS_IND),
14055        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
14056        Builtin::Index(&MZ_CONTINUAL_TASKS_IND),
14057        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
14058        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
14059        Builtin::Index(&MZ_SINK_STATUSES_IND),
14060        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
14061        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
14062        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
14063        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
14064        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
14065        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
14066        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
14067        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
14068        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
14069        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
14070        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
14071        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
14072        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
14073        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
14074        Builtin::Index(&MZ_FRONTIERS_IND),
14075        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
14076        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
14077        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
14078        Builtin::Index(&MZ_COMMENTS_IND),
14079        Builtin::Index(&MZ_DATABASES_IND),
14080        Builtin::Index(&MZ_SCHEMAS_IND),
14081        Builtin::Index(&MZ_CONNECTIONS_IND),
14082        Builtin::Index(&MZ_TABLES_IND),
14083        Builtin::Index(&MZ_TYPES_IND),
14084        Builtin::Index(&MZ_OBJECTS_IND),
14085        Builtin::Index(&MZ_COLUMNS_IND),
14086        Builtin::Index(&MZ_SECRETS_IND),
14087        Builtin::Index(&MZ_VIEWS_IND),
14088        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
14089        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
14090        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
14091        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
14092        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
14093        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
14094        Builtin::Connection(&MZ_ANALYTICS),
14095        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT),
14096        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT),
14097        Builtin::ContinualTask(&MZ_WALLCLOCK_LAG_HISTORY_CT),
14098        Builtin::View(&MZ_INDEX_ADVICE),
14099    ]);
14100
14101    builtins.extend(notice::builtins());
14102
14103    builtins
14104});
14105pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
14106    &MZ_SYSTEM_ROLE,
14107    &MZ_SUPPORT_ROLE,
14108    &MZ_ANALYTICS_ROLE,
14109    &MZ_MONITOR_ROLE,
14110    &MZ_MONITOR_REDACTED,
14111];
14112pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
14113    &MZ_SYSTEM_CLUSTER,
14114    &MZ_CATALOG_SERVER_CLUSTER,
14115    &MZ_PROBE_CLUSTER,
14116    &MZ_SUPPORT_CLUSTER,
14117    &MZ_ANALYTICS_CLUSTER,
14118];
14119pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
14120    &MZ_SYSTEM_CLUSTER_REPLICA,
14121    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14122    &MZ_PROBE_CLUSTER_REPLICA,
14123];
14124
14125#[allow(non_snake_case)]
14126pub mod BUILTINS {
14127    use mz_sql::catalog::BuiltinsConfig;
14128
14129    use super::*;
14130
14131    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14132        BUILTINS_STATIC.iter().filter_map(|b| match b {
14133            Builtin::Log(log) => Some(*log),
14134            _ => None,
14135        })
14136    }
14137
14138    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14139        BUILTINS_STATIC.iter().filter_map(|b| match b {
14140            Builtin::Type(typ) => Some(*typ),
14141            _ => None,
14142        })
14143    }
14144
14145    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14146        BUILTINS_STATIC.iter().filter_map(|b| match b {
14147            Builtin::View(view) => Some(*view),
14148            _ => None,
14149        })
14150    }
14151
14152    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14153        BUILTINS_STATIC.iter().filter_map(|b| match b {
14154            Builtin::Func(func) => Some(func),
14155            _ => None,
14156        })
14157    }
14158
14159    pub fn iter(cfg: &BuiltinsConfig) -> impl Iterator<Item = &'static Builtin<NameReference>> {
14160        let include_continual_tasks = cfg.include_continual_tasks;
14161        BUILTINS_STATIC.iter().filter(move |x| match x {
14162            Builtin::ContinualTask(_) if !include_continual_tasks => false,
14163            _ => true,
14164        })
14165    }
14166}
14167
14168pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14169    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14170/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14171/// the builtin itself.
14172pub static BUILTIN_LOOKUP: LazyLock<
14173    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14174> = LazyLock::new(|| {
14175    // BUILTIN_LOOKUP is only ever used for lookups by key, it's not iterated,
14176    // so it's safe to include all of them, regardless of BuiltinConfig. We
14177    // enforce this statically by using the mz_ore HashMap which disallows
14178    // iteration.
14179    BUILTINS_STATIC
14180        .iter()
14181        .enumerate()
14182        .map(|(idx, builtin)| {
14183            (
14184                SystemObjectDescription {
14185                    schema_name: builtin.schema().to_string(),
14186                    object_type: builtin.catalog_item_type(),
14187                    object_name: builtin.name().to_string(),
14188                },
14189                (idx, builtin),
14190            )
14191        })
14192        .collect()
14193});
14194
14195#[mz_ore::test]
14196#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14197fn test_builtin_type_schema() {
14198    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14199
14200    for typ in BUILTINS::types() {
14201        if typ.oid < FIRST_MATERIALIZE_OID {
14202            assert_eq!(
14203                typ.schema, PG_CATALOG_SCHEMA,
14204                "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14205            );
14206        } else {
14207            // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the mz_catalog
14208            // schema.
14209            assert_eq!(
14210                typ.schema, MZ_CATALOG_SCHEMA,
14211                "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14212            );
14213        }
14214    }
14215}