Permalink
Browse files

A large number of stylistic cleanups across django/db/

  • Loading branch information...
1 parent 0b69a75 commit 03d9566e0df45c72bffa99fe244a92f0279da56f @alex alex committed Jul 8, 2013
Showing with 382 additions and 194 deletions.
  1. +15 −7 django/db/__init__.py
  2. +1 −0 django/db/backends/__init__.py
  3. +4 −3 django/db/backends/creation.py
  4. +12 −1 django/db/backends/dummy/base.py
  5. +10 −3 django/db/backends/mysql/base.py
  6. +1 −1 django/db/backends/mysql/client.py
  7. +6 −0 django/db/backends/mysql/compiler.py
  8. +19 −18 django/db/backends/mysql/creation.py
  9. +1 −1 django/db/backends/mysql/introspection.py
  10. +1 −0 django/db/backends/mysql/validation.py
  11. +11 −9 django/db/backends/oracle/base.py
  12. +1 −1 django/db/backends/oracle/client.py
  13. +5 −0 django/db/backends/oracle/compiler.py
  14. +27 −25 django/db/backends/oracle/creation.py
  15. +9 −6 django/db/backends/oracle/introspection.py
  16. +8 −2 django/db/backends/postgresql_psycopg2/base.py
  17. +1 −1 django/db/backends/postgresql_psycopg2/client.py
  18. +19 −19 django/db/backends/postgresql_psycopg2/creation.py
  19. +3 −3 django/db/backends/postgresql_psycopg2/introspection.py
  20. +3 −3 django/db/backends/postgresql_psycopg2/operations.py
  21. +2 −1 django/db/backends/postgresql_psycopg2/version.py
  22. +16 −1 django/db/backends/sqlite3/base.py
  23. +1 −1 django/db/backends/sqlite3/client.py
  24. +25 −24 django/db/backends/sqlite3/creation.py
  25. +8 −5 django/db/backends/sqlite3/introspection.py
  26. +14 −5 django/db/backends/util.py
  27. +1 −0 django/db/models/__init__.py
  28. +9 −0 django/db/models/aggregates.py
  29. +4 −5 django/db/models/base.py
  30. +3 −0 django/db/models/expressions.py
  31. +37 −11 django/db/models/fields/__init__.py
  32. +6 −1 django/db/models/fields/files.py
  33. +1 −0 django/db/models/fields/proxy.py
  34. +9 −10 django/db/models/fields/related.py
  35. +3 −0 django/db/models/fields/subclassing.py
  36. +2 −0 django/db/models/loading.py
  37. +2 −1 django/db/models/manager.py
  38. +10 −10 django/db/models/query.py
  39. +4 −2 django/db/models/query_utils.py
  40. +1 −0 django/db/models/related.py
  41. +7 −0 django/db/models/sql/aggregates.py
  42. +6 −1 django/db/models/sql/compiler.py
  43. +4 −3 django/db/models/sql/datastructures.py
  44. +3 −1 django/db/models/sql/expressions.py
  45. +5 −5 django/db/models/sql/query.py
  46. +9 −2 django/db/models/sql/subqueries.py
  47. +7 −2 django/db/models/sql/where.py
  48. +26 −0 django/db/transaction.py
View
@@ -1,20 +1,25 @@
import warnings
from django.core import signals
-from django.db.utils import (DEFAULT_DB_ALIAS,
- DataError, OperationalError, IntegrityError, InternalError,
- ProgrammingError, NotSupportedError, DatabaseError,
- InterfaceError, Error,
- load_backend, ConnectionHandler, ConnectionRouter)
+from django.db.utils import (DEFAULT_DB_ALIAS, DataError, OperationalError,
+ IntegrityError, InternalError, ProgrammingError, NotSupportedError,
+ DatabaseError, InterfaceError, Error, load_backend,
+ ConnectionHandler, ConnectionRouter)
from django.utils.functional import cached_property
-__all__ = ('backend', 'connection', 'connections', 'router', 'DatabaseError',
- 'IntegrityError', 'DEFAULT_DB_ALIAS')
+
+__all__ = [
+ 'backend', 'connection', 'connections', 'router', 'DatabaseError',
+ 'IntegrityError', 'InternalError', 'ProgrammingError', 'DataError',
+ 'NotSupportedError', 'Error', 'InterfaceError', 'OperationalError',
+ 'DEFAULT_DB_ALIAS'
+]
connections = ConnectionHandler()
router = ConnectionRouter()
+
# `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
# for backend bits.
@@ -70,6 +75,7 @@ def __delattr__(self, name):
backend = DefaultBackendProxy()
+
def close_connection(**kwargs):
warnings.warn(
"close_connection is superseded by close_old_connections.",
@@ -83,12 +89,14 @@ def close_connection(**kwargs):
transaction.abort(conn)
connections[conn].close()
+
# Register an event to reset saved queries when a Django request is started.
def reset_queries(**kwargs):
for conn in connections.all():
conn.queries = []
signals.request_started.connect(reset_queries)
+
# Register an event to reset transaction state and close connections past
# their lifetime. NB: abort() doesn't do anything outside of a transaction.
def close_old_connections(**kwargs):
@@ -1167,6 +1167,7 @@ def modify_insert_params(self, placeholders, params):
'name type_code display_size internal_size precision scale null_ok'
)
+
class BaseDatabaseIntrospection(object):
"""
This class encapsulates all backend-specific introspection utilities
@@ -251,12 +251,13 @@ def sql_remove_table_constraints(self, model, references_to_delete, style):
r_col = model._meta.get_field(f.rel.field_name).column
r_name = '%s_refs_%s_%s' % (
col, r_col, self._digest(table, r_table))
- output.append('%s %s %s %s;' % \
- (style.SQL_KEYWORD('ALTER TABLE'),
+ output.append('%s %s %s %s;' % (
+ style.SQL_KEYWORD('ALTER TABLE'),
style.SQL_TABLE(qn(table)),
style.SQL_KEYWORD(self.connection.ops.drop_foreignkey_sql()),
style.SQL_FIELD(qn(truncate_name(
- r_name, self.connection.ops.max_name_length())))))
+ r_name, self.connection.ops.max_name_length())))
+ ))
del references_to_delete[model]
return output
@@ -8,40 +8,51 @@
"""
from django.core.exceptions import ImproperlyConfigured
-from django.db.backends import *
+from django.db.backends import (BaseDatabaseOperations, BaseDatabaseClient,
+ BaseDatabaseIntrospection, BaseDatabaseWrapper, BaseDatabaseFeatures,
+ BaseDatabaseValidation)
from django.db.backends.creation import BaseDatabaseCreation
+
def complain(*args, **kwargs):
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
"Please supply the ENGINE value. Check "
"settings documentation for more details.")
+
def ignore(*args, **kwargs):
pass
+
class DatabaseError(Exception):
pass
+
class IntegrityError(DatabaseError):
pass
+
class DatabaseOperations(BaseDatabaseOperations):
quote_name = complain
+
class DatabaseClient(BaseDatabaseClient):
runshell = complain
+
class DatabaseCreation(BaseDatabaseCreation):
create_test_db = ignore
destroy_test_db = ignore
+
class DatabaseIntrospection(BaseDatabaseIntrospection):
get_table_list = complain
get_table_description = complain
get_relations = complain
get_indexes = complain
get_key_columns = complain
+
class DatabaseWrapper(BaseDatabaseWrapper):
operators = {}
# Override the base class implementations with null
@@ -36,8 +36,9 @@
pytz = None
from django.conf import settings
-from django.db import utils
-from django.db.backends import *
+from django.db import (utils, BaseDatabaseFeatures, BaseDatabaseOperations,
+ BaseDatabaseWrapper)
+from django.db.backends import util
from django.db.backends.mysql.client import DatabaseClient
from django.db.backends.mysql.creation import DatabaseCreation
from django.db.backends.mysql.introspection import DatabaseIntrospection
@@ -57,13 +58,15 @@
# It's impossible to import datetime_or_None directly from MySQLdb.times
parse_datetime = conversions[FIELD_TYPE.DATETIME]
+
def parse_datetime_with_timezone_support(value):
dt = parse_datetime(value)
# Confirm that dt is naive before overwriting its tzinfo.
if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
dt = dt.replace(tzinfo=timezone.utc)
return dt
+
def adapt_datetime_with_timezone_support(value, conv):
# Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
if settings.USE_TZ:
@@ -98,6 +101,7 @@ def adapt_datetime_with_timezone_support(value, conv):
# http://dev.mysql.com/doc/refman/5.0/en/news.html .
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
+
# MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
# MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
# point is to raise Warnings as exceptions, this can be done with the Python
@@ -148,6 +152,7 @@ def __getattr__(self, attr):
def __iter__(self):
return iter(self.cursor)
+
class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
update_can_self_select = False
@@ -204,6 +209,7 @@ def has_zoneinfo_database(self):
cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1")
return cursor.fetchone() is not None
+
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "django.db.backends.mysql.compiler"
@@ -319,7 +325,7 @@ def sequence_reset_by_name_sql(self, style, sequences):
# Truncate already resets the AUTO_INCREMENT field from
# MySQL version 5.0.13 onwards. Refs #16961.
if self.connection.mysql_version < (5, 0, 13):
- return ["%s %s %s %s %s;" % \
+ return ["%s %s %s %s %s;" %
(style.SQL_KEYWORD('ALTER'),
style.SQL_KEYWORD('TABLE'),
style.SQL_TABLE(self.quote_name(sequence['table'])),
@@ -373,6 +379,7 @@ def bulk_insert_sql(self, fields, num_values):
items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
return "VALUES " + ", ".join([items_sql] * num_values)
+
class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'mysql'
operators = {
@@ -3,6 +3,7 @@
from django.db.backends import BaseDatabaseClient
+
class DatabaseClient(BaseDatabaseClient):
executable_name = 'mysql'
@@ -37,4 +38,3 @@ def runshell(self):
sys.exit(os.system(" ".join(args)))
else:
os.execvp(self.executable_name, args)
-
@@ -22,20 +22,26 @@ def as_subquery_condition(self, alias, columns, qn):
sql, params = self.as_sql()
return '(%s) IN (%s)' % (', '.join(['%s.%s' % (qn(alias), qn2(column)) for column in columns]), sql), params
+
class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
pass
+
class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
pass
+
class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
pass
+
class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
pass
+
class SQLDateCompiler(compiler.SQLDateCompiler, SQLCompiler):
pass
+
class SQLDateTimeCompiler(compiler.SQLDateTimeCompiler, SQLCompiler):
pass
@@ -1,34 +1,35 @@
from django.db.backends.creation import BaseDatabaseCreation
+
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
- 'AutoField': 'integer AUTO_INCREMENT',
- 'BinaryField': 'longblob',
- 'BooleanField': 'bool',
- 'CharField': 'varchar(%(max_length)s)',
+ 'AutoField': 'integer AUTO_INCREMENT',
+ 'BinaryField': 'longblob',
+ 'BooleanField': 'bool',
+ 'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
- 'DateField': 'date',
- 'DateTimeField': 'datetime',
- 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
- 'FileField': 'varchar(%(max_length)s)',
- 'FilePathField': 'varchar(%(max_length)s)',
- 'FloatField': 'double precision',
- 'IntegerField': 'integer',
- 'BigIntegerField': 'bigint',
- 'IPAddressField': 'char(15)',
+ 'DateField': 'date',
+ 'DateTimeField': 'datetime',
+ 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
+ 'FileField': 'varchar(%(max_length)s)',
+ 'FilePathField': 'varchar(%(max_length)s)',
+ 'FloatField': 'double precision',
+ 'IntegerField': 'integer',
+ 'BigIntegerField': 'bigint',
+ 'IPAddressField': 'char(15)',
'GenericIPAddressField': 'char(39)',
- 'NullBooleanField': 'bool',
- 'OneToOneField': 'integer',
+ 'NullBooleanField': 'bool',
+ 'OneToOneField': 'integer',
'PositiveIntegerField': 'integer UNSIGNED',
'PositiveSmallIntegerField': 'smallint UNSIGNED',
- 'SlugField': 'varchar(%(max_length)s)',
+ 'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
- 'TextField': 'longtext',
- 'TimeField': 'time',
+ 'TextField': 'longtext',
+ 'TimeField': 'time',
}
def sql_table_creation_suffix(self):
@@ -7,6 +7,7 @@
foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
+
class DatabaseIntrospection(BaseDatabaseIntrospection):
data_types_reverse = {
FIELD_TYPE.BLOB: 'TextField',
@@ -116,4 +117,3 @@ def get_indexes(self, cursor, table_name):
continue
indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': not bool(row[1])}
return indexes
-
@@ -1,5 +1,6 @@
from django.db.backends import BaseDatabaseValidation
+
class DatabaseValidation(BaseDatabaseValidation):
def validate_field(self, errors, opts, f):
"""
Oops, something went wrong. Retry.

0 comments on commit 03d9566

Please sign in to comment.