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
5 changes: 4 additions & 1 deletion fuzz/fuzz_seeds/alter_database.sql
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
ALTER DATABASE d RENAME TO "Weird"
ALTER DATABASE d RENAME TO "Weird";
ALTER DATABASE d SET search_path TO "$user", public;
ALTER DATABASE d SET TIME ZONE 'Asia/Tokyo';
ALTER DATABASE d SET XML OPTION DOCUMENT
73 changes: 69 additions & 4 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ use crate::ast::{
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,
RefreshModeKind, ResetConfig, RowAccessPolicy, SequenceOptions,
SetSessionAuthorizationParamKind, 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::keywords::Keyword;
Expand Down Expand Up @@ -5394,12 +5394,15 @@ pub enum AlterDatabaseOperation {
/// New database name.
new_name: Ident,
},
/// `SET ...`, stored as the database's default for a configuration parameter.
Set(ConfigurationSet),
}

impl fmt::Display for AlterDatabaseOperation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterDatabaseOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
AlterDatabaseOperation::Set(set) => write!(f, "{set}"),
}
}
}
Expand All @@ -5416,6 +5419,68 @@ impl Spanned for AlterDatabase {
}
}

/// A `SET` clause that stores a configuration parameter default, as in
/// `ALTER DATABASE ... SET`.
///
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-set.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 ConfigurationSet {
/// `SET configuration_parameter { TO | = } { value [, ...] | DEFAULT }`
/// or `SET configuration_parameter FROM CURRENT`
Parameter(FunctionDefinitionSetParam),
/// `SET TIME ZONE { value | LOCAL | DEFAULT }`
TimeZone(Expr),
/// `SET SCHEMA 'schema'`
Schema(ValueWithSpan),
/// `SET ROLE role_name`
Role(Ident),
/// `SET NAMES [ encoding | DEFAULT ]`
Names(Option<Expr>),
/// `SET SESSION AUTHORIZATION { user_name | DEFAULT }`
SessionAuthorization(SetSessionAuthorizationParamKind),
/// `SET XML OPTION { DOCUMENT | CONTENT }`
XmlOption(XmlOption),
}

impl fmt::Display for ConfigurationSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigurationSet::Parameter(param) => write!(f, "{param}"),
ConfigurationSet::TimeZone(value) => write!(f, "SET TIME ZONE {value}"),
ConfigurationSet::Schema(schema) => write!(f, "SET SCHEMA {schema}"),
ConfigurationSet::Role(role_name) => write!(f, "SET ROLE {role_name}"),
ConfigurationSet::Names(None) => f.write_str("SET NAMES"),
ConfigurationSet::Names(Some(encoding)) => write!(f, "SET NAMES {encoding}"),
ConfigurationSet::SessionAuthorization(kind) => {
write!(f, "SET SESSION AUTHORIZATION {kind}")
}
ConfigurationSet::XmlOption(option) => write!(f, "SET XML OPTION {option}"),
}
}
}

/// Value of `SET XML OPTION`.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum XmlOption {
/// `DOCUMENT`
Document,
/// `CONTENT`
Content,
}

impl fmt::Display for XmlOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
XmlOption::Document => "DOCUMENT",
XmlOption::Content => "CONTENT",
})
}
}

/// `ALTER [ MATERIALIZED ] VIEW` statement.
///
/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altermaterializedview.html)
Expand Down
39 changes: 20 additions & 19 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,25 +76,26 @@ pub use self::ddl::{
AlterTriggerOperation, AlterType, AlterTypeAddValue, AlterTypeAddValuePosition,
AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, AlterView, AlterViewOperation,
ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy,
ColumnPolicyProperty, ConstraintCharacteristics, CreateAggregate, CreateAggregateArgs,
CreateAggregateOption, CreateCollation, CreateCollationDefinition, CreateConnector,
CreateDomain, CreateExtension, CreateForeignDataWrapper, CreateForeignTable, CreateFunction,
CreateIndex, CreateOperator, CreateOperatorClass, CreateOperatorFamily, CreatePolicy,
CreatePolicyCommand, CreatePolicyType, CreateRule, CreateRuleAction, CreateRuleDoKind,
CreateRuleEvent, CreateTable, CreateTextSearch, CreateTrigger, CreateUserMapping, CreateView,
Deduplicate, DeferrableInitial, DetachPartitionMode, DistStyle, DropBehavior, DropExtension,
DropFunction, DropOperator, DropOperatorClass, DropOperatorFamily, DropOperatorSignature,
DropPolicy, DropRule, DropTrigger, ForValues, ForeignDataWrapperRoutineClause,
FunctionReturnType, GeneratedAs, GeneratedExpressionMode, IdentityParameters, IdentityProperty,
IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, IndexColumn,
IndexOption, IndexType, KeyOrIndexDisplay, Msck, NullsDistinctOption, OperatorArgTypes,
OperatorClassItem, OperatorFamilyDropItem, OperatorFamilyItem, OperatorOption, OperatorPurpose,
Owner, Partition, PartitionBoundValue, ProcedureParam, ReferentialAction, RenameTableNameKind,
ReplicaIdentity, SqliteTableOption, SqliteTableOptions, TagsColumnOption, TextSearchObjectType,
TriggerObjectKind, Truncate, UserDefinedTypeCompositeAttributeDef,
UserDefinedTypeInternalLength, UserDefinedTypeRangeOption, UserDefinedTypeRepresentation,
UserDefinedTypeSqlDefinitionOption, UserDefinedTypeStorage, UserMappingUser, ViewColumnDef,
VirtualTableModuleArgument, WithData,
ColumnPolicyProperty, ConfigurationSet, ConstraintCharacteristics, CreateAggregate,
CreateAggregateArgs, CreateAggregateOption, CreateCollation, CreateCollationDefinition,
CreateConnector, CreateDomain, CreateExtension, CreateForeignDataWrapper, CreateForeignTable,
CreateFunction, CreateIndex, CreateOperator, CreateOperatorClass, CreateOperatorFamily,
CreatePolicy, CreatePolicyCommand, CreatePolicyType, CreateRule, CreateRuleAction,
CreateRuleDoKind, CreateRuleEvent, CreateTable, CreateTextSearch, CreateTrigger,
CreateUserMapping, CreateView, Deduplicate, DeferrableInitial, DetachPartitionMode, DistStyle,
DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorClass, DropOperatorFamily,
DropOperatorSignature, DropPolicy, DropRule, DropTrigger, ForValues,
ForeignDataWrapperRoutineClause, FunctionReturnType, GeneratedAs, GeneratedExpressionMode,
IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind,
IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck,
NullsDistinctOption, OperatorArgTypes, OperatorClassItem, OperatorFamilyDropItem,
OperatorFamilyItem, OperatorOption, OperatorPurpose, Owner, Partition, PartitionBoundValue,
ProcedureParam, ReferentialAction, RenameTableNameKind, ReplicaIdentity, SqliteTableOption,
SqliteTableOptions, TagsColumnOption, TextSearchObjectType, TriggerObjectKind, Truncate,
UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
UserDefinedTypeStorage, UserMappingUser, ViewColumnDef, VirtualTableModuleArgument, WithData,
XmlOption,
};
pub use self::dml::{
Delete, Insert, InsertOverriding, Merge, MergeAction, MergeClause, MergeClauseKind,
Expand Down
2 changes: 2 additions & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ define_keywords!(
CONSTRAINT,
CONTACT,
CONTAINS,
CONTENT,
CONTINUE,
CONVERSION,
CONVERT,
Expand Down Expand Up @@ -358,6 +359,7 @@ define_keywords!(
DISTSTYLE,
DIV,
DO,
DOCUMENT,
DOMAIN,
DOUBLE,
DOW,
Expand Down
113 changes: 80 additions & 33 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6291,21 +6291,7 @@ impl<'a> Parser<'a> {
ensure_not_set(&body.support, "SUPPORT")?;
body.support = Some(self.parse_object_name(false)?);
} else if self.parse_keyword(Keyword::SET) {
let name = self.parse_object_name(false)?;
let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
FunctionSetValue::FromCurrent
} else {
if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
return self.expected_ref("= or TO", self.peek_token_ref());
}
if self.parse_keyword(Keyword::DEFAULT) {
FunctionSetValue::Default
} else {
let values = self.parse_comma_separated(Parser::parse_expr)?;
FunctionSetValue::Values(values)
}
};
set_params.push(FunctionDefinitionSetParam { name, value });
set_params.push(self.parse_function_definition_set_param()?);
} else if self.parse_keyword(Keyword::RETURN) {
ensure_not_set(&body.function_body, "RETURN")?;
body.function_body = Some(CreateFunctionBody::Return(self.parse_expr()?));
Expand Down Expand Up @@ -12310,23 +12296,9 @@ impl<'a> Parser<'a> {
} else if self.parse_keyword(Keyword::SUPPORT) {
Some(AlterFunctionAction::Support(self.parse_object_name(false)?))
} else if self.parse_keyword(Keyword::SET) {
let name = self.parse_object_name(false)?;
let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
FunctionSetValue::FromCurrent
} else {
if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
return self.expected_ref("= or TO", self.peek_token_ref());
}
if self.parse_keyword(Keyword::DEFAULT) {
FunctionSetValue::Default
} else {
FunctionSetValue::Values(self.parse_comma_separated(Parser::parse_expr)?)
}
};
Some(AlterFunctionAction::Set(FunctionDefinitionSetParam {
name,
value,
}))
Some(AlterFunctionAction::Set(
self.parse_function_definition_set_param()?,
))
} else if self.parse_keyword(Keyword::RESET) {
let reset_config = if self.parse_keyword(Keyword::ALL) {
ResetConfig::ALL
Expand All @@ -12341,6 +12313,27 @@ impl<'a> Parser<'a> {
Ok(action)
}

/// Parse `configuration_parameter { TO | = } { value [, ...] | DEFAULT }` or
/// `configuration_parameter FROM CURRENT`, after `SET`.
fn parse_function_definition_set_param(
&mut self,
) -> Result<FunctionDefinitionSetParam, ParserError> {
let name = self.parse_object_name(false)?;
let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
FunctionSetValue::FromCurrent
} else {
if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
return self.expected_ref("= or TO", self.peek_token_ref());
}
if self.parse_keyword(Keyword::DEFAULT) {
FunctionSetValue::Default
} else {
FunctionSetValue::Values(self.parse_comma_separated(Parser::parse_expr)?)
}
};
Ok(FunctionDefinitionSetParam { name, value })
}

fn parse_alter_function_actions(
&mut self,
) -> Result<(Vec<AlterFunctionAction>, bool), ParserError> {
Expand Down Expand Up @@ -12626,13 +12619,67 @@ impl<'a> Parser<'a> {
AlterDatabaseOperation::RenameTo {
new_name: self.parse_identifier()?,
}
} else if self.parse_keyword(Keyword::SET) {
AlterDatabaseOperation::Set(self.parse_configuration_set()?)
} else {
return self.expected_ref("RENAME TO after ALTER DATABASE", self.peek_token_ref());
return self.expected_ref(
"RENAME TO or SET after ALTER DATABASE",
self.peek_token_ref(),
);
};

Ok(AlterDatabase { name, operation })
}

/// Parse the clause after `SET` that stores a configuration parameter
/// default, as in `ALTER DATABASE ... SET`.
///
/// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-set.html)
fn parse_configuration_set(&mut self) -> Result<ConfigurationSet, ParserError> {
let set = if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE]) {
ConfigurationSet::TimeZone(self.parse_expr()?)
} else if self.parse_special_set_keyword(Keyword::SCHEMA) {
ConfigurationSet::Schema(self.parse_value()?)
} else if self.parse_special_set_keyword(Keyword::ROLE) {
ConfigurationSet::Role(self.parse_identifier()?)
} else if self.parse_special_set_keyword(Keyword::NAMES) {
ConfigurationSet::Names(
if matches!(self.peek_token_ref().token, Token::EOF | Token::SemiColon) {
None
} else {
Some(self.parse_expr()?)
},
)
} else if self.parse_keywords(&[Keyword::SESSION, Keyword::AUTHORIZATION]) {
ConfigurationSet::SessionAuthorization(if self.parse_keyword(Keyword::DEFAULT) {
SetSessionAuthorizationParamKind::Default
} else {
SetSessionAuthorizationParamKind::User(self.parse_identifier()?)
})
} else if self.parse_keywords(&[Keyword::XML, Keyword::OPTION]) {
ConfigurationSet::XmlOption(
match self.expect_one_of_keywords(&[Keyword::DOCUMENT, Keyword::CONTENT])? {
Keyword::DOCUMENT => XmlOption::Document,
_ => XmlOption::Content,
},
)
} else {
ConfigurationSet::Parameter(self.parse_function_definition_set_param()?)
};
Ok(set)
}

/// Consume `keyword` unless it names the parameter of a
/// `SET name { TO | = | FROM CURRENT }` assignment.
fn parse_special_set_keyword(&mut self, keyword: Keyword) -> bool {
let assignment_follows = match &self.peek_nth_token_ref(1).token {
Token::Eq => true,
Token::Word(w) => matches!(w.keyword, Keyword::TO | Keyword::FROM),
_ => false,
};
!assignment_follows && self.parse_keyword(keyword)
}

/// Parse a [Statement::AlterExtension]
///
/// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-alterextension.html)
Expand Down
Loading
Loading