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
164 changes: 164 additions & 0 deletions src/ast/dcl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,3 +535,167 @@ 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 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,
};
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::{
Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation, AlterConnectorOwner,
Expand Down Expand Up @@ -4636,6 +4637,10 @@ pub enum Statement {
/// ```
Revoke(Revoke),
/// ```sql
/// ALTER DEFAULT PRIVILEGES
/// ```
AlterDefaultPrivileges(AlterDefaultPrivileges),
/// ```sql
/// DEALLOCATE [ PREPARE ] { name | ALL }
/// ```
///
Expand Down Expand Up @@ -6146,6 +6151,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
75 changes: 55 additions & 20 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,32 @@ use core::iter;
use crate::tokenizer::Span;

use super::{
comments, dcl::SecondaryRoles, value::ValueWithSpan, AccessExpr, AlterColumnOperation,
AlterIndexOperation, AlterTableOperation, Analyze, Array, Assignment, AssignmentTarget,
AttachedToken, BeginEndStatements, CaseStatement, CloseCursor, ClusteredIndex, ColumnDef,
ColumnOption, ColumnOptionDef, ConditionalStatementBlock, ConditionalStatements,
ConflictTarget, ConnectByKind, ConstraintCharacteristics, CopySource, CreateIndex, CreateTable,
CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, ExcludeConstraintElement,
ExcludeSelectItem, Expr, ExprWithAlias, Fetch, ForValues, FromTable, Function, FunctionArg,
FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr,
HavingBound, IfStatement, IlikeSelectItem, InTarget, IndexColumn, Insert, Interpolate,
InterpolateExpr, Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView,
LimitClause, MatchRecognizePattern, Measure, Merge, MergeAction, MergeClause, MergeInsertExpr,
MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, NamedParenthesizedList,
NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction,
OnInsert, OpenStatement, OrderBy, OrderByExpr, OrderByKind, OutputClause, Parens, Partition,
PartitionBoundValue, PivotValueSource, ProjectionSelect, Query, RaiseStatement,
RaiseStatementValue, ReferentialAction, RenameSelectItem, ReplaceSelectElement,
ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, Setting, SqlOption, Statement,
Subscript, SymbolDefinition, TableAlias, TableAliasColumnDef, TableConstraint, TableFactor,
TableObject, TableOptionsClustered, TableWithJoins, Update, UpdateTableFromKind, Use, Values,
ViewColumnDef, WhileStatement, WildcardAdditionalOptions, With, WithFill,
comments,
dcl::{
AlterDefaultPrivileges, AlterDefaultPrivilegesOperation, DefaultPrivilegesOption,
SecondaryRoles,
},
value::ValueWithSpan,
AccessExpr, AlterColumnOperation, AlterIndexOperation, AlterTableOperation, Analyze, Array,
Assignment, AssignmentTarget, AttachedToken, BeginEndStatements, CaseStatement, CloseCursor,
ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef, ConditionalStatementBlock,
ConditionalStatements, ConflictTarget, ConnectByKind, ConstraintCharacteristics, CopySource,
CreateIndex, CreateTable, CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem,
ExcludeConstraintElement, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, ForValues, FromTable,
Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList,
FunctionArguments, GranteeName, GroupByExpr, HavingBound, IfStatement, IlikeSelectItem,
InTarget, IndexColumn, Insert, Interpolate, InterpolateExpr, Join, JoinConstraint,
JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause, MatchRecognizePattern, Measure,
Merge, MergeAction, MergeClause, MergeInsertExpr, MergeInsertKind, MergeUpdateExpr,
MergeUpdateKind, NamedParenthesizedList, NamedWindowDefinition, ObjectName, ObjectNamePart,
Offset, OnConflict, OnConflictAction, OnInsert, OpenStatement, OrderBy, OrderByExpr,
OrderByKind, OutputClause, Parens, Partition, PartitionBoundValue, PivotValueSource,
ProjectionSelect, Query, RaiseStatement, RaiseStatementValue, ReferentialAction,
RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, SelectInto, SelectItem,
SetExpr, Setting, SqlOption, Statement, Subscript, SymbolDefinition, TableAlias,
TableAliasColumnDef, TableConstraint, TableFactor, TableObject, TableOptionsClustered,
TableWithJoins, Update, UpdateTableFromKind, Use, Values, ViewColumnDef, WhileStatement,
WildcardAdditionalOptions, With, WithFill,
};

/// Given an iterator of spans, return the [Span::union] of all spans.
Expand Down Expand Up @@ -467,6 +473,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 Expand Up @@ -528,6 +535,34 @@ impl Spanned for Statement {
}
}

impl Spanned for AlterDefaultPrivileges {
fn span(&self) -> Span {
let options = self.options.iter().map(|option| match option {
DefaultPrivilegesOption::ForRole(roles) => {
union_spans(roles.iter().map(|role| role.span))
}
DefaultPrivilegesOption::InSchema(schemas) => {
union_spans(schemas.iter().map(Spanned::span))
}
});
let grantees = match &self.operation {
AlterDefaultPrivilegesOperation::Grant { grantees, .. }
| AlterDefaultPrivilegesOperation::Revoke { grantees, .. } => grantees,
};
union_spans(
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 Spanned for Use {
fn span(&self) -> Span {
match self {
Expand Down
2 changes: 2 additions & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,7 @@ define_keywords!(
ROLLBACK,
ROLLUP,
ROOT,
ROUTINES,
ROW,
ROWGROUPSIZE,
ROWID,
Expand Down Expand Up @@ -1101,6 +1102,7 @@ define_keywords!(
TSVECTOR,
TUPLE,
TYPE,
TYPES,
TYPMOD_IN,
TYPMOD_OUT,
UBIGINT,
Expand Down
Loading
Loading