Im struggling with transactions in SQLAlchemy. So apparently there is always a transaction (unless we use autocommit=True, which is deprecated), and if someone wants to get stuff persisted, we need to call commit, which will, after flushing, create a new transaction in the end. Now my problem is that a lot of users are working on the codebase, so it becomes very complicated to keep control of transactions in the original sense. Imagine we have something like this:
db_session.begin_nested()
try:
method_that_triggers_a_lot()
except:
session.rollback()
session.commit()
This only works as-expected as long as we have one or no commit called under method_that_triggers_a_lot execution. Im aware of that, but other developers might not. So if someone adds another commit somewhere under method_that_triggers_a_lot, i would loose my expected behavior. Im not quite sure if im missing something, other ORMs like doctrine dont ship with a transaction around everything, so you have to explicitly declare begin to open one. As this always goes in pairs, you never loose the expected-behavior. I read that i might be able to use autocommit=True to get rid of the automatic transactions, but as that is marked as deprecated, im wondering if there is a better way of dealing with this. Is there something like "named" transactions, where i could do something like
session.begin_nested("my_transaction")
try:
session.add(Whatever())
session.commit()
session.commit()
except:
session.rollback("my_transaction")
session.commit("my_transaction")
From what i got, neither subtransactions nor nested can help here. Or is there a non-deprecated way to work without default-transactions around everything?