Skip to content

Snowflake: CREATE USER #1950

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 1 commit 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
28 changes: 16 additions & 12 deletions src/ast/helpers/key_value_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,22 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

use crate::ast::display_separated;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct KeyValueOptions {
pub options: Vec<KeyValueOption>,
pub delimiter: KeyValueOptionsDelimiter,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum KeyValueOptionsDelimiter {
Space,
Comma,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
Expand All @@ -59,18 +70,11 @@ pub struct KeyValueOption {

impl fmt::Display for KeyValueOptions {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
if !self.options.is_empty() {
let mut first = false;
for option in &self.options {
if !first {
first = true;
} else {
f.write_str(" ")?;
}
write!(f, "{option}")?;
}
}
Ok(())
let sep = match self.delimiter {
KeyValueOptionsDelimiter::Space => " ",
KeyValueOptionsDelimiter::Comma => ", ",
};
write!(f, "{}", display_separated(&self.options, sep))
}
}

Expand Down
42 changes: 42 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4339,6 +4339,11 @@ pub enum Statement {
///
/// See [ReturnStatement]
Return(ReturnStatement),
/// ```sql
/// CREATE [OR REPLACE] USER <user> [IF NOT EXISTS]
/// ```
/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-user)
CreateUser(CreateUser),
}

/// ```sql
Expand Down Expand Up @@ -6169,6 +6174,7 @@ impl fmt::Display for Statement {
Statement::Return(r) => write!(f, "{r}"),
Statement::List(command) => write!(f, "LIST {command}"),
Statement::Remove(command) => write!(f, "REMOVE {command}"),
Statement::CreateUser(s) => write!(f, "{s}"),
}
}
}
Expand Down Expand Up @@ -10074,6 +10080,42 @@ impl fmt::Display for MemberOf {
}
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct CreateUser {
pub or_replace: bool,
pub if_not_exists: bool,
pub name: Ident,
pub options: KeyValueOptions,
pub with_tags: bool,
pub tags: KeyValueOptions,
}

impl fmt::Display for CreateUser {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "CREATE")?;
if self.or_replace {
write!(f, " OR REPLACE")?;
}
write!(f, " USER")?;
if self.if_not_exists {
write!(f, " IF NOT EXISTS")?;
}
write!(f, " {}", self.name)?;
if !self.options.options.is_empty() {
write!(f, " {}", self.options)?;
}
if !self.tags.options.is_empty() {
if self.with_tags {
write!(f, " WITH")?;
}
write!(f, " TAG ({})", self.tags)?;
}
Ok(())
}
}

#[cfg(test)]
mod tests {
use crate::tokenizer::Location;
Expand Down
1 change: 1 addition & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,7 @@ impl Spanned for Statement {
Statement::Print { .. } => Span::empty(),
Statement::Return { .. } => Span::empty(),
Statement::List(..) | Statement::Remove(..) => Span::empty(),
Statement::CreateUser(..) => Span::empty(),
}
}
}
Expand Down
109 changes: 37 additions & 72 deletions src/dialect/snowflake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

#[cfg(not(feature = "std"))]
use crate::alloc::string::ToString;
use crate::ast::helpers::key_value_options::{KeyValueOption, KeyValueOptionType, KeyValueOptions};
use crate::ast::helpers::key_value_options::{
KeyValueOption, KeyValueOptionType, KeyValueOptions, KeyValueOptionsDelimiter,
};
use crate::ast::helpers::stmt_create_table::CreateTableBuilder;
use crate::ast::helpers::stmt_data_loading::{
FileStagingCommand, StageLoadSelectItem, StageLoadSelectItemKind, StageParamsObject,
Expand All @@ -31,7 +33,7 @@ use crate::ast::{
use crate::dialect::{Dialect, Precedence};
use crate::keywords::Keyword;
use crate::parser::{IsOptional, Parser, ParserError};
use crate::tokenizer::{Token, Word};
use crate::tokenizer::Token;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
Expand Down Expand Up @@ -500,6 +502,7 @@ fn parse_alter_session(parser: &mut Parser, set: bool) -> Result<Statement, Pars
set,
session_params: KeyValueOptions {
options: session_options,
delimiter: KeyValueOptionsDelimiter::Space,
},
})
}
Expand Down Expand Up @@ -761,19 +764,19 @@ pub fn parse_create_stage(
// [ directoryTableParams ]
if parser.parse_keyword(Keyword::DIRECTORY) {
parser.expect_token(&Token::Eq)?;
directory_table_params = parse_parentheses_options(parser)?;
directory_table_params = parser.parse_key_value_options(true, &[])?;
}

// [ file_format]
if parser.parse_keyword(Keyword::FILE_FORMAT) {
parser.expect_token(&Token::Eq)?;
file_format = parse_parentheses_options(parser)?;
file_format = parser.parse_key_value_options(true, &[])?;
}

// [ copy_options ]
if parser.parse_keyword(Keyword::COPY_OPTIONS) {
parser.expect_token(&Token::Eq)?;
copy_options = parse_parentheses_options(parser)?;
copy_options = parser.parse_key_value_options(true, &[])?;
}

// [ comment ]
Expand All @@ -790,12 +793,15 @@ pub fn parse_create_stage(
stage_params,
directory_table_params: KeyValueOptions {
options: directory_table_params,
delimiter: KeyValueOptionsDelimiter::Space,
},
file_format: KeyValueOptions {
options: file_format,
delimiter: KeyValueOptionsDelimiter::Space,
},
copy_options: KeyValueOptions {
options: copy_options,
delimiter: KeyValueOptionsDelimiter::Space,
},
comment,
})
Expand Down Expand Up @@ -863,10 +869,16 @@ pub fn parse_copy_into(parser: &mut Parser) -> Result<Statement, ParserError> {
let mut from_stage = None;
let mut stage_params = StageParamsObject {
url: None,
encryption: KeyValueOptions { options: vec![] },
encryption: KeyValueOptions {
options: vec![],
delimiter: KeyValueOptionsDelimiter::Space,
},
endpoint: None,
storage_integration: None,
credentials: KeyValueOptions { options: vec![] },
credentials: KeyValueOptions {
options: vec![],
delimiter: KeyValueOptionsDelimiter::Space,
},
};
let mut from_query = None;
let mut partition = None;
Expand Down Expand Up @@ -928,7 +940,7 @@ pub fn parse_copy_into(parser: &mut Parser) -> Result<Statement, ParserError> {
// FILE_FORMAT
if parser.parse_keyword(Keyword::FILE_FORMAT) {
parser.expect_token(&Token::Eq)?;
file_format = parse_parentheses_options(parser)?;
file_format = parser.parse_key_value_options(true, &[])?;
// PARTITION BY
} else if parser.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
partition = Some(Box::new(parser.parse_expr()?))
Expand Down Expand Up @@ -966,14 +978,14 @@ pub fn parse_copy_into(parser: &mut Parser) -> Result<Statement, ParserError> {
// COPY OPTIONS
} else if parser.parse_keyword(Keyword::COPY_OPTIONS) {
parser.expect_token(&Token::Eq)?;
copy_options = parse_parentheses_options(parser)?;
copy_options = parser.parse_key_value_options(true, &[])?;
} else {
match parser.next_token().token {
Token::SemiColon | Token::EOF => break,
Token::Comma => continue,
// In `COPY INTO <location>` the copy options do not have a shared key
// like in `COPY INTO <table>`
Token::Word(key) => copy_options.push(parse_option(parser, key)?),
Token::Word(key) => copy_options.push(parser.parse_key_value_option(key)?),
_ => return parser.expected("another copy option, ; or EOF'", parser.peek_token()),
}
}
Expand All @@ -992,9 +1004,11 @@ pub fn parse_copy_into(parser: &mut Parser) -> Result<Statement, ParserError> {
pattern,
file_format: KeyValueOptions {
options: file_format,
delimiter: KeyValueOptionsDelimiter::Space,
},
copy_options: KeyValueOptions {
options: copy_options,
delimiter: KeyValueOptionsDelimiter::Space,
},
validation_mode,
partition,
Expand Down Expand Up @@ -1094,8 +1108,14 @@ fn parse_select_item_for_data_load(

fn parse_stage_params(parser: &mut Parser) -> Result<StageParamsObject, ParserError> {
let (mut url, mut storage_integration, mut endpoint) = (None, None, None);
let mut encryption: KeyValueOptions = KeyValueOptions { options: vec![] };
let mut credentials: KeyValueOptions = KeyValueOptions { options: vec![] };
let mut encryption: KeyValueOptions = KeyValueOptions {
options: vec![],
delimiter: KeyValueOptionsDelimiter::Space,
};
let mut credentials: KeyValueOptions = KeyValueOptions {
options: vec![],
delimiter: KeyValueOptionsDelimiter::Space,
};

// URL
if parser.parse_keyword(Keyword::URL) {
Expand Down Expand Up @@ -1125,15 +1145,17 @@ fn parse_stage_params(parser: &mut Parser) -> Result<StageParamsObject, ParserEr
if parser.parse_keyword(Keyword::CREDENTIALS) {
parser.expect_token(&Token::Eq)?;
credentials = KeyValueOptions {
options: parse_parentheses_options(parser)?,
options: parser.parse_key_value_options(true, &[])?,
delimiter: KeyValueOptionsDelimiter::Space,
};
}

// ENCRYPTION
if parser.parse_keyword(Keyword::ENCRYPTION) {
parser.expect_token(&Token::Eq)?;
encryption = KeyValueOptions {
options: parse_parentheses_options(parser)?,
options: parser.parse_key_value_options(true, &[])?,
delimiter: KeyValueOptionsDelimiter::Space,
};
}

Expand Down Expand Up @@ -1167,7 +1189,7 @@ fn parse_session_options(
Token::Word(key) => {
parser.advance_token();
if set {
let option = parse_option(parser, key)?;
let option = parser.parse_key_value_option(key)?;
options.push(option);
} else {
options.push(KeyValueOption {
Expand All @@ -1191,63 +1213,6 @@ fn parse_session_options(
}
}

/// Parses options provided within parentheses like:
/// ( ENABLE = { TRUE | FALSE }
/// [ AUTO_REFRESH = { TRUE | FALSE } ]
/// [ REFRESH_ON_CREATE = { TRUE | FALSE } ]
/// [ NOTIFICATION_INTEGRATION = '<notification_integration_name>' ] )
///
fn parse_parentheses_options(parser: &mut Parser) -> Result<Vec<KeyValueOption>, ParserError> {
let mut options: Vec<KeyValueOption> = Vec::new();
parser.expect_token(&Token::LParen)?;
loop {
match parser.next_token().token {
Token::RParen => break,
Token::Comma => continue,
Token::Word(key) => options.push(parse_option(parser, key)?),
_ => return parser.expected("another option or ')'", parser.peek_token()),
};
}
Ok(options)
}

/// Parses a `KEY = VALUE` construct based on the specified key
fn parse_option(parser: &mut Parser, key: Word) -> Result<KeyValueOption, ParserError> {
parser.expect_token(&Token::Eq)?;
if parser.parse_keyword(Keyword::TRUE) {
Ok(KeyValueOption {
option_name: key.value,
option_type: KeyValueOptionType::BOOLEAN,
value: "TRUE".to_string(),
})
} else if parser.parse_keyword(Keyword::FALSE) {
Ok(KeyValueOption {
option_name: key.value,
option_type: KeyValueOptionType::BOOLEAN,
value: "FALSE".to_string(),
})
} else {
match parser.next_token().token {
Token::SingleQuotedString(value) => Ok(KeyValueOption {
option_name: key.value,
option_type: KeyValueOptionType::STRING,
value,
}),
Token::Word(word) => Ok(KeyValueOption {
option_name: key.value,
option_type: KeyValueOptionType::ENUM,
value: word.value,
}),
Token::Number(n, _) => Ok(KeyValueOption {
option_name: key.value,
option_type: KeyValueOptionType::NUMBER,
value: n,
}),
_ => parser.expected("expected option value", parser.peek_token()),
}
}
}

/// Parsing a property of identity or autoincrement column option
/// Syntax:
/// ```sql
Expand Down
Loading
Loading