MappedCollection not instrumented when used in a custom subclass

Issue #2406 resolved
Mike Bayer repo owner created an issue
from sqlalchemy.orm.collections import MappedCollection,\
                                    collection, _instrument_class
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
import operator

# this is missing:
# _instrument_class(MappedCollection)

class MyMappedCollection(MappedCollection):
    """Use @internally_instrumented when your methods
    call down to already-instrumented methods.

    """

    @collection.internally_instrumented
    def __setitem__(self, key, value, _sa_initiator=None):
        # do something with key, value
        MappedCollection.__setitem__(self, key, value, _sa_initiator)

    @collection.internally_instrumented
    def __delitem__(self, key, _sa_initiator=None):
        # do something with key
        MappedCollection.__delitem__(self, key, _sa_initiator)

Base= declarative_base()

class A(Base):
    __tablename__ = "a"
    id = Column(Integer, primary_key=True)
    bs = relationship("B",
                collection_class=lambda: MyMappedCollection(operator.attrgetter("name")))

class B(Base):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('a.id'))
    name = Column(String)

a1 = A()
a1.bs['foo']('foo') = B(name="foo")
a1.bs['bar']('bar') = B(name="bar")

Comments (2)

  1. Log in to comment