0

I was trying out this answer from stackoverflow. But I ran into the issue where it would correctly set the OnConflictDoNothing() clause. When I ran another session.add outside of this context manager, it would still add the OnConflictDoNothing clause wrongly! Now I guess this has to with sqlalchemy's caching. I think it stores the first query (the one with OnConflictDoNothing), and then sees no difference with the next query (the one outside the context manager) and then uses the cached query. This makes it so both the queries use the OnConflictDoNothing clause, which is not desirable. I found a way to fix the problem by making following context manager:

@contextmanager
def on_conflict_do_nothing():
    Insert._post_values_clause = OnConflictDoNothing()
    yield
    Insert._post_values_clause = None

But when I run this i get the following warning from sqlalchemy:

models.py:85: SAWarning: Class OnConflictDoNothing will not make use of SQL compilation caching as it does not set the 'inherit_cache' attribute to True. This can have significant performance implications including some performance degradations in comparison to prior SQLAlchemy versions. Set this attribute to True if this object can make use of the cache key generated by the superclass. Alternatively, this attribute may be set to False which will disable this warning. (Background on this error at: https://sqlalche.me/e/14/cprf)

Which is probably the reason this context manager does work. My question is: Is there a context manager which works, but doesn't have this warning? Or should I just use core insert and add it per insert?

Robin Dillen
  • 524
  • 3
  • 10

0 Answers0