Skip to content

Commit 886ac09

Browse files
Merge branch 'main' into extended-create-func
2 parents b2acc60 + 78be8b1 commit 886ac09

File tree

14 files changed

+1227
-80
lines changed

14 files changed

+1227
-80
lines changed

src/ast/ddl.rs

Lines changed: 350 additions & 11 deletions
Large diffs are not rendered by default.

src/ast/mod.rs

Lines changed: 114 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -59,19 +59,21 @@ pub use self::dcl::{
5959
AlterRoleOperation, CreateRole, ResetConfig, RoleOption, SecondaryRoles, SetConfigValue, Use,
6060
};
6161
pub use self::ddl::{
62-
AlterColumnOperation, AlterConnectorOwner, AlterIndexOperation, AlterPolicyOperation,
63-
AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock,
64-
AlterTableOperation, AlterType, AlterTypeAddValue, AlterTypeAddValuePosition,
65-
AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, ClusteredBy, ColumnDef,
66-
ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy, ColumnPolicyProperty,
67-
ConstraintCharacteristics, CreateConnector, CreateDomain, CreateExtension, CreateFunction,
68-
CreateIndex, CreateTable, CreateTrigger, CreateView, Deduplicate, DeferrableInitial,
69-
DropBehavior, DropExtension, DropFunction, DropTrigger, GeneratedAs, GeneratedExpressionMode,
70-
IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind,
71-
IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck,
72-
NullsDistinctOption, Owner, Partition, ProcedureParam, ReferentialAction, RenameTableNameKind,
73-
ReplicaIdentity, TagsColumnOption, TriggerObjectKind, Truncate,
74-
UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation, ViewColumnDef,
62+
Alignment, AlterColumnOperation, AlterConnectorOwner, AlterIndexOperation,
63+
AlterPolicyOperation, AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm,
64+
AlterTableLock, AlterTableOperation, AlterTableType, AlterType, AlterTypeAddValue,
65+
AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue,
66+
ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy,
67+
ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector, CreateDomain,
68+
CreateExtension, CreateFunction, CreateIndex, CreateTable, CreateTrigger, CreateView,
69+
Deduplicate, DeferrableInitial, DropBehavior, DropExtension, DropFunction, DropTrigger,
70+
GeneratedAs, GeneratedExpressionMode, IdentityParameters, IdentityProperty,
71+
IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, IndexColumn,
72+
IndexOption, IndexType, KeyOrIndexDisplay, Msck, NullsDistinctOption, Owner, Partition,
73+
ProcedureParam, ReferentialAction, RenameTableNameKind, ReplicaIdentity, TagsColumnOption,
74+
TriggerObjectKind, Truncate, UserDefinedTypeCompositeAttributeDef,
75+
UserDefinedTypeInternalLength, UserDefinedTypeRangeOption, UserDefinedTypeRepresentation,
76+
UserDefinedTypeSqlDefinitionOption, UserDefinedTypeStorage, ViewColumnDef,
7577
};
7678
pub use self::dml::{Delete, Insert, Update};
7779
pub use self::operator::{BinaryOperator, UnaryOperator};
@@ -2919,6 +2921,15 @@ pub enum Set {
29192921
/// MySQL-style
29202922
/// SET a = 1, b = 2, ..;
29212923
MultipleAssignments { assignments: Vec<SetAssignment> },
2924+
/// Session authorization for Postgres/Redshift
2925+
///
2926+
/// ```sql
2927+
/// SET SESSION AUTHORIZATION { user_name | DEFAULT }
2928+
/// ```
2929+
///
2930+
/// See <https://www.postgresql.org/docs/current/sql-set-session-authorization.html>
2931+
/// See <https://docs.aws.amazon.com/redshift/latest/dg/r_SET_SESSION_AUTHORIZATION.html>
2932+
SetSessionAuthorization(SetSessionAuthorizationParam),
29222933
/// MS-SQL session
29232934
///
29242935
/// See <https://learn.microsoft.com/en-us/sql/t-sql/statements/set-statements-transact-sql>
@@ -2993,6 +3004,7 @@ impl Display for Set {
29933004
modifier = context_modifier.map(|m| format!("{m}")).unwrap_or_default()
29943005
)
29953006
}
3007+
Self::SetSessionAuthorization(kind) => write!(f, "SET SESSION AUTHORIZATION {kind}"),
29963008
Self::SetSessionParam(kind) => write!(f, "SET {kind}"),
29973009
Self::SetTransaction {
29983010
modes,
@@ -4097,7 +4109,7 @@ pub enum Statement {
40974109
/// ```
40984110
CreateType {
40994111
name: ObjectName,
4100-
representation: UserDefinedTypeRepresentation,
4112+
representation: Option<UserDefinedTypeRepresentation>,
41014113
},
41024114
/// ```sql
41034115
/// PRAGMA <schema-name>.<pragma-name> = <pragma-value>
@@ -4258,6 +4270,14 @@ pub enum Statement {
42584270
/// ```
42594271
/// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_VACUUM_command.html)
42604272
Vacuum(VacuumStatement),
4273+
/// Restore the value of a run-time parameter to the default value.
4274+
///
4275+
/// ```sql
4276+
/// RESET configuration_parameter;
4277+
/// RESET ALL;
4278+
/// ```
4279+
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-reset.html)
4280+
Reset(ResetStatement),
42614281
}
42624282

42634283
impl From<Analyze> for Statement {
@@ -5639,7 +5659,11 @@ impl fmt::Display for Statement {
56395659
name,
56405660
representation,
56415661
} => {
5642-
write!(f, "CREATE TYPE {name} AS {representation}")
5662+
write!(f, "CREATE TYPE {name}")?;
5663+
if let Some(repr) = representation {
5664+
write!(f, " {repr}")?;
5665+
}
5666+
Ok(())
56435667
}
56445668
Statement::Pragma { name, value, is_eq } => {
56455669
write!(f, "PRAGMA {name}")?;
@@ -5752,6 +5776,7 @@ impl fmt::Display for Statement {
57525776
Statement::AlterSchema(s) => write!(f, "{s}"),
57535777
Statement::Vacuum(s) => write!(f, "{s}"),
57545778
Statement::AlterUser(s) => write!(f, "{s}"),
5779+
Statement::Reset(s) => write!(f, "{s}"),
57555780
}
57565781
}
57575782
}
@@ -9813,6 +9838,42 @@ impl fmt::Display for TableObject {
98139838
}
98149839
}
98159840

9841+
/// Represents a SET SESSION AUTHORIZATION statement
9842+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9843+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9844+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9845+
pub struct SetSessionAuthorizationParam {
9846+
pub scope: ContextModifier,
9847+
pub kind: SetSessionAuthorizationParamKind,
9848+
}
9849+
9850+
impl fmt::Display for SetSessionAuthorizationParam {
9851+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9852+
write!(f, "{}", self.kind)
9853+
}
9854+
}
9855+
9856+
/// Represents the parameter kind for SET SESSION AUTHORIZATION
9857+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9858+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9859+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9860+
pub enum SetSessionAuthorizationParamKind {
9861+
/// Default authorization
9862+
Default,
9863+
9864+
/// User name
9865+
User(Ident),
9866+
}
9867+
9868+
impl fmt::Display for SetSessionAuthorizationParamKind {
9869+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9870+
match self {
9871+
SetSessionAuthorizationParamKind::Default => write!(f, "DEFAULT"),
9872+
SetSessionAuthorizationParamKind::User(name) => write!(f, "{}", name),
9873+
}
9874+
}
9875+
}
9876+
98169877
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
98179878
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
98189879
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
@@ -10514,6 +10575,38 @@ impl fmt::Display for VacuumStatement {
1051410575
}
1051510576
}
1051610577

10578+
/// Variants of the RESET statement
10579+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10580+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10581+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10582+
pub enum Reset {
10583+
/// Resets all session parameters to their default values.
10584+
ALL,
10585+
10586+
/// Resets a specific session parameter to its default value.
10587+
ConfigurationParameter(ObjectName),
10588+
}
10589+
10590+
/// Resets a session parameter to its default value.
10591+
/// ```sql
10592+
/// RESET { ALL | <configuration_parameter> }
10593+
/// ```
10594+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10595+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10596+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10597+
pub struct ResetStatement {
10598+
pub reset: Reset,
10599+
}
10600+
10601+
impl fmt::Display for ResetStatement {
10602+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10603+
match &self.reset {
10604+
Reset::ALL => write!(f, "RESET ALL"),
10605+
Reset::ConfigurationParameter(param) => write!(f, "RESET {}", param),
10606+
}
10607+
}
10608+
}
10609+
1051710610
impl From<Set> for Statement {
1051810611
fn from(s: Set) -> Self {
1051910612
Self::Set(s)
@@ -10754,6 +10847,12 @@ impl From<VacuumStatement> for Statement {
1075410847
}
1075510848
}
1075610849

10850+
impl From<ResetStatement> for Statement {
10851+
fn from(r: ResetStatement) -> Self {
10852+
Self::Reset(r)
10853+
}
10854+
}
10855+
1075710856
#[cfg(test)]
1075810857
mod tests {
1075910858
use crate::tokenizer::Location;

src/ast/query.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3135,12 +3135,18 @@ pub struct Values {
31353135
/// Was there an explicit ROWs keyword (MySQL)?
31363136
/// <https://dev.mysql.com/doc/refman/8.0/en/values.html>
31373137
pub explicit_row: bool,
3138+
// MySql supports both VALUES and VALUE keywords.
3139+
// <https://dev.mysql.com/doc/refman/9.2/en/insert.html>
3140+
pub value_keyword: bool,
31383141
pub rows: Vec<Vec<Expr>>,
31393142
}
31403143

31413144
impl fmt::Display for Values {
31423145
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3143-
f.write_str("VALUES")?;
3146+
match self.value_keyword {
3147+
true => f.write_str("VALUE")?,
3148+
false => f.write_str("VALUES")?,
3149+
};
31443150
let prefix = if self.explicit_row { "ROW" } else { "" };
31453151
let mut delim = "";
31463152
for row in &self.rows {

src/ast/spans.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ impl Spanned for Values {
223223
fn span(&self) -> Span {
224224
let Values {
225225
explicit_row: _, // bool,
226+
value_keyword: _,
226227
rows,
227228
} = self;
228229

@@ -475,6 +476,7 @@ impl Spanned for Statement {
475476
Statement::AlterSchema(s) => s.span(),
476477
Statement::Vacuum(..) => Span::empty(),
477478
Statement::AlterUser(..) => Span::empty(),
479+
Statement::Reset(..) => Span::empty(),
478480
}
479481
}
480482
}
@@ -1107,6 +1109,9 @@ impl Spanned for AlterTableOperation {
11071109
AlterTableOperation::DropClusteringKey => Span::empty(),
11081110
AlterTableOperation::SuspendRecluster => Span::empty(),
11091111
AlterTableOperation::ResumeRecluster => Span::empty(),
1112+
AlterTableOperation::Refresh => Span::empty(),
1113+
AlterTableOperation::Suspend => Span::empty(),
1114+
AlterTableOperation::Resume => Span::empty(),
11101115
AlterTableOperation::Algorithm { .. } => Span::empty(),
11111116
AlterTableOperation::AutoIncrement { value, .. } => value.span(),
11121117
AlterTableOperation::Lock { .. } => Span::empty(),

src/dialect/snowflake.rs

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
#[cfg(not(feature = "std"))]
1919
use crate::alloc::string::ToString;
20+
use crate::ast::helpers::attached_token::AttachedToken;
2021
use crate::ast::helpers::key_value_options::{
2122
KeyValueOption, KeyValueOptionKind, KeyValueOptions, KeyValueOptionsDelimiter,
2223
};
@@ -26,11 +27,12 @@ use crate::ast::helpers::stmt_data_loading::{
2627
FileStagingCommand, StageLoadSelectItem, StageLoadSelectItemKind, StageParamsObject,
2728
};
2829
use crate::ast::{
29-
CatalogSyncNamespaceMode, ColumnOption, ColumnPolicy, ColumnPolicyProperty, ContactEntry,
30-
CopyIntoSnowflakeKind, CreateTableLikeKind, DollarQuotedString, Ident, IdentityParameters,
31-
IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder,
32-
InitializeKind, ObjectName, ObjectNamePart, RefreshModeKind, RowAccessPolicy, ShowObjects,
33-
SqlOption, Statement, StorageSerializationPolicy, TagsColumnOption, Value, WrappedCollection,
30+
AlterTable, AlterTableOperation, AlterTableType, CatalogSyncNamespaceMode, ColumnOption,
31+
ColumnPolicy, ColumnPolicyProperty, ContactEntry, CopyIntoSnowflakeKind, CreateTableLikeKind,
32+
DollarQuotedString, Ident, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind,
33+
IdentityPropertyKind, IdentityPropertyOrder, InitializeKind, ObjectName, ObjectNamePart,
34+
RefreshModeKind, RowAccessPolicy, ShowObjects, SqlOption, Statement,
35+
StorageSerializationPolicy, TagsColumnOption, Value, WrappedCollection,
3436
};
3537
use crate::dialect::{Dialect, Precedence};
3638
use crate::keywords::Keyword;
@@ -214,6 +216,11 @@ impl Dialect for SnowflakeDialect {
214216
return Some(parser.parse_begin_exception_end());
215217
}
216218

219+
if parser.parse_keywords(&[Keyword::ALTER, Keyword::DYNAMIC, Keyword::TABLE]) {
220+
// ALTER DYNAMIC TABLE
221+
return Some(parse_alter_dynamic_table(parser));
222+
}
223+
217224
if parser.parse_keywords(&[Keyword::ALTER, Keyword::SESSION]) {
218225
// ALTER SESSION
219226
let set = match parser.parse_one_of_keywords(&[Keyword::SET, Keyword::UNSET]) {
@@ -604,6 +611,44 @@ fn parse_file_staging_command(kw: Keyword, parser: &mut Parser) -> Result<Statem
604611
}
605612
}
606613

614+
/// Parse snowflake alter dynamic table.
615+
/// <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
616+
fn parse_alter_dynamic_table(parser: &mut Parser) -> Result<Statement, ParserError> {
617+
// Use parse_object_name(true) to support IDENTIFIER() function
618+
let table_name = parser.parse_object_name(true)?;
619+
620+
// Parse the operation (REFRESH, SUSPEND, or RESUME)
621+
let operation = if parser.parse_keyword(Keyword::REFRESH) {
622+
AlterTableOperation::Refresh
623+
} else if parser.parse_keyword(Keyword::SUSPEND) {
624+
AlterTableOperation::Suspend
625+
} else if parser.parse_keyword(Keyword::RESUME) {
626+
AlterTableOperation::Resume
627+
} else {
628+
return parser.expected(
629+
"REFRESH, SUSPEND, or RESUME after ALTER DYNAMIC TABLE",
630+
parser.peek_token(),
631+
);
632+
};
633+
634+
let end_token = if parser.peek_token_ref().token == Token::SemiColon {
635+
parser.peek_token_ref().clone()
636+
} else {
637+
parser.get_current_token().clone()
638+
};
639+
640+
Ok(Statement::AlterTable(AlterTable {
641+
name: table_name,
642+
if_exists: false,
643+
only: false,
644+
operations: vec![operation],
645+
location: None,
646+
on_cluster: None,
647+
table_type: Some(AlterTableType::Dynamic),
648+
end_token: AttachedToken(end_token),
649+
}))
650+
}
651+
607652
/// Parse snowflake alter session.
608653
/// <https://docs.snowflake.com/en/sql-reference/sql/alter-session>
609654
fn parse_alter_session(parser: &mut Parser, set: bool) -> Result<Statement, ParserError> {

0 commit comments

Comments
 (0)