Skip to content

Add support for DENY statements #1836

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
50 changes: 50 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3791,9 +3791,14 @@ pub enum Statement {
objects: Option<GrantObjects>,
grantees: Vec<Grantee>,
with_grant_option: bool,
as_grantor: Option<Ident>,
granted_by: Option<Ident>,
},
/// ```sql
/// DENY privileges ON object TO grantees
/// ```
Deny(DenyStatement),
/// ```sql
/// REVOKE privileges ON objects FROM grantees
/// ```
Revoke {
Expand Down Expand Up @@ -5409,6 +5414,7 @@ impl fmt::Display for Statement {
objects,
grantees,
with_grant_option,
as_grantor,
granted_by,
} => {
write!(f, "GRANT {privileges} ")?;
Expand All @@ -5419,11 +5425,15 @@ impl fmt::Display for Statement {
if *with_grant_option {
write!(f, " WITH GRANT OPTION")?;
}
if let Some(grantor) = as_grantor {
write!(f, " AS {grantor}")?;
}
if let Some(grantor) = granted_by {
write!(f, " GRANTED BY {grantor}")?;
}
Ok(())
}
Statement::Deny(s) => write!(f, "{s}"),
Statement::Revoke {
privileges,
objects,
Expand Down Expand Up @@ -6187,6 +6197,9 @@ pub enum Action {
},
Delete,
EvolveSchema,
Exec {
obj_type: Option<ActionExecuteObjectType>,
},
Execute {
obj_type: Option<ActionExecuteObjectType>,
},
Expand Down Expand Up @@ -6253,6 +6266,12 @@ impl fmt::Display for Action {
Action::DatabaseRole { role } => write!(f, "DATABASE ROLE {role}")?,
Action::Delete => f.write_str("DELETE")?,
Action::EvolveSchema => f.write_str("EVOLVE SCHEMA")?,
Action::Exec { obj_type } => {
f.write_str("EXEC")?;
if let Some(obj_type) = obj_type {
write!(f, " {obj_type}")?
}
}
Action::Execute { obj_type } => {
f.write_str("EXECUTE")?;
if let Some(obj_type) = obj_type {
Expand Down Expand Up @@ -6674,6 +6693,37 @@ impl fmt::Display for GrantObjects {
}
}

/// A `DENY` statement
///
/// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/deny-transact-sql)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct DenyStatement {
pub privileges: Privileges,
pub objects: GrantObjects,
pub grantees: Vec<Grantee>,
pub granted_by: Option<Ident>,
pub cascade: Option<CascadeOption>,
}

impl fmt::Display for DenyStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DENY {}", self.privileges)?;
write!(f, " ON {}", self.objects)?;
if !self.grantees.is_empty() {
write!(f, " TO {}", display_comma_separated(&self.grantees))?;
}
if let Some(cascade) = &self.cascade {
write!(f, " {cascade}")?;
}
if let Some(granted_by) = &self.granted_by {
write!(f, " AS {granted_by}")?;
}
Ok(())
}
}

/// SQL assignment `foo = expr` as used in SQLUpdate
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down
1 change: 1 addition & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ impl Spanned for Statement {
Statement::CreateStage { .. } => Span::empty(),
Statement::Assert { .. } => Span::empty(),
Statement::Grant { .. } => Span::empty(),
Statement::Deny { .. } => Span::empty(),
Statement::Revoke { .. } => Span::empty(),
Statement::Deallocate { .. } => Span::empty(),
Statement::Execute { .. } => Span::empty(),
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/mssql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ impl Dialect for MsSqlDialect {
|| ch == '_'
}

fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
Some('[')
}

/// SQL Server has `CONVERT(type, value)` instead of `CONVERT(value, type)`
/// <https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16>
fn convert_type_before_value(&self) -> bool {
Expand Down
1 change: 1 addition & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ define_keywords!(
DELIMITER,
DELTA,
DENSE_RANK,
DENY,
DEREF,
DESC,
DESCRIBE,
Expand Down
70 changes: 61 additions & 9 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,10 @@ impl<'a> Parser<'a> {
Keyword::SHOW => self.parse_show(),
Keyword::USE => self.parse_use(),
Keyword::GRANT => self.parse_grant(),
Keyword::DENY => {
self.prev_token();
self.parse_deny()
}
Keyword::REVOKE => self.parse_revoke(),
Keyword::START => self.parse_start_transaction(),
Keyword::BEGIN => self.parse_begin(),
Expand Down Expand Up @@ -12987,23 +12991,34 @@ impl<'a> Parser<'a> {

/// Parse a GRANT statement.
pub fn parse_grant(&mut self) -> Result<Statement, ParserError> {
let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;

self.expect_keyword_is(Keyword::TO)?;
let grantees = self.parse_grantees()?;

let with_grant_option =
self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);

let granted_by = self
.parse_keywords(&[Keyword::GRANTED, Keyword::BY])
.then(|| self.parse_identifier().unwrap());
let as_grantor = if self.peek_keyword(Keyword::AS) {
self.parse_keywords(&[Keyword::AS])
.then(|| self.parse_identifier().unwrap())
} else {
None
};

let granted_by = if self.peek_keywords(&[Keyword::GRANTED, Keyword::BY]) {
self.parse_keywords(&[Keyword::GRANTED, Keyword::BY])
.then(|| self.parse_identifier().unwrap())
} else {
None
};

Ok(Statement::Grant {
privileges,
objects,
grantees,
with_grant_option,
as_grantor,
granted_by,
})
}
Expand All @@ -13020,14 +13035,18 @@ impl<'a> Parser<'a> {
GranteesType::Share
} else if self.parse_keyword(Keyword::GROUP) {
GranteesType::Group
} else if self.parse_keyword(Keyword::PUBLIC) {
GranteesType::Public
} else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
GranteesType::DatabaseRole
} else if self.parse_keywords(&[Keyword::APPLICATION, Keyword::ROLE]) {
GranteesType::ApplicationRole
} else if self.parse_keyword(Keyword::APPLICATION) {
GranteesType::Application
} else if self.peek_keyword(Keyword::PUBLIC) {
if dialect_of!(self is MsSqlDialect) {
grantee_type
} else {
GranteesType::Public
}
} else {
grantee_type // keep from previous iteraton, if not specified
};
Expand Down Expand Up @@ -13066,7 +13085,7 @@ impl<'a> Parser<'a> {
Ok(values)
}

pub fn parse_grant_revoke_privileges_objects(
pub fn parse_grant_deny_revoke_privileges_objects(
&mut self,
) -> Result<(Privileges, Option<GrantObjects>), ParserError> {
let privileges = if self.parse_keyword(Keyword::ALL) {
Expand Down Expand Up @@ -13116,7 +13135,6 @@ impl<'a> Parser<'a> {
let object_type = self.parse_one_of_keywords(&[
Keyword::SEQUENCE,
Keyword::DATABASE,
Keyword::DATABASE,
Keyword::SCHEMA,
Keyword::TABLE,
Keyword::VIEW,
Expand Down Expand Up @@ -13211,6 +13229,9 @@ impl<'a> Parser<'a> {
Ok(Action::Create { obj_type })
} else if self.parse_keyword(Keyword::DELETE) {
Ok(Action::Delete)
} else if self.parse_keyword(Keyword::EXEC) {
let obj_type = self.maybe_parse_action_execute_obj_type();
Ok(Action::Exec { obj_type })
} else if self.parse_keyword(Keyword::EXECUTE) {
let obj_type = self.maybe_parse_action_execute_obj_type();
Ok(Action::Execute { obj_type })
Expand Down Expand Up @@ -13409,9 +13430,40 @@ impl<'a> Parser<'a> {
}
}

/// Parse [`Statement::Deny`]
pub fn parse_deny(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::DENY)?;

let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
let objects = match objects {
Some(o) => o,
None => {
return parser_err!(
"DENY statements must specify an object",
self.peek_token().span.start
)
}
};

self.expect_keyword_is(Keyword::TO)?;
let grantees = self.parse_grantees()?;
let cascade = self.parse_cascade_option();
let granted_by = self
.parse_keywords(&[Keyword::AS])
.then(|| self.parse_identifier().unwrap());

Ok(Statement::Deny(DenyStatement {
privileges,
objects,
grantees,
cascade,
granted_by,
}))
}

/// Parse a REVOKE statement
pub fn parse_revoke(&mut self) -> Result<Statement, ParserError> {
let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;

self.expect_keyword_is(Keyword::FROM)?;
let grantees = self.parse_grantees()?;
Expand Down
33 changes: 33 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9323,6 +9323,39 @@ fn parse_grant() {
verified_stmt("GRANT USAGE ON WAREHOUSE wh1 TO ROLE role1");
verified_stmt("GRANT OWNERSHIP ON INTEGRATION int1 TO ROLE role1");
verified_stmt("GRANT SELECT ON VIEW view1 TO ROLE role1");
verified_stmt("GRANT EXEC ON my_sp TO runner");
verified_stmt("GRANT UPDATE ON my_table TO updater_role AS dbo");

all_dialects_where(|d| d.identifier_quote_style("none") == Some('['))
.verified_stmt("GRANT SELECT ON [my_table] TO [public]");
}

#[test]
fn parse_deny() {
let sql = "DENY INSERT, DELETE ON users TO analyst CASCADE AS admin";
match verified_stmt(sql) {
Statement::Deny(deny) => {
assert_eq!(
Privileges::Actions(vec![Action::Insert { columns: None }, Action::Delete]),
deny.privileges
);
assert_eq!(
&GrantObjects::Tables(vec![ObjectName::from(vec![Ident::new("users")])]),
&deny.objects
);
assert_eq_vec(&["analyst"], &deny.grantees);
assert_eq!(Some(CascadeOption::Cascade), deny.cascade);
assert_eq!(Some(Ident::from("admin")), deny.granted_by);
}
_ => unreachable!(),
}

verified_stmt("DENY SELECT, INSERT, UPDATE, DELETE ON db1.sc1 TO role1, role2");
verified_stmt("DENY ALL ON db1.sc1 TO role1");
verified_stmt("DENY EXEC ON my_sp TO runner");

all_dialects_where(|d| d.identifier_quote_style("none") == Some('['))
.verified_stmt("DENY SELECT ON [my_table] TO [public]");
}

#[test]
Expand Down
10 changes: 10 additions & 0 deletions tests/sqlparser_mssql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2160,3 +2160,13 @@ fn parse_print() {
let _ = ms().verified_stmt("PRINT N'Hello, ⛄️!'");
let _ = ms().verified_stmt("PRINT @my_variable");
}

#[test]
fn parse_mssql_grant() {
ms().verified_stmt("GRANT SELECT ON my_table TO public, db_admin");
}

#[test]
fn parse_mssql_deny() {
ms().verified_stmt("DENY SELECT ON my_table TO public, db_admin");
}
1 change: 1 addition & 0 deletions tests/sqlparser_mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3283,6 +3283,7 @@ fn parse_grant() {
objects,
grantees,
with_grant_option,
as_grantor: _,
granted_by,
} = stmt
{
Expand Down