Mike Bayer avatar Mike Bayer committed 650f805

- Fixed bug related to [ticket:2141] whereby the
same modified index behavior in PG 9 affected
primary key reflection on a renamed column.
[ticket:2291].

Comments (0)

Files changed (3)

     ForeignKeyConstraint refers to a column name in 
     the parent that is not found.
 
+- postgresql
+  - Fixed bug related to [ticket:2141] whereby the 
+    same modified index behavior in PG 9 affected
+    primary key reflection on a renamed column.
+    [ticket:2291].
+
 - mysql
   - Fixed OurSQL dialect to use ansi-neutral 
     quote symbol "'" for XA commands instead

lib/sqlalchemy/dialects/postgresql/base.py

     def get_primary_keys(self, connection, table_name, schema=None, **kw):
         table_oid = self.get_table_oid(connection, table_name, schema,
                                        info_cache=kw.get('info_cache'))
+
         PK_SQL = """
-          SELECT attname FROM pg_attribute
-          WHERE attrelid = (
-             SELECT indexrelid FROM pg_index i
-             WHERE i.indrelid = :table_oid
-             AND i.indisprimary = 't')
-          ORDER BY attnum
+            SELECT a.attname
+                FROM 
+                    pg_class t
+                    join pg_index ix on t.oid = ix.indrelid
+                    join pg_attribute a 
+                        on t.oid=a.attrelid and a.attnum=ANY(ix.indkey)
+          WHERE
+              t.oid = :table_oid and
+              ix.indisprimary = 't'
+          ORDER BY
+            a.attnum
         """
         t = sql.text(PK_SQL, typemap={'attname':sqltypes.Unicode})
         c = connection.execute(t, table_oid=table_oid)

test/dialect/test_postgresql.py

         finally:
             metadata.drop_all()
 
+    @testing.provide_metadata
+    def test_renamed_pk_reflection(self):
+        t = Table('t', metadata, Column('id', Integer, primary_key=True))
+        metadata.create_all()
+        testing.db.connect().execution_options(autocommit=True).\
+            execute('alter table t rename id to t_id')
+        m2 = MetaData(testing.db)
+        t2 = Table('t', m2, autoload=True)
+        eq_([c.name for c in t2.primary_key], ['t_id'])
+
     def test_schema_reflection(self):
         metadata = MetaData(testing.db)
         etype = Enum(
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.