Permalink
Browse files

Reordered methods in database wrappers.

* Grouped related methods together -- with banner comments :/
* Described which methods are intended to be implemented in backends.
* Added docstrings.
* Used the same order in all wrappers.
  • Loading branch information...
1 parent c5a25c2 commit d63e55039d42c2ba8bb6c8f8d133ede085b60969 @aaugustin aaugustin committed Mar 2, 2013
@@ -48,19 +48,19 @@ class DatabaseWrapper(BaseDatabaseWrapper):
# implementations. Anything that tries to actually
# do something raises complain; anything that tries
# to rollback or undo something raises ignore.
+ _cursor = complain
_commit = complain
_rollback = ignore
- enter_transaction_management = complain
- leave_transaction_management = ignore
+ _close = ignore
+ _savepoint = ignore
+ _savepoint_commit = complain
+ _savepoint_rollback = ignore
+ _enter_transaction_management = complain
+ _leave_transaction_management = ignore
set_dirty = complain
set_clean = complain
commit_unless_managed = complain
rollback_unless_managed = ignore
- savepoint = ignore
- savepoint_commit = complain
- savepoint_rollback = ignore
- close = ignore
- cursor = complain
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
@@ -439,29 +439,12 @@ def create_cursor(self):
cursor = self.connection.cursor()
return CursorWrapper(cursor)
- def is_usable(self):
- try:
- self.connection.ping()
- except DatabaseError:
- return False
- else:
- return True
-
def _rollback(self):
try:
BaseDatabaseWrapper._rollback(self)
except Database.NotSupportedError:
pass
- @cached_property
- def mysql_version(self):
- with self.temporary_connection():
- server_info = self.connection.get_server_info()
- match = server_version_re.match(server_info)
- if not match:
- raise Exception('Unable to determine MySQL version from version string %r' % server_info)
- return tuple([int(x) for x in match.groups()])
-
def disable_constraint_checking(self):
"""
Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True,
@@ -510,3 +493,20 @@ def check_constraints(self, table_names=None):
% (table_name, bad_row[0],
table_name, column_name, bad_row[1],
referenced_table_name, referenced_column_name))
+
+ def is_usable(self):
+ try:
+ self.connection.ping()
+ except DatabaseError:
+ return False
+ else:
+ return True
+
+ @cached_property
+ def mysql_version(self):
+ with self.temporary_connection():
+ server_info = self.connection.get_server_info()
+ match = server_version_re.match(server_info)
+ if not match:
+ raise Exception('Unable to determine MySQL version from version string %r' % server_info)
+ return tuple([int(x) for x in match.groups()])
@@ -515,14 +515,6 @@ def __init__(self, *args, **kwargs):
self.introspection = DatabaseIntrospection(self)
self.validation = BaseDatabaseValidation(self)
- def check_constraints(self, table_names=None):
- """
- To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
- are returned to deferred.
- """
- self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
- self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
-
def _connect_string(self):
settings_dict = self.settings_dict
if not settings_dict['HOST'].strip():
@@ -536,9 +528,6 @@ def _connect_string(self):
return "%s/%s@%s" % (settings_dict['USER'],
settings_dict['PASSWORD'], dsn)
- def create_cursor(self):
- return FormatStylePlaceholderCursor(self.connection)
-
def get_connection_params(self):
conn_params = self.settings_dict['OPTIONS'].copy()
if 'use_returning_into' in conn_params:
@@ -598,21 +587,8 @@ def init_connection_state(self):
# stmtcachesize is available only in 4.3.2 and up.
pass
- def is_usable(self):
- try:
- if hasattr(self.connection, 'ping'): # Oracle 10g R2 and higher
- self.connection.ping()
- else:
- # Use a cx_Oracle cursor directly, bypassing Django's utilities.
- self.connection.cursor().execute("SELECT 1 FROM DUAL")
- except DatabaseError:
- return False
- else:
- return True
-
- # Oracle doesn't support savepoint commits. Ignore them.
- def _savepoint_commit(self, sid):
- pass
+ def create_cursor(self):
+ return FormatStylePlaceholderCursor(self.connection)
def _commit(self):
if self.connection is not None:
@@ -632,6 +608,30 @@ def _commit(self):
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
+ # Oracle doesn't support savepoint commits. Ignore them.
+ def _savepoint_commit(self, sid):
+ pass
+
+ def check_constraints(self, table_names=None):
+ """
+ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
+ are returned to deferred.
+ """
+ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
+ self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
+
+ def is_usable(self):
+ try:
+ if hasattr(self.connection, 'ping'): # Oracle 10g R2 and higher
+ self.connection.ping()
+ else:
+ # Use a cx_Oracle cursor directly, bypassing Django's utilities.
+ self.connection.cursor().execute("SELECT 1 FROM DUAL")
+ except DatabaseError:
+ return False
+ else:
+ return True
+
@cached_property
def oracle_version(self):
with self.temporary_connection():
@@ -91,40 +91,6 @@ def __init__(self, *args, **kwargs):
self.introspection = DatabaseIntrospection(self)
self.validation = BaseDatabaseValidation(self)
- def check_constraints(self, table_names=None):
- """
- To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
- are returned to deferred.
- """
- self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
- self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
-
- def close(self):
- self.validate_thread_sharing()
- if self.connection is None:
- return
-
- try:
- self.connection.close()
- self.connection = None
- except Database.Error:
- # In some cases (database restart, network connection lost etc...)
- # the connection to the database is lost without giving Django a
- # notification. If we don't set self.connection to None, the error
- # will occur a every request.
- self.connection = None
- logger.warning('psycopg2 error while closing the connection.',
- exc_info=sys.exc_info()
- )
- raise
- finally:
- self.set_clean()
-
- @cached_property
- def pg_version(self):
- with self.temporary_connection():
- return get_version(self.connection)
-
def get_connection_params(self):
settings_dict = self.settings_dict
if not settings_dict['NAME']:
@@ -177,14 +143,26 @@ def create_cursor(self):
cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
return cursor
- def is_usable(self):
+ def close(self):
+ self.validate_thread_sharing()
+ if self.connection is None:
+ return
+
try:
- # Use a psycopg cursor directly, bypassing Django's utilities.
- self.connection.cursor().execute("SELECT 1")
- except DatabaseError:
- return False
- else:
- return True
+ self.connection.close()
+ self.connection = None
+ except Database.Error:
+ # In some cases (database restart, network connection lost etc...)
+ # the connection to the database is lost without giving Django a
+ # notification. If we don't set self.connection to None, the error
+ # will occur a every request.
+ self.connection = None
+ logger.warning('psycopg2 error while closing the connection.',
+ exc_info=sys.exc_info()
+ )
+ raise
+ finally:
+ self.set_clean()
def _enter_transaction_management(self, managed):
"""
@@ -222,3 +200,25 @@ def set_dirty(self):
if ((self.transaction_state and self.transaction_state[-1]) or
not self.features.uses_autocommit):
super(DatabaseWrapper, self).set_dirty()
+
+ def check_constraints(self, table_names=None):
+ """
+ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
+ are returned to deferred.
+ """
+ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
+ self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
+
+ def is_usable(self):
+ try:
+ # Use a psycopg cursor directly, bypassing Django's utilities.
+ self.connection.cursor().execute("SELECT 1")
+ except DatabaseError:
+ return False
+ else:
+ return True
+
+ @cached_property
+ def pg_version(self):
+ with self.temporary_connection():
+ return get_version(self.connection)
@@ -347,8 +347,13 @@ def init_connection_state(self):
def create_cursor(self):
return self.connection.cursor(factory=SQLiteCursorWrapper)
- def is_usable(self):
- return True
+ def close(self):
+ self.validate_thread_sharing()
+ # If database is in memory, closing the connection destroys the
+ # database. To prevent accidental data loss, ignore close requests on
+ # an in-memory db.
+ if self.settings_dict['NAME'] != ":memory:":
+ BaseDatabaseWrapper.close(self)
def check_constraints(self, table_names=None):
"""
@@ -384,13 +389,9 @@ def check_constraints(self, table_names=None):
% (table_name, bad_row[0], table_name, column_name, bad_row[1],
referenced_table_name, referenced_column_name))
- def close(self):
- self.validate_thread_sharing()
- # If database is in memory, closing the connection destroys the
- # database. To prevent accidental data loss, ignore close requests on
- # an in-memory db.
- if self.settings_dict['NAME'] != ":memory:":
- BaseDatabaseWrapper.close(self)
+ def is_usable(self):
+ return True
+
FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')

0 comments on commit d63e550

Please sign in to comment.