Comment 7 for bug 1556178

Revision history for this message
Kevin Benton (kevinbenton) wrote : Re: sqlalchemy weakrefs live between retries in unit tests

Here's a demonstration of how it is failing in Neutron. It seems to be an issue with the relationship and it being referenced.

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class B(Base):
    __tablename__ = 'b'
    a_id = Column(Integer, ForeignKey('a.id', ondelete="CASCADE"),
                  nullable=True)
    address = Column(String(36), nullable=False, primary_key=True)

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    b_recs = relationship(B, backref='A', lazy='joined',
                          passive_deletes='all')

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e, autocommit=True)

try:
    with s.begin():
        a1 = A(id=1)
        s.add(a1)

        s.flush()
        s.add(B(a_id=1, address='1234'))

        # other code references relationship
        assert a1.b_recs

        # a1 is now persistent
        assert inspect(a1).persistent

        # exception is raised
        raise Exception("something broke")
except Exception:
    # context manager has called rollback()

    # a1 is no longer persistent, it's bumped out
    assert a1 not in s
    assert inspect(a1).transient

    # retry - no problem with a2
    with s.begin():
        a2 = A(id=1)
        s.add(a2)
        s.add(B(a_id=1, address='1234'))

    assert inspect(a1).transient
    assert inspect(a2).persistent