From 5ff93c4b1cb2be271b5e13dc4330d136b6c7d0c9 Mon Sep 17 00:00:00 2001 From: Hunter Date: Tue, 24 Nov 2026 00:59:56 +0800 Subject: [PATCH] PostgreSQL: Add support for CREATE STATISTICS --- src/ast/ddl.rs | 38 ++++++++++++++++++++++++++++ src/ast/mod.rs | 32 +++++++++++++----------- src/ast/spans.rs | 2 +- src/dialect/generic.rs | 4 +++ src/dialect/mod.rs | 5 ++++ src/dialect/postgresql.rs | 4 +++ src/parser/mod.rs | 50 +++++++++++++++++++++++++++++++++++++ tests/sqlparser_postgres.rs | 38 ++++++++++++++++++++++++++++ 8 files changed, 158 insertions(+), 15 deletions(-) diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index 28d498f8aa..c0226e0993 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -3950,6 +3950,44 @@ impl fmt::Display for CreateDomain { } } +/// [PostgreSQL extended statistics definition](https://www.postgresql.org/docs/current/sql-createstatistics.html). +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct CreateStatistics { + /// Name of the statistics object, if explicitly specified. + pub name: Option, + /// Whether an existing statistics object should be skipped. + pub if_not_exists: bool, + /// Requested kinds, such as `ndistinct` or `mcv`. + pub kinds: Vec, + /// Expressions on which to collect statistics. + pub expressions: Vec, + /// Relation on which to collect statistics. + pub table: ObjectName, +} + +impl fmt::Display for CreateStatistics { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("CREATE STATISTICS")?; + if self.if_not_exists { + f.write_str(" IF NOT EXISTS")?; + } + if let Some(name) = &self.name { + write!(f, " {name}")?; + } + if !self.kinds.is_empty() { + write!(f, " ({})", display_comma_separated(&self.kinds))?; + } + write!( + f, + " ON {} FROM {}", + display_comma_separated(&self.expressions), + self.table + ) + } +} + /// The return type of a `CREATE FUNCTION` statement. #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 97cb38ee56..def1e1114b 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -80,20 +80,21 @@ pub use self::ddl::{ 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, + CreateRuleDoKind, CreateRuleEvent, CreateStatistics, 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, }; pub use self::dml::{ Delete, Insert, InsertOverriding, Merge, MergeAction, MergeClause, MergeClauseKind, @@ -4889,6 +4890,8 @@ pub enum Statement { }, /// A `CREATE DOMAIN` statement. CreateDomain(CreateDomain), + /// PostgreSQL extended statistics definition. + CreateStatistics(CreateStatistics), /// ```sql /// CREATE TYPE /// ``` @@ -5613,6 +5616,7 @@ impl fmt::Display for Statement { } Statement::CreateFunction(create_function) => create_function.fmt(f), Statement::CreateDomain(create_domain) => create_domain.fmt(f), + Statement::CreateStatistics(statistics) => statistics.fmt(f), Statement::CreateTrigger(create_trigger) => create_trigger.fmt(f), Statement::DropTrigger(drop_trigger) => drop_trigger.fmt(f), Statement::CreateProcedure { diff --git a/src/ast/spans.rs b/src/ast/spans.rs index 89bd249cad..4ee081055a 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -454,7 +454,7 @@ impl Spanned for Statement { Statement::CreateSchema { .. } => Span::empty(), Statement::CreateDatabase { .. } => Span::empty(), Statement::CreateFunction { .. } => Span::empty(), - Statement::CreateDomain { .. } => Span::empty(), + Statement::CreateDomain { .. } | Statement::CreateStatistics(_) => Span::empty(), Statement::CreateTrigger { .. } => Span::empty(), Statement::DropTrigger { .. } => Span::empty(), Statement::CreateProcedure { .. } => Span::empty(), diff --git a/src/dialect/generic.rs b/src/dialect/generic.rs index fdf3529054..a6d93ed0a5 100644 --- a/src/dialect/generic.rs +++ b/src/dialect/generic.rs @@ -137,6 +137,10 @@ impl Dialect for GenericDialect { true } + fn supports_create_statistics(&self) -> bool { + true + } + fn supports_create_index_with_clause(&self) -> bool { true } diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs index 9c74cc62af..078a9b6698 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs @@ -1348,6 +1348,11 @@ pub trait Dialect: Debug + Any { false } + /// Whether PostgreSQL-style extended statistics can be defined. + fn supports_create_statistics(&self) -> bool { + false + } + /// Does the dialect support with clause in create index statement? /// e.g. `CREATE INDEX idx ON t WITH (key = value, key2)` fn supports_create_index_with_clause(&self) -> bool { diff --git a/src/dialect/postgresql.rs b/src/dialect/postgresql.rs index 361396b5fe..bc5a24080d 100644 --- a/src/dialect/postgresql.rs +++ b/src/dialect/postgresql.rs @@ -398,6 +398,10 @@ impl Dialect for PostgreSqlDialect { true } + fn supports_create_statistics(&self) -> bool { + true + } + fn supports_create_index_with_clause(&self) -> bool { true } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index f2a4b6e718..7da2b12d84 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -5566,6 +5566,16 @@ impl<'a> Parser<'a> { self.parse_create_external_table(or_replace).map(Into::into) } else if self.parse_keyword(Keyword::FUNCTION) { self.parse_create_function(or_alter, or_replace, temporary) + } else if self.dialect.supports_create_statistics() + && self.parse_keyword(Keyword::STATISTICS) + { + if has_modifier { + return parser_err!( + "CREATE STATISTICS does not accept this modifier", + modifier_loc + ); + } + self.parse_create_statistics() } else if self.parse_keyword(Keyword::DOMAIN) { self.parse_create_domain().map(Into::into) } else if self.parse_keyword(Keyword::TRIGGER) { @@ -7552,6 +7562,46 @@ impl<'a> Parser<'a> { Ok(owner) } + fn parse_create_statistics(&mut self) -> Result { + let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]); + let name = if !if_not_exists + && (self.peek_keyword(Keyword::ON) || self.peek_token_ref().token == Token::LParen) + { + None + } else { + Some(self.parse_object_name(false)?) + }; + let kinds = if self.peek_token_ref().token == Token::LParen { + self.parse_parenthesized(|parser| { + parser.parse_comma_separated(|parser| parser.parse_identifier()) + })? + } else { + Vec::new() + }; + self.expect_keyword_is(Keyword::ON)?; + let expressions = self.parse_comma_separated(|parser| { + let location = parser.peek_token_ref().span.start; + let expr = parser.parse_expr()?; + match expr { + Expr::Identifier(_) | Expr::Nested(_) => Ok(expr), + Expr::Function(ref fun) if fun.over.is_none() => Ok(expr), + _ => parser_err!( + "Expected a column, function call, or parenthesized expression", + location + ), + } + })?; + self.expect_keyword_is(Keyword::FROM)?; + let table = self.parse_object_name(false)?; + Ok(Statement::CreateStatistics(CreateStatistics { + name, + if_not_exists, + kinds, + expressions, + table, + })) + } + /// Parses a [Statement::CreateDomain] statement. fn parse_create_domain(&mut self) -> Result { let name = self.parse_object_name(false)?; diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index f5d84c5ed5..743a67e0bf 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -14530,3 +14530,41 @@ fn parse_alter_table_set_schema() { "sql parser error: Expected: identifier, found: EOF" ); } + +#[test] +fn parse_create_statistics() { + let statement = pg_and_generic().verified_stmt( + "CREATE STATISTICS IF NOT EXISTS public.s (mcv, dependencies) ON a, (b + 1) FROM public.t", + ); + let Statement::CreateStatistics(statistics) = statement else { + panic!("expected CREATE STATISTICS"); + }; + assert!(statistics.if_not_exists); + assert_eq!( + statistics.name.expect("statistics name").to_string(), + "public.s" + ); + assert_eq!(statistics.table.to_string(), "public.t"); + assert_eq!( + statistics.kinds, + vec![Ident::new("mcv"), Ident::new("dependencies")] + ); + assert!(matches!( + statistics.expressions.as_slice(), + [Expr::Identifier(_), Expr::Nested(_)] + )); + + for sql in [ + "CREATE STATISTICS s ON a, b FROM t", + "CREATE STATISTICS ON (a + b) FROM t", + "CREATE STATISTICS ON lower(a) FROM t", + "CREATE STATISTICS (ndistinct) ON a, b FROM t", + ] { + pg_and_generic().verified_stmt(sql); + } + + let error = pg_and_generic() + .parse_sql_statements("CREATE STATISTICS s ON a, b") + .expect_err("expected missing FROM clause"); + assert!(error.to_string().contains("Expected: FROM"), "{error}"); +}