Skip to content

Instantly share code, notes, and snippets.

@ods
Created August 28, 2013 15:59
Show Gist options
  • Save ods/6367710 to your computer and use it in GitHub Desktop.
Save ods/6367710 to your computer and use it in GitHub Desktop.
Custom collection replication prove of concept
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.orm.collections import attribute_mapped_collection
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parents'
id = Column(Integer, primary_key=True)
children = relationship(
'Child', cascade='all,delete-orphan',\
collection_class=attribute_mapped_collection('key'))
def __repr__(self):
return 'Parent(id=%r, children=%r)' % (self.id, self.children)
class Child(Base):
__tablename__ = 'children'
id = Column(Integer, primary_key=True)
parent_id = Column(ForeignKey(Parent.id), nullable=False)
parent = relationship(Parent)
key = Column(String(250), nullable=False)
def __repr__(self):
return 'Child(id=%r, key=%r)' % (self.id, self.key)
engine = create_engine('sqlite://')#, echo=True)
Base.metadata.create_all(engine)
db = sessionmaker(bind=engine)()
p = Parent(children={'a': Child(key='a'), 'b': Child(key='b')})
db.add(p)
db.commit()
print 'Initial property value:', p.children
from sqlalchemy.orm.attributes import instance_state, instance_dict
from sqlalchemy.orm.collections import collection_adapter
# Get collection as iterable or list
adapter = collection_adapter(p.children)
old_values = list(adapter.adapt_like_to_iterable(p.children))
print 'Old values:', old_values
# Set collection from list
impl = instance_state(p).get_impl('children')
new_values = [Child(key='c'), Child(key='d')]
impl._set_iterable(instance_state(p), instance_dict(p), new_values)
print 'New property value:', p.children
db.commit()
db.expunge_all()
print 'Reloaded objects:', db.query(Parent).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment