Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions fuzz/fuzz_seeds/postgres_2417_alter_default_privileges.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT SELECT ON TABLES TO app_user;
ALTER DEFAULT PRIVILEGES FOR ROLE a, b IN SCHEMA s1, s2 GRANT SELECT, INSERT ON TABLES TO app WITH GRANT OPTION;
ALTER DEFAULT PRIVILEGES FOR USER bob GRANT ALL PRIVILEGES ON SEQUENCES TO app;
ALTER DEFAULT PRIVILEGES GRANT EXECUTE ON FUNCTIONS TO app;
ALTER DEFAULT PRIVILEGES GRANT USAGE ON ROUTINES TO app;
ALTER DEFAULT PRIVILEGES GRANT USAGE, CREATE ON TYPES TO app;
ALTER DEFAULT PRIVILEGES GRANT SELECT ON SCHEMAS TO app;
ALTER DEFAULT PRIVILEGES GRANT SELECT, UPDATE ON LARGE OBJECTS TO app;
ALTER DEFAULT PRIVILEGES REVOKE SELECT ON TABLES FROM app;
ALTER DEFAULT PRIVILEGES REVOKE GRANT OPTION FOR ALL ON TABLES FROM app CASCADE
196 changes: 194 additions & 2 deletions src/ast/dcl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use sqlparser_derive::{Visit, VisitMut};

use super::{display_comma_separated, Expr, Ident, Password, Spanned};
use crate::ast::{
display_separated, CascadeOption, CurrentGrantsKind, GrantObjects, Grantee, ObjectName,
Privileges,
display_separated, CascadeOption, CurrentGrantsKind, GrantObjects, Grantee, GranteeName,
ObjectName, Privileges,
};
use crate::tokenizer::Span;

Expand Down Expand Up @@ -535,3 +535,195 @@ impl From<Revoke> for crate::ast::Statement {
crate::ast::Statement::Revoke(v)
}
}

/// The options of [`AlterDefaultPrivileges`], kept in the order written.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum DefaultPrivilegesOption {
/// `FOR ROLE <role> [, ...]`.
ForRole(Vec<Ident>),
/// `IN SCHEMA <schema> [, ...]`.
InSchema(Vec<ObjectName>),
}

impl fmt::Display for DefaultPrivilegesOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
DefaultPrivilegesOption::ForRole(roles) => {
write!(f, "FOR ROLE {}", display_comma_separated(roles))
}
DefaultPrivilegesOption::InSchema(schemas) => {
write!(f, "IN SCHEMA {}", display_comma_separated(schemas))
}
}
}
}

/// `ALTER DEFAULT PRIVILEGES`, which applies to objects created later rather
/// than to existing ones.
///
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterdefaultprivileges.html)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct AlterDefaultPrivileges {
/// The `FOR ROLE` and `IN SCHEMA` options, in written order.
pub options: Vec<DefaultPrivilegesOption>,
/// The abbreviated `GRANT` or `REVOKE` that follows.
pub operation: AlterDefaultPrivilegesOperation,
}

impl fmt::Display for AlterDefaultPrivileges {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("ALTER DEFAULT PRIVILEGES")?;
for option in &self.options {
write!(f, " {option}")?;
}
write!(f, " {}", self.operation)
}
}

impl Spanned for AlterDefaultPrivileges {
fn span(&self) -> Span {
let options = self.options.iter().map(|option| match option {
DefaultPrivilegesOption::ForRole(roles) => {
Span::union_iter(roles.iter().map(|role| role.span))
}
DefaultPrivilegesOption::InSchema(schemas) => {
Span::union_iter(schemas.iter().map(Spanned::span))
}
});
let grantees = match &self.operation {
AlterDefaultPrivilegesOperation::Grant { grantees, .. }
| AlterDefaultPrivilegesOperation::Revoke { grantees, .. } => grantees,
};
Span::union_iter(
options.chain(
grantees
.iter()
.filter_map(|grantee| grantee.name.as_ref())
.map(|name| match name {
GranteeName::ObjectName(name) => name.span(),
GranteeName::UserHost { user, host } => user.span.union(&host.span),
}),
),
)
}
}

impl From<AlterDefaultPrivileges> for crate::ast::Statement {
fn from(v: AlterDefaultPrivileges) -> Self {
crate::ast::Statement::AlterDefaultPrivileges(v)
}
}

/// The abbreviated `GRANT` or `REVOKE` of an [`AlterDefaultPrivileges`], naming
/// an object type rather than named objects and so unable to reuse [`Grant`].
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum AlterDefaultPrivilegesOperation {
/// `GRANT <privileges> ON <object_type> TO <grantees> [WITH GRANT OPTION]`
Grant {
/// The privileges being granted.
privileges: Privileges,
/// The kind of future object the privileges apply to.
object_type: DefaultPrivilegesObjectType,
/// The roles receiving the privileges.
grantees: Vec<Grantee>,
/// Whether `WITH GRANT OPTION` is present.
with_grant_option: bool,
},
/// `REVOKE [GRANT OPTION FOR] <privileges> ON <object_type> FROM <grantees> [CASCADE | RESTRICT]`
Revoke {
/// Whether `GRANT OPTION FOR` is present.
grant_option_for: bool,
/// The privileges being revoked.
privileges: Privileges,
/// The kind of future object the privileges apply to.
object_type: DefaultPrivilegesObjectType,
/// The roles losing the privileges.
grantees: Vec<Grantee>,
/// Optional `CASCADE`/`RESTRICT` behaviour.
cascade: Option<CascadeOption>,
},
}

impl fmt::Display for AlterDefaultPrivilegesOperation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterDefaultPrivilegesOperation::Grant {
privileges,
object_type,
grantees,
with_grant_option,
} => {
write!(
f,
"GRANT {privileges} ON {object_type} TO {}",
display_comma_separated(grantees)
)?;
if *with_grant_option {
f.write_str(" WITH GRANT OPTION")?;
}
}
AlterDefaultPrivilegesOperation::Revoke {
grant_option_for,
privileges,
object_type,
grantees,
cascade,
} => {
f.write_str("REVOKE ")?;
if *grant_option_for {
f.write_str("GRANT OPTION FOR ")?;
}
write!(
f,
"{privileges} ON {object_type} FROM {}",
display_comma_separated(grantees)
)?;
if let Some(cascade) = cascade {
write!(f, " {cascade}")?;
}
}
}
Ok(())
}
}

/// The kind of future object an [`AlterDefaultPrivileges`] applies to.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum DefaultPrivilegesObjectType {
/// `TABLES`, which also covers views and foreign tables.
Tables,
/// `SEQUENCES`
Sequences,
/// `FUNCTIONS`
Functions,
/// `ROUTINES`, a synonym of `FUNCTIONS`.
Routines,
/// `TYPES`
Types,
/// `SCHEMAS`
Schemas,
/// `LARGE OBJECTS`
LargeObjects,
}

impl fmt::Display for DefaultPrivilegesObjectType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
DefaultPrivilegesObjectType::Tables => "TABLES",
DefaultPrivilegesObjectType::Sequences => "SEQUENCES",
DefaultPrivilegesObjectType::Functions => "FUNCTIONS",
DefaultPrivilegesObjectType::Routines => "ROUTINES",
DefaultPrivilegesObjectType::Types => "TYPES",
DefaultPrivilegesObjectType::Schemas => "SCHEMAS",
DefaultPrivilegesObjectType::LargeObjects => "LARGE OBJECTS",
})
}
}
10 changes: 8 additions & 2 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ pub use self::data_type::{
ExactNumberInfo, IntervalFields, MapBracketKind, StructBracketKind, TimezoneInfo, TypeModifier,
};
pub use self::dcl::{
AlterRoleOperation, CreateRole, Grant, ResetConfig, Revoke, RoleOption, SecondaryRoles,
SetConfigValue, Use,
AlterDefaultPrivileges, AlterDefaultPrivilegesOperation, AlterRoleOperation, CreateRole,
DefaultPrivilegesObjectType, DefaultPrivilegesOption, Grant, ResetConfig, Revoke, RoleOption,
SecondaryRoles, SetConfigValue, Use,
};
pub use self::ddl::{
AggregateModifyKind, Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation,
Expand Down Expand Up @@ -4644,6 +4645,10 @@ pub enum Statement {
/// ```
Revoke(Revoke),
/// ```sql
/// ALTER DEFAULT PRIVILEGES
/// ```
AlterDefaultPrivileges(AlterDefaultPrivileges),
/// ```sql
/// DEALLOCATE [ PREPARE ] { name | ALL }
/// ```
///
Expand Down Expand Up @@ -6147,6 +6152,7 @@ impl fmt::Display for Statement {
Statement::Grant(grant) => write!(f, "{grant}"),
Statement::Deny(s) => write!(f, "{s}"),
Statement::Revoke(revoke) => write!(f, "{revoke}"),
Statement::AlterDefaultPrivileges(stmt) => write!(f, "{stmt}"),
Statement::Deallocate { name, prepare } => write!(
f,
"DEALLOCATE {prepare}{name}",
Expand Down
1 change: 1 addition & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ impl Spanned for Statement {
Statement::Grant { .. } => Span::empty(),
Statement::Deny { .. } => Span::empty(),
Statement::Revoke { .. } => Span::empty(),
Statement::AlterDefaultPrivileges(privileges) => privileges.span(),
Statement::Deallocate { .. } => Span::empty(),
Statement::Execute { .. } => Span::empty(),
Statement::Prepare { .. } => Span::empty(),
Expand Down
2 changes: 2 additions & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,7 @@ define_keywords!(
ROLLBACK,
ROLLUP,
ROOT,
ROUTINES,
ROW,
ROWGROUPSIZE,
ROWID,
Expand Down Expand Up @@ -1125,6 +1126,7 @@ define_keywords!(
TSVECTOR,
TUPLE,
TYPE,
TYPES,
TYPMOD_IN,
TYPMOD_OUT,
UBIGINT,
Expand Down
Loading
Loading