before_attach method in SessionExtension

Issue #1500 resolved
Former user created an issue

I will paste a log from the IRC channel instead of explanation

<loxs> folks, I want to override some of the behaviour of the session object. Is there some "good" way of doing it?

<jezier> loxs: it depends what "some" means

<loxs> jezier, generally, I want to modify the .add() method so that before it actually .add()s the object, it first does something (that doesn't mess with sqlalchemy at all)

<loxs> jezier, so generally I want to override in a way that it will first do my stuff and then call the actual .add()

<nosklo> loxs: why? Can't you do that stuff on, say, init?

<nosklo> loxs: of your own object?

<loxs> no, because what I do is to analyze the same object that is given to add and copy it to couchdb

<jezier> loxs: http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.SessionExtension.after_attach

<jezier> loxs: something like this?

<nosklo> cool

<loxs> yeah, but would be great if I can do it before the object is added, not after

<jezier> loxs: add a ticket to track, maybe zzzeek will add before_attach..

<loxs> because I store object's couchdb id in a field of the sqlobject

<loxs> so I actually need to save the document to couchdb first (so that I know the autogenerated id), and after that save it to sql

<loxs> I will add a ticket, thanks for the help jezier

<jezier> loxs: but... adding to session doesn't mean that it is commited to database, so is there a difference if you will do it before or after_attach?

<loxs> jezier, if I modify the object in the after_attach method, will that changes get saved?

<jezier> loxs: yes

<loxs> if so, that's great and after_attach does my job

<loxs> thanks

<jezier> loxs: .. you can still add a ticket.. it would be nice to have before_attach too

Comments (1)

  1. Mike Bayer repo owner

    add() and _attach() don't emit any SQL. so it's safe to add to couchDB and retrieve your new ID at that point, within SessionExtension after_attach(). However you're probably better off doing it in MapperExtension.before_insert() - that way you definitely know the object is brand new and not already persistent, and if your couchdb operation fails, you can raise an error and abort the flush().

    we definitely dont need the overhead of a before_attach().

  2. Log in to comment