PostgreSQL: Support ALTER COLUMN SET GENERATED and RESTART
diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index 6f41afa..6722444 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs
@@ -1431,6 +1431,13 @@ /// Optional sequence options for identity generation. sequence_options: Option<Vec<SequenceOptions>>, }, + /// `{ SET GENERATED { ALWAYS | BY DEFAULT } | RESTART [ [ WITH ] restart ] } [...]` + /// + /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertable.html) + AlterIdentity { + /// The identity changes, in source order. + options: Vec<AlterIdentityOption>, + }, /// `DROP IDENTITY [ IF EXISTS ]` /// /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertable.html) @@ -1495,6 +1502,9 @@ } Ok(()) } + AlterColumnOperation::AlterIdentity { options } => { + write!(f, "{}", display_separated(options, " ")) + } AlterColumnOperation::DropIdentity { if_exists } => { write!(f, "DROP IDENTITY")?; if *if_exists { @@ -1509,6 +1519,41 @@ } } +/// One change to an identity column in [`AlterColumnOperation::AlterIdentity`]. +/// +/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertable.html) +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub enum AlterIdentityOption { + /// `SET GENERATED { ALWAYS | BY DEFAULT }` + SetGenerated(GeneratedAs), + /// `RESTART`, restarting at the sequence's start value. + Restart, + /// `RESTART [WITH] <expr>`, with `true` when `WITH` is present. + RestartWith(Expr, bool), +} + +impl fmt::Display for AlterIdentityOption { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + AlterIdentityOption::SetGenerated(generated_as) => { + let generated_as = match generated_as { + GeneratedAs::Always => "ALWAYS", + GeneratedAs::ByDefault => "BY DEFAULT", + GeneratedAs::ExpStored => "", + }; + write!(f, "SET GENERATED {generated_as}") + } + AlterIdentityOption::Restart => write!(f, "RESTART"), + AlterIdentityOption::RestartWith(restart, with) => { + let with = if *with { " WITH" } else { "" }; + write!(f, "RESTART{with} {restart}") + } + } + } +} + /// An element of a PostgreSQL `OPTIONS ( [ ADD | SET | DROP ] option ['value'] [, ...] )` /// list in an `ALTER` statement. ///
diff --git a/src/ast/mod.rs b/src/ast/mod.rs index b64cb6a..1962162 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs
@@ -67,11 +67,11 @@ AggregateArgs, AggregateModifyKind, AggregateSignature, Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation, AlterConnectorOwner, AlterExtension, AlterExtensionMember, AlterExtensionOperation, AlterFunction, AlterFunctionAction, - AlterFunctionOperation, AlterFunctionSignature, AlterGenericOption, AlterIndexOperation, - AlterOperator, AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily, - AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy, AlterPolicyOperation, - AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock, - AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation, + AlterFunctionOperation, AlterFunctionSignature, AlterGenericOption, AlterIdentityOption, + AlterIndexOperation, AlterOperator, AlterOperatorClass, AlterOperatorClassOperation, + AlterOperatorFamily, AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy, + AlterPolicyOperation, AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, + AlterTableLock, AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation, AlterTextSearchOption, AlterTrigger, AlterTriggerOperation, AlterType, AlterTypeAddValue, AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, AlterView, AlterViewOperation, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef,
diff --git a/src/ast/spans.rs b/src/ast/spans.rs index dee7eea..d8c015b 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs
@@ -970,6 +970,7 @@ /// - [AlterColumnOperation::DropNotNull] /// - [AlterColumnOperation::DropDefault] /// - [AlterColumnOperation::AddGenerated] +/// - [AlterColumnOperation::AlterIdentity] /// - [AlterColumnOperation::DropIdentity] impl Spanned for AlterColumnOperation { fn span(&self) -> Span { @@ -984,6 +985,7 @@ had_set: _, } => using.as_ref().map_or(Span::empty(), |u| u.span()), AlterColumnOperation::AddGenerated { .. } + | AlterColumnOperation::AlterIdentity { .. } | AlterColumnOperation::DropIdentity { .. } => Span::empty(), AlterColumnOperation::GenericOptions { options } => { union_spans(options.iter().map(|option| option.span()))
diff --git a/src/parser/mod.rs b/src/parser/mod.rs index ab658b7..e465598 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs
@@ -11770,6 +11770,12 @@ generated_as, sequence_options, } + } else if let Some(option) = self.parse_alter_identity_option()? { + let mut options = vec![option]; + while let Some(option) = self.parse_alter_identity_option()? { + options.push(option); + } + AlterColumnOperation::AlterIdentity { options } } else if self.parse_keywords(&[Keyword::DROP, Keyword::IDENTITY]) { AlterColumnOperation::DropIdentity { if_exists: self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]), @@ -21971,6 +21977,34 @@ Ok(sequence_options) } + /// Parse one item of the identity column changes of `ALTER COLUMN`, or + /// return `None` without consuming anything when the next tokens start none. + fn parse_alter_identity_option(&mut self) -> Result<Option<AlterIdentityOption>, ParserError> { + if self.parse_keyword(Keyword::RESTART) { + let with = self.parse_keyword(Keyword::WITH); + let value = if with { + Some(self.parse_number()?) + } else { + self.maybe_parse(|parser| parser.parse_number())? + }; + return Ok(Some(match value { + Some(value) => AlterIdentityOption::RestartWith(value, with), + None => AlterIdentityOption::Restart, + })); + } + if self.parse_keywords(&[Keyword::SET, Keyword::GENERATED]) { + let generated_as = if self.parse_keyword(Keyword::ALWAYS) { + GeneratedAs::Always + } else if self.parse_keywords(&[Keyword::BY, Keyword::DEFAULT]) { + GeneratedAs::ByDefault + } else { + return self.expected_ref("ALWAYS or BY DEFAULT", self.peek_token_ref()); + }; + return Ok(Some(AlterIdentityOption::SetGenerated(generated_as))); + } + Ok(None) + } + /// Parse a `CREATE SERVER` statement. /// /// See [Statement::CreateServer]
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index 983b612..d732f96 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs
@@ -14162,3 +14162,52 @@ "sql parser error: Expected: end of statement, found: IF" ); } + +#[test] +fn parse_alter_table_alter_column_identity() { + for sql in [ + "ALTER TABLE tab ALTER COLUMN id SET GENERATED BY DEFAULT", + "ALTER TABLE tab ALTER COLUMN id RESTART WITH 100", + "ALTER TABLE tab ALTER COLUMN id RESTART -5", + "ALTER TABLE tab ALTER COLUMN id RESTART", + "ALTER TABLE tab ALTER COLUMN id RESTART SET GENERATED ALWAYS, ALTER COLUMN other SET NOT NULL", + ] { + pg_and_generic().verified_stmt(sql); + } + + match alter_table_op( + pg_and_generic() + .verified_stmt("ALTER TABLE tab ALTER COLUMN id SET GENERATED ALWAYS RESTART 7"), + ) { + AlterTableOperation::AlterColumn { column_name, op } => { + assert_eq!("id", column_name.to_string()); + assert_eq!( + op, + AlterColumnOperation::AlterIdentity { + options: vec![ + AlterIdentityOption::SetGenerated(GeneratedAs::Always), + AlterIdentityOption::RestartWith(Expr::value(number("7")), false), + ], + } + ); + } + _ => unreachable!(), + } + + for (sql, expected) in [ + ( + "ALTER TABLE tab ALTER COLUMN id RESTART WITH", + "Expected: a value, found: EOF", + ), + ( + "ALTER TABLE tab ALTER COLUMN id SET GENERATED", + "Expected: ALWAYS or BY DEFAULT, found: EOF", + ), + ] { + assert_eq!( + pg().parse_sql_statements(sql).unwrap_err().to_string(), + format!("sql parser error: {expected}"), + "{sql}" + ); + } +}