I wanted to know some views about the soft-delete (anti?) pattern and
whether or not I'm going about it the right way in my code base.

We have a piece of code:

class NoDeletedQuery(Query):
    def __new__(cls, *args, **kwargs):
        if args and hasattr(args[0][0], "deleted_at"):
            return Query(*args, **kwargs).filter_by(deleted_at=None)
        else:
            return object.__new__(cls)


Session = scoped_session(sessionmaker(query_cls=NoDeletedQuery))

This is pretty obvious, just auto adds a filter that ignores the deleted
at, but, I think this is a very hard thing to get right, especially with
joins and whatnot. This works, but I would like to know what's the
recommended idiom? I looked at this stack overflow question:

http://stackoverflow.com/questions/920724/the-right-way-to-auto-filter-sqlalchemy-queries


The mapper solution seems ideal, which would look like:

active_accts_q = (select([
    accounts_t
])
.where(accounts_t.c.deleted_at == None).alias()
)

class Account(Base):
    __table__ = active_accts_q

    def soft_delete(self):
           self.deleted_at = func.clock_timestamp()



The problem I get here is that in my code, I do something like:

account.soft_delete()
Session.commit()


and I get a

ObjectDeletedError: Instance '<Account at 0x102b2d390>' has been deleted,
or its row is otherwise not present.


So, I'm guessing I'm just doing it wrong. Any suggestions?

For a little context, we're using soft deletes and and for external
purposes, we need to simulate a resource deletion but *still* have some
attributes of the "deleted" row come back. There are other ways to solve
this, which can be solved by triggers and the like, but I think updating a
foreign key and adding a new column that represents a deleted view is too
complicated for something that can be simplified by just having this
"deleted_at" property.

Thanks!

-- 
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 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to