Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TABLE t (b INT, LIKE a INCLUDING DEFAULTS, c INT, LIKE d)
79 changes: 59 additions & 20 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,18 @@ use crate::ast::{
UniqueConstraint,
},
ArgMode, AttachedToken, BeginEndStatements, CommentDef, ConditionalStatements,
CreateFunctionBody, CreateFunctionUsing, CreateServerOption, CreateTableLikeKind,
CreateTableOptions, CreateViewParams, DataType, Expr, FileFormat, FunctionBehavior,
FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc, FunctionDeterminismSpecifier,
FunctionParallel, FunctionSecurity, HiveDistributionStyle, HiveFormat, HiveIOFormat,
HiveRowFormat, HiveSetLocation, Ident, InitializeKind, MySQLColumnPosition, ObjectName,
OnCommit, OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect, Query,
RefreshModeKind, ResetConfig, RowAccessPolicy, SequenceOptions, Spanned, SqlOption, Statement,
StorageLifecyclePolicy, StorageSerializationPolicy, TableVersion, Tag, TriggerEvent,
TriggerExecBody, TriggerObject, TriggerPeriod, TriggerReferencing, Value, ValueWithSpan,
WrappedCollection,
CreateFunctionBody, CreateFunctionUsing, CreateServerOption, CreateTableLikeElement,
CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr, FileFormat,
FunctionBehavior, FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc,
FunctionDeterminismSpecifier, FunctionParallel, FunctionSecurity, HiveDistributionStyle,
HiveFormat, HiveIOFormat, HiveRowFormat, HiveSetLocation, Ident, InitializeKind,
MySQLColumnPosition, ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg,
OrderByExpr, ProjectionSelect, Query, RefreshModeKind, ResetConfig, RowAccessPolicy,
SequenceOptions, Spanned, SqlOption, Statement, StorageLifecyclePolicy,
StorageSerializationPolicy, TableVersion, Tag, TriggerEvent, TriggerExecBody, TriggerObject,
TriggerPeriod, TriggerReferencing, Value, ValueWithSpan, WrappedCollection,
};
use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
use crate::display_utils::{Indent, NewLine, SpaceOrNewline};
use crate::keywords::Keyword;
use crate::tokenizer::{Span, Token};

Expand Down Expand Up @@ -3453,15 +3453,19 @@ impl fmt::Display for CreateTable {
if let Some(on_cluster) = &self.on_cluster {
write!(f, " ON CLUSTER {on_cluster}")?;
}
if !self.columns.is_empty() || !self.constraints.is_empty() {
let like_elements: &[CreateTableLikeElement] = match &self.like {
Some(CreateTableLikeKind::Parenthesized(like_elements)) => like_elements,
_ => &[],
};
if !self.columns.is_empty() || !self.constraints.is_empty() || !like_elements.is_empty() {
f.write_str(" (")?;
NewLine.fmt(f)?;
Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
if !self.columns.is_empty() && !self.constraints.is_empty() {
f.write_str(",")?;
SpaceOrNewline.fmt(f)?;
}
Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
Indent(TableElements {
columns: &self.columns,
like_elements,
constraints: &self.constraints,
})
.fmt(f)?;
NewLine.fmt(f)?;
f.write_str(")")?;
} else if self.query.is_none()
Expand All @@ -3471,8 +3475,6 @@ impl fmt::Display for CreateTable {
{
// PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
f.write_str(" ()")?;
} else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
write!(f, " ({like_in_columns_list})")?;
}
if let Some(for_values) = &self.for_values {
write!(f, " {for_values}")?;
Expand Down Expand Up @@ -3744,6 +3746,43 @@ impl fmt::Display for CreateTable {
}
}

/// The column list of `CREATE TABLE`, with each `LIKE` element after the columns written before it.
struct TableElements<'a> {
columns: &'a [ColumnDef],
like_elements: &'a [CreateTableLikeElement],
constraints: &'a [TableConstraint],
}

impl fmt::Display for TableElements<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
let mut write_element = |f: &mut fmt::Formatter, element: &dyn fmt::Display| {
if !first {
f.write_char(',')?;
SpaceOrNewline.fmt(f)?;
}
first = false;
element.fmt(f)
};
let mut like_elements = self.like_elements.iter().peekable();
for (index, column) in self.columns.iter().enumerate() {
while let Some(like_element) =
like_elements.next_if(|like| like.columns_before <= index)
{
write_element(f, &like_element.like)?;
}
write_element(f, column)?;
}
for like_element in like_elements {
write_element(f, &like_element.like)?;
}
for constraint in self.constraints {
write_element(f, constraint)?;
}
Ok(())
}
}

/// `WITH DATA` clause on `CREATE TABLE ... AS` statement.
///
/// [Teradata](https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Definition-Language-Syntax-and-Examples/Table-Statements/CREATE-TABLE-and-CREATE-TABLE-AS/Syntax-Elements/AS_clause/WITH-Clause-Phrase)
Expand Down
16 changes: 14 additions & 2 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12311,10 +12311,11 @@ impl Display for AlterUserPassword {
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum CreateTableLikeKind {
/// '''sql
/// CREATE TABLE new (LIKE old ...)
/// CREATE TABLE new (LIKE old ..., column ...)
/// '''
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
/// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
Parenthesized(CreateTableLike),
Parenthesized(Vec<CreateTableLikeElement>),
/// '''sql
/// CREATE TABLE new LIKE old ...
/// '''
Expand All @@ -12323,6 +12324,17 @@ pub enum CreateTableLikeKind {
Plain(CreateTableLike),
}

/// A `LIKE` element of a `CREATE TABLE` column list.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct CreateTableLikeElement {
/// The copied table and its options.
pub like: CreateTableLike,
/// The number of columns written before this element, which sets where the copied columns go.
pub columns_before: usize,
}

/// An option of a `CREATE TABLE ... (LIKE ...)` clause. A later option overrides an earlier one.
///
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
Expand Down
2 changes: 1 addition & 1 deletion src/ast/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ macro_rules! visit_noop {
};
}

visit_noop!(u8, u16, u32, u64, i8, i16, i32, i64, char, bool, String);
visit_noop!(u8, u16, u32, u64, usize, i8, i16, i32, i64, char, bool, String);

#[cfg(feature = "bigdecimal")]
visit_noop!(bigdecimal::BigDecimal);
Expand Down
165 changes: 94 additions & 71 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9516,10 +9516,25 @@ impl<'a> Parser<'a> {
};

// parse optional column list (schema)
let mut like_elements = vec![];
let (columns, constraints) = if partition_of.is_some() {
self.parse_partition_of_columns()?
} else {
self.parse_columns()?
let accepts_like = self.dialect.supports_create_table_like_parenthesized();
self.parse_table_elements(
Parser::parse_column_def,
accepts_like.then_some(&mut like_elements),
)?
};
let like = if like_elements.is_empty() {
like
} else if like.is_some() {
return parser_err!(
"CREATE TABLE cannot take LIKE both before and inside the column list",
like_elements[0].like.name.span().start
);
} else {
Some(CreateTableLikeKind::Parenthesized(like_elements))
};
let comment_after_column_def =
if dialect_of!(self is HiveDialect) && self.parse_keyword(Keyword::COMMENT) {
Expand Down Expand Up @@ -9759,69 +9774,60 @@ impl<'a> Parser<'a> {
&mut self,
allow_unquoted_hyphen: bool,
) -> Result<Option<CreateTableLikeKind>, ParserError> {
let like = if self.dialect.supports_create_table_like_parenthesized()
&& self.consume_token(&Token::LParen)
{
if self.parse_keyword(Keyword::LIKE) {
let name = self.parse_object_name(allow_unquoted_hyphen)?;
let mut options = Vec::new();
while let Some(keyword) =
self.parse_one_of_keywords(&[Keyword::INCLUDING, Keyword::EXCLUDING])
{
let property = match self.expect_one_of_keywords(&[
Keyword::ALL,
Keyword::COMMENTS,
Keyword::COMPRESSION,
Keyword::CONSTRAINTS,
Keyword::DEFAULTS,
Keyword::GENERATED,
Keyword::IDENTITY,
Keyword::INDEXES,
Keyword::STATISTICS,
Keyword::STORAGE,
])? {
Keyword::ALL => CreateTableLikeProperty::All,
Keyword::COMMENTS => CreateTableLikeProperty::Comments,
Keyword::COMPRESSION => CreateTableLikeProperty::Compression,
Keyword::CONSTRAINTS => CreateTableLikeProperty::Constraints,
Keyword::DEFAULTS => CreateTableLikeProperty::Defaults,
Keyword::GENERATED => CreateTableLikeProperty::Generated,
Keyword::IDENTITY => CreateTableLikeProperty::Identity,
Keyword::INDEXES => CreateTableLikeProperty::Indexes,
Keyword::STATISTICS => CreateTableLikeProperty::Statistics,
Keyword::STORAGE => CreateTableLikeProperty::Storage,
other => {
return Err(ParserError::ParserError(format!(
"Internal parser error: unexpected LIKE option {other:?}"
)))
}
};
options.push(if keyword == Keyword::INCLUDING {
CreateTableLikeOption::Including(property)
} else {
CreateTableLikeOption::Excluding(property)
});
}
self.expect_token(&Token::RParen)?;
Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
name,
options,
}))
} else {
// Rollback the '(' it's probably the columns list
self.prev_token();
None
}
} else if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
let name = self.parse_object_name(allow_unquoted_hyphen)?;
Some(CreateTableLikeKind::Plain(CreateTableLike {
Ok(Some(CreateTableLikeKind::Plain(CreateTableLike {
name,
options: vec![],
}))
})))
} else {
None
};
Ok(like)
Ok(None)
}
}

/// Parse the `INCLUDING` and `EXCLUDING` options of a `LIKE` element in a `CREATE TABLE` column list.
fn parse_create_table_like_options(
&mut self,
) -> Result<Vec<CreateTableLikeOption>, ParserError> {
let mut options = Vec::new();
while let Some(keyword) =
self.parse_one_of_keywords(&[Keyword::INCLUDING, Keyword::EXCLUDING])
{
let property = match self.expect_one_of_keywords(&[
Keyword::ALL,
Keyword::COMMENTS,
Keyword::COMPRESSION,
Keyword::CONSTRAINTS,
Keyword::DEFAULTS,
Keyword::GENERATED,
Keyword::IDENTITY,
Keyword::INDEXES,
Keyword::STATISTICS,
Keyword::STORAGE,
])? {
Keyword::ALL => CreateTableLikeProperty::All,
Keyword::COMMENTS => CreateTableLikeProperty::Comments,
Keyword::COMPRESSION => CreateTableLikeProperty::Compression,
Keyword::CONSTRAINTS => CreateTableLikeProperty::Constraints,
Keyword::DEFAULTS => CreateTableLikeProperty::Defaults,
Keyword::GENERATED => CreateTableLikeProperty::Generated,
Keyword::IDENTITY => CreateTableLikeProperty::Identity,
Keyword::INDEXES => CreateTableLikeProperty::Indexes,
Keyword::STATISTICS => CreateTableLikeProperty::Statistics,
Keyword::STORAGE => CreateTableLikeProperty::Storage,
other => {
return Err(ParserError::ParserError(format!(
"Internal parser error: unexpected LIKE option {other:?}"
)))
}
};
options.push(if keyword == Keyword::INCLUDING {
CreateTableLikeOption::Including(property)
} else {
CreateTableLikeOption::Excluding(property)
});
}
Ok(options)
}

pub(crate) fn parse_create_table_on_commit(&mut self) -> Result<OnCommit, ParserError> {
Expand Down Expand Up @@ -10237,7 +10243,7 @@ impl<'a> Parser<'a> {

/// Parse columns and constraints.
pub fn parse_columns(&mut self) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError> {
self.parse_table_elements(Parser::parse_column_def)
self.parse_table_elements(Parser::parse_column_def, None)
}

/// Parse the columns and constraints of a `PARTITION OF` table, whose column entries
Expand All @@ -10247,20 +10253,26 @@ impl<'a> Parser<'a> {
fn parse_partition_of_columns(
&mut self,
) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError> {
self.parse_table_elements(|parser| {
let name = parser.parse_identifier()?;
let _ = parser.parse_keywords(&[Keyword::WITH, Keyword::OPTIONS]); // [ WITH OPTIONS ]
Ok(ColumnDef {
name,
data_type: DataType::Unspecified,
options: parser.parse_column_option_defs()?,
})
})
self.parse_table_elements(
|parser| {
let name = parser.parse_identifier()?;
let _ = parser.parse_keywords(&[Keyword::WITH, Keyword::OPTIONS]); // [ WITH OPTIONS ]
Ok(ColumnDef {
name,
data_type: DataType::Unspecified,
options: parser.parse_column_option_defs()?,
})
},
None,
)
}

/// Parse a parenthesized list of columns and constraints, and of `LIKE` elements when
/// `like_elements` is given.
fn parse_table_elements(
&mut self,
mut parse_column: impl FnMut(&mut Self) -> Result<ColumnDef, ParserError>,
mut like_elements: Option<&mut Vec<CreateTableLikeElement>>,
) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError> {
let mut columns = vec![];
let mut constraints = vec![];
Expand All @@ -10269,7 +10281,18 @@ impl<'a> Parser<'a> {
}

loop {
if let Some(constraint) = self.parse_optional_table_constraint()? {
if let Some(like_elements) = like_elements
.as_deref_mut()
.filter(|_| self.parse_keyword(Keyword::LIKE))
{
like_elements.push(CreateTableLikeElement {
like: CreateTableLike {
name: self.parse_object_name(false)?,
options: self.parse_create_table_like_options()?,
},
columns_before: columns.len(),
});
} else if let Some(constraint) = self.parse_optional_table_constraint()? {
constraints.push(constraint);
} else if let Token::Word(_) = &self.peek_token_ref().token {
columns.push(parse_column(self)?);
Expand Down
Loading
Loading