Skip to main content

mz_sql_parser/ast/defs/
statement.rs

1// Copyright 2018 sqlparser-rs contributors. All rights reserved.
2// Copyright Materialize, Inc. and contributors. All rights reserved.
3//
4// This file is derived from the sqlparser-rs project, available at
5// https://github.com/andygrove/sqlparser-rs. It was incorporated
6// directly into Materialize on December 21, 2019.
7//
8// Licensed under the Apache License, Version 2.0 (the "License");
9// you may not use this file except in compliance with the License.
10// You may obtain a copy of the License in the LICENSE file at the
11// root of this repository, or online at
12//
13//     http://www.apache.org/licenses/LICENSE-2.0
14//
15// Unless required by applicable law or agreed to in writing, software
16// distributed under the License is distributed on an "AS IS" BASIS,
17// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18// See the License for the specific language governing permissions and
19// limitations under the License.
20
21use std::collections::BTreeMap;
22use std::fmt;
23
24use enum_kinds::EnumKind;
25use serde::{Deserialize, Serialize};
26use smallvec::{SmallVec, smallvec};
27
28use crate::ast::display::{self, AstDisplay, AstFormatter, WithOptionName};
29use crate::ast::{
30    AstInfo, ColumnDef, ConnectionOption, ConnectionOptionName, CreateConnectionOption,
31    CreateConnectionType, CreateSinkConnection, CreateSourceConnection, CreateSourceOption,
32    CreateSourceOptionName, DeferredItemName, Expr, Format, FormatSpecifier, IcebergSinkMode,
33    Ident, IntervalValue, KeyConstraint, MaterializedViewOption, Query, SelectItem, SinkEnvelope,
34    SourceEnvelope, SourceIncludeMetadata, SubscribeOutput, TableAlias, TableConstraint,
35    TableWithJoins, UnresolvedDatabaseName, UnresolvedItemName, UnresolvedObjectName,
36    UnresolvedSchemaName, Value,
37};
38
39/// A top-level statement (SELECT, INSERT, CREATE, etc.)
40#[allow(clippy::large_enum_variant)]
41#[derive(Debug, Clone, PartialEq, Eq, Hash, EnumKind)]
42#[enum_kind(StatementKind, derive(Serialize, Deserialize))]
43pub enum Statement<T: AstInfo> {
44    Select(SelectStatement<T>),
45    Insert(InsertStatement<T>),
46    Copy(CopyStatement<T>),
47    Update(UpdateStatement<T>),
48    Delete(DeleteStatement<T>),
49    CreateConnection(CreateConnectionStatement<T>),
50    CreateDatabase(CreateDatabaseStatement),
51    CreateSchema(CreateSchemaStatement),
52    CreateWebhookSource(CreateWebhookSourceStatement<T>),
53    CreateSource(CreateSourceStatement<T>),
54    CreateSubsource(CreateSubsourceStatement<T>),
55    CreateSink(CreateSinkStatement<T>),
56    CreateMetricSink(CreateMetricSinkStatement<T>),
57    CreateView(CreateViewStatement<T>),
58    CreateMaterializedView(CreateMaterializedViewStatement<T>),
59    CreateTable(CreateTableStatement<T>),
60    CreateTableFromSource(CreateTableFromSourceStatement<T>),
61    CreateIndex(CreateIndexStatement<T>),
62    CreateType(CreateTypeStatement<T>),
63    CreateRole(CreateRoleStatement),
64    CreateCluster(CreateClusterStatement<T>),
65    CreateClusterReplica(CreateClusterReplicaStatement<T>),
66    CreateSecret(CreateSecretStatement<T>),
67    CreateNetworkPolicy(CreateNetworkPolicyStatement<T>),
68    CreateQueryPolicy(CreateQueryPolicyStatement<T>),
69    AlterCluster(AlterClusterStatement<T>),
70    AlterOwner(AlterOwnerStatement<T>),
71    AlterObjectRename(AlterObjectRenameStatement),
72    AlterObjectSwap(AlterObjectSwapStatement),
73    AlterRetainHistory(AlterRetainHistoryStatement<T>),
74    AlterIndex(AlterIndexStatement<T>),
75    AlterSecret(AlterSecretStatement<T>),
76    AlterSetCluster(AlterSetClusterStatement<T>),
77    AlterSink(AlterSinkStatement<T>),
78    AlterSource(AlterSourceStatement<T>),
79    AlterSystemSet(AlterSystemSetStatement),
80    AlterSystemReset(AlterSystemResetStatement),
81    AlterSystemResetAll(AlterSystemResetAllStatement),
82    AlterConnection(AlterConnectionStatement<T>),
83    AlterNetworkPolicy(AlterNetworkPolicyStatement<T>),
84    AlterQueryPolicy(AlterQueryPolicyStatement<T>),
85    AlterRole(AlterRoleStatement<T>),
86    AlterTableAddColumn(AlterTableAddColumnStatement<T>),
87    AlterMaterializedViewApplyReplacement(AlterMaterializedViewApplyReplacementStatement),
88    Discard(DiscardStatement),
89    DropObjects(DropObjectsStatement),
90    DropOwned(DropOwnedStatement<T>),
91    SetVariable(SetVariableStatement),
92    ResetVariable(ResetVariableStatement),
93    Show(ShowStatement<T>),
94    StartTransaction(StartTransactionStatement),
95    SetTransaction(SetTransactionStatement),
96    Commit(CommitStatement),
97    Rollback(RollbackStatement),
98    Subscribe(SubscribeStatement<T>),
99    ExplainPlan(ExplainPlanStatement<T>),
100    ExplainPushdown(ExplainPushdownStatement<T>),
101    ExplainTimestamp(ExplainTimestampStatement<T>),
102    ExplainSinkSchema(ExplainSinkSchemaStatement<T>),
103    ExplainAnalyzeObject(ExplainAnalyzeObjectStatement<T>),
104    ExplainAnalyzeCluster(ExplainAnalyzeClusterStatement),
105    Declare(DeclareStatement<T>),
106    Fetch(FetchStatement<T>),
107    Close(CloseStatement),
108    Prepare(PrepareStatement<T>),
109    Execute(ExecuteStatement<T>),
110    ExecuteUnitTest(ExecuteUnitTestStatement<T>),
111    Deallocate(DeallocateStatement),
112    Raise(RaiseStatement),
113    GrantRole(GrantRoleStatement<T>),
114    RevokeRole(RevokeRoleStatement<T>),
115    GrantPrivileges(GrantPrivilegesStatement<T>),
116    RevokePrivileges(RevokePrivilegesStatement<T>),
117    AlterDefaultPrivileges(AlterDefaultPrivilegesStatement<T>),
118    ReassignOwned(ReassignOwnedStatement<T>),
119    ValidateConnection(ValidateConnectionStatement<T>),
120    Comment(CommentStatement<T>),
121}
122
123impl<T: AstInfo> AstDisplay for Statement<T> {
124    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
125        match self {
126            Statement::Select(stmt) => f.write_node(stmt),
127            Statement::Insert(stmt) => f.write_node(stmt),
128            Statement::Copy(stmt) => f.write_node(stmt),
129            Statement::Update(stmt) => f.write_node(stmt),
130            Statement::Delete(stmt) => f.write_node(stmt),
131            Statement::CreateConnection(stmt) => f.write_node(stmt),
132            Statement::CreateDatabase(stmt) => f.write_node(stmt),
133            Statement::CreateSchema(stmt) => f.write_node(stmt),
134            Statement::CreateWebhookSource(stmt) => f.write_node(stmt),
135            Statement::CreateSource(stmt) => f.write_node(stmt),
136            Statement::CreateSubsource(stmt) => f.write_node(stmt),
137            Statement::CreateSink(stmt) => f.write_node(stmt),
138            Statement::CreateMetricSink(stmt) => f.write_node(stmt),
139            Statement::CreateView(stmt) => f.write_node(stmt),
140            Statement::CreateMaterializedView(stmt) => f.write_node(stmt),
141            Statement::CreateTable(stmt) => f.write_node(stmt),
142            Statement::CreateTableFromSource(stmt) => f.write_node(stmt),
143            Statement::CreateIndex(stmt) => f.write_node(stmt),
144            Statement::CreateRole(stmt) => f.write_node(stmt),
145            Statement::CreateSecret(stmt) => f.write_node(stmt),
146            Statement::CreateType(stmt) => f.write_node(stmt),
147            Statement::CreateCluster(stmt) => f.write_node(stmt),
148            Statement::CreateClusterReplica(stmt) => f.write_node(stmt),
149            Statement::CreateNetworkPolicy(stmt) => f.write_node(stmt),
150            Statement::CreateQueryPolicy(stmt) => f.write_node(stmt),
151            Statement::AlterCluster(stmt) => f.write_node(stmt),
152            Statement::AlterNetworkPolicy(stmt) => f.write_node(stmt),
153            Statement::AlterQueryPolicy(stmt) => f.write_node(stmt),
154            Statement::AlterOwner(stmt) => f.write_node(stmt),
155            Statement::AlterObjectRename(stmt) => f.write_node(stmt),
156            Statement::AlterRetainHistory(stmt) => f.write_node(stmt),
157            Statement::AlterObjectSwap(stmt) => f.write_node(stmt),
158            Statement::AlterIndex(stmt) => f.write_node(stmt),
159            Statement::AlterSetCluster(stmt) => f.write_node(stmt),
160            Statement::AlterSecret(stmt) => f.write_node(stmt),
161            Statement::AlterSink(stmt) => f.write_node(stmt),
162            Statement::AlterSource(stmt) => f.write_node(stmt),
163            Statement::AlterSystemSet(stmt) => f.write_node(stmt),
164            Statement::AlterSystemReset(stmt) => f.write_node(stmt),
165            Statement::AlterSystemResetAll(stmt) => f.write_node(stmt),
166            Statement::AlterConnection(stmt) => f.write_node(stmt),
167            Statement::AlterRole(stmt) => f.write_node(stmt),
168            Statement::AlterTableAddColumn(stmt) => f.write_node(stmt),
169            Statement::AlterMaterializedViewApplyReplacement(stmt) => f.write_node(stmt),
170            Statement::Discard(stmt) => f.write_node(stmt),
171            Statement::DropObjects(stmt) => f.write_node(stmt),
172            Statement::DropOwned(stmt) => f.write_node(stmt),
173            Statement::SetVariable(stmt) => f.write_node(stmt),
174            Statement::ResetVariable(stmt) => f.write_node(stmt),
175            Statement::Show(stmt) => f.write_node(stmt),
176            Statement::StartTransaction(stmt) => f.write_node(stmt),
177            Statement::SetTransaction(stmt) => f.write_node(stmt),
178            Statement::Commit(stmt) => f.write_node(stmt),
179            Statement::Rollback(stmt) => f.write_node(stmt),
180            Statement::Subscribe(stmt) => f.write_node(stmt),
181            Statement::ExplainPlan(stmt) => f.write_node(stmt),
182            Statement::ExplainPushdown(stmt) => f.write_node(stmt),
183            Statement::ExplainAnalyzeObject(stmt) => f.write_node(stmt),
184            Statement::ExplainAnalyzeCluster(stmt) => f.write_node(stmt),
185            Statement::ExplainTimestamp(stmt) => f.write_node(stmt),
186            Statement::ExplainSinkSchema(stmt) => f.write_node(stmt),
187            Statement::Declare(stmt) => f.write_node(stmt),
188            Statement::Close(stmt) => f.write_node(stmt),
189            Statement::Fetch(stmt) => f.write_node(stmt),
190            Statement::Prepare(stmt) => f.write_node(stmt),
191            Statement::Execute(stmt) => f.write_node(stmt),
192            Statement::ExecuteUnitTest(stmt) => f.write_node(stmt),
193            Statement::Deallocate(stmt) => f.write_node(stmt),
194            Statement::Raise(stmt) => f.write_node(stmt),
195            Statement::GrantRole(stmt) => f.write_node(stmt),
196            Statement::RevokeRole(stmt) => f.write_node(stmt),
197            Statement::GrantPrivileges(stmt) => f.write_node(stmt),
198            Statement::RevokePrivileges(stmt) => f.write_node(stmt),
199            Statement::AlterDefaultPrivileges(stmt) => f.write_node(stmt),
200            Statement::ReassignOwned(stmt) => f.write_node(stmt),
201            Statement::ValidateConnection(stmt) => f.write_node(stmt),
202            Statement::Comment(stmt) => f.write_node(stmt),
203        }
204    }
205}
206impl_display_t!(Statement);
207
208impl StatementKind {
209    /// Whether this statement explains a query or catalog object.
210    pub fn is_explain(&self) -> bool {
211        match self {
212            Self::ExplainPlan
213            | Self::ExplainPushdown
214            | Self::ExplainTimestamp
215            | Self::ExplainSinkSchema
216            | Self::ExplainAnalyzeObject
217            | Self::ExplainAnalyzeCluster => true,
218            Self::Select
219            | Self::Insert
220            | Self::Copy
221            | Self::Update
222            | Self::Delete
223            | Self::CreateConnection
224            | Self::CreateDatabase
225            | Self::CreateSchema
226            | Self::CreateWebhookSource
227            | Self::CreateSource
228            | Self::CreateSubsource
229            | Self::CreateSink
230            | Self::CreateMetricSink
231            | Self::CreateView
232            | Self::CreateMaterializedView
233            | Self::CreateTable
234            | Self::CreateTableFromSource
235            | Self::CreateIndex
236            | Self::CreateType
237            | Self::CreateRole
238            | Self::CreateCluster
239            | Self::CreateClusterReplica
240            | Self::CreateSecret
241            | Self::CreateNetworkPolicy
242            | Self::CreateQueryPolicy
243            | Self::AlterCluster
244            | Self::AlterOwner
245            | Self::AlterObjectRename
246            | Self::AlterObjectSwap
247            | Self::AlterRetainHistory
248            | Self::AlterIndex
249            | Self::AlterSecret
250            | Self::AlterSetCluster
251            | Self::AlterSink
252            | Self::AlterSource
253            | Self::AlterSystemSet
254            | Self::AlterSystemReset
255            | Self::AlterSystemResetAll
256            | Self::AlterConnection
257            | Self::AlterNetworkPolicy
258            | Self::AlterQueryPolicy
259            | Self::AlterRole
260            | Self::AlterTableAddColumn
261            | Self::AlterMaterializedViewApplyReplacement
262            | Self::Discard
263            | Self::DropObjects
264            | Self::DropOwned
265            | Self::SetVariable
266            | Self::ResetVariable
267            | Self::Show
268            | Self::StartTransaction
269            | Self::SetTransaction
270            | Self::Commit
271            | Self::Rollback
272            | Self::Subscribe
273            | Self::Declare
274            | Self::Fetch
275            | Self::Close
276            | Self::Prepare
277            | Self::Execute
278            | Self::ExecuteUnitTest
279            | Self::Deallocate
280            | Self::Raise
281            | Self::GrantRole
282            | Self::RevokeRole
283            | Self::GrantPrivileges
284            | Self::RevokePrivileges
285            | Self::AlterDefaultPrivileges
286            | Self::ReassignOwned
287            | Self::ValidateConnection
288            | Self::Comment => false,
289        }
290    }
291
292    /// Whether this kind of statement can carry secret values, i.e. `CREATE
293    /// SECRET` or `ALTER SECRET`. Such secret material must never be persisted
294    /// verbatim (e.g. in `mz_statement_execution_history`), not even in error
295    /// messages.
296    pub fn is_secret(&self) -> bool {
297        matches!(
298            self,
299            StatementKind::CreateSecret | StatementKind::AlterSecret
300        )
301    }
302
303    /// Whether this kind of statement can carry sensitive material that we
304    /// redact from logged SQL text (and error messages): secret values, or
305    /// bulk/PII user data in `INSERT`/`UPDATE`/`EXECUTE`. A superset of
306    /// [`Self::is_secret`].
307    pub fn is_sensitive(&self) -> bool {
308        self.is_secret()
309            || matches!(
310                self,
311                StatementKind::Insert | StatementKind::Update | StatementKind::Execute
312            )
313    }
314}
315
316/// A static str for each statement kind
317pub fn statement_kind_label_value(kind: StatementKind) -> &'static str {
318    match kind {
319        StatementKind::Select => "select",
320        StatementKind::Insert => "insert",
321        StatementKind::Copy => "copy",
322        StatementKind::Update => "update",
323        StatementKind::Delete => "delete",
324        StatementKind::CreateConnection => "create_connection",
325        StatementKind::CreateDatabase => "create_database",
326        StatementKind::CreateSchema => "create_schema",
327        StatementKind::CreateWebhookSource => "create_webhook",
328        StatementKind::CreateSource => "create_source",
329        StatementKind::CreateSubsource => "create_subsource",
330        StatementKind::CreateSink => "create_sink",
331        StatementKind::CreateMetricSink => "create_metric_sink",
332        StatementKind::CreateView => "create_view",
333        StatementKind::CreateMaterializedView => "create_materialized_view",
334        StatementKind::CreateTable => "create_table",
335        StatementKind::CreateTableFromSource => "create_table_from_source",
336        StatementKind::CreateIndex => "create_index",
337        StatementKind::CreateType => "create_type",
338        StatementKind::CreateRole => "create_role",
339        StatementKind::CreateCluster => "create_cluster",
340        StatementKind::CreateClusterReplica => "create_cluster_replica",
341        StatementKind::CreateSecret => "create_secret",
342        StatementKind::CreateNetworkPolicy => "create_network_policy",
343        StatementKind::CreateQueryPolicy => "create_query_policy",
344        StatementKind::AlterCluster => "alter_cluster",
345        StatementKind::AlterObjectRename => "alter_object_rename",
346        StatementKind::AlterRetainHistory => "alter_retain_history",
347        StatementKind::AlterObjectSwap => "alter_object_swap",
348        StatementKind::AlterIndex => "alter_index",
349        StatementKind::AlterNetworkPolicy => "alter_network_policy",
350        StatementKind::AlterQueryPolicy => "alter_query_policy",
351        StatementKind::AlterRole => "alter_role",
352        StatementKind::AlterSecret => "alter_secret",
353        StatementKind::AlterSetCluster => "alter_set_cluster",
354        StatementKind::AlterSink => "alter_sink",
355        StatementKind::AlterSource => "alter_source",
356        StatementKind::AlterSystemSet => "alter_system_set",
357        StatementKind::AlterSystemReset => "alter_system_reset",
358        StatementKind::AlterSystemResetAll => "alter_system_reset_all",
359        StatementKind::AlterOwner => "alter_owner",
360        StatementKind::AlterConnection => "alter_connection",
361        StatementKind::AlterTableAddColumn => "alter_table",
362        StatementKind::AlterMaterializedViewApplyReplacement => {
363            "alter_materialized_view_apply_replacement"
364        }
365        StatementKind::Discard => "discard",
366        StatementKind::DropObjects => "drop_objects",
367        StatementKind::DropOwned => "drop_owned",
368        StatementKind::SetVariable => "set_variable",
369        StatementKind::ResetVariable => "reset_variable",
370        StatementKind::Show => "show",
371        StatementKind::StartTransaction => "start_transaction",
372        StatementKind::SetTransaction => "set_transaction",
373        StatementKind::Commit => "commit",
374        StatementKind::Rollback => "rollback",
375        StatementKind::Subscribe => "subscribe",
376        StatementKind::ExplainPlan => "explain_plan",
377        StatementKind::ExplainPushdown => "explain_pushdown",
378        StatementKind::ExplainAnalyzeObject => "explain_analyze_object",
379        StatementKind::ExplainAnalyzeCluster => "explain_analyze_cluster",
380        StatementKind::ExplainTimestamp => "explain_timestamp",
381        StatementKind::ExplainSinkSchema => "explain_sink_schema",
382        StatementKind::Declare => "declare",
383        StatementKind::Fetch => "fetch",
384        StatementKind::Close => "close",
385        StatementKind::Prepare => "prepare",
386        StatementKind::Execute => "execute",
387        StatementKind::ExecuteUnitTest => "execute_unit_test",
388        StatementKind::Deallocate => "deallocate",
389        StatementKind::Raise => "raise",
390        StatementKind::GrantRole => "grant_role",
391        StatementKind::RevokeRole => "revoke_role",
392        StatementKind::GrantPrivileges => "grant_privileges",
393        StatementKind::RevokePrivileges => "revoke_privileges",
394        StatementKind::AlterDefaultPrivileges => "alter_default_privileges",
395        StatementKind::ReassignOwned => "reassign_owned",
396        StatementKind::ValidateConnection => "validate_connection",
397        StatementKind::Comment => "comment",
398    }
399}
400
401/// `SELECT`
402#[derive(Debug, Clone, PartialEq, Eq, Hash)]
403pub struct SelectStatement<T: AstInfo> {
404    pub query: Query<T>,
405    pub as_of: Option<AsOf<T>>,
406}
407
408impl<T: AstInfo> AstDisplay for SelectStatement<T> {
409    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
410        // A query whose rendering begins with `SHOW` (a bare `SHOW` body, or a
411        // set operation whose leftmost operand is one) only reparses as a query
412        // when parenthesized: a top-level leading `SHOW` is dispatched as a
413        // `Statement::Show`, which terminates and would reject a following set
414        // operator or ORDER BY/LIMIT/OFFSET. The parser unwraps the redundant
415        // outer parens (see `parse_query_tail`), so wrapping round-trips.
416        let parenthesize_show = self.query.body.starts_with_show();
417        if parenthesize_show {
418            f.write_str("(");
419        }
420        f.write_node(&self.query);
421        if parenthesize_show {
422            f.write_str(")");
423        }
424        if let Some(as_of) = &self.as_of {
425            f.write_str(" ");
426            f.write_node(as_of);
427        }
428    }
429}
430impl_display_t!(SelectStatement);
431
432/// `INSERT`
433#[derive(Debug, Clone, PartialEq, Eq, Hash)]
434pub struct InsertStatement<T: AstInfo> {
435    /// TABLE
436    pub table_name: T::ItemName,
437    /// COLUMNS
438    pub columns: Vec<Ident>,
439    /// A SQL query that specifies what to insert.
440    pub source: InsertSource<T>,
441    /// RETURNING
442    pub returning: Vec<SelectItem<T>>,
443}
444
445impl<T: AstInfo> AstDisplay for InsertStatement<T> {
446    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
447        f.write_str("INSERT INTO ");
448        f.write_node(&self.table_name);
449        if !self.columns.is_empty() {
450            f.write_str(" (");
451            f.write_node(&display::comma_separated(&self.columns));
452            f.write_str(")");
453        }
454        f.write_str(" ");
455        f.write_node(&self.source);
456        if !self.returning.is_empty() {
457            f.write_str(" RETURNING ");
458            f.write_node(&display::comma_separated(&self.returning));
459        }
460    }
461}
462impl_display_t!(InsertStatement);
463
464#[derive(Debug, Clone, PartialEq, Eq, Hash)]
465pub enum CopyRelation<T: AstInfo> {
466    Named {
467        name: T::ItemName,
468        columns: Vec<Ident>,
469    },
470    Select(SelectStatement<T>),
471    Subscribe(SubscribeStatement<T>),
472}
473
474#[derive(Debug, Clone, PartialEq, Eq, Hash)]
475pub enum CopyDirection {
476    To,
477    From,
478}
479
480impl AstDisplay for CopyDirection {
481    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
482        f.write_str(match self {
483            CopyDirection::To => "TO",
484            CopyDirection::From => "FROM",
485        })
486    }
487}
488impl_display!(CopyDirection);
489
490#[derive(Debug, Clone, PartialEq, Eq, Hash)]
491pub enum CopyTarget<T: AstInfo> {
492    Stdin,
493    Stdout,
494    Expr(Expr<T>),
495}
496
497impl<T: AstInfo> AstDisplay for CopyTarget<T> {
498    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
499        match self {
500            CopyTarget::Stdin => f.write_str("STDIN"),
501            CopyTarget::Stdout => f.write_str("STDOUT"),
502            CopyTarget::Expr(expr) => f.write_node(expr),
503        }
504    }
505}
506impl_display_t!(CopyTarget);
507
508#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
509pub enum CopyOptionName {
510    Format,
511    Delimiter,
512    Null,
513    Escape,
514    Quote,
515    Header,
516    AwsConnection,
517    MaxFileSize,
518    Files,
519    Pattern,
520}
521
522impl AstDisplay for CopyOptionName {
523    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
524        f.write_str(match self {
525            CopyOptionName::Format => "FORMAT",
526            CopyOptionName::Delimiter => "DELIMITER",
527            CopyOptionName::Null => "NULL",
528            CopyOptionName::Escape => "ESCAPE",
529            CopyOptionName::Quote => "QUOTE",
530            CopyOptionName::Header => "HEADER",
531            CopyOptionName::AwsConnection => "AWS CONNECTION",
532            CopyOptionName::MaxFileSize => "MAX FILE SIZE",
533            CopyOptionName::Files => "FILES",
534            CopyOptionName::Pattern => "PATTERN",
535        })
536    }
537}
538
539impl WithOptionName for CopyOptionName {
540    /// # WARNING
541    ///
542    /// Whenever implementing this trait consider very carefully whether or not
543    /// this value could contain sensitive user data. If you're uncertain, err
544    /// on the conservative side and return `true`.
545    fn redact_value(&self) -> bool {
546        match self {
547            CopyOptionName::Format
548            | CopyOptionName::Delimiter
549            | CopyOptionName::Null
550            | CopyOptionName::Escape
551            | CopyOptionName::Quote
552            | CopyOptionName::Header
553            | CopyOptionName::AwsConnection
554            | CopyOptionName::MaxFileSize => false,
555            CopyOptionName::Files | CopyOptionName::Pattern => true,
556        }
557    }
558}
559
560#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
561pub struct CopyOption<T: AstInfo> {
562    pub name: CopyOptionName,
563    pub value: Option<WithOptionValue<T>>,
564}
565impl_display_for_with_option!(CopyOption);
566
567/// `COPY`
568#[derive(Debug, Clone, PartialEq, Eq, Hash)]
569pub struct CopyStatement<T: AstInfo> {
570    /// RELATION
571    pub relation: CopyRelation<T>,
572    /// DIRECTION
573    pub direction: CopyDirection,
574    // TARGET
575    pub target: CopyTarget<T>,
576    // OPTIONS
577    pub options: Vec<CopyOption<T>>,
578}
579
580impl<T: AstInfo> AstDisplay for CopyStatement<T> {
581    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
582        f.write_str("COPY ");
583        match &self.relation {
584            CopyRelation::Named { name, columns } => {
585                f.write_node(name);
586                if !columns.is_empty() {
587                    f.write_str("(");
588                    f.write_node(&display::comma_separated(columns));
589                    f.write_str(")");
590                }
591            }
592            CopyRelation::Select(query) => {
593                f.write_str("(");
594                f.write_node(query);
595                f.write_str(")");
596            }
597            CopyRelation::Subscribe(query) => {
598                f.write_str("(");
599                f.write_node(query);
600                f.write_str(")");
601            }
602        };
603        f.write_str(" ");
604        f.write_node(&self.direction);
605        f.write_str(" ");
606        f.write_node(&self.target);
607        if !self.options.is_empty() {
608            f.write_str(" WITH (");
609            f.write_node(&display::comma_separated(&self.options));
610            f.write_str(")");
611        }
612    }
613}
614impl_display_t!(CopyStatement);
615
616/// `UPDATE`
617#[derive(Debug, Clone, PartialEq, Eq, Hash)]
618pub struct UpdateStatement<T: AstInfo> {
619    /// `FROM`
620    pub table_name: T::ItemName,
621    pub alias: Option<TableAlias>,
622    /// Column assignments
623    pub assignments: Vec<Assignment<T>>,
624    /// WHERE
625    pub selection: Option<Expr<T>>,
626}
627
628impl<T: AstInfo> AstDisplay for UpdateStatement<T> {
629    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
630        f.write_str("UPDATE ");
631        f.write_node(&self.table_name);
632        if let Some(alias) = &self.alias {
633            f.write_str(" AS ");
634            f.write_node(alias);
635        }
636        if !self.assignments.is_empty() {
637            f.write_str(" SET ");
638            f.write_node(&display::comma_separated(&self.assignments));
639        }
640        if let Some(selection) = &self.selection {
641            f.write_str(" WHERE ");
642            f.write_node(selection);
643        }
644    }
645}
646impl_display_t!(UpdateStatement);
647
648/// `DELETE`
649#[derive(Debug, Clone, PartialEq, Eq, Hash)]
650pub struct DeleteStatement<T: AstInfo> {
651    /// `FROM`
652    pub table_name: T::ItemName,
653    /// `AS`
654    pub alias: Option<TableAlias>,
655    /// `USING`
656    pub using: Vec<TableWithJoins<T>>,
657    /// `WHERE`
658    pub selection: Option<Expr<T>>,
659}
660
661impl<T: AstInfo> AstDisplay for DeleteStatement<T> {
662    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
663        f.write_str("DELETE FROM ");
664        f.write_node(&self.table_name);
665        if let Some(alias) = &self.alias {
666            f.write_str(" AS ");
667            f.write_node(alias);
668        }
669        if !self.using.is_empty() {
670            f.write_str(" USING ");
671            f.write_node(&display::comma_separated(&self.using));
672        }
673        if let Some(selection) = &self.selection {
674            f.write_str(" WHERE ");
675            f.write_node(selection);
676        }
677    }
678}
679impl_display_t!(DeleteStatement);
680
681/// `CREATE DATABASE`
682#[derive(Debug, Clone, PartialEq, Eq, Hash)]
683pub struct CreateDatabaseStatement {
684    pub name: UnresolvedDatabaseName,
685    pub if_not_exists: bool,
686}
687
688impl AstDisplay for CreateDatabaseStatement {
689    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
690        f.write_str("CREATE DATABASE ");
691        if self.if_not_exists {
692            f.write_str("IF NOT EXISTS ");
693        }
694        f.write_node(&self.name);
695    }
696}
697impl_display!(CreateDatabaseStatement);
698
699/// `CREATE SCHEMA`
700#[derive(Debug, Clone, PartialEq, Eq, Hash)]
701pub struct CreateSchemaStatement {
702    pub name: UnresolvedSchemaName,
703    pub if_not_exists: bool,
704}
705
706impl AstDisplay for CreateSchemaStatement {
707    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
708        f.write_str("CREATE SCHEMA ");
709        if self.if_not_exists {
710            f.write_str("IF NOT EXISTS ");
711        }
712        f.write_node(&self.name);
713    }
714}
715impl_display!(CreateSchemaStatement);
716
717#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
718pub struct ConnectionDefaultAwsPrivatelink<T: AstInfo> {
719    pub connection: T::ItemName,
720    // TODO port should be switched to a vec of options similar to KafkaBrokerAwsPrivatelink if ever support more than port
721    pub port: Option<u16>,
722}
723
724impl<T: AstInfo> AstDisplay for ConnectionDefaultAwsPrivatelink<T> {
725    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
726        f.write_node(&self.connection);
727        if let Some(port) = self.port {
728            f.write_str(" (PORT ");
729            f.write_node(&display::escape_single_quote_string(&port.to_string()));
730            f.write_str(")");
731        }
732    }
733}
734impl_display_t!(ConnectionDefaultAwsPrivatelink);
735
736#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
737/// A MATCHING rule inside BROKERS (...) that routes brokers matching a pattern
738/// through an AWS PrivateLink tunnel.
739pub struct KafkaMatchingBrokerRule<T: AstInfo> {
740    /// Given a broker's host:port, should we use this route?
741    pub pattern: ConnectionRulePattern,
742    /// Route to the broker through this PrivateLink connection.
743    pub tunnel: KafkaBrokerAwsPrivatelink<T>,
744}
745
746#[derive(
747    Debug,
748    Clone,
749    PartialEq,
750    Eq,
751    Hash,
752    PartialOrd,
753    Ord,
754    Serialize,
755    Deserialize
756)]
757/// Parsed from a string, with optional leading and trailing '*' wildcards.
758pub struct ConnectionRulePattern {
759    /// If true, allow any combination of characters before the literal match.
760    pub prefix_wildcard: bool,
761    /// We expect the broker's host:port to match these characters in their entirety.
762    pub literal_match: String,
763    /// If true, allow any combination of characters after the literal match.
764    pub suffix_wildcard: bool,
765}
766
767impl<T: AstInfo> AstDisplay for KafkaMatchingBrokerRule<T> {
768    fn fmt<W>(&self, f: &mut AstFormatter<W>)
769    where
770        W: fmt::Write,
771    {
772        f.write_str("MATCHING ");
773        f.write_node(&self.pattern);
774        f.write_str(" ");
775        f.write_node(&self.tunnel);
776    }
777}
778impl_display_t!(KafkaMatchingBrokerRule);
779
780impl AstDisplay for ConnectionRulePattern {
781    fn fmt<W>(&self, f: &mut AstFormatter<W>)
782    where
783        W: fmt::Write,
784    {
785        f.write_str("'");
786        if self.prefix_wildcard {
787            f.write_str("*");
788        }
789        f.write_node(&display::escape_single_quote_string(&self.literal_match));
790        if self.suffix_wildcard {
791            f.write_str("*");
792        }
793        f.write_str("'");
794    }
795}
796impl_display!(ConnectionRulePattern);
797
798#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
799pub struct KafkaBroker<T: AstInfo> {
800    pub address: String,
801    pub tunnel: KafkaBrokerTunnel<T>,
802}
803
804impl<T: AstInfo> AstDisplay for KafkaBroker<T> {
805    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
806        f.write_str("'");
807        f.write_node(&display::escape_single_quote_string(&self.address));
808        f.write_str("'");
809        f.write_node(&self.tunnel);
810    }
811}
812
813impl_display_t!(KafkaBroker);
814
815#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
816pub enum KafkaBrokerTunnel<T: AstInfo> {
817    Direct,
818    AwsPrivatelink(KafkaBrokerAwsPrivatelink<T>),
819    SshTunnel(T::ItemName),
820}
821
822impl<T: AstInfo> AstDisplay for KafkaBrokerTunnel<T> {
823    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
824        use KafkaBrokerTunnel::*;
825        match self {
826            Direct => {}
827            AwsPrivatelink(aws) => {
828                f.write_str(" ");
829                f.write_node(aws);
830            }
831            Self::SshTunnel(connection) => {
832                f.write_str("USING SSH TUNNEL ");
833                f.write_node(connection);
834            }
835        }
836    }
837}
838
839impl_display_t!(KafkaBrokerTunnel);
840
841#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
842pub enum KafkaBrokerAwsPrivatelinkOptionName {
843    AvailabilityZone,
844    Port,
845}
846
847impl AstDisplay for KafkaBrokerAwsPrivatelinkOptionName {
848    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
849        match self {
850            Self::AvailabilityZone => f.write_str("AVAILABILITY ZONE"),
851            Self::Port => f.write_str("PORT"),
852        }
853    }
854}
855impl_display!(KafkaBrokerAwsPrivatelinkOptionName);
856
857impl WithOptionName for KafkaBrokerAwsPrivatelinkOptionName {
858    /// # WARNING
859    ///
860    /// Whenever implementing this trait consider very carefully whether or not
861    /// this value could contain sensitive user data. If you're uncertain, err
862    /// on the conservative side and return `true`.
863    fn redact_value(&self) -> bool {
864        match self {
865            Self::AvailabilityZone | Self::Port => false,
866        }
867    }
868}
869
870#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
871pub struct KafkaBrokerAwsPrivatelinkOption<T: AstInfo> {
872    pub name: KafkaBrokerAwsPrivatelinkOptionName,
873    pub value: Option<WithOptionValue<T>>,
874}
875impl_display_for_with_option!(KafkaBrokerAwsPrivatelinkOption);
876impl_display_t!(KafkaBrokerAwsPrivatelinkOption);
877
878#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
879pub struct KafkaBrokerAwsPrivatelink<T: AstInfo> {
880    pub connection: T::ItemName,
881    pub options: Vec<KafkaBrokerAwsPrivatelinkOption<T>>,
882}
883
884impl<T: AstInfo> AstDisplay for KafkaBrokerAwsPrivatelink<T> {
885    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
886        f.write_str("USING AWS PRIVATELINK ");
887        f.write_node(&self.connection);
888        if !self.options.is_empty() {
889            f.write_str(" (");
890            f.write_node(&display::comma_separated(&self.options));
891            f.write_str(")");
892        }
893    }
894}
895impl_display_t!(KafkaBrokerAwsPrivatelink);
896
897/// `CREATE CONNECTION` refactor WIP
898#[derive(Debug, Clone, PartialEq, Eq, Hash)]
899pub struct CreateConnectionStatement<T: AstInfo> {
900    pub name: UnresolvedItemName,
901    pub connection_type: CreateConnectionType,
902    pub if_not_exists: bool,
903    pub values: Vec<ConnectionOption<T>>,
904    pub with_options: Vec<CreateConnectionOption<T>>,
905}
906
907impl<T: AstInfo> AstDisplay for CreateConnectionStatement<T> {
908    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
909        f.write_str("CREATE CONNECTION ");
910        if self.if_not_exists {
911            f.write_str("IF NOT EXISTS ");
912        }
913        f.write_node(&self.name);
914        f.write_str(" TO ");
915        self.connection_type.fmt(f);
916        f.write_str(" (");
917        f.write_node(&display::comma_separated(&self.values));
918        f.write_str(")");
919
920        if !self.with_options.is_empty() {
921            f.write_str(" WITH (");
922            f.write_node(&display::comma_separated(&self.with_options));
923            f.write_str(")");
924        }
925    }
926}
927impl_display_t!(CreateConnectionStatement);
928
929/// `VALIDATE CONNECTION`
930#[derive(Debug, Clone, PartialEq, Eq, Hash)]
931pub struct ValidateConnectionStatement<T: AstInfo> {
932    /// The connection to validate
933    pub name: T::ItemName,
934}
935
936impl<T: AstInfo> AstDisplay for ValidateConnectionStatement<T> {
937    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
938        f.write_str("VALIDATE CONNECTION ");
939        f.write_node(&self.name);
940    }
941}
942impl_display_t!(ValidateConnectionStatement);
943
944/// `CREATE (SOURCE | TABLE) <name> FROM WEBHOOK`
945#[derive(Debug, Clone, PartialEq, Eq, Hash)]
946pub struct CreateWebhookSourceStatement<T: AstInfo> {
947    pub name: UnresolvedItemName,
948    pub is_table: bool,
949    pub if_not_exists: bool,
950    pub body_format: Format<T>,
951    pub include_headers: CreateWebhookSourceIncludeHeaders,
952    pub validate_using: Option<CreateWebhookSourceCheck<T>>,
953    pub in_cluster: Option<T::ClusterName>,
954}
955
956impl<T: AstInfo> AstDisplay for CreateWebhookSourceStatement<T> {
957    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
958        f.write_str("CREATE ");
959
960        if self.is_table {
961            f.write_str("TABLE ");
962        } else {
963            f.write_str("SOURCE ");
964        }
965
966        if self.if_not_exists {
967            f.write_str("IF NOT EXISTS ");
968        }
969        f.write_node(&self.name);
970
971        // CREATE TABLE ... FROM WEBHOOK does not support specifying a cluster.
972        if !self.is_table {
973            if let Some(cluster_name) = &self.in_cluster {
974                f.write_str(" IN CLUSTER ");
975                f.write_node(cluster_name);
976            }
977        }
978
979        f.write_str(" FROM WEBHOOK ");
980
981        f.write_str("BODY FORMAT ");
982        f.write_node(&self.body_format);
983
984        f.write_node(&self.include_headers);
985
986        if let Some(validate) = &self.validate_using {
987            f.write_str(" ");
988            f.write_node(validate);
989        }
990    }
991}
992
993impl_display_t!(CreateWebhookSourceStatement);
994
995/// `CHECK ( ... )`
996#[derive(Debug, Clone, PartialEq, Eq, Hash)]
997pub struct CreateWebhookSourceCheck<T: AstInfo> {
998    pub options: Option<CreateWebhookSourceCheckOptions<T>>,
999    pub using: Expr<T>,
1000}
1001
1002impl<T: AstInfo> AstDisplay for CreateWebhookSourceCheck<T> {
1003    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1004        f.write_str("CHECK (");
1005
1006        if let Some(options) = &self.options {
1007            f.write_node(options);
1008            f.write_str(" ");
1009        }
1010
1011        f.write_node(&self.using);
1012        f.write_str(")");
1013    }
1014}
1015
1016impl_display_t!(CreateWebhookSourceCheck);
1017
1018/// `CHECK ( WITH ( ... ) )`
1019#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1020pub struct CreateWebhookSourceCheckOptions<T: AstInfo> {
1021    pub secrets: Vec<CreateWebhookSourceSecret<T>>,
1022    pub headers: Vec<CreateWebhookSourceHeader>,
1023    pub bodies: Vec<CreateWebhookSourceBody>,
1024}
1025
1026impl<T: AstInfo> AstDisplay for CreateWebhookSourceCheckOptions<T> {
1027    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1028        f.write_str("WITH (");
1029
1030        let mut delim = "";
1031        if !self.headers.is_empty() {
1032            f.write_node(&display::comma_separated(&self.headers[..]));
1033            delim = ", ";
1034        }
1035        if !self.bodies.is_empty() {
1036            f.write_str(delim);
1037            f.write_node(&display::comma_separated(&self.bodies[..]));
1038            delim = ", ";
1039        }
1040        if !self.secrets.is_empty() {
1041            f.write_str(delim);
1042            f.write_node(&display::comma_separated(&self.secrets[..]));
1043        }
1044
1045        f.write_str(")");
1046    }
1047}
1048
1049impl_display_t!(CreateWebhookSourceCheckOptions);
1050
1051/// `SECRET ... [AS ...] [BYTES]`
1052#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1053pub struct CreateWebhookSourceSecret<T: AstInfo> {
1054    pub secret: T::ItemName,
1055    pub alias: Option<Ident>,
1056    pub use_bytes: bool,
1057}
1058
1059impl<T: AstInfo> AstDisplay for CreateWebhookSourceSecret<T> {
1060    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1061        f.write_str("SECRET ");
1062        f.write_node(&self.secret);
1063
1064        if let Some(alias) = &self.alias {
1065            f.write_str(" AS ");
1066            f.write_node(alias);
1067        }
1068
1069        if self.use_bytes {
1070            f.write_str(" BYTES");
1071        }
1072    }
1073}
1074
1075impl_display_t!(CreateWebhookSourceSecret);
1076
1077/// `HEADER [AS ...] [BYTES]`
1078#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1079pub struct CreateWebhookSourceHeader {
1080    pub alias: Option<Ident>,
1081    pub use_bytes: bool,
1082}
1083
1084impl AstDisplay for CreateWebhookSourceHeader {
1085    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1086        f.write_str("HEADERS");
1087
1088        if let Some(alias) = &self.alias {
1089            f.write_str(" AS ");
1090            f.write_node(alias);
1091        }
1092
1093        if self.use_bytes {
1094            f.write_str(" BYTES");
1095        }
1096    }
1097}
1098
1099impl_display!(CreateWebhookSourceHeader);
1100
1101/// `BODY [AS ...] [BYTES]`
1102#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1103pub struct CreateWebhookSourceBody {
1104    pub alias: Option<Ident>,
1105    pub use_bytes: bool,
1106}
1107
1108impl AstDisplay for CreateWebhookSourceBody {
1109    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1110        f.write_str("BODY");
1111
1112        if let Some(alias) = &self.alias {
1113            f.write_str(" AS ");
1114            f.write_node(alias);
1115        }
1116
1117        if self.use_bytes {
1118            f.write_str(" BYTES");
1119        }
1120    }
1121}
1122
1123impl_display!(CreateWebhookSourceBody);
1124
1125/// `INCLUDE [HEADER | HEADERS]`
1126#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
1127pub struct CreateWebhookSourceIncludeHeaders {
1128    /// Mapping individual header names to columns in the source.
1129    pub mappings: Vec<CreateWebhookSourceMapHeader>,
1130    /// Whether or not to include the `headers` column, and any filtering we might want to do.
1131    pub column: Option<Vec<CreateWebhookSourceFilterHeader>>,
1132}
1133
1134impl AstDisplay for CreateWebhookSourceIncludeHeaders {
1135    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1136        if !self.mappings.is_empty() {
1137            f.write_str(" ");
1138        }
1139        f.write_node(&display::separated(&self.mappings[..], " "));
1140
1141        if let Some(column) = &self.column {
1142            f.write_str(" INCLUDE HEADERS");
1143
1144            if !column.is_empty() {
1145                f.write_str(" ");
1146                f.write_str("(");
1147                f.write_node(&display::comma_separated(&column[..]));
1148                f.write_str(")");
1149            }
1150        }
1151    }
1152}
1153
1154impl_display!(CreateWebhookSourceIncludeHeaders);
1155
1156#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1157pub struct CreateWebhookSourceFilterHeader {
1158    pub block: bool,
1159    pub header_name: String,
1160}
1161
1162impl AstDisplay for CreateWebhookSourceFilterHeader {
1163    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1164        if self.block {
1165            f.write_str("NOT ");
1166        }
1167        f.write_node(&display::escaped_string_literal(&self.header_name));
1168    }
1169}
1170
1171impl_display!(CreateWebhookSourceFilterHeader);
1172
1173/// `INCLUDE HEADER <name> [AS <alias>] [BYTES]`
1174#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1175pub struct CreateWebhookSourceMapHeader {
1176    pub header_name: String,
1177    pub column_name: Ident,
1178    pub use_bytes: bool,
1179}
1180
1181impl AstDisplay for CreateWebhookSourceMapHeader {
1182    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1183        f.write_str("INCLUDE HEADER ");
1184
1185        f.write_node(&display::escaped_string_literal(&self.header_name));
1186
1187        f.write_str(" AS ");
1188        f.write_node(&self.column_name);
1189
1190        if self.use_bytes {
1191            f.write_str(" BYTES");
1192        }
1193    }
1194}
1195
1196impl_display!(CreateWebhookSourceMapHeader);
1197
1198/// `CREATE SOURCE`
1199#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1200pub struct CreateSourceStatement<T: AstInfo> {
1201    pub name: UnresolvedItemName,
1202    pub in_cluster: Option<T::ClusterName>,
1203    pub col_names: Vec<Ident>,
1204    pub connection: CreateSourceConnection<T>,
1205    pub include_metadata: Vec<SourceIncludeMetadata>,
1206    pub format: Option<FormatSpecifier<T>>,
1207    pub envelope: Option<SourceEnvelope>,
1208    pub if_not_exists: bool,
1209    pub key_constraint: Option<KeyConstraint>,
1210    pub with_options: Vec<CreateSourceOption<T>>,
1211    pub external_references: Option<ExternalReferences>,
1212    pub progress_subsource: Option<DeferredItemName<T>>,
1213}
1214
1215impl<T: AstInfo> AstDisplay for CreateSourceStatement<T> {
1216    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1217        f.write_str("CREATE SOURCE ");
1218        if self.if_not_exists {
1219            f.write_str("IF NOT EXISTS ");
1220        }
1221        f.write_node(&self.name);
1222        if !self.col_names.is_empty() {
1223            f.write_str(" (");
1224            f.write_node(&display::comma_separated(&self.col_names));
1225            if let Some(key_constraint) = &self.key_constraint {
1226                f.write_str(", ");
1227                f.write_node(key_constraint);
1228            }
1229            f.write_str(")");
1230        } else if let Some(key_constraint) = &self.key_constraint {
1231            f.write_str(" (");
1232            f.write_node(key_constraint);
1233            f.write_str(")")
1234        }
1235        if let Some(cluster) = &self.in_cluster {
1236            f.write_str(" IN CLUSTER ");
1237            f.write_node(cluster);
1238        }
1239        f.write_str(" FROM ");
1240        f.write_node(&self.connection);
1241        if let Some(format) = &self.format {
1242            f.write_str(" ");
1243            f.write_node(format);
1244        }
1245        if !self.include_metadata.is_empty() {
1246            f.write_str(" INCLUDE ");
1247            f.write_node(&display::comma_separated(&self.include_metadata));
1248        }
1249
1250        if let Some(envelope) = &self.envelope {
1251            f.write_str(" ENVELOPE ");
1252            f.write_node(envelope);
1253        }
1254
1255        if let Some(subsources) = &self.external_references {
1256            f.write_str(" ");
1257            f.write_node(subsources);
1258        }
1259
1260        if let Some(progress) = &self.progress_subsource {
1261            f.write_str(" EXPOSE PROGRESS AS ");
1262            f.write_node(progress);
1263        }
1264
1265        if !self.with_options.is_empty() {
1266            f.write_str(" WITH (");
1267            f.write_node(&display::comma_separated(&self.with_options));
1268            f.write_str(")");
1269        }
1270    }
1271}
1272impl_display_t!(CreateSourceStatement);
1273
1274/// A selected external reference in a FOR TABLES (..) statement
1275#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
1276pub struct ExternalReferenceExport {
1277    pub reference: UnresolvedItemName,
1278    pub alias: Option<UnresolvedItemName>,
1279}
1280
1281impl AstDisplay for ExternalReferenceExport {
1282    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1283        f.write_node(&self.reference);
1284        if let Some(alias) = &self.alias {
1285            f.write_str(" AS ");
1286            f.write_node(alias);
1287        }
1288    }
1289}
1290impl_display!(ExternalReferenceExport);
1291
1292/// Specifies which set of external references to generate a source export
1293/// for in a `CREATE SOURCE` statement.
1294#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1295pub enum ExternalReferences {
1296    /// A subset defined with FOR TABLES (...)
1297    SubsetTables(Vec<ExternalReferenceExport>),
1298    /// A subset defined with FOR SCHEMAS (...)
1299    SubsetSchemas(Vec<Ident>),
1300    /// FOR ALL TABLES
1301    All,
1302}
1303
1304impl AstDisplay for ExternalReferences {
1305    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1306        match self {
1307            Self::SubsetTables(tables) => {
1308                f.write_str("FOR TABLES (");
1309                f.write_node(&display::comma_separated(tables));
1310                f.write_str(")");
1311            }
1312            Self::SubsetSchemas(schemas) => {
1313                f.write_str("FOR SCHEMAS (");
1314                f.write_node(&display::comma_separated(schemas));
1315                f.write_str(")");
1316            }
1317            Self::All => f.write_str("FOR ALL TABLES"),
1318        }
1319    }
1320}
1321impl_display!(ExternalReferences);
1322
1323/// An option in a `CREATE SUBSOURCE` statement.
1324#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1325pub enum CreateSubsourceOptionName {
1326    Progress,
1327    /// Tracks which item this subsource references in the primary source.
1328    ExternalReference,
1329    /// The `RETAIN HISTORY` option
1330    RetainHistory,
1331    /// Columns whose types you want to unconditionally format as text
1332    TextColumns,
1333    /// Columns you want to exclude when ingesting data
1334    ExcludeColumns,
1335    /// `DETAILS` for this subsource, hex-encoded protobuf type
1336    /// `mz_storage_types::sources::SourceExportStatementDetails`
1337    Details,
1338}
1339
1340impl AstDisplay for CreateSubsourceOptionName {
1341    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1342        f.write_str(match self {
1343            CreateSubsourceOptionName::Progress => "PROGRESS",
1344            CreateSubsourceOptionName::ExternalReference => "EXTERNAL REFERENCE",
1345            CreateSubsourceOptionName::RetainHistory => "RETAIN HISTORY",
1346            CreateSubsourceOptionName::TextColumns => "TEXT COLUMNS",
1347            CreateSubsourceOptionName::ExcludeColumns => "EXCLUDE COLUMNS",
1348            CreateSubsourceOptionName::Details => "DETAILS",
1349        })
1350    }
1351}
1352
1353impl WithOptionName for CreateSubsourceOptionName {
1354    /// # WARNING
1355    ///
1356    /// Whenever implementing this trait consider very carefully whether or not
1357    /// this value could contain sensitive user data. If you're uncertain, err
1358    /// on the conservative side and return `true`.
1359    fn redact_value(&self) -> bool {
1360        match self {
1361            CreateSubsourceOptionName::Progress
1362            | CreateSubsourceOptionName::ExternalReference
1363            | CreateSubsourceOptionName::RetainHistory
1364            | CreateSubsourceOptionName::Details
1365            | CreateSubsourceOptionName::TextColumns
1366            | CreateSubsourceOptionName::ExcludeColumns => false,
1367        }
1368    }
1369}
1370
1371#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1372pub struct CreateSubsourceOption<T: AstInfo> {
1373    pub name: CreateSubsourceOptionName,
1374    pub value: Option<WithOptionValue<T>>,
1375}
1376impl_display_for_with_option!(CreateSubsourceOption);
1377
1378/// `CREATE SUBSOURCE`
1379#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1380pub struct CreateSubsourceStatement<T: AstInfo> {
1381    pub name: UnresolvedItemName,
1382    pub columns: Vec<ColumnDef<T>>,
1383    /// Tracks the primary source of this subsource if an ingestion export (i.e.
1384    /// not a progress subsource).
1385    pub of_source: Option<T::ItemName>,
1386    pub constraints: Vec<TableConstraint<T>>,
1387    pub if_not_exists: bool,
1388    pub with_options: Vec<CreateSubsourceOption<T>>,
1389}
1390
1391impl<T: AstInfo> AstDisplay for CreateSubsourceStatement<T> {
1392    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1393        f.write_str("CREATE SUBSOURCE ");
1394        if self.if_not_exists {
1395            f.write_str("IF NOT EXISTS ");
1396        }
1397
1398        f.write_node(&self.name);
1399        f.write_str(" (");
1400        f.write_node(&display::comma_separated(&self.columns));
1401        if !self.constraints.is_empty() {
1402            f.write_str(", ");
1403            f.write_node(&display::comma_separated(&self.constraints));
1404        }
1405        f.write_str(")");
1406
1407        if let Some(of_source) = &self.of_source {
1408            f.write_str(" OF SOURCE ");
1409            f.write_node(of_source);
1410        }
1411
1412        if !self.with_options.is_empty() {
1413            f.write_str(" WITH (");
1414            f.write_node(&display::comma_separated(&self.with_options));
1415            f.write_str(")");
1416        }
1417    }
1418}
1419impl_display_t!(CreateSubsourceStatement);
1420
1421/// An option in a `CREATE SINK` statement.
1422#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1423pub enum CreateSinkOptionName {
1424    Snapshot,
1425    Version,
1426    PartitionStrategy,
1427    CommitInterval,
1428}
1429
1430impl AstDisplay for CreateSinkOptionName {
1431    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1432        match self {
1433            CreateSinkOptionName::Snapshot => {
1434                f.write_str("SNAPSHOT");
1435            }
1436            CreateSinkOptionName::Version => {
1437                f.write_str("VERSION");
1438            }
1439            CreateSinkOptionName::PartitionStrategy => {
1440                f.write_str("PARTITION STRATEGY");
1441            }
1442            CreateSinkOptionName::CommitInterval => {
1443                f.write_str("COMMIT INTERVAL");
1444            }
1445        }
1446    }
1447}
1448
1449impl WithOptionName for CreateSinkOptionName {
1450    /// # WARNING
1451    ///
1452    /// Whenever implementing this trait consider very carefully whether or not
1453    /// this value could contain sensitive user data. If you're uncertain, err
1454    /// on the conservative side and return `true`.
1455    fn redact_value(&self) -> bool {
1456        match self {
1457            CreateSinkOptionName::Snapshot => false,
1458            CreateSinkOptionName::Version => false,
1459            CreateSinkOptionName::PartitionStrategy => false,
1460            CreateSinkOptionName::CommitInterval => false,
1461        }
1462    }
1463}
1464
1465#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1466pub struct CreateSinkOption<T: AstInfo> {
1467    pub name: CreateSinkOptionName,
1468    pub value: Option<WithOptionValue<T>>,
1469}
1470impl_display_for_with_option!(CreateSinkOption);
1471
1472/// `CREATE SINK`
1473#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1474pub struct CreateSinkStatement<T: AstInfo> {
1475    pub name: Option<UnresolvedItemName>,
1476    pub in_cluster: Option<T::ClusterName>,
1477    pub if_not_exists: bool,
1478    pub from: T::ItemName,
1479    pub connection: CreateSinkConnection<T>,
1480    pub format: Option<FormatSpecifier<T>>,
1481    pub envelope: Option<SinkEnvelope>,
1482    pub mode: Option<IcebergSinkMode>,
1483    pub with_options: Vec<CreateSinkOption<T>>,
1484}
1485
1486impl<T: AstInfo> AstDisplay for CreateSinkStatement<T> {
1487    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1488        f.write_str("CREATE SINK ");
1489        if self.if_not_exists {
1490            f.write_str("IF NOT EXISTS ");
1491        }
1492        if let Some(name) = &self.name {
1493            f.write_node(&name);
1494            f.write_str(" ");
1495        }
1496        if let Some(cluster) = &self.in_cluster {
1497            f.write_str("IN CLUSTER ");
1498            f.write_node(cluster);
1499            f.write_str(" ");
1500        }
1501        f.write_str("FROM ");
1502        f.write_node(&self.from);
1503        f.write_str(" INTO ");
1504        f.write_node(&self.connection);
1505        if let Some(format) = &self.format {
1506            f.write_str(" ");
1507            f.write_node(format);
1508        }
1509        if let Some(envelope) = &self.envelope {
1510            f.write_str(" ENVELOPE ");
1511            f.write_node(envelope);
1512        }
1513        if let Some(mode) = &self.mode {
1514            f.write_str(" MODE ");
1515            f.write_node(mode);
1516        }
1517
1518        if !self.with_options.is_empty() {
1519            f.write_str(" WITH (");
1520            f.write_node(&display::comma_separated(&self.with_options));
1521            f.write_str(")");
1522        }
1523    }
1524}
1525impl_display_t!(CreateSinkStatement);
1526
1527/// An option in a `CREATE METRIC SINK` statement.
1528#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1529pub enum CreateMetricSinkOptionName {
1530    Prefix,
1531}
1532
1533impl AstDisplay for CreateMetricSinkOptionName {
1534    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1535        match self {
1536            CreateMetricSinkOptionName::Prefix => {
1537                f.write_str("PREFIX");
1538            }
1539        }
1540    }
1541}
1542
1543impl WithOptionName for CreateMetricSinkOptionName {
1544    /// # WARNING
1545    ///
1546    /// Whenever implementing this trait consider very carefully whether or not
1547    /// this value could contain sensitive user data. If you're uncertain, err
1548    /// on the conservative side and return `true`.
1549    fn redact_value(&self) -> bool {
1550        match self {
1551            CreateMetricSinkOptionName::Prefix => false,
1552        }
1553    }
1554}
1555
1556#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1557pub struct CreateMetricSinkOption<T: AstInfo> {
1558    pub name: CreateMetricSinkOptionName,
1559    pub value: Option<WithOptionValue<T>>,
1560}
1561impl_display_for_with_option!(CreateMetricSinkOption);
1562
1563/// `CREATE METRIC SINK`
1564#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1565pub struct CreateMetricSinkStatement<T: AstInfo> {
1566    pub name: UnresolvedItemName,
1567    pub in_cluster: Option<T::ClusterName>,
1568    pub if_not_exists: bool,
1569    pub from: T::ItemName,
1570    pub with_options: Vec<CreateMetricSinkOption<T>>,
1571}
1572
1573impl<T: AstInfo> AstDisplay for CreateMetricSinkStatement<T> {
1574    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1575        f.write_str("CREATE METRIC SINK ");
1576        if self.if_not_exists {
1577            f.write_str("IF NOT EXISTS ");
1578        }
1579        f.write_node(&self.name);
1580        f.write_str(" ");
1581        if let Some(cluster) = &self.in_cluster {
1582            f.write_str("IN CLUSTER ");
1583            f.write_node(cluster);
1584            f.write_str(" ");
1585        }
1586        f.write_str("FROM ");
1587        f.write_node(&self.from);
1588
1589        // NOTE: `create_sql` is persisted through this impl and re-parsed on boot, so dropping
1590        // the clause here would silently lose the prefix across a restart.
1591        if !self.with_options.is_empty() {
1592            f.write_str(" WITH (");
1593            f.write_node(&display::comma_separated(&self.with_options));
1594            f.write_str(")");
1595        }
1596    }
1597}
1598impl_display_t!(CreateMetricSinkStatement);
1599
1600#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1601pub struct ViewDefinition<T: AstInfo> {
1602    /// View name
1603    pub name: UnresolvedItemName,
1604    pub columns: Vec<Ident>,
1605    pub query: Query<T>,
1606}
1607
1608impl<T: AstInfo> AstDisplay for ViewDefinition<T> {
1609    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1610        f.write_node(&self.name);
1611
1612        if !self.columns.is_empty() {
1613            f.write_str(" (");
1614            f.write_node(&display::comma_separated(&self.columns));
1615            f.write_str(")");
1616        }
1617
1618        f.write_str(" AS ");
1619        f.write_node(&self.query);
1620    }
1621}
1622impl_display_t!(ViewDefinition);
1623
1624/// `CREATE VIEW`
1625#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1626pub struct CreateViewStatement<T: AstInfo> {
1627    pub if_exists: IfExistsBehavior,
1628    pub temporary: bool,
1629    pub definition: ViewDefinition<T>,
1630}
1631
1632impl<T: AstInfo> AstDisplay for CreateViewStatement<T> {
1633    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1634        f.write_str("CREATE");
1635        if self.if_exists == IfExistsBehavior::Replace {
1636            f.write_str(" OR REPLACE");
1637        }
1638        if self.temporary {
1639            f.write_str(" TEMPORARY");
1640        }
1641
1642        f.write_str(" VIEW");
1643
1644        if self.if_exists == IfExistsBehavior::Skip {
1645            f.write_str(" IF NOT EXISTS");
1646        }
1647
1648        f.write_str(" ");
1649        f.write_node(&self.definition);
1650    }
1651}
1652impl_display_t!(CreateViewStatement);
1653
1654/// `CREATE MATERIALIZED VIEW`
1655#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1656pub struct CreateMaterializedViewStatement<T: AstInfo> {
1657    pub if_exists: IfExistsBehavior,
1658    pub name: UnresolvedItemName,
1659    pub columns: Vec<Ident>,
1660    pub replacement_for: Option<T::ItemName>,
1661    pub in_cluster: Option<T::ClusterName>,
1662    pub in_cluster_replica: Option<Ident>,
1663    pub query: Query<T>,
1664    pub as_of: Option<u64>,
1665    pub with_options: Vec<MaterializedViewOption<T>>,
1666}
1667
1668impl<T: AstInfo> AstDisplay for CreateMaterializedViewStatement<T> {
1669    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1670        f.write_str("CREATE");
1671        if self.if_exists == IfExistsBehavior::Replace {
1672            f.write_str(" OR REPLACE");
1673        }
1674        if self.replacement_for.is_some() {
1675            f.write_str(" REPLACEMENT");
1676        }
1677
1678        f.write_str(" MATERIALIZED VIEW");
1679
1680        if self.if_exists == IfExistsBehavior::Skip {
1681            f.write_str(" IF NOT EXISTS");
1682        }
1683
1684        f.write_str(" ");
1685        f.write_node(&self.name);
1686
1687        if !self.columns.is_empty() {
1688            f.write_str(" (");
1689            f.write_node(&display::comma_separated(&self.columns));
1690            f.write_str(")");
1691        }
1692
1693        if let Some(target) = &self.replacement_for {
1694            f.write_str(" FOR ");
1695            f.write_node(target);
1696        }
1697
1698        match (&self.in_cluster, &self.in_cluster_replica) {
1699            (Some(cluster), Some(replica)) => {
1700                f.write_str(" IN CLUSTER ");
1701                f.write_node(cluster);
1702                f.write_str(" REPLICA ");
1703                f.write_node(replica);
1704            }
1705            (Some(cluster), None) => {
1706                f.write_str(" IN CLUSTER ");
1707                f.write_node(cluster);
1708            }
1709            (None, Some(replica)) => {
1710                f.write_str(" IN REPLICA ");
1711                f.write_node(replica);
1712            }
1713            (None, None) => {}
1714        }
1715
1716        if !self.with_options.is_empty() {
1717            f.write_str(" WITH (");
1718            f.write_node(&display::comma_separated(&self.with_options));
1719            f.write_str(")");
1720        }
1721
1722        f.write_str(" AS ");
1723        f.write_node(&self.query);
1724
1725        if let Some(time) = &self.as_of {
1726            f.write_str(" AS OF ");
1727            f.write_str(time);
1728        }
1729    }
1730}
1731impl_display_t!(CreateMaterializedViewStatement);
1732
1733/// `ALTER SET CLUSTER`
1734#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1735pub struct AlterSetClusterStatement<T: AstInfo> {
1736    pub if_exists: bool,
1737    pub name: UnresolvedItemName,
1738    pub object_type: ObjectType,
1739    pub set_cluster: T::ClusterName,
1740}
1741
1742impl<T: AstInfo> AstDisplay for AlterSetClusterStatement<T> {
1743    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1744        f.write_str("ALTER ");
1745        f.write_node(&self.object_type);
1746
1747        if self.if_exists {
1748            f.write_str(" IF EXISTS");
1749        }
1750
1751        f.write_str(" ");
1752        f.write_node(&self.name);
1753
1754        f.write_str(" SET CLUSTER ");
1755        f.write_node(&self.set_cluster);
1756    }
1757}
1758impl_display_t!(AlterSetClusterStatement);
1759
1760/// `CREATE TABLE`
1761#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1762pub struct CreateTableStatement<T: AstInfo> {
1763    /// Table name
1764    pub name: UnresolvedItemName,
1765    /// Optional schema
1766    pub columns: Vec<ColumnDef<T>>,
1767    pub constraints: Vec<TableConstraint<T>>,
1768    pub if_not_exists: bool,
1769    pub temporary: bool,
1770    pub with_options: Vec<TableOption<T>>,
1771}
1772
1773impl<T: AstInfo> AstDisplay for CreateTableStatement<T> {
1774    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1775        let Self {
1776            name,
1777            columns,
1778            constraints,
1779            if_not_exists,
1780            temporary,
1781            with_options,
1782        } = self;
1783        f.write_str("CREATE ");
1784        if *temporary {
1785            f.write_str("TEMPORARY ");
1786        }
1787        f.write_str("TABLE ");
1788        if *if_not_exists {
1789            f.write_str("IF NOT EXISTS ");
1790        }
1791        f.write_node(name);
1792        f.write_str(" (");
1793        f.write_node(&display::comma_separated(columns));
1794        if !self.constraints.is_empty() {
1795            if !columns.is_empty() {
1796                f.write_str(", ");
1797            }
1798            f.write_node(&display::comma_separated(constraints));
1799        }
1800        f.write_str(")");
1801        if !with_options.is_empty() {
1802            f.write_str(" WITH (");
1803            f.write_node(&display::comma_separated(&self.with_options));
1804            f.write_str(")");
1805        }
1806    }
1807}
1808impl_display_t!(CreateTableStatement);
1809
1810#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1811pub enum TableOptionName {
1812    // The `PARTITION BY` option
1813    PartitionBy,
1814    // The `RETAIN HISTORY` option
1815    RetainHistory,
1816    /// A special option to test that we do redact values.
1817    RedactedTest,
1818}
1819
1820impl AstDisplay for TableOptionName {
1821    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1822        match self {
1823            TableOptionName::PartitionBy => {
1824                f.write_str("PARTITION BY");
1825            }
1826            TableOptionName::RetainHistory => {
1827                f.write_str("RETAIN HISTORY");
1828            }
1829            TableOptionName::RedactedTest => {
1830                f.write_str("REDACTED");
1831            }
1832        }
1833    }
1834}
1835
1836impl WithOptionName for TableOptionName {
1837    /// # WARNING
1838    ///
1839    /// Whenever implementing this trait consider very carefully whether or not
1840    /// this value could contain sensitive user data. If you're uncertain, err
1841    /// on the conservative side and return `true`.
1842    fn redact_value(&self) -> bool {
1843        match self {
1844            // The value is an arbitrary user expression/literal that may embed
1845            // sensitive data, so redact it (mirrors `KafkaSinkConfigOptionName`).
1846            TableOptionName::PartitionBy => true,
1847            TableOptionName::RetainHistory => false,
1848            TableOptionName::RedactedTest => true,
1849        }
1850    }
1851}
1852
1853#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1854pub struct TableOption<T: AstInfo> {
1855    pub name: TableOptionName,
1856    pub value: Option<WithOptionValue<T>>,
1857}
1858impl_display_for_with_option!(TableOption);
1859
1860#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1861pub enum TableFromSourceOptionName {
1862    /// Columns whose types you want to unconditionally format as text
1863    TextColumns,
1864    /// Columns you want to exclude when ingesting data
1865    ExcludeColumns,
1866    /// Upstream `PRIMARY KEY`/`UNIQUE` constraints, by name, that Materialize
1867    /// should not record as keys, so that their later upstream drop is a
1868    /// non-event.
1869    ExcludeConstraints,
1870    /// Record no upstream constraints at all: no keys, and every column
1871    /// ingested as nullable.
1872    ExcludeAllConstraints,
1873    /// Ignore all `NOT NULL` constraints on columns
1874    ExcludeAllNotNullConstraints,
1875    /// Hex-encoded protobuf of a `ProtoSourceExportStatementDetails`
1876    /// message, which includes details necessary for planning this
1877    /// table as a Source Export
1878    Details,
1879    /// Partition the given table by the provided columns.
1880    PartitionBy,
1881    // The `RETAIN HISTORY` option
1882    RetainHistory,
1883}
1884
1885impl AstDisplay for TableFromSourceOptionName {
1886    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1887        f.write_str(match self {
1888            TableFromSourceOptionName::TextColumns => "TEXT COLUMNS",
1889            TableFromSourceOptionName::ExcludeColumns => "EXCLUDE COLUMNS",
1890            TableFromSourceOptionName::ExcludeConstraints => "EXCLUDE CONSTRAINTS",
1891            TableFromSourceOptionName::ExcludeAllConstraints => "EXCLUDE ALL CONSTRAINTS",
1892            TableFromSourceOptionName::ExcludeAllNotNullConstraints => {
1893                "EXCLUDE ALL NOT NULL CONSTRAINTS"
1894            }
1895            TableFromSourceOptionName::Details => "DETAILS",
1896            TableFromSourceOptionName::PartitionBy => "PARTITION BY",
1897            TableFromSourceOptionName::RetainHistory => "RETAIN HISTORY",
1898        })
1899    }
1900}
1901impl_display!(TableFromSourceOptionName);
1902
1903impl WithOptionName for TableFromSourceOptionName {
1904    /// # WARNING
1905    ///
1906    /// Whenever implementing this trait consider very carefully whether or not
1907    /// this value could contain sensitive user data. If you're uncertain, err
1908    /// on the conservative side and return `true`.
1909    fn redact_value(&self) -> bool {
1910        match self {
1911            TableFromSourceOptionName::Details
1912            | TableFromSourceOptionName::TextColumns
1913            | TableFromSourceOptionName::ExcludeColumns
1914            | TableFromSourceOptionName::ExcludeConstraints
1915            | TableFromSourceOptionName::ExcludeAllConstraints
1916            | TableFromSourceOptionName::ExcludeAllNotNullConstraints
1917            | TableFromSourceOptionName::RetainHistory => false,
1918            // The value is an arbitrary user expression/literal that may embed
1919            // sensitive data, so redact it (mirrors `KafkaSinkConfigOptionName`).
1920            TableFromSourceOptionName::PartitionBy => true,
1921        }
1922    }
1923}
1924
1925#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1926pub struct TableFromSourceOption<T: AstInfo> {
1927    pub name: TableFromSourceOptionName,
1928    pub value: Option<WithOptionValue<T>>,
1929}
1930impl_display_for_with_option!(TableFromSourceOption);
1931
1932/// `CREATE TABLE .. FROM SOURCE` columns specification
1933/// can have 3 states:
1934/// Before purification they can be `NotSpecified` or `Named`
1935/// by the user to specify the column names to use.
1936/// After purification they can be in any of the 3 states.
1937/// For some source types we define the columns during purification
1938/// and for others the columns are defined during planning based
1939/// on the encoding option of the source.
1940#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1941pub enum TableFromSourceColumns<T: AstInfo> {
1942    /// The user did not specify which columns to use.
1943    NotSpecified,
1944    /// The user requested the named columns. Only compatible
1945    /// with source types that allow user-specified column names.
1946    Named(Vec<Ident>),
1947    /// Columns defined during purification for some source types.
1948    Defined(Vec<ColumnDef<T>>),
1949}
1950
1951/// `CREATE TABLE .. FROM SOURCE`
1952#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1953pub struct CreateTableFromSourceStatement<T: AstInfo> {
1954    pub name: UnresolvedItemName,
1955    pub columns: TableFromSourceColumns<T>,
1956    pub constraints: Vec<TableConstraint<T>>,
1957    pub if_not_exists: bool,
1958    pub source: T::ItemName,
1959    pub external_reference: Option<UnresolvedItemName>,
1960    pub with_options: Vec<TableFromSourceOption<T>>,
1961    pub include_metadata: Vec<SourceIncludeMetadata>,
1962    pub format: Option<FormatSpecifier<T>>,
1963    pub envelope: Option<SourceEnvelope>,
1964}
1965
1966impl<T: AstInfo> AstDisplay for CreateTableFromSourceStatement<T> {
1967    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
1968        let Self {
1969            name,
1970            columns,
1971            constraints,
1972            source,
1973            external_reference,
1974            if_not_exists,
1975            with_options,
1976            include_metadata,
1977            format,
1978            envelope,
1979        } = self;
1980        f.write_str("CREATE TABLE ");
1981        if *if_not_exists {
1982            f.write_str("IF NOT EXISTS ");
1983        }
1984        f.write_node(name);
1985        if !matches!(columns, TableFromSourceColumns::NotSpecified) || !constraints.is_empty() {
1986            f.write_str(" (");
1987
1988            match columns {
1989                TableFromSourceColumns::NotSpecified => {}
1990                TableFromSourceColumns::Named(columns) => {
1991                    f.write_node(&display::comma_separated(columns))
1992                }
1993                TableFromSourceColumns::Defined(columns) => {
1994                    f.write_node(&display::comma_separated(columns))
1995                }
1996            };
1997            if !constraints.is_empty() {
1998                if !matches!(columns, TableFromSourceColumns::NotSpecified) {
1999                    f.write_str(", ");
2000                }
2001                f.write_node(&display::comma_separated(constraints));
2002            }
2003            f.write_str(")");
2004        }
2005        f.write_str(" FROM SOURCE ");
2006        f.write_node(source);
2007        if let Some(external_reference) = external_reference {
2008            f.write_str(" (REFERENCE = ");
2009            f.write_node(external_reference);
2010            f.write_str(")");
2011        }
2012
2013        if let Some(format) = &format {
2014            f.write_str(" ");
2015            f.write_node(format);
2016        }
2017        if !include_metadata.is_empty() {
2018            f.write_str(" INCLUDE ");
2019            f.write_node(&display::comma_separated(include_metadata));
2020        }
2021        if let Some(envelope) = &envelope {
2022            f.write_str(" ENVELOPE ");
2023            f.write_node(envelope);
2024        }
2025        if !with_options.is_empty() {
2026            f.write_str(" WITH (");
2027            f.write_node(&display::comma_separated(with_options));
2028            f.write_str(")");
2029        }
2030    }
2031}
2032impl_display_t!(CreateTableFromSourceStatement);
2033
2034/// `CREATE INDEX`
2035#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2036pub struct CreateIndexStatement<T: AstInfo> {
2037    /// Optional index name.
2038    pub name: Option<Ident>,
2039    pub in_cluster: Option<T::ClusterName>,
2040    /// `ON` table or view name
2041    pub on_name: T::ItemName,
2042    /// Expressions that form part of the index key. If not included, the
2043    /// key_parts will be inferred from the named object.
2044    pub key_parts: Option<Vec<Expr<T>>>,
2045    pub with_options: Vec<IndexOption<T>>,
2046    pub if_not_exists: bool,
2047}
2048
2049impl<T: AstInfo> AstDisplay for CreateIndexStatement<T> {
2050    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2051        f.write_str("CREATE ");
2052        if self.key_parts.is_none() {
2053            f.write_str("DEFAULT ");
2054        }
2055        f.write_str("INDEX ");
2056        if self.if_not_exists {
2057            f.write_str("IF NOT EXISTS ");
2058        }
2059        if let Some(name) = &self.name {
2060            // A bare `in` index name re-lexes as the start of the optional
2061            // `IN CLUSTER` clause below (`CREATE INDEX in ON …` fails to reparse
2062            // with "Expected ON, found IN"), so force it quoted. `in` is
2063            // legitimately bare in other name positions — e.g. a required
2064            // `CREATE SINK` name — so this is local to the optional-name +
2065            // `IN CLUSTER` ambiguity, not a `can_be_printed_bare` case.
2066            if name.as_str().eq_ignore_ascii_case("in") {
2067                f.write_str("\"");
2068                f.write_str(name.as_str());
2069                f.write_str("\"");
2070            } else {
2071                f.write_node(name);
2072            }
2073            f.write_str(" ");
2074        }
2075        if let Some(cluster) = &self.in_cluster {
2076            f.write_str("IN CLUSTER ");
2077            f.write_node(cluster);
2078            f.write_str(" ");
2079        }
2080        f.write_str("ON ");
2081        f.write_node(&self.on_name);
2082        if let Some(key_parts) = &self.key_parts {
2083            f.write_str(" (");
2084            f.write_node(&display::comma_separated(key_parts));
2085            f.write_str(")");
2086        }
2087        if !self.with_options.is_empty() {
2088            f.write_str(" WITH (");
2089            f.write_node(&display::comma_separated(&self.with_options));
2090            f.write_str(")");
2091        }
2092    }
2093}
2094impl_display_t!(CreateIndexStatement);
2095
2096/// An option in a `CREATE CLUSTER` statement.
2097#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2098pub enum IndexOptionName {
2099    // The `RETAIN HISTORY` option
2100    RetainHistory,
2101}
2102
2103impl AstDisplay for IndexOptionName {
2104    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2105        match self {
2106            IndexOptionName::RetainHistory => {
2107                f.write_str("RETAIN HISTORY");
2108            }
2109        }
2110    }
2111}
2112
2113impl WithOptionName for IndexOptionName {
2114    /// # WARNING
2115    ///
2116    /// Whenever implementing this trait consider very carefully whether or not
2117    /// this value could contain sensitive user data. If you're uncertain, err
2118    /// on the conservative side and return `true`.
2119    fn redact_value(&self) -> bool {
2120        match self {
2121            IndexOptionName::RetainHistory => false,
2122        }
2123    }
2124}
2125
2126#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2127pub struct IndexOption<T: AstInfo> {
2128    pub name: IndexOptionName,
2129    pub value: Option<WithOptionValue<T>>,
2130}
2131impl_display_for_with_option!(IndexOption);
2132
2133/// A `CREATE ROLE` statement.
2134#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2135pub struct CreateRoleStatement {
2136    /// The specified role.
2137    pub name: Ident,
2138    /// Any options that were attached, in the order they were presented.
2139    pub options: Vec<RoleAttribute>,
2140}
2141
2142impl AstDisplay for CreateRoleStatement {
2143    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2144        f.write_str("CREATE ");
2145        f.write_str("ROLE ");
2146        f.write_node(&self.name);
2147        for option in &self.options {
2148            f.write_str(" ");
2149            option.fmt(f)
2150        }
2151    }
2152}
2153impl_display!(CreateRoleStatement);
2154
2155/// Attributes that can be attached to roles.
2156#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2157pub enum RoleAttribute {
2158    /// The `INHERIT` option.
2159    Inherit,
2160    /// The `NOINHERIT` option.
2161    NoInherit,
2162    /// The `PASSWORD` option.
2163    Password(Option<String>),
2164    // The following are not supported, but included to give helpful error messages.
2165    Login,
2166    NoLogin,
2167    SuperUser,
2168    NoSuperUser,
2169    CreateCluster,
2170    NoCreateCluster,
2171    CreateDB,
2172    NoCreateDB,
2173    CreateRole,
2174    NoCreateRole,
2175}
2176
2177impl AstDisplay for RoleAttribute {
2178    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2179        match self {
2180            RoleAttribute::SuperUser => f.write_str("SUPERUSER"),
2181            RoleAttribute::NoSuperUser => f.write_str("NOSUPERUSER"),
2182            RoleAttribute::Login => f.write_str("LOGIN"),
2183            RoleAttribute::NoLogin => f.write_str("NOLOGIN"),
2184            RoleAttribute::Inherit => f.write_str("INHERIT"),
2185            RoleAttribute::NoInherit => f.write_str("NOINHERIT"),
2186            RoleAttribute::CreateCluster => f.write_str("CREATECLUSTER"),
2187            RoleAttribute::NoCreateCluster => f.write_str("NOCREATECLUSTER"),
2188            RoleAttribute::CreateDB => f.write_str("CREATEDB"),
2189            RoleAttribute::NoCreateDB => f.write_str("NOCREATEDB"),
2190            RoleAttribute::CreateRole => f.write_str("CREATEROLE"),
2191            RoleAttribute::NoCreateRole => f.write_str("NOCREATEROLE"),
2192            // `PASSWORD NULL` removes the password and carries no secret, so
2193            // print it verbatim. A `PASSWORD '<secret>'` is always redacted (in
2194            // every mode, matching the prior behavior) — but as a *parseable*
2195            // placeholder string, not a bare `PASSWORD`, which fails to reparse
2196            // (the grammar requires `NULL` or a string literal after `PASSWORD`).
2197            RoleAttribute::Password(None) => f.write_str("PASSWORD NULL"),
2198            RoleAttribute::Password(Some(_)) => f.write_str("PASSWORD '<REDACTED>'"),
2199        }
2200    }
2201}
2202impl_display!(RoleAttribute);
2203
2204/// `ALTER ROLE role_name [SET | RESET] ...`
2205#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2206pub enum SetRoleVar {
2207    /// `SET name TO value`
2208    Set { name: Ident, value: SetVariableTo },
2209    /// `RESET name`
2210    Reset { name: Ident },
2211}
2212
2213impl AstDisplay for SetRoleVar {
2214    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2215        match self {
2216            SetRoleVar::Set { name, value } => {
2217                f.write_str("SET ");
2218                f.write_node(name);
2219                f.write_str(" = ");
2220                f.write_node(value);
2221            }
2222            SetRoleVar::Reset { name } => {
2223                f.write_str("RESET ");
2224                f.write_node(name);
2225            }
2226        }
2227    }
2228}
2229impl_display!(SetRoleVar);
2230
2231/// AN `ALTER NETWORK POLICY` statement.
2232#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2233pub struct AlterNetworkPolicyStatement<T: AstInfo> {
2234    /// The specified Network Policy.
2235    pub name: Ident,
2236    /// Any options that were attached, in the order they were presented.
2237    pub options: Vec<NetworkPolicyOption<T>>,
2238}
2239
2240impl<T: AstInfo> AstDisplay for AlterNetworkPolicyStatement<T> {
2241    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2242        f.write_str("ALTER ");
2243        f.write_str("NETWORK POLICY ");
2244        f.write_node(&self.name);
2245        f.write_str(" SET (");
2246        f.write_node(&display::comma_separated(&self.options));
2247        f.write_str(" )");
2248    }
2249}
2250impl_display_t!(AlterNetworkPolicyStatement);
2251
2252/// A `CREATE NETWORK POLICY` statement.
2253#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2254pub struct CreateNetworkPolicyStatement<T: AstInfo> {
2255    /// The specified network policy.
2256    pub name: Ident,
2257    /// Any options that were attached, in the order they were presented.
2258    pub options: Vec<NetworkPolicyOption<T>>,
2259}
2260
2261impl<T: AstInfo> AstDisplay for CreateNetworkPolicyStatement<T> {
2262    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2263        f.write_str("CREATE ");
2264        f.write_str("NETWORK POLICY ");
2265        f.write_node(&self.name);
2266        f.write_str(" (");
2267        f.write_node(&display::comma_separated(&self.options));
2268        f.write_str(" )");
2269    }
2270}
2271impl_display_t!(CreateNetworkPolicyStatement);
2272
2273#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2274pub struct NetworkPolicyOption<T: AstInfo> {
2275    pub name: NetworkPolicyOptionName,
2276    pub value: Option<WithOptionValue<T>>,
2277}
2278
2279#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2280pub enum NetworkPolicyOptionName {
2281    Rules,
2282}
2283
2284impl WithOptionName for NetworkPolicyOptionName {
2285    /// # WARNING
2286    ///
2287    /// Whenever implementing this trait consider very carefully whether or not
2288    /// this value could contain sensitive user data. If you're uncertain, err
2289    /// on the conservative side and return `true`.
2290    fn redact_value(&self) -> bool {
2291        match self {
2292            NetworkPolicyOptionName::Rules => false,
2293        }
2294    }
2295}
2296
2297impl AstDisplay for NetworkPolicyOptionName {
2298    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2299        match self {
2300            NetworkPolicyOptionName::Rules => f.write_str("RULES"),
2301        }
2302    }
2303}
2304impl_display_for_with_option!(NetworkPolicyOption);
2305
2306#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2307pub struct NetworkPolicyRuleDefinition<T: AstInfo> {
2308    pub name: Ident,
2309    pub options: Vec<NetworkPolicyRuleOption<T>>,
2310}
2311
2312impl<T: AstInfo> AstDisplay for NetworkPolicyRuleDefinition<T> {
2313    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2314        f.write_node(&self.name);
2315        f.write_str(" (");
2316        f.write_node(&display::comma_separated(&self.options));
2317        f.write_str(" )");
2318    }
2319}
2320
2321#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2322pub struct NetworkPolicyRuleOption<T: AstInfo> {
2323    pub name: NetworkPolicyRuleOptionName,
2324    pub value: Option<WithOptionValue<T>>,
2325}
2326
2327#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2328pub enum NetworkPolicyRuleOptionName {
2329    Direction,
2330    Action,
2331    Address,
2332}
2333
2334impl WithOptionName for NetworkPolicyRuleOptionName {
2335    /// # WARNING
2336    ///
2337    /// Whenever implementing this trait consider very carefully whether or not
2338    /// this value could contain sensitive user data. If you're uncertain, err
2339    /// on the conservative side and return `true`.
2340    fn redact_value(&self) -> bool {
2341        match self {
2342            NetworkPolicyRuleOptionName::Direction
2343            | NetworkPolicyRuleOptionName::Action
2344            | NetworkPolicyRuleOptionName::Address => false,
2345        }
2346    }
2347}
2348
2349impl AstDisplay for NetworkPolicyRuleOptionName {
2350    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2351        match self {
2352            NetworkPolicyRuleOptionName::Direction => f.write_str("DIRECTION"),
2353            NetworkPolicyRuleOptionName::Action => f.write_str("ACTION"),
2354            NetworkPolicyRuleOptionName::Address => f.write_str("ADDRESS"),
2355        }
2356    }
2357}
2358
2359impl_display_for_with_option!(NetworkPolicyRuleOption);
2360
2361/// A `CREATE QUERY POLICY` statement. Query policies have a flat namespace.
2362#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2363pub struct CreateQueryPolicyStatement<T: AstInfo> {
2364    pub name: Ident,
2365    pub options: Vec<QueryPolicyOption<T>>,
2366}
2367
2368impl<T: AstInfo> AstDisplay for CreateQueryPolicyStatement<T> {
2369    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2370        f.write_str("CREATE QUERY POLICY ");
2371        f.write_node(&self.name);
2372        f.write_str(" (");
2373        f.write_node(&display::comma_separated(&self.options));
2374        f.write_str(")");
2375    }
2376}
2377impl_display_t!(CreateQueryPolicyStatement);
2378
2379/// An `ALTER QUERY POLICY ... SET` statement.
2380#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2381pub struct AlterQueryPolicyStatement<T: AstInfo> {
2382    pub name: Ident,
2383    pub options: Vec<QueryPolicyOption<T>>,
2384}
2385
2386impl<T: AstInfo> AstDisplay for AlterQueryPolicyStatement<T> {
2387    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2388        f.write_str("ALTER QUERY POLICY ");
2389        f.write_node(&self.name);
2390        f.write_str(" SET (");
2391        f.write_node(&display::comma_separated(&self.options));
2392        f.write_str(")");
2393    }
2394}
2395impl_display_t!(AlterQueryPolicyStatement);
2396
2397#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2398pub enum QueryPolicyOption<T: AstInfo> {
2399    Mode(Value),
2400    Rules(Vec<QueryPolicyRuleDefinition<T>>),
2401}
2402
2403impl<T: AstInfo> AstDisplay for QueryPolicyOption<T> {
2404    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2405        match self {
2406            Self::Mode(value) => {
2407                f.write_str("MODE = ");
2408                f.write_node(value);
2409            }
2410            Self::Rules(rules) => {
2411                f.write_str("RULES (");
2412                f.write_node(&display::comma_separated(rules));
2413                f.write_str(")");
2414            }
2415        }
2416    }
2417}
2418
2419#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2420pub struct QueryPolicyRuleDefinition<T: AstInfo> {
2421    pub name: Ident,
2422    pub options: Vec<QueryPolicyRuleOption<T>>,
2423}
2424
2425impl<T: AstInfo> AstDisplay for QueryPolicyRuleDefinition<T> {
2426    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2427        f.write_node(&self.name);
2428        f.write_str(" (");
2429        f.write_node(&display::comma_separated(&self.options));
2430        f.write_str(")");
2431    }
2432}
2433
2434#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2435pub struct QueryPolicyRuleOption<T: AstInfo> {
2436    pub name: QueryPolicyRuleOptionName,
2437    pub value: Option<WithOptionValue<T>>,
2438}
2439
2440#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2441pub enum QueryPolicyRuleOptionName {
2442    Action,
2443    Metric,
2444    Value,
2445}
2446
2447impl AstDisplay for QueryPolicyRuleOptionName {
2448    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2449        f.write_str(match self {
2450            Self::Action => "ACTION",
2451            Self::Metric => "METRIC",
2452            Self::Value => "VALUE",
2453        });
2454    }
2455}
2456
2457impl WithOptionName for QueryPolicyRuleOptionName {
2458    fn redact_value(&self) -> bool {
2459        false
2460    }
2461}
2462impl_display_for_with_option!(QueryPolicyRuleOption);
2463
2464/// A `CREATE SECRET` statement.
2465#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2466pub struct CreateSecretStatement<T: AstInfo> {
2467    pub name: UnresolvedItemName,
2468    pub if_not_exists: bool,
2469    pub value: Expr<T>,
2470}
2471
2472impl<T: AstInfo> AstDisplay for CreateSecretStatement<T> {
2473    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2474        f.write_str("CREATE SECRET ");
2475        if self.if_not_exists {
2476            f.write_str("IF NOT EXISTS ");
2477        }
2478        f.write_node(&self.name);
2479        f.write_str(" AS ");
2480
2481        if f.redacted() {
2482            f.write_str("'<REDACTED>'");
2483        } else {
2484            f.write_node(&self.value);
2485        }
2486    }
2487}
2488impl_display_t!(CreateSecretStatement);
2489
2490/// `CREATE TYPE ..`
2491#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2492pub struct CreateTypeStatement<T: AstInfo> {
2493    /// Name of the created type.
2494    pub name: UnresolvedItemName,
2495    /// The new type's "base type".
2496    pub as_type: CreateTypeAs<T>,
2497}
2498
2499impl<T: AstInfo> AstDisplay for CreateTypeStatement<T> {
2500    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2501        f.write_str("CREATE TYPE ");
2502        f.write_node(&self.name);
2503        f.write_str(" AS ");
2504        match &self.as_type {
2505            CreateTypeAs::List { options } => {
2506                f.write_str(&self.as_type);
2507                f.write_str("(");
2508                if !options.is_empty() {
2509                    f.write_node(&display::comma_separated(options));
2510                }
2511                f.write_str(")");
2512            }
2513            CreateTypeAs::Map { options } => {
2514                f.write_str(&self.as_type);
2515                f.write_str("(");
2516                if !options.is_empty() {
2517                    f.write_node(&display::comma_separated(options));
2518                }
2519                f.write_str(")");
2520            }
2521            CreateTypeAs::Record { column_defs } => {
2522                f.write_str("(");
2523                if !column_defs.is_empty() {
2524                    f.write_node(&display::comma_separated(column_defs));
2525                }
2526                f.write_str(")");
2527            }
2528        };
2529    }
2530}
2531impl_display_t!(CreateTypeStatement);
2532
2533#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2534pub enum ClusterOptionName {
2535    /// The `AUTO SCALING STRATEGY [[=] (...)]` option.
2536    AutoScalingStrategy,
2537    /// The `AVAILABILITY ZONES [[=] '[' <values> ']' ]` option.
2538    AvailabilityZones,
2539    /// The `DISK` option.
2540    Disk,
2541    /// The `EXPERIMENTAL ARRANGEMENT COMPRESSION [[=] <enabled>]` option.
2542    ExperimentalArrangementCompression,
2543    /// The `INTROSPECTION INTERVAL [[=] <interval>]` option.
2544    IntrospectionInterval,
2545    /// The `INTROSPECTION DEBUGGING [[=] <enabled>]` option.
2546    IntrospectionDebugging,
2547    /// The `MANAGED` option.
2548    Managed,
2549    /// The `REPLICAS` option.
2550    Replicas,
2551    /// The `REPLICATION FACTOR` option.
2552    ReplicationFactor,
2553    /// The `SIZE` option.
2554    Size,
2555    /// The `SCHEDULE` option.
2556    Schedule,
2557    /// The `WORKLOAD CLASS` option.
2558    WorkloadClass,
2559    /// The durable query-policy attachment.
2560    QueryPolicy,
2561}
2562
2563impl AstDisplay for ClusterOptionName {
2564    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2565        match self {
2566            ClusterOptionName::AutoScalingStrategy => f.write_str("AUTO SCALING STRATEGY"),
2567            ClusterOptionName::AvailabilityZones => f.write_str("AVAILABILITY ZONES"),
2568            ClusterOptionName::Disk => f.write_str("DISK"),
2569            ClusterOptionName::ExperimentalArrangementCompression => {
2570                f.write_str("EXPERIMENTAL ARRANGEMENT COMPRESSION")
2571            }
2572            ClusterOptionName::IntrospectionDebugging => f.write_str("INTROSPECTION DEBUGGING"),
2573            ClusterOptionName::IntrospectionInterval => f.write_str("INTROSPECTION INTERVAL"),
2574            ClusterOptionName::Managed => f.write_str("MANAGED"),
2575            ClusterOptionName::Replicas => f.write_str("REPLICAS"),
2576            ClusterOptionName::ReplicationFactor => f.write_str("REPLICATION FACTOR"),
2577            ClusterOptionName::Size => f.write_str("SIZE"),
2578            ClusterOptionName::Schedule => f.write_str("SCHEDULE"),
2579            ClusterOptionName::WorkloadClass => f.write_str("WORKLOAD CLASS"),
2580            ClusterOptionName::QueryPolicy => f.write_str("QUERY POLICY"),
2581        }
2582    }
2583}
2584
2585impl WithOptionName for ClusterOptionName {
2586    /// # WARNING
2587    ///
2588    /// Whenever implementing this trait consider very carefully whether or not
2589    /// this value could contain sensitive user data. If you're uncertain, err
2590    /// on the conservative side and return `true`.
2591    fn redact_value(&self) -> bool {
2592        match self {
2593            ClusterOptionName::AutoScalingStrategy
2594            | ClusterOptionName::AvailabilityZones
2595            | ClusterOptionName::Disk
2596            | ClusterOptionName::ExperimentalArrangementCompression
2597            | ClusterOptionName::IntrospectionDebugging
2598            | ClusterOptionName::IntrospectionInterval
2599            | ClusterOptionName::Managed
2600            | ClusterOptionName::Replicas
2601            | ClusterOptionName::ReplicationFactor
2602            | ClusterOptionName::Size
2603            | ClusterOptionName::Schedule
2604            | ClusterOptionName::WorkloadClass
2605            | ClusterOptionName::QueryPolicy => false,
2606        }
2607    }
2608}
2609
2610#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2611/// An option in a `CREATE CLUSTER` statement.
2612pub struct ClusterOption<T: AstInfo> {
2613    pub name: ClusterOptionName,
2614    pub value: Option<WithOptionValue<T>>,
2615}
2616impl_display_for_with_option!(ClusterOption);
2617
2618#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2619pub enum ClusterAlterUntilReadyOptionName {
2620    Timeout,
2621    OnTimeout,
2622}
2623
2624impl AstDisplay for ClusterAlterUntilReadyOptionName {
2625    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2626        match self {
2627            Self::Timeout => f.write_str("TIMEOUT"),
2628            Self::OnTimeout => f.write_str("ON TIMEOUT"),
2629        }
2630    }
2631}
2632
2633impl WithOptionName for ClusterAlterUntilReadyOptionName {
2634    /// # WARNING
2635    ///
2636    /// Whenever implementing this trait consider very carefully whether or not
2637    /// this value could contain sensitive user data. If you're uncertain, err
2638    /// on the conservative side and return `true`.
2639    fn redact_value(&self) -> bool {
2640        match self {
2641            ClusterAlterUntilReadyOptionName::Timeout
2642            | ClusterAlterUntilReadyOptionName::OnTimeout => false,
2643        }
2644    }
2645}
2646
2647#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2648pub struct ClusterAlterUntilReadyOption<T: AstInfo> {
2649    pub name: ClusterAlterUntilReadyOptionName,
2650    pub value: Option<WithOptionValue<T>>,
2651}
2652impl_display_for_with_option!(ClusterAlterUntilReadyOption);
2653
2654#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2655pub enum ClusterAlterOptionName {
2656    Wait,
2657}
2658
2659impl AstDisplay for ClusterAlterOptionName {
2660    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2661        match self {
2662            ClusterAlterOptionName::Wait => f.write_str("WAIT"),
2663        }
2664    }
2665}
2666
2667impl WithOptionName for ClusterAlterOptionName {
2668    /// # WARNING
2669    ///
2670    /// Whenever implementing this trait consider very carefully whether or not
2671    /// this value could contain sensitive user data. If you're uncertain, err
2672    /// on the conservative side and return `true`.
2673    fn redact_value(&self) -> bool {
2674        match self {
2675            ClusterAlterOptionName::Wait => false,
2676        }
2677    }
2678}
2679
2680#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2681pub enum ClusterAlterOptionValue<T: AstInfo> {
2682    For(Value),
2683    UntilReady(Vec<ClusterAlterUntilReadyOption<T>>),
2684}
2685
2686impl<T: AstInfo> AstDisplay for ClusterAlterOptionValue<T> {
2687    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2688        match self {
2689            ClusterAlterOptionValue::For(duration) => {
2690                f.write_str("FOR ");
2691                f.write_node(duration);
2692            }
2693            ClusterAlterOptionValue::UntilReady(options) => {
2694                f.write_str("UNTIL READY (");
2695                f.write_node(&display::comma_separated(options));
2696                f.write_str(")");
2697            }
2698        }
2699    }
2700}
2701
2702#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2703/// An option in a `ALTER CLUSTER... WITH` statement.
2704pub struct ClusterAlterOption<T: AstInfo> {
2705    pub name: ClusterAlterOptionName,
2706    pub value: Option<WithOptionValue<T>>,
2707}
2708
2709impl_display_for_with_option!(ClusterAlterOption);
2710
2711// Note: the `AstDisplay` implementation and `Parser::parse_` method for this
2712// enum are generated automatically by this crate's `build.rs`.
2713#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2714pub enum ClusterFeatureName {
2715    ReoptimizeImportedViews,
2716    EnableNewOuterJoinLowering,
2717    EnableEagerDeltaJoins,
2718    EnableVariadicLeftJoinLowering,
2719    EnableLetrecFixpointAnalysis,
2720    EnableJoinPrioritizeArranged,
2721    EnableProjectionPushdownAfterRelationCse,
2722    EnableUnionCancellationAfterRelationCse,
2723}
2724
2725impl WithOptionName for ClusterFeatureName {
2726    /// # WARNING
2727    ///
2728    /// Whenever implementing this trait consider very carefully whether or not
2729    /// this value could contain sensitive user data. If you're uncertain, err
2730    /// on the conservative side and return `true`.
2731    fn redact_value(&self) -> bool {
2732        match self {
2733            Self::ReoptimizeImportedViews
2734            | Self::EnableNewOuterJoinLowering
2735            | Self::EnableEagerDeltaJoins
2736            | Self::EnableVariadicLeftJoinLowering
2737            | Self::EnableLetrecFixpointAnalysis
2738            | Self::EnableJoinPrioritizeArranged
2739            | Self::EnableProjectionPushdownAfterRelationCse
2740            | Self::EnableUnionCancellationAfterRelationCse => false,
2741        }
2742    }
2743}
2744
2745#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2746pub struct ClusterFeature<T: AstInfo> {
2747    pub name: ClusterFeatureName,
2748    pub value: Option<WithOptionValue<T>>,
2749}
2750impl_display_for_with_option!(ClusterFeature);
2751
2752/// `CREATE CLUSTER ..`
2753#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2754pub struct CreateClusterStatement<T: AstInfo> {
2755    /// Name of the created cluster.
2756    pub name: Ident,
2757    /// The comma-separated options.
2758    pub options: Vec<ClusterOption<T>>,
2759    /// The comma-separated features enabled on the cluster.
2760    pub features: Vec<ClusterFeature<T>>,
2761    pub if_not_exists: bool,
2762}
2763
2764impl<T: AstInfo> AstDisplay for CreateClusterStatement<T> {
2765    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2766        f.write_str("CREATE CLUSTER ");
2767        if self.if_not_exists {
2768            f.write_str("IF NOT EXISTS ");
2769        }
2770        f.write_node(&self.name);
2771        if !self.options.is_empty() {
2772            f.write_str(" (");
2773            f.write_node(&display::comma_separated(&self.options));
2774            f.write_str(")");
2775        }
2776        if !self.features.is_empty() {
2777            f.write_str(" FEATURES (");
2778            f.write_node(&display::comma_separated(&self.features));
2779            f.write_str(")");
2780        }
2781    }
2782}
2783impl_display_t!(CreateClusterStatement);
2784
2785#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2786pub struct ReplicaDefinition<T: AstInfo> {
2787    /// Name of the created replica.
2788    pub name: Ident,
2789    /// The comma-separated options.
2790    pub options: Vec<ReplicaOption<T>>,
2791}
2792
2793// Note that this display is meant for replicas defined inline when creating
2794// clusters.
2795impl<T: AstInfo> AstDisplay for ReplicaDefinition<T> {
2796    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2797        f.write_node(&self.name);
2798        f.write_str(" (");
2799        f.write_node(&display::comma_separated(&self.options));
2800        f.write_str(")");
2801    }
2802}
2803impl_display_t!(ReplicaDefinition);
2804
2805#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2806pub enum AlterClusterAction<T: AstInfo> {
2807    SetOptions {
2808        options: Vec<ClusterOption<T>>,
2809        with_options: Vec<ClusterAlterOption<T>>,
2810    },
2811    ResetOptions(Vec<ClusterOptionName>),
2812}
2813
2814/// `ALTER CLUSTER .. SET ...`
2815#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2816pub struct AlterClusterStatement<T: AstInfo> {
2817    /// The `IF EXISTS` option.
2818    pub if_exists: bool,
2819    /// Name of the altered cluster.
2820    pub name: Ident,
2821    /// The action.
2822    pub action: AlterClusterAction<T>,
2823}
2824
2825impl<T: AstInfo> AstDisplay for AlterClusterStatement<T> {
2826    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2827        f.write_str("ALTER CLUSTER ");
2828        if self.if_exists {
2829            f.write_str("IF EXISTS ");
2830        }
2831        f.write_node(&self.name);
2832        f.write_str(" ");
2833        match &self.action {
2834            AlterClusterAction::SetOptions {
2835                options,
2836                with_options,
2837            } => {
2838                f.write_str("SET (");
2839                f.write_node(&display::comma_separated(options));
2840                f.write_str(")");
2841                if !with_options.is_empty() {
2842                    f.write_str(" WITH (");
2843                    f.write_node(&display::comma_separated(with_options));
2844                    f.write_str(")");
2845                }
2846            }
2847            AlterClusterAction::ResetOptions(options) => {
2848                f.write_str("RESET (");
2849                f.write_node(&display::comma_separated(options));
2850                f.write_str(")");
2851            }
2852        }
2853    }
2854}
2855impl_display_t!(AlterClusterStatement);
2856
2857/// `CREATE CLUSTER REPLICA ..`
2858#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2859pub struct CreateClusterReplicaStatement<T: AstInfo> {
2860    /// Name of the replica's cluster.
2861    pub of_cluster: Ident,
2862    /// The replica's definition.
2863    pub definition: ReplicaDefinition<T>,
2864    pub if_not_exists: bool,
2865}
2866
2867impl<T: AstInfo> AstDisplay for CreateClusterReplicaStatement<T> {
2868    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2869        f.write_str("CREATE CLUSTER REPLICA ");
2870        if self.if_not_exists {
2871            f.write_str("IF NOT EXISTS ");
2872        }
2873        f.write_node(&self.of_cluster);
2874        f.write_str(".");
2875        f.write_node(&self.definition.name);
2876        f.write_str(" (");
2877        f.write_node(&display::comma_separated(&self.definition.options));
2878        f.write_str(")");
2879    }
2880}
2881impl_display_t!(CreateClusterReplicaStatement);
2882
2883#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2884pub enum ReplicaOptionName {
2885    /// The `BILLED AS [=] <value>` option.
2886    BilledAs,
2887    /// The `SIZE [[=] <size>]` option.
2888    Size,
2889    /// The `AVAILABILITY ZONE [[=] <id>]` option.
2890    AvailabilityZone,
2891    /// The `STORAGE ADDRESSES` option.
2892    StorageAddresses,
2893    /// The `STORAGECTL ADDRESSES` option.
2894    StoragectlAddresses,
2895    /// The `COMPUTECTL ADDRESSES` option.
2896    ComputectlAddresses,
2897    /// The `COMPUTE ADDRESSES` option.
2898    ComputeAddresses,
2899    /// The `WORKERS` option.
2900    Workers,
2901    /// The `INTERNAL` option.
2902    Internal,
2903    /// The `INTROSPECTION INTERVAL [[=] <interval>]` option.
2904    IntrospectionInterval,
2905    /// The `INTROSPECTION DEBUGGING [[=] <enabled>]` option.
2906    IntrospectionDebugging,
2907    /// The `DISK [[=] <enabled>]` option.
2908    Disk,
2909    /// The `EXPERIMENTAL ARRANGEMENT COMPRESSION [[=] <enabled>]` option.
2910    ExperimentalArrangementCompression,
2911}
2912
2913impl AstDisplay for ReplicaOptionName {
2914    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2915        match self {
2916            ReplicaOptionName::BilledAs => f.write_str("BILLED AS"),
2917            ReplicaOptionName::Size => f.write_str("SIZE"),
2918            ReplicaOptionName::AvailabilityZone => f.write_str("AVAILABILITY ZONE"),
2919            ReplicaOptionName::StorageAddresses => f.write_str("STORAGE ADDRESSES"),
2920            ReplicaOptionName::StoragectlAddresses => f.write_str("STORAGECTL ADDRESSES"),
2921            ReplicaOptionName::ComputectlAddresses => f.write_str("COMPUTECTL ADDRESSES"),
2922            ReplicaOptionName::ComputeAddresses => f.write_str("COMPUTE ADDRESSES"),
2923            ReplicaOptionName::Workers => f.write_str("WORKERS"),
2924            ReplicaOptionName::Internal => f.write_str("INTERNAL"),
2925            ReplicaOptionName::IntrospectionInterval => f.write_str("INTROSPECTION INTERVAL"),
2926            ReplicaOptionName::IntrospectionDebugging => f.write_str("INTROSPECTION DEBUGGING"),
2927            ReplicaOptionName::Disk => f.write_str("DISK"),
2928            ReplicaOptionName::ExperimentalArrangementCompression => {
2929                f.write_str("EXPERIMENTAL ARRANGEMENT COMPRESSION")
2930            }
2931        }
2932    }
2933}
2934
2935impl WithOptionName for ReplicaOptionName {
2936    /// # WARNING
2937    ///
2938    /// Whenever implementing this trait consider very carefully whether or not
2939    /// this value could contain sensitive user data. If you're uncertain, err
2940    /// on the conservative side and return `true`.
2941    fn redact_value(&self) -> bool {
2942        match self {
2943            ReplicaOptionName::BilledAs
2944            | ReplicaOptionName::Size
2945            | ReplicaOptionName::AvailabilityZone
2946            | ReplicaOptionName::StorageAddresses
2947            | ReplicaOptionName::StoragectlAddresses
2948            | ReplicaOptionName::ComputectlAddresses
2949            | ReplicaOptionName::ComputeAddresses
2950            | ReplicaOptionName::Workers
2951            | ReplicaOptionName::Internal
2952            | ReplicaOptionName::IntrospectionInterval
2953            | ReplicaOptionName::IntrospectionDebugging
2954            | ReplicaOptionName::Disk
2955            | ReplicaOptionName::ExperimentalArrangementCompression => false,
2956        }
2957    }
2958}
2959
2960#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2961/// An option in a `CREATE CLUSTER REPLICA` statement.
2962pub struct ReplicaOption<T: AstInfo> {
2963    pub name: ReplicaOptionName,
2964    pub value: Option<WithOptionValue<T>>,
2965}
2966impl_display_for_with_option!(ReplicaOption);
2967
2968/// `CREATE TYPE .. AS <TYPE>`
2969#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2970pub enum CreateTypeAs<T: AstInfo> {
2971    List {
2972        options: Vec<CreateTypeListOption<T>>,
2973    },
2974    Map {
2975        options: Vec<CreateTypeMapOption<T>>,
2976    },
2977    Record {
2978        column_defs: Vec<ColumnDef<T>>,
2979    },
2980}
2981
2982impl<T: AstInfo> AstDisplay for CreateTypeAs<T> {
2983    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
2984        match self {
2985            CreateTypeAs::List { .. } => f.write_str("LIST "),
2986            CreateTypeAs::Map { .. } => f.write_str("MAP "),
2987            CreateTypeAs::Record { .. } => f.write_str("RECORD "),
2988        }
2989    }
2990}
2991impl_display_t!(CreateTypeAs);
2992
2993#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2994pub enum CreateTypeListOptionName {
2995    ElementType,
2996}
2997
2998impl AstDisplay for CreateTypeListOptionName {
2999    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3000        f.write_str(match self {
3001            CreateTypeListOptionName::ElementType => "ELEMENT TYPE",
3002        })
3003    }
3004}
3005
3006impl WithOptionName for CreateTypeListOptionName {
3007    /// # WARNING
3008    ///
3009    /// Whenever implementing this trait consider very carefully whether or not
3010    /// this value could contain sensitive user data. If you're uncertain, err
3011    /// on the conservative side and return `true`.
3012    fn redact_value(&self) -> bool {
3013        match self {
3014            CreateTypeListOptionName::ElementType => false,
3015        }
3016    }
3017}
3018
3019#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3020pub struct CreateTypeListOption<T: AstInfo> {
3021    pub name: CreateTypeListOptionName,
3022    pub value: Option<WithOptionValue<T>>,
3023}
3024impl_display_for_with_option!(CreateTypeListOption);
3025
3026#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3027pub enum CreateTypeMapOptionName {
3028    KeyType,
3029    ValueType,
3030}
3031
3032impl AstDisplay for CreateTypeMapOptionName {
3033    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3034        f.write_str(match self {
3035            CreateTypeMapOptionName::KeyType => "KEY TYPE",
3036            CreateTypeMapOptionName::ValueType => "VALUE TYPE",
3037        })
3038    }
3039}
3040
3041impl WithOptionName for CreateTypeMapOptionName {
3042    /// # WARNING
3043    ///
3044    /// Whenever implementing this trait consider very carefully whether or not
3045    /// this value could contain sensitive user data. If you're uncertain, err
3046    /// on the conservative side and return `true`.
3047    fn redact_value(&self) -> bool {
3048        match self {
3049            CreateTypeMapOptionName::KeyType | CreateTypeMapOptionName::ValueType => false,
3050        }
3051    }
3052}
3053
3054#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3055pub struct CreateTypeMapOption<T: AstInfo> {
3056    pub name: CreateTypeMapOptionName,
3057    pub value: Option<WithOptionValue<T>>,
3058}
3059impl_display_for_with_option!(CreateTypeMapOption);
3060
3061/// `ALTER <OBJECT> ... OWNER TO`
3062#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3063pub struct AlterOwnerStatement<T: AstInfo> {
3064    pub object_type: ObjectType,
3065    pub if_exists: bool,
3066    pub name: UnresolvedObjectName,
3067    pub new_owner: T::RoleName,
3068}
3069
3070impl<T: AstInfo> AstDisplay for AlterOwnerStatement<T> {
3071    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3072        f.write_str("ALTER ");
3073        f.write_node(&self.object_type);
3074        f.write_str(" ");
3075        if self.if_exists {
3076            f.write_str("IF EXISTS ");
3077        }
3078        f.write_node(&self.name);
3079        f.write_str(" OWNER TO ");
3080        f.write_node(&self.new_owner);
3081    }
3082}
3083impl_display_t!(AlterOwnerStatement);
3084
3085/// `ALTER <OBJECT> ... RENAME TO`
3086#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3087pub struct AlterObjectRenameStatement {
3088    pub object_type: ObjectType,
3089    pub if_exists: bool,
3090    pub name: UnresolvedObjectName,
3091    pub to_item_name: Ident,
3092}
3093
3094impl AstDisplay for AlterObjectRenameStatement {
3095    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3096        f.write_str("ALTER ");
3097        f.write_node(&self.object_type);
3098        f.write_str(" ");
3099        if self.if_exists {
3100            f.write_str("IF EXISTS ");
3101        }
3102        f.write_node(&self.name);
3103        f.write_str(" RENAME TO ");
3104        f.write_node(&self.to_item_name);
3105    }
3106}
3107impl_display!(AlterObjectRenameStatement);
3108
3109/// `ALTER <OBJECT> ... [RE]SET (RETAIN HISTORY [FOR ...])`
3110#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3111pub struct AlterRetainHistoryStatement<T: AstInfo> {
3112    pub object_type: ObjectType,
3113    pub if_exists: bool,
3114    pub name: UnresolvedObjectName,
3115    pub history: Option<WithOptionValue<T>>,
3116}
3117
3118impl<T: AstInfo> AstDisplay for AlterRetainHistoryStatement<T> {
3119    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3120        f.write_str("ALTER ");
3121        f.write_node(&self.object_type);
3122        f.write_str(" ");
3123        if self.if_exists {
3124            f.write_str("IF EXISTS ");
3125        }
3126        f.write_node(&self.name);
3127        if let Some(history) = &self.history {
3128            f.write_str(" SET (RETAIN HISTORY ");
3129            f.write_node(history);
3130        } else {
3131            f.write_str(" RESET (RETAIN HISTORY");
3132        }
3133        f.write_str(")");
3134    }
3135}
3136impl_display_t!(AlterRetainHistoryStatement);
3137
3138/// `ALTER <OBJECT> SWAP ...`
3139#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3140pub struct AlterObjectSwapStatement {
3141    pub object_type: ObjectType,
3142    pub if_exists: bool,
3143    pub name_a: UnresolvedObjectName,
3144    pub name_b: Ident,
3145}
3146
3147impl AstDisplay for AlterObjectSwapStatement {
3148    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3149        f.write_str("ALTER ");
3150
3151        f.write_node(&self.object_type);
3152        f.write_str(" ");
3153        if self.if_exists {
3154            f.write_str("IF EXISTS ");
3155        }
3156        f.write_node(&self.name_a);
3157
3158        f.write_str(" SWAP WITH ");
3159        f.write_node(&self.name_b);
3160    }
3161}
3162impl_display!(AlterObjectSwapStatement);
3163
3164#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3165pub enum AlterIndexAction<T: AstInfo> {
3166    SetOptions(Vec<IndexOption<T>>),
3167    ResetOptions(Vec<IndexOptionName>),
3168}
3169
3170/// `ALTER INDEX ... {RESET, SET}`
3171#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3172pub struct AlterIndexStatement<T: AstInfo> {
3173    pub index_name: UnresolvedItemName,
3174    pub if_exists: bool,
3175    pub action: AlterIndexAction<T>,
3176}
3177
3178impl<T: AstInfo> AstDisplay for AlterIndexStatement<T> {
3179    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3180        f.write_str("ALTER INDEX ");
3181        if self.if_exists {
3182            f.write_str("IF EXISTS ");
3183        }
3184        f.write_node(&self.index_name);
3185        f.write_str(" ");
3186
3187        match &self.action {
3188            AlterIndexAction::SetOptions(options) => {
3189                f.write_str("SET (");
3190                f.write_node(&display::comma_separated(options));
3191                f.write_str(")");
3192            }
3193            AlterIndexAction::ResetOptions(options) => {
3194                f.write_str("RESET (");
3195                f.write_node(&display::comma_separated(options));
3196                f.write_str(")");
3197            }
3198        }
3199    }
3200}
3201
3202impl_display_t!(AlterIndexStatement);
3203
3204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3205pub enum AlterSinkAction<T: AstInfo> {
3206    SetOptions(Vec<CreateSinkOption<T>>),
3207    ResetOptions(Vec<CreateSinkOptionName>),
3208    ChangeRelation(T::ItemName),
3209}
3210
3211#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3212pub struct AlterSinkStatement<T: AstInfo> {
3213    pub sink_name: UnresolvedItemName,
3214    pub if_exists: bool,
3215    pub action: AlterSinkAction<T>,
3216}
3217
3218impl<T: AstInfo> AstDisplay for AlterSinkStatement<T> {
3219    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3220        f.write_str("ALTER SINK ");
3221        if self.if_exists {
3222            f.write_str("IF EXISTS ");
3223        }
3224        f.write_node(&self.sink_name);
3225        f.write_str(" ");
3226
3227        match &self.action {
3228            AlterSinkAction::ChangeRelation(from) => {
3229                f.write_str("SET FROM ");
3230                f.write_node(from);
3231            }
3232            AlterSinkAction::SetOptions(options) => {
3233                f.write_str("SET (");
3234                f.write_node(&display::comma_separated(options));
3235                f.write_str(")");
3236            }
3237            AlterSinkAction::ResetOptions(options) => {
3238                f.write_str("RESET (");
3239                f.write_node(&display::comma_separated(options));
3240                f.write_str(")");
3241            }
3242        }
3243    }
3244}
3245
3246#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3247pub enum AlterSourceAddSubsourceOptionName {
3248    /// Columns whose types you want to unconditionally format as text
3249    TextColumns,
3250    /// Columns you want to ignore when ingesting data
3251    ExcludeColumns,
3252    /// Updated `DETAILS` for an ingestion, e.g.
3253    /// [`crate::ast::PgConfigOptionName::Details`]
3254    /// or
3255    /// [`crate::ast::MySqlConfigOptionName::Details`].
3256    Details,
3257}
3258
3259impl AstDisplay for AlterSourceAddSubsourceOptionName {
3260    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3261        f.write_str(match self {
3262            AlterSourceAddSubsourceOptionName::TextColumns => "TEXT COLUMNS",
3263            AlterSourceAddSubsourceOptionName::ExcludeColumns => "EXCLUDE COLUMNS",
3264            AlterSourceAddSubsourceOptionName::Details => "DETAILS",
3265        })
3266    }
3267}
3268impl_display!(AlterSourceAddSubsourceOptionName);
3269
3270impl WithOptionName for AlterSourceAddSubsourceOptionName {
3271    /// # WARNING
3272    ///
3273    /// Whenever implementing this trait consider very carefully whether or not
3274    /// this value could contain sensitive user data. If you're uncertain, err
3275    /// on the conservative side and return `true`.
3276    fn redact_value(&self) -> bool {
3277        match self {
3278            AlterSourceAddSubsourceOptionName::Details
3279            | AlterSourceAddSubsourceOptionName::TextColumns
3280            | AlterSourceAddSubsourceOptionName::ExcludeColumns => false,
3281        }
3282    }
3283}
3284
3285#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3286/// An option in an `ALTER SOURCE...ADD SUBSOURCE` statement.
3287pub struct AlterSourceAddSubsourceOption<T: AstInfo> {
3288    pub name: AlterSourceAddSubsourceOptionName,
3289    pub value: Option<WithOptionValue<T>>,
3290}
3291impl_display_for_with_option!(AlterSourceAddSubsourceOption);
3292impl_display_t!(AlterSourceAddSubsourceOption);
3293
3294#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3295pub enum AlterSourceAction<T: AstInfo> {
3296    SetOptions(Vec<CreateSourceOption<T>>),
3297    ResetOptions(Vec<CreateSourceOptionName>),
3298    AddSubsources {
3299        external_references: Vec<ExternalReferenceExport>,
3300        options: Vec<AlterSourceAddSubsourceOption<T>>,
3301    },
3302    DropSubsources {
3303        if_exists: bool,
3304        cascade: bool,
3305        names: Vec<UnresolvedItemName>,
3306    },
3307    RefreshReferences,
3308}
3309
3310impl<T: AstInfo> AstDisplay for AlterSourceAction<T> {
3311    fn fmt<W>(&self, f: &mut AstFormatter<W>)
3312    where
3313        W: fmt::Write,
3314    {
3315        match &self {
3316            AlterSourceAction::SetOptions(options) => {
3317                f.write_str("SET (");
3318                f.write_node(&display::comma_separated(options));
3319                f.write_str(")");
3320            }
3321            AlterSourceAction::ResetOptions(options) => {
3322                f.write_str("RESET (");
3323                f.write_node(&display::comma_separated(options));
3324                f.write_str(")");
3325            }
3326            AlterSourceAction::DropSubsources {
3327                if_exists,
3328                cascade,
3329                names,
3330            } => {
3331                f.write_str("DROP SUBSOURCE ");
3332                if *if_exists {
3333                    f.write_str("IF EXISTS ");
3334                }
3335
3336                f.write_node(&display::comma_separated(names));
3337
3338                if *cascade {
3339                    f.write_str(" CASCADE");
3340                }
3341            }
3342            AlterSourceAction::AddSubsources {
3343                external_references: subsources,
3344                options,
3345            } => {
3346                f.write_str("ADD SUBSOURCE ");
3347
3348                f.write_node(&display::comma_separated(subsources));
3349
3350                if !options.is_empty() {
3351                    f.write_str(" WITH (");
3352                    f.write_node(&display::comma_separated(options));
3353                    f.write_str(")");
3354                }
3355            }
3356            AlterSourceAction::RefreshReferences => {
3357                f.write_str("REFRESH REFERENCES");
3358            }
3359        }
3360    }
3361}
3362
3363#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3364pub struct AlterSourceStatement<T: AstInfo> {
3365    pub source_name: UnresolvedItemName,
3366    pub if_exists: bool,
3367    pub action: AlterSourceAction<T>,
3368}
3369
3370impl<T: AstInfo> AstDisplay for AlterSourceStatement<T> {
3371    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3372        f.write_str("ALTER SOURCE ");
3373        if self.if_exists {
3374            f.write_str("IF EXISTS ");
3375        }
3376        f.write_node(&self.source_name);
3377        f.write_str(" ");
3378        f.write_node(&self.action)
3379    }
3380}
3381
3382impl_display_t!(AlterSourceStatement);
3383
3384/// `ALTER SECRET ... AS`
3385#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3386pub struct AlterSecretStatement<T: AstInfo> {
3387    pub name: UnresolvedItemName,
3388    pub if_exists: bool,
3389    pub value: Expr<T>,
3390}
3391
3392impl<T: AstInfo> AstDisplay for AlterSecretStatement<T> {
3393    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3394        f.write_str("ALTER SECRET ");
3395        if self.if_exists {
3396            f.write_str("IF EXISTS ");
3397        }
3398        f.write_node(&self.name);
3399        f.write_str(" AS ");
3400
3401        if f.redacted() {
3402            f.write_str("'<REDACTED>'");
3403        } else {
3404            f.write_node(&self.value);
3405        }
3406    }
3407}
3408
3409impl_display_t!(AlterSecretStatement);
3410
3411#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3412pub enum AlterConnectionAction<T: AstInfo> {
3413    RotateKeys,
3414    SetOption(ConnectionOption<T>),
3415    DropOption(ConnectionOptionName),
3416}
3417
3418impl<T: AstInfo> AstDisplay for AlterConnectionAction<T> {
3419    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3420        match self {
3421            AlterConnectionAction::RotateKeys => f.write_str("ROTATE KEYS"),
3422            AlterConnectionAction::SetOption(option) => {
3423                f.write_str("SET (");
3424                f.write_node(option);
3425                f.write_str(")");
3426            }
3427            AlterConnectionAction::DropOption(option) => {
3428                f.write_str("DROP (");
3429                f.write_node(option);
3430                f.write_str(")");
3431            }
3432        }
3433    }
3434}
3435impl_display_t!(AlterConnectionAction);
3436
3437#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3438pub enum AlterConnectionOptionName {
3439    Validate,
3440}
3441
3442impl AstDisplay for AlterConnectionOptionName {
3443    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3444        f.write_str(match self {
3445            AlterConnectionOptionName::Validate => "VALIDATE",
3446        })
3447    }
3448}
3449impl_display!(AlterConnectionOptionName);
3450
3451impl WithOptionName for AlterConnectionOptionName {
3452    /// # WARNING
3453    ///
3454    /// Whenever implementing this trait consider very carefully whether or not
3455    /// this value could contain sensitive user data. If you're uncertain, err
3456    /// on the conservative side and return `true`.
3457    fn redact_value(&self) -> bool {
3458        match self {
3459            AlterConnectionOptionName::Validate => false,
3460        }
3461    }
3462}
3463
3464#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3465/// An option in an `ALTER CONNECTION...` statement.
3466pub struct AlterConnectionOption<T: AstInfo> {
3467    pub name: AlterConnectionOptionName,
3468    pub value: Option<WithOptionValue<T>>,
3469}
3470impl_display_for_with_option!(AlterConnectionOption);
3471impl_display_t!(AlterConnectionOption);
3472
3473/// `ALTER CONNECTION`
3474#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3475pub struct AlterConnectionStatement<T: AstInfo> {
3476    pub name: UnresolvedItemName,
3477    pub if_exists: bool,
3478    pub actions: Vec<AlterConnectionAction<T>>,
3479    pub with_options: Vec<AlterConnectionOption<T>>,
3480}
3481
3482impl<T: AstInfo> AstDisplay for AlterConnectionStatement<T> {
3483    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3484        f.write_str("ALTER CONNECTION ");
3485        if self.if_exists {
3486            f.write_str("IF EXISTS ");
3487        }
3488        f.write_node(&self.name);
3489        f.write_str(" ");
3490        f.write_node(&display::comma_separated(&self.actions));
3491
3492        if !self.with_options.is_empty() {
3493            f.write_str(" WITH (");
3494            f.write_node(&display::comma_separated(&self.with_options));
3495            f.write_str(")");
3496        }
3497    }
3498}
3499
3500impl_display_t!(AlterConnectionStatement);
3501
3502/// `ALTER ROLE`
3503#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3504pub struct AlterRoleStatement<T: AstInfo> {
3505    /// The specified role.
3506    pub name: T::RoleName,
3507    /// Alterations we're making to the role.
3508    pub option: AlterRoleOption,
3509}
3510
3511impl<T: AstInfo> AstDisplay for AlterRoleStatement<T> {
3512    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3513        f.write_str("ALTER ROLE ");
3514        f.write_node(&self.name);
3515        f.write_node(&self.option);
3516    }
3517}
3518impl_display_t!(AlterRoleStatement);
3519
3520/// `ALTER ROLE ... [ WITH | SET ] ...`
3521#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3522pub enum AlterRoleOption {
3523    /// Any options that were attached, in the order they were presented.
3524    Attributes(Vec<RoleAttribute>),
3525    /// A variable that we want to provide a default value for this role.
3526    Variable(SetRoleVar),
3527}
3528
3529impl AstDisplay for AlterRoleOption {
3530    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3531        match self {
3532            AlterRoleOption::Attributes(attrs) => {
3533                for attr in attrs {
3534                    f.write_str(" ");
3535                    attr.fmt(f)
3536                }
3537            }
3538            AlterRoleOption::Variable(var) => {
3539                f.write_str(" ");
3540                f.write_node(var);
3541            }
3542        }
3543    }
3544}
3545impl_display!(AlterRoleOption);
3546
3547/// `ALTER TABLE ... ADD COLUMN ...`
3548#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3549pub struct AlterTableAddColumnStatement<T: AstInfo> {
3550    pub if_exists: bool,
3551    pub name: UnresolvedItemName,
3552    pub if_col_not_exist: bool,
3553    pub column_name: Ident,
3554    pub data_type: T::DataType,
3555}
3556
3557impl<T: AstInfo> AstDisplay for AlterTableAddColumnStatement<T> {
3558    fn fmt<W>(&self, f: &mut AstFormatter<W>)
3559    where
3560        W: fmt::Write,
3561    {
3562        f.write_str("ALTER TABLE ");
3563        if self.if_exists {
3564            f.write_str("IF EXISTS ");
3565        }
3566        f.write_node(&self.name);
3567
3568        f.write_str(" ADD COLUMN ");
3569        if self.if_col_not_exist {
3570            f.write_str("IF NOT EXISTS ");
3571        }
3572
3573        f.write_node(&self.column_name);
3574        f.write_str(" ");
3575        f.write_node(&self.data_type);
3576    }
3577}
3578
3579impl_display_t!(AlterTableAddColumnStatement);
3580
3581/// `ALTER MATERIALIZED VIEW ... APPLY REPLACEMENT ...`
3582#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3583pub struct AlterMaterializedViewApplyReplacementStatement {
3584    pub if_exists: bool,
3585    pub name: UnresolvedItemName,
3586    pub replacement_name: UnresolvedItemName,
3587}
3588
3589impl AstDisplay for AlterMaterializedViewApplyReplacementStatement {
3590    fn fmt<W>(&self, f: &mut AstFormatter<W>)
3591    where
3592        W: fmt::Write,
3593    {
3594        f.write_str("ALTER MATERIALIZED VIEW ");
3595        if self.if_exists {
3596            f.write_str("IF EXISTS ");
3597        }
3598        f.write_node(&self.name);
3599
3600        f.write_str(" APPLY REPLACEMENT ");
3601        f.write_node(&self.replacement_name);
3602    }
3603}
3604
3605impl_display!(AlterMaterializedViewApplyReplacementStatement);
3606
3607#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3608pub struct DiscardStatement {
3609    pub target: DiscardTarget,
3610}
3611
3612impl AstDisplay for DiscardStatement {
3613    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3614        f.write_str("DISCARD ");
3615        f.write_node(&self.target);
3616    }
3617}
3618impl_display!(DiscardStatement);
3619
3620#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3621pub enum DiscardTarget {
3622    Plans,
3623    Sequences,
3624    Temp,
3625    All,
3626}
3627
3628impl AstDisplay for DiscardTarget {
3629    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3630        match self {
3631            DiscardTarget::Plans => f.write_str("PLANS"),
3632            DiscardTarget::Sequences => f.write_str("SEQUENCES"),
3633            DiscardTarget::Temp => f.write_str("TEMP"),
3634            DiscardTarget::All => f.write_str("ALL"),
3635        }
3636    }
3637}
3638impl_display!(DiscardTarget);
3639
3640/// `DROP`
3641#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3642pub struct DropObjectsStatement {
3643    /// The type of the object to drop: TABLE, VIEW, etc.
3644    pub object_type: ObjectType,
3645    /// An optional `IF EXISTS` clause. (Non-standard.)
3646    pub if_exists: bool,
3647    /// One or more objects to drop. (ANSI SQL requires exactly one.)
3648    pub names: Vec<UnresolvedObjectName>,
3649    /// Whether `CASCADE` was specified. This will be `false` when
3650    /// `RESTRICT` was specified.
3651    pub cascade: bool,
3652}
3653
3654impl AstDisplay for DropObjectsStatement {
3655    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3656        f.write_str("DROP ");
3657        f.write_node(&self.object_type);
3658        f.write_str(" ");
3659        if self.if_exists {
3660            f.write_str("IF EXISTS ");
3661        }
3662        f.write_node(&display::comma_separated(&self.names));
3663        if self.cascade && self.object_type != ObjectType::Database {
3664            f.write_str(" CASCADE");
3665        } else if !self.cascade && self.object_type == ObjectType::Database {
3666            f.write_str(" RESTRICT");
3667        }
3668    }
3669}
3670impl_display!(DropObjectsStatement);
3671
3672/// `DROP OWNED BY ...`
3673#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3674pub struct DropOwnedStatement<T: AstInfo> {
3675    /// The roles whose owned objects are being dropped.
3676    pub role_names: Vec<T::RoleName>,
3677    /// Whether `CASCADE` was specified. `false` for `RESTRICT` and `None` if no drop behavior at
3678    /// all was specified.
3679    pub cascade: Option<bool>,
3680}
3681
3682impl<T: AstInfo> DropOwnedStatement<T> {
3683    pub fn cascade(&self) -> bool {
3684        self.cascade == Some(true)
3685    }
3686}
3687
3688impl<T: AstInfo> AstDisplay for DropOwnedStatement<T> {
3689    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3690        f.write_str("DROP OWNED BY ");
3691        f.write_node(&display::comma_separated(&self.role_names));
3692        if let Some(true) = self.cascade {
3693            f.write_str(" CASCADE");
3694        } else if let Some(false) = self.cascade {
3695            f.write_str(" RESTRICT");
3696        }
3697    }
3698}
3699impl_display_t!(DropOwnedStatement);
3700
3701#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3702pub struct QualifiedReplica {
3703    pub cluster: Ident,
3704    pub replica: Ident,
3705}
3706
3707impl AstDisplay for QualifiedReplica {
3708    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3709        f.write_node(&self.cluster);
3710        f.write_str(".");
3711        f.write_node(&self.replica);
3712    }
3713}
3714impl_display!(QualifiedReplica);
3715
3716/// `SET <variable>`
3717///
3718/// Note: this is not a standard SQL statement, but it is supported by at
3719/// least MySQL and PostgreSQL. Not all MySQL-specific syntactic forms are
3720/// supported yet.
3721#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3722pub struct SetVariableStatement {
3723    pub local: bool,
3724    pub variable: Ident,
3725    pub to: SetVariableTo,
3726}
3727
3728impl AstDisplay for SetVariableStatement {
3729    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3730        f.write_str("SET ");
3731        if self.local {
3732            f.write_str("LOCAL ");
3733        }
3734        f.write_node(&self.variable);
3735        f.write_str(" = ");
3736        f.write_node(&self.to);
3737    }
3738}
3739impl_display!(SetVariableStatement);
3740
3741/// `RESET <variable>`
3742///
3743/// Note: this is not a standard SQL statement, but it is supported by at
3744/// least MySQL and PostgreSQL. Not all syntactic forms are supported yet.
3745#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3746pub struct ResetVariableStatement {
3747    pub variable: Ident,
3748}
3749
3750impl AstDisplay for ResetVariableStatement {
3751    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3752        f.write_str("RESET ");
3753        f.write_node(&self.variable);
3754    }
3755}
3756impl_display!(ResetVariableStatement);
3757
3758/// `SHOW <variable>`
3759#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3760pub struct ShowVariableStatement {
3761    pub variable: Ident,
3762}
3763
3764impl AstDisplay for ShowVariableStatement {
3765    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3766        f.write_str("SHOW ");
3767        f.write_node(&self.variable);
3768    }
3769}
3770impl_display!(ShowVariableStatement);
3771
3772/// `INSPECT SHARD <id>`
3773#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3774pub struct InspectShardStatement {
3775    pub id: String,
3776}
3777
3778impl AstDisplay for InspectShardStatement {
3779    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3780        f.write_str("INSPECT SHARD ");
3781        f.write_str("'");
3782        f.write_node(&display::escape_single_quote_string(&self.id));
3783        f.write_str("'");
3784    }
3785}
3786impl_display!(InspectShardStatement);
3787
3788#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3789pub enum ShowObjectType<T: AstInfo> {
3790    MaterializedView {
3791        in_cluster: Option<T::ClusterName>,
3792    },
3793    Index {
3794        in_cluster: Option<T::ClusterName>,
3795        on_object: Option<T::ItemName>,
3796    },
3797    Table {
3798        on_source: Option<T::ItemName>,
3799    },
3800    View,
3801    Source {
3802        in_cluster: Option<T::ClusterName>,
3803    },
3804    Sink {
3805        in_cluster: Option<T::ClusterName>,
3806    },
3807    MetricSink {
3808        in_cluster: Option<T::ClusterName>,
3809    },
3810    Type,
3811    Role,
3812    Cluster,
3813    ClusterReplica,
3814    Object,
3815    Secret,
3816    Connection,
3817    Database,
3818    Schema {
3819        from: Option<T::DatabaseName>,
3820    },
3821    Subsource {
3822        on_source: Option<T::ItemName>,
3823    },
3824    Privileges {
3825        object_type: Option<SystemObjectType>,
3826        role: Option<T::RoleName>,
3827    },
3828    DefaultPrivileges {
3829        object_type: Option<ObjectType>,
3830        role: Option<T::RoleName>,
3831    },
3832    RoleMembership {
3833        role: Option<T::RoleName>,
3834    },
3835    NetworkPolicy,
3836    QueryPolicy,
3837}
3838/// `SHOW <object>S`
3839///
3840/// ```sql
3841/// SHOW TABLES;
3842/// SHOW SOURCES;
3843/// SHOW VIEWS;
3844/// SHOW SINKS;
3845/// ```
3846#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3847pub struct ShowObjectsStatement<T: AstInfo> {
3848    pub object_type: ShowObjectType<T>,
3849    pub from: Option<T::SchemaName>,
3850    pub filter: Option<ShowStatementFilter<T>>,
3851}
3852
3853impl<T: AstInfo> AstDisplay for ShowObjectsStatement<T> {
3854    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3855        f.write_str("SHOW");
3856        f.write_str(" ");
3857
3858        f.write_str(match &self.object_type {
3859            ShowObjectType::Table { .. } => "TABLES",
3860            ShowObjectType::View => "VIEWS",
3861            ShowObjectType::Source { .. } => "SOURCES",
3862            ShowObjectType::Sink { .. } => "SINKS",
3863            ShowObjectType::MetricSink { .. } => "METRIC SINKS",
3864            ShowObjectType::Type => "TYPES",
3865            ShowObjectType::Role => "ROLES",
3866            ShowObjectType::Cluster => "CLUSTERS",
3867            ShowObjectType::ClusterReplica => "CLUSTER REPLICAS",
3868            ShowObjectType::Object => "OBJECTS",
3869            ShowObjectType::Secret => "SECRETS",
3870            ShowObjectType::Connection => "CONNECTIONS",
3871            ShowObjectType::MaterializedView { .. } => "MATERIALIZED VIEWS",
3872            ShowObjectType::Index { .. } => "INDEXES",
3873            ShowObjectType::Database => "DATABASES",
3874            ShowObjectType::Schema { .. } => "SCHEMAS",
3875            ShowObjectType::Subsource { .. } => "SUBSOURCES",
3876            ShowObjectType::Privileges { .. } => "PRIVILEGES",
3877            ShowObjectType::DefaultPrivileges { .. } => "DEFAULT PRIVILEGES",
3878            ShowObjectType::RoleMembership { .. } => "ROLE MEMBERSHIP",
3879            ShowObjectType::NetworkPolicy => "NETWORK POLICIES",
3880            ShowObjectType::QueryPolicy => "QUERY POLICIES",
3881        });
3882
3883        if let ShowObjectType::Index { on_object, .. } = &self.object_type {
3884            if let Some(on_object) = on_object {
3885                f.write_str(" ON ");
3886                f.write_node(on_object);
3887            }
3888        }
3889
3890        if let ShowObjectType::Schema { from: Some(from) } = &self.object_type {
3891            f.write_str(" FROM ");
3892            f.write_node(from);
3893        }
3894
3895        if let Some(from) = &self.from {
3896            f.write_str(" FROM ");
3897            f.write_node(from);
3898        }
3899
3900        // append IN CLUSTER clause
3901        match &self.object_type {
3902            ShowObjectType::MaterializedView { in_cluster }
3903            | ShowObjectType::Index { in_cluster, .. }
3904            | ShowObjectType::Sink { in_cluster }
3905            | ShowObjectType::MetricSink { in_cluster }
3906            | ShowObjectType::Source { in_cluster } => {
3907                if let Some(cluster) = in_cluster {
3908                    f.write_str(" IN CLUSTER ");
3909                    f.write_node(cluster);
3910                }
3911            }
3912            _ => (),
3913        }
3914
3915        if let ShowObjectType::Subsource { on_source } = &self.object_type {
3916            if let Some(on_source) = on_source {
3917                f.write_str(" ON ");
3918                f.write_node(on_source);
3919            }
3920        }
3921
3922        if let ShowObjectType::Table { on_source } = &self.object_type {
3923            if let Some(on_source) = on_source {
3924                f.write_str(" ON ");
3925                f.write_node(on_source);
3926            }
3927        }
3928
3929        if let ShowObjectType::Privileges { object_type, role } = &self.object_type {
3930            if let Some(object_type) = object_type {
3931                f.write_str(" ON ");
3932                match object_type {
3933                    SystemObjectType::System => f.write_str("SYSTEM"),
3934                    SystemObjectType::Object(object_type) => {
3935                        write_grant_object_type_plural(f, object_type);
3936                    }
3937                }
3938            }
3939            if let Some(role) = role {
3940                f.write_str(" FOR ");
3941                f.write_node(role);
3942            }
3943        }
3944
3945        if let ShowObjectType::DefaultPrivileges { object_type, role } = &self.object_type {
3946            if let Some(object_type) = object_type {
3947                f.write_str(" ON ");
3948                write_grant_object_type_plural(f, object_type);
3949            }
3950            if let Some(role) = role {
3951                f.write_str(" FOR ");
3952                f.write_node(role);
3953            }
3954        }
3955
3956        if let ShowObjectType::RoleMembership {
3957            role: Some(role), ..
3958        } = &self.object_type
3959        {
3960            f.write_str(" FOR ");
3961            f.write_node(role);
3962        }
3963
3964        if let Some(filter) = &self.filter {
3965            f.write_str(" ");
3966            f.write_node(filter);
3967        }
3968    }
3969}
3970impl_display_t!(ShowObjectsStatement);
3971
3972/// `SHOW COLUMNS`
3973///
3974/// Note: this is a MySQL-specific statement.
3975#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3976pub struct ShowColumnsStatement<T: AstInfo> {
3977    pub table_name: T::ItemName,
3978    pub filter: Option<ShowStatementFilter<T>>,
3979}
3980
3981impl<T: AstInfo> AstDisplay for ShowColumnsStatement<T> {
3982    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
3983        f.write_str("SHOW ");
3984        f.write_str("COLUMNS FROM ");
3985        f.write_node(&self.table_name);
3986        if let Some(filter) = &self.filter {
3987            f.write_str(" ");
3988            f.write_node(filter);
3989        }
3990    }
3991}
3992impl_display_t!(ShowColumnsStatement);
3993
3994/// `SHOW [REDACTED] CREATE VIEW <view>`
3995#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3996pub struct ShowCreateViewStatement<T: AstInfo> {
3997    pub view_name: T::ItemName,
3998    pub redacted: bool,
3999}
4000
4001impl<T: AstInfo> AstDisplay for ShowCreateViewStatement<T> {
4002    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4003        f.write_str("SHOW ");
4004        if self.redacted {
4005            f.write_str("REDACTED ");
4006        }
4007        f.write_str("CREATE VIEW ");
4008        f.write_node(&self.view_name);
4009    }
4010}
4011impl_display_t!(ShowCreateViewStatement);
4012
4013/// `SHOW [REDACTED] CREATE MATERIALIZED VIEW <name>`
4014#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4015pub struct ShowCreateMaterializedViewStatement<T: AstInfo> {
4016    pub materialized_view_name: T::ItemName,
4017    pub redacted: bool,
4018}
4019
4020impl<T: AstInfo> AstDisplay for ShowCreateMaterializedViewStatement<T> {
4021    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4022        f.write_str("SHOW ");
4023        if self.redacted {
4024            f.write_str("REDACTED ");
4025        }
4026        f.write_str("CREATE MATERIALIZED VIEW ");
4027        f.write_node(&self.materialized_view_name);
4028    }
4029}
4030impl_display_t!(ShowCreateMaterializedViewStatement);
4031
4032/// `SHOW [REDACTED] CREATE SOURCE <source>`
4033#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4034pub struct ShowCreateSourceStatement<T: AstInfo> {
4035    pub source_name: T::ItemName,
4036    pub redacted: bool,
4037}
4038
4039impl<T: AstInfo> AstDisplay for ShowCreateSourceStatement<T> {
4040    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4041        f.write_str("SHOW ");
4042        if self.redacted {
4043            f.write_str("REDACTED ");
4044        }
4045        f.write_str("CREATE SOURCE ");
4046        f.write_node(&self.source_name);
4047    }
4048}
4049impl_display_t!(ShowCreateSourceStatement);
4050
4051/// `SHOW [REDACTED] CREATE TABLE <table>`
4052#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4053pub struct ShowCreateTableStatement<T: AstInfo> {
4054    pub table_name: T::ItemName,
4055    pub redacted: bool,
4056}
4057
4058impl<T: AstInfo> AstDisplay for ShowCreateTableStatement<T> {
4059    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4060        f.write_str("SHOW ");
4061        if self.redacted {
4062            f.write_str("REDACTED ");
4063        }
4064        f.write_str("CREATE TABLE ");
4065        f.write_node(&self.table_name);
4066    }
4067}
4068impl_display_t!(ShowCreateTableStatement);
4069
4070/// `SHOW [REDACTED] CREATE SINK <sink>`
4071#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4072pub struct ShowCreateSinkStatement<T: AstInfo> {
4073    pub sink_name: T::ItemName,
4074    pub redacted: bool,
4075}
4076
4077impl<T: AstInfo> AstDisplay for ShowCreateSinkStatement<T> {
4078    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4079        f.write_str("SHOW ");
4080        if self.redacted {
4081            f.write_str("REDACTED ");
4082        }
4083        f.write_str("CREATE SINK ");
4084        f.write_node(&self.sink_name);
4085    }
4086}
4087impl_display_t!(ShowCreateSinkStatement);
4088
4089/// `SHOW [REDACTED] CREATE METRIC SINK <sink>`
4090#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4091pub struct ShowCreateMetricSinkStatement<T: AstInfo> {
4092    pub metric_sink_name: T::ItemName,
4093    pub redacted: bool,
4094}
4095
4096impl<T: AstInfo> AstDisplay for ShowCreateMetricSinkStatement<T> {
4097    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4098        f.write_str("SHOW ");
4099        if self.redacted {
4100            f.write_str("REDACTED ");
4101        }
4102        f.write_str("CREATE METRIC SINK ");
4103        f.write_node(&self.metric_sink_name);
4104    }
4105}
4106impl_display_t!(ShowCreateMetricSinkStatement);
4107
4108/// `SHOW [REDACTED] CREATE INDEX <index>`
4109#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4110pub struct ShowCreateIndexStatement<T: AstInfo> {
4111    pub index_name: T::ItemName,
4112    pub redacted: bool,
4113}
4114
4115impl<T: AstInfo> AstDisplay for ShowCreateIndexStatement<T> {
4116    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4117        f.write_str("SHOW ");
4118        if self.redacted {
4119            f.write_str("REDACTED ");
4120        }
4121        f.write_str("CREATE INDEX ");
4122        f.write_node(&self.index_name);
4123    }
4124}
4125impl_display_t!(ShowCreateIndexStatement);
4126
4127/// `SHOW [REDACTED] CREATE CONNECTION <connection>`
4128#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4129pub struct ShowCreateConnectionStatement<T: AstInfo> {
4130    pub connection_name: T::ItemName,
4131    pub redacted: bool,
4132}
4133
4134impl<T: AstInfo> AstDisplay for ShowCreateConnectionStatement<T> {
4135    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4136        f.write_str("SHOW ");
4137        if self.redacted {
4138            f.write_str("REDACTED ");
4139        }
4140        f.write_str("CREATE CONNECTION ");
4141        f.write_node(&self.connection_name);
4142    }
4143}
4144
4145#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4146pub struct ShowCreateClusterStatement<T: AstInfo> {
4147    pub cluster_name: T::ClusterName,
4148}
4149
4150impl<T: AstInfo> AstDisplay for ShowCreateClusterStatement<T> {
4151    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4152        f.write_str("SHOW CREATE CLUSTER ");
4153        f.write_node(&self.cluster_name);
4154    }
4155}
4156
4157/// `{ BEGIN [ TRANSACTION | WORK ] | START TRANSACTION } ...`
4158#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4159pub struct StartTransactionStatement {
4160    pub modes: Vec<TransactionMode>,
4161}
4162
4163impl AstDisplay for StartTransactionStatement {
4164    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4165        f.write_str("START TRANSACTION");
4166        if !self.modes.is_empty() {
4167            f.write_str(" ");
4168            f.write_node(&display::comma_separated(&self.modes));
4169        }
4170    }
4171}
4172impl_display!(StartTransactionStatement);
4173
4174/// `SHOW [REDACTED] CREATE TYPE <type>`
4175#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4176pub struct ShowCreateTypeStatement<T: AstInfo> {
4177    pub type_name: T::DataType,
4178    pub redacted: bool,
4179}
4180
4181impl<T: AstInfo> AstDisplay for ShowCreateTypeStatement<T> {
4182    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4183        f.write_str("SHOW ");
4184        if self.redacted {
4185            f.write_str("REDACTED ");
4186        }
4187        f.write_str("CREATE TYPE ");
4188        f.write_node(&self.type_name);
4189    }
4190}
4191
4192/// `SET TRANSACTION ...`
4193#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4194pub struct SetTransactionStatement {
4195    pub local: bool,
4196    pub modes: Vec<TransactionMode>,
4197}
4198
4199impl AstDisplay for SetTransactionStatement {
4200    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4201        f.write_str("SET ");
4202        if !self.local {
4203            f.write_str("SESSION CHARACTERISTICS AS ");
4204        }
4205        f.write_str("TRANSACTION");
4206        if !self.modes.is_empty() {
4207            f.write_str(" ");
4208            f.write_node(&display::comma_separated(&self.modes));
4209        }
4210    }
4211}
4212impl_display!(SetTransactionStatement);
4213
4214/// `COMMIT [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]`
4215#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4216pub struct CommitStatement {
4217    pub chain: bool,
4218}
4219
4220impl AstDisplay for CommitStatement {
4221    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4222        f.write_str("COMMIT");
4223        if self.chain {
4224            f.write_str(" AND CHAIN");
4225        }
4226    }
4227}
4228impl_display!(CommitStatement);
4229
4230/// `ROLLBACK [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]`
4231#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4232pub struct RollbackStatement {
4233    pub chain: bool,
4234}
4235
4236impl AstDisplay for RollbackStatement {
4237    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4238        f.write_str("ROLLBACK");
4239        if self.chain {
4240            f.write_str(" AND CHAIN");
4241        }
4242    }
4243}
4244impl_display!(RollbackStatement);
4245
4246#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4247pub enum SubscribeOptionName {
4248    Snapshot,
4249    Progress,
4250}
4251
4252impl AstDisplay for SubscribeOptionName {
4253    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4254        match self {
4255            SubscribeOptionName::Snapshot => f.write_str("SNAPSHOT"),
4256            SubscribeOptionName::Progress => f.write_str("PROGRESS"),
4257        }
4258    }
4259}
4260impl_display!(SubscribeOptionName);
4261
4262impl WithOptionName for SubscribeOptionName {
4263    /// # WARNING
4264    ///
4265    /// Whenever implementing this trait consider very carefully whether or not
4266    /// this value could contain sensitive user data. If you're uncertain, err
4267    /// on the conservative side and return `true`.
4268    fn redact_value(&self) -> bool {
4269        match self {
4270            SubscribeOptionName::Snapshot | SubscribeOptionName::Progress => false,
4271        }
4272    }
4273}
4274
4275#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4276pub struct SubscribeOption<T: AstInfo> {
4277    pub name: SubscribeOptionName,
4278    pub value: Option<WithOptionValue<T>>,
4279}
4280impl_display_for_with_option!(SubscribeOption);
4281impl_display_t!(SubscribeOption);
4282
4283/// `SUBSCRIBE`
4284#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4285pub struct SubscribeStatement<T: AstInfo> {
4286    pub relation: SubscribeRelation<T>,
4287    pub options: Vec<SubscribeOption<T>>,
4288    pub as_of: Option<AsOf<T>>,
4289    pub up_to: Option<Expr<T>>,
4290    pub output: SubscribeOutput<T>,
4291}
4292
4293impl<T: AstInfo> AstDisplay for SubscribeStatement<T> {
4294    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4295        f.write_str("SUBSCRIBE ");
4296        if self.relation.needs_explicit_to(f.simple()) {
4297            // Without the optional `TO` keyword, a relation whose first name
4298            // component is the bare keyword `to` (e.g. `SUBSCRIBE TO to`) would
4299            // display as `SUBSCRIBE to`, which re-parses with `to` consumed as
4300            // the optional keyword, dropping the relation name.
4301            f.write_str("TO ");
4302        }
4303        f.write_node(&self.relation);
4304        if !self.options.is_empty() {
4305            f.write_str(" WITH (");
4306            f.write_node(&display::comma_separated(&self.options));
4307            f.write_str(")");
4308        }
4309        if let Some(as_of) = &self.as_of {
4310            f.write_str(" ");
4311            f.write_node(as_of);
4312        }
4313        if let Some(up_to) = &self.up_to {
4314            f.write_str(" UP TO ");
4315            f.write_node(up_to);
4316        }
4317        f.write_str(&self.output);
4318    }
4319}
4320impl_display_t!(SubscribeStatement);
4321
4322#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4323pub enum SubscribeRelation<T: AstInfo> {
4324    Name(T::ItemName),
4325    Query(Query<T>),
4326}
4327
4328impl<T: AstInfo> SubscribeRelation<T> {
4329    /// Reports whether printing this relation after `SUBSCRIBE` requires the
4330    /// optional `TO` keyword to avoid reparsing the first name component as that
4331    /// keyword instead of as part of the relation name.
4332    pub fn needs_explicit_to(&self, bare_identifiers: bool) -> bool {
4333        let SubscribeRelation::Name(name) = self else {
4334            return false;
4335        };
4336        bare_identifiers && name_starts_with_bare_to(&name.to_ast_string_simple())
4337    }
4338}
4339
4340fn name_starts_with_bare_to(name: &str) -> bool {
4341    let Some(rest) = name.strip_prefix("to") else {
4342        return false;
4343    };
4344    rest.is_empty() || rest.starts_with('.')
4345}
4346
4347impl<T: AstInfo> AstDisplay for SubscribeRelation<T> {
4348    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4349        match self {
4350            SubscribeRelation::Name(name) => f.write_node(name),
4351            SubscribeRelation::Query(query) => {
4352                f.write_str("(");
4353                f.write_node(query);
4354                f.write_str(")");
4355            }
4356        }
4357    }
4358}
4359impl_display_t!(SubscribeRelation);
4360
4361#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4362pub struct ExplainPlanStatement<T: AstInfo> {
4363    pub stage: Option<ExplainStage>,
4364    pub with_options: Vec<ExplainPlanOption<T>>,
4365    pub format: Option<ExplainFormat>,
4366    pub explainee: Explainee<T>,
4367}
4368
4369impl<T: AstInfo> ExplainPlanStatement<T> {
4370    pub fn stage(&self) -> ExplainStage {
4371        self.stage.unwrap_or(ExplainStage::PhysicalPlan)
4372    }
4373
4374    pub fn format(&self) -> ExplainFormat {
4375        self.format.unwrap_or(ExplainFormat::Text)
4376    }
4377}
4378
4379impl<T: AstInfo> AstDisplay for ExplainPlanStatement<T> {
4380    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4381        f.write_str("EXPLAIN");
4382        if let Some(stage) = &self.stage {
4383            f.write_str(" ");
4384            f.write_node(stage);
4385        }
4386        if !self.with_options.is_empty() {
4387            f.write_str(" WITH (");
4388            f.write_node(&display::comma_separated(&self.with_options));
4389            f.write_str(")");
4390        }
4391        if let Some(format) = &self.format {
4392            f.write_str(" AS ");
4393            f.write_node(format);
4394        }
4395        if self.stage.is_some() {
4396            f.write_str(" FOR");
4397        }
4398        f.write_str(" ");
4399        f.write_node(&self.explainee);
4400    }
4401}
4402impl_display_t!(ExplainPlanStatement);
4403
4404// Note: the `AstDisplay` implementation and `Parser::parse_` method for this
4405// enum are generated automatically by this crate's `build.rs`.
4406#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4407pub enum ExplainPlanOptionName {
4408    Arity,
4409    Cardinality,
4410    ColumnNames,
4411    FilterPushdown,
4412    HumanizedExpressions,
4413    JoinImplementations,
4414    Keys,
4415    LinearChains,
4416    NonNegative,
4417    NoFastPath,
4418    NoNotices,
4419    NodeIdentifiers,
4420    RawPlans,
4421    RawSyntax,
4422    Raw, // Listed after the `Raw~` variants to keep the parser happy!
4423    Redacted,
4424    SubtreeSize,
4425    Timing,
4426    Types,
4427    Equivalences,
4428    ReoptimizeImportedViews,
4429    EnableNewOuterJoinLowering,
4430    EnableEagerDeltaJoins,
4431    EnableVariadicLeftJoinLowering,
4432    EnableLetrecFixpointAnalysis,
4433    EnableJoinPrioritizeArranged,
4434    EnableProjectionPushdownAfterRelationCse,
4435    EnableFixedCorrelatedCteLowering,
4436    EnableUnionCancellationAfterRelationCse,
4437}
4438
4439impl WithOptionName for ExplainPlanOptionName {
4440    /// # WARNING
4441    ///
4442    /// Whenever implementing this trait consider very carefully whether or not
4443    /// this value could contain sensitive user data. If you're uncertain, err
4444    /// on the conservative side and return `true`.
4445    fn redact_value(&self) -> bool {
4446        match self {
4447            Self::Arity
4448            | Self::Cardinality
4449            | Self::ColumnNames
4450            | Self::FilterPushdown
4451            | Self::HumanizedExpressions
4452            | Self::JoinImplementations
4453            | Self::Keys
4454            | Self::LinearChains
4455            | Self::NonNegative
4456            | Self::NoFastPath
4457            | Self::NoNotices
4458            | Self::NodeIdentifiers
4459            | Self::RawPlans
4460            | Self::RawSyntax
4461            | Self::Raw
4462            | Self::Redacted
4463            | Self::SubtreeSize
4464            | Self::Timing
4465            | Self::Types
4466            | Self::Equivalences
4467            | Self::ReoptimizeImportedViews
4468            | Self::EnableNewOuterJoinLowering
4469            | Self::EnableEagerDeltaJoins
4470            | Self::EnableVariadicLeftJoinLowering
4471            | Self::EnableLetrecFixpointAnalysis
4472            | Self::EnableJoinPrioritizeArranged
4473            | Self::EnableProjectionPushdownAfterRelationCse
4474            | Self::EnableFixedCorrelatedCteLowering
4475            | Self::EnableUnionCancellationAfterRelationCse => false,
4476        }
4477    }
4478}
4479
4480#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4481pub struct ExplainPlanOption<T: AstInfo> {
4482    pub name: ExplainPlanOptionName,
4483    pub value: Option<WithOptionValue<T>>,
4484}
4485impl_display_for_with_option!(ExplainPlanOption);
4486
4487#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4488pub enum ExplainSinkSchemaFor {
4489    Key,
4490    Value,
4491}
4492#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4493pub struct ExplainSinkSchemaStatement<T: AstInfo> {
4494    pub schema_for: ExplainSinkSchemaFor,
4495    pub format: Option<ExplainFormat>,
4496    pub statement: CreateSinkStatement<T>,
4497}
4498
4499impl<T: AstInfo> AstDisplay for ExplainSinkSchemaStatement<T> {
4500    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4501        f.write_str("EXPLAIN ");
4502        match &self.schema_for {
4503            ExplainSinkSchemaFor::Key => f.write_str("KEY"),
4504            ExplainSinkSchemaFor::Value => f.write_str("VALUE"),
4505        }
4506        f.write_str(" SCHEMA");
4507        if let Some(format) = &self.format {
4508            f.write_str(" AS ");
4509            f.write_node(format);
4510        }
4511        f.write_str(" FOR ");
4512        f.write_node(&self.statement);
4513    }
4514}
4515impl_display_t!(ExplainSinkSchemaStatement);
4516
4517#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4518pub struct ExplainPushdownStatement<T: AstInfo> {
4519    pub explainee: Explainee<T>,
4520}
4521
4522impl<T: AstInfo> AstDisplay for ExplainPushdownStatement<T> {
4523    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4524        f.write_str("EXPLAIN FILTER PUSHDOWN FOR ");
4525        f.write_node(&self.explainee);
4526    }
4527}
4528impl_display_t!(ExplainPushdownStatement);
4529
4530#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4531pub enum ExplainAnalyzeComputationProperty {
4532    Cpu,
4533    Memory,
4534}
4535
4536#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4537pub enum ExplainAnalyzeProperty {
4538    Computation(ExplainAnalyzeComputationProperties),
4539    Hints,
4540}
4541
4542#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4543pub struct ExplainAnalyzeComputationProperties {
4544    /// Must be non-empty.
4545    pub properties: Vec<ExplainAnalyzeComputationProperty>,
4546    pub skew: bool,
4547}
4548#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4549pub struct ExplainAnalyzeObjectStatement<T: AstInfo> {
4550    pub properties: ExplainAnalyzeProperty,
4551    /// Should only be `Explainee::Index` or `Explainee::MaterializedView`
4552    pub explainee: Explainee<T>,
4553    pub as_sql: bool,
4554}
4555
4556impl<T: AstInfo> AstDisplay for ExplainAnalyzeObjectStatement<T> {
4557    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4558        f.write_str("EXPLAIN ANALYZE");
4559        match &self.properties {
4560            ExplainAnalyzeProperty::Computation(ExplainAnalyzeComputationProperties {
4561                properties,
4562                skew,
4563            }) => {
4564                let mut first = true;
4565                for property in properties {
4566                    if first {
4567                        first = false;
4568                    } else {
4569                        f.write_str(",");
4570                    }
4571                    match property {
4572                        ExplainAnalyzeComputationProperty::Cpu => f.write_str(" CPU"),
4573                        ExplainAnalyzeComputationProperty::Memory => f.write_str(" MEMORY"),
4574                    }
4575                }
4576                if *skew {
4577                    f.write_str(" WITH SKEW");
4578                }
4579            }
4580            ExplainAnalyzeProperty::Hints => f.write_str(" HINTS"),
4581        }
4582        f.write_str(" FOR ");
4583        f.write_node(&self.explainee);
4584        if self.as_sql {
4585            f.write_str(" AS SQL");
4586        }
4587    }
4588}
4589impl_display_t!(ExplainAnalyzeObjectStatement);
4590
4591#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4592pub struct ExplainAnalyzeClusterStatement {
4593    pub properties: ExplainAnalyzeComputationProperties,
4594    pub as_sql: bool,
4595}
4596
4597impl AstDisplay for ExplainAnalyzeClusterStatement {
4598    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4599        f.write_str("EXPLAIN ANALYZE CLUSTER");
4600
4601        let mut first = true;
4602        for property in &self.properties.properties {
4603            if first {
4604                first = false;
4605            } else {
4606                f.write_str(",");
4607            }
4608            match property {
4609                ExplainAnalyzeComputationProperty::Cpu => f.write_str(" CPU"),
4610                ExplainAnalyzeComputationProperty::Memory => f.write_str(" MEMORY"),
4611            }
4612        }
4613
4614        if self.properties.skew {
4615            f.write_str(" WITH SKEW");
4616        }
4617        if self.as_sql {
4618            f.write_str(" AS SQL");
4619        }
4620    }
4621}
4622impl_display!(ExplainAnalyzeClusterStatement);
4623
4624#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4625pub struct ExplainTimestampStatement<T: AstInfo> {
4626    pub format: Option<ExplainFormat>,
4627    pub select: SelectStatement<T>,
4628}
4629
4630impl<T: AstInfo> ExplainTimestampStatement<T> {
4631    pub fn format(&self) -> ExplainFormat {
4632        self.format.unwrap_or(ExplainFormat::Text)
4633    }
4634}
4635
4636impl<T: AstInfo> AstDisplay for ExplainTimestampStatement<T> {
4637    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4638        f.write_str("EXPLAIN TIMESTAMP");
4639        if let Some(format) = &self.format {
4640            f.write_str(" AS ");
4641            f.write_node(format);
4642        }
4643        f.write_str(" FOR ");
4644        f.write_node(&self.select);
4645    }
4646}
4647impl_display_t!(ExplainTimestampStatement);
4648
4649#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4650pub enum InsertSource<T: AstInfo> {
4651    Query(Query<T>),
4652    DefaultValues,
4653}
4654
4655impl<T: AstInfo> AstDisplay for InsertSource<T> {
4656    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4657        match self {
4658            InsertSource::Query(query) => f.write_node(query),
4659            InsertSource::DefaultValues => f.write_str("DEFAULT VALUES"),
4660        }
4661    }
4662}
4663impl_display_t!(InsertSource);
4664
4665#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Copy)]
4666pub enum ObjectType {
4667    Table,
4668    View,
4669    MaterializedView,
4670    Source,
4671    Sink,
4672    MetricSink,
4673    Index,
4674    Type,
4675    Role,
4676    Cluster,
4677    ClusterReplica,
4678    Secret,
4679    Connection,
4680    Database,
4681    Schema,
4682    Func,
4683    Subsource,
4684    NetworkPolicy,
4685    QueryPolicy,
4686}
4687
4688impl ObjectType {
4689    pub fn lives_in_schema(&self) -> bool {
4690        match self {
4691            ObjectType::Table
4692            | ObjectType::View
4693            | ObjectType::MaterializedView
4694            | ObjectType::Source
4695            | ObjectType::Sink
4696            | ObjectType::MetricSink
4697            | ObjectType::Index
4698            | ObjectType::Type
4699            | ObjectType::Secret
4700            | ObjectType::Connection
4701            | ObjectType::Func
4702            | ObjectType::Subsource => true,
4703            ObjectType::Database
4704            | ObjectType::Schema
4705            | ObjectType::Cluster
4706            | ObjectType::ClusterReplica
4707            | ObjectType::Role
4708            | ObjectType::NetworkPolicy
4709            | ObjectType::QueryPolicy => false,
4710        }
4711    }
4712}
4713
4714impl AstDisplay for ObjectType {
4715    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4716        f.write_str(match self {
4717            ObjectType::Table => "TABLE",
4718            ObjectType::View => "VIEW",
4719            ObjectType::MaterializedView => "MATERIALIZED VIEW",
4720            ObjectType::Source => "SOURCE",
4721            ObjectType::Sink => "SINK",
4722            ObjectType::MetricSink => "METRIC SINK",
4723            ObjectType::Index => "INDEX",
4724            ObjectType::Type => "TYPE",
4725            ObjectType::Role => "ROLE",
4726            ObjectType::Cluster => "CLUSTER",
4727            ObjectType::ClusterReplica => "CLUSTER REPLICA",
4728            ObjectType::Secret => "SECRET",
4729            ObjectType::Connection => "CONNECTION",
4730            ObjectType::Database => "DATABASE",
4731            ObjectType::Schema => "SCHEMA",
4732            ObjectType::Func => "FUNCTION",
4733            ObjectType::Subsource => "SUBSOURCE",
4734            ObjectType::NetworkPolicy => "NETWORK POLICY",
4735            ObjectType::QueryPolicy => "QUERY POLICY",
4736        })
4737    }
4738}
4739impl_display!(ObjectType);
4740
4741#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Copy)]
4742pub enum SystemObjectType {
4743    System,
4744    Object(ObjectType),
4745}
4746
4747impl AstDisplay for SystemObjectType {
4748    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4749        match self {
4750            SystemObjectType::System => f.write_str("SYSTEM"),
4751            SystemObjectType::Object(object) => f.write_node(object),
4752        }
4753    }
4754}
4755impl_display!(SystemObjectType);
4756
4757#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4758pub enum ShowStatementFilter<T: AstInfo> {
4759    Like(String),
4760    Where(Expr<T>),
4761}
4762
4763impl<T: AstInfo> AstDisplay for ShowStatementFilter<T> {
4764    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4765        use ShowStatementFilter::*;
4766        match self {
4767            Like(pattern) => {
4768                f.write_str("LIKE '");
4769                f.write_node(&display::escape_single_quote_string(pattern));
4770                f.write_str("'");
4771            }
4772            Where(expr) => {
4773                f.write_str("WHERE ");
4774                f.write_node(expr);
4775            }
4776        }
4777    }
4778}
4779impl_display_t!(ShowStatementFilter);
4780
4781#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4782pub enum WithOptionValue<T: AstInfo> {
4783    Value(Value),
4784    DataType(T::DataType),
4785    Secret(T::ItemName),
4786    Item(T::ItemName),
4787    UnresolvedItemName(UnresolvedItemName),
4788    Ident(Ident),
4789    Sequence(Vec<WithOptionValue<T>>),
4790    Map(BTreeMap<String, WithOptionValue<T>>),
4791    // Special cases.
4792    Expr(Expr<T>),
4793    ClusterReplicas(Vec<ReplicaDefinition<T>>),
4794    ConnectionKafkaBroker(KafkaBroker<T>),
4795    ConnectionAwsPrivatelink(ConnectionDefaultAwsPrivatelink<T>),
4796    KafkaMatchingBrokerRule(KafkaMatchingBrokerRule<T>),
4797    RetainHistoryFor(Value),
4798    Refresh(RefreshOptionValue<T>),
4799    ClusterScheduleOptionValue(ClusterScheduleOptionValue),
4800    ClusterAutoScalingStrategyOptionValue(ClusterAutoScalingStrategyOptionValue),
4801    ClusterAlterStrategy(ClusterAlterOptionValue<T>),
4802    NetworkPolicyRules(Vec<NetworkPolicyRuleDefinition<T>>),
4803}
4804
4805impl<T: AstInfo> AstDisplay for WithOptionValue<T> {
4806    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4807        if f.redacted() {
4808            // When adding branches to this match statement, think about whether it is OK for us to collect
4809            // the value as part of our telemetry. Check the data management policy to be sure!
4810            match self {
4811                WithOptionValue::Value(_)
4812                | WithOptionValue::Sequence(_)
4813                | WithOptionValue::Map(_)
4814                | WithOptionValue::RetainHistoryFor(_)
4815                | WithOptionValue::Refresh(_)
4816                | WithOptionValue::Expr(_) => {
4817                    // These are redact-aware.
4818                }
4819                WithOptionValue::ConnectionKafkaBroker(_) => {
4820                    f.write_str("'<REDACTED>'");
4821                    return;
4822                }
4823                // A secret reference is a catalog item name, not the secret
4824                // value, so it is safe to show in redacted output. An option
4825                // that accepts an inline credential is parsed as a `Value`,
4826                // which is redacted by that arm together with the option's
4827                // `redact_value()`.
4828                WithOptionValue::Secret(_) => {}
4829                WithOptionValue::DataType(_)
4830                | WithOptionValue::Item(_)
4831                | WithOptionValue::UnresolvedItemName(_)
4832                | WithOptionValue::Ident(_)
4833                | WithOptionValue::ConnectionAwsPrivatelink(_)
4834                | WithOptionValue::KafkaMatchingBrokerRule(_)
4835                | WithOptionValue::ClusterReplicas(_)
4836                | WithOptionValue::ClusterScheduleOptionValue(_)
4837                | WithOptionValue::ClusterAutoScalingStrategyOptionValue(_)
4838                | WithOptionValue::ClusterAlterStrategy(_)
4839                | WithOptionValue::NetworkPolicyRules(_) => {
4840                    // These do not need redaction.
4841                }
4842            }
4843        }
4844        match self {
4845            WithOptionValue::Sequence(values) => {
4846                f.write_str("(");
4847                f.write_node(&display::comma_separated(values));
4848                f.write_str(")");
4849            }
4850            WithOptionValue::Map(values) => {
4851                f.write_str("MAP[");
4852                let len = values.len();
4853                for (i, (key, value)) in values.iter().enumerate() {
4854                    f.write_str("'");
4855                    f.write_node(&display::escape_single_quote_string(key));
4856                    f.write_str("' => ");
4857                    f.write_node(value);
4858                    if i + 1 < len {
4859                        f.write_str(", ");
4860                    }
4861                }
4862                f.write_str("]");
4863            }
4864            WithOptionValue::Expr(e) => f.write_node(e),
4865            WithOptionValue::Value(value) => f.write_node(value),
4866            WithOptionValue::DataType(typ) => f.write_node(typ),
4867            WithOptionValue::Secret(name) => {
4868                f.write_str("SECRET ");
4869                f.write_node(name)
4870            }
4871            WithOptionValue::Item(obj) => f.write_node(obj),
4872            WithOptionValue::UnresolvedItemName(r) => f.write_node(r),
4873            WithOptionValue::Ident(r) => f.write_node(r),
4874            WithOptionValue::ClusterReplicas(replicas) => {
4875                f.write_str("(");
4876                f.write_node(&display::comma_separated(replicas));
4877                f.write_str(")");
4878            }
4879            WithOptionValue::NetworkPolicyRules(rules) => {
4880                f.write_str("(");
4881                f.write_node(&display::comma_separated(rules));
4882                f.write_str(")");
4883            }
4884            WithOptionValue::ConnectionAwsPrivatelink(aws_privatelink) => {
4885                f.write_node(aws_privatelink);
4886            }
4887            WithOptionValue::KafkaMatchingBrokerRule(rule) => {
4888                f.write_node(rule);
4889            }
4890            WithOptionValue::ConnectionKafkaBroker(broker) => {
4891                f.write_node(broker);
4892            }
4893            WithOptionValue::RetainHistoryFor(value) => {
4894                f.write_str("FOR ");
4895                f.write_node(value);
4896            }
4897            WithOptionValue::Refresh(opt) => f.write_node(opt),
4898            WithOptionValue::ClusterScheduleOptionValue(value) => f.write_node(value),
4899            WithOptionValue::ClusterAutoScalingStrategyOptionValue(value) => f.write_node(value),
4900            WithOptionValue::ClusterAlterStrategy(value) => f.write_node(value),
4901        }
4902    }
4903}
4904impl_display_t!(WithOptionValue);
4905
4906#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4907pub enum RefreshOptionValue<T: AstInfo> {
4908    OnCommit,
4909    AtCreation,
4910    At(RefreshAtOptionValue<T>),
4911    Every(RefreshEveryOptionValue<T>),
4912}
4913
4914#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4915pub struct RefreshAtOptionValue<T: AstInfo> {
4916    // We need an Expr because we want to support `mz_now()`.
4917    pub time: Expr<T>,
4918}
4919
4920#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4921pub struct RefreshEveryOptionValue<T: AstInfo> {
4922    // The refresh interval.
4923    pub interval: IntervalValue,
4924    // We need an Expr because we want to support `mz_now()`.
4925    pub aligned_to: Option<Expr<T>>,
4926}
4927
4928impl<T: AstInfo> AstDisplay for RefreshOptionValue<T> {
4929    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4930        match self {
4931            RefreshOptionValue::OnCommit => {
4932                f.write_str("ON COMMIT");
4933            }
4934            RefreshOptionValue::AtCreation => {
4935                f.write_str("AT CREATION");
4936            }
4937            RefreshOptionValue::At(RefreshAtOptionValue { time }) => {
4938                f.write_str("AT ");
4939                f.write_node(time);
4940            }
4941            RefreshOptionValue::Every(RefreshEveryOptionValue {
4942                interval,
4943                aligned_to,
4944            }) => {
4945                f.write_str("EVERY '");
4946                f.write_node(interval);
4947                if let Some(aligned_to) = aligned_to {
4948                    f.write_str(" ALIGNED TO ");
4949                    f.write_node(aligned_to)
4950                }
4951            }
4952        }
4953    }
4954}
4955
4956#[derive(
4957    Debug,
4958    Clone,
4959    PartialEq,
4960    Eq,
4961    Hash,
4962    PartialOrd,
4963    Ord,
4964    Deserialize,
4965    Serialize
4966)]
4967pub enum ClusterScheduleOptionValue {
4968    Manual,
4969    Refresh {
4970        hydration_time_estimate: Option<IntervalValue>,
4971    },
4972}
4973
4974impl Default for ClusterScheduleOptionValue {
4975    fn default() -> Self {
4976        // (Has to be consistent with `impl Default for ClusterSchedule`.)
4977        ClusterScheduleOptionValue::Manual
4978    }
4979}
4980
4981impl AstDisplay for ClusterScheduleOptionValue {
4982    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
4983        match self {
4984            ClusterScheduleOptionValue::Manual => {
4985                f.write_str("MANUAL");
4986            }
4987            ClusterScheduleOptionValue::Refresh {
4988                hydration_time_estimate,
4989            } => {
4990                f.write_str("ON REFRESH");
4991                if let Some(hydration_time_estimate) = hydration_time_estimate {
4992                    f.write_str(" (HYDRATION TIME ESTIMATE = '");
4993                    f.write_node(hydration_time_estimate);
4994                    f.write_str(")");
4995                }
4996            }
4997        }
4998    }
4999}
5000
5001/// The value of the `AUTO SCALING STRATEGY` cluster option: the autoscaling
5002/// policy block. Extensible: future strategies are additional optional
5003/// sub-policies, so the block grows without changing existing ones. An empty
5004/// block (all sub-policies absent) disables autoscaling for the cluster, the same
5005/// as `RESET (AUTO SCALING STRATEGY)`.
5006#[derive(
5007    Debug,
5008    Clone,
5009    PartialEq,
5010    Eq,
5011    Hash,
5012    PartialOrd,
5013    Ord,
5014    Deserialize,
5015    Serialize
5016)]
5017pub struct ClusterAutoScalingStrategyOptionValue {
5018    pub on_hydration: Option<OnHydrationOptionValue>,
5019}
5020
5021impl AstDisplay for ClusterAutoScalingStrategyOptionValue {
5022    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5023        f.write_str("(");
5024        if let Some(on_hydration) = &self.on_hydration {
5025            f.write_node(on_hydration);
5026        }
5027        f.write_str(")");
5028    }
5029}
5030
5031/// The `ON HYDRATION` autoscaling sub-policy: while objects are un-hydrated, run
5032/// an extra replica at `hydration_size` to accelerate hydration, lingering for
5033/// `linger_duration` after the steady-state replicas hydrate.
5034#[derive(
5035    Debug,
5036    Clone,
5037    PartialEq,
5038    Eq,
5039    Hash,
5040    PartialOrd,
5041    Ord,
5042    Deserialize,
5043    Serialize
5044)]
5045pub struct OnHydrationOptionValue {
5046    pub hydration_size: Value,
5047    pub linger_duration: Option<Value>,
5048}
5049
5050impl AstDisplay for OnHydrationOptionValue {
5051    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5052        f.write_str("ON HYDRATION (HYDRATION SIZE = ");
5053        f.write_node(&self.hydration_size);
5054        if let Some(linger_duration) = &self.linger_duration {
5055            f.write_str(", LINGER DURATION = ");
5056            f.write_node(linger_duration);
5057        }
5058        f.write_str(")");
5059    }
5060}
5061
5062#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
5063pub enum TransactionMode {
5064    AccessMode(TransactionAccessMode),
5065    IsolationLevel(TransactionIsolationLevel),
5066}
5067
5068impl AstDisplay for TransactionMode {
5069    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5070        use TransactionMode::*;
5071        match self {
5072            AccessMode(access_mode) => f.write_node(access_mode),
5073            IsolationLevel(iso_level) => {
5074                f.write_str("ISOLATION LEVEL ");
5075                f.write_node(iso_level);
5076            }
5077        }
5078    }
5079}
5080impl_display!(TransactionMode);
5081
5082/// The access mode of a transaction, as specified by the `BEGIN ...` statement.
5083#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
5084pub enum TransactionAccessMode {
5085    ReadOnly,
5086    ReadWrite,
5087}
5088
5089impl AstDisplay for TransactionAccessMode {
5090    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5091        use TransactionAccessMode::*;
5092        f.write_str(match self {
5093            ReadOnly => "READ ONLY",
5094            ReadWrite => "READ WRITE",
5095        })
5096    }
5097}
5098impl_display!(TransactionAccessMode);
5099
5100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
5101pub enum TransactionIsolationLevel {
5102    ReadUncommitted,
5103    ReadCommitted,
5104    RepeatableRead,
5105    Serializable,
5106    StrongSessionSerializable,
5107    StrictSerializable,
5108}
5109
5110impl AstDisplay for TransactionIsolationLevel {
5111    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5112        use TransactionIsolationLevel::*;
5113        f.write_str(match self {
5114            ReadUncommitted => "READ UNCOMMITTED",
5115            ReadCommitted => "READ COMMITTED",
5116            RepeatableRead => "REPEATABLE READ",
5117            Serializable => "SERIALIZABLE",
5118            StrongSessionSerializable => "STRONG SESSION SERIALIZABLE",
5119            StrictSerializable => "STRICT SERIALIZABLE",
5120        })
5121    }
5122}
5123impl_display!(TransactionIsolationLevel);
5124
5125#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5126pub enum SetVariableTo {
5127    Default,
5128    Values(Vec<SetVariableValue>),
5129}
5130
5131impl AstDisplay for SetVariableTo {
5132    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5133        use SetVariableTo::*;
5134        match self {
5135            Values(values) => f.write_node(&display::comma_separated(values)),
5136            Default => f.write_str("DEFAULT"),
5137        }
5138    }
5139}
5140impl_display!(SetVariableTo);
5141
5142#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5143pub enum SetVariableValue {
5144    Ident(Ident),
5145    Literal(Value),
5146}
5147
5148impl AstDisplay for SetVariableValue {
5149    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5150        use SetVariableValue::*;
5151        match self {
5152            Ident(ident) => f.write_node(ident),
5153            Literal(literal) => f.write_node(literal),
5154        }
5155    }
5156}
5157impl_display!(SetVariableValue);
5158
5159impl SetVariableValue {
5160    /// Returns the underlying value without quotes.
5161    pub fn into_unquoted_value(self) -> String {
5162        match self {
5163            // `lit.to_string` will quote a `Value::String`, so get the unquoted
5164            // version.
5165            SetVariableValue::Literal(Value::String(s)) => s,
5166            SetVariableValue::Literal(lit) => lit.to_string(),
5167            SetVariableValue::Ident(ident) => ident.into_string(),
5168        }
5169    }
5170}
5171
5172/// SQL assignment `foo = expr` as used in SQLUpdate
5173#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5174pub struct Assignment<T: AstInfo> {
5175    pub id: Ident,
5176    pub value: Expr<T>,
5177}
5178
5179impl<T: AstInfo> AstDisplay for Assignment<T> {
5180    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5181        f.write_node(&self.id);
5182        f.write_str(" = ");
5183        f.write_node(&self.value);
5184    }
5185}
5186impl_display_t!(Assignment);
5187
5188/// Specifies what [Statement::ExplainPlan] is actually explained.
5189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5190pub enum ExplainStage {
5191    /// The mz_sql::HirRelationExpr after parsing
5192    RawPlan,
5193    /// The mz_expr::MirRelationExpr after decorrelation
5194    DecorrelatedPlan,
5195    /// The mz_expr::MirRelationExpr after local optimization
5196    LocalPlan,
5197    /// The mz_expr::MirRelationExpr after global optimization
5198    GlobalPlan,
5199    /// The mz_compute_types::plan::Plan
5200    PhysicalPlan,
5201    /// The complete trace of the plan through the optimizer
5202    Trace,
5203    /// Insights about the plan
5204    PlanInsights,
5205}
5206
5207impl ExplainStage {
5208    /// Return the tracing path that corresponds to a given stage.
5209    pub fn paths(&self) -> Option<SmallVec<[NamedPlan; 4]>> {
5210        use NamedPlan::*;
5211        match self {
5212            Self::RawPlan => Some(smallvec![Raw]),
5213            Self::DecorrelatedPlan => Some(smallvec![Decorrelated]),
5214            Self::LocalPlan => Some(smallvec![Local]),
5215            Self::GlobalPlan => Some(smallvec![Global]),
5216            Self::PhysicalPlan => Some(smallvec![Physical]),
5217            Self::Trace => None,
5218            Self::PlanInsights => Some(smallvec![Raw, Global, FastPath]),
5219        }
5220    }
5221
5222    // Whether instead of the plan associated with this [`ExplainStage`] we
5223    // should show the [`NamedPlan::FastPath`] plan if available.
5224    pub fn show_fast_path(&self) -> bool {
5225        match self {
5226            Self::RawPlan => false,
5227            Self::DecorrelatedPlan => false,
5228            Self::LocalPlan => false,
5229            Self::GlobalPlan => true,
5230            Self::PhysicalPlan => true,
5231            Self::Trace => false,
5232            Self::PlanInsights => false,
5233        }
5234    }
5235}
5236
5237impl AstDisplay for ExplainStage {
5238    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5239        match self {
5240            Self::RawPlan => f.write_str("RAW PLAN"),
5241            Self::DecorrelatedPlan => f.write_str("DECORRELATED PLAN"),
5242            Self::LocalPlan => f.write_str("LOCALLY OPTIMIZED PLAN"),
5243            Self::GlobalPlan => f.write_str("OPTIMIZED PLAN"),
5244            Self::PhysicalPlan => f.write_str("PHYSICAL PLAN"),
5245            Self::Trace => f.write_str("OPTIMIZER TRACE"),
5246            Self::PlanInsights => f.write_str("PLAN INSIGHTS"),
5247        }
5248    }
5249}
5250impl_display!(ExplainStage);
5251
5252/// An enum of named plans that identifies specific stages in an optimizer trace
5253/// where these plans can be found.
5254#[derive(Clone)]
5255pub enum NamedPlan {
5256    Raw,
5257    Decorrelated,
5258    Local,
5259    Global,
5260    Physical,
5261    FastPath,
5262}
5263
5264impl NamedPlan {
5265    /// Return the [`NamedPlan`] for a given `path` if it exists.
5266    pub fn of_path(value: &str) -> Option<Self> {
5267        match value {
5268            "optimize/raw" => Some(Self::Raw),
5269            "optimize/hir_to_mir" => Some(Self::Decorrelated),
5270            "optimize/local" => Some(Self::Local),
5271            "optimize/global" => Some(Self::Global),
5272            "optimize/finalize_dataflow" => Some(Self::Physical),
5273            "optimize/fast_path" => Some(Self::FastPath),
5274            _ => None,
5275        }
5276    }
5277
5278    /// Return the tracing path under which the plan can be found in an
5279    /// optimizer trace.
5280    pub fn path(&self) -> &'static str {
5281        match self {
5282            Self::Raw => "optimize/raw",
5283            Self::Decorrelated => "optimize/hir_to_mir",
5284            Self::Local => "optimize/local",
5285            Self::Global => "optimize/global",
5286            Self::Physical => "optimize/finalize_dataflow",
5287            Self::FastPath => "optimize/fast_path",
5288        }
5289    }
5290}
5291
5292/// What is being explained.
5293/// The bools mean whether this is an EXPLAIN BROKEN.
5294#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5295pub enum Explainee<T: AstInfo> {
5296    View(T::ItemName),
5297    MaterializedView(T::ItemName),
5298    Index(T::ItemName),
5299    ReplanView(T::ItemName),
5300    ReplanMaterializedView(T::ItemName),
5301    ReplanIndex(T::ItemName),
5302    Select(Box<SelectStatement<T>>, bool),
5303    CreateView(Box<CreateViewStatement<T>>, bool),
5304    CreateMaterializedView(Box<CreateMaterializedViewStatement<T>>, bool),
5305    CreateIndex(Box<CreateIndexStatement<T>>, bool),
5306    Subscribe(Box<SubscribeStatement<T>>, bool),
5307}
5308
5309impl<T: AstInfo> Explainee<T> {
5310    pub fn name(&self) -> Option<&T::ItemName> {
5311        match self {
5312            Self::View(name)
5313            | Self::ReplanView(name)
5314            | Self::MaterializedView(name)
5315            | Self::ReplanMaterializedView(name)
5316            | Self::Index(name)
5317            | Self::ReplanIndex(name) => Some(name),
5318            Self::Select(..)
5319            | Self::CreateView(..)
5320            | Self::CreateMaterializedView(..)
5321            | Self::CreateIndex(..)
5322            | Self::Subscribe(..) => None,
5323        }
5324    }
5325
5326    pub fn is_view(&self) -> bool {
5327        use Explainee::*;
5328        matches!(self, View(_) | ReplanView(_) | CreateView(_, _))
5329    }
5330}
5331
5332impl<T: AstInfo> AstDisplay for Explainee<T> {
5333    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5334        match self {
5335            Self::View(name) => {
5336                f.write_str("VIEW ");
5337                f.write_node(name);
5338            }
5339            Self::MaterializedView(name) => {
5340                f.write_str("MATERIALIZED VIEW ");
5341                f.write_node(name);
5342            }
5343            Self::Index(name) => {
5344                f.write_str("INDEX ");
5345                f.write_node(name);
5346            }
5347            Self::ReplanView(name) => {
5348                f.write_str("REPLAN VIEW ");
5349                f.write_node(name);
5350            }
5351            Self::ReplanMaterializedView(name) => {
5352                f.write_str("REPLAN MATERIALIZED VIEW ");
5353                f.write_node(name);
5354            }
5355            Self::ReplanIndex(name) => {
5356                f.write_str("REPLAN INDEX ");
5357                f.write_node(name);
5358            }
5359            Self::Select(select, broken) => {
5360                if *broken {
5361                    f.write_str("BROKEN ");
5362                }
5363                f.write_node(select);
5364            }
5365            Self::CreateView(statement, broken) => {
5366                if *broken {
5367                    f.write_str("BROKEN ");
5368                }
5369                f.write_node(statement);
5370            }
5371            Self::CreateMaterializedView(statement, broken) => {
5372                if *broken {
5373                    f.write_str("BROKEN ");
5374                }
5375                f.write_node(statement);
5376            }
5377            Self::CreateIndex(statement, broken) => {
5378                if *broken {
5379                    f.write_str("BROKEN ");
5380                }
5381                f.write_node(statement);
5382            }
5383            Self::Subscribe(statement, broken) => {
5384                if *broken {
5385                    f.write_str("BROKEN ");
5386                }
5387                f.write_node(statement);
5388            }
5389        }
5390    }
5391}
5392impl_display_t!(Explainee);
5393
5394#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
5395pub enum ExplainFormat {
5396    /// Human readable display format
5397    Text,
5398    /// Human readable display format with full debug information
5399    VerboseText,
5400    /// Machine-consumable JSON format
5401    Json,
5402    /// Machine-consumable DOT (graphviz) format
5403    Dot,
5404}
5405
5406impl AstDisplay for ExplainFormat {
5407    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5408        match self {
5409            Self::Text => f.write_str("TEXT"),
5410            Self::VerboseText => f.write_str("VERBOSE TEXT"),
5411            Self::Json => f.write_str("JSON"),
5412            Self::Dot => f.write_str("DOT"),
5413        }
5414    }
5415}
5416impl_display!(ExplainFormat);
5417
5418#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5419pub enum IfExistsBehavior {
5420    Error,
5421    Skip,
5422    Replace,
5423}
5424
5425/// `DECLARE ...`
5426#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5427pub struct DeclareStatement<T: AstInfo> {
5428    pub name: Ident,
5429    pub stmt: Box<T::NestedStatement>,
5430    pub sql: String,
5431}
5432
5433impl<T: AstInfo> AstDisplay for DeclareStatement<T> {
5434    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5435        f.write_str("DECLARE ");
5436        f.write_node(&self.name);
5437        f.write_str(" CURSOR FOR ");
5438        f.write_node(&self.stmt);
5439    }
5440}
5441impl_display_t!(DeclareStatement);
5442
5443/// `CLOSE ...`
5444#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5445pub struct CloseStatement {
5446    pub name: Ident,
5447}
5448
5449impl AstDisplay for CloseStatement {
5450    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5451        f.write_str("CLOSE ");
5452        f.write_node(&self.name);
5453    }
5454}
5455impl_display!(CloseStatement);
5456
5457#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5458pub enum FetchOptionName {
5459    Timeout,
5460}
5461
5462impl AstDisplay for FetchOptionName {
5463    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5464        f.write_str(match self {
5465            FetchOptionName::Timeout => "TIMEOUT",
5466        })
5467    }
5468}
5469
5470impl WithOptionName for FetchOptionName {
5471    /// # WARNING
5472    ///
5473    /// Whenever implementing this trait consider very carefully whether or not
5474    /// this value could contain sensitive user data. If you're uncertain, err
5475    /// on the conservative side and return `true`.
5476    fn redact_value(&self) -> bool {
5477        match self {
5478            FetchOptionName::Timeout => false,
5479        }
5480    }
5481}
5482
5483#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5484pub struct FetchOption<T: AstInfo> {
5485    pub name: FetchOptionName,
5486    pub value: Option<WithOptionValue<T>>,
5487}
5488impl_display_for_with_option!(FetchOption);
5489
5490/// `FETCH ...`
5491#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5492pub struct FetchStatement<T: AstInfo> {
5493    pub name: Ident,
5494    pub count: Option<FetchDirection>,
5495    pub options: Vec<FetchOption<T>>,
5496}
5497
5498impl<T: AstInfo> AstDisplay for FetchStatement<T> {
5499    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5500        f.write_str("FETCH ");
5501        if let Some(ref count) = self.count {
5502            f.write_str(format!("{} ", count));
5503        }
5504        // `FETCH` consumes an optional leading `FORWARD` keyword, so a cursor
5505        // literally named `forward` printed bare with no preceding count would
5506        // be swallowed on reparse, leaving no cursor name. Force it to quote.
5507        if self.count.is_none() && self.name.as_str().eq_ignore_ascii_case("forward") {
5508            f.write_str(self.name.to_ast_string_stable());
5509        } else {
5510            f.write_node(&self.name);
5511        }
5512        if !self.options.is_empty() {
5513            f.write_str(" WITH (");
5514            f.write_node(&display::comma_separated(&self.options));
5515            f.write_str(")");
5516        }
5517    }
5518}
5519impl_display_t!(FetchStatement);
5520
5521#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5522pub enum FetchDirection {
5523    ForwardAll,
5524    ForwardCount(u64),
5525}
5526
5527impl AstDisplay for FetchDirection {
5528    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5529        match self {
5530            FetchDirection::ForwardAll => f.write_str("ALL"),
5531            FetchDirection::ForwardCount(count) => f.write_str(format!("{}", count)),
5532        }
5533    }
5534}
5535impl_display!(FetchDirection);
5536
5537/// `PREPARE ...`
5538#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5539pub struct PrepareStatement<T: AstInfo> {
5540    pub name: Ident,
5541    pub stmt: Box<T::NestedStatement>,
5542    pub sql: String,
5543}
5544
5545impl<T: AstInfo> AstDisplay for PrepareStatement<T> {
5546    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5547        f.write_str("PREPARE ");
5548        f.write_node(&self.name);
5549        f.write_str(" AS ");
5550        f.write_node(&self.stmt);
5551    }
5552}
5553impl_display_t!(PrepareStatement);
5554
5555/// `EXECUTE ...`
5556#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5557pub struct ExecuteStatement<T: AstInfo> {
5558    pub name: Ident,
5559    pub params: Vec<Expr<T>>,
5560}
5561
5562impl<T: AstInfo> AstDisplay for ExecuteStatement<T> {
5563    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5564        f.write_str("EXECUTE ");
5565        f.write_node(&self.name);
5566        if !self.params.is_empty() {
5567            f.write_str(" (");
5568            f.write_node(&display::comma_separated(&self.params));
5569            f.write_str(")");
5570        }
5571    }
5572}
5573impl_display_t!(ExecuteStatement);
5574
5575/// `EXECUTE UNIT TEST ...`
5576#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5577pub struct ExecuteUnitTestStatement<T: AstInfo> {
5578    pub name: Ident,
5579    pub target: T::ItemName,
5580    pub at_time: Option<Expr<T>>,
5581    pub mocks: Vec<MockViewDef<T>>,
5582    pub expected: ExpectedResultDef<T>,
5583}
5584
5585impl<T: AstInfo> AstDisplay for ExecuteUnitTestStatement<T> {
5586    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5587        f.write_str("EXECUTE UNIT TEST ");
5588        f.write_node(&self.name);
5589        f.write_str(" FOR ");
5590        f.write_node(&self.target);
5591        if let Some(at_time) = &self.at_time {
5592            f.write_str(" AT TIME ");
5593            f.write_node(at_time);
5594        }
5595        for (i, mock) in self.mocks.iter().enumerate() {
5596            f.write_str(if i == 0 { " MOCK " } else { ", MOCK " });
5597            f.write_node(mock);
5598        }
5599        f.write_str(" EXPECTED ");
5600        f.write_node(&self.expected);
5601    }
5602}
5603impl_display_t!(ExecuteUnitTestStatement);
5604
5605/// Mock view definition for EXECUTE UNIT TEST
5606#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5607pub struct MockViewDef<T: AstInfo> {
5608    pub name: T::ItemName,
5609    pub columns: Vec<ColumnDef<T>>,
5610    pub query: Query<T>,
5611}
5612
5613impl<T: AstInfo> AstDisplay for MockViewDef<T> {
5614    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5615        f.write_node(&self.name);
5616        f.write_str("(");
5617        f.write_node(&display::comma_separated(&self.columns));
5618        f.write_str(") AS (");
5619        f.write_node(&self.query);
5620        f.write_str(")");
5621    }
5622}
5623impl_display_t!(MockViewDef);
5624
5625/// Expected result definition for EXECUTE UNIT TEST
5626#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5627pub struct ExpectedResultDef<T: AstInfo> {
5628    pub columns: Vec<ColumnDef<T>>,
5629    pub query: Query<T>,
5630}
5631
5632impl<T: AstInfo> AstDisplay for ExpectedResultDef<T> {
5633    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5634        f.write_str("(");
5635        f.write_node(&display::comma_separated(&self.columns));
5636        f.write_str(") AS (");
5637        f.write_node(&self.query);
5638        f.write_str(")");
5639    }
5640}
5641impl_display_t!(ExpectedResultDef);
5642
5643/// `DEALLOCATE ...`
5644#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5645pub struct DeallocateStatement {
5646    pub name: Option<Ident>,
5647}
5648
5649impl AstDisplay for DeallocateStatement {
5650    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5651        f.write_str("DEALLOCATE ");
5652        match &self.name {
5653            Some(name) => f.write_node(name),
5654            None => f.write_str("ALL"),
5655        };
5656    }
5657}
5658impl_display!(DeallocateStatement);
5659
5660/// `RAISE ...`
5661#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5662pub struct RaiseStatement {
5663    pub severity: NoticeSeverity,
5664}
5665
5666impl AstDisplay for RaiseStatement {
5667    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5668        f.write_str("RAISE ");
5669        f.write_node(&self.severity);
5670    }
5671}
5672impl_display!(RaiseStatement);
5673
5674#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5675pub enum NoticeSeverity {
5676    Debug,
5677    Info,
5678    Log,
5679    Notice,
5680    Warning,
5681}
5682
5683impl AstDisplay for NoticeSeverity {
5684    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5685        f.write_str(match self {
5686            NoticeSeverity::Debug => "DEBUG",
5687            NoticeSeverity::Info => "INFO",
5688            NoticeSeverity::Log => "LOG",
5689            NoticeSeverity::Notice => "NOTICE",
5690            NoticeSeverity::Warning => "WARNING",
5691        })
5692    }
5693}
5694impl_display!(NoticeSeverity);
5695
5696/// `ALTER SYSTEM SET ...`
5697#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5698pub struct AlterSystemSetStatement {
5699    pub name: Ident,
5700    pub to: SetVariableTo,
5701}
5702
5703impl AstDisplay for AlterSystemSetStatement {
5704    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5705        f.write_str("ALTER SYSTEM SET ");
5706        f.write_node(&self.name);
5707        f.write_str(" = ");
5708        f.write_node(&self.to);
5709    }
5710}
5711impl_display!(AlterSystemSetStatement);
5712
5713/// `ALTER SYSTEM RESET ...`
5714#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5715pub struct AlterSystemResetStatement {
5716    pub name: Ident,
5717}
5718
5719impl AstDisplay for AlterSystemResetStatement {
5720    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5721        f.write_str("ALTER SYSTEM RESET ");
5722        f.write_node(&self.name);
5723    }
5724}
5725impl_display!(AlterSystemResetStatement);
5726
5727/// `ALTER SYSTEM RESET ALL`
5728#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5729pub struct AlterSystemResetAllStatement {}
5730
5731impl AstDisplay for AlterSystemResetAllStatement {
5732    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5733        f.write_str("ALTER SYSTEM RESET ALL");
5734    }
5735}
5736impl_display!(AlterSystemResetAllStatement);
5737
5738#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5739pub enum AsOf<T: AstInfo> {
5740    At(Expr<T>),
5741    AtLeast(Expr<T>),
5742}
5743
5744impl<T: AstInfo> AstDisplay for AsOf<T> {
5745    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5746        f.write_str("AS OF ");
5747        match self {
5748            AsOf::At(expr) => f.write_node(expr),
5749            AsOf::AtLeast(expr) => {
5750                f.write_str("AT LEAST ");
5751                f.write_node(expr);
5752            }
5753        }
5754    }
5755}
5756impl_display_t!(AsOf);
5757
5758#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
5759pub enum ShowStatement<T: AstInfo> {
5760    ShowObjects(ShowObjectsStatement<T>),
5761    ShowColumns(ShowColumnsStatement<T>),
5762    ShowCreateView(ShowCreateViewStatement<T>),
5763    ShowCreateMaterializedView(ShowCreateMaterializedViewStatement<T>),
5764    ShowCreateSource(ShowCreateSourceStatement<T>),
5765    ShowCreateTable(ShowCreateTableStatement<T>),
5766    ShowCreateSink(ShowCreateSinkStatement<T>),
5767    ShowCreateMetricSink(ShowCreateMetricSinkStatement<T>),
5768    ShowCreateIndex(ShowCreateIndexStatement<T>),
5769    ShowCreateConnection(ShowCreateConnectionStatement<T>),
5770    ShowCreateCluster(ShowCreateClusterStatement<T>),
5771    ShowCreateType(ShowCreateTypeStatement<T>),
5772    ShowVariable(ShowVariableStatement),
5773    InspectShard(InspectShardStatement),
5774}
5775
5776impl<T: AstInfo> AstDisplay for ShowStatement<T> {
5777    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5778        match self {
5779            ShowStatement::ShowObjects(stmt) => f.write_node(stmt),
5780            ShowStatement::ShowColumns(stmt) => f.write_node(stmt),
5781            ShowStatement::ShowCreateView(stmt) => f.write_node(stmt),
5782            ShowStatement::ShowCreateMaterializedView(stmt) => f.write_node(stmt),
5783            ShowStatement::ShowCreateSource(stmt) => f.write_node(stmt),
5784            ShowStatement::ShowCreateTable(stmt) => f.write_node(stmt),
5785            ShowStatement::ShowCreateSink(stmt) => f.write_node(stmt),
5786            ShowStatement::ShowCreateMetricSink(stmt) => f.write_node(stmt),
5787            ShowStatement::ShowCreateIndex(stmt) => f.write_node(stmt),
5788            ShowStatement::ShowCreateConnection(stmt) => f.write_node(stmt),
5789            ShowStatement::ShowCreateCluster(stmt) => f.write_node(stmt),
5790            ShowStatement::ShowCreateType(stmt) => f.write_node(stmt),
5791            ShowStatement::ShowVariable(stmt) => f.write_node(stmt),
5792            ShowStatement::InspectShard(stmt) => f.write_node(stmt),
5793        }
5794    }
5795}
5796impl_display_t!(ShowStatement);
5797
5798/// `GRANT ...`
5799#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5800pub struct GrantRoleStatement<T: AstInfo> {
5801    /// The roles that are gaining members.
5802    pub role_names: Vec<T::RoleName>,
5803    /// The roles that will be added to `role_name`.
5804    pub member_names: Vec<T::RoleName>,
5805}
5806
5807impl<T: AstInfo> AstDisplay for GrantRoleStatement<T> {
5808    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5809        f.write_str("GRANT ");
5810        f.write_node(&display::comma_separated(&self.role_names));
5811        f.write_str(" TO ");
5812        f.write_node(&display::comma_separated(&self.member_names));
5813    }
5814}
5815impl_display_t!(GrantRoleStatement);
5816
5817/// `REVOKE ...`
5818#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5819pub struct RevokeRoleStatement<T: AstInfo> {
5820    /// The roles that are losing members.
5821    pub role_names: Vec<T::RoleName>,
5822    /// The roles that will be removed from `role_name`.
5823    pub member_names: Vec<T::RoleName>,
5824}
5825
5826impl<T: AstInfo> AstDisplay for RevokeRoleStatement<T> {
5827    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5828        f.write_str("REVOKE ");
5829        f.write_node(&display::comma_separated(&self.role_names));
5830        f.write_str(" FROM ");
5831        f.write_node(&display::comma_separated(&self.member_names));
5832    }
5833}
5834impl_display_t!(RevokeRoleStatement);
5835
5836#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5837pub enum Privilege {
5838    SELECT,
5839    INSERT,
5840    UPDATE,
5841    DELETE,
5842    USAGE,
5843    CREATE,
5844    CREATEROLE,
5845    CREATEDB,
5846    CREATECLUSTER,
5847    CREATENETWORKPOLICY,
5848    CREATEQUERYPOLICY,
5849}
5850
5851impl AstDisplay for Privilege {
5852    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5853        f.write_str(match self {
5854            Privilege::SELECT => "SELECT",
5855            Privilege::INSERT => "INSERT",
5856            Privilege::UPDATE => "UPDATE",
5857            Privilege::DELETE => "DELETE",
5858            Privilege::CREATE => "CREATE",
5859            Privilege::USAGE => "USAGE",
5860            Privilege::CREATEROLE => "CREATEROLE",
5861            Privilege::CREATEDB => "CREATEDB",
5862            Privilege::CREATECLUSTER => "CREATECLUSTER",
5863            Privilege::CREATENETWORKPOLICY => "CREATENETWORKPOLICY",
5864            Privilege::CREATEQUERYPOLICY => "CREATEQUERYPOLICY",
5865        });
5866    }
5867}
5868impl_display!(Privilege);
5869
5870#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5871pub enum PrivilegeSpecification {
5872    All,
5873    Privileges(Vec<Privilege>),
5874}
5875
5876impl AstDisplay for PrivilegeSpecification {
5877    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5878        match self {
5879            PrivilegeSpecification::All => f.write_str("ALL"),
5880            PrivilegeSpecification::Privileges(privileges) => {
5881                f.write_node(&display::comma_separated(privileges))
5882            }
5883        }
5884    }
5885}
5886impl_display!(PrivilegeSpecification);
5887
5888#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5889pub enum GrantTargetSpecification<T: AstInfo> {
5890    Object {
5891        /// The type of object.
5892        ///
5893        /// Note: For views, materialized views, and sources this will be [`ObjectType::Table`].
5894        object_type: ObjectType,
5895        /// Specification of each object affected.
5896        object_spec_inner: GrantTargetSpecificationInner<T>,
5897    },
5898    System,
5899}
5900
5901#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5902pub enum GrantTargetSpecificationInner<T: AstInfo> {
5903    All(GrantTargetAllSpecification<T>),
5904    Objects { names: Vec<T::ObjectName> },
5905}
5906
5907#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5908pub enum GrantTargetAllSpecification<T: AstInfo> {
5909    All,
5910    AllDatabases { databases: Vec<T::DatabaseName> },
5911    AllSchemas { schemas: Vec<T::SchemaName> },
5912}
5913
5914impl<T: AstInfo> GrantTargetAllSpecification<T> {
5915    pub fn len(&self) -> usize {
5916        match self {
5917            GrantTargetAllSpecification::All => 1,
5918            GrantTargetAllSpecification::AllDatabases { databases } => databases.len(),
5919            GrantTargetAllSpecification::AllSchemas { schemas } => schemas.len(),
5920        }
5921    }
5922}
5923
5924/// Writes the plural keyword for `object_type` as `GRANT`/`REVOKE ... ON ALL`
5925/// expects it. Most object types just take a trailing `S` (`TABLES`, `SECRETS`,
5926/// ...), but `NETWORK POLICY` pluralizes to the `POLICIES` keyword the parser
5927/// accepts — naively appending `S` would emit `NETWORK POLICYS`, which fails to
5928/// reparse.
5929fn write_grant_object_type_plural<W: fmt::Write>(
5930    f: &mut AstFormatter<W>,
5931    object_type: &ObjectType,
5932) {
5933    match object_type {
5934        ObjectType::NetworkPolicy => f.write_str("POLICIES"),
5935        ObjectType::QueryPolicy => f.write_str("QUERY POLICIES"),
5936        other => {
5937            f.write_node(other);
5938            f.write_str("S");
5939        }
5940    }
5941}
5942
5943impl<T: AstInfo> AstDisplay for GrantTargetSpecification<T> {
5944    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5945        match self {
5946            GrantTargetSpecification::Object {
5947                object_type,
5948                object_spec_inner,
5949            } => match object_spec_inner {
5950                GrantTargetSpecificationInner::All(all_spec) => match all_spec {
5951                    GrantTargetAllSpecification::All => {
5952                        f.write_str("ALL ");
5953                        write_grant_object_type_plural(f, object_type);
5954                    }
5955                    GrantTargetAllSpecification::AllDatabases { databases } => {
5956                        f.write_str("ALL ");
5957                        write_grant_object_type_plural(f, object_type);
5958                        f.write_str(" IN DATABASE ");
5959                        f.write_node(&display::comma_separated(databases));
5960                    }
5961                    GrantTargetAllSpecification::AllSchemas { schemas } => {
5962                        f.write_str("ALL ");
5963                        write_grant_object_type_plural(f, object_type);
5964                        f.write_str(" IN SCHEMA ");
5965                        f.write_node(&display::comma_separated(schemas));
5966                    }
5967                },
5968                GrantTargetSpecificationInner::Objects { names } => {
5969                    f.write_node(object_type);
5970                    f.write_str(" ");
5971                    f.write_node(&display::comma_separated(names));
5972                }
5973            },
5974            GrantTargetSpecification::System => f.write_str("SYSTEM"),
5975        }
5976    }
5977}
5978impl_display_t!(GrantTargetSpecification);
5979
5980/// `GRANT ...`
5981#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5982pub struct GrantPrivilegesStatement<T: AstInfo> {
5983    /// The privileges being granted on an object.
5984    pub privileges: PrivilegeSpecification,
5985    /// The objects that are affected by the GRANT.
5986    pub target: GrantTargetSpecification<T>,
5987    /// The roles that will granted the privileges.
5988    pub roles: Vec<T::RoleName>,
5989}
5990
5991impl<T: AstInfo> AstDisplay for GrantPrivilegesStatement<T> {
5992    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
5993        f.write_str("GRANT ");
5994        f.write_node(&self.privileges);
5995        f.write_str(" ON ");
5996        f.write_node(&self.target);
5997        f.write_str(" TO ");
5998        f.write_node(&display::comma_separated(&self.roles));
5999    }
6000}
6001impl_display_t!(GrantPrivilegesStatement);
6002
6003/// `REVOKE ...`
6004#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6005pub struct RevokePrivilegesStatement<T: AstInfo> {
6006    /// The privileges being revoked.
6007    pub privileges: PrivilegeSpecification,
6008    /// The objects that are affected by the REVOKE.
6009    pub target: GrantTargetSpecification<T>,
6010    /// The roles that will have privileges revoked.
6011    pub roles: Vec<T::RoleName>,
6012}
6013
6014impl<T: AstInfo> AstDisplay for RevokePrivilegesStatement<T> {
6015    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6016        f.write_str("REVOKE ");
6017        f.write_node(&self.privileges);
6018        f.write_str(" ON ");
6019        f.write_node(&self.target);
6020        f.write_str(" FROM ");
6021        f.write_node(&display::comma_separated(&self.roles));
6022    }
6023}
6024impl_display_t!(RevokePrivilegesStatement);
6025
6026#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6027pub enum TargetRoleSpecification<T: AstInfo> {
6028    /// Specific list of roles.
6029    Roles(Vec<T::RoleName>),
6030    /// All current and future roles.
6031    AllRoles,
6032}
6033
6034impl<T: AstInfo> AstDisplay for TargetRoleSpecification<T> {
6035    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6036        match self {
6037            TargetRoleSpecification::Roles(roles) => f.write_node(&display::comma_separated(roles)),
6038            TargetRoleSpecification::AllRoles => f.write_str("ALL ROLES"),
6039        }
6040    }
6041}
6042impl_display_t!(TargetRoleSpecification);
6043
6044#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6045pub struct AbbreviatedGrantStatement<T: AstInfo> {
6046    /// The privileges being granted.
6047    pub privileges: PrivilegeSpecification,
6048    /// The type of object.
6049    ///
6050    /// Note: For views, materialized views, and sources this will be [`ObjectType::Table`].
6051    pub object_type: ObjectType,
6052    /// The roles that will granted the privileges.
6053    pub grantees: Vec<T::RoleName>,
6054}
6055
6056impl<T: AstInfo> AstDisplay for AbbreviatedGrantStatement<T> {
6057    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6058        f.write_str("GRANT ");
6059        f.write_node(&self.privileges);
6060        f.write_str(" ON ");
6061        write_grant_object_type_plural(f, &self.object_type);
6062        f.write_str(" TO ");
6063        f.write_node(&display::comma_separated(&self.grantees));
6064    }
6065}
6066impl_display_t!(AbbreviatedGrantStatement);
6067
6068#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6069pub struct AbbreviatedRevokeStatement<T: AstInfo> {
6070    /// The privileges being revoked.
6071    pub privileges: PrivilegeSpecification,
6072    /// The type of object.
6073    ///
6074    /// Note: For views, materialized views, and sources this will be [`ObjectType::Table`].
6075    pub object_type: ObjectType,
6076    /// The roles that the privilege will be revoked from.
6077    pub revokees: Vec<T::RoleName>,
6078}
6079
6080impl<T: AstInfo> AstDisplay for AbbreviatedRevokeStatement<T> {
6081    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6082        f.write_str("REVOKE ");
6083        f.write_node(&self.privileges);
6084        f.write_str(" ON ");
6085        write_grant_object_type_plural(f, &self.object_type);
6086        f.write_str(" FROM ");
6087        f.write_node(&display::comma_separated(&self.revokees));
6088    }
6089}
6090impl_display_t!(AbbreviatedRevokeStatement);
6091
6092#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6093pub enum AbbreviatedGrantOrRevokeStatement<T: AstInfo> {
6094    Grant(AbbreviatedGrantStatement<T>),
6095    Revoke(AbbreviatedRevokeStatement<T>),
6096}
6097
6098impl<T: AstInfo> AbbreviatedGrantOrRevokeStatement<T> {
6099    pub fn privileges(&self) -> &PrivilegeSpecification {
6100        match self {
6101            AbbreviatedGrantOrRevokeStatement::Grant(grant) => &grant.privileges,
6102            AbbreviatedGrantOrRevokeStatement::Revoke(revoke) => &revoke.privileges,
6103        }
6104    }
6105
6106    pub fn object_type(&self) -> &ObjectType {
6107        match self {
6108            AbbreviatedGrantOrRevokeStatement::Grant(grant) => &grant.object_type,
6109            AbbreviatedGrantOrRevokeStatement::Revoke(revoke) => &revoke.object_type,
6110        }
6111    }
6112
6113    pub fn roles(&self) -> &Vec<T::RoleName> {
6114        match self {
6115            AbbreviatedGrantOrRevokeStatement::Grant(grant) => &grant.grantees,
6116            AbbreviatedGrantOrRevokeStatement::Revoke(revoke) => &revoke.revokees,
6117        }
6118    }
6119}
6120
6121impl<T: AstInfo> AstDisplay for AbbreviatedGrantOrRevokeStatement<T> {
6122    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6123        match self {
6124            AbbreviatedGrantOrRevokeStatement::Grant(grant) => f.write_node(grant),
6125            AbbreviatedGrantOrRevokeStatement::Revoke(revoke) => f.write_node(revoke),
6126        }
6127    }
6128}
6129impl_display_t!(AbbreviatedGrantOrRevokeStatement);
6130
6131/// `ALTER DEFAULT PRIVILEGES ...`
6132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6133pub struct AlterDefaultPrivilegesStatement<T: AstInfo> {
6134    /// The roles for which created objects are affected.
6135    pub target_roles: TargetRoleSpecification<T>,
6136    /// The objects that are affected by the default privilege.
6137    pub target_objects: GrantTargetAllSpecification<T>,
6138    /// The privilege to grant or revoke.
6139    pub grant_or_revoke: AbbreviatedGrantOrRevokeStatement<T>,
6140}
6141
6142impl<T: AstInfo> AstDisplay for AlterDefaultPrivilegesStatement<T> {
6143    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6144        f.write_str("ALTER DEFAULT PRIVILEGES");
6145        match &self.target_roles {
6146            TargetRoleSpecification::Roles(_) => {
6147                f.write_str(" FOR ROLE ");
6148                f.write_node(&self.target_roles);
6149            }
6150            TargetRoleSpecification::AllRoles => {
6151                f.write_str(" FOR ");
6152                f.write_node(&self.target_roles);
6153            }
6154        }
6155        match &self.target_objects {
6156            GrantTargetAllSpecification::All => {}
6157            GrantTargetAllSpecification::AllDatabases { databases } => {
6158                f.write_str(" IN DATABASE ");
6159                f.write_node(&display::comma_separated(databases));
6160            }
6161            GrantTargetAllSpecification::AllSchemas { schemas } => {
6162                f.write_str(" IN SCHEMA ");
6163                f.write_node(&display::comma_separated(schemas));
6164            }
6165        }
6166        f.write_str(" ");
6167        f.write_node(&self.grant_or_revoke);
6168    }
6169}
6170impl_display_t!(AlterDefaultPrivilegesStatement);
6171
6172/// `REASSIGN OWNED ...`
6173#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6174pub struct ReassignOwnedStatement<T: AstInfo> {
6175    /// The roles whose owned objects are being reassigned.
6176    pub old_roles: Vec<T::RoleName>,
6177    /// The new owner of the objects.
6178    pub new_role: T::RoleName,
6179}
6180
6181impl<T: AstInfo> AstDisplay for ReassignOwnedStatement<T> {
6182    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6183        f.write_str("REASSIGN OWNED BY ");
6184        f.write_node(&display::comma_separated(&self.old_roles));
6185        f.write_str(" TO ");
6186        f.write_node(&self.new_role);
6187    }
6188}
6189impl_display_t!(ReassignOwnedStatement);
6190
6191/// `COMMENT ON ...`
6192#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6193pub struct CommentStatement<T: AstInfo> {
6194    pub object: CommentObjectType<T>,
6195    pub comment: Option<String>,
6196}
6197
6198impl<T: AstInfo> AstDisplay for CommentStatement<T> {
6199    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6200        f.write_str("COMMENT ON ");
6201        f.write_node(&self.object);
6202
6203        f.write_str(" IS ");
6204        match &self.comment {
6205            Some(s) => {
6206                if f.redacted() {
6207                    // The comment body is arbitrary free text and may contain PII,
6208                    // so redact it like every other user-supplied value.
6209                    f.write_str("'<REDACTED>'");
6210                } else {
6211                    f.write_str("'");
6212                    f.write_node(&display::escape_single_quote_string(s));
6213                    f.write_str("'");
6214                }
6215            }
6216            None => f.write_str("NULL"),
6217        }
6218    }
6219}
6220impl_display_t!(CommentStatement);
6221
6222#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
6223pub struct ColumnName<T: AstInfo> {
6224    pub relation: T::ItemName,
6225    pub column: T::ColumnReference,
6226}
6227
6228impl<T: AstInfo> AstDisplay for ColumnName<T> {
6229    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6230        f.write_node(&self.relation);
6231        f.write_str(".");
6232        f.write_node(&self.column);
6233    }
6234}
6235impl_display_t!(ColumnName);
6236
6237#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6238pub enum CommentObjectType<T: AstInfo> {
6239    Table { name: T::ItemName },
6240    View { name: T::ItemName },
6241    Column { name: ColumnName<T> },
6242    MaterializedView { name: T::ItemName },
6243    Source { name: T::ItemName },
6244    Sink { name: T::ItemName },
6245    Index { name: T::ItemName },
6246    Func { name: T::ItemName },
6247    Connection { name: T::ItemName },
6248    Type { ty: T::DataType },
6249    Secret { name: T::ItemName },
6250    Role { name: T::RoleName },
6251    Database { name: T::DatabaseName },
6252    Schema { name: T::SchemaName },
6253    Cluster { name: T::ClusterName },
6254    ClusterReplica { name: QualifiedReplica },
6255    NetworkPolicy { name: T::NetworkPolicyName },
6256    QueryPolicy { name: Ident },
6257}
6258
6259impl<T: AstInfo> AstDisplay for CommentObjectType<T> {
6260    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
6261        use CommentObjectType::*;
6262
6263        match self {
6264            Table { name } => {
6265                f.write_str("TABLE ");
6266                f.write_node(name);
6267            }
6268            View { name } => {
6269                f.write_str("VIEW ");
6270                f.write_node(name);
6271            }
6272            Column { name } => {
6273                f.write_str("COLUMN ");
6274                f.write_node(name);
6275            }
6276            MaterializedView { name } => {
6277                f.write_str("MATERIALIZED VIEW ");
6278                f.write_node(name);
6279            }
6280            Source { name } => {
6281                f.write_str("SOURCE ");
6282                f.write_node(name);
6283            }
6284            Sink { name } => {
6285                f.write_str("SINK ");
6286                f.write_node(name);
6287            }
6288            Index { name } => {
6289                f.write_str("INDEX ");
6290                f.write_node(name);
6291            }
6292            Func { name } => {
6293                f.write_str("FUNCTION ");
6294                f.write_node(name);
6295            }
6296            Connection { name } => {
6297                f.write_str("CONNECTION ");
6298                f.write_node(name);
6299            }
6300            Type { ty } => {
6301                f.write_str("TYPE ");
6302                f.write_node(ty);
6303            }
6304            Secret { name } => {
6305                f.write_str("SECRET ");
6306                f.write_node(name);
6307            }
6308            Role { name } => {
6309                f.write_str("ROLE ");
6310                f.write_node(name);
6311            }
6312            Database { name } => {
6313                f.write_str("DATABASE ");
6314                f.write_node(name);
6315            }
6316            Schema { name } => {
6317                f.write_str("SCHEMA ");
6318                f.write_node(name);
6319            }
6320            Cluster { name } => {
6321                f.write_str("CLUSTER ");
6322                f.write_node(name);
6323            }
6324            ClusterReplica { name } => {
6325                f.write_str("CLUSTER REPLICA ");
6326                f.write_node(name);
6327            }
6328            NetworkPolicy { name } => {
6329                f.write_str("NETWORK POLICY ");
6330                f.write_node(name);
6331            }
6332            QueryPolicy { name } => {
6333                f.write_str("QUERY POLICY ");
6334                f.write_node(name);
6335            }
6336        }
6337    }
6338}
6339
6340impl_display_t!(CommentObjectType);
6341
6342// Include the `AstDisplay` implementations for simple options derived by the
6343// crate's build.rs script.
6344include!(concat!(env!("OUT_DIR"), "/display.simple_options.rs"));