From 7aacde84f2b499d9c35741cbfccb621af6b48903 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Sat, 2 Mar 2013 20:25:25 +0100 Subject: Made transaction.managed a no-op and deprecated it. enter_transaction_management() was nearly always followed by managed(). In three places it wasn't, but they will all be refactored eventually. The "forced" keyword argument avoids introducing behavior changes until then. This is mostly backwards-compatible, except, of course, for managed itself. There's a minor difference in _enter_transaction_management: the top self.transaction_state now contains the new 'managed' state rather than the previous one. Django doesn't access self.transaction_state in _enter_transaction_management. --- docs/internals/deprecation.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'docs/internals') diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index b5173af298..296f908a5b 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -339,8 +339,6 @@ these changes. * ``Model._meta.module_name`` was renamed to ``model_name``. -* The private API ``django.db.close_connection`` will be removed. - * Remove the backward compatible shims introduced to rename ``get_query_set`` and similar queryset methods. This affects the following classes: ``BaseModelAdmin``, ``ChangeList``, ``BaseCommentNode``, @@ -350,6 +348,10 @@ these changes. * Remove the backward compatible shims introduced to rename the attributes ``ChangeList.root_query_set`` and ``ChangeList.query_set``. +* The private API ``django.db.close_connection`` will be removed. + +* The private API ``django.transaction.managed`` will be removed. + 2.0 --- -- cgit v1.3 From f5156194945661d217523d6648dfb9b48707ec95 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Sat, 2 Mar 2013 13:47:46 +0100 Subject: Added an API to control database-level autocommit. --- django/db/backends/__init__.py | 14 ++++++++++++++ django/db/backends/creation.py | 6 +++++- django/db/backends/dummy/base.py | 1 + django/db/backends/mysql/base.py | 3 +++ django/db/backends/oracle/base.py | 3 +++ django/db/backends/oracle/creation.py | 3 --- django/db/backends/postgresql_psycopg2/base.py | 8 ++++++++ django/db/backends/postgresql_psycopg2/creation.py | 3 --- django/db/backends/sqlite3/base.py | 11 +++++++++++ django/db/backends/sqlite3/creation.py | 3 --- django/db/transaction.py | 12 ++++++++++++ django/test/testcases.py | 3 +++ docs/internals/deprecation.txt | 7 ++++--- docs/topics/db/transactions.txt | 17 +++++++++++++++++ 14 files changed, 81 insertions(+), 13 deletions(-) (limited to 'docs/internals') diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index f11ee35260..379416fad7 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -44,6 +44,7 @@ class BaseDatabaseWrapper(object): self.savepoint_state = 0 # Transaction management related attributes + self.autocommit = False self.transaction_state = [] # Tracks if the connection is believed to be in transaction. This is # set somewhat aggressively, as the DBAPI doesn't make it easy to @@ -232,6 +233,12 @@ class BaseDatabaseWrapper(object): """ pass + def _set_autocommit(self, autocommit): + """ + Backend-specific implementation to enable or disable autocommit. + """ + raise NotImplementedError + ##### Generic transaction management methods ##### def enter_transaction_management(self, managed=True, forced=False): @@ -274,6 +281,13 @@ class BaseDatabaseWrapper(object): raise TransactionManagementError( "Transaction managed block ended with pending COMMIT/ROLLBACK") + def set_autocommit(self, autocommit=True): + """ + Enable or disable autocommit. + """ + self._set_autocommit(autocommit) + self.autocommit = autocommit + def abort(self): """ Roll back any ongoing transaction and clean the transaction state diff --git a/django/db/backends/creation.py b/django/db/backends/creation.py index 70c24bc820..aa4fb82b12 100644 --- a/django/db/backends/creation.py +++ b/django/db/backends/creation.py @@ -1,6 +1,7 @@ import hashlib import sys import time +import warnings from django.conf import settings from django.db.utils import load_backend @@ -466,7 +467,10 @@ class BaseDatabaseCreation(object): anymore by Django code. Kept for compatibility with user code that might use it. """ - pass + warnings.warn( + "set_autocommit was moved from BaseDatabaseCreation to " + "BaseDatabaseWrapper.", PendingDeprecationWarning, stacklevel=2) + return self.connection.set_autocommit() def _prepare_for_test_db_ddl(self): """ diff --git a/django/db/backends/dummy/base.py b/django/db/backends/dummy/base.py index c59f037a27..a8c2d5bada 100644 --- a/django/db/backends/dummy/base.py +++ b/django/db/backends/dummy/base.py @@ -57,6 +57,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): _savepoint_rollback = ignore _enter_transaction_management = complain _leave_transaction_management = ignore + _set_autocommit = complain set_dirty = complain set_clean = complain commit_unless_managed = complain diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index 400fe6cdac..39fd3695b7 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -445,6 +445,9 @@ class DatabaseWrapper(BaseDatabaseWrapper): except Database.NotSupportedError: pass + def _set_autocommit(self, autocommit): + self.connection.autocommit(autocommit) + def disable_constraint_checking(self): """ Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True, diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index 60ee1ba632..d895c1583a 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -612,6 +612,9 @@ class DatabaseWrapper(BaseDatabaseWrapper): def _savepoint_commit(self, sid): pass + def _set_autocommit(self, autocommit): + self.connection.autocommit = autocommit + def check_constraints(self, table_names=None): """ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py index aaca74e8d1..5485830bf5 100644 --- a/django/db/backends/oracle/creation.py +++ b/django/db/backends/oracle/creation.py @@ -273,6 +273,3 @@ class DatabaseCreation(BaseDatabaseCreation): settings_dict['NAME'], self._test_database_user(), ) - - def set_autocommit(self): - self.connection.connection.autocommit = True diff --git a/django/db/backends/postgresql_psycopg2/base.py b/django/db/backends/postgresql_psycopg2/base.py index f9af507311..a14844433e 100644 --- a/django/db/backends/postgresql_psycopg2/base.py +++ b/django/db/backends/postgresql_psycopg2/base.py @@ -201,6 +201,14 @@ class DatabaseWrapper(BaseDatabaseWrapper): self.isolation_level = level self.features.uses_savepoints = bool(level) + def _set_autocommit(self, autocommit): + if autocommit: + level = psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT + else: + level = self.settings_dict["OPTIONS"].get('isolation_level', + psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED) + self._set_isolation_level(level) + def set_dirty(self): if ((self.transaction_state and self.transaction_state[-1]) or not self.features.uses_autocommit): diff --git a/django/db/backends/postgresql_psycopg2/creation.py b/django/db/backends/postgresql_psycopg2/creation.py index b19926b440..e6400d79a1 100644 --- a/django/db/backends/postgresql_psycopg2/creation.py +++ b/django/db/backends/postgresql_psycopg2/creation.py @@ -78,9 +78,6 @@ class DatabaseCreation(BaseDatabaseCreation): ' text_pattern_ops')) return output - def set_autocommit(self): - self._prepare_for_test_db_ddl() - def _prepare_for_test_db_ddl(self): """Rollback and close the active transaction.""" # Make sure there is an open connection. diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 416a6293f5..9a37dd17fe 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -355,6 +355,17 @@ class DatabaseWrapper(BaseDatabaseWrapper): if self.settings_dict['NAME'] != ":memory:": BaseDatabaseWrapper.close(self) + def _set_autocommit(self, autocommit): + if autocommit: + level = None + else: + # sqlite3's internal default is ''. It's different from None. + # See Modules/_sqlite/connection.c. + level = '' + # 'isolation_level' is a misleading API. + # SQLite always runs at the SERIALIZABLE isolation level. + self.connection.isolation_level = level + def check_constraints(self, table_names=None): """ Checks each table name in `table_names` for rows with invalid foreign key references. This method is diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py index c90a697e35..a9fb273f7a 100644 --- a/django/db/backends/sqlite3/creation.py +++ b/django/db/backends/sqlite3/creation.py @@ -72,9 +72,6 @@ class DatabaseCreation(BaseDatabaseCreation): # Remove the SQLite database file os.remove(test_database_name) - def set_autocommit(self): - self.connection.connection.isolation_level = None - def test_db_signature(self): """ Returns a tuple that uniquely identifies a test database. diff --git a/django/db/transaction.py b/django/db/transaction.py index 09ce2abbd2..dd48e14bf4 100644 --- a/django/db/transaction.py +++ b/django/db/transaction.py @@ -39,6 +39,18 @@ def get_connection(using=None): using = DEFAULT_DB_ALIAS return connections[using] +def get_autocommit(using=None): + """ + Get the autocommit status of the connection. + """ + return get_connection(using).autocommit + +def set_autocommit(using=None, autocommit=True): + """ + Set the autocommit status of the connection. + """ + return get_connection(using).set_autocommit(autocommit) + def abort(using=None): """ Roll back any ongoing transactions and clean the transaction management diff --git a/django/test/testcases.py b/django/test/testcases.py index 7f6b1a49ba..4b9116e3bc 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -63,6 +63,7 @@ def to_list(value): value = [value] return value +real_set_autocommit = transaction.set_autocommit real_commit = transaction.commit real_rollback = transaction.rollback real_enter_transaction_management = transaction.enter_transaction_management @@ -73,6 +74,7 @@ def nop(*args, **kwargs): return def disable_transaction_methods(): + transaction.set_autocommit = nop transaction.commit = nop transaction.rollback = nop transaction.enter_transaction_management = nop @@ -80,6 +82,7 @@ def disable_transaction_methods(): transaction.abort = nop def restore_transaction_methods(): + transaction.set_autocommit = real_set_autocommit transaction.commit = real_commit transaction.rollback = real_rollback transaction.enter_transaction_management = real_enter_transaction_management diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 296f908a5b..74fbb563f0 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -348,9 +348,10 @@ these changes. * Remove the backward compatible shims introduced to rename the attributes ``ChangeList.root_query_set`` and ``ChangeList.query_set``. -* The private API ``django.db.close_connection`` will be removed. - -* The private API ``django.transaction.managed`` will be removed. +* The following private APIs will be removed: + - ``django.db.close_connection()`` + - ``django.db.backends.creation.BaseDatabaseCreation.set_autocommit()`` + - ``django.db.transaction.managed()`` 2.0 --- diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 11755ff5c5..e145edf149 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -208,6 +208,23 @@ This applies to all database operations, not just write operations. Even if your transaction only reads from the database, the transaction must be committed or rolled back before you complete a request. +.. _managing-autocommit: + +Managing autocommit +=================== + +.. versionadded:: 1.6 + +Django provides a straightforward API to manage the autocommit state of each +database connection, if you need to. + +.. function:: get_autocommit(using=None) + +.. function:: set_autocommit(using=None, autocommit=True) + +These functions take a ``using`` argument which should be the name of a +database. If it isn't provided, Django uses the ``"default"`` database. + .. _deactivate-transaction-management: How to globally deactivate transaction management -- cgit v1.3 From ba5138b1c0253fcf390b7509ad7b954117b3be88 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Mon, 4 Mar 2013 13:12:59 +0100 Subject: Deprecated transaction.commit/rollback_unless_managed. Since "unless managed" now means "if database-level autocommit", committing or rolling back doesn't have any effect. Restored transactional integrity in a few places that relied on automatically-started transactions with a transitory API. --- django/contrib/gis/utils/layermapping.py | 4 -- django/contrib/sessions/backends/db.py | 1 - django/core/cache/backends/db.py | 7 +- .../core/management/commands/createcachetable.py | 21 +++--- django/core/management/commands/flush.py | 9 ++- django/core/management/commands/loaddata.py | 1 - django/core/management/commands/syncdb.py | 77 ++++++++++---------- django/db/__init__.py | 11 --- django/db/backends/__init__.py | 21 ------ django/db/backends/dummy/base.py | 2 - django/db/models/base.py | 84 +++++++++++----------- django/db/models/deletion.py | 2 - django/db/models/query.py | 4 -- django/db/transaction.py | 27 ++++--- django/test/testcases.py | 19 +---- docs/internals/deprecation.txt | 2 + tests/transactions_regress/tests.py | 32 --------- 17 files changed, 116 insertions(+), 208 deletions(-) (limited to 'docs/internals') diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index e4ea44d0d2..51f70f5350 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -555,10 +555,6 @@ class LayerMapping(object): except SystemExit: raise except Exception as msg: - if self.transaction_mode == 'autocommit': - # Rolling back the transaction so that other model saves - # will work. - transaction.rollback_unless_managed() if strict: # Bailing out if the `strict` keyword is set. if not silent: diff --git a/django/contrib/sessions/backends/db.py b/django/contrib/sessions/backends/db.py index 47e89b66e5..30da0b7a10 100644 --- a/django/contrib/sessions/backends/db.py +++ b/django/contrib/sessions/backends/db.py @@ -74,7 +74,6 @@ class SessionStore(SessionBase): @classmethod def clear_expired(cls): Session.objects.filter(expire_date__lt=timezone.now()).delete() - transaction.commit_unless_managed() # At bottom to avoid circular import diff --git a/django/core/cache/backends/db.py b/django/core/cache/backends/db.py index bb91d8cb05..53d7f4d22a 100644 --- a/django/core/cache/backends/db.py +++ b/django/core/cache/backends/db.py @@ -10,7 +10,7 @@ except ImportError: from django.conf import settings from django.core.cache.backends.base import BaseCache -from django.db import connections, router, transaction, DatabaseError +from django.db import connections, router, DatabaseError from django.utils import timezone, six from django.utils.encoding import force_bytes @@ -70,7 +70,6 @@ class DatabaseCache(BaseDatabaseCache): cursor = connections[db].cursor() cursor.execute("DELETE FROM %s " "WHERE cache_key = %%s" % table, [key]) - transaction.commit_unless_managed(using=db) return default value = connections[db].ops.process_clob(row[1]) return pickle.loads(base64.b64decode(force_bytes(value))) @@ -124,10 +123,8 @@ class DatabaseCache(BaseDatabaseCache): [key, b64encoded, connections[db].ops.value_to_db_datetime(exp)]) except DatabaseError: # To be threadsafe, updates/inserts are allowed to fail silently - transaction.rollback_unless_managed(using=db) return False else: - transaction.commit_unless_managed(using=db) return True def delete(self, key, version=None): @@ -139,7 +136,6 @@ class DatabaseCache(BaseDatabaseCache): cursor = connections[db].cursor() cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key]) - transaction.commit_unless_managed(using=db) def has_key(self, key, version=None): key = self.make_key(key, version=version) @@ -184,7 +180,6 @@ class DatabaseCache(BaseDatabaseCache): table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute('DELETE FROM %s' % table) - transaction.commit_unless_managed(using=db) # For backwards compatibility class CacheClass(DatabaseCache): diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py index 411042ee76..94b6b09400 100644 --- a/django/core/management/commands/createcachetable.py +++ b/django/core/management/commands/createcachetable.py @@ -53,14 +53,13 @@ class Command(LabelCommand): for i, line in enumerate(table_output): full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or '')) full_statement.append(');') - curs = connection.cursor() - try: - curs.execute("\n".join(full_statement)) - except DatabaseError as e: - transaction.rollback_unless_managed(using=db) - raise CommandError( - "Cache table '%s' could not be created.\nThe error was: %s." % - (tablename, force_text(e))) - for statement in index_output: - curs.execute(statement) - transaction.commit_unless_managed(using=db) + with transaction.commit_on_success_unless_managed(): + curs = connection.cursor() + try: + curs.execute("\n".join(full_statement)) + except DatabaseError as e: + raise CommandError( + "Cache table '%s' could not be created.\nThe error was: %s." % + (tablename, force_text(e))) + for statement in index_output: + curs.execute(statement) diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py index 3bf1e9c672..9bd65e735c 100644 --- a/django/core/management/commands/flush.py +++ b/django/core/management/commands/flush.py @@ -57,18 +57,17 @@ Are you sure you want to do this? if confirm == 'yes': try: - cursor = connection.cursor() - for sql in sql_list: - cursor.execute(sql) + with transaction.commit_on_success_unless_managed(): + cursor = connection.cursor() + for sql in sql_list: + cursor.execute(sql) except Exception as e: - transaction.rollback_unless_managed(using=db) raise CommandError("""Database %s couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run. The full error: %s""" % (connection.settings_dict['NAME'], e)) - transaction.commit_unless_managed(using=db) # Emit the post sync signal. This allows individual # applications to respond as if the database had been diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 77b9a44a43..674e6be7b0 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -73,7 +73,6 @@ class Command(BaseCommand): # Start transaction management. All fixtures are installed in a # single transaction to ensure that all references are resolved. if commit: - transaction.commit_unless_managed(using=self.using) transaction.enter_transaction_management(using=self.using) class SingleZipReader(zipfile.ZipFile): diff --git a/django/core/management/commands/syncdb.py b/django/core/management/commands/syncdb.py index 4ce2910fb5..e7e11a8c90 100644 --- a/django/core/management/commands/syncdb.py +++ b/django/core/management/commands/syncdb.py @@ -83,26 +83,25 @@ class Command(NoArgsCommand): # Create the tables for each model if verbosity >= 1: self.stdout.write("Creating tables ...\n") - for app_name, model_list in manifest.items(): - for model in model_list: - # Create the model's database table, if it doesn't already exist. - if verbosity >= 3: - self.stdout.write("Processing %s.%s model\n" % (app_name, model._meta.object_name)) - sql, references = connection.creation.sql_create_model(model, self.style, seen_models) - seen_models.add(model) - created_models.add(model) - for refto, refs in references.items(): - pending_references.setdefault(refto, []).extend(refs) - if refto in seen_models: - sql.extend(connection.creation.sql_for_pending_references(refto, self.style, pending_references)) - sql.extend(connection.creation.sql_for_pending_references(model, self.style, pending_references)) - if verbosity >= 1 and sql: - self.stdout.write("Creating table %s\n" % model._meta.db_table) - for statement in sql: - cursor.execute(statement) - tables.append(connection.introspection.table_name_converter(model._meta.db_table)) - - transaction.commit_unless_managed(using=db) + with transaction.commit_on_success_unless_managed(using=db): + for app_name, model_list in manifest.items(): + for model in model_list: + # Create the model's database table, if it doesn't already exist. + if verbosity >= 3: + self.stdout.write("Processing %s.%s model\n" % (app_name, model._meta.object_name)) + sql, references = connection.creation.sql_create_model(model, self.style, seen_models) + seen_models.add(model) + created_models.add(model) + for refto, refs in references.items(): + pending_references.setdefault(refto, []).extend(refs) + if refto in seen_models: + sql.extend(connection.creation.sql_for_pending_references(refto, self.style, pending_references)) + sql.extend(connection.creation.sql_for_pending_references(model, self.style, pending_references)) + if verbosity >= 1 and sql: + self.stdout.write("Creating table %s\n" % model._meta.db_table) + for statement in sql: + cursor.execute(statement) + tables.append(connection.introspection.table_name_converter(model._meta.db_table)) # Send the post_syncdb signal, so individual apps can do whatever they need # to do at this point. @@ -122,17 +121,16 @@ class Command(NoArgsCommand): if custom_sql: if verbosity >= 2: self.stdout.write("Installing custom SQL for %s.%s model\n" % (app_name, model._meta.object_name)) - try: - for sql in custom_sql: - cursor.execute(sql) - except Exception as e: - self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ - (app_name, model._meta.object_name, e)) - if show_traceback: - traceback.print_exc() - transaction.rollback_unless_managed(using=db) - else: - transaction.commit_unless_managed(using=db) + with transaction.commit_on_success_unless_managed(using=db): + try: + for sql in custom_sql: + cursor.execute(sql) + except Exception as e: + self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ + (app_name, model._meta.object_name, e)) + if show_traceback: + traceback.print_exc() + raise else: if verbosity >= 3: self.stdout.write("No custom SQL for %s.%s model\n" % (app_name, model._meta.object_name)) @@ -147,15 +145,14 @@ class Command(NoArgsCommand): if index_sql: if verbosity >= 2: self.stdout.write("Installing index for %s.%s model\n" % (app_name, model._meta.object_name)) - try: - for sql in index_sql: - cursor.execute(sql) - except Exception as e: - self.stderr.write("Failed to install index for %s.%s model: %s\n" % \ - (app_name, model._meta.object_name, e)) - transaction.rollback_unless_managed(using=db) - else: - transaction.commit_unless_managed(using=db) + with transaction.commit_on_success_unless_managed(using=db): + try: + for sql in index_sql: + cursor.execute(sql) + except Exception as e: + self.stderr.write("Failed to install index for %s.%s model: %s\n" % \ + (app_name, model._meta.object_name, e)) + raise # Load initial_data fixtures (unless that has been disabled) if load_initial_data: diff --git a/django/db/__init__.py b/django/db/__init__.py index 60fe8f6ce2..13ba68ba7e 100644 --- a/django/db/__init__.py +++ b/django/db/__init__.py @@ -77,14 +77,3 @@ def close_old_connections(**kwargs): conn.close_if_unusable_or_obsolete() signals.request_started.connect(close_old_connections) signals.request_finished.connect(close_old_connections) - -# Register an event that rolls back the connections -# when a Django request has an exception. -def _rollback_on_exception(**kwargs): - from django.db import transaction - for conn in connections: - try: - transaction.rollback_unless_managed(using=conn) - except DatabaseError: - pass -signals.got_request_exception.connect(_rollback_on_exception) diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index 4031e8f668..848f6df2d6 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -339,27 +339,6 @@ class BaseDatabaseWrapper(object): return self.transaction_state[-1] return settings.TRANSACTIONS_MANAGED - def commit_unless_managed(self): - """ - Commits changes if the system is not in managed transaction mode. - """ - self.validate_thread_sharing() - if not self.is_managed(): - self.commit() - self.clean_savepoints() - else: - self.set_dirty() - - def rollback_unless_managed(self): - """ - Rolls back changes if the system is not in managed transaction mode. - """ - self.validate_thread_sharing() - if not self.is_managed(): - self.rollback() - else: - self.set_dirty() - ##### Foreign key constraints checks handling ##### @contextmanager diff --git a/django/db/backends/dummy/base.py b/django/db/backends/dummy/base.py index 02f0b6462d..9a220ffd8b 100644 --- a/django/db/backends/dummy/base.py +++ b/django/db/backends/dummy/base.py @@ -58,8 +58,6 @@ class DatabaseWrapper(BaseDatabaseWrapper): _set_autocommit = complain set_dirty = complain set_clean = complain - commit_unless_managed = complain - rollback_unless_managed = ignore def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) diff --git a/django/db/models/base.py b/django/db/models/base.py index 543cdfc165..ab0e42d461 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -609,48 +609,48 @@ class Model(six.with_metaclass(ModelBase)): if update_fields: non_pks = [f for f in non_pks if f.name in update_fields or f.attname in update_fields] - # First, try an UPDATE. If that doesn't update anything, do an INSERT. - pk_val = self._get_pk_val(meta) - pk_set = pk_val is not None - record_exists = True - manager = cls._base_manager - if pk_set: - # Determine if we should do an update (pk already exists, forced update, - # no force_insert) - if ((force_update or update_fields) or (not force_insert and - manager.using(using).filter(pk=pk_val).exists())): - if force_update or non_pks: - values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks] - if values: - rows = manager.using(using).filter(pk=pk_val)._update(values) - if force_update and not rows: - raise DatabaseError("Forced update did not affect any rows.") - if update_fields and not rows: - raise DatabaseError("Save with update_fields did not affect any rows.") - else: - record_exists = False - if not pk_set or not record_exists: - if meta.order_with_respect_to: - # If this is a model with an order_with_respect_to - # autopopulate the _order field - field = meta.order_with_respect_to - order_value = manager.using(using).filter(**{field.name: getattr(self, field.attname)}).count() - self._order = order_value - - fields = meta.local_fields - if not pk_set: - if force_update or update_fields: - raise ValueError("Cannot force an update in save() with no primary key.") - fields = [f for f in fields if not isinstance(f, AutoField)] + with transaction.commit_on_success_unless_managed(using=using): + # First, try an UPDATE. If that doesn't update anything, do an INSERT. + pk_val = self._get_pk_val(meta) + pk_set = pk_val is not None + record_exists = True + manager = cls._base_manager + if pk_set: + # Determine if we should do an update (pk already exists, forced update, + # no force_insert) + if ((force_update or update_fields) or (not force_insert and + manager.using(using).filter(pk=pk_val).exists())): + if force_update or non_pks: + values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks] + if values: + rows = manager.using(using).filter(pk=pk_val)._update(values) + if force_update and not rows: + raise DatabaseError("Forced update did not affect any rows.") + if update_fields and not rows: + raise DatabaseError("Save with update_fields did not affect any rows.") + else: + record_exists = False + if not pk_set or not record_exists: + if meta.order_with_respect_to: + # If this is a model with an order_with_respect_to + # autopopulate the _order field + field = meta.order_with_respect_to + order_value = manager.using(using).filter(**{field.name: getattr(self, field.attname)}).count() + self._order = order_value + + fields = meta.local_fields + if not pk_set: + if force_update or update_fields: + raise ValueError("Cannot force an update in save() with no primary key.") + fields = [f for f in fields if not isinstance(f, AutoField)] - record_exists = False + record_exists = False - update_pk = bool(meta.has_auto_field and not pk_set) - result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) + update_pk = bool(meta.has_auto_field and not pk_set) + result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) - if update_pk: - setattr(self, meta.pk.attname, result) - transaction.commit_unless_managed(using=using) + if update_pk: + setattr(self, meta.pk.attname, result) # Store the database on which the object was saved self._state.db = using @@ -963,9 +963,9 @@ def method_set_order(ordered_obj, self, id_list, using=None): order_name = ordered_obj._meta.order_with_respect_to.name # FIXME: It would be nice if there was an "update many" version of update # for situations like this. - for i, j in enumerate(id_list): - ordered_obj.objects.filter(**{'pk': j, order_name: rel_val}).update(_order=i) - transaction.commit_unless_managed(using=using) + with transaction.commit_on_success_unless_managed(using=using): + for i, j in enumerate(id_list): + ordered_obj.objects.filter(**{'pk': j, order_name: rel_val}).update(_order=i) def method_get_order(ordered_obj, self): diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py index 93ef0006cb..26f63391d5 100644 --- a/django/db/models/deletion.py +++ b/django/db/models/deletion.py @@ -62,8 +62,6 @@ def force_managed(func): func(self, *args, **kwargs) if forced_managed: transaction.commit(using=self.using) - else: - transaction.commit_unless_managed(using=self.using) finally: if forced_managed: transaction.leave_transaction_management(using=self.using) diff --git a/django/db/models/query.py b/django/db/models/query.py index b41007ee4f..22f71c6aee 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -460,8 +460,6 @@ class QuerySet(object): self._batched_insert(objs_without_pk, fields, batch_size) if forced_managed: transaction.commit(using=self.db) - else: - transaction.commit_unless_managed(using=self.db) finally: if forced_managed: transaction.leave_transaction_management(using=self.db) @@ -590,8 +588,6 @@ class QuerySet(object): rows = query.get_compiler(self.db).execute_sql(None) if forced_managed: transaction.commit(using=self.db) - else: - transaction.commit_unless_managed(using=self.db) finally: if forced_managed: transaction.leave_transaction_management(using=self.db) diff --git a/django/db/transaction.py b/django/db/transaction.py index dd48e14bf4..a8e80c6c02 100644 --- a/django/db/transaction.py +++ b/django/db/transaction.py @@ -123,16 +123,12 @@ def managed(flag=True, using=None): PendingDeprecationWarning, stacklevel=2) def commit_unless_managed(using=None): - """ - Commits changes if the system is not in managed transaction mode. - """ - get_connection(using).commit_unless_managed() + warnings.warn("'commit_unless_managed' is now a no-op.", + PendingDeprecationWarning, stacklevel=2) def rollback_unless_managed(using=None): - """ - Rolls back changes if the system is not in managed transaction mode. - """ - get_connection(using).rollback_unless_managed() + warnings.warn("'rollback_unless_managed' is now a no-op.", + PendingDeprecationWarning, stacklevel=2) ############### # Public APIs # @@ -280,3 +276,18 @@ def commit_manually(using=None): leave_transaction_management(using=using) return _transaction_func(entering, exiting, using) + +def commit_on_success_unless_managed(using=None): + """ + Transitory API to preserve backwards-compatibility while refactoring. + """ + if is_managed(using): + def entering(using): + pass + + def exiting(exc_value, using): + set_dirty(using=using) + + return _transaction_func(entering, exiting, using) + else: + return commit_on_success(using) diff --git a/django/test/testcases.py b/django/test/testcases.py index 4b9116e3bc..55673dca25 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -157,14 +157,6 @@ class DocTestRunner(doctest.DocTestRunner): doctest.DocTestRunner.__init__(self, *args, **kwargs) self.optionflags = doctest.ELLIPSIS - def report_unexpected_exception(self, out, test, example, exc_info): - doctest.DocTestRunner.report_unexpected_exception(self, out, test, - example, exc_info) - # Rollback, in case of database errors. Otherwise they'd have - # side effects on other tests. - for conn in connections: - transaction.rollback_unless_managed(using=conn) - class _AssertNumQueriesContext(CaptureQueriesContext): def __init__(self, test_case, num, connection): @@ -490,14 +482,10 @@ class TransactionTestCase(SimpleTestCase): conn.ops.sequence_reset_by_name_sql(no_style(), conn.introspection.sequence_list()) if sql_list: - try: + with transaction.commit_on_success_unless_managed(using=db_name): cursor = conn.cursor() for sql in sql_list: cursor.execute(sql) - except Exception: - transaction.rollback_unless_managed(using=db_name) - raise - transaction.commit_unless_managed(using=db_name) def _fixture_setup(self): for db_name in self._databases_names(include_mirrors=False): @@ -537,11 +525,6 @@ class TransactionTestCase(SimpleTestCase): conn.close() def _fixture_teardown(self): - # Roll back any pending transactions in order to avoid a deadlock - # during flush when TEST_MIRROR is used (#18984). - for conn in connections.all(): - conn.rollback_unless_managed() - for db in self._databases_names(include_mirrors=False): call_command('flush', verbosity=0, interactive=False, database=db, skip_validation=True, reset_sequences=False) diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 74fbb563f0..a81b16278f 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -352,6 +352,8 @@ these changes. - ``django.db.close_connection()`` - ``django.db.backends.creation.BaseDatabaseCreation.set_autocommit()`` - ``django.db.transaction.managed()`` + - ``django.db.transaction.commit_unless_managed()`` + - ``django.db.transaction.rollback_unless_managed()`` 2.0 --- diff --git a/tests/transactions_regress/tests.py b/tests/transactions_regress/tests.py index e6750cddcf..3d571fba2f 100644 --- a/tests/transactions_regress/tests.py +++ b/tests/transactions_regress/tests.py @@ -208,38 +208,6 @@ class TestNewConnection(TransactionTestCase): connection.leave_transaction_management() self.assertEqual(orig_dirty, connection._dirty) - # TODO: update this test to account for database-level autocommit. - @expectedFailure - def test_commit_unless_managed(self): - cursor = connection.cursor() - cursor.execute("INSERT into transactions_regress_mod (fld) values (2)") - connection.commit_unless_managed() - self.assertFalse(connection.is_dirty()) - self.assertEqual(len(Mod.objects.all()), 1) - self.assertTrue(connection.is_dirty()) - connection.commit_unless_managed() - self.assertFalse(connection.is_dirty()) - - # TODO: update this test to account for database-level autocommit. - @expectedFailure - def test_commit_unless_managed_in_managed(self): - cursor = connection.cursor() - connection.enter_transaction_management() - cursor.execute("INSERT into transactions_regress_mod (fld) values (2)") - connection.commit_unless_managed() - self.assertTrue(connection.is_dirty()) - connection.rollback() - self.assertFalse(connection.is_dirty()) - self.assertEqual(len(Mod.objects.all()), 0) - connection.commit() - connection.leave_transaction_management() - self.assertFalse(connection.is_dirty()) - self.assertEqual(len(Mod.objects.all()), 0) - self.assertTrue(connection.is_dirty()) - connection.commit_unless_managed() - self.assertFalse(connection.is_dirty()) - self.assertEqual(len(Mod.objects.all()), 0) - @skipUnless(connection.vendor == 'postgresql', "This test only valid for PostgreSQL") -- cgit v1.3 From 3bdc7a6a70bb030324fdebe9b1dce1fa5358f0c6 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Mon, 4 Mar 2013 15:24:01 +0100 Subject: Deprecated transaction.is_managed(). It's synchronized with the autocommit flag. --- django/db/backends/__init__.py | 30 ++++++++++++------------------ django/db/models/deletion.py | 2 +- django/db/models/query.py | 4 ++-- django/db/transaction.py | 12 +++++------- django/middleware/transaction.py | 2 +- docs/internals/deprecation.txt | 1 + tests/middleware/tests.py | 2 +- 7 files changed, 23 insertions(+), 30 deletions(-) (limited to 'docs/internals') diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index 848f6df2d6..499bc32113 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -256,11 +256,12 @@ class BaseDatabaseWrapper(object): """ self.transaction_state.append(managed) - if managed and self.autocommit: - self.set_autocommit(False) - if not managed and self.is_dirty() and not forced: self.commit() + self.set_clean() + + if managed == self.autocommit: + self.set_autocommit(not managed) def leave_transaction_management(self): """ @@ -274,19 +275,20 @@ class BaseDatabaseWrapper(object): raise TransactionManagementError( "This code isn't under transaction management") - # That's the next state -- we already left the previous state behind. - managed = self.is_managed() + if self.transaction_state: + managed = self.transaction_state[-1] + else: + managed = settings.TRANSACTIONS_MANAGED if self._dirty: self.rollback() - if not managed and not self.autocommit: - self.set_autocommit(True) + if managed == self.autocommit: + self.set_autocommit(not managed) raise TransactionManagementError( "Transaction managed block ended with pending COMMIT/ROLLBACK") - if not managed and not self.autocommit: - self.set_autocommit(True) - + if managed == self.autocommit: + self.set_autocommit(not managed) def set_autocommit(self, autocommit=True): """ @@ -331,14 +333,6 @@ class BaseDatabaseWrapper(object): self._dirty = False self.clean_savepoints() - def is_managed(self): - """ - Checks whether the transaction manager is in manual or in auto state. - """ - if self.transaction_state: - return self.transaction_state[-1] - return settings.TRANSACTIONS_MANAGED - ##### Foreign key constraints checks handling ##### @contextmanager diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py index 26f63391d5..27184c9350 100644 --- a/django/db/models/deletion.py +++ b/django/db/models/deletion.py @@ -53,7 +53,7 @@ def DO_NOTHING(collector, field, sub_objs, using): def force_managed(func): @wraps(func) def decorated(self, *args, **kwargs): - if not transaction.is_managed(using=self.using): + if transaction.get_autocommit(using=self.using): transaction.enter_transaction_management(using=self.using, forced=True) forced_managed = True else: diff --git a/django/db/models/query.py b/django/db/models/query.py index 22f71c6aee..834fe363b4 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -442,7 +442,7 @@ class QuerySet(object): self._for_write = True connection = connections[self.db] fields = self.model._meta.local_fields - if not transaction.is_managed(using=self.db): + if transaction.get_autocommit(using=self.db): transaction.enter_transaction_management(using=self.db, forced=True) forced_managed = True else: @@ -579,7 +579,7 @@ class QuerySet(object): self._for_write = True query = self.query.clone(sql.UpdateQuery) query.add_update_values(kwargs) - if not transaction.is_managed(using=self.db): + if transaction.get_autocommit(using=self.db): transaction.enter_transaction_management(using=self.db, forced=True) forced_managed = True else: diff --git a/django/db/transaction.py b/django/db/transaction.py index a8e80c6c02..49b67f4122 100644 --- a/django/db/transaction.py +++ b/django/db/transaction.py @@ -113,10 +113,8 @@ def clean_savepoints(using=None): get_connection(using).clean_savepoints() def is_managed(using=None): - """ - Checks whether the transaction manager is in manual or in auto state. - """ - return get_connection(using).is_managed() + warnings.warn("'is_managed' is deprecated.", + PendingDeprecationWarning, stacklevel=2) def managed(flag=True, using=None): warnings.warn("'managed' no longer serves a purpose.", @@ -281,7 +279,9 @@ def commit_on_success_unless_managed(using=None): """ Transitory API to preserve backwards-compatibility while refactoring. """ - if is_managed(using): + if get_autocommit(using): + return commit_on_success(using) + else: def entering(using): pass @@ -289,5 +289,3 @@ def commit_on_success_unless_managed(using=None): set_dirty(using=using) return _transaction_func(entering, exiting, using) - else: - return commit_on_success(using) diff --git a/django/middleware/transaction.py b/django/middleware/transaction.py index b5a07a02b7..35f765d99f 100644 --- a/django/middleware/transaction.py +++ b/django/middleware/transaction.py @@ -23,7 +23,7 @@ class TransactionMiddleware(object): def process_response(self, request, response): """Commits and leaves transaction management.""" - if transaction.is_managed(): + if not transaction.get_autocommit(): if transaction.is_dirty(): # Note: it is possible that the commit fails. If the reason is # closed connection or some similar reason, then there is diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index a81b16278f..1c8618713a 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -351,6 +351,7 @@ these changes. * The following private APIs will be removed: - ``django.db.close_connection()`` - ``django.db.backends.creation.BaseDatabaseCreation.set_autocommit()`` + - ``django.db.transaction.is_managed()`` - ``django.db.transaction.managed()`` - ``django.db.transaction.commit_unless_managed()`` - ``django.db.transaction.rollback_unless_managed()`` diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index 17751dd158..e704fce342 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -689,7 +689,7 @@ class TransactionMiddlewareTest(TransactionTestCase): def test_request(self): TransactionMiddleware().process_request(self.request) - self.assertTrue(transaction.is_managed()) + self.assertFalse(transaction.get_autocommit()) def test_managed_response(self): transaction.enter_transaction_management() -- cgit v1.3 From 7c46c8d5f27fe305507359588ca0635b6d87c59a Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Mon, 4 Mar 2013 23:26:31 +0100 Subject: Added some assertions to enforce the atomicity of atomic. --- django/db/__init__.py | 1 + django/db/backends/__init__.py | 15 ++ django/db/transaction.py | 18 +- docs/internals/deprecation.txt | 4 + docs/releases/1.3-alpha-1.txt | 6 +- docs/releases/1.3.txt | 6 +- docs/releases/1.6.txt | 17 +- docs/topics/db/transactions.txt | 439 +++++++++++++++------------------- tests/backends/tests.py | 15 +- tests/fixtures_model_package/tests.py | 11 +- tests/fixtures_regress/tests.py | 7 +- tests/middleware/tests.py | 6 +- tests/transactions/tests.py | 71 +++++- tests/transactions_regress/tests.py | 12 +- 14 files changed, 359 insertions(+), 269 deletions(-) (limited to 'docs/internals') diff --git a/django/db/__init__.py b/django/db/__init__.py index 13ba68ba7e..08c901ab7b 100644 --- a/django/db/__init__.py +++ b/django/db/__init__.py @@ -70,6 +70,7 @@ signals.request_started.connect(reset_queries) # their lifetime. NB: abort() doesn't do anything outside of a transaction. def close_old_connections(**kwargs): for conn in connections.all(): + # Remove this when the legacy transaction management goes away. try: conn.abort() except DatabaseError: diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index 818850bf43..346d10198d 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -157,6 +157,7 @@ class BaseDatabaseWrapper(object): Commits a transaction and resets the dirty flag. """ self.validate_thread_sharing() + self.validate_no_atomic_block() self._commit() self.set_clean() @@ -165,6 +166,7 @@ class BaseDatabaseWrapper(object): Rolls back a transaction and resets the dirty flag. """ self.validate_thread_sharing() + self.validate_no_atomic_block() self._rollback() self.set_clean() @@ -265,6 +267,8 @@ class BaseDatabaseWrapper(object): If you switch off transaction management and there is a pending commit/rollback, the data will be commited, unless "forced" is True. """ + self.validate_no_atomic_block() + self.transaction_state.append(managed) if not managed and self.is_dirty() and not forced: @@ -280,6 +284,8 @@ class BaseDatabaseWrapper(object): over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) """ + self.validate_no_atomic_block() + if self.transaction_state: del self.transaction_state[-1] else: @@ -305,10 +311,19 @@ class BaseDatabaseWrapper(object): """ Enable or disable autocommit. """ + self.validate_no_atomic_block() self.ensure_connection() self._set_autocommit(autocommit) self.autocommit = autocommit + def validate_no_atomic_block(self): + """ + Raise an error if an atomic block is active. + """ + if self.in_atomic_block: + raise TransactionManagementError( + "This is forbidden when an 'atomic' block is active.") + def abort(self): """ Roll back any ongoing transaction and clean the transaction state diff --git a/django/db/transaction.py b/django/db/transaction.py index 8126c18a70..eb9d85e274 100644 --- a/django/db/transaction.py +++ b/django/db/transaction.py @@ -367,6 +367,9 @@ def autocommit(using=None): this decorator is useful if you globally activated transaction management in your settings file and want the default behavior in some view functions. """ + warnings.warn("autocommit is deprecated in favor of set_autocommit.", + PendingDeprecationWarning, stacklevel=2) + def entering(using): enter_transaction_management(managed=False, using=using) @@ -382,6 +385,9 @@ def commit_on_success(using=None): a rollback is made. This is one of the most common ways to do transaction control in Web apps. """ + warnings.warn("commit_on_success is deprecated in favor of atomic.", + PendingDeprecationWarning, stacklevel=2) + def entering(using): enter_transaction_management(using=using) @@ -409,6 +415,9 @@ def commit_manually(using=None): own -- it's up to the user to call the commit and rollback functions themselves. """ + warnings.warn("commit_manually is deprecated in favor of set_autocommit.", + PendingDeprecationWarning, stacklevel=2) + def entering(using): enter_transaction_management(using=using) @@ -420,10 +429,15 @@ def commit_manually(using=None): def commit_on_success_unless_managed(using=None): """ Transitory API to preserve backwards-compatibility while refactoring. + + Once the legacy transaction management is fully deprecated, this should + simply be replaced by atomic. Until then, it's necessary to avoid making a + commit where Django didn't use to, since entering atomic in managed mode + triggers a commmit. """ connection = get_connection(using) - if connection.autocommit and not connection.in_atomic_block: - return commit_on_success(using) + if connection.autocommit or connection.in_atomic_block: + return atomic(using) else: def entering(using): pass diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 1c8618713a..6c13af7ae4 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -329,6 +329,10 @@ these changes. 1.8 --- +* The decorators and context managers ``django.db.transaction.autocommit``, + ``commit_on_success`` and ``commit_manually`` will be removed. See + :ref:`transactions-upgrading-from-1.5`. + * The :ttag:`cycle` and :ttag:`firstof` template tags will auto-escape their arguments. In 1.6 and 1.7, this behavior is provided by the version of these tags in the ``future`` template tag library. diff --git a/docs/releases/1.3-alpha-1.txt b/docs/releases/1.3-alpha-1.txt index ba8a4fc557..53d38a006b 100644 --- a/docs/releases/1.3-alpha-1.txt +++ b/docs/releases/1.3-alpha-1.txt @@ -105,16 +105,14 @@ you just won't get any of the nice new unittest2 features. Transaction context managers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Users of Python 2.5 and above may now use :ref:`transaction management functions -` as `context managers`_. For example:: +Users of Python 2.5 and above may now use transaction management functions as +`context managers`_. For example:: with transaction.autocommit(): # ... .. _context managers: http://docs.python.org/glossary.html#term-context-manager -For more information, see :ref:`transaction-management-functions`. - Configurable delete-cascade ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/releases/1.3.txt b/docs/releases/1.3.txt index 4c8dd2f81f..582bceffca 100644 --- a/docs/releases/1.3.txt +++ b/docs/releases/1.3.txt @@ -148,16 +148,14 @@ you just won't get any of the nice new unittest2 features. Transaction context managers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Users of Python 2.5 and above may now use :ref:`transaction management functions -` as `context managers`_. For example:: +Users of Python 2.5 and above may now use transaction management functions as +`context managers`_. For example:: with transaction.autocommit(): # ... .. _context managers: http://docs.python.org/glossary.html#term-context-manager -For more information, see :ref:`transaction-management-functions`. - Configurable delete-cascade ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index c55ef0ef38..cc3bf94ef5 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -39,7 +39,7 @@ should improve performance. The existing APIs were deprecated, and new APIs were introduced, as described in :doc:`/topics/db/transactions`. Please review carefully the list of :ref:`known backwards-incompatibilities -` to determine if you need to make changes in +` to determine if you need to make changes in your code. Persistent database connections @@ -163,7 +163,7 @@ Backwards incompatible changes in 1.6 * Database-level autocommit is enabled by default in Django 1.6. While this doesn't change the general spirit of Django's transaction management, there are a few known backwards-incompatibities, described in the :ref:`transaction - management docs `. You should review your code + management docs `. You should review your code to determine if you're affected. * In previous versions, database-level autocommit was only an option for @@ -256,6 +256,19 @@ Backwards incompatible changes in 1.6 Features deprecated in 1.6 ========================== +Transaction management APIs +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Transaction management was completely overhauled in Django 1.6, and the +current APIs are deprecated: + +- :func:`django.db.transaction.autocommit` +- :func:`django.db.transaction.commit_on_success` +- :func:`django.db.transaction.commit_manually` + +The reasons for this change and the upgrade path are described in the +:ref:`transactions documentation `. + Changes to :ttag:`cycle` and :ttag:`firstof` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 2a4cd306c6..91b2cf41b3 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -24,7 +24,7 @@ immediately committed to the database. :ref:`See below for details .. versionchanged:: 1.6 Previous version of Django featured :ref:`a more complicated default - behavior `. + behavior `. Tying transactions to HTTP requests ----------------------------------- @@ -89,7 +89,7 @@ Django provides a single API to control database transactions. database. If this argument isn't provided, Django uses the ``"default"`` database. - ``atomic`` is usable both as a decorator:: + ``atomic`` is usable both as a `decorator`_:: from django.db import transaction @@ -98,7 +98,7 @@ Django provides a single API to control database transactions. # This code executes inside a transaction. do_stuff() - and as a context manager:: + and as a `context manager`_:: from django.db import transaction @@ -110,6 +110,9 @@ Django provides a single API to control database transactions. # This code executes inside a transaction. do_more_stuff() + .. _decorator: http://docs.python.org/glossary.html#term-decorator + .. _context manager: http://docs.python.org/glossary.html#term-context-manager + Wrapping ``atomic`` in a try/except block allows for natural handling of integrity errors:: @@ -145,158 +148,116 @@ Django provides a single API to control database transactions. - releases or rolls back to the savepoint when exiting an inner block; - commits or rolls back the transaction when exiting the outermost block. -.. _transaction-management-functions: - -Controlling transaction management in views -=========================================== - -For most people, implicit request-based transactions work wonderfully. However, -if you need more fine-grained control over how transactions are managed, you can -use a set of functions in ``django.db.transaction`` to control transactions on a -per-function or per-code-block basis. - -These functions, described in detail below, can be used in two different ways: - -* As a decorator_ on a particular function. For example:: - - from django.db import transaction - - @transaction.commit_on_success - def viewfunc(request): - # ... - # this code executes inside a transaction - # ... - -* As a `context manager`_ around a particular block of code:: - - from django.db import transaction - - def viewfunc(request): - # ... - # this code executes using default transaction management - # ... - - with transaction.commit_on_success(): - # ... - # this code executes inside a transaction - # ... - -Both techniques work with all supported version of Python. +.. _topics-db-transactions-savepoints: -.. _decorator: http://docs.python.org/glossary.html#term-decorator -.. _context manager: http://docs.python.org/glossary.html#term-context-manager +Savepoints +========== -For maximum compatibility, all of the examples below show transactions using the -decorator syntax, but all of the follow functions may be used as context -managers, too. +A savepoint is a marker within a transaction that enables you to roll back +part of a transaction, rather than the full transaction. Savepoints are +available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using +the InnoDB storage engine) backends. Other backends provide the savepoint +functions, but they're empty operations -- they don't actually do anything. -.. note:: +Savepoints aren't especially useful if you are using autocommit, the default +behavior of Django. However, once you open a transaction with :func:`atomic`, +you build up a series of database operations awaiting a commit or rollback. If +you issue a rollback, the entire transaction is rolled back. Savepoints +provide the ability to perform a fine-grained rollback, rather than the full +rollback that would be performed by ``transaction.rollback()``. - Although the examples below use view functions as examples, these - decorators and context managers can be used anywhere in your code - that you need to deal with transactions. +.. versionchanged:: 1.6 -.. _topics-db-transactions-autocommit: +When the :func:`atomic` decorator is nested, it creates a savepoint to allow +partial commit or rollback. You're strongly encouraged to use :func:`atomic` +rather than the functions described below, but they're still part of the +public API, and there's no plan to deprecate them. -.. function:: autocommit +Each of these functions takes a ``using`` argument which should be the name of +a database for which the behavior applies. If no ``using`` argument is +provided then the ``"default"`` database is used. - Use the ``autocommit`` decorator to switch a view function to Django's - default commit behavior. +Savepoints are controlled by three methods on the transaction object: - Example:: +.. method:: transaction.savepoint(using=None) - from django.db import transaction + Creates a new savepoint. This marks a point in the transaction that + is known to be in a "good" state. - @transaction.autocommit - def viewfunc(request): - .... + Returns the savepoint ID (sid). - @transaction.autocommit(using="my_other_database") - def viewfunc2(request): - .... +.. method:: transaction.savepoint_commit(sid, using=None) - Within ``viewfunc()``, transactions will be committed as soon as you call - ``model.save()``, ``model.delete()``, or any other function that writes to - the database. ``viewfunc2()`` will have this same behavior, but for the - ``"my_other_database"`` connection. + Updates the savepoint to include any operations that have been performed + since the savepoint was created, or since the last commit. -.. function:: commit_on_success +.. method:: transaction.savepoint_rollback(sid, using=None) - Use the ``commit_on_success`` decorator to use a single transaction for all - the work done in a function:: + Rolls the transaction back to the last point at which the savepoint was + committed. - from django.db import transaction +The following example demonstrates the use of savepoints:: - @transaction.commit_on_success - def viewfunc(request): - .... + from django.db import transaction - @transaction.commit_on_success(using="my_other_database") - def viewfunc2(request): - .... + # open a transaction + @transaction.atomic + def viewfunc(request): - If the function returns successfully, then Django will commit all work done - within the function at that point. If the function raises an exception, - though, Django will roll back the transaction. + a.save() + # transaction now contains a.save() -.. function:: commit_manually + sid = transaction.savepoint() - Use the ``commit_manually`` decorator if you need full control over - transactions. It tells Django you'll be managing the transaction on your - own. + b.save() + # transaction now contains a.save() and b.save() - Whether you are writing or simply reading from the database, you must - ``commit()`` or ``rollback()`` explicitly or Django will raise a - :exc:`TransactionManagementError` exception. This is required when reading - from the database because ``SELECT`` statements may call functions which - modify tables, and thus it is impossible to know if any data has been - modified. + if want_to_keep_b: + transaction.savepoint_commit(sid) + # open transaction still contains a.save() and b.save() + else: + transaction.savepoint_rollback(sid) + # open transaction now contains only a.save() - Manual transaction management looks like this:: +Autocommit +========== - from django.db import transaction +.. _autocommit-details: - @transaction.commit_manually - def viewfunc(request): - ... - # You can commit/rollback however and whenever you want - transaction.commit() - ... +Why Django uses autocommit +-------------------------- - # But you've got to remember to do it yourself! - try: - ... - except: - transaction.rollback() - else: - transaction.commit() +In the SQL standards, each SQL query starts a transaction, unless one is +already in progress. Such transactions must then be committed or rolled back. - @transaction.commit_manually(using="my_other_database") - def viewfunc2(request): - .... +This isn't always convenient for application developers. To alleviate this +problem, most databases provide an autocommit mode. When autocommit is turned +on, each SQL query is wrapped in its own transaction. In other words, the +transaction is not only automatically started, but also automatically +committed. -.. _topics-db-transactions-requirements: +:pep:`249`, the Python Database API Specification v2.0, requires autocommit to +be initially turned off. Django overrides this default and turns autocommit +on. -Requirements for transaction handling -===================================== +To avoid this, you can :ref:`deactivate the transaction management +`, but it isn't recommended. -Django requires that every transaction that is opened is closed before the -completion of a request. +.. versionchanged:: 1.6 + Before Django 1.6, autocommit was turned off, and it was emulated by + forcing a commit after write operations in the ORM. -If you are using :func:`autocommit` (the default commit mode) or -:func:`commit_on_success`, this will be done for you automatically. However, -if you are manually managing transactions (using the :func:`commit_manually` -decorator), you must ensure that the transaction is either committed or rolled -back before a request is completed. +.. warning:: -This applies to all database operations, not just write operations. Even -if your transaction only reads from the database, the transaction must -be committed or rolled back before you complete a request. + If you're using the database API directly — for instance, you're running + SQL queries with ``cursor.execute()`` — be aware that autocommit is on, + and consider wrapping your operations in a transaction, with + :func:`atomic`, to ensure consistency. .. _managing-autocommit: Managing autocommit -=================== +------------------- .. versionadded:: 1.6 @@ -310,10 +271,17 @@ database connection, if you need to. These functions take a ``using`` argument which should be the name of a database. If it isn't provided, Django uses the ``"default"`` database. +Autocommit is initially turned on. If you turn it off, it's your +responsibility to restore it. + +:func:`atomic` requires autocommit to be turned on; it will raise an exception +if autocommit is off. Django will also refuse to turn autocommit off when an +:func:`atomic` block is active, because that would break atomicity. + .. _deactivate-transaction-management: -How to globally deactivate transaction management -================================================= +Deactivating transaction management +----------------------------------- Control freaks can totally disable all transaction management by setting :setting:`TRANSACTIONS_MANAGED` to ``True`` in the Django settings file. If @@ -328,71 +296,6 @@ something really strange. In almost all situations, you'll be better off using the default behavior, or the transaction middleware, and only modify selected functions as needed. -.. _topics-db-transactions-savepoints: - -Savepoints -========== - -A savepoint is a marker within a transaction that enables you to roll back -part of a transaction, rather than the full transaction. Savepoints are -available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using -the InnoDB storage engine) backends. Other backends provide the savepoint -functions, but they're empty operations -- they don't actually do anything. - -Savepoints aren't especially useful if you are using the default -``autocommit`` behavior of Django. However, if you are using -``commit_on_success`` or ``commit_manually``, each open transaction will build -up a series of database operations, awaiting a commit or rollback. If you -issue a rollback, the entire transaction is rolled back. Savepoints provide -the ability to perform a fine-grained rollback, rather than the full rollback -that would be performed by ``transaction.rollback()``. - -Each of these functions takes a ``using`` argument which should be the name of -a database for which the behavior applies. If no ``using`` argument is -provided then the ``"default"`` database is used. - -Savepoints are controlled by three methods on the transaction object: - -.. method:: transaction.savepoint(using=None) - - Creates a new savepoint. This marks a point in the transaction that - is known to be in a "good" state. - - Returns the savepoint ID (sid). - -.. method:: transaction.savepoint_commit(sid, using=None) - - Updates the savepoint to include any operations that have been performed - since the savepoint was created, or since the last commit. - -.. method:: transaction.savepoint_rollback(sid, using=None) - - Rolls the transaction back to the last point at which the savepoint was - committed. - -The following example demonstrates the use of savepoints:: - - from django.db import transaction - - @transaction.commit_manually - def viewfunc(request): - - a.save() - # open transaction now contains a.save() - sid = transaction.savepoint() - - b.save() - # open transaction now contains a.save() and b.save() - - if want_to_keep_b: - transaction.savepoint_commit(sid) - # open transaction still contains a.save() and b.save() - else: - transaction.savepoint_rollback(sid) - # open transaction now contains only a.save() - - transaction.commit() - Database-specific notes ======================= @@ -477,45 +380,57 @@ transaction. For example:: In this example, ``a.save()`` will not be undone in the case where ``b.save()`` raises an exception. -Under the hood -============== +.. _transactions-upgrading-from-1.5: -.. _autocommit-details: +Changes from Django 1.5 and earlier +=================================== -Details on autocommit ---------------------- +The features described below were deprecated in Django 1.6 and will be removed +in Django 1.8. They're documented in order to ease the migration to the new +transaction management APIs. -In the SQL standards, each SQL query starts a transaction, unless one is -already in progress. Such transactions must then be committed or rolled back. +Legacy APIs +----------- -This isn't always convenient for application developers. To alleviate this -problem, most databases provide an autocommit mode. When autocommit is turned -on, each SQL query is wrapped in its own transaction. In other words, the -transaction is not only automatically started, but also automatically -committed. +The following functions, defined in ``django.db.transaction``, provided a way +to control transactions on a per-function or per-code-block basis. They could +be used as decorators or as context managers, and they accepted a ``using`` +argument, exactly like :func:`atomic`. -:pep:`249`, the Python Database API Specification v2.0, requires autocommit to -be initially turned off. Django overrides this default and turns autocommit -on. +.. function:: autocommit -To avoid this, you can :ref:`deactivate the transaction management -`, but it isn't recommended. + Enable Django's default autocommit behavior. -.. versionchanged:: 1.6 - Before Django 1.6, autocommit was turned off, and it was emulated by - forcing a commit after write operations in the ORM. + Transactions will be committed as soon as you call ``model.save()``, + ``model.delete()``, or any other function that writes to the database. -.. warning:: +.. function:: commit_on_success - If you're using the database API directly — for instance, you're running - SQL queries with ``cursor.execute()`` — be aware that autocommit is on, - and consider wrapping your operations in a transaction to ensure - consistency. + Use a single transaction for all the work done in a function. + + If the function returns successfully, then Django will commit all work done + within the function at that point. If the function raises an exception, + though, Django will roll back the transaction. + +.. function:: commit_manually + + Tells Django you'll be managing the transaction on your own. + + Whether you are writing or simply reading from the database, you must + ``commit()`` or ``rollback()`` explicitly or Django will raise a + :exc:`TransactionManagementError` exception. This is required when reading + from the database because ``SELECT`` statements may call functions which + modify tables, and thus it is impossible to know if any data has been + modified. .. _transaction-states: -Transaction management states ------------------------------ +Transaction states +------------------ + +The three functions described above relied on a concept called "transaction +states". This mechanisme was deprecated in Django 1.6, but it's still +available until Django 1.8.. At any time, each database connection is in one of these two states: @@ -529,35 +444,80 @@ Django starts in auto mode. ``TransactionMiddleware``, Internally, Django keeps a stack of states. Activations and deactivations must be balanced. -For example, at the beginning of each HTTP request, ``TransactionMiddleware`` -switches to managed mode; at the end of the request, it commits or rollbacks, +For example, ``commit_on_success`` switches to managed mode when entering the +block of code it controls; when exiting the block, it commits or rollbacks, and switches back to auto mode. -.. admonition:: Nesting decorators / context managers +So :func:`commit_on_success` really has two effects: it changes the +transaction state and it defines an transaction block. Nesting will give the +expected results in terms of transaction state, but not in terms of +transaction semantics. Most often, the inner block will commit, breaking the +atomicity of the outer block. - :func:`commit_on_success` has two effects: it changes the transaction - state, and defines an atomic transaction block. +:func:`autocommit` and :func:`commit_manually` have similar limitations. - Nesting with :func:`autocommit` and :func:`commit_manually` will give the - expected results in terms of transaction state, but not in terms of - transaction semantics. Most often, the inner block will commit, breaking - the atomicity of the outer block. +API changes +----------- -Django currently doesn't provide any APIs to create transactions in auto mode. +Managing transactions +~~~~~~~~~~~~~~~~~~~~~ -.. _transactions-changes-from-1.5: +Starting with Django 1.6, :func:`atomic` is the only supported API for +defining a transaction. Unlike the deprecated APIs, it's nestable and always +guarantees atomicity. -Changes from Django 1.5 and earlier -=================================== +In most cases, it will be a drop-in replacement for :func:`commit_on_success`. -Since version 1.6, Django uses database-level autocommit in auto mode. +During the deprecation period, it's possible to use :func:`atomic` within +:func:`autocommit`, :func:`commit_on_success` or :func:`commit_manually`. +However, the reverse is forbidden, because nesting the old decorators / +context managers breaks atomicity. + +If you enter :func:`atomic` while you're in managed mode, it will trigger a +commit to start from a clean slate. + +Managing autocommit +~~~~~~~~~~~~~~~~~~~ + +Django 1.6 introduces an explicit :ref:`API for mananging autocommit +`. + +To disable autocommit temporarily, instead of:: + with transaction.commit_manually(): + # do stuff + +you should now use:: + + transaction.set_autocommit(autocommit=False) + try: + # do stuff + finally: + transaction.set_autocommit(autocommit=True) + +To enable autocommit temporarily, instead of:: + + with transaction.autocommit(): + # do stuff + +you should now use:: + + transaction.set_autocommit(autocommit=True) + try: + # do stuff + finally: + transaction.set_autocommit(autocommit=False) + +Backwards incompatibilities +--------------------------- + +Since version 1.6, Django uses database-level autocommit in auto mode. Previously, it implemented application-level autocommit by triggering a commit after each ORM write. -As a consequence, each database query (for instance, an -ORM read) started a transaction that lasted until the next ORM write. Such -"automatic transactions" no longer exist in Django 1.6. +As a consequence, each database query (for instance, an ORM read) started a +transaction that lasted until the next ORM write. Such "automatic +transactions" no longer exist in Django 1.6. There are four known scenarios where this is backwards-incompatible. @@ -565,7 +525,7 @@ Note that managed mode isn't affected at all. This section assumes auto mode. See the :ref:`description of modes ` above. Sequences of custom SQL queries -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you're executing several :ref:`custom SQL queries ` in a row, each one now runs in its own transaction, instead of sharing the @@ -577,20 +537,20 @@ usually followed by a call to ``transaction.commit_unless_managed``, which isn't necessary any more and should be removed. Select for update ------------------ +~~~~~~~~~~~~~~~~~ If you were relying on "automatic transactions" to provide locking between :meth:`~django.db.models.query.QuerySet.select_for_update` and a subsequent write operation — an extremely fragile design, but nonetheless possible — you -must wrap the relevant code in :func:`commit_on_success`. +must wrap the relevant code in :func:`atomic`. Using a high isolation level ----------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you were using the "repeatable read" isolation level or higher, and if you relied on "automatic transactions" to guarantee consistency between successive -reads, the new behavior is backwards-incompatible. To maintain consistency, -you must wrap such sequences in :func:`commit_on_success`. +reads, the new behavior might be backwards-incompatible. To enforce +consistency, you must wrap such sequences in :func:`atomic`. MySQL defaults to "repeatable read" and SQLite to "serializable"; they may be affected by this problem. @@ -602,10 +562,9 @@ PostgreSQL and Oracle default to "read committed" and aren't affected, unless you changed the isolation level. Using unsupported database features ------------------------------------ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With triggers, views, or functions, it's possible to make ORM reads result in database modifications. Django 1.5 and earlier doesn't deal with this case and it's theoretically possible to observe a different behavior after upgrading to -Django 1.6 or later. In doubt, use :func:`commit_on_success` to enforce -integrity. +Django 1.6 or later. In doubt, use :func:`atomic` to enforce integrity. diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 5c8a8955eb..51acbcb07f 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -522,7 +522,8 @@ class FkConstraintsTests(TransactionTestCase): """ When constraint checks are disabled, should be able to write bad data without IntegrityErrors. """ - with transaction.commit_manually(): + transaction.set_autocommit(autocommit=False) + try: # Create an Article. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) # Retrive it from the DB @@ -536,12 +537,15 @@ class FkConstraintsTests(TransactionTestCase): self.fail("IntegrityError should not have occurred.") finally: transaction.rollback() + finally: + transaction.set_autocommit(autocommit=True) def test_disable_constraint_checks_context_manager(self): """ When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors. """ - with transaction.commit_manually(): + transaction.set_autocommit(autocommit=False) + try: # Create an Article. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) # Retrive it from the DB @@ -554,12 +558,15 @@ class FkConstraintsTests(TransactionTestCase): self.fail("IntegrityError should not have occurred.") finally: transaction.rollback() + finally: + transaction.set_autocommit(autocommit=True) def test_check_constraints(self): """ Constraint checks should raise an IntegrityError when bad data is in the DB. """ - with transaction.commit_manually(): + try: + transaction.set_autocommit(autocommit=False) # Create an Article. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) # Retrive it from the DB @@ -572,6 +579,8 @@ class FkConstraintsTests(TransactionTestCase): connection.check_constraints() finally: transaction.rollback() + finally: + transaction.set_autocommit(autocommit=True) class ThreadTests(TestCase): diff --git a/tests/fixtures_model_package/tests.py b/tests/fixtures_model_package/tests.py index d147fe68a7..894a6c7fde 100644 --- a/tests/fixtures_model_package/tests.py +++ b/tests/fixtures_model_package/tests.py @@ -25,7 +25,8 @@ class SampleTestCase(TestCase): class TestNoInitialDataLoading(TransactionTestCase): def test_syncdb(self): - with transaction.commit_manually(): + transaction.set_autocommit(autocommit=False) + try: Book.objects.all().delete() management.call_command( @@ -35,6 +36,9 @@ class TestNoInitialDataLoading(TransactionTestCase): ) self.assertQuerysetEqual(Book.objects.all(), []) transaction.rollback() + finally: + transaction.set_autocommit(autocommit=True) + def test_flush(self): # Test presence of fixture (flush called by TransactionTestCase) @@ -45,7 +49,8 @@ class TestNoInitialDataLoading(TransactionTestCase): lambda a: a.name ) - with transaction.commit_manually(): + transaction.set_autocommit(autocommit=False) + try: management.call_command( 'flush', verbosity=0, @@ -55,6 +60,8 @@ class TestNoInitialDataLoading(TransactionTestCase): ) self.assertQuerysetEqual(Book.objects.all(), []) transaction.rollback() + finally: + transaction.set_autocommit(autocommit=True) class FixtureTestCase(TestCase): diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py index 61dc4460df..f965dd81ac 100644 --- a/tests/fixtures_regress/tests.py +++ b/tests/fixtures_regress/tests.py @@ -684,5 +684,8 @@ class TestTicket11101(TransactionTestCase): @skipUnlessDBFeature('supports_transactions') def test_ticket_11101(self): """Test that fixtures can be rolled back (ticket #11101).""" - ticket_11101 = transaction.commit_manually(self.ticket_11101) - ticket_11101() + transaction.set_autocommit(autocommit=False) + try: + self.ticket_11101() + finally: + transaction.set_autocommit(autocommit=True) diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index e704fce342..7e26037967 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -24,6 +24,8 @@ from django.utils.encoding import force_str from django.utils.six.moves import xrange from django.utils.unittest import expectedFailure +from transactions.tests import IgnorePendingDeprecationWarningsMixin + from .models import Band @@ -670,11 +672,12 @@ class ETagGZipMiddlewareTest(TestCase): self.assertNotEqual(gzip_etag, nogzip_etag) -class TransactionMiddlewareTest(TransactionTestCase): +class TransactionMiddlewareTest(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): """ Test the transaction middleware. """ def setUp(self): + super(TransactionMiddlewareTest, self).setUp() self.request = HttpRequest() self.request.META = { 'SERVER_NAME': 'testserver', @@ -686,6 +689,7 @@ class TransactionMiddlewareTest(TransactionTestCase): def tearDown(self): transaction.abort() + super(TransactionMiddlewareTest, self).tearDown() def test_request(self): TransactionMiddleware().process_request(self.request) diff --git a/tests/transactions/tests.py b/tests/transactions/tests.py index 14252dd6dc..d6cfd8ae95 100644 --- a/tests/transactions/tests.py +++ b/tests/transactions/tests.py @@ -1,9 +1,10 @@ from __future__ import absolute_import import sys +import warnings from django.db import connection, transaction, IntegrityError -from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature +from django.test import TransactionTestCase, skipUnlessDBFeature from django.utils import six from django.utils.unittest import skipUnless @@ -158,7 +159,69 @@ class AtomicInsideTransactionTests(AtomicTests): self.atomic.__exit__(*sys.exc_info()) -class TransactionTests(TransactionTestCase): +class AtomicInsideLegacyTransactionManagementTests(AtomicTests): + + def setUp(self): + transaction.enter_transaction_management() + + def tearDown(self): + # The tests access the database after exercising 'atomic', making the + # connection dirty; a rollback is required to make it clean. + transaction.rollback() + transaction.leave_transaction_management() + + +@skipUnless(connection.features.uses_savepoints, + "'atomic' requires transactions and savepoints.") +class AtomicErrorsTests(TransactionTestCase): + + def test_atomic_requires_autocommit(self): + transaction.set_autocommit(autocommit=False) + try: + with self.assertRaises(transaction.TransactionManagementError): + with transaction.atomic(): + pass + finally: + transaction.set_autocommit(autocommit=True) + + def test_atomic_prevents_disabling_autocommit(self): + autocommit = transaction.get_autocommit() + with transaction.atomic(): + with self.assertRaises(transaction.TransactionManagementError): + transaction.set_autocommit(autocommit=not autocommit) + # Make sure autocommit wasn't changed. + self.assertEqual(connection.autocommit, autocommit) + + def test_atomic_prevents_calling_transaction_methods(self): + with transaction.atomic(): + with self.assertRaises(transaction.TransactionManagementError): + transaction.commit() + with self.assertRaises(transaction.TransactionManagementError): + transaction.rollback() + + def test_atomic_prevents_calling_transaction_management_methods(self): + with transaction.atomic(): + with self.assertRaises(transaction.TransactionManagementError): + transaction.enter_transaction_management() + with self.assertRaises(transaction.TransactionManagementError): + transaction.leave_transaction_management() + + +class IgnorePendingDeprecationWarningsMixin(object): + + def setUp(self): + super(IgnorePendingDeprecationWarningsMixin, self).setUp() + self.catch_warnings = warnings.catch_warnings() + self.catch_warnings.__enter__() + warnings.filterwarnings("ignore", category=PendingDeprecationWarning) + + def tearDown(self): + self.catch_warnings.__exit__(*sys.exc_info()) + super(IgnorePendingDeprecationWarningsMixin, self).tearDown() + + +class TransactionTests(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): + def create_a_reporter_then_fail(self, first, last): a = Reporter(first_name=first, last_name=last) a.save() @@ -313,7 +376,7 @@ class TransactionTests(TransactionTestCase): ) -class TransactionRollbackTests(TransactionTestCase): +class TransactionRollbackTests(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): def execute_bad_sql(self): cursor = connection.cursor() cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") @@ -330,7 +393,7 @@ class TransactionRollbackTests(TransactionTestCase): self.assertRaises(IntegrityError, execute_bad_sql) transaction.rollback() -class TransactionContextManagerTests(TransactionTestCase): +class TransactionContextManagerTests(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): def create_reporter_and_fail(self): Reporter.objects.create(first_name="Bob", last_name="Holtzman") raise Exception diff --git a/tests/transactions_regress/tests.py b/tests/transactions_regress/tests.py index e86db4d0aa..d5ee62da5e 100644 --- a/tests/transactions_regress/tests.py +++ b/tests/transactions_regress/tests.py @@ -6,10 +6,12 @@ from django.test import TransactionTestCase, skipUnlessDBFeature from django.test.utils import override_settings from django.utils.unittest import skipIf, skipUnless, expectedFailure +from transactions.tests import IgnorePendingDeprecationWarningsMixin + from .models import Mod, M2mA, M2mB -class TestTransactionClosing(TransactionTestCase): +class TestTransactionClosing(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): """ Tests to make sure that transactions are properly closed when they should be, and aren't left pending after operations @@ -166,7 +168,7 @@ class TestTransactionClosing(TransactionTestCase): (connection.settings_dict['NAME'] == ':memory:' or not connection.settings_dict['NAME']), 'Test uses multiple connections, but in-memory sqlite does not support this') -class TestNewConnection(TransactionTestCase): +class TestNewConnection(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): """ Check that new connections don't have special behaviour. """ @@ -211,7 +213,7 @@ class TestNewConnection(TransactionTestCase): @skipUnless(connection.vendor == 'postgresql', "This test only valid for PostgreSQL") -class TestPostgresAutocommitAndIsolation(TransactionTestCase): +class TestPostgresAutocommitAndIsolation(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): """ Tests to make sure psycopg2's autocommit mode and isolation level is restored after entering and leaving transaction management. @@ -292,7 +294,7 @@ class TestPostgresAutocommitAndIsolation(TransactionTestCase): self.assertTrue(connection.autocommit) -class TestManyToManyAddTransaction(TransactionTestCase): +class TestManyToManyAddTransaction(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): def test_manyrelated_add_commit(self): "Test for https://code.djangoproject.com/ticket/16818" a = M2mA.objects.create() @@ -307,7 +309,7 @@ class TestManyToManyAddTransaction(TransactionTestCase): self.assertEqual(a.others.count(), 1) -class SavepointTest(TransactionTestCase): +class SavepointTest(IgnorePendingDeprecationWarningsMixin, TransactionTestCase): @skipIf(connection.vendor == 'sqlite', "SQLite doesn't support savepoints in managed mode") -- cgit v1.3 From ac37ed21b3d66dde1748f6edf3279656b0267b70 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Wed, 6 Mar 2013 11:12:24 +0100 Subject: Deprecated TransactionMiddleware and TRANSACTIONS_MANAGED. Replaced them with per-database options, for proper multi-db support. Also toned down the recommendation to tie transactions to HTTP requests. Thanks Jeremy for sharing his experience. --- django/core/handlers/base.py | 12 +++- django/db/backends/__init__.py | 4 +- django/db/utils.py | 8 +++ django/middleware/transaction.py | 13 +++- docs/internals/deprecation.txt | 11 +++- docs/ref/middleware.txt | 4 ++ docs/ref/settings.txt | 30 +++++++++ docs/releases/1.6.txt | 8 ++- docs/topics/db/transactions.txt | 134 +++++++++++++++++++++++++++------------ tests/handlers/tests.py | 30 ++++++++- tests/handlers/urls.py | 9 ++- tests/handlers/views.py | 17 +++++ 12 files changed, 223 insertions(+), 57 deletions(-) create mode 100644 tests/handlers/views.py (limited to 'docs/internals') diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py index 0dcd9794c7..5327ce5891 100644 --- a/django/core/handlers/base.py +++ b/django/core/handlers/base.py @@ -6,10 +6,10 @@ import types from django import http from django.conf import settings -from django.core import exceptions from django.core import urlresolvers from django.core import signals from django.core.exceptions import MiddlewareNotUsed, PermissionDenied +from django.db import connections, transaction from django.utils.encoding import force_text from django.utils.module_loading import import_by_path from django.utils import six @@ -65,6 +65,13 @@ class BaseHandler(object): # as a flag for initialization being complete. self._request_middleware = request_middleware + def make_view_atomic(self, view): + if getattr(view, 'transactions_per_request', True): + for db in connections.all(): + if db.settings_dict['ATOMIC_REQUESTS']: + view = transaction.atomic(using=db.alias)(view) + return view + def get_response(self, request): "Returns an HttpResponse object for the given HttpRequest" try: @@ -101,8 +108,9 @@ class BaseHandler(object): break if response is None: + wrapped_callback = self.make_view_atomic(callback) try: - response = callback(request, *callback_args, **callback_kwargs) + response = wrapped_callback(request, *callback_args, **callback_kwargs) except Exception as e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index 68551aad51..2cf75bd528 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -104,7 +104,7 @@ class BaseDatabaseWrapper(object): conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() - if not settings.TRANSACTIONS_MANAGED: + if self.settings_dict['AUTOCOMMIT']: self.set_autocommit() connection_created.send(sender=self.__class__, connection=self) @@ -299,7 +299,7 @@ class BaseDatabaseWrapper(object): if self.transaction_state: managed = self.transaction_state[-1] else: - managed = settings.TRANSACTIONS_MANAGED + managed = not self.settings_dict['AUTOCOMMIT'] if self._dirty: self.rollback() diff --git a/django/db/utils.py b/django/db/utils.py index 71b89f93fb..936b42039d 100644 --- a/django/db/utils.py +++ b/django/db/utils.py @@ -2,6 +2,7 @@ from functools import wraps import os import pkgutil from threading import local +import warnings from django.conf import settings from django.core.exceptions import ImproperlyConfigured @@ -158,6 +159,13 @@ class ConnectionHandler(object): except KeyError: raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) + conn.setdefault('ATOMIC_REQUESTS', False) + if settings.TRANSACTIONS_MANAGED: + warnings.warn( + "TRANSACTIONS_MANAGED is deprecated. Use AUTOCOMMIT instead.", + PendingDeprecationWarning, stacklevel=2) + conn.setdefault('AUTOCOMMIT', False) + conn.setdefault('AUTOCOMMIT', True) conn.setdefault('ENGINE', 'django.db.backends.dummy') if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']: conn['ENGINE'] = 'django.db.backends.dummy' diff --git a/django/middleware/transaction.py b/django/middleware/transaction.py index 35f765d99f..95cc9a21f3 100644 --- a/django/middleware/transaction.py +++ b/django/middleware/transaction.py @@ -1,4 +1,7 @@ -from django.db import transaction +import warnings + +from django.core.exceptions import MiddlewareNotUsed +from django.db import connection, transaction class TransactionMiddleware(object): """ @@ -7,6 +10,14 @@ class TransactionMiddleware(object): commit, the commit is done when a successful response is created. If an exception happens, the database is rolled back. """ + + def __init__(self): + warnings.warn( + "TransactionMiddleware is deprecated in favor of ATOMIC_REQUESTS.", + PendingDeprecationWarning, stacklevel=2) + if connection.settings_dict['ATOMIC_REQUESTS']: + raise MiddlewareNotUsed + def process_request(self, request): """Enters transaction management""" transaction.enter_transaction_management() diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 6c13af7ae4..19675801e4 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -329,9 +329,14 @@ these changes. 1.8 --- -* The decorators and context managers ``django.db.transaction.autocommit``, - ``commit_on_success`` and ``commit_manually`` will be removed. See - :ref:`transactions-upgrading-from-1.5`. +* The following transaction management APIs will be removed: + + - ``TransactionMiddleware``, + - the decorators and context managers ``autocommit``, ``commit_on_success``, + and ``commit_manually``, + - the ``TRANSACTIONS_MANAGED`` setting. + + Upgrade paths are described in :ref:`transactions-upgrading-from-1.5`. * The :ttag:`cycle` and :ttag:`firstof` template tags will auto-escape their arguments. In 1.6 and 1.7, this behavior is provided by the version of these diff --git a/docs/ref/middleware.txt b/docs/ref/middleware.txt index 1e6e57f720..20bb2fb751 100644 --- a/docs/ref/middleware.txt +++ b/docs/ref/middleware.txt @@ -205,6 +205,10 @@ Transaction middleware .. class:: TransactionMiddleware +.. versionchanged:: 1.6 + ``TransactionMiddleware`` is deprecated. The documentation of transactions + contains :ref:`upgrade instructions `. + Binds commit and rollback of the default database to the request/response phase. If a view function runs successfully, a commit is done. If it fails with an exception, a rollback is done. diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index 0cd141bcef..2b80527d8b 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -408,6 +408,30 @@ SQLite. This can be configured using the following:: For other database backends, or more complex SQLite configurations, other options will be required. The following inner options are available. +.. setting:: DATABASE-ATOMIC_REQUESTS + +ATOMIC_REQUESTS +~~~~~~~~~~~~~~~ + +.. versionadded:: 1.6 + +Default: ``False`` + +Set this to ``True`` to wrap each HTTP request in a transaction on this +database. See :ref:`tying-transactions-to-http-requests`. + +.. setting:: DATABASE-AUTOCOMMIT + +AUTOCOMMIT +~~~~~~~~~~ + +.. versionadded:: 1.6 + +Default: ``True`` + +Set this to ``False`` if you want to :ref:`disable Django's transaction +management ` and implement your own. + .. setting:: DATABASE-ENGINE ENGINE @@ -1807,6 +1831,12 @@ to ensure your processes are running in the correct environment. TRANSACTIONS_MANAGED -------------------- +.. deprecated:: 1.6 + + This setting was deprecated because its name is very misleading. Use the + :setting:`AUTOCOMMIT ` key in :setting:`DATABASES` + entries instead. + Default: ``False`` Set this to ``True`` if you want to :ref:`disable Django's transaction diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index cc3bf94ef5..a1fe69229c 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -262,9 +262,11 @@ Transaction management APIs Transaction management was completely overhauled in Django 1.6, and the current APIs are deprecated: -- :func:`django.db.transaction.autocommit` -- :func:`django.db.transaction.commit_on_success` -- :func:`django.db.transaction.commit_manually` +- ``django.middleware.transaction.TransactionMiddleware`` +- ``django.db.transaction.autocommit`` +- ``django.db.transaction.commit_on_success`` +- ``django.db.transaction.commit_manually`` +- the ``TRANSACTIONS_MANAGED`` setting The reasons for this change and the upgrade path are described in the :ref:`transactions documentation `. diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 91b2cf41b3..37a369a02f 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -26,45 +26,61 @@ immediately committed to the database. :ref:`See below for details Previous version of Django featured :ref:`a more complicated default behavior `. +.. _tying-transactions-to-http-requests: + Tying transactions to HTTP requests ----------------------------------- -The recommended way to handle transactions in Web requests is to tie them to -the request and response phases via Django's ``TransactionMiddleware``. +A common way to handle transactions on the web is to wrap each request in a +transaction. Set :setting:`ATOMIC_REQUESTS ` to +``True`` in the configuration of each database for which you want to enable +this behavior. It works like this. When a request starts, Django starts a transaction. If the -response is produced without problems, Django commits any pending transactions. -If the view function produces an exception, Django rolls back any pending -transactions. - -To activate this feature, just add the ``TransactionMiddleware`` middleware to -your :setting:`MIDDLEWARE_CLASSES` setting:: - - MIDDLEWARE_CLASSES = ( - 'django.middleware.cache.UpdateCacheMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.transaction.TransactionMiddleware', - 'django.middleware.cache.FetchFromCacheMiddleware', - ) - -The order is quite important. The transaction middleware applies not only to -view functions, but also for all middleware modules that come after it. So if -you use the session middleware after the transaction middleware, session -creation will be part of the transaction. - -The various cache middlewares are an exception: ``CacheMiddleware``, -:class:`~django.middleware.cache.UpdateCacheMiddleware`, and -:class:`~django.middleware.cache.FetchFromCacheMiddleware` are never affected. -Even when using database caching, Django's cache backend uses its own database -connection internally. - -.. note:: - - The ``TransactionMiddleware`` only affects the database aliased - as "default" within your :setting:`DATABASES` setting. If you are using - multiple databases and want transaction control over databases other than - "default", you will need to write your own transaction middleware. +response is produced without problems, Django commits the transaction. If the +view function produces an exception, Django rolls back the transaction. +Middleware always runs outside of this transaction. + +You may perfom partial commits and rollbacks in your view code, typically with +the :func:`atomic` context manager. However, at the end of the view, either +all the changes will be committed, or none of them. + +To disable this behavior for a specific view, you must set the +``transactions_per_request`` attribute of the view function itself to +``False``, like this:: + + def my_view(request): + do_stuff() + my_view.transactions_per_request = False + +.. warning:: + + While the simplicity of this transaction model is appealing, it also makes it + inefficient when traffic increases. Opening a transaction for every view has + some overhead. The impact on performance depends on the query patterns of your + application and on how well your database handles locking. + +.. admonition:: Per-request transactions and streaming responses + + When a view returns a :class:`~django.http.StreamingHttpResponse`, reading + the contents of the response will often execute code to generate the + content. Since the view has already returned, such code runs outside of + the transaction. + + Generally speaking, it isn't advisable to write to the database while + generating a streaming response, since there's no sensible way to handle + errors after starting to send the response. + +In practice, this feature simply wraps every view function in the :func:`atomic` +decorator described below. + +Note that only the execution of your view in enclosed in the transactions. +Middleware run outside of the transaction, and so does the rendering of +template responses. + +.. versionchanged:: 1.6 + Django used to provide this feature via ``TransactionMiddleware``, which is + now deprecated. Controlling transactions explicitly ----------------------------------- @@ -283,18 +299,20 @@ if autocommit is off. Django will also refuse to turn autocommit off when an Deactivating transaction management ----------------------------------- -Control freaks can totally disable all transaction management by setting -:setting:`TRANSACTIONS_MANAGED` to ``True`` in the Django settings file. If -you do this, Django won't enable autocommit. You'll get the regular behavior -of the underlying database library. +You can totally disable Django's transaction management for a given database +by setting :setting:`AUTOCOMMIT ` to ``False`` in its +configuration. If you do this, Django won't enable autocommit, and won't +perform any commits. You'll get the regular behavior of the underlying +database library. This requires you to commit explicitly every transaction, even those started by Django or by third-party libraries. Thus, this is best used in situations where you want to run your own transaction-controlling middleware or do something really strange. -In almost all situations, you'll be better off using the default behavior, or -the transaction middleware, and only modify selected functions as needed. +.. versionchanged:: 1.6 + This used to be controlled by the ``TRANSACTIONS_MANAGED`` setting. + Database-specific notes ======================= @@ -459,6 +477,35 @@ atomicity of the outer block. API changes ----------- +Transaction middleware +~~~~~~~~~~~~~~~~~~~~~~ + +In Django 1.6, ``TransactionMiddleware`` is deprecated and replaced +:setting:`ATOMIC_REQUESTS `. While the general +behavior is the same, there are a few differences. + +With the transaction middleware, it was still possible to switch to autocommit +or to commit explicitly in a view. Since :func:`atomic` guarantees atomicity, +this isn't allowed any longer. + +To avoid wrapping a particular view in a transaction, instead of:: + + @transaction.autocommit + def my_view(request): + do_stuff() + +you must now use this pattern:: + + def my_view(request): + do_stuff() + my_view.transactions_per_request = False + +The transaction middleware applied not only to view functions, but also to +middleware modules that come after it. For instance, if you used the session +middleware after the transaction middleware, session creation was part of the +transaction. :setting:`ATOMIC_REQUESTS ` only +applies to the view itself. + Managing transactions ~~~~~~~~~~~~~~~~~~~~~ @@ -508,6 +555,13 @@ you should now use:: finally: transaction.set_autocommit(autocommit=False) +Disabling transaction management +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Instead of setting ``TRANSACTIONS_MANAGED = True``, set the ``AUTOCOMMIT`` key +to ``False`` in the configuration of each database, as explained in :ref +:`deactivate-transaction-management`. + Backwards incompatibilities --------------------------- diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py index 6eb9bd23fe..3680eecdd2 100644 --- a/tests/handlers/tests.py +++ b/tests/handlers/tests.py @@ -1,9 +1,8 @@ from django.core.handlers.wsgi import WSGIHandler from django.core.signals import request_started, request_finished -from django.db import close_old_connections -from django.test import RequestFactory, TestCase +from django.db import close_old_connections, connection +from django.test import RequestFactory, TestCase, TransactionTestCase from django.test.utils import override_settings -from django.utils import six class HandlerTests(TestCase): @@ -37,6 +36,31 @@ class HandlerTests(TestCase): self.assertEqual(response.status_code, 400) +class TransactionsPerRequestTests(TransactionTestCase): + urls = 'handlers.urls' + + def test_no_transaction(self): + response = self.client.get('/in_transaction/') + self.assertContains(response, 'False') + + def test_auto_transaction(self): + old_atomic_requests = connection.settings_dict['ATOMIC_REQUESTS'] + try: + connection.settings_dict['ATOMIC_REQUESTS'] = True + response = self.client.get('/in_transaction/') + finally: + connection.settings_dict['ATOMIC_REQUESTS'] = old_atomic_requests + self.assertContains(response, 'True') + + def test_no_auto_transaction(self): + old_atomic_requests = connection.settings_dict['ATOMIC_REQUESTS'] + try: + connection.settings_dict['ATOMIC_REQUESTS'] = True + response = self.client.get('/not_in_transaction/') + finally: + connection.settings_dict['ATOMIC_REQUESTS'] = old_atomic_requests + self.assertContains(response, 'False') + class SignalsTests(TestCase): urls = 'handlers.urls' diff --git a/tests/handlers/urls.py b/tests/handlers/urls.py index 8570f04696..29858055ab 100644 --- a/tests/handlers/urls.py +++ b/tests/handlers/urls.py @@ -1,9 +1,12 @@ from __future__ import unicode_literals from django.conf.urls import patterns, url -from django.http import HttpResponse, StreamingHttpResponse + +from . import views urlpatterns = patterns('', - url(r'^regular/$', lambda request: HttpResponse(b"regular content")), - url(r'^streaming/$', lambda request: StreamingHttpResponse([b"streaming", b" ", b"content"])), + url(r'^regular/$', views.regular), + url(r'^streaming/$', views.streaming), + url(r'^in_transaction/$', views.in_transaction), + url(r'^not_in_transaction/$', views.not_in_transaction), ) diff --git a/tests/handlers/views.py b/tests/handlers/views.py new file mode 100644 index 0000000000..22d9ea4c7d --- /dev/null +++ b/tests/handlers/views.py @@ -0,0 +1,17 @@ +from __future__ import unicode_literals + +from django.db import connection +from django.http import HttpResponse, StreamingHttpResponse + +def regular(request): + return HttpResponse(b"regular content") + +def streaming(request): + return StreamingHttpResponse([b"streaming", b" ", b"content"]) + +def in_transaction(request): + return HttpResponse(str(connection.in_atomic_block)) + +def not_in_transaction(request): + return HttpResponse(str(connection.in_atomic_block)) +not_in_transaction.transactions_per_request = False -- cgit v1.3