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
2 changes: 2 additions & 0 deletions fuzz/fuzz_seeds/postgres_create_statistics.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CREATE STATISTICS IF NOT EXISTS public.s (mcv, dependencies) ON a, (b + 1) FROM public.t;
CREATE STATISTICS (ndistinct) ON lower(a) FROM t
44 changes: 41 additions & 3 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ use crate::ast::{
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,
StorageLifecyclePolicy, StorageSerializationPolicy, TableVersion, TableWithJoins, 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 @@ -3966,6 +3966,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<ObjectName>,
/// Whether an existing statistics object should be skipped.
pub if_not_exists: bool,
/// Requested kinds, such as `ndistinct` or `mcv`.
pub kinds: Vec<Ident>,
/// Expressions on which to collect statistics.
pub expressions: Vec<Expr>,
/// Relations on which to collect statistics.
pub from: Vec<TableWithJoins>,
}

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),
display_comma_separated(&self.from)
)
}
}

/// The return type of a `CREATE FUNCTION` statement.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down
32 changes: 18 additions & 14 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -4889,6 +4890,8 @@ pub enum Statement {
},
/// A `CREATE DOMAIN` statement.
CreateDomain(CreateDomain),
/// PostgreSQL extended statistics definition.
CreateStatistics(CreateStatistics),
/// ```sql
/// CREATE TYPE <name>
/// ```
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/postgresql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
64 changes: 64 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please open an issue / if you have time also a PR to try and refactor these has_modifier checks into a single standardized error? I see it repeats several times.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see.There were already three has_modifier guards; this PR just adds a fourth. I'll open a tracking issue to consolidate them into one helper with a single standardized error, and send the refactor as a separate PR after this PR lands.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But the guard is still opt-in: CREATE TEMP POLICY/DOMAIN/RULE parse and lose TEMP on Display. Should the tracking issue cover that structural fix too, or just the helper?

@lei-jia-xing lei-jia-xing Nov 25, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dug into the has_modifier guard a bit more. It's a single bool checked only in four branches (STATISTICS, USER MAPPING, FOREIGN TABLE, FOREIGN DATA WRAPPER). Other branches whose AST cannot store modifiers don't check it, and silently drop them

@lei-jia-xing lei-jia-xing Nov 25, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for a such illegal test.sql

CREATE TEMP POLICY p ON t USING (true);

run with

cargo run --quiet --example cli -- ./test.sql --postgres

Round-trip:
'CREATE POLICY p ON t USING (true)'
It parses and remove the temp. But it can't be parsed

https://www.postgresql.org/docs/17/sql-createpolicy.html

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @LucaCappelletti94, I've opened a follow-up issue to track this.

Before opening a PR, could you please let me know if the CreateModifiers struct approach (consuming valid modifiers per target and rejecting any unconsumed ones via ensure_empty()) aligns with what you have in mind?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes a struct approach is most likely the cleanest refactoring.

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) {
Expand Down Expand Up @@ -7556,6 +7566,60 @@ impl<'a> Parser<'a> {
Ok(owner)
}

fn parse_create_statistics(&mut self) -> Result<Statement, ParserError> {
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let name = if self.peek_keyword(Keyword::ON) || self.peek_token_ref().token == Token::LParen
{
if if_not_exists {
return self.expected_ref("identifier", self.peek_token_ref());
}
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(_)
| Expr::Cast {
kind: CastKind::Cast,
..
}
| Expr::Extract { .. }
| Expr::Substring { .. }
| Expr::Trim { .. }
| Expr::Position { .. }
| Expr::Overlay { .. }
| Expr::Ceil { .. }
| Expr::Floor { .. } => 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 from = self.parse_comma_separated(Parser::parse_table_and_joins)?;
Ok(Statement::CreateStatistics(CreateStatistics {
name,
if_not_exists,
kinds,
expressions,
from,
}))
}

/// Parses a [Statement::CreateDomain] statement.
fn parse_create_domain(&mut self) -> Result<CreateDomain, ParserError> {
let name = self.parse_object_name(false)?;
Expand Down
115 changes: 115 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14597,3 +14597,118 @@ fn parse_alter_column_set_storage() {
);
}
}

#[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",
);
assert_eq!(statement.span(), Span::empty());
assert_display_propagates_write_errors(
&statement,
&["CREATE STATISTICS", " IF NOT EXISTS", "s", " (", " ON "],
);
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.from[0].relation.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",
r#"CREATE STATISTICS IF NOT EXISTS "on" ON a FROM t"#,
"CREATE STATISTICS ON (a + b) FROM t",
"CREATE STATISTICS ON lower(a) FROM t",
"CREATE STATISTICS (ndistinct) ON a, b FROM t",
"CREATE STATISTICS s ON CAST(a AS INT), EXTRACT(YEAR FROM b), SUBSTRING(c FROM 1 FOR 2), TRIM(d), POSITION('x' IN e), OVERLAY(f PLACING 'x' FROM 1), CEIL(g), FLOOR(h) FROM t",
"CREATE STATISTICS s ON a, b FROM t alias",
"CREATE STATISTICS s ON a, b FROM t AS alias",
"CREATE STATISTICS s ON a, b FROM t1, t2",
"CREATE STATISTICS s ON a, b FROM t1 JOIN t2 ON t1.id = t2.id",
"CREATE STATISTICS s ON a, b FROM (SELECT 1) AS sub",
"CREATE STATISTICS s ON a, b FROM generate_series(1, 10) AS s",
] {
pg_and_generic().verified_stmt(sql);
}

for sql in [
"CREATE STATISTICS s ON a, b FROM ONLY t",
"CREATE STATISTICS s ON a, b FROM t *",
] {
pg().verified_stmt(sql);
}

for (invalid_sql, expected_error) in [
("CREATE STATISTICS s ON a, b", "Expected: FROM, found: EOF"),
(
"CREATE STATISTICS s ON a + 1 FROM t",
"Expected a column, function call, or parenthesized expression",
),
(
"CREATE STATISTICS s ON a::INT FROM t",
"Expected a column, function call, or parenthesized expression",
),
(
"CREATE STATISTICS s ON row_number() OVER () FROM t",
"Expected a column, function call, or parenthesized expression",
),
(
"CREATE STATISTICS IF NOT EXISTS ON a FROM t",
"Expected: identifier, found: ON",
),
(
"CREATE STATISTICS IF NOT EXISTS (ndistinct) ON a FROM t",
"Expected: identifier, found: (",
),
(
"CREATE STATISTICS 123 ON a FROM t",
"Expected: identifier, found: 123",
),
(
"CREATE STATISTICS s () ON a FROM t",
"Expected: identifier, found: )",
),
("CREATE STATISTICS s a FROM t", "Expected: ON, found: a"),
(
"CREATE STATISTICS s ON ) FROM t",
"Expected: an expression, found: )",
),
(
"CREATE STATISTICS s ON a FROM",
"Expected: identifier, found: EOF",
),
(
"CREATE TEMP STATISTICS s ON a FROM t",
"CREATE STATISTICS does not accept this modifier",
),
] {
assert_eq!(
pg_and_generic()
.parse_sql_statements(invalid_sql)
.unwrap_err(),
ParserError::ParserError(expected_error.to_string()),
"{invalid_sql}"
);
}

assert_eq!(
all_dialects_where(|d| !d.supports_create_statistics())
.parse_sql_statements("CREATE STATISTICS s ON a FROM t")
.unwrap_err(),
ParserError::ParserError(
"Expected: an object type after CREATE, found: STATISTICS".to_string()
)
);
}
Loading