Skip to content

Commit dfa1183

Browse files
committed
Parse Snowflake USE ROLE and USE SECONDARY ROLES
1 parent e16b246 commit dfa1183

File tree

6 files changed

+100
-21
lines changed

6 files changed

+100
-21
lines changed

src/ast/dcl.rs

+34-7
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use serde::{Deserialize, Serialize};
2828
#[cfg(feature = "visitor")]
2929
use sqlparser_derive::{Visit, VisitMut};
3030

31-
use super::{Expr, Ident, Password};
31+
use super::{display_comma_separated, Expr, Ident, Password};
3232
use crate::ast::{display_separated, ObjectName};
3333

3434
/// An option in `ROLE` statement.
@@ -204,12 +204,14 @@ impl fmt::Display for AlterRoleOperation {
204204
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
205205
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
206206
pub enum Use {
207-
Catalog(ObjectName), // e.g. `USE CATALOG foo.bar`
208-
Schema(ObjectName), // e.g. `USE SCHEMA foo.bar`
209-
Database(ObjectName), // e.g. `USE DATABASE foo.bar`
210-
Warehouse(ObjectName), // e.g. `USE WAREHOUSE foo.bar`
211-
Object(ObjectName), // e.g. `USE foo.bar`
212-
Default, // e.g. `USE DEFAULT`
207+
Catalog(ObjectName), // e.g. `USE CATALOG foo.bar`
208+
Schema(ObjectName), // e.g. `USE SCHEMA foo.bar`
209+
Database(ObjectName), // e.g. `USE DATABASE foo.bar`
210+
Warehouse(ObjectName), // e.g. `USE WAREHOUSE foo.bar`
211+
Role(ObjectName), // e.g. `USE ROLE PUBLIC`
212+
SecondaryRoles(SecondaryRoles), // e.g. `USE SECONDARY ROLES ALL`
213+
Object(ObjectName), // e.g. `USE foo.bar`
214+
Default, // e.g. `USE DEFAULT`
213215
}
214216

215217
impl fmt::Display for Use {
@@ -220,8 +222,33 @@ impl fmt::Display for Use {
220222
Use::Schema(name) => write!(f, "SCHEMA {}", name),
221223
Use::Database(name) => write!(f, "DATABASE {}", name),
222224
Use::Warehouse(name) => write!(f, "WAREHOUSE {}", name),
225+
Use::Role(name) => write!(f, "ROLE {}", name),
226+
Use::SecondaryRoles(secondary_roles) => {
227+
write!(f, "SECONDARY ROLES {}", secondary_roles)
228+
}
223229
Use::Object(name) => write!(f, "{}", name),
224230
Use::Default => write!(f, "DEFAULT"),
225231
}
226232
}
227233
}
234+
235+
/// Snowflake `SECONDARY ROLES` USE variant
236+
/// See: <https://docs.snowflake.com/en/sql-reference/sql/use-secondary-roles>
237+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
238+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
239+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
240+
pub enum SecondaryRoles {
241+
All,
242+
None,
243+
List(Vec<Ident>),
244+
}
245+
246+
impl fmt::Display for SecondaryRoles {
247+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248+
match self {
249+
SecondaryRoles::All => write!(f, "ALL"),
250+
SecondaryRoles::None => write!(f, "NONE"),
251+
SecondaryRoles::List(roles) => write!(f, "{}", display_comma_separated(roles)),
252+
}
253+
}
254+
}

src/ast/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ pub use self::data_type::{
4343
ArrayElemTypeDef, CharLengthUnits, CharacterLength, DataType, ExactNumberInfo,
4444
StructBracketKind, TimezoneInfo,
4545
};
46-
pub use self::dcl::{AlterRoleOperation, ResetConfig, RoleOption, SetConfigValue, Use};
46+
pub use self::dcl::{
47+
AlterRoleOperation, ResetConfig, RoleOption, SecondaryRoles, SetConfigValue, Use,
48+
};
4749
pub use self::ddl::{
4850
AlterColumnOperation, AlterIndexOperation, AlterPolicyOperation, AlterTableOperation,
4951
ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnPolicy, ColumnPolicyProperty,

src/ast/spans.rs

+12-5
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ use core::iter;
33
use crate::tokenizer::Span;
44

55
use super::{
6-
AlterColumnOperation, AlterIndexOperation, AlterTableOperation, Array, Assignment,
7-
AssignmentTarget, CloseCursor, ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef,
8-
ConflictTarget, ConnectBy, ConstraintCharacteristics, CopySource, CreateIndex, CreateTable,
9-
CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, ExcludeSelectItem, Expr,
10-
ExprWithAlias, Fetch, FromTable, Function, FunctionArg, FunctionArgExpr,
6+
dcl::SecondaryRoles, AlterColumnOperation, AlterIndexOperation, AlterTableOperation, Array,
7+
Assignment, AssignmentTarget, CloseCursor, ClusteredIndex, ColumnDef, ColumnOption,
8+
ColumnOptionDef, ConflictTarget, ConnectBy, ConstraintCharacteristics, CopySource, CreateIndex,
9+
CreateTable, CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, ExcludeSelectItem,
10+
Expr, ExprWithAlias, Fetch, FromTable, Function, FunctionArg, FunctionArgExpr,
1111
FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr, HavingBound,
1212
IlikeSelectItem, Insert, Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator,
1313
JsonPath, JsonPathElem, LateralView, MatchRecognizePattern, Measure, NamedWindowDefinition,
@@ -484,6 +484,13 @@ impl Spanned for Use {
484484
Use::Schema(object_name) => object_name.span(),
485485
Use::Database(object_name) => object_name.span(),
486486
Use::Warehouse(object_name) => object_name.span(),
487+
Use::Role(object_name) => object_name.span(),
488+
Use::SecondaryRoles(secondary_roles) => {
489+
if let SecondaryRoles::List(roles) = secondary_roles {
490+
return union_spans(roles.iter().map(|i| i.span));
491+
}
492+
Span::empty()
493+
}
487494
Use::Object(object_name) => object_name.span(),
488495
Use::Default => Span::empty(),
489496
}

src/keywords.rs

+2
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,7 @@ define_keywords!(
661661
RIGHT,
662662
RLIKE,
663663
ROLE,
664+
ROLES,
664665
ROLLBACK,
665666
ROLLUP,
666667
ROOT,
@@ -679,6 +680,7 @@ define_keywords!(
679680
SCROLL,
680681
SEARCH,
681682
SECOND,
683+
SECONDARY,
682684
SECRET,
683685
SECURITY,
684686
SELECT,

src/parser/mod.rs

+31-8
Original file line numberDiff line numberDiff line change
@@ -10050,23 +10050,46 @@ impl<'a> Parser<'a> {
1005010050
} else if dialect_of!(self is DatabricksDialect) {
1005110051
self.parse_one_of_keywords(&[Keyword::CATALOG, Keyword::DATABASE, Keyword::SCHEMA])
1005210052
} else if dialect_of!(self is SnowflakeDialect) {
10053-
self.parse_one_of_keywords(&[Keyword::DATABASE, Keyword::SCHEMA, Keyword::WAREHOUSE])
10053+
self.parse_one_of_keywords(&[
10054+
Keyword::DATABASE,
10055+
Keyword::SCHEMA,
10056+
Keyword::WAREHOUSE,
10057+
Keyword::ROLE,
10058+
Keyword::SECONDARY,
10059+
])
1005410060
} else {
1005510061
None // No specific keywords for other dialects, including GenericDialect
1005610062
};
1005710063

10058-
let obj_name = self.parse_object_name(false)?;
10059-
let result = match parsed_keyword {
10060-
Some(Keyword::CATALOG) => Use::Catalog(obj_name),
10061-
Some(Keyword::DATABASE) => Use::Database(obj_name),
10062-
Some(Keyword::SCHEMA) => Use::Schema(obj_name),
10063-
Some(Keyword::WAREHOUSE) => Use::Warehouse(obj_name),
10064-
_ => Use::Object(obj_name),
10064+
let result = if matches!(parsed_keyword, Some(Keyword::SECONDARY)) {
10065+
self.parse_secondary_roles()?
10066+
} else {
10067+
let obj_name = self.parse_object_name(false)?;
10068+
match parsed_keyword {
10069+
Some(Keyword::CATALOG) => Use::Catalog(obj_name),
10070+
Some(Keyword::DATABASE) => Use::Database(obj_name),
10071+
Some(Keyword::SCHEMA) => Use::Schema(obj_name),
10072+
Some(Keyword::WAREHOUSE) => Use::Warehouse(obj_name),
10073+
Some(Keyword::ROLE) => Use::Role(obj_name),
10074+
_ => Use::Object(obj_name),
10075+
}
1006510076
};
1006610077

1006710078
Ok(Statement::Use(result))
1006810079
}
1006910080

10081+
fn parse_secondary_roles(&mut self) -> Result<Use, ParserError> {
10082+
self.expect_keyword(Keyword::ROLES)?;
10083+
if self.parse_keyword(Keyword::NONE) {
10084+
Ok(Use::SecondaryRoles(SecondaryRoles::None))
10085+
} else if self.parse_keyword(Keyword::ALL) {
10086+
Ok(Use::SecondaryRoles(SecondaryRoles::All))
10087+
} else {
10088+
let roles = self.parse_comma_separated(|parser| parser.parse_identifier(false))?;
10089+
Ok(Use::SecondaryRoles(SecondaryRoles::List(roles)))
10090+
}
10091+
}
10092+
1007010093
pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError> {
1007110094
let relation = self.parse_table_factor()?;
1007210095
// Note that for keywords to be properly handled here, they need to be

tests/sqlparser_snowflake.rs

+18
Original file line numberDiff line numberDiff line change
@@ -2709,6 +2709,20 @@ fn parse_use() {
27092709
Ident::with_quote(quote, "my_schema")
27102710
])))
27112711
);
2712+
std::assert_eq!(
2713+
snowflake().verified_stmt(&format!("USE ROLE {0}my_role{0}", quote)),
2714+
Statement::Use(Use::Role(ObjectName(vec![Ident::with_quote(
2715+
quote,
2716+
"my_role".to_string(),
2717+
)])))
2718+
);
2719+
std::assert_eq!(
2720+
snowflake().verified_stmt(&format!("USE WAREHOUSE {0}my_wh{0}", quote)),
2721+
Statement::Use(Use::Warehouse(ObjectName(vec![Ident::with_quote(
2722+
quote,
2723+
"my_wh".to_string(),
2724+
)])))
2725+
);
27122726
}
27132727

27142728
// Test invalid syntax - missing identifier
@@ -2719,6 +2733,10 @@ fn parse_use() {
27192733
ParserError::ParserError("Expected: identifier, found: EOF".to_string()),
27202734
);
27212735
}
2736+
2737+
snowflake().verified_stmt("USE SECONDARY ROLES ALL");
2738+
snowflake().verified_stmt("USE SECONDARY ROLES NONE");
2739+
snowflake().verified_stmt("USE SECONDARY ROLES r1, r2, r3");
27222740
}
27232741

27242742
#[test]

0 commit comments

Comments
 (0)