Parse column constraints in any order

CREATE TABLE t (a INT NOT NULL DEFAULT 1 PRIMARY KEY) is as valid as
CREATE TABLE t (a INT DEFAULT 1 PRIMARY KEY NOT NULL).
This commit is contained in:
Nikhil Benesch 2019-05-29 15:46:21 -04:00
parent fc5e662b91
commit ffa1c8f853
No known key found for this signature in database
GPG key ID: F7386C5DEADABA7F
5 changed files with 412 additions and 219 deletions

View file

@ -1,6 +1,6 @@
//! AST types specific to CREATE/ALTER variants of `SQLStatement`
//! (commonly referred to as Data Definition Language, or DDL)
use super::{ASTNode, SQLIdent, SQLObjectName};
use super::{ASTNode, SQLIdent, SQLObjectName, SQLType};
/// An `ALTER TABLE` (`SQLStatement::SQLAlterTable`) operation
#[derive(Debug, Clone, PartialEq, Hash)]
@ -48,11 +48,6 @@ pub enum TableConstraint {
impl ToString for TableConstraint {
fn to_string(&self) -> String {
fn format_constraint_name(name: &Option<SQLIdent>) -> String {
name.as_ref()
.map(|name| format!("CONSTRAINT {} ", name))
.unwrap_or_default()
}
match self {
TableConstraint::Unique {
name,
@ -84,3 +79,116 @@ impl ToString for TableConstraint {
}
}
}
/// SQL column definition
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct SQLColumnDef {
pub name: SQLIdent,
pub data_type: SQLType,
pub collation: Option<SQLObjectName>,
pub options: Vec<ColumnOptionDef>,
}
impl ToString for SQLColumnDef {
fn to_string(&self) -> String {
format!(
"{} {}{}",
self.name,
self.data_type.to_string(),
self.options
.iter()
.map(|c| format!(" {}", c.to_string()))
.collect::<Vec<_>>()
.join("")
)
}
}
/// An optionally-named `ColumnOption`: `[ CONSTRAINT <name> ] <column-option>`.
///
/// Note that implementations are substantially more permissive than the ANSI
/// specification on what order column options can be presented in, and whether
/// they are allowed to be named. The specification distinguishes between
/// constraints (NOT NULL, UNIQUE, PRIMARY KEY, and CHECK), which can be named
/// and can appear in any order, and other options (DEFAULT, GENERATED), which
/// cannot be named and must appear in a fixed order. PostgreSQL, however,
/// allows preceding any option with `CONSTRAINT <name>`, even those that are
/// not really constraints, like NULL and DEFAULT. MSSQL is less permissive,
/// allowing DEFAULT, UNIQUE, PRIMARY KEY and CHECK to be named, but not NULL or
/// NOT NULL constraints (the last of which is in violation of the spec).
///
/// For maximum flexibility, we don't distinguish between constraint and
/// non-constraint options, lumping them all together under the umbrella of
/// "column options," and we allow any column option to be named.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct ColumnOptionDef {
pub name: Option<SQLIdent>,
pub option: ColumnOption,
}
impl ToString for ColumnOptionDef {
fn to_string(&self) -> String {
format!(
"{}{}",
format_constraint_name(&self.name),
self.option.to_string()
)
}
}
/// `ColumnOption`s are modifiers that follow a column definition in a `CREATE
/// TABLE` statement.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum ColumnOption {
/// `NULL`
Null,
/// `NOT NULL`
NotNull,
/// `DEFAULT <restricted-expr>`
Default(ASTNode),
/// `{ PRIMARY KEY | UNIQUE }`
Unique {
is_primary: bool,
},
/// A referential integrity constraint (`[FOREIGN KEY REFERENCES
/// <foreign_table> (<referred_columns>)`).
ForeignKey {
foreign_table: SQLObjectName,
referred_columns: Vec<SQLIdent>,
},
// `CHECK (<expr>)`
Check(ASTNode),
}
impl ToString for ColumnOption {
fn to_string(&self) -> String {
use ColumnOption::*;
match self {
Null => "NULL".to_string(),
NotNull => "NOT NULL".to_string(),
Default(expr) => format!("DEFAULT {}", expr.to_string()),
Unique { is_primary } => {
if *is_primary {
"PRIMARY KEY".to_string()
} else {
"UNIQUE".to_string()
}
}
ForeignKey {
foreign_table,
referred_columns,
} => format!(
"REFERENCES {} ({})",
foreign_table.to_string(),
referred_columns.join(", ")
),
Check(expr) => format!("CHECK ({})", expr.to_string(),),
}
}
}
fn format_constraint_name(name: &Option<SQLIdent>) -> String {
name.as_ref()
.map(|name| format!("CONSTRAINT {} ", name))
.unwrap_or_default()
}

View file

@ -22,7 +22,9 @@ mod value;
use std::ops::Deref;
pub use self::ddl::{AlterTableOperation, TableConstraint};
pub use self::ddl::{
AlterTableOperation, ColumnOption, ColumnOptionDef, SQLColumnDef, TableConstraint,
};
pub use self::query::{
Cte, Fetch, Join, JoinConstraint, JoinOperator, SQLOrderByExpr, SQLQuery, SQLSelect,
SQLSelectItem, SQLSetExpr, SQLSetOperator, SQLValues, TableAlias, TableFactor,
@ -580,36 +582,6 @@ impl ToString for SQLAssignment {
}
}
/// SQL column definition
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct SQLColumnDef {
pub name: SQLIdent,
pub data_type: SQLType,
pub is_primary: bool,
pub is_unique: bool,
pub default: Option<ASTNode>,
pub allow_null: bool,
}
impl ToString for SQLColumnDef {
fn to_string(&self) -> String {
let mut s = format!("{} {}", self.name, self.data_type.to_string());
if self.is_primary {
s += " PRIMARY KEY";
}
if self.is_unique {
s += " UNIQUE";
}
if let Some(ref default) = self.default {
s += &format!(" DEFAULT {}", default.to_string());
}
if !self.allow_null {
s += " NOT NULL";
}
s
}
}
/// SQL function
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct SQLFunction {

View file

@ -156,29 +156,6 @@ impl Parser {
Ok(expr)
}
/// Parse expression for DEFAULT clause in CREATE TABLE
pub fn parse_default_expr(&mut self, precedence: u8) -> Result<ASTNode, ParserError> {
debug!("parsing expr");
let mut expr = self.parse_prefix()?;
debug!("prefix: {:?}", expr);
loop {
// stop parsing on `NULL` | `NOT NULL`
match self.peek_token() {
Some(Token::SQLWord(ref k)) if k.keyword == "NOT" || k.keyword == "NULL" => break,
_ => {}
}
let next_precedence = self.get_next_precedence()?;
debug!("next precedence: {:?}", next_precedence);
if precedence >= next_precedence {
break;
}
expr = self.parse_infix(expr, next_precedence)?;
}
Ok(expr)
}
/// Parse an expression prefix
pub fn parse_prefix(&mut self) -> Result<ASTNode, ParserError> {
let tok = self
@ -897,29 +874,24 @@ impl Parser {
} else if let Some(Token::SQLWord(column_name)) = self.peek_token() {
self.next_token();
let data_type = self.parse_data_type()?;
let is_primary = self.parse_keywords(vec!["PRIMARY", "KEY"]);
let is_unique = self.parse_keyword("UNIQUE");
let default = if self.parse_keyword("DEFAULT") {
let expr = self.parse_default_expr(0)?;
Some(expr)
let collation = if self.parse_keyword("COLLATE") {
Some(self.parse_object_name()?)
} else {
None
};
let allow_null = if self.parse_keywords(vec!["NOT", "NULL"]) {
false
} else {
let _ = self.parse_keyword("NULL");
true
};
debug!("default: {:?}", default);
let mut options = vec![];
loop {
match self.peek_token() {
None | Some(Token::Comma) | Some(Token::RParen) => break,
_ => options.push(self.parse_column_option_def()?),
}
}
columns.push(SQLColumnDef {
name: column_name.as_sql_ident(),
data_type,
allow_null,
is_primary,
is_unique,
default,
collation,
options,
});
} else {
return self.expected("column name or constraint definition", self.peek_token());
@ -936,6 +908,45 @@ impl Parser {
Ok((columns, constraints))
}
pub fn parse_column_option_def(&mut self) -> Result<ColumnOptionDef, ParserError> {
let name = if self.parse_keyword("CONSTRAINT") {
Some(self.parse_identifier()?)
} else {
None
};
let option = if self.parse_keywords(vec!["NOT", "NULL"]) {
ColumnOption::NotNull
} else if self.parse_keyword("NULL") {
ColumnOption::Null
} else if self.parse_keyword("DEFAULT") {
ColumnOption::Default(self.parse_expr()?)
} else if self.parse_keywords(vec!["PRIMARY", "KEY"]) {
ColumnOption::Unique { is_primary: true }
} else if self.parse_keyword("UNIQUE") {
ColumnOption::Unique { is_primary: false }
} else if self.parse_keyword("REFERENCES") {
let foreign_table = self.parse_object_name()?;
let referred_columns = self.parse_parenthesized_column_list(Mandatory)?;
ColumnOption::ForeignKey {
foreign_table,
referred_columns,
}
} else if self.parse_keyword("CHECK") {
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
ColumnOption::Check(expr)
} else {
return parser_err!(format!(
"Unexpected token in column definition: {:?}",
self.peek_token()
));
};
Ok(ColumnOptionDef { name, option })
}
pub fn parse_optional_table_constraint(
&mut self,
) -> Result<Option<TableConstraint>, ParserError> {