From a78718b9340e9840a470300932af178ce57c0f7d Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Thu, 25 May 2017 10:17:11 -0400 Subject: Raise if ForeignKeyConstraint created with different numbers of local and remote columns. An :class:`.ArgumentError` is now raised if a :class:`.ForeignKeyConstraint` object is created with a mismatched number of "local" and "remote" columns, which otherwise causes the internal state of the constraint to be incorrect. Note that this also impacts the condition where a dialect's reflection process produces a mismatched set of columns for a foreign key constraint. Downstream DB2 dialect has been reported as potentially causing this scenario. Change-Id: Id51c34a6c43749bb582639f9c1dc28723482f0e5 Fixes: #3949 References: #3998 --- lib/sqlalchemy/sql/schema.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'lib/sqlalchemy/sql') diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py index a9aee5883..4eb095196 100644 --- a/lib/sqlalchemy/sql/schema.py +++ b/lib/sqlalchemy/sql/schema.py @@ -2883,6 +2883,22 @@ class ForeignKeyConstraint(ColumnCollectionConstraint): self.use_alter = use_alter self.match = match + if len(set(columns)) != len(refcolumns): + if len(set(columns)) != len(columns): + # e.g. FOREIGN KEY (a, a) REFERENCES r (b, c) + raise exc.ArgumentError( + "ForeignKeyConstraint with duplicate source column " + "references are not supported." + ) + else: + # e.g. FOREIGN KEY (a) REFERENCES r (b, c) + # paraphrasing https://www.postgresql.org/docs/9.2/static/\ + # ddl-constraints.html + raise exc.ArgumentError( + "ForeignKeyConstraint number " + "of constrained columns must match the number of " + "referenced columns.") + # standalone ForeignKeyConstraint - create # associated ForeignKey objects which will be applied to hosted # Column objects (in col.foreign_keys), either now or when attached -- cgit v1.2.1