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

Merged
merged 22 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
abd971d
Tokenize at signs separately from subsequent strings
mvzink Nov 19, 2024
9dc0d9e
Fix parsing GRANT/REVOKE for MySQL
mvzink Nov 20, 2024
64669ed
Parse MySQL CREATE VIEW parameters
mvzink Nov 20, 2024
69bb0d8
Fix lint error and no-std build
mvzink Nov 20, 2024
797c510
Add more test cases for create view
mvzink Nov 27, 2024
c896e10
Use generic names for optional `CREATE VIEW` params
mvzink Nov 27, 2024
935777b
Return errors instead of panicking when expect_one_keyword returns so…
mvzink Nov 27, 2024
99bf3f6
Add dialect support toggle for MySQL grantee syntax
mvzink Nov 27, 2024
3091653
Refactor parsing revoke cascade/restrict option to reuse truncate code
mvzink Nov 27, 2024
50506c4
Fix a doc comment about BigQuery identifiers
mvzink Nov 27, 2024
93a4b03
Merge branch 'main' into mysql-users
mvzink Nov 28, 2024
3fc2164
Accommodate new span field on ident for grantees and wildcards
mvzink Nov 28, 2024
f6b2a6a
Merge branch 'main' into mysql-users
mvzink Dec 12, 2024
4aebd01
Add comment about breaking on quotes in @ tokenization
mvzink Dec 12, 2024
9042222
Use destructuring to write create view params
mvzink Dec 12, 2024
1423d9e
Add tests for other quote styles
mvzink Dec 12, 2024
888773d
Merge branch 'main' into mysql-users
mvzink Dec 20, 2024
126b7b4
Merge branch 'main' into mysql-users
mvzink Dec 23, 2024
ed3e591
Address comments about dialect switching
mvzink Dec 24, 2024
7f1ff61
Merge branch 'main' into mysql-users
mvzink Jan 2, 2025
d052db1
Merge branch 'main' into mysql-users
mvzink Jan 8, 2025
c7f85ea
Avoid unnecessary clone when extracting identifier from object name
mvzink Jan 9, 2025
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
119 changes: 111 additions & 8 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,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 @@ -2427,6 +2427,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<MySQLViewParams>,
},
/// ```sql
/// CREATE TABLE
Expand Down Expand Up @@ -3121,7 +3123,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 @@ -3131,9 +3133,9 @@ pub enum Statement {
Revoke {
privileges: Privileges,
objects: GrantObjects,
grantees: Vec<Ident>,
grantees: Vec<Grantee>,
granted_by: Option<Ident>,
cascade: bool,
cascade: Option<bool>,
},
/// ```sql
/// DEALLOCATE [ PREPARE ] { name | ALL }
Expand Down Expand Up @@ -3939,11 +3941,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 @@ -4660,7 +4670,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, " {}", if *cascade { "CASCADE" } else { "RESTRICT" })?;
}
Ok(())
}
Statement::Deallocate { name, prepare } => write!(
Expand Down Expand Up @@ -5381,6 +5393,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 @@ -7311,15 +7345,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 MySQLViewAlgorithm {
Undefined,
Merge,
TempTable,
}

impl Display for MySQLViewAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MySQLViewAlgorithm::Undefined => write!(f, "UNDEFINED"),
MySQLViewAlgorithm::Merge => write!(f, "MERGE"),
MySQLViewAlgorithm::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 MySQLViewSecurity {
Definer,
Invoker,
}

impl Display for MySQLViewSecurity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MySQLViewSecurity::Definer => write!(f, "DEFINER"),
MySQLViewSecurity::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 MySQLViewParams {
mvzink marked this conversation as resolved.
Show resolved Hide resolved
pub algorithm: Option<MySQLViewAlgorithm>,
pub definer: Option<Grantee>,
pub security: Option<MySQLViewSecurity>,
}

impl Display for MySQLViewParams {
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)
mvzink marked this conversation as resolved.
Show resolved Hide resolved
}
}

/// Engine of DB. Some warehouse has parameters of engine, e.g. [clickhouse]
///
/// [clickhouse]: https://clickhouse.com/docs/en/engines/table-engines
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
Loading