]> git.ipfire.org Git - thirdparty/sqlalchemy/alembic.git/commitdiff
- [bug] Repaired create_foreign_key() for
authorMike Bayer <mike_mp@zzzcomputing.com>
Sat, 4 Aug 2012 11:18:01 +0000 (07:18 -0400)
committerMike Bayer <mike_mp@zzzcomputing.com>
Sat, 4 Aug 2012 11:18:01 +0000 (07:18 -0400)
  self-referential foreign keys, which weren't working
  at all.

CHANGES
alembic/operations.py
tests/test_op.py

diff --git a/CHANGES b/CHANGES
index ef50e63d80bf5ecdf18b6057e8edc97f42e2635d..4fe2e7ddff418d1ed8ce36003e4ee225e2143c2b 100644 (file)
--- a/CHANGES
+++ b/CHANGES
   config option is being used but SQL access isn't
   desired.
 
+- [bug] Repaired create_foreign_key() for
+  self-referential foreign keys, which weren't working
+  at all.
+
 - [bug] 'alembic' command reports an informative
   error message when the configuration is missing
   the 'script_directory' key.  #63
index d044ccdc7f2605f9fda73515463950a87c1f2941..d1f7835afb2c26615323943babd09e8e4b168b15 100644 (file)
@@ -54,11 +54,16 @@ class Operations(object):
                                     local_cols, remote_cols,
                                     onupdate=None, ondelete=None):
         m = schema.MetaData()
-        t1 = schema.Table(source, m,
-                *[schema.Column(n, NULLTYPE) for n in local_cols])
-        t2 = schema.Table(referent, m,
+        if source == referent:
+            t1_cols = local_cols + remote_cols
+        else:
+            t1_cols = local_cols
+            schema.Table(referent, m,
                 *[schema.Column(n, NULLTYPE) for n in remote_cols])
 
+        t1 = schema.Table(source, m,
+                *[schema.Column(n, NULLTYPE) for n in t1_cols])
+
         f = schema.ForeignKeyConstraint(local_cols,
                                             ["%s.%s" % (referent, n)
                                             for n in remote_cols],
index b7abaef9df7b32a052d2013cd4adee74f42c1fd1..b5dbc26dcf736c3d2c34709b758f5497c3eb9f62 100644 (file)
@@ -196,6 +196,14 @@ def test_add_foreign_key_ondelete():
             "REFERENCES t2 (bat, hoho) ON DELETE CASCADE"
     )
 
+def test_add_foreign_key_self_referential():
+    context = op_fixture()
+    op.create_foreign_key("fk_test", "t1", "t1", ["foo"], ["bar"])
+    context.assert_(
+        "ALTER TABLE t1 ADD CONSTRAINT fk_test "
+        "FOREIGN KEY(foo) REFERENCES t1 (bar)"
+    )
+
 def test_add_check_constraint():
     context = op_fixture()
     op.create_check_constraint(