Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support parsing optional nulls handling for unique constraint #1567

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
30 changes: 29 additions & 1 deletion src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,8 @@ pub enum TableConstraint {
columns: Vec<Ident>,
index_options: Vec<IndexOption>,
characteristics: Option<ConstraintCharacteristics>,
/// Optional Postgres nulls handling: `[ NULLS [ NOT ] DISTINCT ]`
nulls_distinct: NullsDistinctOption,
},
/// MySQL [definition][1] for `PRIMARY KEY` constraints statements:\
/// * `[CONSTRAINT [<name>]] PRIMARY KEY [index_name] [index_type] (<columns>) <index_options>`
Expand Down Expand Up @@ -775,10 +777,11 @@ impl fmt::Display for TableConstraint {
columns,
index_options,
characteristics,
nulls_distinct,
} => {
write!(
f,
"{}UNIQUE{index_type_display:>}{}{} ({})",
"{}UNIQUE{nulls_distinct}{index_type_display:>}{}{} ({})",
display_constraint_name(name),
display_option_spaced(index_name),
display_option(" USING ", "", index_type),
Expand Down Expand Up @@ -986,6 +989,31 @@ impl fmt::Display for IndexOption {
}
}

/// [Postgres] unique index nulls handling option: `[ NULLS [ NOT ] DISTINCT ]`
///
/// [Postgres]: https://www.postgresql.org/docs/17/sql-altertable.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 NullsDistinctOption {
/// Not specified
None,
/// NULLS DISTINCT
Distinct,
/// NULLS NOT DISTINCT
NotDistinct,
}

impl fmt::Display for NullsDistinctOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::None => Ok(()),
Self::Distinct => write!(f, " NULLS DISTINCT"),
Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
}
}
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
Expand Down
9 changes: 5 additions & 4 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ pub use self::ddl::{
ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnPolicy, ColumnPolicyProperty,
ConstraintCharacteristics, Deduplicate, DeferrableInitial, GeneratedAs,
GeneratedExpressionMode, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind,
IdentityPropertyKind, IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay, Owner,
Partition, ProcedureParam, ReferentialAction, TableConstraint, TagsColumnOption,
UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation, ViewColumnDef,
IdentityPropertyKind, IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay,
NullsDistinctOption, Owner, Partition, ProcedureParam, ReferentialAction, TableConstraint,
TagsColumnOption, UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation,
ViewColumnDef,
};
pub use self::dml::{CreateIndex, CreateTable, Delete, Insert};
pub use self::operator::{BinaryOperator, UnaryOperator};
Expand Down Expand Up @@ -885,7 +886,7 @@ pub enum Expr {
/// Example:
///
/// ```sql
/// SELECT (SELECT ',' + name FROM sys.objects FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)')
/// SELECT (SELECT ',' + name FROM sys.objects FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)')
/// SELECT CONVERT(XML,'<Book>abc</Book>').value('.','NVARCHAR(MAX)').value('.','NVARCHAR(MAX)')
/// ```
///
Expand Down
1 change: 1 addition & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,7 @@ impl Spanned for TableConstraint {
columns,
index_options: _,
characteristics,
nulls_distinct: _,
} => union_spans(
name.iter()
.map(|i| i.span)
Expand Down
17 changes: 17 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6728,6 +6728,8 @@ impl<'a> Parser<'a> {
.expected("`index_name` or `(column_name [, ...])`", self.peek_token());
}

let nulls_distinct = self.parse_optional_nulls_distinct()?;

// optional index name
let index_name = self.parse_optional_indent()?;
let index_type = self.parse_optional_using_then_index_type()?;
Expand All @@ -6743,6 +6745,7 @@ impl<'a> Parser<'a> {
columns,
index_options,
characteristics,
nulls_distinct,
}))
}
Token::Word(w) if w.keyword == Keyword::PRIMARY => {
Expand Down Expand Up @@ -6865,6 +6868,20 @@ impl<'a> Parser<'a> {
}
}

fn parse_optional_nulls_distinct(&mut self) -> Result<NullsDistinctOption, ParserError> {
Ok(if self.parse_keyword(Keyword::NULLS) {
let not = self.parse_keyword(Keyword::NOT);
self.expect_keyword(Keyword::DISTINCT)?;
if not {
NullsDistinctOption::NotDistinct
} else {
NullsDistinctOption::Distinct
}
} else {
NullsDistinctOption::None
})
}

pub fn maybe_parse_options(
&mut self,
keyword: Keyword,
Expand Down
1 change: 1 addition & 0 deletions tests/sqlparser_mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,7 @@ fn table_constraint_unique_primary_ctor(
columns,
index_options,
characteristics,
nulls_distinct: NullsDistinctOption::None,
},
None => TableConstraint::PrimaryKey {
name,
Expand Down
7 changes: 7 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,13 @@ fn parse_alter_table_constraints_rename() {
}
}

#[test]
fn parse_alter_table_constraints_unique_nulls_distinct() {
pg_and_generic().verified_stmt("ALTER TABLE t ADD CONSTRAINT b UNIQUE NULLS NOT DISTINCT (c)");
Copy link
Contributor

Choose a reason for hiding this comment

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

For one of the test cases can we include an assertion on the AST, like in this style? just to sanity check where in the statement the nulls option ends up in the tree

pg_and_generic().verified_stmt("ALTER TABLE t ADD CONSTRAINT b UNIQUE NULLS DISTINCT (c)");
pg_and_generic().verified_stmt("ALTER TABLE t ADD CONSTRAINT b UNIQUE (c)");
}

#[test]
fn parse_alter_table_disable() {
pg_and_generic().verified_stmt("ALTER TABLE tab DISABLE ROW LEVEL SECURITY");
Expand Down