diff --git a/fuzz/fuzz_seeds/postgres_referential_action_set_columns.sql b/fuzz/fuzz_seeds/postgres_referential_action_set_columns.sql new file mode 100644 index 0000000000..657c4f5cab --- /dev/null +++ b/fuzz/fuzz_seeds/postgres_referential_action_set_columns.sql @@ -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)) \ No newline at end of file diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index a4a21bff05..b8775b04f6 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -2514,10 +2514,12 @@ impl fmt::Display for ConstraintCharacteristics { } /// ` = -/// { 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 { @@ -2525,23 +2527,29 @@ pub enum ReferentialAction { 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), /// `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), } 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(()) } } diff --git a/src/ast/spans.rs b/src/ast/spans.rs index 2ce471e95b..78d511eb13 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -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(), + } } } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index a4580954a1..0ddf666149 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -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 { 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", diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 38a4a159d2..87d07700a0 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -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, } @@ -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, } @@ -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), @@ -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), @@ -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}"); diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index d00aac9a9f..fd1edaf8a8 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -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()) ); @@ -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: )" + ); +}