Skip to content
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

Fix MySQL parsing of GRANT, REVOKE, and CREATE VIEW #1538

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
138 changes: 125 additions & 13 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -885,7 +885,7 @@ pub enum Expr {
/// Example:
///
/// ```sql
/// SELECT (SELECT ',' + name FROM sys.objects FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)')
/// SELECT (SELECT ',' + name FROM sys.objects FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)')
/// SELECT CONVERT(XML,'<Book>abc</Book>').value('.','NVARCHAR(MAX)').value('.','NVARCHAR(MAX)')
/// ```
///
Expand Down Expand Up @@ -2352,7 +2352,7 @@ pub enum Statement {
identity: Option<TruncateIdentityOption>,
/// Postgres-specific option
/// [ CASCADE | RESTRICT ]
cascade: Option<TruncateCascadeOption>,
cascade: Option<CascadeOption>,
/// ClickHouse-specific option
/// [ ON CLUSTER cluster_name ]
///
Expand Down Expand Up @@ -2493,6 +2493,8 @@ pub enum Statement {
/// if not None, has Clickhouse `TO` clause, specify the table into which to insert results
/// <https://clickhouse.com/docs/en/sql-reference/statements/create/view#materialized-view>
to: Option<ObjectName>,
/// MySQL: Optional parameters for the view algorithm, definer, and security context
params: Option<CreateViewParams>,
},
/// ```sql
/// CREATE TABLE
Expand Down Expand Up @@ -3187,7 +3189,7 @@ pub enum Statement {
Grant {
privileges: Privileges,
objects: GrantObjects,
grantees: Vec<Ident>,
grantees: Vec<Grantee>,
with_grant_option: bool,
granted_by: Option<Ident>,
},
Expand All @@ -3197,9 +3199,9 @@ pub enum Statement {
Revoke {
privileges: Privileges,
objects: GrantObjects,
grantees: Vec<Ident>,
grantees: Vec<Grantee>,
granted_by: Option<Ident>,
cascade: bool,
cascade: Option<CascadeOption>,
},
/// ```sql
/// DEALLOCATE [ PREPARE ] { name | ALL }
Expand Down Expand Up @@ -3615,8 +3617,8 @@ impl fmt::Display for Statement {
}
if let Some(cascade) = cascade {
match cascade {
TruncateCascadeOption::Cascade => write!(f, " CASCADE")?,
TruncateCascadeOption::Restrict => write!(f, " RESTRICT")?,
CascadeOption::Cascade => write!(f, " CASCADE")?,
CascadeOption::Restrict => write!(f, " RESTRICT")?,
}
}

Expand Down Expand Up @@ -4005,11 +4007,19 @@ impl fmt::Display for Statement {
if_not_exists,
temporary,
to,
params,
} => {
write!(
f,
"CREATE {or_replace}{materialized}{temporary}VIEW {if_not_exists}{name}{to}",
"CREATE {or_replace}",
or_replace = if *or_replace { "OR REPLACE " } else { "" },
)?;
if let Some(params) = params {
write!(f, "{params} ")?;
}
write!(
f,
"{materialized}{temporary}VIEW {if_not_exists}{name}{to}",
materialized = if *materialized { "MATERIALIZED " } else { "" },
name = name,
temporary = if *temporary { "TEMPORARY " } else { "" },
Expand Down Expand Up @@ -4726,7 +4736,9 @@ impl fmt::Display for Statement {
if let Some(grantor) = granted_by {
write!(f, " GRANTED BY {grantor}")?;
}
write!(f, " {}", if *cascade { "CASCADE" } else { "RESTRICT" })?;
if let Some(cascade) = cascade {
write!(f, " {}", cascade)?;
}
Ok(())
}
Statement::Deallocate { name, prepare } => write!(
Expand Down Expand Up @@ -5123,16 +5135,25 @@ pub enum TruncateIdentityOption {
Continue,
}

/// PostgreSQL cascade option for TRUNCATE table
/// Cascade/restrict option for Postgres TRUNCATE table, MySQL GRANT/REVOKE, etc.
/// [ CASCADE | RESTRICT ]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum TruncateCascadeOption {
pub enum CascadeOption {
Cascade,
Restrict,
}

impl Display for CascadeOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CascadeOption::Cascade => write!(f, "CASCADE"),
CascadeOption::Restrict => write!(f, "RESTRICT"),
}
}
}

/// Can use to describe options in create sequence or table column type identity
/// [ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
Expand Down Expand Up @@ -5447,6 +5468,28 @@ impl fmt::Display for GrantObjects {
}
}

/// Users/roles designated in a GRANT/REVOKE
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum Grantee {
/// A bare identifier
Ident(Ident),
/// A MySQL user/host pair such as 'root'@'%'
UserHost { user: Ident, host: Ident },
}

impl fmt::Display for Grantee {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Grantee::Ident(ident) => ident.fmt(f),
Grantee::UserHost { user, host } => {
write!(f, "{}@{}", user, host)
}
}
}
}

/// 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 Expand Up @@ -7377,15 +7420,84 @@ pub enum MySQLColumnPosition {
impl Display for MySQLColumnPosition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MySQLColumnPosition::First => Ok(write!(f, "FIRST")?),
MySQLColumnPosition::First => write!(f, "FIRST"),
MySQLColumnPosition::After(ident) => {
let column_name = &ident.value;
Ok(write!(f, "AFTER {column_name}")?)
write!(f, "AFTER {column_name}")
}
}
}
}

/// MySQL `CREATE VIEW` algorithm parameter: [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum CreateViewAlgorithm {
Undefined,
Merge,
TempTable,
}

impl Display for CreateViewAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CreateViewAlgorithm::Undefined => write!(f, "UNDEFINED"),
CreateViewAlgorithm::Merge => write!(f, "MERGE"),
CreateViewAlgorithm::TempTable => write!(f, "TEMPTABLE"),
}
}
}
/// MySQL `CREATE VIEW` security parameter: [SQL SECURITY { DEFINER | INVOKER }]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum CreateViewSecurity {
Definer,
Invoker,
}

impl Display for CreateViewSecurity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CreateViewSecurity::Definer => write!(f, "DEFINER"),
CreateViewSecurity::Invoker => write!(f, "INVOKER"),
}
}
}

/// [MySQL] `CREATE VIEW` additional parameters
///
/// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/create-view.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 CreateViewParams {
pub algorithm: Option<CreateViewAlgorithm>,
pub definer: Option<Grantee>,
pub security: Option<CreateViewSecurity>,
}

impl Display for CreateViewParams {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let parts = [
self.algorithm
.as_ref()
.map(|algorithm| format!("ALGORITHM = {algorithm}")),
self.definer
.as_ref()
.map(|definer| format!("DEFINER = {definer}")),
self.security
.as_ref()
.map(|security| format!("SQL SECURITY {security}")),
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
display_separated(&parts, " ").fmt(f)
Comment on lines +7483 to +7497
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we write these explicitly as e.g?

if let Some(algorithm) = self.algorithm { write!() }

I think that potentially makes it easier to spot the final output and extend in the future.
Also ideally we can use an exhaustive check with

let CreateviewParams { algorithm, definer, security } = self

so that the user is automatically guided to this function whenever the representation changes

}
}

/// Engine of DB. Some warehouse has parameters of engine, e.g. [clickhouse]
///
/// [clickhouse]: https://clickhouse.com/docs/en/engines/table-engines
Expand Down
1 change: 1 addition & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ impl Spanned for Statement {
if_not_exists: _,
temporary: _,
to,
params: _,
} => union_spans(
core::iter::once(name.span())
.chain(columns.iter().map(|i| i.span()))
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,8 @@ impl Dialect for GenericDialect {
fn supports_named_fn_args_with_assignment_operator(&self) -> bool {
true
}

fn supports_user_host_grantee(&self) -> bool {
true
}
}
5 changes: 5 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,11 @@ pub trait Dialect: Debug + Any {
self.supports_trailing_commas()
}

/// Does the dialect support MySQL-style `'user'@'host'` grantee syntax?
fn supports_user_host_grantee(&self) -> bool {
false
}

/// Dialect-specific infix parser override
///
/// This method is called to parse the next infix expression.
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ impl Dialect for MySqlDialect {
fn supports_create_table_select(&self) -> bool {
true
}

fn supports_user_host_grantee(&self) -> bool {
true
}
}

/// `LOCK TABLES`
Expand Down
5 changes: 5 additions & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ define_keywords!(
AFTER,
AGAINST,
AGGREGATION,
ALGORITHM,
ALIAS,
ALL,
ALLOCATE,
Expand Down Expand Up @@ -241,6 +242,7 @@ define_keywords!(
DEFERRED,
DEFINE,
DEFINED,
DEFINER,
DELAYED,
DELETE,
DELIMITED,
Expand Down Expand Up @@ -412,6 +414,7 @@ define_keywords!(
INTERSECTION,
INTERVAL,
INTO,
INVOKER,
IS,
ISODOW,
ISOLATION,
Expand Down Expand Up @@ -750,6 +753,7 @@ define_keywords!(
TBLPROPERTIES,
TEMP,
TEMPORARY,
TEMPTABLE,
TERMINATED,
TERSE,
TEXT,
Expand Down Expand Up @@ -795,6 +799,7 @@ define_keywords!(
UNBOUNDED,
UNCACHE,
UNCOMMITTED,
UNDEFINED,
UNFREEZE,
UNION,
UNIQUE,
Expand Down
Loading