On Apr 1, 9:22 pm, Yassen Damyanov <yassen....@gmail.com> wrote: > Jyotirmoy wrote: > > I want to know what is the best way to write code using sqlalchemy > > that given a value of the primary key inserts a record if no record > > with that key exists or updates the value of the other columns if the > > key already exists.
> You may prefer to use session.merge() leaving the SELECT and the > subsequent decision to INSERT or UPDATE to SQLAlchemy > (seehttp://www.sqlalchemy.org/docs/05/session.html?highlight=merge#merging) > > The main section of your example should look like this then: > > ---snip----------------------- > id = 55 > val = random.choice(range(1000)) > t = T(id, val) > session = Session() > session.merge(t) > session.commit() > ---snip----------------------- This also has a race condition, as another process running the same code can commit between the merge and commit in this process. So the only solution seems to be to use table locks, as your alternate code does. I was wondering if there could be some way to make SA do the locking on its own rather than my having to use explicit SQL or alternatively issue something like MySQL's 'INSERT..ON DUPLICATE UPDATE'. --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---