Additional background: In the proposed code snippet, I placed the try/except around the `begin_nested()` block instead of just the `orm_session.add()` statement because the `add()` might not get flushed to database until the savepoint is released in the event the session is not auto-flushing.
I also came across a nice graphical illustration of the race condition associated with concurrent INSERT here: http://rachbelaid.com/handling-race-condition-insert-with-sqlalchemy/ On Thursday, February 4, 2021 at 5:42:40 PM UTC-8 Vitaly Kruglikov wrote: > Thanks Mike! I followed up on your suggestion concerning savepoints and > came up with the following code snippet. Does this look right to you? > > ``` > try: > with orm_session.begin_nested(): > orm_session.add(record) > except psycopg2.errors.UniqueViolation as error: # or is it > `sqlalchemy.exc.IntegrityError`??? > # Matching metadata row already inserted by someone else > # Fetch and return existing record > > # We inserted it! > return record > ``` > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- 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 sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ded97aab-d4f3-498b-aea9-af89d2e411fan%40googlegroups.com.