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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TABLE c (a INT, b INT, FOREIGN KEY (a, b) REFERENCES r ON DELETE SET NULL (b) ON UPDATE SET DEFAULT (a, b))
34 changes: 21 additions & 13 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2514,34 +2514,42 @@ impl fmt::Display for ConstraintCharacteristics {
}

/// `<referential_action> =
/// { RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }`
/// { RESTRICT | CASCADE | SET NULL [ ( column [, ...] ) ] | NO ACTION | SET DEFAULT [ ( column [, ...] ) ] }`
///
/// Used in foreign key constraints in `ON UPDATE` and `ON DELETE` options.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
///
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum ReferentialAction {
/// `RESTRICT` - disallow action if it would break referential integrity.
Restrict,
/// `CASCADE` - propagate the action to referencing rows.
Cascade,
/// `SET NULL` - set referencing columns to NULL.
SetNull,
/// `SET NULL [(columns)]` - set the listed referencing columns, or all of them, to NULL.
SetNull(Vec<Ident>),
/// `NO ACTION` - no action at the time; may be deferred.
NoAction,
/// `SET DEFAULT` - set referencing columns to their default values.
SetDefault,
/// `SET DEFAULT [(columns)]` - set the listed referencing columns, or all of them, to their
/// default values.
SetDefault(Vec<Ident>),
}

impl fmt::Display for ReferentialAction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
ReferentialAction::Restrict => "RESTRICT",
ReferentialAction::Cascade => "CASCADE",
ReferentialAction::SetNull => "SET NULL",
ReferentialAction::NoAction => "NO ACTION",
ReferentialAction::SetDefault => "SET DEFAULT",
})
let (action, columns) = match self {
ReferentialAction::Restrict => return f.write_str("RESTRICT"),
ReferentialAction::Cascade => return f.write_str("CASCADE"),
ReferentialAction::NoAction => return f.write_str("NO ACTION"),
ReferentialAction::SetNull(columns) => ("SET NULL", columns),
ReferentialAction::SetDefault(columns) => ("SET DEFAULT", columns),
};
f.write_str(action)?;
if !columns.is_empty() {
write!(f, " ({})", display_comma_separated(columns))?;
}
Ok(())
}
}

Expand Down
13 changes: 11 additions & 2 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -922,10 +922,19 @@ impl Spanned for ColumnOption {
}
}

/// # missing span
/// # partial span
///
/// Covers only the column list of `SET NULL` and `SET DEFAULT`.
impl Spanned for ReferentialAction {
fn span(&self) -> Span {
Span::empty()
match self {
ReferentialAction::SetNull(columns) | ReferentialAction::SetDefault(columns) => {
union_spans(columns.iter().map(|column| column.span))
}
ReferentialAction::Restrict
| ReferentialAction::Cascade
| ReferentialAction::NoAction => Span::empty(),
}
}
}

Expand Down
11 changes: 8 additions & 3 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10753,18 +10753,23 @@ impl<'a> Parser<'a> {

/// Parse a referential action used in foreign key clauses.
///
/// Recognized forms: `RESTRICT`, `CASCADE`, `SET NULL`, `NO ACTION`, `SET DEFAULT`.
/// Recognized forms: `RESTRICT`, `CASCADE`, `SET NULL [(columns)]`, `NO ACTION`,
/// `SET DEFAULT [(columns)]`.
pub fn parse_referential_action(&mut self) -> Result<ReferentialAction, ParserError> {
if self.parse_keyword(Keyword::RESTRICT) {
Ok(ReferentialAction::Restrict)
} else if self.parse_keyword(Keyword::CASCADE) {
Ok(ReferentialAction::Cascade)
} else if self.parse_keywords(&[Keyword::SET, Keyword::NULL]) {
Ok(ReferentialAction::SetNull)
Ok(ReferentialAction::SetNull(
self.parse_parenthesized_column_list(Optional, false)?,
))
} else if self.parse_keywords(&[Keyword::NO, Keyword::ACTION]) {
Ok(ReferentialAction::NoAction)
} else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
Ok(ReferentialAction::SetDefault)
Ok(ReferentialAction::SetDefault(
self.parse_parenthesized_column_list(Optional, false)?,
))
} else {
self.expected_ref(
"one of RESTRICT, CASCADE, SET NULL, NO ACTION or SET DEFAULT",
Expand Down
14 changes: 7 additions & 7 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4583,7 +4583,7 @@ fn parse_create_table() {
foreign_table: ObjectName::from(vec!["othertable4".into()]),
referred_columns: vec!["lat".into()],
on_delete: Some(ReferentialAction::Cascade),
on_update: Some(ReferentialAction::SetDefault),
on_update: Some(ReferentialAction::SetDefault(vec![])),
match_kind: None,
characteristics: None,
}
Expand All @@ -4595,7 +4595,7 @@ fn parse_create_table() {
foreign_table: ObjectName::from(vec!["othertable4".into()]),
referred_columns: vec!["longitude".into()],
on_delete: None,
on_update: Some(ReferentialAction::SetNull),
on_update: Some(ReferentialAction::SetNull(vec![])),
match_kind: None,
characteristics: None,
}
Expand Down Expand Up @@ -4726,7 +4726,7 @@ fn parse_create_table_with_constraint_characteristics() {
foreign_table: ObjectName::from(vec!["othertable4".into()]),
referred_columns: vec!["lat".into()],
on_delete: Some(ReferentialAction::Cascade),
on_update: Some(ReferentialAction::SetDefault),
on_update: Some(ReferentialAction::SetDefault(vec![])),
match_kind: None,
characteristics: Some(ConstraintCharacteristics {
deferrable: Some(false),
Expand All @@ -4742,7 +4742,7 @@ fn parse_create_table_with_constraint_characteristics() {
foreign_table: ObjectName::from(vec!["othertable4".into()]),
referred_columns: vec!["longitude".into()],
on_delete: None,
on_update: Some(ReferentialAction::SetNull),
on_update: Some(ReferentialAction::SetNull(vec![])),
match_kind: None,
characteristics: Some(ConstraintCharacteristics {
deferrable: Some(false),
Expand Down Expand Up @@ -22555,10 +22555,10 @@ fn parse_reference_clauses_leave_duplicates_unconsumed() {
assert_eq!(
(
constraint.match_kind,
constraint.on_delete,
constraint.on_update
constraint.on_delete.as_ref(),
constraint.on_update.as_ref()
),
(match_kind, on_delete, on_update),
(match_kind, on_delete.as_ref(), on_update.as_ref()),
"{sql}"
);
assert!(parser.peek_keyword(keyword), "{sql}");
Expand Down
71 changes: 71 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7555,6 +7555,7 @@ fn parse_drop_trigger() {
"DROP TRIGGER{} check_update ON table_name{}",
if if_exists { " IF EXISTS" } else { "" },
option
.as_ref()
.map(|o| format!(" {o}"))
.unwrap_or_else(|| "".to_string())
);
Expand Down Expand Up @@ -14321,3 +14322,73 @@ fn display_create_index_on_only_propagates_formatter_errors() {
assert_eq!(write!(writer, "{stmt}"), Err(fmt::Error), "{rejected:?}");
}
}

#[test]
fn parse_referential_action_set_column_list() {
let foreign_key_actions = |statement: Statement| match statement {
Statement::CreateTable(CreateTable { constraints, .. }) => {
match <[_; 1]>::try_from(constraints) {
Ok([TableConstraint::ForeignKey(fk)]) => (fk.on_delete, fk.on_update),
_ => unreachable!(),
}
}
_ => unreachable!(),
};
let verified_actions = |sql: &str| foreign_key_actions(pg_and_generic().verified_stmt(sql));

let sql =
"CREATE TABLE c (a INT, b INT, FOREIGN KEY (a, b) REFERENCES r ON DELETE SET NULL (b))";
assert_eq!(
verified_actions(sql),
(Some(ReferentialAction::SetNull(vec!["b".into()])), None)
);
let (on_delete, _) = foreign_key_actions(
Parser::parse_sql(&PostgreSqlDialect {}, sql)
.unwrap()
.remove(0),
);
assert_eq!(
on_delete.unwrap().span(),
Span::new(Location::new(1, 83), Location::new(1, 84))
);
assert_eq!(
verified_actions(
"CREATE TABLE c (a INT, b INT, FOREIGN KEY (a, b) REFERENCES r ON DELETE SET DEFAULT (a, b))"
),
(
Some(ReferentialAction::SetDefault(vec!["a".into(), "b".into()])),
None
)
);
assert_eq!(
verified_actions(
"CREATE TABLE c (a INT, b INT, FOREIGN KEY (a, b) REFERENCES r ON DELETE SET NULL ON UPDATE SET DEFAULT)"
),
(
Some(ReferentialAction::SetNull(vec![])),
Some(ReferentialAction::SetDefault(vec![]))
)
);
assert_eq!(
verified_actions(
"CREATE TABLE c (a INT, b INT, FOREIGN KEY (a, b) REFERENCES r ON UPDATE SET NULL (b))"
),
(None, Some(ReferentialAction::SetNull(vec!["b".into()])))
);

pg_and_generic()
.verified_stmt("CREATE TABLE c (a INT, b INT REFERENCES r (b) ON DELETE SET NULL (b))");
pg_and_generic().verified_stmt(
"ALTER TABLE c ADD FOREIGN KEY (a, b) REFERENCES r ON DELETE SET DEFAULT (a)",
);

assert_eq!(
pg_and_generic()
.parse_sql_statements(
"CREATE TABLE c (a INT, FOREIGN KEY (a) REFERENCES r ON DELETE SET NULL ())"
)
.unwrap_err()
.to_string(),
"sql parser error: Expected: identifier, found: )"
);
}
Loading