On 07/26/2016 02:29 PM, drMental wrote:
I'd like to restrict deletion and updates on an object based on the
boolean attribute 'locked' on the same object.

I've managed to successfully suppress updates but it doesn't seem to
work for deletes with the following code.

@listen_for(mapper, 'mapper_configured')
def mapper_configured(mapper, cls):
    def extract(obj):
        try: return obj[0]
        except IndexError: return False
    if issubclass(cls, Base):
        @listen_for(cls, 'before_update)
        @listen_for(cls, 'before_delete)
        def restrict(mapper, connection, target):
            session = Session.object_session(target)
            added, unchanged, deleted = map(extract,
inspect(target).attrs.locked.history)
            if unchanged:
                session.expire(target)

How can I make SA restrict the delete and keep object in database when a
session.delete(obj) is issued?

if you want to raise an error, super easy. raise it in the before_update and before_delete events.

if you want to make the changes be silently reset, that is probably better done inside of the before_flush() events; that way, the object is not considered for the flush plan at all. resetting it inside the mapper event would probably cause problems (I guess with delete it's still deleting it).

But even then, if an object has a "locked" state, I would probably do this at the object level; as soon as "locked" is set, call session.expire() and/or session.refresh() so it has state right there, and then override __setattr__() to block all subsequent activities during that locked state. Then keep before_update and before_delete in, and have them raise; since no object should ever get in there with locked + pending changes they serve as assertions.









Any help appreciated,

Mats

--
You received this message because you are subscribed to the Google
Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send
an email to [email protected]
<mailto:[email protected]>.
To post to this group, send email to [email protected]
<mailto:[email protected]>.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to