From 86556610144f3e1ea227c9ae63ef89ee4f63de16 Mon Sep 17 00:00:00 2001 From: Dan Bradley Date: Thu, 21 Apr 2016 09:49:11 +0100 Subject: [PATCH 1/2] Test to show a nasty little bug with foreign keys with same name where CASCADE is picked up by non-cascading FKs if another FK with same name in different schema is CASCADE --- test/DatabaseTester.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/DatabaseTester.cs b/test/DatabaseTester.cs index 6165d99c..d3aa9eb5 100644 --- a/test/DatabaseTester.cs +++ b/test/DatabaseTester.cs @@ -286,7 +286,7 @@ CONSTRAINT [PK_1a] PRIMARY KEY (a) CREATE TABLE [dbo].[t1b] ( a INT NOT NULL, - CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [dbo].[t1a] ([a]) + CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [dbo].[t1a] ([a]) ON UPDATE CASCADE ) CREATE TABLE [s2].[t2a] @@ -298,7 +298,7 @@ CONSTRAINT [PK_2a] PRIMARY KEY (a) CREATE TABLE [s2].[t2b] ( a INT NOT NULL, - CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [s2].[t2a] ([a]) + CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [s2].[t2a] ([a]) ON DELETE CASCADE ) "; @@ -321,6 +321,11 @@ CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [s2].[t2a] ([a]) Assert.AreEqual(db.ForeignKeys[0].Name, db.ForeignKeys[1].Name); Assert.AreNotEqual(db.ForeignKeys[0].Table.Owner, db.ForeignKeys[1].Table.Owner); + Assert.AreEqual("CASCADE", db.FindForeignKey("FKName", "dbo").OnUpdate); + Assert.AreEqual("NO ACTION", db.FindForeignKey("FKName", "s2").OnUpdate); + + Assert.AreEqual("NO ACTION", db.FindForeignKey("FKName", "dbo").OnDelete); + Assert.AreEqual("CASCADE", db.FindForeignKey("FKName", "s2").OnDelete); } public void TestScriptViewInsteadOfTrigger() { From 524690100e7dfd67f0ce12784d72563a450e5dcd Mon Sep 17 00:00:00 2001 From: Dan Bradley Date: Thu, 21 Apr 2016 09:52:51 +0100 Subject: [PATCH 2/2] Fix for foreign keys with same name to ensure that onupdate and ondelete are correct --- model/Database.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/model/Database.cs b/model/Database.cs index a991bc39..5d76df79 100644 --- a/model/Database.cs +++ b/model/Database.cs @@ -399,7 +399,7 @@ from INFORMATION_SCHEMA.TABLE_CONSTRAINTS DELETE_RULE, fk.is_disabled from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc - inner join sys.foreign_keys fk on rc.CONSTRAINT_NAME = fk.name"; + inner join sys.foreign_keys fk on rc.CONSTRAINT_NAME = fk.name and rc.CONSTRAINT_SCHEMA = OBJECT_SCHEMA_NAME(fk.parent_object_id)"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey((string) dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]);