Skip to content

Commit b660a3b

Browse files
authored
Redshift: CREATE TABLE ... (LIKE ..) (#1967)
1 parent 60a5c8d commit b660a3b

File tree

10 files changed

+224
-29
lines changed

10 files changed

+224
-29
lines changed

src/ast/ddl.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,12 @@ use sqlparser_derive::{Visit, VisitMut};
3131
use crate::ast::value::escape_single_quote_string;
3232
use crate::ast::{
3333
display_comma_separated, display_separated, ArgMode, CommentDef, CreateFunctionBody,
34-
CreateFunctionUsing, CreateTableOptions, DataType, Expr, FileFormat, FunctionBehavior,
35-
FunctionCalledOnNull, FunctionDeterminismSpecifier, FunctionParallel, HiveDistributionStyle,
36-
HiveFormat, HiveIOFormat, HiveRowFormat, Ident, MySQLColumnPosition, ObjectName, OnCommit,
37-
OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect, Query, RowAccessPolicy,
38-
SequenceOptions, Spanned, SqlOption, StorageSerializationPolicy, Tag, Value, ValueWithSpan,
39-
WrappedCollection,
34+
CreateFunctionUsing, CreateTableLikeKind, CreateTableOptions, DataType, Expr, FileFormat,
35+
FunctionBehavior, FunctionCalledOnNull, FunctionDeterminismSpecifier, FunctionParallel,
36+
HiveDistributionStyle, HiveFormat, HiveIOFormat, HiveRowFormat, Ident, MySQLColumnPosition,
37+
ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect,
38+
Query, RowAccessPolicy, SequenceOptions, Spanned, SqlOption, StorageSerializationPolicy, Tag,
39+
Value, ValueWithSpan, WrappedCollection,
4040
};
4141
use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
4242
use crate::keywords::Keyword;
@@ -2430,7 +2430,7 @@ pub struct CreateTable {
24302430
pub location: Option<String>,
24312431
pub query: Option<Box<Query>>,
24322432
pub without_rowid: bool,
2433-
pub like: Option<ObjectName>,
2433+
pub like: Option<CreateTableLikeKind>,
24342434
pub clone: Option<ObjectName>,
24352435
// For Hive dialect, the table comment is after the column definitions without `=`,
24362436
// so the `comment` field is optional and different than the comment field in the general options list.
@@ -2559,6 +2559,8 @@ impl fmt::Display for CreateTable {
25592559
} else if self.query.is_none() && self.like.is_none() && self.clone.is_none() {
25602560
// PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
25612561
f.write_str(" ()")?;
2562+
} else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
2563+
write!(f, " ({like_in_columns_list})")?;
25622564
}
25632565

25642566
// Hive table comment should be after column definitions, please refer to:
@@ -2572,9 +2574,8 @@ impl fmt::Display for CreateTable {
25722574
write!(f, " WITHOUT ROWID")?;
25732575
}
25742576

2575-
// Only for Hive
2576-
if let Some(l) = &self.like {
2577-
write!(f, " LIKE {l}")?;
2577+
if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
2578+
write!(f, " {like}")?;
25782579
}
25792580

25802581
if let Some(c) = &self.clone {

src/ast/helpers/stmt_create_table.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ use serde::{Deserialize, Serialize};
2525
use sqlparser_derive::{Visit, VisitMut};
2626

2727
use crate::ast::{
28-
ClusteredBy, ColumnDef, CommentDef, CreateTable, CreateTableOptions, Expr, FileFormat,
29-
HiveDistributionStyle, HiveFormat, Ident, ObjectName, OnCommit, OneOrManyWithParens, Query,
30-
RowAccessPolicy, Statement, StorageSerializationPolicy, TableConstraint, Tag,
31-
WrappedCollection,
28+
ClusteredBy, ColumnDef, CommentDef, CreateTable, CreateTableLikeKind, CreateTableOptions, Expr,
29+
FileFormat, HiveDistributionStyle, HiveFormat, Ident, ObjectName, OnCommit,
30+
OneOrManyWithParens, Query, RowAccessPolicy, Statement, StorageSerializationPolicy,
31+
TableConstraint, Tag, WrappedCollection,
3232
};
3333

3434
use crate::parser::ParserError;
@@ -81,7 +81,7 @@ pub struct CreateTableBuilder {
8181
pub location: Option<String>,
8282
pub query: Option<Box<Query>>,
8383
pub without_rowid: bool,
84-
pub like: Option<ObjectName>,
84+
pub like: Option<CreateTableLikeKind>,
8585
pub clone: Option<ObjectName>,
8686
pub comment: Option<CommentDef>,
8787
pub on_commit: Option<OnCommit>,
@@ -237,7 +237,7 @@ impl CreateTableBuilder {
237237
self
238238
}
239239

240-
pub fn like(mut self, like: Option<ObjectName>) -> Self {
240+
pub fn like(mut self, like: Option<CreateTableLikeKind>) -> Self {
241241
self.like = like;
242242
self
243243
}

src/ast/mod.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10465,6 +10465,62 @@ impl fmt::Display for CreateUser {
1046510465
}
1046610466
}
1046710467

10468+
/// Specifies how to create a new table based on an existing table's schema.
10469+
/// '''sql
10470+
/// CREATE TABLE new LIKE old ...
10471+
/// '''
10472+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10473+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10474+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10475+
pub enum CreateTableLikeKind {
10476+
/// '''sql
10477+
/// CREATE TABLE new (LIKE old ...)
10478+
/// '''
10479+
/// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
10480+
Parenthesized(CreateTableLike),
10481+
/// '''sql
10482+
/// CREATE TABLE new LIKE old ...
10483+
/// '''
10484+
/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-table#label-create-table-like)
10485+
/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_like)
10486+
Plain(CreateTableLike),
10487+
}
10488+
10489+
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10490+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10491+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10492+
pub enum CreateTableLikeDefaults {
10493+
Including,
10494+
Excluding,
10495+
}
10496+
10497+
impl fmt::Display for CreateTableLikeDefaults {
10498+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10499+
match self {
10500+
CreateTableLikeDefaults::Including => write!(f, "INCLUDING DEFAULTS"),
10501+
CreateTableLikeDefaults::Excluding => write!(f, "EXCLUDING DEFAULTS"),
10502+
}
10503+
}
10504+
}
10505+
10506+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10507+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10508+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10509+
pub struct CreateTableLike {
10510+
pub name: ObjectName,
10511+
pub defaults: Option<CreateTableLikeDefaults>,
10512+
}
10513+
10514+
impl fmt::Display for CreateTableLike {
10515+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10516+
write!(f, "LIKE {}", self.name)?;
10517+
if let Some(defaults) = &self.defaults {
10518+
write!(f, " {defaults}")?;
10519+
}
10520+
Ok(())
10521+
}
10522+
}
10523+
1046810524
#[cfg(test)]
1046910525
mod tests {
1047010526
use crate::tokenizer::Location;

src/ast/spans.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,7 @@ impl Spanned for CreateTable {
592592
location: _, // string, no span
593593
query,
594594
without_rowid: _, // bool
595-
like,
595+
like: _,
596596
clone,
597597
comment: _, // todo, no span
598598
on_commit: _,
@@ -627,7 +627,6 @@ impl Spanned for CreateTable {
627627
.chain(columns.iter().map(|i| i.span()))
628628
.chain(constraints.iter().map(|i| i.span()))
629629
.chain(query.iter().map(|i| i.span()))
630-
.chain(like.iter().map(|i| i.span()))
631630
.chain(clone.iter().map(|i| i.span())),
632631
)
633632
}

src/dialect/mod.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,25 @@ pub trait Dialect: Debug + Any {
11631163
fn supports_interval_options(&self) -> bool {
11641164
false
11651165
}
1166+
1167+
/// Returns true if the dialect supports specifying which table to copy
1168+
/// the schema from inside parenthesis.
1169+
///
1170+
/// Not parenthesized:
1171+
/// '''sql
1172+
/// CREATE TABLE new LIKE old ...
1173+
/// '''
1174+
/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-table#label-create-table-like)
1175+
/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_like)
1176+
///
1177+
/// Parenthesized:
1178+
/// '''sql
1179+
/// CREATE TABLE new (LIKE old ...)
1180+
/// '''
1181+
/// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
1182+
fn supports_create_table_like_parenthesized(&self) -> bool {
1183+
false
1184+
}
11661185
}
11671186

11681187
/// This represents the operators for which precedence must be defined

src/dialect/redshift.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,4 +139,8 @@ impl Dialect for RedshiftSqlDialect {
139139
fn supports_select_exclude(&self) -> bool {
140140
true
141141
}
142+
143+
fn supports_create_table_like_parenthesized(&self) -> bool {
144+
true
145+
}
142146
}

src/dialect/snowflake.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ use crate::ast::helpers::stmt_data_loading::{
2727
};
2828
use crate::ast::{
2929
CatalogSyncNamespaceMode, ColumnOption, ColumnPolicy, ColumnPolicyProperty, ContactEntry,
30-
CopyIntoSnowflakeKind, DollarQuotedString, Ident, IdentityParameters, IdentityProperty,
31-
IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, ObjectName,
32-
ObjectNamePart, RowAccessPolicy, ShowObjects, SqlOption, Statement, StorageSerializationPolicy,
33-
TagsColumnOption, WrappedCollection,
30+
CopyIntoSnowflakeKind, CreateTableLikeKind, DollarQuotedString, Ident, IdentityParameters,
31+
IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder,
32+
ObjectName, ObjectNamePart, RowAccessPolicy, ShowObjects, SqlOption, Statement,
33+
StorageSerializationPolicy, TagsColumnOption, WrappedCollection,
3434
};
3535
use crate::dialect::{Dialect, Precedence};
3636
use crate::keywords::Keyword;
@@ -668,8 +668,13 @@ pub fn parse_create_table(
668668
builder = builder.clone_clause(clone);
669669
}
670670
Keyword::LIKE => {
671-
let like = parser.parse_object_name(false).ok();
672-
builder = builder.like(like);
671+
let name = parser.parse_object_name(false)?;
672+
builder = builder.like(Some(CreateTableLikeKind::Plain(
673+
crate::ast::CreateTableLike {
674+
name,
675+
defaults: None,
676+
},
677+
)));
673678
}
674679
Keyword::CLUSTER => {
675680
parser.expect_keyword_is(Keyword::BY)?;

src/keywords.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ define_keywords!(
268268
DECLARE,
269269
DEDUPLICATE,
270270
DEFAULT,
271+
DEFAULTS,
271272
DEFAULT_DDL_COLLATION,
272273
DEFERRABLE,
273274
DEFERRED,
@@ -339,6 +340,7 @@ define_keywords!(
339340
EXCEPTION,
340341
EXCHANGE,
341342
EXCLUDE,
343+
EXCLUDING,
342344
EXCLUSIVE,
343345
EXEC,
344346
EXECUTE,
@@ -441,6 +443,7 @@ define_keywords!(
441443
IN,
442444
INCLUDE,
443445
INCLUDE_NULL_VALUES,
446+
INCLUDING,
444447
INCREMENT,
445448
INDEX,
446449
INDICATOR,

src/parser/mod.rs

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7347,11 +7347,7 @@ impl<'a> Parser<'a> {
73477347
// Clickhouse has `ON CLUSTER 'cluster'` syntax for DDLs
73487348
let on_cluster = self.parse_optional_on_cluster()?;
73497349

7350-
let like = if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
7351-
self.parse_object_name(allow_unquoted_hyphen).ok()
7352-
} else {
7353-
None
7354-
};
7350+
let like = self.maybe_parse_create_table_like(allow_unquoted_hyphen)?;
73557351

73567352
let clone = if self.parse_keyword(Keyword::CLONE) {
73577353
self.parse_object_name(allow_unquoted_hyphen).ok()
@@ -7455,6 +7451,44 @@ impl<'a> Parser<'a> {
74557451
.build())
74567452
}
74577453

7454+
fn maybe_parse_create_table_like(
7455+
&mut self,
7456+
allow_unquoted_hyphen: bool,
7457+
) -> Result<Option<CreateTableLikeKind>, ParserError> {
7458+
let like = if self.dialect.supports_create_table_like_parenthesized()
7459+
&& self.consume_token(&Token::LParen)
7460+
{
7461+
if self.parse_keyword(Keyword::LIKE) {
7462+
let name = self.parse_object_name(allow_unquoted_hyphen)?;
7463+
let defaults = if self.parse_keywords(&[Keyword::INCLUDING, Keyword::DEFAULTS]) {
7464+
Some(CreateTableLikeDefaults::Including)
7465+
} else if self.parse_keywords(&[Keyword::EXCLUDING, Keyword::DEFAULTS]) {
7466+
Some(CreateTableLikeDefaults::Excluding)
7467+
} else {
7468+
None
7469+
};
7470+
self.expect_token(&Token::RParen)?;
7471+
Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
7472+
name,
7473+
defaults,
7474+
}))
7475+
} else {
7476+
// Rollback the '(' it's probably the columns list
7477+
self.prev_token();
7478+
None
7479+
}
7480+
} else if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
7481+
let name = self.parse_object_name(allow_unquoted_hyphen)?;
7482+
Some(CreateTableLikeKind::Plain(CreateTableLike {
7483+
name,
7484+
defaults: None,
7485+
}))
7486+
} else {
7487+
None
7488+
};
7489+
Ok(like)
7490+
}
7491+
74587492
pub(crate) fn parse_create_table_on_commit(&mut self) -> Result<OnCommit, ParserError> {
74597493
if self.parse_keywords(&[Keyword::DELETE, Keyword::ROWS]) {
74607494
Ok(OnCommit::DeleteRows)

tests/sqlparser_common.rs

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16655,3 +16655,77 @@ fn test_parse_default_with_collate_column_option() {
1665516655
panic!("Expected create table statement");
1665616656
}
1665716657
}
16658+
16659+
#[test]
16660+
fn parse_create_table_like() {
16661+
let dialects = all_dialects_except(|d| d.supports_create_table_like_parenthesized());
16662+
let sql = "CREATE TABLE new LIKE old";
16663+
match dialects.verified_stmt(sql) {
16664+
Statement::CreateTable(stmt) => {
16665+
assert_eq!(
16666+
stmt.name,
16667+
ObjectName::from(vec![Ident::new("new".to_string())])
16668+
);
16669+
assert_eq!(
16670+
stmt.like,
16671+
Some(CreateTableLikeKind::Plain(CreateTableLike {
16672+
name: ObjectName::from(vec![Ident::new("old".to_string())]),
16673+
defaults: None,
16674+
}))
16675+
)
16676+
}
16677+
_ => unreachable!(),
16678+
}
16679+
let dialects = all_dialects_where(|d| d.supports_create_table_like_parenthesized());
16680+
let sql = "CREATE TABLE new (LIKE old)";
16681+
match dialects.verified_stmt(sql) {
16682+
Statement::CreateTable(stmt) => {
16683+
assert_eq!(
16684+
stmt.name,
16685+
ObjectName::from(vec![Ident::new("new".to_string())])
16686+
);
16687+
assert_eq!(
16688+
stmt.like,
16689+
Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
16690+
name: ObjectName::from(vec![Ident::new("old".to_string())]),
16691+
defaults: None,
16692+
}))
16693+
)
16694+
}
16695+
_ => unreachable!(),
16696+
}
16697+
let sql = "CREATE TABLE new (LIKE old INCLUDING DEFAULTS)";
16698+
match dialects.verified_stmt(sql) {
16699+
Statement::CreateTable(stmt) => {
16700+
assert_eq!(
16701+
stmt.name,
16702+
ObjectName::from(vec![Ident::new("new".to_string())])
16703+
);
16704+
assert_eq!(
16705+
stmt.like,
16706+
Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
16707+
name: ObjectName::from(vec![Ident::new("old".to_string())]),
16708+
defaults: Some(CreateTableLikeDefaults::Including),
16709+
}))
16710+
)
16711+
}
16712+
_ => unreachable!(),
16713+
}
16714+
let sql = "CREATE TABLE new (LIKE old EXCLUDING DEFAULTS)";
16715+
match dialects.verified_stmt(sql) {
16716+
Statement::CreateTable(stmt) => {
16717+
assert_eq!(
16718+
stmt.name,
16719+
ObjectName::from(vec![Ident::new("new".to_string())])
16720+
);
16721+
assert_eq!(
16722+
stmt.like,
16723+
Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
16724+
name: ObjectName::from(vec![Ident::new("old".to_string())]),
16725+
defaults: Some(CreateTableLikeDefaults::Excluding),
16726+
}))
16727+
)
16728+
}
16729+
_ => unreachable!(),
16730+
}
16731+
}

0 commit comments

Comments
 (0)