Skip to content

Commit 8e4531f

Browse files
Merge branch 'main' into unify-check-constraint
2 parents f9d643c + c8531d4 commit 8e4531f

File tree

8 files changed

+170
-56
lines changed

8 files changed

+170
-56
lines changed

src/ast/ddl.rs

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use sqlparser_derive::{Visit, VisitMut};
3131
use crate::ast::value::escape_single_quote_string;
3232
use crate::ast::{
3333
display_comma_separated, display_separated,
34-
table_constraints::{CheckConstraint, TableConstraint},
34+
table_constraints::{CheckConstraint, ForeignKeyConstraint, TableConstraint},
3535
ArgMode, AttachedToken, CommentDef, ConditionalStatements, CreateFunctionBody,
3636
CreateFunctionUsing, CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr,
3737
FileFormat, FunctionBehavior, FunctionCalledOnNull, FunctionDesc, FunctionDeterminismSpecifier,
@@ -1560,20 +1560,14 @@ pub enum ColumnOption {
15601560
is_primary: bool,
15611561
characteristics: Option<ConstraintCharacteristics>,
15621562
},
1563-
/// A referential integrity constraint (`[FOREIGN KEY REFERENCES
1564-
/// <foreign_table> (<referred_columns>)
1563+
/// A referential integrity constraint (`REFERENCES <foreign_table> (<referred_columns>)
1564+
/// [ MATCH { FULL | PARTIAL | SIMPLE } ]
15651565
/// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
15661566
/// [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
1567-
/// }
1567+
/// }
15681568
/// [<constraint_characteristics>]
15691569
/// `).
1570-
ForeignKey {
1571-
foreign_table: ObjectName,
1572-
referred_columns: Vec<Ident>,
1573-
on_delete: Option<ReferentialAction>,
1574-
on_update: Option<ReferentialAction>,
1575-
characteristics: Option<ConstraintCharacteristics>,
1576-
},
1570+
ForeignKey(ForeignKeyConstraint),
15771571
/// `CHECK (<expr>)`
15781572
Check(CheckConstraint),
15791573
/// Dialect-specific options, such as:
@@ -1649,6 +1643,11 @@ impl From<CheckConstraint> for ColumnOption {
16491643
ColumnOption::Check(c)
16501644
}
16511645
}
1646+
impl From<ForeignKeyConstraint> for ColumnOption {
1647+
fn from(fk: ForeignKeyConstraint) -> Self {
1648+
ColumnOption::ForeignKey(fk)
1649+
}
1650+
}
16521651

16531652
impl fmt::Display for ColumnOption {
16541653
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -1676,24 +1675,25 @@ impl fmt::Display for ColumnOption {
16761675
}
16771676
Ok(())
16781677
}
1679-
ForeignKey {
1680-
foreign_table,
1681-
referred_columns,
1682-
on_delete,
1683-
on_update,
1684-
characteristics,
1685-
} => {
1686-
write!(f, "REFERENCES {foreign_table}")?;
1687-
if !referred_columns.is_empty() {
1688-
write!(f, " ({})", display_comma_separated(referred_columns))?;
1678+
ForeignKey(constraint) => {
1679+
write!(f, "REFERENCES {}", constraint.foreign_table)?;
1680+
if !constraint.referred_columns.is_empty() {
1681+
write!(
1682+
f,
1683+
" ({})",
1684+
display_comma_separated(&constraint.referred_columns)
1685+
)?;
16891686
}
1690-
if let Some(action) = on_delete {
1687+
if let Some(match_kind) = &constraint.match_kind {
1688+
write!(f, " {match_kind}")?;
1689+
}
1690+
if let Some(action) = &constraint.on_delete {
16911691
write!(f, " ON DELETE {action}")?;
16921692
}
1693-
if let Some(action) = on_update {
1693+
if let Some(action) = &constraint.on_update {
16941694
write!(f, " ON UPDATE {action}")?;
16951695
}
1696-
if let Some(characteristics) = characteristics {
1696+
if let Some(characteristics) = &constraint.characteristics {
16971697
write!(f, " {characteristics}")?;
16981698
}
16991699
Ok(())

src/ast/mod.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,31 @@ pub enum CastKind {
657657
DoubleColon,
658658
}
659659

660+
/// `MATCH` type for constraint references
661+
///
662+
/// See: <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES>
663+
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
664+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
665+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
666+
pub enum ConstraintReferenceMatchKind {
667+
/// `MATCH FULL`
668+
Full,
669+
/// `MATCH PARTIAL`
670+
Partial,
671+
/// `MATCH SIMPLE`
672+
Simple,
673+
}
674+
675+
impl fmt::Display for ConstraintReferenceMatchKind {
676+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
677+
match self {
678+
Self::Full => write!(f, "MATCH FULL"),
679+
Self::Partial => write!(f, "MATCH PARTIAL"),
680+
Self::Simple => write!(f, "MATCH SIMPLE"),
681+
}
682+
}
683+
}
684+
660685
/// `EXTRACT` syntax variants.
661686
///
662687
/// In Snowflake dialect, the `EXTRACT` expression can support either the `from` syntax

src/ast/spans.rs

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -741,20 +741,8 @@ impl Spanned for ColumnOption {
741741
ColumnOption::Ephemeral(expr) => expr.as_ref().map_or(Span::empty(), |e| e.span()),
742742
ColumnOption::Alias(expr) => expr.span(),
743743
ColumnOption::Unique { .. } => Span::empty(),
744-
ColumnOption::ForeignKey {
745-
foreign_table,
746-
referred_columns,
747-
on_delete,
748-
on_update,
749-
characteristics,
750-
} => union_spans(
751-
core::iter::once(foreign_table.span())
752-
.chain(referred_columns.iter().map(|i| i.span))
753-
.chain(on_delete.iter().map(|i| i.span()))
754-
.chain(on_update.iter().map(|i| i.span()))
755-
.chain(characteristics.iter().map(|i| i.span())),
756-
),
757744
ColumnOption::Check(constraint) => constraint.span(),
745+
ColumnOption::ForeignKey(constraint) => constraint.span(),
758746
ColumnOption::DialectSpecific(_) => Span::empty(),
759747
ColumnOption::CharacterSet(object_name) => object_name.span(),
760748
ColumnOption::Collation(object_name) => object_name.span(),

src/ast/table_constraints.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
//! SQL Abstract Syntax Tree (AST) types for table constraints
1919
2020
use crate::ast::{
21-
display_comma_separated, display_separated, ConstraintCharacteristics, Expr, Ident,
22-
IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, NullsDistinctOption, ObjectName,
23-
ReferentialAction,
21+
display_comma_separated, display_separated, ConstraintCharacteristics,
22+
ConstraintReferenceMatchKind, Expr, Ident, IndexColumn, IndexOption, IndexType,
23+
KeyOrIndexDisplay, NullsDistinctOption, ObjectName, ReferentialAction,
2424
};
2525
use crate::tokenizer::Span;
2626
use core::fmt;
@@ -189,7 +189,7 @@ impl crate::ast::Spanned for CheckConstraint {
189189
}
190190

191191
/// A referential integrity constraint (`[ CONSTRAINT <name> ] FOREIGN KEY (<columns>)
192-
/// REFERENCES <foreign_table> (<referred_columns>)
192+
/// REFERENCES <foreign_table> (<referred_columns>) [ MATCH { FULL | PARTIAL | SIMPLE } ]
193193
/// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
194194
/// [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
195195
/// }`).
@@ -206,6 +206,7 @@ pub struct ForeignKeyConstraint {
206206
pub referred_columns: Vec<Ident>,
207207
pub on_delete: Option<ReferentialAction>,
208208
pub on_update: Option<ReferentialAction>,
209+
pub match_kind: Option<ConstraintReferenceMatchKind>,
209210
pub characteristics: Option<ConstraintCharacteristics>,
210211
}
211212

@@ -223,6 +224,9 @@ impl fmt::Display for ForeignKeyConstraint {
223224
if !self.referred_columns.is_empty() {
224225
write!(f, "({})", display_comma_separated(&self.referred_columns))?;
225226
}
227+
if let Some(match_kind) = &self.match_kind {
228+
write!(f, " {match_kind}")?;
229+
}
226230
if let Some(action) = &self.on_delete {
227231
write!(f, " ON DELETE {action}")?;
228232
}

src/keywords.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -713,6 +713,7 @@ define_keywords!(
713713
PARAMETER,
714714
PARQUET,
715715
PART,
716+
PARTIAL,
716717
PARTITION,
717718
PARTITIONED,
718719
PARTITIONS,
@@ -885,6 +886,7 @@ define_keywords!(
885886
SHOW,
886887
SIGNED,
887888
SIMILAR,
889+
SIMPLE,
888890
SKIP,
889891
SLOW,
890892
SMALLINT,

src/parser/mod.rs

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7940,7 +7940,7 @@ impl<'a> Parser<'a> {
79407940
}
79417941

79427942
pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError> {
7943-
let name = self.parse_identifier()?;
7943+
let col_name = self.parse_identifier()?;
79447944
let data_type = if self.is_column_type_sqlite_unspecified() {
79457945
DataType::Unspecified
79467946
} else {
@@ -7965,7 +7965,7 @@ impl<'a> Parser<'a> {
79657965
};
79667966
}
79677967
Ok(ColumnDef {
7968-
name,
7968+
name: col_name,
79697969
data_type,
79707970
options,
79717971
})
@@ -8065,10 +8065,15 @@ impl<'a> Parser<'a> {
80658065
// PostgreSQL allows omitting the column list and
80668066
// uses the primary key column of the foreign table by default
80678067
let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
8068+
let mut match_kind = None;
80688069
let mut on_delete = None;
80698070
let mut on_update = None;
80708071
loop {
8071-
if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
8072+
if match_kind.is_none() && self.parse_keyword(Keyword::MATCH) {
8073+
match_kind = Some(self.parse_match_kind()?);
8074+
} else if on_delete.is_none()
8075+
&& self.parse_keywords(&[Keyword::ON, Keyword::DELETE])
8076+
{
80728077
on_delete = Some(self.parse_referential_action()?);
80738078
} else if on_update.is_none()
80748079
&& self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
@@ -8080,13 +8085,20 @@ impl<'a> Parser<'a> {
80808085
}
80818086
let characteristics = self.parse_constraint_characteristics()?;
80828087

8083-
Ok(Some(ColumnOption::ForeignKey {
8084-
foreign_table,
8085-
referred_columns,
8086-
on_delete,
8087-
on_update,
8088-
characteristics,
8089-
}))
8088+
Ok(Some(
8089+
ForeignKeyConstraint {
8090+
name: None, // Column-level constraints don't have names
8091+
index_name: None, // Not applicable for column-level constraints
8092+
columns: vec![], // Not applicable for column-level constraints
8093+
foreign_table,
8094+
referred_columns,
8095+
on_delete,
8096+
on_update,
8097+
match_kind,
8098+
characteristics,
8099+
}
8100+
.into(),
8101+
))
80908102
} else if self.parse_keyword(Keyword::CHECK) {
80918103
self.expect_token(&Token::LParen)?;
80928104
// since `CHECK` requires parentheses, we can parse the inner expression in ParserState::Normal
@@ -8367,6 +8379,18 @@ impl<'a> Parser<'a> {
83678379
}
83688380
}
83698381

8382+
pub fn parse_match_kind(&mut self) -> Result<ConstraintReferenceMatchKind, ParserError> {
8383+
if self.parse_keyword(Keyword::FULL) {
8384+
Ok(ConstraintReferenceMatchKind::Full)
8385+
} else if self.parse_keyword(Keyword::PARTIAL) {
8386+
Ok(ConstraintReferenceMatchKind::Partial)
8387+
} else if self.parse_keyword(Keyword::SIMPLE) {
8388+
Ok(ConstraintReferenceMatchKind::Simple)
8389+
} else {
8390+
self.expected("one of FULL, PARTIAL or SIMPLE", self.peek_token())
8391+
}
8392+
}
8393+
83708394
pub fn parse_constraint_characteristics(
83718395
&mut self,
83728396
) -> Result<Option<ConstraintCharacteristics>, ParserError> {
@@ -8477,10 +8501,15 @@ impl<'a> Parser<'a> {
84778501
self.expect_keyword_is(Keyword::REFERENCES)?;
84788502
let foreign_table = self.parse_object_name(false)?;
84798503
let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
8504+
let mut match_kind = None;
84808505
let mut on_delete = None;
84818506
let mut on_update = None;
84828507
loop {
8483-
if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
8508+
if match_kind.is_none() && self.parse_keyword(Keyword::MATCH) {
8509+
match_kind = Some(self.parse_match_kind()?);
8510+
} else if on_delete.is_none()
8511+
&& self.parse_keywords(&[Keyword::ON, Keyword::DELETE])
8512+
{
84848513
on_delete = Some(self.parse_referential_action()?);
84858514
} else if on_update.is_none()
84868515
&& self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
@@ -8502,6 +8531,7 @@ impl<'a> Parser<'a> {
85028531
referred_columns,
85038532
on_delete,
85048533
on_update,
8534+
match_kind,
85058535
characteristics,
85068536
}
85078537
.into(),

0 commit comments

Comments
 (0)