Skip to content

Commit

Permalink
A large number of stylistic cleanups across django/db/
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Jul 8, 2013
1 parent 0b69a75 commit 03d9566
Show file tree
Hide file tree
Showing 48 changed files with 382 additions and 194 deletions.
22 changes: 15 additions & 7 deletions django/db/__init__.py
@@ -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.

Expand Down Expand Up @@ -70,6 +75,7 @@ def __delattr__(self, name):

backend = DefaultBackendProxy()


def close_connection(**kwargs):
warnings.warn(
"close_connection is superseded by close_old_connections.",
Expand All @@ -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):
Expand Down
1 change: 1 addition & 0 deletions django/db/backends/__init__.py
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions django/db/backends/creation.py
Expand Up @@ -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

Expand Down
13 changes: 12 additions & 1 deletion django/db/backends/dummy/base.py
Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions django/db/backends/mysql/base.py
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"

Expand Down Expand Up @@ -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'])),
Expand Down Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion django/db/backends/mysql/client.py
Expand Up @@ -3,6 +3,7 @@

from django.db.backends import BaseDatabaseClient


class DatabaseClient(BaseDatabaseClient):
executable_name = 'mysql'

Expand Down Expand Up @@ -37,4 +38,3 @@ def runshell(self):
sys.exit(os.system(" ".join(args)))
else:
os.execvp(self.executable_name, args)

6 changes: 6 additions & 0 deletions django/db/backends/mysql/compiler.py
Expand Up @@ -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
37 changes: 19 additions & 18 deletions django/db/backends/mysql/creation.py
@@ -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):
Expand Down
2 changes: 1 addition & 1 deletion django/db/backends/mysql/introspection.py
Expand Up @@ -7,6 +7,7 @@

foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")


class DatabaseIntrospection(BaseDatabaseIntrospection):
data_types_reverse = {
FIELD_TYPE.BLOB: 'TextField',
Expand Down Expand Up @@ -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 change: 1 addition & 0 deletions django/db/backends/mysql/validation.py
@@ -1,5 +1,6 @@
from django.db.backends import BaseDatabaseValidation


class DatabaseValidation(BaseDatabaseValidation):
def validate_field(self, errors, opts, f):
"""
Expand Down

0 comments on commit 03d9566

Please sign in to comment.