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
38 changes: 38 additions & 0 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<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>,
/// 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))]
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
50 changes: 50 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 {
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 @@ -7552,6 +7562,46 @@ 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 !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<CreateDomain, ParserError> {
let name = self.parse_object_name(false)?;
Expand Down
38 changes: 38 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
Loading