Hello list, I'm trying to learn Sqlalchemy. After reading the docs I decided to create an example to test what I had learned so far. I usually do this by creating a unittest.TestCase class and testing if everything is working according to what I expect it to.
Meanwhile I'm having a bit of a problem handling deleted elements. I've picked up your 'backref_tree' example and added some testcases to explain my problem: after deleting the elements of a relation the other side - the attribute - of the relation is not refreshed after a objectstore.commit() followed by a objectstore.clear(). Is this the expected behaviour, if it is can you please explain me why? The problem is that this will raise inconsistencies and obligate all the reference objects to be refreshed. Another question why does the 'clear' method must be called after a 'commit'? If I'm committing my change isn't it expected that all the remaining queries be flushed into the server? On a side note, the deleting objects part is really missing on the docs. There are no example on how deleting objects affect the remaining "ecosystem", hence my confusion. Thanks in advance, -- Tiago Cogumbreiro <[EMAIL PROTECTED]> http://s1x.homelinux.net/
from sqlalchemy import * import sqlalchemy.attributes as attributes engine = create_engine('sqlite://', echo=True) class Tree(object): def __init__(self, name='', father=None): self.name = name self.father = father def __str__(self): return '<TreeNode: %s>' % self.name def __repr__(self): return self.__str__() table = Table('tree', engine, Column('id', Integer, primary_key=True), Column('name', String(64), nullable=False), Column('father_id', Integer, ForeignKey('tree.id'), nullable=True),) assign_mapper(Tree, table, properties={ # set up a backref using a string #'father':relation(Tree, foreignkey=table.c.id,primaryjoin=table.c.father_id==table.c.id, backref='childs')}, # or set up using the backref() function, which allows arguments to be passed 'childs':relation(Tree, foreignkey=table.c.father_id, primaryjoin=table.c.father_id==table.c.id, backref=backref('father', uselist=False, foreignkey=table.c.id))}, ) table.create() root = Tree('root') child1 = Tree('child1', root) child2 = Tree('child2', root) child3 = Tree('child3', child1) objectstore.commit() assert root.father is None assert child1 in root.childs assert child2 in root.childs assert len(root.childs) == 2 assert child3 in child1.childs assert len(child1.childs) == 1 assert len(Tree.select()) == 4, Tree.select() child1.delete() objectstore.commit() objectstore.clear() # Why does the 'clear' method called explicitly assert len(Tree.select()) == 3, Tree.select() new_root = Tree.select_by(name="root")[0] new_child3 = Tree.select_by(name="child3")[0] assert child1 not in new_root.childs assert new_child3.father is None # Fails assert child3.father is None assert child1 not in root.childs, root.childs