﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
11569	django.core.cache.backends.db has bad transaction handling	Glenn Maynard	Aymeric Augustin	"(This problem is manifesting in core.cache, but the real problem is in db.transaction, so I've marked this as a DB problem.)

The database backend for caching handles transactions badly.

When inserting a cache key, it searches for an existing cache key.  If found, it does an UPDATE.  If not found, it does an INSERT.  The INSERT case can lead to a constraint violation, if another thread inserts that key between the SELECT and the INSERT.  The code expects this, and catches DatabaseError.

This rolls back the whole transaction, including anything the caller is doing.  It needs a savepoint for this, so it only rolls back its own work.

To handle this sanely, transaction support really needs to require savepoints, so it can expose a helper to start and commit a nested transaction, eg. db.transaction.run_in_transaction(func):

 - If a transaction is started already, start a savepoint; when finished, release the savepoint.
 - If a transaction is not started, start one (typically a no-op due to non-autocommit); when finished, commit.
 - On exception, rollback whichever it started.

Savepoints are supported by all production-quality databases (including MySQL, Postgres and SQLite), so requiring them in the backend seems reasonable.  I've hit the need for nested transactions in Django so many times I had to write my own wrapper to implement this.
"	Bug	closed	Core (Cache system)	dev	Normal	fixed		gerdemb	Accepted	0	0	0	0	0	0
