count ForeignKey error with autoload enabled

Issue #1278 resolved
Former user created an issue

When performing count() on a query of a table attribute that is a foreign key reference, a KeyError is generated at:

File "/usr/local/lib/python2.5/site-packages/SQLAlchemy-0.5.0-py2.5.egg/sqlalchemy/schema.py", line 929, in _set_parent
    self.parent.table.foreign_keys.remove(fk)
KeyError: ForeignKey('foreign_table.foreign_id')

This only occurs when the original table definition contains autoload and the item being counted is a foreign key.

A full example script that demonstrates the problem is attached. To work with in-memory tables I had to double define the QueryTable to show the issue. The original problem is seen on a regularly defined MySQL table.

The workaround for those with the problem is to fully define the query table and not use autoload. Please let me know if I can provide any other information.

Brad

Comments (3)

  1. Mike Bayer repo owner

    autoload/ForeignKey issues can always be illustrated without any ORM/declarative stuff, to illustate the real minimal example:

    from sqlalchemy import *
    
    engine = create_engine('sqlite:///:memory:')
    
    m2 = MetaData()
    Table('foreign_table', m2, 
        Column('foreign_id', Integer, primary_key=True)
    )
    Table('query_table', m2,
        Column('query_id', Integer, primary_key = True),
        Column('foreign_id', Integer, ForeignKey('foreign_table.foreign_id'))
    )
    m2.create_all(engine)
    
    m1 = MetaData(engine)
    q = Table('query_table', m1,
        Column('foreign_id', Integer, ForeignKey('foreign_table.foreign_id')),
        autoload=True
    )
    s = select([q.c.foreign_id](q.c.foreign_id))
    s.c.foreign_id
    

    thanks for the test case, 37b7e458c201a2f7788f3db8d85bed2ab2f8e190

  2. Log in to comment