Josh Stratton wrote: > Ah, I see. I think the only thing I don't understand still is using > this mapping with a session and handling inserts that aren't unique. > Using a session, the problem presents itself at the commit, which > seems to mess up the entire insertion instead of the single collision. > Maybe it's more of an SQL question, but when using a session/mapper > configuration like this and one were continually trying to insert data > into the database that might have been added already, how do you > efficiently skip that insertion?
typically you have to work your code such that you've already loaded the existing rows you'd care about. or you can do a load-each-row-at-a-time type of thing. session.merge() can actually accomplish either result. 1. load everything first, then check for existing my_stuff = session.query(MyStuff).filter(<criterion you care about>).all() now everything is present in "my_stuff", as well as in the session. if you then say: obj = session.merge(MyStuff(id=12, username='jack')) it will lookup MyStuff with that primary key (either "12" or "12, jack", depending on what attributes comprise your primary key) in the session's identity map. Since everything was already loaded, it shouldn't issue any further database calls, and it will give you either the existing "MyStuff" or return to you the new one you just made. 2. load-each-row-at-a-time just remove the first query. the session will then look up things using merge() as you ask. There's other ways to do this on other databases, such as on PG you can use savepoints to attempt the insert, fail, and then try again, or MySQL provides a "REPLACE" construct (SQLA ORM doesn't support that directly); but the above approach tends to be the most straightforward. --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---