From 327db8e3ffd9ba6347eabf1ca9871bedc7ce7774 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sun, 17 Mar 2024 14:41:21 +0100 Subject: [PATCH] Check foreign key constraint on column definition --- src/lexer/sql/test.rs | 8 ++++++++ src/parser/ast/mod.rs | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/lexer/sql/test.rs b/src/lexer/sql/test.rs index 28d0228..d5e7893 100644 --- a/src/lexer/sql/test.rs +++ b/src/lexer/sql/test.rs @@ -216,6 +216,14 @@ fn create_strict_table_unknown_datatype() { ); } +#[test] +fn foreign_key_on_column() { + expect_parser_err_msg( + b"CREATE TABLE t(a REFERENCES o(a,b))", + "foreign key on a should reference only one column of table o", + ); +} + #[test] fn create_strict_table_generated_column() { parse_cmd( diff --git a/src/parser/ast/mod.rs b/src/parser/ast/mod.rs index b345254..f1ba448 100644 --- a/src/parser/ast/mod.rs +++ b/src/parser/ast/mod.rs @@ -1148,6 +1148,24 @@ impl ColumnDefinition { col_type.name = new_type.join(" "); } } + for constraint in &cd.constraints { + if let ColumnConstraint::ForeignKey { + clause: + ForeignKeyClause { + tbl_name, columns, .. + }, + .. + } = &constraint.constraint + { + if columns.as_ref().map_or(0, |v| v.len()) != 1 { + return Err(custom_err!( + "foreign key on {} should reference only one column of table {}", + col_name, + tbl_name + )); + } + } + } columns.insert(col_name, cd); Ok(()) }