@Transaction() runs a Service method as one transaction: every SQLAlchemy DataAccess call inside it shares one session per database, committed once when the method returns and rolled back when it raises. It works at the connection level, so DataAccess code does not change.
core_lib.connection.transaction_decorator.Transaction [source]
Usage
Mark the Service method. @Transaction() goes under every decorator that must see its commit (@Cache, @DuplicateErrorHandler(), @Observe, @ResultToDict(), @staticmethod / @classmethod) and above @NotFoundErrorHandler():
from core_lib.cache.cache_decorator import Cache
from core_lib.connection.transaction_decorator import Transaction
from core_lib.data_layers.service.service import Service
from core_lib.error_handling.duplicate_error_decorator import DuplicateErrorHandler
CACHE_KEY_GROUP = 'widget_group_{group_id}'
class WidgetService(Service):
def __init__(self, widget_data_access: WidgetDataAccess):
self._widget_data_access = widget_data_access
@Cache(CACHE_KEY_GROUP, handler_name=WIDGET_CACHE, invalidate=True)
@DuplicateErrorHandler()
@Transaction()
def replace_group(self, group_id: int, names: list) -> list:
self._widget_data_access.delete_group(group_id)
for name in names:
self._widget_data_access.create({Widget.group_id.key: group_id, Widget.name.key: name})
return self.list_group(group_id)
@Cache(CACHE_KEY_GROUP, handler_name=WIDGET_CACHE)
def list_group(self, group_id: int) -> list:
return self._widget_data_access.names_in_group(group_id)
The DataAccess is written exactly as outside a transaction — no session parameter, no transaction() or *_in_transaction methods:
class WidgetDataAccess(CRUDDataAccess):
def delete_group(self, group_id: int):
with self._db.get() as session:
return session.query(Widget).filter(Widget.group_id == group_id).delete()
- Each
with self._db.get()block ends with a flush, socreatereturns the row with its id set and a child row can use it at once. - Every DataAccess on the same database joins the same session, a DataAccess of another library included, even when it holds a different factory for that database.
- A row lock is an ordinary DataAccess read (
session.get(Entity, id, with_for_update=True)) called inside the transaction; it is held until the commit.FOR UPDATEdoes nothing on sqlite.
def, never an async def, an async generator or a generator (yield). Calling one of those only builds a coroutine or a generator, so the transaction opens and closes empty, and the body runs later outside it: every write commits on its own, and an error rolls nothing back. @Transaction() logs a warning naming the function when it is applied to one. It cannot see an async function hidden behind another decorator’s plain wrapper.How it works
- Which transaction am I in? A
TransactionScopeis one transaction’s data, a dataclass: its connections plus its after-commit callbacks.TransactionManagerholds the logic that uses it (hand out its connections, end them).CoreLib.transaction_scope_registry(aTransactionScopeRegistry) stores which scope is open on each thread, keyed by the thread’s id:@Transaction()registers a scope when the method starts and unregisters it when the method ends, andget()returns the scope of the calling thread. Each thread has its own entry, so two concurrent requests never see each other’s scope. - Same session or a new one?
SqlAlchemyConnectionFactoryis aTransactionalConnectionFactory, whoseget()is one line,TransactionManager.get_connection(self), which asks the registry first (CoreLib.transaction_scope_registry.get()):- No scope: a new session each time, as before.
- A scope, and no session yet for this database: it creates one with the factory’s
create_connection(), marks itin_transaction, keeps it and returns it. Two factories on one database have the sameidentity()(its URL, without the password), so they are equal (==) and share the session. An in-memory sqlite, in any spelling (sqlite://,:memory:,file::memory:,?mode=memory), is one database per engine: factories on the same engine (a copy) share it, others never do. - A scope that already has one: it returns the same stored session.
- Why doesn’t each block commit?
SqlAlchemyConnectionis aTransactionalConnection. When a DataAccess block ends, Python calls its__exit__, which ends the connection (end) outside a transaction, but while the connection isin_transactiononly callsflush(): the SQL is sent, ids are assigned, and a duplicate raises at that call. There is no commit and no close. - Who commits? The scope, once, at the end: it calls each connection’s
endwith(None, None, None)on success, which commits and closes, or with the exception on failure, which rolls back and closes. - Nested
@Transaction()(Service A calls Service B, both decorated, on the same thread): B finds a scope already registered for this thread and simply runs inside it. Only A’s end commits. - Threads. The registry is keyed by thread, so only the thread that opened the scope finds it. A worker thread gets its own connection and commits on its own (see Threads below).
- Only SQLAlchemy joins. The scope never touches SQL; it only postpones the connection’s own end. Other connection types are not part of the transaction (see below).
Flow walkthroughs
Success:
replace_group() starts -> @Transaction puts scope {} on this thread
delete_group() -> factory.get(): factory not in scope -> new session S1, stored
DELETE on S1, block ends -> flush, NO commit
create(row1) -> factory.get(): factory in scope -> S1 again -> INSERT, flush (id set)
create(row2) -> S1 again -> INSERT, flush (id set)
list_group() -> @Cache sees the scope -> skips the cache; SELECT on S1 sees row1, row2
replace_group() returned -> scope ends -> SqlAlchemyConnection.__exit__(None, None, None) -> ONE COMMIT + close
@Cache(invalidate=True), outside the transaction -> cache key deleted
Failure:
replace_group() starts -> @Transaction puts scope {} on this thread
delete_group() -> factory.get(): factory not in scope -> new session S1, stored
DELETE on S1, block ends -> flush, NO commit
create(row1) -> factory.get(): factory in scope -> S1 again -> INSERT, flush (id set)
create(row2) -> S1 again -> INSERT fails -> IntegrityError
replace_group() raised -> scope ends -> SqlAlchemyConnection.__exit__(IntegrityError) -> rollback + close
DELETE and row1 undone; @DuplicateErrorHandler -> 409; cache key kept
Nested services:
WidgetService.move_widget() starts -> @Transaction puts scope {} on this thread
update(widget) -> new session S1, stored; UPDATE, flush
GroupService.add_member() -> also @Transaction(): a scope is already open -> runs inside it
create(member) -> same database, same factory -> S1 again; INSERT, flush
add_member() returned -> inner end: nothing committed
move_widget() returned -> outer end: ONE COMMIT for both writes
(had move_widget() raised after add_member(), both would roll back)
Other connection types
Only a TransactionalConnectionFactory joins a transaction, and in core-lib that is SqlAlchemyConnectionFactory. Every other factory’s get() works inside a transaction exactly as outside, and its writes are not undone by a rollback:
| Connection | Why it does not join |
|---|---|
| MongoDB | a transaction needs a replica set and a session= passed to every call |
| Neo4j | each run auto-commits |
| Solr, Elasticsearch, Object | no transactions |
Two SQLAlchemy databases in one transaction are each atomic on their own, but not across databases: there is no two-phase commit. Sessions are ended in the order they joined; if one commit fails, the ones after it are rolled back with that error, while the ones before it stay committed.
Errors
- The original exception propagates unchanged. A connection whose rollback fails is logged, and the others are still rolled back; the one whose rollback failed is still closed (its pooled connection goes back) and never committed. An interrupt (
KeyboardInterrupt) during a commit still rolls the rest back. - A database error swallowed inside the transaction still fails it: the session’s flush failed, so the commit raises
PendingRollbackError, nothing is saved, and the session is closed. A swallowed error that is not from the database (a 404, aValueError) lets the transaction commit. There is no “rollback-only” marking. - If a commit fails, the after-commit callbacks (deferred cache deletes) do not run. They run in order, and every one runs: one that raises never stops the rest (the data is already committed); the first error is raised once all ran, and the later ones are logged.
No savepoints: a failure undoes all of it, or none of it
A transaction is one unit. Nothing inside it can be undone on its own: there are no savepoints (a savepoint is the database feature that undoes only part of a transaction). This matters only when code catches an error inside the transaction and carries on:
@Transaction()
def outer():
write(a)
try:
inner() # also @Transaction(): it JOINS outer, writes b, then raises
except SomeError:
pass # outer carries on
# the commit saves a AND b, although inner failed
The same holds one level smaller: an error in a block opened inside another block, caught inside the outer block, still leaves what the inner block had not sent to be saved by the outer block.
@Transaction() always rolls back everything.One session, same reads and writes
- When the last open block ends, the session lets go of the rows it loaded and drops the writes it did not send, as the end of a block outside a transaction does: a later
get()reads the database again, so a raw SQL update or another thread’s commit is seen, a returned row changed in memory is not saved, and a block that raised (even when the service swallows the error) saves nothing it had not flushed. - A block opened inside another block on the same database (a DataAccess calling another) only flushes: the outer block’s rows stay loaded, and its later changes are saved (an error caught between them: see No savepoints).
- SQL errors and logged queries never show the values written (
hide_parameters=Trueon the engine): a failed write’s log and the error a caller gets show the statement, not the data. - A library on its own database login has a different URL, so it gets a second connection; it can wait on this transaction’s locks.
- A write on another thread outside the transaction commits on its own and survives the transaction’s rollback; on sqlite it waits for the transaction’s write lock first.
Threads
- A scope is joined only from the thread that opened it.
- Concurrent transactions on different threads are isolated: each has its own scope and its own connection, uncommitted rows of one are invisible to the other, and a rollback in one never touches another.
- A worker thread,
asyncio.to_threadincluded, has its own id, so it finds no scope: one SQLAlchemySessionis not safe across threads. It gets its own connection and commits on its own. A worker may open its own@Transaction(). - A sync
@Transaction()function called from inside a running asyncio event loop works as anywhere else. It blocks the loop while it runs, socall_soon/call_latercallbacks it schedules run after it ended, outside it. - A worker transaction (
to_thread, an executor,run_in_executor) is its own:gather,wait,as_completed,TaskGroupand aSemaphoreonly decide when its awaiter resumes. Cancelling the awaiter (or agather) never stops the worker: it commits or rolls back by itself;shieldchanges nothing for it. - A coroutine a worker sends to the loop with
run_coroutine_threadsaferuns on the loop’s thread, outside the worker’s transaction;asyncio.runinside a worker runs its coroutines on that worker, outside its caller’s transaction.
Processes
- Each process has its own transactions: a spawned process, a process pool worker or a forked child never sees another process’s transaction, and commits or rolls back only its own rows. Several processes may write one database at once; on sqlite their writes take turns.
- A process forked inside a transaction starts with none (the registry clears itself in the child): it never joins, commits or rolls back its parent’s transaction. A forked child that returns through the parent’s
@Transaction()raises (KeyError) instead of ending a transaction it does not own.
Alert: one database, one URL
identity(), which compares URLs, not where they lead. The same database written two ways (./x.db and x.db, localhost and 127.0.0.1, HOST and host) is two different identities: inside one transaction it gets two connections, they do not see each other’s uncommitted rows, the transaction is no longer all-or-nothing across them, and the second can wait forever on the first one’s locks.Limits
- A transaction makes writes all-or-nothing; it does not serialize a check-then-write. Two requests that both read “the slot is free” both take it. Let the database refuse the second: a unique index (the loser gets 409 through
@DuplicateErrorHandler()), or a row lock on Postgres (with_for_update=True; it does nothing on sqlite). - Never wait inside a transaction for another thread that writes the same database. The transaction holds the write lock until it ends, so the worker cannot write: sqlite gives up after its 5-second busy timeout, another database may wait forever.
- A DataAccess never commits or rolls back the session itself. A hand-made commit saves everything so far at once; a hand-made rollback silently drops the earlier blocks while the transaction goes on.
@Observehears of the commit only on the outermost transaction. A method in the right order (@Observeabove@Transaction()) that is called inside another transaction joins it, so its listeners hear of the write when the method returns, before the outer commit, and also when the outer transaction then rolls back.- A process forked inside a transaction starts with none. The child never joins or ends the parent’s transaction.
- A transactional factory never overrides
__eq__or__hash__: the base builds both fromidentity(). A subclass that defines__eq__alone loses__hash__and fails withTypeError: unhashableinside a transaction.
Decorators in the wrong order
| Order | What happens |
|---|---|
@Transaction() above @DuplicateErrorHandler() |
a duplicate found at a block’s flush is still 409, one found at the commit escapes as a raw IntegrityError |
@Transaction() above a cached read’s @Cache |
the cache is skipped inside a transaction, so it is never filled or used: every call reads the database |
@Transaction() above @Observe |
listeners hear of the write before it commits, even when the commit then fails |
@NotFoundErrorHandler() above @Transaction() |
the write commits first, then the caller gets 404 |
@Transaction() above @classmethod (or @staticmethod before Python 3.10) |
TypeError on every call: the wrapper cannot call the descriptor |
@Cache(..., invalidate=True) or @ResultToDict() either way |
the same result: the delete waits for the commit, the dict is the same |
@Cache inside a transaction
The cache is skipped only by the code running inside the transaction, and only until it ends. For everyone else it keeps working:
| Who | What the cache does |
|---|---|
| the code inside the transaction (its thread, until it ends) | a read skips the cache, with no hit and no fill: every read goes to the database. An invalidation waits on the transaction’s to-do list |
| every other thread or request, at the same moment | as always: a read uses the cache, and fills it on a miss |
| everyone, after the commit | as always. The to-do list runs and the changed keys are deleted, so the next read gets the new rows |
| everyone, after a rollback | as always. The to-do list is dropped: nothing changed, so the cache is still right |
Why the transaction cannot use the cache: until the commit, nobody knows if its writes will stay.
- It cannot read the cache. The cache may still hold the value from before its own write, so a check (“is this field still empty?”) would look at old data instead of the row it just changed or locked.
- It cannot fill the cache. What it read may include its own writes that are not committed yet. After a rollback the cache would hold data that never existed, and everyone would read it.
The cost is speed: inside a transaction a cached read goes to the database every time. A transaction is usually short (a check and a few writes), and a read under a lock must come from the database anyway. Version 1 does not fill the cache after the commit with what the transaction read.
- A cached read bypasses the cache entirely: no read (the cache may hold the row as it was before this transaction’s writes) and no fill (the rows are not committed yet and may be rolled back).
invalidate=Truewaits for the commit and is dropped on rollback. A failing delete raises after the commit, and the remaining deletes still run.- The key is built when the invalidating method is called, so changing its argument afterwards changes nothing; it is cut and cleaned like a read’s key, so the delete removes exactly what the read stored.
- Every call schedules its own delete (a key invalidated 100 times is deleted 100 times, after the commit), in call order, on the handler registered at the call.
- In a nested transaction the deletes wait for the outermost commit. An invalidating method that raised schedules nothing; one that succeeded inside an inner transaction whose error the outer one swallowed is still deleted at the commit.
- One race stays open, as without transactions: a read on another thread that loaded before the commit and stores after the invalidation leaves the old value cached until it expires or is invalidated again.
- Outside a transaction, and in a worker thread,
@Cachebehaves exactly as before.
A custom connection that supports transactions
A backend with real transactions joins @Transaction() by subclassing two abstract classes. They do the transaction work; the backend writes five small methods:
from core_lib.connection.transactional_connection import TransactionalConnection
from core_lib.connection.transactional_connection_factory import TransactionalConnectionFactory
class AcmeConnection(TransactionalConnection):
def __init__(self, client):
self.session = client.start_session()
def open(self): # what the `with` block gets
return self.session
def flush(self): # send pending writes, do not commit
self.session.flush()
def release(self): # the last open block ended: forget what was loaded
self.session.forget_loaded()
def end(self, exec_type, exec_value, traceback): # commit, or roll back on an error; then close
if exec_type is None:
self.session.commit()
else:
self.session.rollback()
self.session.close()
class AcmeConnectionFactory(TransactionalConnectionFactory):
def __init__(self, client):
self._client = client
def create_connection(self) -> AcmeConnection: # a new connection, every call
return AcmeConnection(self._client)
def identity(self) -> str: # what the connections reach; never a secret
return 'acme://{}'.format(self._client.address)
A subclass that leaves out a method marked you write it cannot be created (TypeError naming the method).
TransactionalConnectionFactory
core_lib.connection.transactional_connection_factory.TransactionalConnectionFactory [source]
create_connection() — you write it
Returns a new connection, every call. Outside a transaction it is called for every get(); inside one, only the first time the transaction needs this factory’s connection. SqlAlchemyConnectionFactory: SqlAlchemyConnection(self._engine, ...).
identity() — you write it
Returns a str naming what this factory’s connections reach. Factories with the same identity share one connection inside a transaction. It is a plain string anyone may print, so it never holds a secret: SqlAlchemyConnectionFactory returns its URL without the password, and adds its engine for an in-memory sqlite (a new database per engine). A factory whose connections are never shared returns something only it has.
get() — done by the base
What every DataAccess calls (with self._db.get() as session:). It takes no arguments (it keeps Factory.get’s signature): every connection comes from create_connection(). It is TransactionManager.get_connection(self): outside a transaction a new connection from create_connection(); inside one, the transaction’s one connection for this identity, created at its first use and marked in_transaction.
__eq__() / __hash__() — done by the base
Both are built from identity(), so they can never disagree; they are how the transaction finds the connection a factory already has. Never override them: a subclass that defines __eq__ alone loses __hash__ and fails with TypeError: unhashable inside a transaction.
TransactionalConnection
core_lib.connection.transactional_connection.TransactionalConnection [source]
open() — you write it
Returns what the with block gets: the session, the client. Called at the start of every block. SqlAlchemyConnection: the SQLAlchemy Session.
flush() — you write it
Sends the block’s pending writes without committing them. Called at the end of every block that ends cleanly inside a transaction, so ids are set and a duplicate raises at the DataAccess call. SqlAlchemyConnection: session.flush().
release() — you write it
Called when the last open block on this connection ends inside a transaction, after an error too: let go of what the blocks loaded and drop the writes they did not send, as the end of a block outside a transaction does. A block opened inside another block does not release, so the outer block keeps its rows. SqlAlchemyConnection: session.expunge_all(). A backend with nothing to release writes pass.
end(exec_type, exec_value, traceback) — you write it
Ends the connection: commit when exec_type is None, roll back otherwise, then close it. Outside a transaction it runs at the end of every block; inside one, TransactionManager.end calls it once, when the transaction ends. SqlAlchemyConnection: rolls back on an error, then commits and closes; a rollback that fails still closes the session and never commits.
__enter__() / __exit__() — done by the base
__enter__ counts the block (open_blocks) and returns open(). __exit__ uncounts it; outside a transaction it calls end; inside one it calls flush after a clean block and release when the last open block ends, and lets an error go up (the transaction rolls back through end).
in_transaction / open_blocks — kept by the base
in_transaction is True while a transaction holds this connection (TransactionManager sets it); open_blocks is how many with blocks are using it right now.