Skip to content

create if not exists for all dialect #163

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

Merged
merged 3 commits into from
Apr 21, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 4 additions & 1 deletion src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,7 @@ pub enum Statement {
columns: Vec<ColumnDef>,
constraints: Vec<TableConstraint>,
with_options: Vec<SqlOption>,
if_not_exists: bool,
external: bool,
file_format: Option<FileFormat>,
location: Option<String>,
Expand Down Expand Up @@ -623,14 +624,16 @@ impl fmt::Display for Statement {
columns,
constraints,
with_options,
if_not_exists,
external,
file_format,
location,
} => {
write!(
f,
"CREATE {}TABLE {} ({}",
"CREATE {}TABLE {}{} ({}",
if *external { "EXTERNAL " } else { "" },
if *if_not_exists { "IF NOT EXISTS " } else { "" },
name,
display_comma_separated(columns)
)?;
Expand Down
31 changes: 31 additions & 0 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,7 @@ impl Parser {
columns,
constraints,
with_options: vec![],
if_not_exists: false,
external: true,
file_format: Some(file_format),
location: Some(location),
Expand Down Expand Up @@ -932,6 +933,35 @@ impl Parser {
}

pub fn parse_create_table(&mut self) -> Result<Statement, ParserError> {
let if_keyword = self.parse_keyword("IF");
Copy link
Contributor

Choose a reason for hiding this comment

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

I think you can simply use let if_not_exists = self.parse_keywords(vec!["IF", "NOT", "EXISTS"]);, why not?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If I use let if_not_exists = self.parse_keywords(vec!["IF", "NOT", "EXISTS"]); I wouldn't be able to say if user typed in just CREATE TABLE or missed one of keyword because self.parse_keywords returns bool

Copy link
Contributor

Choose a reason for hiding this comment

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

Not sure I fully understand what you're saying.. When parse_keywords returns false the current token is left unchanged. So CREATE TABLE if (...) would be accepted (which seems more appropriate for the generic parser at least; I don't know if Postgres rejects that), and missing some of the keywords like CREATE TABLE IF NOT ... would fail with an error like "Expected end of statement, found: NOT" instead of more specific error message, which seems acceptable too.

Listing all possible errors for multiple dialects doesn't seem maintainable, and we already use parse_keywords in other places.

let not_keyword = self.parse_keyword("NOT");
let exists_keyword = self.parse_keyword("EXISTS");

if !if_keyword && not_keyword {
return Err(ParserError::ParserError(
"Expected a table name found: keyword NOT".to_string(),
));
}

if if_keyword && !not_keyword && !exists_keyword {
return Err(ParserError::ParserError(
"Expected keyword NOT found: table name".to_string(),
));
}

if if_keyword && !not_keyword {
return Err(ParserError::ParserError(
"Expected keyword NOT found: keyword EXISTS".to_string(),
));
}

if if_keyword && not_keyword && !exists_keyword {
return Err(ParserError::ParserError(
"Expected keyword EXISTS found: table name".to_string(),
));
}

let if_not_exists = if_keyword && not_keyword && exists_keyword;
let table_name = self.parse_object_name()?;
// parse optional column list (schema)
let (columns, constraints) = self.parse_columns()?;
Expand All @@ -942,6 +972,7 @@ impl Parser {
columns,
constraints,
with_options,
if_not_exists,
external: false,
file_format: None,
location: None,
Expand Down
3 changes: 3 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,7 @@ fn parse_create_table() {
columns,
constraints,
with_options,
if_not_exists: false,
external: false,
file_format: None,
location: None,
Expand Down Expand Up @@ -1045,6 +1046,7 @@ fn parse_create_external_table() {
columns,
constraints,
with_options,
if_not_exists,
external,
file_format,
location,
Expand Down Expand Up @@ -1086,6 +1088,7 @@ fn parse_create_external_table() {
assert_eq!("/tmp/example.csv", location.unwrap());

assert_eq!(with_options, vec![]);
assert!(!if_not_exists);
}
_ => unreachable!(),
}
Expand Down
54 changes: 54 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ fn parse_create_table_with_defaults() {
columns,
constraints,
with_options,
if_not_exists: false,
external: false,
file_format: None,
location: None,
Expand Down Expand Up @@ -225,6 +226,59 @@ fn parse_create_table_with_inherit() {
pg().verified_stmt(sql);
}

#[test]
fn parse_create_table_if_not_exists() {
let sql = "CREATE TABLE IF NOT EXISTS uk_cities ()";
let ast = pg().one_statement_parses_to(
sql,
"CREATE TABLE IF NOT EXISTS uk_cities ()",
);
match ast {
Statement::CreateTable {
name,
columns: _columns,
constraints,
with_options,
if_not_exists: true,
external: false,
file_format: None,
location: None,
} => {
assert_eq!("uk_cities", name.to_string());
assert!(constraints.is_empty());
assert_eq!(with_options, vec![]);
}
_ => unreachable!(),
}
}

#[test]
fn parse_bad_if_not_exists() {
let res = pg().parse_sql_statements("CREATE TABLE NOT EXISTS uk_cities ()");
assert_eq!(
ParserError::ParserError("Expected a table name found: keyword NOT".to_string()),
res.unwrap_err()
);

let res = pg().parse_sql_statements("CREATE TABLE IF EXISTS uk_cities ()");
assert_eq!(
ParserError::ParserError("Expected keyword NOT found: keyword EXISTS".to_string()),
res.unwrap_err()
);

let res = pg().parse_sql_statements("CREATE TABLE IF uk_cities ()");
assert_eq!(
ParserError::ParserError("Expected keyword NOT found: table name".to_string()),
res.unwrap_err()
);

let res = pg().parse_sql_statements("CREATE TABLE IF NOT uk_cities ()");
assert_eq!(
ParserError::ParserError("Expected keyword EXISTS found: table name".to_string()),
res.unwrap_err()
);
}

#[test]
fn parse_copy_example() {
let sql = r#"COPY public.actor (actor_id, first_name, last_name, last_update, value) FROM stdin;
Expand Down