Skip to content

Commit c75a992

Browse files
authored
Add support for Postgres ALTER TYPE (#1727)
1 parent 68c41a9 commit c75a992

File tree

6 files changed

+271
-61
lines changed

6 files changed

+271
-61
lines changed

src/ast/ddl.rs

+89
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,95 @@ impl fmt::Display for AlterIndexOperation {
640640
}
641641
}
642642

643+
/// An `ALTER TYPE` statement (`Statement::AlterType`)
644+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
645+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
646+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
647+
pub struct AlterType {
648+
pub name: ObjectName,
649+
pub operation: AlterTypeOperation,
650+
}
651+
652+
/// An [AlterType] operation
653+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
654+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
655+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
656+
pub enum AlterTypeOperation {
657+
Rename(AlterTypeRename),
658+
AddValue(AlterTypeAddValue),
659+
RenameValue(AlterTypeRenameValue),
660+
}
661+
662+
/// See [AlterTypeOperation::Rename]
663+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
664+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
665+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
666+
pub struct AlterTypeRename {
667+
pub new_name: Ident,
668+
}
669+
670+
/// See [AlterTypeOperation::AddValue]
671+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
672+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
673+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
674+
pub struct AlterTypeAddValue {
675+
pub if_not_exists: bool,
676+
pub value: Ident,
677+
pub position: Option<AlterTypeAddValuePosition>,
678+
}
679+
680+
/// See [AlterTypeAddValue]
681+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
682+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
683+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
684+
pub enum AlterTypeAddValuePosition {
685+
Before(Ident),
686+
After(Ident),
687+
}
688+
689+
/// See [AlterTypeOperation::RenameValue]
690+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
691+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
692+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
693+
pub struct AlterTypeRenameValue {
694+
pub from: Ident,
695+
pub to: Ident,
696+
}
697+
698+
impl fmt::Display for AlterTypeOperation {
699+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700+
match self {
701+
Self::Rename(AlterTypeRename { new_name }) => {
702+
write!(f, "RENAME TO {new_name}")
703+
}
704+
Self::AddValue(AlterTypeAddValue {
705+
if_not_exists,
706+
value,
707+
position,
708+
}) => {
709+
write!(f, "ADD VALUE")?;
710+
if *if_not_exists {
711+
write!(f, " IF NOT EXISTS")?;
712+
}
713+
write!(f, " {value}")?;
714+
match position {
715+
Some(AlterTypeAddValuePosition::Before(neighbor_value)) => {
716+
write!(f, " BEFORE {neighbor_value}")?;
717+
}
718+
Some(AlterTypeAddValuePosition::After(neighbor_value)) => {
719+
write!(f, " AFTER {neighbor_value}")?;
720+
}
721+
None => {}
722+
};
723+
Ok(())
724+
}
725+
Self::RenameValue(AlterTypeRenameValue { from, to }) => {
726+
write!(f, "RENAME VALUE {from} TO {to}")
727+
}
728+
}
729+
}
730+
}
731+
643732
/// An `ALTER COLUMN` (`Statement::AlterTable`) operation
644733
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
645734
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]

src/ast/mod.rs

+17-7
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,15 @@ pub use self::dcl::{
4848
};
4949
pub use self::ddl::{
5050
AlterColumnOperation, AlterConnectorOwner, AlterIndexOperation, AlterPolicyOperation,
51-
AlterTableOperation, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnPolicy,
52-
ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector, CreateFunction, Deduplicate,
53-
DeferrableInitial, DropBehavior, GeneratedAs, GeneratedExpressionMode, IdentityParameters,
54-
IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder,
55-
IndexOption, IndexType, KeyOrIndexDisplay, NullsDistinctOption, Owner, Partition,
56-
ProcedureParam, ReferentialAction, TableConstraint, TagsColumnOption,
57-
UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation, ViewColumnDef,
51+
AlterTableOperation, AlterType, AlterTypeAddValue, AlterTypeAddValuePosition,
52+
AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, ClusteredBy, ColumnDef,
53+
ColumnOption, ColumnOptionDef, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics,
54+
CreateConnector, CreateFunction, Deduplicate, DeferrableInitial, DropBehavior, GeneratedAs,
55+
GeneratedExpressionMode, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind,
56+
IdentityPropertyKind, IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay,
57+
NullsDistinctOption, Owner, Partition, ProcedureParam, ReferentialAction, TableConstraint,
58+
TagsColumnOption, UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation,
59+
ViewColumnDef,
5860
};
5961
pub use self::dml::{CreateIndex, CreateTable, Delete, Insert};
6062
pub use self::operator::{BinaryOperator, UnaryOperator};
@@ -2691,6 +2693,11 @@ pub enum Statement {
26912693
with_options: Vec<SqlOption>,
26922694
},
26932695
/// ```sql
2696+
/// ALTER TYPE
2697+
/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertype.html)
2698+
/// ```
2699+
AlterType(AlterType),
2700+
/// ```sql
26942701
/// ALTER ROLE
26952702
/// ```
26962703
AlterRole {
@@ -4438,6 +4445,9 @@ impl fmt::Display for Statement {
44384445
}
44394446
write!(f, " AS {query}")
44404447
}
4448+
Statement::AlterType(AlterType { name, operation }) => {
4449+
write!(f, "ALTER TYPE {name} {operation}")
4450+
}
44414451
Statement::AlterRole { name, operation } => {
44424452
write!(f, "ALTER ROLE {name} {operation}")
44434453
}

src/ast/spans.rs

+2
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ impl Spanned for Values {
215215
/// - [Statement::CopyIntoSnowflake]
216216
/// - [Statement::CreateSecret]
217217
/// - [Statement::CreateRole]
218+
/// - [Statement::AlterType]
218219
/// - [Statement::AlterRole]
219220
/// - [Statement::AttachDatabase]
220221
/// - [Statement::AttachDuckDBDatabase]
@@ -427,6 +428,7 @@ impl Spanned for Statement {
427428
.chain(with_options.iter().map(|i| i.span())),
428429
),
429430
// These statements need to be implemented
431+
Statement::AlterType { .. } => Span::empty(),
430432
Statement::AlterRole { .. } => Span::empty(),
431433
Statement::AttachDatabase { .. } => Span::empty(),
432434
Statement::AttachDuckDBDatabase { .. } => Span::empty(),

src/dialect/postgresql.rs

-44
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
// limitations under the License.
2929
use log::debug;
3030

31-
use crate::ast::{ObjectName, Statement, UserDefinedTypeRepresentation};
3231
use crate::dialect::{Dialect, Precedence};
3332
use crate::keywords::Keyword;
3433
use crate::parser::{Parser, ParserError};
@@ -135,15 +134,6 @@ impl Dialect for PostgreSqlDialect {
135134
}
136135
}
137136

138-
fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
139-
if parser.parse_keyword(Keyword::CREATE) {
140-
parser.prev_token(); // unconsume the CREATE in case we don't end up parsing anything
141-
parse_create(parser)
142-
} else {
143-
None
144-
}
145-
}
146-
147137
fn supports_filter_during_aggregation(&self) -> bool {
148138
true
149139
}
@@ -259,37 +249,3 @@ impl Dialect for PostgreSqlDialect {
259249
true
260250
}
261251
}
262-
263-
pub fn parse_create(parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
264-
let name = parser.maybe_parse(|parser| -> Result<ObjectName, ParserError> {
265-
parser.expect_keyword_is(Keyword::CREATE)?;
266-
parser.expect_keyword_is(Keyword::TYPE)?;
267-
let name = parser.parse_object_name(false)?;
268-
parser.expect_keyword_is(Keyword::AS)?;
269-
parser.expect_keyword_is(Keyword::ENUM)?;
270-
Ok(name)
271-
});
272-
273-
match name {
274-
Ok(name) => name.map(|name| parse_create_type_as_enum(parser, name)),
275-
Err(e) => Some(Err(e)),
276-
}
277-
}
278-
279-
// https://www.postgresql.org/docs/current/sql-createtype.html
280-
pub fn parse_create_type_as_enum(
281-
parser: &mut Parser,
282-
name: ObjectName,
283-
) -> Result<Statement, ParserError> {
284-
if !parser.consume_token(&Token::LParen) {
285-
return parser.expected("'(' after CREATE TYPE AS ENUM", parser.peek_token());
286-
}
287-
288-
let labels = parser.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
289-
parser.expect_token(&Token::RParen)?;
290-
291-
Ok(Statement::CreateType {
292-
name,
293-
representation: UserDefinedTypeRepresentation::Enum { labels },
294-
})
295-
}

src/parser/mod.rs

+69
Original file line numberDiff line numberDiff line change
@@ -8042,6 +8042,7 @@ impl<'a> Parser<'a> {
80428042
pub fn parse_alter(&mut self) -> Result<Statement, ParserError> {
80438043
let object_type = self.expect_one_of_keywords(&[
80448044
Keyword::VIEW,
8045+
Keyword::TYPE,
80458046
Keyword::TABLE,
80468047
Keyword::INDEX,
80478048
Keyword::ROLE,
@@ -8050,6 +8051,7 @@ impl<'a> Parser<'a> {
80508051
])?;
80518052
match object_type {
80528053
Keyword::VIEW => self.parse_alter_view(),
8054+
Keyword::TYPE => self.parse_alter_type(),
80538055
Keyword::TABLE => {
80548056
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
80558057
let only = self.parse_keyword(Keyword::ONLY); // [ ONLY ]
@@ -8122,6 +8124,55 @@ impl<'a> Parser<'a> {
81228124
})
81238125
}
81248126

8127+
/// Parse a [Statement::AlterType]
8128+
pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError> {
8129+
let name = self.parse_object_name(false)?;
8130+
8131+
if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
8132+
let new_name = self.parse_identifier()?;
8133+
Ok(Statement::AlterType(AlterType {
8134+
name,
8135+
operation: AlterTypeOperation::Rename(AlterTypeRename { new_name }),
8136+
}))
8137+
} else if self.parse_keywords(&[Keyword::ADD, Keyword::VALUE]) {
8138+
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8139+
let new_enum_value = self.parse_identifier()?;
8140+
let position = if self.parse_keyword(Keyword::BEFORE) {
8141+
Some(AlterTypeAddValuePosition::Before(self.parse_identifier()?))
8142+
} else if self.parse_keyword(Keyword::AFTER) {
8143+
Some(AlterTypeAddValuePosition::After(self.parse_identifier()?))
8144+
} else {
8145+
None
8146+
};
8147+
8148+
Ok(Statement::AlterType(AlterType {
8149+
name,
8150+
operation: AlterTypeOperation::AddValue(AlterTypeAddValue {
8151+
if_not_exists,
8152+
value: new_enum_value,
8153+
position,
8154+
}),
8155+
}))
8156+
} else if self.parse_keywords(&[Keyword::RENAME, Keyword::VALUE]) {
8157+
let existing_enum_value = self.parse_identifier()?;
8158+
self.expect_keyword(Keyword::TO)?;
8159+
let new_enum_value = self.parse_identifier()?;
8160+
8161+
Ok(Statement::AlterType(AlterType {
8162+
name,
8163+
operation: AlterTypeOperation::RenameValue(AlterTypeRenameValue {
8164+
from: existing_enum_value,
8165+
to: new_enum_value,
8166+
}),
8167+
}))
8168+
} else {
8169+
return self.expected_ref(
8170+
"{RENAME TO | { RENAME | ADD } VALUE}",
8171+
self.peek_token_ref(),
8172+
);
8173+
}
8174+
}
8175+
81258176
/// Parse a `CALL procedure_name(arg1, arg2, ...)`
81268177
/// or `CALL procedure_name` statement
81278178
pub fn parse_call(&mut self) -> Result<Statement, ParserError> {
@@ -14222,6 +14273,10 @@ impl<'a> Parser<'a> {
1422214273
let name = self.parse_object_name(false)?;
1422314274
self.expect_keyword_is(Keyword::AS)?;
1422414275

14276+
if self.parse_keyword(Keyword::ENUM) {
14277+
return self.parse_create_type_enum(name);
14278+
}
14279+
1422514280
let mut attributes = vec![];
1422614281
if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
1422714282
return Ok(Statement::CreateType {
@@ -14258,6 +14313,20 @@ impl<'a> Parser<'a> {
1425814313
})
1425914314
}
1426014315

14316+
/// Parse remainder of `CREATE TYPE AS ENUM` statement (see [Statement::CreateType] and [Self::parse_create_type])
14317+
///
14318+
/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
14319+
pub fn parse_create_type_enum(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
14320+
self.expect_token(&Token::LParen)?;
14321+
let labels = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
14322+
self.expect_token(&Token::RParen)?;
14323+
14324+
Ok(Statement::CreateType {
14325+
name,
14326+
representation: UserDefinedTypeRepresentation::Enum { labels },
14327+
})
14328+
}
14329+
1426114330
fn parse_parenthesized_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
1426214331
self.expect_token(&Token::LParen)?;
1426314332
let partitions = self.parse_comma_separated(|p| p.parse_identifier())?;

0 commit comments

Comments
 (0)