Skip to main content

sqlparser/ast/
dcl.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! AST types specific to GRANT/REVOKE/ROLE variants of [`Statement`](crate::ast::Statement)
19//! (commonly referred to as Data Control Language, or DCL)
20
21#[cfg(not(feature = "std"))]
22use alloc::vec::Vec;
23use core::fmt;
24
25#[cfg(feature = "serde")]
26use serde::{Deserialize, Serialize};
27
28#[cfg(feature = "visitor")]
29use sqlparser_derive::{Visit, VisitMut};
30
31use super::{display_comma_separated, Expr, Ident, Password, Spanned};
32use crate::ast::{
33    display_separated, CascadeOption, CurrentGrantsKind, GrantObjects, Grantee, GranteeName,
34    ObjectName, Privileges,
35};
36use crate::tokenizer::Span;
37
38/// The object keyword in a `CREATE ROLE` or `CREATE GROUP` statement.
39#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
40#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
41#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
42pub enum RoleKeyword {
43    /// `ROLE`, the general role object in both PostgreSQL and Redshift.
44    Role,
45    /// `GROUP`, an obsolete spelling of `ROLE` in PostgreSQL, and a user group
46    /// distinct from a role in Redshift.
47    Group,
48}
49
50impl fmt::Display for RoleKeyword {
51    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52        f.write_str(match self {
53            RoleKeyword::Role => "ROLE",
54            RoleKeyword::Group => "GROUP",
55        })
56    }
57}
58
59/// An option in `ROLE` statement.
60///
61/// <https://www.postgresql.org/docs/current/sql-createrole.html>
62#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
63#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
64#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
65pub enum RoleOption {
66    /// Enable or disable BYPASSRLS.
67    BypassRLS(bool),
68    /// Connection limit expression.
69    ConnectionLimit(Expr),
70    /// CREATEDB flag.
71    CreateDB(bool),
72    /// CREATEROLE flag.
73    CreateRole(bool),
74    /// INHERIT flag.
75    Inherit(bool),
76    /// LOGIN flag.
77    Login(bool),
78    /// Password value or NULL password.
79    Password(Password),
80    /// Replication privilege flag.
81    Replication(bool),
82    /// SUPERUSER flag.
83    SuperUser(bool),
84    /// `VALID UNTIL` expression.
85    ValidUntil(Expr),
86}
87
88impl fmt::Display for RoleOption {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        match self {
91            RoleOption::BypassRLS(value) => {
92                write!(f, "{}", if *value { "BYPASSRLS" } else { "NOBYPASSRLS" })
93            }
94            RoleOption::ConnectionLimit(expr) => {
95                write!(f, "CONNECTION LIMIT {expr}")
96            }
97            RoleOption::CreateDB(value) => {
98                write!(f, "{}", if *value { "CREATEDB" } else { "NOCREATEDB" })
99            }
100            RoleOption::CreateRole(value) => {
101                write!(f, "{}", if *value { "CREATEROLE" } else { "NOCREATEROLE" })
102            }
103            RoleOption::Inherit(value) => {
104                write!(f, "{}", if *value { "INHERIT" } else { "NOINHERIT" })
105            }
106            RoleOption::Login(value) => {
107                write!(f, "{}", if *value { "LOGIN" } else { "NOLOGIN" })
108            }
109            RoleOption::Password(password) => match password {
110                Password::Password(expr) => write!(f, "PASSWORD {expr}"),
111                Password::NullPassword => write!(f, "PASSWORD NULL"),
112            },
113            RoleOption::Replication(value) => {
114                write!(
115                    f,
116                    "{}",
117                    if *value {
118                        "REPLICATION"
119                    } else {
120                        "NOREPLICATION"
121                    }
122                )
123            }
124            RoleOption::SuperUser(value) => {
125                write!(f, "{}", if *value { "SUPERUSER" } else { "NOSUPERUSER" })
126            }
127            RoleOption::ValidUntil(expr) => {
128                write!(f, "VALID UNTIL {expr}")
129            }
130        }
131    }
132}
133
134/// SET config value option:
135/// * SET `configuration_parameter` { TO | = } { `value` | DEFAULT }
136/// * SET `configuration_parameter` FROM CURRENT
137#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
138#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
139#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
140pub enum SetConfigValue {
141    /// Use the default value.
142    Default,
143    /// Use the current value (`FROM CURRENT`).
144    FromCurrent,
145    /// Set to the provided expression value.
146    Value(Expr),
147}
148
149/// RESET config option:
150/// * RESET `configuration_parameter`
151/// * RESET ALL
152#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
153#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
154#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
155pub enum ResetConfig {
156    /// Reset all configuration parameters.
157    ALL,
158    /// Reset the named configuration parameter.
159    ConfigName(ObjectName),
160}
161
162/// An `ALTER ROLE` (`Statement::AlterRole`) operation
163#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
164#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
165#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
166pub enum AlterRoleOperation {
167    /// Generic
168    RenameRole {
169        /// Role name to rename.
170        role_name: Ident,
171    },
172    /// MS SQL Server
173    /// <https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-role-transact-sql>
174    AddMember {
175        /// Member name to add to the role.
176        member_name: Ident,
177    },
178    /// MS SQL Server
179    ///
180    /// <https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-role-transact-sql>
181    DropMember {
182        /// Member name to remove from the role.
183        member_name: Ident,
184    },
185    /// PostgreSQL
186    /// <https://www.postgresql.org/docs/current/sql-alterrole.html>
187    WithOptions {
188        /// Role options to apply.
189        options: Vec<RoleOption>,
190    },
191    /// PostgreSQL
192    /// <https://www.postgresql.org/docs/current/sql-alterrole.html>
193    ///
194    /// `SET configuration_parameter { TO | = } { value | DEFAULT }`
195    Set {
196        /// Configuration name to set.
197        config_name: ObjectName,
198        /// Value to assign to the configuration.
199        config_value: SetConfigValue,
200        /// Optional database scope for the setting.
201        in_database: Option<ObjectName>,
202    },
203    /// PostgreSQL
204    /// <https://www.postgresql.org/docs/current/sql-alterrole.html>
205    ///
206    /// `RESET configuration_parameter` | `RESET ALL`
207    Reset {
208        /// Configuration to reset.
209        config_name: ResetConfig,
210        /// Optional database scope for the reset.
211        in_database: Option<ObjectName>,
212    },
213}
214
215impl fmt::Display for AlterRoleOperation {
216    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217        match self {
218            AlterRoleOperation::RenameRole { role_name } => {
219                write!(f, "RENAME TO {role_name}")
220            }
221            AlterRoleOperation::AddMember { member_name } => {
222                write!(f, "ADD MEMBER {member_name}")
223            }
224            AlterRoleOperation::DropMember { member_name } => {
225                write!(f, "DROP MEMBER {member_name}")
226            }
227            AlterRoleOperation::WithOptions { options } => {
228                write!(f, "WITH {}", display_separated(options, " "))
229            }
230            AlterRoleOperation::Set {
231                config_name,
232                config_value,
233                in_database,
234            } => {
235                if let Some(database_name) = in_database {
236                    write!(f, "IN DATABASE {database_name} ")?;
237                }
238
239                match config_value {
240                    SetConfigValue::Default => write!(f, "SET {config_name} TO DEFAULT"),
241                    SetConfigValue::FromCurrent => write!(f, "SET {config_name} FROM CURRENT"),
242                    SetConfigValue::Value(expr) => write!(f, "SET {config_name} TO {expr}"),
243                }
244            }
245            AlterRoleOperation::Reset {
246                config_name,
247                in_database,
248            } => {
249                if let Some(database_name) = in_database {
250                    write!(f, "IN DATABASE {database_name} ")?;
251                }
252
253                match config_name {
254                    ResetConfig::ALL => write!(f, "RESET ALL"),
255                    ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
256                }
257            }
258        }
259    }
260}
261
262/// A `USE` (`Statement::Use`) operation
263#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
264#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
265#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
266pub enum Use {
267    /// Switch to the given catalog (e.g. `USE CATALOG ...`).
268    Catalog(ObjectName),
269    /// Switch to the given schema (e.g. `USE SCHEMA ...`).
270    Schema(ObjectName),
271    /// Switch to the given database (e.g. `USE DATABASE ...`).
272    Database(ObjectName),
273    /// Switch to the given warehouse (e.g. `USE WAREHOUSE ...`).
274    Warehouse(ObjectName),
275    /// Switch to the given role (e.g. `USE ROLE ...`).
276    Role(ObjectName),
277    /// Use secondary roles specification (e.g. `USE SECONDARY ROLES ...`).
278    SecondaryRoles(SecondaryRoles),
279    /// Use the specified object (e.g. `USE foo.bar`).
280    Object(ObjectName),
281    /// Reset to default (e.g. `USE DEFAULT`).
282    Default,
283}
284
285impl fmt::Display for Use {
286    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287        f.write_str("USE ")?;
288        match self {
289            Use::Catalog(name) => write!(f, "CATALOG {name}"),
290            Use::Schema(name) => write!(f, "SCHEMA {name}"),
291            Use::Database(name) => write!(f, "DATABASE {name}"),
292            Use::Warehouse(name) => write!(f, "WAREHOUSE {name}"),
293            Use::Role(name) => write!(f, "ROLE {name}"),
294            Use::SecondaryRoles(secondary_roles) => {
295                write!(f, "SECONDARY ROLES {secondary_roles}")
296            }
297            Use::Object(name) => write!(f, "{name}"),
298            Use::Default => write!(f, "DEFAULT"),
299        }
300    }
301}
302
303/// Snowflake `SECONDARY ROLES` USE variant
304/// See: <https://docs.snowflake.com/en/sql-reference/sql/use-secondary-roles>
305#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
306#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
307#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
308pub enum SecondaryRoles {
309    /// Use all secondary roles.
310    All,
311    /// Use no secondary roles.
312    None,
313    /// Explicit list of secondary roles.
314    List(Vec<Ident>),
315}
316
317impl fmt::Display for SecondaryRoles {
318    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
319        match self {
320            SecondaryRoles::All => write!(f, "ALL"),
321            SecondaryRoles::None => write!(f, "NONE"),
322            SecondaryRoles::List(roles) => write!(f, "{}", display_comma_separated(roles)),
323        }
324    }
325}
326
327/// CREATE ROLE statement
328/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createrole.html)
329#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
332pub struct CreateRole {
333    /// Whether the statement was spelled `CREATE ROLE` or `CREATE GROUP`.
334    pub keyword: RoleKeyword,
335    /// Role names to create.
336    pub names: Vec<ObjectName>,
337    /// Whether `IF NOT EXISTS` was specified.
338    pub if_not_exists: bool,
339    // Postgres
340    /// Whether `LOGIN` was specified.
341    pub login: Option<bool>,
342    /// Whether `INHERIT` was specified.
343    pub inherit: Option<bool>,
344    /// Whether `BYPASSRLS` was specified.
345    pub bypassrls: Option<bool>,
346    /// Optional password for the role.
347    pub password: Option<Password>,
348    /// Whether `SUPERUSER` was specified.
349    pub superuser: Option<bool>,
350    /// Whether `CREATEDB` was specified.
351    pub create_db: Option<bool>,
352    /// Whether `CREATEROLE` was specified.
353    pub create_role: Option<bool>,
354    /// Whether `REPLICATION` privilege was specified.
355    pub replication: Option<bool>,
356    /// Optional connection limit expression.
357    pub connection_limit: Option<Expr>,
358    /// Optional account validity expression.
359    pub valid_until: Option<Expr>,
360    /// Members of `IN ROLE` clause.
361    pub in_role: Vec<Ident>,
362    /// Members of `IN GROUP` clause.
363    pub in_group: Vec<Ident>,
364    /// Roles listed in `ROLE` clause.
365    pub role: Vec<Ident>,
366    /// Users listed in `USER` clause.
367    pub user: Vec<Ident>,
368    /// Admin users listed in `ADMIN` clause.
369    pub admin: Vec<Ident>,
370    // MSSQL
371    /// Optional authorization owner.
372    pub authorization_owner: Option<ObjectName>,
373}
374
375impl fmt::Display for CreateRole {
376    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
377        write!(
378            f,
379            "CREATE {keyword} {if_not_exists}{names}{superuser}{create_db}{create_role}{inherit}{login}{replication}{bypassrls}",
380            keyword = self.keyword,
381            if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
382            names = display_separated(&self.names, ", "),
383            superuser = match self.superuser {
384                Some(true) => " SUPERUSER",
385                Some(false) => " NOSUPERUSER",
386                None => ""
387            },
388            create_db = match self.create_db {
389                Some(true) => " CREATEDB",
390                Some(false) => " NOCREATEDB",
391                None => ""
392            },
393            create_role = match self.create_role {
394                Some(true) => " CREATEROLE",
395                Some(false) => " NOCREATEROLE",
396                None => ""
397            },
398            inherit = match self.inherit {
399                Some(true) => " INHERIT",
400                Some(false) => " NOINHERIT",
401                None => ""
402            },
403            login = match self.login {
404                Some(true) => " LOGIN",
405                Some(false) => " NOLOGIN",
406                None => ""
407            },
408            replication = match self.replication {
409                Some(true) => " REPLICATION",
410                Some(false) => " NOREPLICATION",
411                None => ""
412            },
413            bypassrls = match self.bypassrls {
414                Some(true) => " BYPASSRLS",
415                Some(false) => " NOBYPASSRLS",
416                None => ""
417            }
418        )?;
419        if let Some(limit) = &self.connection_limit {
420            write!(f, " CONNECTION LIMIT {limit}")?;
421        }
422        match &self.password {
423            Some(Password::Password(pass)) => write!(f, " PASSWORD {pass}")?,
424            Some(Password::NullPassword) => write!(f, " PASSWORD NULL")?,
425            None => {}
426        };
427        if let Some(until) = &self.valid_until {
428            write!(f, " VALID UNTIL {until}")?;
429        }
430        if !self.in_role.is_empty() {
431            write!(f, " IN ROLE {}", display_comma_separated(&self.in_role))?;
432        }
433        if !self.in_group.is_empty() {
434            write!(f, " IN GROUP {}", display_comma_separated(&self.in_group))?;
435        }
436        if !self.role.is_empty() {
437            write!(f, " ROLE {}", display_comma_separated(&self.role))?;
438        }
439        if !self.user.is_empty() {
440            write!(f, " USER {}", display_comma_separated(&self.user))?;
441        }
442        if !self.admin.is_empty() {
443            write!(f, " ADMIN {}", display_comma_separated(&self.admin))?;
444        }
445        if let Some(owner) = &self.authorization_owner {
446            write!(f, " AUTHORIZATION {owner}")?;
447        }
448        Ok(())
449    }
450}
451
452impl Spanned for CreateRole {
453    fn span(&self) -> Span {
454        Span::empty()
455    }
456}
457
458/// GRANT privileges ON objects TO grantees
459#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
460#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
461#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
462pub struct Grant {
463    /// Privileges being granted.
464    pub privileges: Privileges,
465    /// Optional objects the privileges apply to.
466    pub objects: Option<GrantObjects>,
467    /// List of grantees receiving the privileges.
468    pub grantees: Vec<Grantee>,
469    /// Whether `WITH GRANT OPTION` is present.
470    pub with_grant_option: bool,
471    /// Optional `AS GRANTOR` identifier.
472    pub as_grantor: Option<Ident>,
473    /// Optional `GRANTED BY` identifier.
474    ///
475    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dcl-statements)
476    pub granted_by: Option<Ident>,
477    /// Optional `CURRENT GRANTS` modifier.
478    ///
479    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/grant-privilege)
480    pub current_grants: Option<CurrentGrantsKind>,
481}
482
483impl fmt::Display for Grant {
484    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
485        write!(f, "GRANT {privileges}", privileges = self.privileges)?;
486        if let Some(ref objects) = self.objects {
487            write!(f, " ON {objects}")?;
488        }
489        write!(f, " TO {}", display_comma_separated(&self.grantees))?;
490        // Printed in the order the parser reads them, so the output re-parses.
491        if self.with_grant_option {
492            write!(f, " WITH GRANT OPTION")?;
493        }
494        if let Some(ref current_grants) = self.current_grants {
495            write!(f, " {current_grants}")?;
496        }
497        if let Some(ref as_grantor) = self.as_grantor {
498            write!(f, " AS {as_grantor}")?;
499        }
500        if let Some(ref granted_by) = self.granted_by {
501            write!(f, " GRANTED BY {granted_by}")?;
502        }
503        Ok(())
504    }
505}
506
507impl From<Grant> for crate::ast::Statement {
508    fn from(v: Grant) -> Self {
509        crate::ast::Statement::Grant(v)
510    }
511}
512
513/// REVOKE privileges ON objects FROM grantees
514/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-revoke.html)
515#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
516#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
517#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
518pub struct Revoke {
519    /// Whether `GRANT OPTION FOR` is present, withdrawing the right to grant
520    /// the privileges rather than the privileges themselves.
521    pub grant_option_for: bool,
522    /// Privileges to revoke.
523    pub privileges: Privileges,
524    /// Optional objects from which to revoke.
525    pub objects: Option<GrantObjects>,
526    /// Grantees affected by the revoke.
527    pub grantees: Vec<Grantee>,
528    /// Optional `GRANTED BY` identifier.
529    ///
530    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dcl-statements)
531    pub granted_by: Option<Ident>,
532    /// Optional `CASCADE`/`RESTRICT` behavior.
533    pub cascade: Option<CascadeOption>,
534}
535
536impl fmt::Display for Revoke {
537    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538        write!(f, "REVOKE ")?;
539        if self.grant_option_for {
540            write!(f, "GRANT OPTION FOR ")?;
541        }
542        write!(f, "{}", self.privileges)?;
543        if let Some(ref objects) = self.objects {
544            write!(f, " ON {objects}")?;
545        }
546        write!(f, " FROM {}", display_comma_separated(&self.grantees))?;
547        if let Some(ref granted_by) = self.granted_by {
548            write!(f, " GRANTED BY {granted_by}")?;
549        }
550        if let Some(ref cascade) = self.cascade {
551            write!(f, " {cascade}")?;
552        }
553        Ok(())
554    }
555}
556
557impl From<Revoke> for crate::ast::Statement {
558    fn from(v: Revoke) -> Self {
559        crate::ast::Statement::Revoke(v)
560    }
561}
562
563/// `REVOKE [option OPTION FOR] role [, ...] FROM grantee [, ...] [GRANTED BY grantor] [CASCADE | RESTRICT]`
564///
565/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-revoke.html)
566#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
567#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
568#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
569pub struct RevokeRole {
570    /// The option named in `OPTION FOR`, such as `ADMIN`, withdrawn while the membership stays.
571    pub option_for: Option<Ident>,
572    /// Roles whose membership is revoked.
573    pub roles: Vec<Ident>,
574    /// Roles losing the membership.
575    pub grantees: Vec<Grantee>,
576    /// Optional `GRANTED BY` identifier.
577    pub granted_by: Option<Ident>,
578    /// Optional `CASCADE`/`RESTRICT` behavior.
579    pub cascade: Option<CascadeOption>,
580}
581
582impl fmt::Display for RevokeRole {
583    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
584        write!(f, "REVOKE ")?;
585        if let Some(option_for) = &self.option_for {
586            write!(f, "{option_for} OPTION FOR ")?;
587        }
588        write!(
589            f,
590            "{} FROM {}",
591            display_comma_separated(&self.roles),
592            display_comma_separated(&self.grantees)
593        )?;
594        if let Some(granted_by) = &self.granted_by {
595            write!(f, " GRANTED BY {granted_by}")?;
596        }
597        if let Some(cascade) = &self.cascade {
598            write!(f, " {cascade}")?;
599        }
600        Ok(())
601    }
602}
603
604impl From<RevokeRole> for crate::ast::Statement {
605    fn from(v: RevokeRole) -> Self {
606        crate::ast::Statement::RevokeRole(v)
607    }
608}
609
610/// `GRANT role [, ...] TO grantee [, ...] [WITH option [, ...]] [GRANTED BY grantor]`
611///
612/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-grant.html)
613#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
614#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
615#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
616pub struct GrantRole {
617    /// Roles whose membership is granted.
618    pub roles: Vec<Ident>,
619    /// Roles receiving the membership.
620    pub grantees: Vec<Grantee>,
621    /// Options of the membership, from `WITH`.
622    pub options: Vec<RoleGrantOption>,
623    /// Optional `GRANTED BY` identifier.
624    pub granted_by: Option<Ident>,
625}
626
627impl fmt::Display for GrantRole {
628    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
629        write!(
630            f,
631            "GRANT {} TO {}",
632            display_comma_separated(&self.roles),
633            display_comma_separated(&self.grantees)
634        )?;
635        if !self.options.is_empty() {
636            write!(f, " WITH {}", display_comma_separated(&self.options))?;
637        }
638        if let Some(granted_by) = &self.granted_by {
639            write!(f, " GRANTED BY {granted_by}")?;
640        }
641        Ok(())
642    }
643}
644
645impl From<GrantRole> for crate::ast::Statement {
646    fn from(v: GrantRole) -> Self {
647        crate::ast::Statement::GrantRole(v)
648    }
649}
650
651/// An option of a role membership, such as `ADMIN OPTION` or `SET FALSE`.
652#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
653#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
654#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
655pub struct RoleGrantOption {
656    /// The option name, such as `ADMIN`, `INHERIT` or `SET`.
657    pub name: Ident,
658    /// The value it is set to.
659    pub value: RoleGrantOptionValue,
660}
661
662impl fmt::Display for RoleGrantOption {
663    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
664        write!(f, "{} {}", self.name, self.value)
665    }
666}
667
668/// The value of a [`RoleGrantOption`].
669#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
670#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
671#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
672pub enum RoleGrantOptionValue {
673    /// `OPTION`, equivalent to `TRUE`.
674    Option,
675    /// `TRUE`
676    True,
677    /// `FALSE`
678    False,
679}
680
681impl fmt::Display for RoleGrantOptionValue {
682    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683        f.write_str(match self {
684            RoleGrantOptionValue::Option => "OPTION",
685            RoleGrantOptionValue::True => "TRUE",
686            RoleGrantOptionValue::False => "FALSE",
687        })
688    }
689}
690
691/// The options of [`AlterDefaultPrivileges`], kept in the order written.
692#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
693#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
694#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
695pub enum DefaultPrivilegesOption {
696    /// `FOR ROLE <role> [, ...]`.
697    ForRole(Vec<Ident>),
698    /// `IN SCHEMA <schema> [, ...]`.
699    InSchema(Vec<ObjectName>),
700}
701
702impl fmt::Display for DefaultPrivilegesOption {
703    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
704        match self {
705            DefaultPrivilegesOption::ForRole(roles) => {
706                write!(f, "FOR ROLE {}", display_comma_separated(roles))
707            }
708            DefaultPrivilegesOption::InSchema(schemas) => {
709                write!(f, "IN SCHEMA {}", display_comma_separated(schemas))
710            }
711        }
712    }
713}
714
715/// `ALTER DEFAULT PRIVILEGES`, which applies to objects created later rather
716/// than to existing ones.
717///
718/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterdefaultprivileges.html)
719#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
720#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
721#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
722pub struct AlterDefaultPrivileges {
723    /// The `FOR ROLE` and `IN SCHEMA` options, in written order.
724    pub options: Vec<DefaultPrivilegesOption>,
725    /// The abbreviated `GRANT` or `REVOKE` that follows.
726    pub operation: AlterDefaultPrivilegesOperation,
727}
728
729impl fmt::Display for AlterDefaultPrivileges {
730    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
731        f.write_str("ALTER DEFAULT PRIVILEGES")?;
732        for option in &self.options {
733            write!(f, " {option}")?;
734        }
735        write!(f, " {}", self.operation)
736    }
737}
738
739impl Spanned for AlterDefaultPrivileges {
740    fn span(&self) -> Span {
741        let options = self.options.iter().map(|option| match option {
742            DefaultPrivilegesOption::ForRole(roles) => {
743                Span::union_iter(roles.iter().map(|role| role.span))
744            }
745            DefaultPrivilegesOption::InSchema(schemas) => {
746                Span::union_iter(schemas.iter().map(Spanned::span))
747            }
748        });
749        let grantees = match &self.operation {
750            AlterDefaultPrivilegesOperation::Grant { grantees, .. }
751            | AlterDefaultPrivilegesOperation::Revoke { grantees, .. } => grantees,
752        };
753        Span::union_iter(
754            options.chain(
755                grantees
756                    .iter()
757                    .filter_map(|grantee| grantee.name.as_ref())
758                    .map(|name| match name {
759                        GranteeName::ObjectName(name) => name.span(),
760                        GranteeName::UserHost { user, host } => user.span.union(&host.span),
761                    }),
762            ),
763        )
764    }
765}
766
767impl From<AlterDefaultPrivileges> for crate::ast::Statement {
768    fn from(v: AlterDefaultPrivileges) -> Self {
769        crate::ast::Statement::AlterDefaultPrivileges(v)
770    }
771}
772
773/// The abbreviated `GRANT` or `REVOKE` of an [`AlterDefaultPrivileges`], naming
774/// an object type rather than named objects and so unable to reuse [`Grant`].
775#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
776#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
777#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
778pub enum AlterDefaultPrivilegesOperation {
779    /// `GRANT <privileges> ON <object_type> TO <grantees> [WITH GRANT OPTION]`
780    Grant {
781        /// The privileges being granted.
782        privileges: Privileges,
783        /// The kind of future object the privileges apply to.
784        object_type: DefaultPrivilegesObjectType,
785        /// The roles receiving the privileges.
786        grantees: Vec<Grantee>,
787        /// Whether `WITH GRANT OPTION` is present.
788        with_grant_option: bool,
789    },
790    /// `REVOKE [GRANT OPTION FOR] <privileges> ON <object_type> FROM <grantees> [CASCADE | RESTRICT]`
791    Revoke {
792        /// Whether `GRANT OPTION FOR` is present.
793        grant_option_for: bool,
794        /// The privileges being revoked.
795        privileges: Privileges,
796        /// The kind of future object the privileges apply to.
797        object_type: DefaultPrivilegesObjectType,
798        /// The roles losing the privileges.
799        grantees: Vec<Grantee>,
800        /// Optional `CASCADE`/`RESTRICT` behaviour.
801        cascade: Option<CascadeOption>,
802    },
803}
804
805impl fmt::Display for AlterDefaultPrivilegesOperation {
806    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
807        match self {
808            AlterDefaultPrivilegesOperation::Grant {
809                privileges,
810                object_type,
811                grantees,
812                with_grant_option,
813            } => {
814                write!(
815                    f,
816                    "GRANT {privileges} ON {object_type} TO {}",
817                    display_comma_separated(grantees)
818                )?;
819                if *with_grant_option {
820                    f.write_str(" WITH GRANT OPTION")?;
821                }
822            }
823            AlterDefaultPrivilegesOperation::Revoke {
824                grant_option_for,
825                privileges,
826                object_type,
827                grantees,
828                cascade,
829            } => {
830                f.write_str("REVOKE ")?;
831                if *grant_option_for {
832                    f.write_str("GRANT OPTION FOR ")?;
833                }
834                write!(
835                    f,
836                    "{privileges} ON {object_type} FROM {}",
837                    display_comma_separated(grantees)
838                )?;
839                if let Some(cascade) = cascade {
840                    write!(f, " {cascade}")?;
841                }
842            }
843        }
844        Ok(())
845    }
846}
847
848/// The kind of future object an [`AlterDefaultPrivileges`] applies to.
849#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
850#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
851#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
852pub enum DefaultPrivilegesObjectType {
853    /// `TABLES`, which also covers views and foreign tables.
854    Tables,
855    /// `SEQUENCES`
856    Sequences,
857    /// `FUNCTIONS`
858    Functions,
859    /// `ROUTINES`, a synonym of `FUNCTIONS`.
860    Routines,
861    /// `TYPES`
862    Types,
863    /// `SCHEMAS`
864    Schemas,
865    /// `LARGE OBJECTS`
866    LargeObjects,
867}
868
869impl fmt::Display for DefaultPrivilegesObjectType {
870    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
871        f.write_str(match self {
872            DefaultPrivilegesObjectType::Tables => "TABLES",
873            DefaultPrivilegesObjectType::Sequences => "SEQUENCES",
874            DefaultPrivilegesObjectType::Functions => "FUNCTIONS",
875            DefaultPrivilegesObjectType::Routines => "ROUTINES",
876            DefaultPrivilegesObjectType::Types => "TYPES",
877            DefaultPrivilegesObjectType::Schemas => "SCHEMAS",
878            DefaultPrivilegesObjectType::LargeObjects => "LARGE OBJECTS",
879        })
880    }
881}