On Aug 6, 2014, at 11:15 PM, Michael Bayer <[email protected]> wrote:

> 
> The actual ordering here is based on a topological sort, and a description on 
> how the unit of work makes use of this is in section 20.9 of 
> http://aosabook.org/en/sqlalchemy.html.
> 
> In this case, from SQLAlchemy's point of view, it only needs to emit INSERT 
> for Book and Author before it INSERTs into "link_books_authors".   It's 
> deterministic in this regard, but as far as Book and Author themselves, there 
> is no natural ordering to that, so ultimately it is set/dict ordering that 
> takes effect.
> 
> If you'd like to affect the topological sort here, it's doable by creating a 
> dependency between Book and Author.  But what is blowing me away is that 
> there does not seem to be a public API for this as I really recall doing this 
> for someone.    I could show you something that does it but it would not be 
> stable API.
> 

Well anyway, it's not terrible, if you want to play with it.  This API hasn't 
changed in a couple of years and nothing is planned, but it isn't guaranteed:

@event.listens_for(Session, "before_flush")
def setup_author_book_dependency(session, ctx, objects):
    from sqlalchemy.orm.unitofwork import SaveUpdateAll
    ctx.dependencies.add(
        (
            SaveUpdateAll(ctx, Author.__mapper__),
            SaveUpdateAll(ctx, Book.__mapper__)
        )
    )

I'm fine with this kind of thing becoming available via a simpler public API 
but it would have to be carefully planned so that we aren't forced to change it 
at some point down the road.


Then within your test, to force it to randomize the order you can do this:

def test():
    from sqlalchemy.orm.util import randomize_unitofwork
    randomize_unitofwork()
    # .. rest of test

You'll find that with the above randomize, your test case is very different 50% 
of the time, unless you add that dependency between Author and Book, in which 
case it runs identically every time.




-- 
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 http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to