Skip to content

Commit ee23171

Browse files
Merge branch 'main' into alter-operator-class
2 parents bae6ee6 + 00da3d7 commit ee23171

20 files changed

+876
-52
lines changed

src/ast/ddl.rs

Lines changed: 111 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,14 @@ use crate::ast::{
4343
},
4444
ArgMode, AttachedToken, CommentDef, ConditionalStatements, CreateFunctionBody,
4545
CreateFunctionUsing, CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr,
46-
FileFormat, FunctionBehavior, FunctionCalledOnNull, FunctionDesc, FunctionDeterminismSpecifier,
47-
FunctionParallel, HiveDistributionStyle, HiveFormat, HiveIOFormat, HiveRowFormat,
48-
HiveSetLocation, Ident, InitializeKind, MySQLColumnPosition, ObjectName, OnCommit,
49-
OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect, Query, RefreshModeKind,
50-
RowAccessPolicy, SequenceOptions, Spanned, SqlOption, StorageSerializationPolicy, TableVersion,
51-
Tag, TriggerEvent, TriggerExecBody, TriggerObject, TriggerPeriod, TriggerReferencing, Value,
52-
ValueWithSpan, WrappedCollection,
46+
FileFormat, FunctionBehavior, FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc,
47+
FunctionDeterminismSpecifier, FunctionParallel, FunctionSecurity, HiveDistributionStyle,
48+
HiveFormat, HiveIOFormat, HiveRowFormat, HiveSetLocation, Ident, InitializeKind,
49+
MySQLColumnPosition, ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg,
50+
OrderByExpr, ProjectionSelect, Query, RefreshModeKind, RowAccessPolicy, SequenceOptions,
51+
Spanned, SqlOption, StorageSerializationPolicy, TableVersion, Tag, TriggerEvent,
52+
TriggerExecBody, TriggerObject, TriggerPeriod, TriggerReferencing, Value, ValueWithSpan,
53+
WrappedCollection,
5354
};
5455
use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
5556
use crate::keywords::Keyword;
@@ -2944,6 +2945,14 @@ pub struct CreateTable {
29442945
/// <https://www.postgresql.org/docs/current/ddl-inherit.html>
29452946
/// <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-INHERITS>
29462947
pub inherits: Option<Vec<ObjectName>>,
2948+
/// PostgreSQL `PARTITION OF` clause to create a partition of a parent table.
2949+
/// Contains the parent table name.
2950+
/// <https://www.postgresql.org/docs/current/sql-createtable.html>
2951+
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2952+
pub partition_of: Option<ObjectName>,
2953+
/// PostgreSQL partition bound specification for PARTITION OF.
2954+
/// <https://www.postgresql.org/docs/current/sql-createtable.html>
2955+
pub for_values: Option<ForValues>,
29472956
/// SQLite "STRICT" clause.
29482957
/// if the "STRICT" table-option keyword is added to the end, after the closing ")",
29492958
/// then strict typing rules apply to that table.
@@ -3039,6 +3048,9 @@ impl fmt::Display for CreateTable {
30393048
dynamic = if self.dynamic { "DYNAMIC " } else { "" },
30403049
name = self.name,
30413050
)?;
3051+
if let Some(partition_of) = &self.partition_of {
3052+
write!(f, " PARTITION OF {partition_of}")?;
3053+
}
30423054
if let Some(on_cluster) = &self.on_cluster {
30433055
write!(f, " ON CLUSTER {on_cluster}")?;
30443056
}
@@ -3053,12 +3065,19 @@ impl fmt::Display for CreateTable {
30533065
Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
30543066
NewLine.fmt(f)?;
30553067
f.write_str(")")?;
3056-
} else if self.query.is_none() && self.like.is_none() && self.clone.is_none() {
3068+
} else if self.query.is_none()
3069+
&& self.like.is_none()
3070+
&& self.clone.is_none()
3071+
&& self.partition_of.is_none()
3072+
{
30573073
// PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
30583074
f.write_str(" ()")?;
30593075
} else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
30603076
write!(f, " ({like_in_columns_list})")?;
30613077
}
3078+
if let Some(for_values) = &self.for_values {
3079+
write!(f, " {for_values}")?;
3080+
}
30623081

30633082
// Hive table comment should be after column definitions, please refer to:
30643083
// [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
@@ -3300,6 +3319,76 @@ impl fmt::Display for CreateTable {
33003319
}
33013320
}
33023321

3322+
/// PostgreSQL partition bound specification for `PARTITION OF`.
3323+
///
3324+
/// Specifies partition bounds for a child partition table.
3325+
///
3326+
/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
3327+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3328+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3329+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3330+
pub enum ForValues {
3331+
/// `FOR VALUES IN (expr, ...)`
3332+
In(Vec<Expr>),
3333+
/// `FOR VALUES FROM (expr|MINVALUE|MAXVALUE, ...) TO (expr|MINVALUE|MAXVALUE, ...)`
3334+
From {
3335+
from: Vec<PartitionBoundValue>,
3336+
to: Vec<PartitionBoundValue>,
3337+
},
3338+
/// `FOR VALUES WITH (MODULUS n, REMAINDER r)`
3339+
With { modulus: u64, remainder: u64 },
3340+
/// `DEFAULT`
3341+
Default,
3342+
}
3343+
3344+
impl fmt::Display for ForValues {
3345+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3346+
match self {
3347+
ForValues::In(values) => {
3348+
write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3349+
}
3350+
ForValues::From { from, to } => {
3351+
write!(
3352+
f,
3353+
"FOR VALUES FROM ({}) TO ({})",
3354+
display_comma_separated(from),
3355+
display_comma_separated(to)
3356+
)
3357+
}
3358+
ForValues::With { modulus, remainder } => {
3359+
write!(
3360+
f,
3361+
"FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3362+
)
3363+
}
3364+
ForValues::Default => write!(f, "DEFAULT"),
3365+
}
3366+
}
3367+
}
3368+
3369+
/// A value in a partition bound specification.
3370+
///
3371+
/// Used in RANGE partition bounds where values can be expressions,
3372+
/// MINVALUE (negative infinity), or MAXVALUE (positive infinity).
3373+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3374+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3375+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3376+
pub enum PartitionBoundValue {
3377+
Expr(Expr),
3378+
MinValue,
3379+
MaxValue,
3380+
}
3381+
3382+
impl fmt::Display for PartitionBoundValue {
3383+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3384+
match self {
3385+
PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3386+
PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3387+
PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3388+
}
3389+
}
3390+
}
3391+
33033392
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
33043393
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
33053394
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
@@ -3392,6 +3481,14 @@ pub struct CreateFunction {
33923481
///
33933482
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
33943483
pub parallel: Option<FunctionParallel>,
3484+
/// SECURITY { DEFINER | INVOKER }
3485+
///
3486+
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3487+
pub security: Option<FunctionSecurity>,
3488+
/// SET configuration_parameter clauses
3489+
///
3490+
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3491+
pub set_params: Vec<FunctionDefinitionSetParam>,
33953492
/// USING ... (Hive only)
33963493
pub using: Option<CreateFunctionUsing>,
33973494
/// Language used in a UDF definition.
@@ -3458,6 +3555,12 @@ impl fmt::Display for CreateFunction {
34583555
if let Some(parallel) = &self.parallel {
34593556
write!(f, " {parallel}")?;
34603557
}
3558+
if let Some(security) = &self.security {
3559+
write!(f, " {security}")?;
3560+
}
3561+
for set_param in &self.set_params {
3562+
write!(f, " {set_param}")?;
3563+
}
34613564
if let Some(remote_connection) = &self.remote_connection {
34623565
write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
34633566
}

src/ast/helpers/stmt_create_table.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ use sqlparser_derive::{Visit, VisitMut};
2626

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

@@ -124,6 +124,10 @@ pub struct CreateTableBuilder {
124124
pub clustered_by: Option<ClusteredBy>,
125125
/// Optional parent tables (`INHERITS`).
126126
pub inherits: Option<Vec<ObjectName>>,
127+
/// Optional partitioned table (`PARTITION OF`)
128+
pub partition_of: Option<ObjectName>,
129+
/// Range of values associated with the partition (`FOR VALUES`)
130+
pub for_values: Option<ForValues>,
127131
/// `STRICT` table flag.
128132
pub strict: bool,
129133
/// Whether to copy grants from the source.
@@ -202,6 +206,8 @@ impl CreateTableBuilder {
202206
cluster_by: None,
203207
clustered_by: None,
204208
inherits: None,
209+
partition_of: None,
210+
for_values: None,
205211
strict: false,
206212
copy_grants: false,
207213
enable_schema_evolution: None,
@@ -371,6 +377,19 @@ impl CreateTableBuilder {
371377
self.inherits = inherits;
372378
self
373379
}
380+
381+
/// Sets the table which is partitioned to create the current table.
382+
pub fn partition_of(mut self, partition_of: Option<ObjectName>) -> Self {
383+
self.partition_of = partition_of;
384+
self
385+
}
386+
387+
/// Sets the range of values associated with the partition.
388+
pub fn for_values(mut self, for_values: Option<ForValues>) -> Self {
389+
self.for_values = for_values;
390+
self
391+
}
392+
374393
/// Set `STRICT` option.
375394
pub fn strict(mut self, strict: bool) -> Self {
376395
self.strict = strict;
@@ -518,6 +537,8 @@ impl CreateTableBuilder {
518537
cluster_by: self.cluster_by,
519538
clustered_by: self.clustered_by,
520539
inherits: self.inherits,
540+
partition_of: self.partition_of,
541+
for_values: self.for_values,
521542
strict: self.strict,
522543
copy_grants: self.copy_grants,
523544
enable_schema_evolution: self.enable_schema_evolution,
@@ -582,6 +603,8 @@ impl TryFrom<Statement> for CreateTableBuilder {
582603
cluster_by,
583604
clustered_by,
584605
inherits,
606+
partition_of,
607+
for_values,
585608
strict,
586609
copy_grants,
587610
enable_schema_evolution,
@@ -632,6 +655,8 @@ impl TryFrom<Statement> for CreateTableBuilder {
632655
cluster_by,
633656
clustered_by,
634657
inherits,
658+
partition_of,
659+
for_values,
635660
strict,
636661
iceberg,
637662
copy_grants,

src/ast/mod.rs

Lines changed: 84 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -60,24 +60,24 @@ pub use self::dcl::{
6060
};
6161
pub use self::ddl::{
6262
Alignment, AlterColumnOperation, AlterConnectorOwner, AlterIndexOperation, AlterOperator,
63-
AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily,
64-
AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicyOperation, AlterSchema,
65-
AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock, AlterTableOperation,
66-
AlterTableType, AlterType, AlterTypeAddValue, AlterTypeAddValuePosition, AlterTypeOperation,
67-
AlterTypeRename, AlterTypeRenameValue, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef,
68-
ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector,
69-
CreateDomain, CreateExtension, CreateFunction, CreateIndex, CreateOperator,
70-
CreateOperatorClass, CreateOperatorFamily, CreateTable, CreateTrigger, CreateView, Deduplicate,
71-
DeferrableInitial, DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorClass,
72-
DropOperatorFamily, DropOperatorSignature, DropTrigger, GeneratedAs, GeneratedExpressionMode,
63+
AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily, AlterOperatorFamilyOperation, AlterOperatorOperation,
64+
AlterPolicyOperation, AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm,
65+
AlterTableLock, AlterTableOperation, AlterTableType, AlterType, AlterTypeAddValue,
66+
AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue,
67+
ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy,
68+
ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector, CreateDomain,
69+
CreateExtension, CreateFunction, CreateIndex, CreateOperator, CreateOperatorClass,
70+
CreateOperatorFamily, CreateTable, CreateTrigger, CreateView, Deduplicate, DeferrableInitial,
71+
DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorClass, DropOperatorFamily,
72+
DropOperatorSignature, DropTrigger, ForValues, GeneratedAs, GeneratedExpressionMode,
7373
IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind,
7474
IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck,
7575
NullsDistinctOption, OperatorArgTypes, OperatorClassItem, OperatorFamilyDropItem,
76-
OperatorFamilyItem, OperatorOption, OperatorPurpose, Owner, Partition, ProcedureParam,
77-
ReferentialAction, RenameTableNameKind, ReplicaIdentity, TagsColumnOption, TriggerObjectKind,
78-
Truncate, UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
79-
UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
80-
UserDefinedTypeStorage, ViewColumnDef,
76+
OperatorFamilyItem, OperatorOption, OperatorPurpose, Owner, Partition, PartitionBoundValue,
77+
ProcedureParam, ReferentialAction, RenameTableNameKind, ReplicaIdentity, TagsColumnOption,
78+
TriggerObjectKind, Truncate, UserDefinedTypeCompositeAttributeDef,
79+
UserDefinedTypeInternalLength, UserDefinedTypeRangeOption, UserDefinedTypeRepresentation,
80+
UserDefinedTypeSqlDefinitionOption, UserDefinedTypeStorage, ViewColumnDef,
8181
};
8282
pub use self::dml::{
8383
Delete, Insert, Merge, MergeAction, MergeClause, MergeClauseKind, MergeInsertExpr,
@@ -9173,14 +9173,14 @@ pub enum CopyLegacyOption {
91739173
IamRole(IamRoleKind),
91749174
/// IGNOREHEADER \[ AS \] number_rows
91759175
IgnoreHeader(u64),
9176-
/// JSON
9177-
Json,
9178-
/// `MANIFEST \[ VERBOSE \]`
9176+
/// JSON \[ AS \] 'json_option'
9177+
Json(Option<String>),
9178+
/// MANIFEST \[ VERBOSE \]
91799179
Manifest {
9180-
/// Whether the MANIFEST is verbose.
9181-
verbose: bool,
9180+
/// Whether the MANIFEST is verbose.
9181+
verbose: bool
91829182
},
9183-
/// `MAXFILESIZE \[ AS \] max-size \[ MB | GB \]`
9183+
/// MAXFILESIZE \[ AS \] max-size \[ MB | GB \]
91849184
MaxFileSize(FileSize),
91859185
/// `NULL \[ AS \] 'null_string'`
91869186
Null(String),
@@ -9268,7 +9268,13 @@ impl fmt::Display for CopyLegacyOption {
92689268
Header => write!(f, "HEADER"),
92699269
IamRole(role) => write!(f, "IAM_ROLE {role}"),
92709270
IgnoreHeader(num_rows) => write!(f, "IGNOREHEADER {num_rows}"),
9271-
Json => write!(f, "JSON"),
9271+
Json(opt) => {
9272+
write!(f, "JSON")?;
9273+
if let Some(opt) = opt {
9274+
write!(f, " AS '{}'", value::escape_single_quote_string(opt))?;
9275+
}
9276+
Ok(())
9277+
}
92729278
Manifest { verbose } => write!(f, "MANIFEST{}", if *verbose { " VERBOSE" } else { "" }),
92739279
MaxFileSize(file_size) => write!(f, "MAXFILESIZE {file_size}"),
92749280
Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
@@ -9704,6 +9710,62 @@ impl fmt::Display for FunctionBehavior {
97049710
}
97059711
}
97069712

9713+
/// Security attribute for functions: SECURITY DEFINER or SECURITY INVOKER.
9714+
///
9715+
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
9716+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9717+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9718+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9719+
pub enum FunctionSecurity {
9720+
Definer,
9721+
Invoker,
9722+
}
9723+
9724+
impl fmt::Display for FunctionSecurity {
9725+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9726+
match self {
9727+
FunctionSecurity::Definer => write!(f, "SECURITY DEFINER"),
9728+
FunctionSecurity::Invoker => write!(f, "SECURITY INVOKER"),
9729+
}
9730+
}
9731+
}
9732+
9733+
/// Value for a SET configuration parameter in a CREATE FUNCTION statement.
9734+
///
9735+
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
9736+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9737+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9738+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9739+
pub enum FunctionSetValue {
9740+
/// SET param = value1, value2, ...
9741+
Values(Vec<Expr>),
9742+
/// SET param FROM CURRENT
9743+
FromCurrent,
9744+
}
9745+
9746+
/// A SET configuration_parameter clause in a CREATE FUNCTION statement.
9747+
///
9748+
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
9749+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9750+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9751+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9752+
pub struct FunctionDefinitionSetParam {
9753+
pub name: Ident,
9754+
pub value: FunctionSetValue,
9755+
}
9756+
9757+
impl fmt::Display for FunctionDefinitionSetParam {
9758+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9759+
write!(f, "SET {} ", self.name)?;
9760+
match &self.value {
9761+
FunctionSetValue::Values(values) => {
9762+
write!(f, "= {}", display_comma_separated(values))
9763+
}
9764+
FunctionSetValue::FromCurrent => write!(f, "FROM CURRENT"),
9765+
}
9766+
}
9767+
}
9768+
97079769
/// These attributes describe the behavior of the function when called with a null argument.
97089770
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
97099771
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]

0 commit comments

Comments
 (0)