Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
52 changes: 27 additions & 25 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ use sqlparser_derive::{Visit, VisitMut};

use crate::ast::value::escape_single_quote_string;
use crate::ast::{
display_comma_separated, display_separated, table_constraints::TableConstraint, ArgMode,
CommentDef, ConditionalStatements, CreateFunctionBody, CreateFunctionUsing,
display_comma_separated, display_separated,
table_constraints::{ForeignKeyConstraint, TableConstraint},
ArgMode, CommentDef, ConditionalStatements, CreateFunctionBody, CreateFunctionUsing,
CreateTableLikeKind, CreateTableOptions, DataType, Expr, FileFormat, FunctionBehavior,
FunctionCalledOnNull, FunctionDeterminismSpecifier, FunctionParallel, HiveDistributionStyle,
HiveFormat, HiveIOFormat, HiveRowFormat, Ident, InitializeKind, MySQLColumnPosition,
Expand Down Expand Up @@ -1558,20 +1559,14 @@ pub enum ColumnOption {
is_primary: bool,
characteristics: Option<ConstraintCharacteristics>,
},
/// A referential integrity constraint (`[FOREIGN KEY REFERENCES
/// <foreign_table> (<referred_columns>)
/// A referential integrity constraint (`REFERENCES <foreign_table> (<referred_columns>)
/// [ MATCH { FULL | PARTIAL | SIMPLE } ]
/// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
/// [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
/// }
/// }
/// [<constraint_characteristics>]
/// `).
ForeignKey {
foreign_table: ObjectName,
referred_columns: Vec<Ident>,
on_delete: Option<ReferentialAction>,
on_update: Option<ReferentialAction>,
characteristics: Option<ConstraintCharacteristics>,
},
ForeignKey(ForeignKeyConstraint),
/// `CHECK (<expr>)`
Check(Expr),
/// Dialect-specific options, such as:
Expand Down Expand Up @@ -1642,6 +1637,12 @@ pub enum ColumnOption {
Invisible,
}

impl From<ForeignKeyConstraint> for ColumnOption {
fn from(fk: ForeignKeyConstraint) -> Self {
ColumnOption::ForeignKey(fk)
}
}

impl fmt::Display for ColumnOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use ColumnOption::*;
Expand All @@ -1668,24 +1669,25 @@ impl fmt::Display for ColumnOption {
}
Ok(())
}
ForeignKey {
foreign_table,
referred_columns,
on_delete,
on_update,
characteristics,
} => {
write!(f, "REFERENCES {foreign_table}")?;
if !referred_columns.is_empty() {
write!(f, " ({})", display_comma_separated(referred_columns))?;
ForeignKey(constraint) => {
write!(f, "REFERENCES {}", constraint.foreign_table)?;
if !constraint.referred_columns.is_empty() {
write!(
f,
" ({})",
display_comma_separated(&constraint.referred_columns)
)?;
}
if let Some(action) = on_delete {
if let Some(match_kind) = &constraint.match_kind {
write!(f, " {match_kind}")?;
}
if let Some(action) = &constraint.on_delete {
write!(f, " ON DELETE {action}")?;
}
if let Some(action) = on_update {
if let Some(action) = &constraint.on_update {
write!(f, " ON UPDATE {action}")?;
}
if let Some(characteristics) = characteristics {
if let Some(characteristics) = &constraint.characteristics {
write!(f, " {characteristics}")?;
}
Ok(())
Expand Down
34 changes: 34 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,40 @@ pub enum CastKind {
DoubleColon,
}

/// The MATCH option for foreign key constraints.
///
/// Specifies how to match composite foreign keys against the referenced table.
/// A value inserted into the referencing column(s) is matched against the values
/// of the referenced table and referenced columns using the given match type.
///
/// See: <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES>
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum MatchKind {
/// `MATCH FULL` - Will not allow one column of a multicolumn foreign key to be null
/// unless all foreign key columns are null; if they are all null, the row is not
/// required to have a match in the referenced table.
Full,
/// `MATCH PARTIAL` - Not yet implemented by most databases (part of SQL standard).
/// Would allow partial matches in multicolumn foreign keys.
Partial,
/// `MATCH SIMPLE` - The default behavior. Allows any of the foreign key columns
/// to be null; if any of them are null, the row is not required to have a match
/// in the referenced table.
Simple,
}

impl fmt::Display for MatchKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MatchKind::Full => write!(f, "MATCH FULL"),
MatchKind::Partial => write!(f, "MATCH PARTIAL"),
MatchKind::Simple => write!(f, "MATCH SIMPLE"),
}
}
}

/// `EXTRACT` syntax variants.
///
/// In Snowflake dialect, the `EXTRACT` expression can support either the `from` syntax
Expand Down
14 changes: 1 addition & 13 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -822,19 +822,7 @@ impl Spanned for ColumnOption {
ColumnOption::Ephemeral(expr) => expr.as_ref().map_or(Span::empty(), |e| e.span()),
ColumnOption::Alias(expr) => expr.span(),
ColumnOption::Unique { .. } => Span::empty(),
ColumnOption::ForeignKey {
foreign_table,
referred_columns,
on_delete,
on_update,
characteristics,
} => union_spans(
core::iter::once(foreign_table.span())
.chain(referred_columns.iter().map(|i| i.span))
.chain(on_delete.iter().map(|i| i.span()))
.chain(on_update.iter().map(|i| i.span()))
.chain(characteristics.iter().map(|i| i.span())),
),
ColumnOption::ForeignKey(constraint) => constraint.span(),
ColumnOption::Check(expr) => expr.span(),
ColumnOption::DialectSpecific(_) => Span::empty(),
ColumnOption::CharacterSet(object_name) => object_name.span(),
Expand Down
10 changes: 7 additions & 3 deletions src/ast/table_constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

use crate::ast::{
display_comma_separated, display_separated, ConstraintCharacteristics, Expr, Ident,
IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, NullsDistinctOption, ObjectName,
ReferentialAction,
IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, MatchKind, NullsDistinctOption,
ObjectName, ReferentialAction,
};
use crate::tokenizer::Span;
use core::fmt;
Expand Down Expand Up @@ -189,7 +189,7 @@ impl crate::ast::Spanned for CheckConstraint {
}

/// A referential integrity constraint (`[ CONSTRAINT <name> ] FOREIGN KEY (<columns>)
/// REFERENCES <foreign_table> (<referred_columns>)
/// REFERENCES <foreign_table> (<referred_columns>) [ MATCH { FULL | PARTIAL | SIMPLE } ]
/// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
/// [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
/// }`).
Expand All @@ -206,6 +206,7 @@ pub struct ForeignKeyConstraint {
pub referred_columns: Vec<Ident>,
pub on_delete: Option<ReferentialAction>,
pub on_update: Option<ReferentialAction>,
pub match_kind: Option<MatchKind>,
pub characteristics: Option<ConstraintCharacteristics>,
}

Expand All @@ -223,6 +224,9 @@ impl fmt::Display for ForeignKeyConstraint {
if !self.referred_columns.is_empty() {
write!(f, "({})", display_comma_separated(&self.referred_columns))?;
}
if let Some(match_kind) = &self.match_kind {
write!(f, " {match_kind}")?;
}
if let Some(action) = &self.on_delete {
write!(f, " ON DELETE {action}")?;
}
Expand Down
2 changes: 2 additions & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,7 @@ define_keywords!(
PARAMETER,
PARQUET,
PART,
PARTIAL,
PARTITION,
PARTITIONED,
PARTITIONS,
Expand Down Expand Up @@ -885,6 +886,7 @@ define_keywords!(
SHOW,
SIGNED,
SIMILAR,
SIMPLE,
SKIP,
SLOW,
SMALLINT,
Expand Down
Loading