Hi all,

I have just spent most of a day tracking down a weird bug in an
application I built on top of a legacy database, in which I use simple
(non-polymorphic) multi-table inheritance. The problem arises when the
parent and child tables share the same name for their primary key
("id" in my case), but with different values (each table has its own
sequence).

I illustrate the problem in the runnable script attached below, using
a Person / Employee hierarchy. Most of the time, everything works fine
(Employee alice1 has the right "alice" Person object). But when an
Employee object is loaded (alice2), for which a Person object with the
same id already exists in the session (bob was loaded, and bob's
person.id happens to be the same as alice's employee.id), then the
wrong parent object is loaded (Employee alice2 has the wrong Person
object "bob").


Here is a runnable script that reproduces this bug:

### BEGIN: multitable_inheritance_test.py ###
from sqlalchemy import *

db = create_engine('sqlite://', echo=False)
__meta__ = BoundMetaData(db)

person_table = Table("persons", __meta__,
        Column("id", Integer, primary_key=True),
        Column("name", String(80)),
        )

employee_table = Table("employees", __meta__,
        Column("id", Integer, primary_key=True),
        Column("salary", Integer),
        Column("person_id", Integer, ForeignKey("persons.id")),
        )

class Person(object):
    def __init__(self, name):
        self.name = name

class Employee(Person): pass

__meta__.create_all()

person_mapper = mapper(Person, person_table)
mapper(Employee, employee_table, inherits=person_mapper)

person_insert = person_table.insert()
person_insert.execute(id=1, name='alice')
person_insert.execute(id=2, name='bob')

employee_insert = employee_table.insert()
employee_insert.execute(id=2, salary=250, person_id=1) # alice
employee_insert.execute(id=3, salary=200, person_id=2) # bob

session = create_session()
query = session.query(Employee)

alice1 = query.get(2)
bob = query.get(3)
alice2 = query.get(2)

print 'alice1.name: %s' % alice1.name
print 'alice2.name: %s' % alice2.name

### END ###


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to