Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

A large number of stylistic cleanups across django/db/

  • Loading branch information...
commit 03d9566e0df45c72bffa99fe244a92f0279da56f 1 parent 0b69a75
Alex Gaynor authored July 08, 2013

Showing 48 changed files with 382 additions and 194 deletions. Show diff stats Hide diff stats

  1. 22  django/db/__init__.py
  2. 1  django/db/backends/__init__.py
  3. 7  django/db/backends/creation.py
  4. 13  django/db/backends/dummy/base.py
  5. 13  django/db/backends/mysql/base.py
  6. 2  django/db/backends/mysql/client.py
  7. 6  django/db/backends/mysql/compiler.py
  8. 37  django/db/backends/mysql/creation.py
  9. 2  django/db/backends/mysql/introspection.py
  10. 1  django/db/backends/mysql/validation.py
  11. 20  django/db/backends/oracle/base.py
  12. 2  django/db/backends/oracle/client.py
  13. 5  django/db/backends/oracle/compiler.py
  14. 52  django/db/backends/oracle/creation.py
  15. 15  django/db/backends/oracle/introspection.py
  16. 10  django/db/backends/postgresql_psycopg2/base.py
  17. 2  django/db/backends/postgresql_psycopg2/client.py
  18. 38  django/db/backends/postgresql_psycopg2/creation.py
  19. 6  django/db/backends/postgresql_psycopg2/introspection.py
  20. 6  django/db/backends/postgresql_psycopg2/operations.py
  21. 3  django/db/backends/postgresql_psycopg2/version.py
  22. 17  django/db/backends/sqlite3/base.py
  23. 2  django/db/backends/sqlite3/client.py
  24. 49  django/db/backends/sqlite3/creation.py
  25. 13  django/db/backends/sqlite3/introspection.py
  26. 19  django/db/backends/util.py
  27. 1  django/db/models/__init__.py
  28. 9  django/db/models/aggregates.py
  29. 9  django/db/models/base.py
  30. 3  django/db/models/expressions.py
  31. 48  django/db/models/fields/__init__.py
  32. 7  django/db/models/fields/files.py
  33. 1  django/db/models/fields/proxy.py
  34. 19  django/db/models/fields/related.py
  35. 3  django/db/models/fields/subclassing.py
  36. 2  django/db/models/loading.py
  37. 3  django/db/models/manager.py
  38. 20  django/db/models/query.py
  39. 6  django/db/models/query_utils.py
  40. 1  django/db/models/related.py
  41. 7  django/db/models/sql/aggregates.py
  42. 7  django/db/models/sql/compiler.py
  43. 7  django/db/models/sql/datastructures.py
  44. 4  django/db/models/sql/expressions.py
  45. 10  django/db/models/sql/query.py
  46. 11  django/db/models/sql/subqueries.py
  47. 9  django/db/models/sql/where.py
  48. 26  django/db/transaction.py
22  django/db/__init__.py
... ...
@@ -1,20 +1,25 @@
1 1
 import warnings
2 2
 
3 3
 from django.core import signals
4  
-from django.db.utils import (DEFAULT_DB_ALIAS,
5  
-    DataError, OperationalError, IntegrityError, InternalError,
6  
-    ProgrammingError, NotSupportedError, DatabaseError,
7  
-    InterfaceError, Error,
8  
-    load_backend, ConnectionHandler, ConnectionRouter)
  4
+from django.db.utils import (DEFAULT_DB_ALIAS, DataError, OperationalError,
  5
+    IntegrityError, InternalError, ProgrammingError, NotSupportedError,
  6
+    DatabaseError, InterfaceError, Error, load_backend,
  7
+    ConnectionHandler, ConnectionRouter)
9 8
 from django.utils.functional import cached_property
10 9
 
11  
-__all__ = ('backend', 'connection', 'connections', 'router', 'DatabaseError',
12  
-    'IntegrityError', 'DEFAULT_DB_ALIAS')
  10
+
  11
+__all__ = [
  12
+    'backend', 'connection', 'connections', 'router', 'DatabaseError',
  13
+    'IntegrityError', 'InternalError', 'ProgrammingError', 'DataError',
  14
+    'NotSupportedError', 'Error', 'InterfaceError', 'OperationalError',
  15
+    'DEFAULT_DB_ALIAS'
  16
+]
13 17
 
14 18
 connections = ConnectionHandler()
15 19
 
16 20
 router = ConnectionRouter()
17 21
 
  22
+
18 23
 # `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
19 24
 # for backend bits.
20 25
 
@@ -70,6 +75,7 @@ def __delattr__(self, name):
70 75
 
71 76
 backend = DefaultBackendProxy()
72 77
 
  78
+
73 79
 def close_connection(**kwargs):
74 80
     warnings.warn(
75 81
         "close_connection is superseded by close_old_connections.",
@@ -83,12 +89,14 @@ def close_connection(**kwargs):
83 89
         transaction.abort(conn)
84 90
         connections[conn].close()
85 91
 
  92
+
86 93
 # Register an event to reset saved queries when a Django request is started.
87 94
 def reset_queries(**kwargs):
88 95
     for conn in connections.all():
89 96
         conn.queries = []
90 97
 signals.request_started.connect(reset_queries)
91 98
 
  99
+
92 100
 # Register an event to reset transaction state and close connections past
93 101
 # their lifetime. NB: abort() doesn't do anything outside of a transaction.
94 102
 def close_old_connections(**kwargs):
1  django/db/backends/__init__.py
@@ -1167,6 +1167,7 @@ def modify_insert_params(self, placeholders, params):
1167 1167
     'name type_code display_size internal_size precision scale null_ok'
1168 1168
 )
1169 1169
 
  1170
+
1170 1171
 class BaseDatabaseIntrospection(object):
1171 1172
     """
1172 1173
     This class encapsulates all backend-specific introspection utilities
7  django/db/backends/creation.py
@@ -251,12 +251,13 @@ def sql_remove_table_constraints(self, model, references_to_delete, style):
251 251
             r_col = model._meta.get_field(f.rel.field_name).column
252 252
             r_name = '%s_refs_%s_%s' % (
253 253
                 col, r_col, self._digest(table, r_table))
254  
-            output.append('%s %s %s %s;' % \
255  
-                (style.SQL_KEYWORD('ALTER TABLE'),
  254
+            output.append('%s %s %s %s;' % (
  255
+                style.SQL_KEYWORD('ALTER TABLE'),
256 256
                 style.SQL_TABLE(qn(table)),
257 257
                 style.SQL_KEYWORD(self.connection.ops.drop_foreignkey_sql()),
258 258
                 style.SQL_FIELD(qn(truncate_name(
259  
-                    r_name, self.connection.ops.max_name_length())))))
  259
+                    r_name, self.connection.ops.max_name_length())))
  260
+            ))
260 261
         del references_to_delete[model]
261 262
         return output
262 263
 
13  django/db/backends/dummy/base.py
@@ -8,33 +8,43 @@
8 8
 """
9 9
 
10 10
 from django.core.exceptions import ImproperlyConfigured
11  
-from django.db.backends import *
  11
+from django.db.backends import (BaseDatabaseOperations, BaseDatabaseClient,
  12
+    BaseDatabaseIntrospection, BaseDatabaseWrapper, BaseDatabaseFeatures,
  13
+    BaseDatabaseValidation)
12 14
 from django.db.backends.creation import BaseDatabaseCreation
13 15
 
  16
+
14 17
 def complain(*args, **kwargs):
15 18
     raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
16 19
                                "Please supply the ENGINE value. Check "
17 20
                                "settings documentation for more details.")
18 21
 
  22
+
19 23
 def ignore(*args, **kwargs):
20 24
     pass
21 25
 
  26
+
22 27
 class DatabaseError(Exception):
23 28
     pass
24 29
 
  30
+
25 31
 class IntegrityError(DatabaseError):
26 32
     pass
27 33
 
  34
+
28 35
 class DatabaseOperations(BaseDatabaseOperations):
29 36
     quote_name = complain
30 37
 
  38
+
31 39
 class DatabaseClient(BaseDatabaseClient):
32 40
     runshell = complain
33 41
 
  42
+
34 43
 class DatabaseCreation(BaseDatabaseCreation):
35 44
     create_test_db = ignore
36 45
     destroy_test_db = ignore
37 46
 
  47
+
38 48
 class DatabaseIntrospection(BaseDatabaseIntrospection):
39 49
     get_table_list = complain
40 50
     get_table_description = complain
@@ -42,6 +52,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
42 52
     get_indexes = complain
43 53
     get_key_columns = complain
44 54
 
  55
+
45 56
 class DatabaseWrapper(BaseDatabaseWrapper):
46 57
     operators = {}
47 58
     # Override the base class implementations with null
13  django/db/backends/mysql/base.py
@@ -36,8 +36,9 @@
36 36
     pytz = None
37 37
 
38 38
 from django.conf import settings
39  
-from django.db import utils
40  
-from django.db.backends import *
  39
+from django.db import (utils, BaseDatabaseFeatures, BaseDatabaseOperations,
  40
+    BaseDatabaseWrapper)
  41
+from django.db.backends import util
41 42
 from django.db.backends.mysql.client import DatabaseClient
42 43
 from django.db.backends.mysql.creation import DatabaseCreation
43 44
 from django.db.backends.mysql.introspection import DatabaseIntrospection
@@ -57,6 +58,7 @@
57 58
 # It's impossible to import datetime_or_None directly from MySQLdb.times
58 59
 parse_datetime = conversions[FIELD_TYPE.DATETIME]
59 60
 
  61
+
60 62
 def parse_datetime_with_timezone_support(value):
61 63
     dt = parse_datetime(value)
62 64
     # Confirm that dt is naive before overwriting its tzinfo.
@@ -64,6 +66,7 @@ def parse_datetime_with_timezone_support(value):
64 66
         dt = dt.replace(tzinfo=timezone.utc)
65 67
     return dt
66 68
 
  69
+
67 70
 def adapt_datetime_with_timezone_support(value, conv):
68 71
     # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
69 72
     if settings.USE_TZ:
@@ -98,6 +101,7 @@ def adapt_datetime_with_timezone_support(value, conv):
98 101
 # http://dev.mysql.com/doc/refman/5.0/en/news.html .
99 102
 server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
100 103
 
  104
+
101 105
 # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
102 106
 # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
103 107
 # point is to raise Warnings as exceptions, this can be done with the Python
@@ -148,6 +152,7 @@ def __getattr__(self, attr):
148 152
     def __iter__(self):
149 153
         return iter(self.cursor)
150 154
 
  155
+
151 156
 class DatabaseFeatures(BaseDatabaseFeatures):
152 157
     empty_fetchmany_value = ()
153 158
     update_can_self_select = False
@@ -204,6 +209,7 @@ def has_zoneinfo_database(self):
204 209
         cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1")
205 210
         return cursor.fetchone() is not None
206 211
 
  212
+
207 213
 class DatabaseOperations(BaseDatabaseOperations):
208 214
     compiler_module = "django.db.backends.mysql.compiler"
209 215
 
@@ -319,7 +325,7 @@ def sequence_reset_by_name_sql(self, style, sequences):
319 325
         # Truncate already resets the AUTO_INCREMENT field from
320 326
         # MySQL version 5.0.13 onwards. Refs #16961.
321 327
         if self.connection.mysql_version < (5, 0, 13):
322  
-            return ["%s %s %s %s %s;" % \
  328
+            return ["%s %s %s %s %s;" %
323 329
                     (style.SQL_KEYWORD('ALTER'),
324 330
                     style.SQL_KEYWORD('TABLE'),
325 331
                     style.SQL_TABLE(self.quote_name(sequence['table'])),
@@ -373,6 +379,7 @@ def bulk_insert_sql(self, fields, num_values):
373 379
         items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
374 380
         return "VALUES " + ", ".join([items_sql] * num_values)
375 381
 
  382
+
376 383
 class DatabaseWrapper(BaseDatabaseWrapper):
377 384
     vendor = 'mysql'
378 385
     operators = {
2  django/db/backends/mysql/client.py
@@ -3,6 +3,7 @@
3 3
 
4 4
 from django.db.backends import BaseDatabaseClient
5 5
 
  6
+
6 7
 class DatabaseClient(BaseDatabaseClient):
7 8
     executable_name = 'mysql'
8 9
 
@@ -37,4 +38,3 @@ def runshell(self):
37 38
             sys.exit(os.system(" ".join(args)))
38 39
         else:
39 40
             os.execvp(self.executable_name, args)
40  
-
6  django/db/backends/mysql/compiler.py
@@ -22,20 +22,26 @@ def as_subquery_condition(self, alias, columns, qn):
22 22
         sql, params = self.as_sql()
23 23
         return '(%s) IN (%s)' % (', '.join(['%s.%s' % (qn(alias), qn2(column)) for column in columns]), sql), params
24 24
 
  25
+
25 26
 class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
26 27
     pass
27 28
 
  29
+
28 30
 class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
29 31
     pass
30 32
 
  33
+
31 34
 class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
32 35
     pass
33 36
 
  37
+
34 38
 class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
35 39
     pass
36 40
 
  41
+
37 42
 class SQLDateCompiler(compiler.SQLDateCompiler, SQLCompiler):
38 43
     pass
39 44
 
  45
+
40 46
 class SQLDateTimeCompiler(compiler.SQLDateTimeCompiler, SQLCompiler):
41 47
     pass
37  django/db/backends/mysql/creation.py
... ...
@@ -1,34 +1,35 @@
1 1
 from django.db.backends.creation import BaseDatabaseCreation
2 2
 
  3
+
3 4
 class DatabaseCreation(BaseDatabaseCreation):
4 5
     # This dictionary maps Field objects to their associated MySQL column
5 6
     # types, as strings. Column-type strings can contain format strings; they'll
6 7
     # be interpolated against the values of Field.__dict__ before being output.
7 8
     # If a column type is set to None, it won't be included in the output.
8 9
     data_types = {
9  
-        'AutoField':         'integer AUTO_INCREMENT',
10  
-        'BinaryField':       'longblob',
11  
-        'BooleanField':      'bool',
12  
-        'CharField':         'varchar(%(max_length)s)',
  10
+        'AutoField': 'integer AUTO_INCREMENT',
  11
+        'BinaryField': 'longblob',
  12
+        'BooleanField': 'bool',
  13
+        'CharField': 'varchar(%(max_length)s)',
13 14
         'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
14  
-        'DateField':         'date',
15  
-        'DateTimeField':     'datetime',
16  
-        'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)',
17  
-        'FileField':         'varchar(%(max_length)s)',
18  
-        'FilePathField':     'varchar(%(max_length)s)',
19  
-        'FloatField':        'double precision',
20  
-        'IntegerField':      'integer',
21  
-        'BigIntegerField':   'bigint',
22  
-        'IPAddressField':    'char(15)',
  15
+        'DateField': 'date',
  16
+        'DateTimeField': 'datetime',
  17
+        'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
  18
+        'FileField': 'varchar(%(max_length)s)',
  19
+        'FilePathField': 'varchar(%(max_length)s)',
  20
+        'FloatField': 'double precision',
  21
+        'IntegerField': 'integer',
  22
+        'BigIntegerField': 'bigint',
  23
+        'IPAddressField': 'char(15)',
23 24
         'GenericIPAddressField': 'char(39)',
24  
-        'NullBooleanField':  'bool',
25  
-        'OneToOneField':     'integer',
  25
+        'NullBooleanField': 'bool',
  26
+        'OneToOneField': 'integer',
26 27
         'PositiveIntegerField': 'integer UNSIGNED',
27 28
         'PositiveSmallIntegerField': 'smallint UNSIGNED',
28  
-        'SlugField':         'varchar(%(max_length)s)',
  29
+        'SlugField': 'varchar(%(max_length)s)',
29 30
         'SmallIntegerField': 'smallint',
30  
-        'TextField':         'longtext',
31  
-        'TimeField':         'time',
  31
+        'TextField': 'longtext',
  32
+        'TimeField': 'time',
32 33
     }
33 34
 
34 35
     def sql_table_creation_suffix(self):
2  django/db/backends/mysql/introspection.py
@@ -7,6 +7,7 @@
7 7
 
8 8
 foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
9 9
 
  10
+
10 11
 class DatabaseIntrospection(BaseDatabaseIntrospection):
11 12
     data_types_reverse = {
12 13
         FIELD_TYPE.BLOB: 'TextField',
@@ -116,4 +117,3 @@ def get_indexes(self, cursor, table_name):
116 117
                 continue
117 118
             indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': not bool(row[1])}
118 119
         return indexes
119  
-
1  django/db/backends/mysql/validation.py
... ...
@@ -1,5 +1,6 @@
1 1
 from django.db.backends import BaseDatabaseValidation
2 2
 
  3
+
3 4
 class DatabaseValidation(BaseDatabaseValidation):
4 5
     def validate_field(self, errors, opts, f):
5 6
         """
20  django/db/backends/oracle/base.py
@@ -7,11 +7,12 @@
7 7
 
8 8
 import decimal
9 9
 import re
  10
+import platform
10 11
 import sys
11 12
 import warnings
12 13
 
  14
+
13 15
 def _setup_environment(environ):
14  
-    import platform
15 16
     # Cygwin requires some special voodoo to set the environment variables
16 17
     # properly so that Oracle will see them.
17 18
     if platform.system().upper().startswith('CYGWIN'):
@@ -90,6 +91,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
90 91
     supports_tablespaces = True
91 92
     supports_sequence_reset = False
92 93
 
  94
+
93 95
 class DatabaseOperations(BaseDatabaseOperations):
94 96
     compiler_module = "django.db.backends.oracle.compiler"
95 97
 
@@ -308,7 +310,7 @@ def quote_name(self, name):
308 310
         # Oracle puts the query text into a (query % args) construct, so % signs
309 311
         # in names need to be escaped. The '%%' will be collapsed back to '%' at
310 312
         # that stage so we aren't really making the name longer here.
311  
-        name = name.replace('%','%%')
  313
+        name = name.replace('%', '%%')
312 314
         return name.upper()
313 315
 
314 316
     def random_function_sql(self):
@@ -758,7 +760,7 @@ def __init__(self, connection):
758 760
 
759 761
     def _format_params(self, params):
760 762
         try:
761  
-            return dict((k,OracleParam(v, self, True)) for k,v in params.items())
  763
+            return dict((k, OracleParam(v, self, True)) for k, v in params.items())
762 764
         except AttributeError:
763 765
             return tuple([OracleParam(p, self, True) for p in params])
764 766
 
@@ -778,12 +780,12 @@ def _guess_input_sizes(self, params_list):
778 780
                 for i, value in enumerate(params):
779 781
                     if value.input_size:
780 782
                         sizes[i] = value.input_size
781  
-            self.setinputsizes(*sizes)        
  783
+            self.setinputsizes(*sizes)
782 784
 
783 785
     def _param_generator(self, params):
784 786
         # Try dict handling; if that fails, treat as sequence
785 787
         if hasattr(params, 'items'):
786  
-            return dict((k, v.force_bytes) for k,v in params.items())
  788
+            return dict((k, v.force_bytes) for k, v in params.items())
787 789
         else:
788 790
             return [p.force_bytes for p in params]
789 791
 
@@ -799,14 +801,14 @@ def _fix_for_params(self, query, params):
799 801
             query = convert_unicode(query, self.charset)
800 802
         elif hasattr(params, 'keys'):
801 803
             # Handle params as dict
802  
-            args = dict((k, ":%s"%k) for k in params.keys())
  804
+            args = dict((k, ":%s" % k) for k in params.keys())
803 805
             query = convert_unicode(query % args, self.charset)
804 806
         else:
805 807
             # Handle params as sequence
806 808
             args = [(':arg%d' % i) for i in range(len(params))]
807 809
             query = convert_unicode(query % tuple(args), self.charset)
808 810
         return query, self._format_params(params)
809  
-        
  811
+
810 812
     def execute(self, query, params=None):
811 813
         query, params = self._fix_for_params(query, params)
812 814
         self._guess_input_sizes([params])
@@ -825,9 +827,9 @@ def executemany(self, query, params=None):
825 827
         # uniform treatment for sequences and iterables
826 828
         params_iter = iter(params)
827 829
         query, firstparams = self._fix_for_params(query, next(params_iter))
828  
-        # we build a list of formatted params; as we're going to traverse it 
  830
+        # we build a list of formatted params; as we're going to traverse it
829 831
         # more than once, we can't make it lazy by using a generator
830  
-        formatted = [firstparams]+[self._format_params(p) for p in params_iter]
  832
+        formatted = [firstparams] + [self._format_params(p) for p in params_iter]
831 833
         self._guess_input_sizes(formatted)
832 834
         try:
833 835
             return self.cursor.executemany(query,
2  django/db/backends/oracle/client.py
@@ -3,6 +3,7 @@
3 3
 
4 4
 from django.db.backends import BaseDatabaseClient
5 5
 
  6
+
6 7
 class DatabaseClient(BaseDatabaseClient):
7 8
     executable_name = 'sqlplus'
8 9
 
@@ -13,4 +14,3 @@ def runshell(self):
13 14
             sys.exit(os.system(" ".join(args)))
14 15
         else:
15 16
             os.execvp(self.executable_name, args)
16  
-
5  django/db/backends/oracle/compiler.py
@@ -60,17 +60,22 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
60 60
 class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
61 61
     pass
62 62
 
  63
+
63 64
 class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
64 65
     pass
65 66
 
  67
+
66 68
 class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
67 69
     pass
68 70
 
  71
+
69 72
 class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
70 73
     pass
71 74
 
  75
+
72 76
 class SQLDateCompiler(compiler.SQLDateCompiler, SQLCompiler):
73 77
     pass
74 78
 
  79
+
75 80
 class SQLDateTimeCompiler(compiler.SQLDateTimeCompiler, SQLCompiler):
76 81
     pass
52  django/db/backends/oracle/creation.py
@@ -5,9 +5,11 @@
5 5
 from django.db.backends.creation import BaseDatabaseCreation
6 6
 from django.utils.six.moves import input
7 7
 
  8
+
8 9
 TEST_DATABASE_PREFIX = 'test_'
9 10
 PASSWORD = 'Im_a_lumberjack'
10 11
 
  12
+
11 13
 class DatabaseCreation(BaseDatabaseCreation):
12 14
     # This dictionary maps Field objects to their associated Oracle column
13 15
     # types, as strings. Column-type strings can contain format strings; they'll
@@ -18,30 +20,30 @@ class DatabaseCreation(BaseDatabaseCreation):
18 20
     # output (the "qn_" prefix is stripped before the lookup is performed.
19 21
 
20 22
     data_types = {
21  
-        'AutoField':                    'NUMBER(11)',
22  
-        'BinaryField':                  'BLOB',
23  
-        'BooleanField':                 'NUMBER(1) CHECK (%(qn_column)s IN (0,1))',
24  
-        'CharField':                    'NVARCHAR2(%(max_length)s)',
25  
-        'CommaSeparatedIntegerField':   'VARCHAR2(%(max_length)s)',
26  
-        'DateField':                    'DATE',
27  
-        'DateTimeField':                'TIMESTAMP',
28  
-        'DecimalField':                 'NUMBER(%(max_digits)s, %(decimal_places)s)',
29  
-        'FileField':                    'NVARCHAR2(%(max_length)s)',
30  
-        'FilePathField':                'NVARCHAR2(%(max_length)s)',
31  
-        'FloatField':                   'DOUBLE PRECISION',
32  
-        'IntegerField':                 'NUMBER(11)',
33  
-        'BigIntegerField':              'NUMBER(19)',
34  
-        'IPAddressField':               'VARCHAR2(15)',
35  
-        'GenericIPAddressField':        'VARCHAR2(39)',
36  
-        'NullBooleanField':             'NUMBER(1) CHECK ((%(qn_column)s IN (0,1)) OR (%(qn_column)s IS NULL))',
37  
-        'OneToOneField':                'NUMBER(11)',
38  
-        'PositiveIntegerField':         'NUMBER(11) CHECK (%(qn_column)s >= 0)',
39  
-        'PositiveSmallIntegerField':    'NUMBER(11) CHECK (%(qn_column)s >= 0)',
40  
-        'SlugField':                    'NVARCHAR2(%(max_length)s)',
41  
-        'SmallIntegerField':            'NUMBER(11)',
42  
-        'TextField':                    'NCLOB',
43  
-        'TimeField':                    'TIMESTAMP',
44  
-        'URLField':                     'VARCHAR2(%(max_length)s)',
  23
+        'AutoField': 'NUMBER(11)',
  24
+        'BinaryField': 'BLOB',
  25
+        'BooleanField': 'NUMBER(1) CHECK (%(qn_column)s IN (0,1))',
  26
+        'CharField': 'NVARCHAR2(%(max_length)s)',
  27
+        'CommaSeparatedIntegerField': 'VARCHAR2(%(max_length)s)',
  28
+        'DateField': 'DATE',
  29
+        'DateTimeField': 'TIMESTAMP',
  30
+        'DecimalField': 'NUMBER(%(max_digits)s, %(decimal_places)s)',
  31
+        'FileField': 'NVARCHAR2(%(max_length)s)',
  32
+        'FilePathField': 'NVARCHAR2(%(max_length)s)',
  33
+        'FloatField': 'DOUBLE PRECISION',
  34
+        'IntegerField': 'NUMBER(11)',
  35
+        'BigIntegerField': 'NUMBER(19)',
  36
+        'IPAddressField': 'VARCHAR2(15)',
  37
+        'GenericIPAddressField': 'VARCHAR2(39)',
  38
+        'NullBooleanField': 'NUMBER(1) CHECK ((%(qn_column)s IN (0,1)) OR (%(qn_column)s IS NULL))',
  39
+        'OneToOneField': 'NUMBER(11)',
  40
+        'PositiveIntegerField': 'NUMBER(11) CHECK (%(qn_column)s >= 0)',
  41
+        'PositiveSmallIntegerField': 'NUMBER(11) CHECK (%(qn_column)s >= 0)',
  42
+        'SlugField': 'NVARCHAR2(%(max_length)s)',
  43
+        'SmallIntegerField': 'NUMBER(11)',
  44
+        'TextField': 'NCLOB',
  45
+        'TimeField': 'TIMESTAMP',
  46
+        'URLField': 'VARCHAR2(%(max_length)s)',
45 47
     }
46 48
 
47 49
     def __init__(self, connection):
@@ -183,7 +185,7 @@ def _execute_test_db_destruction(self, cursor, parameters, verbosity):
183 185
         statements = [
184 186
             'DROP TABLESPACE %(tblspace)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS',
185 187
             'DROP TABLESPACE %(tblspace_temp)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS',
186  
-            ]
  188
+        ]
187 189
         self._execute_statements(cursor, statements, parameters, verbosity)
188 190
 
189 191
     def _destroy_test_user(self, cursor, parameters, verbosity):
15  django/db/backends/oracle/introspection.py
... ...
@@ -1,10 +1,13 @@
  1
+import re
  2
+
  3
+import cx_Oracle
  4
+
1 5
 from django.db.backends import BaseDatabaseIntrospection, FieldInfo
2 6
 from django.utils.encoding import force_text
3  
-import cx_Oracle
4  
-import re
5 7
 
6 8
 foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
7 9
 
  10
+
8 11
 class DatabaseIntrospection(BaseDatabaseIntrospection):
9 12
     # Maps type objects to Django Field types.
10 13
     data_types_reverse = {
@@ -95,11 +98,11 @@ def get_key_columns(self, cursor, table_name):
95 98
             SELECT ccol.column_name, rcol.table_name AS referenced_table, rcol.column_name AS referenced_column
96 99
             FROM user_constraints c
97 100
             JOIN user_cons_columns ccol
98  
-              ON ccol.constraint_name = c.constraint_name 
  101
+              ON ccol.constraint_name = c.constraint_name
99 102
             JOIN user_cons_columns rcol
100  
-              ON rcol.constraint_name = c.r_constraint_name 
101  
-            WHERE c.table_name = %s AND c.constraint_type = 'R'""" , [table_name.upper()])
102  
-        return [tuple(cell.lower() for cell in row) 
  103
+              ON rcol.constraint_name = c.r_constraint_name
  104
+            WHERE c.table_name = %s AND c.constraint_type = 'R'""", [table_name.upper()])
  105
+        return [tuple(cell.lower() for cell in row)
103 106
                 for row in cursor.fetchall()]
104 107
 
105 108
     def get_indexes(self, cursor, table_name):
10  django/db/backends/postgresql_psycopg2/base.py
@@ -6,7 +6,9 @@
6 6
 import logging
7 7
 import sys
8 8
 
9  
-from django.db.backends import *
  9
+from django.conf import settings
  10
+from django.db.backends import (BaseDatabaseFeatures, BaseDatabaseWrapper,
  11
+    BaseDatabaseValidation)
10 12
 from django.db.backends.postgresql_psycopg2.operations import DatabaseOperations
11 13
 from django.db.backends.postgresql_psycopg2.client import DatabaseClient
12 14
 from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
@@ -33,11 +35,13 @@
33 35
 
34 36
 logger = logging.getLogger('django.db.backends')
35 37
 
  38
+
36 39
 def utc_tzinfo_factory(offset):
37 40
     if offset != 0:
38 41
         raise AssertionError("database connection isn't set to UTC")
39 42
     return utc
40 43
 
  44
+
41 45
 class DatabaseFeatures(BaseDatabaseFeatures):
42 46
     needs_datetime_string_cast = False
43 47
     can_return_id_from_insert = True
@@ -52,6 +56,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
52 56
     supports_transactions = True
53 57
     can_distinct_on_fields = True
54 58
 
  59
+
55 60
 class DatabaseWrapper(BaseDatabaseWrapper):
56 61
     vendor = 'postgresql'
57 62
     operators = {
@@ -132,7 +137,8 @@ def init_connection_state(self):
132 137
                 # Set the time zone in autocommit mode (see #17062)
133 138
                 self.set_autocommit(True)
134 139
                 self.connection.cursor().execute(
135  
-                        self.ops.set_time_zone_sql(), [tz])
  140
+                    self.ops.set_time_zone_sql(), [tz]
  141
+                )
136 142
         self.connection.set_isolation_level(self.isolation_level)
137 143
 
138 144
     def create_cursor(self):
2  django/db/backends/postgresql_psycopg2/client.py
@@ -3,6 +3,7 @@
3 3
 
4 4
 from django.db.backends import BaseDatabaseClient
5 5
 
  6
+
6 7
 class DatabaseClient(BaseDatabaseClient):
7 8
     executable_name = 'psql'
8 9
 
@@ -20,4 +21,3 @@ def runshell(self):
20 21
             sys.exit(os.system(" ".join(args)))
21 22
         else:
22 23
             os.execvp(self.executable_name, args)
23  
-
38  django/db/backends/postgresql_psycopg2/creation.py
@@ -8,29 +8,29 @@ class DatabaseCreation(BaseDatabaseCreation):
8 8
     # be interpolated against the values of Field.__dict__ before being output.
9 9
     # If a column type is set to None, it won't be included in the output.
10 10
     data_types = {
11  
-        'AutoField':         'serial',
12  
-        'BinaryField':       'bytea',
13  
-        'BooleanField':      'boolean',
14  
-        'CharField':         'varchar(%(max_length)s)',
  11
+        'AutoField': 'serial',
  12
+        'BinaryField': 'bytea',
  13
+        'BooleanField': 'boolean',
  14
+        'CharField': 'varchar(%(max_length)s)',
15 15
         'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
16  
-        'DateField':         'date',
17  
-        'DateTimeField':     'timestamp with time zone',
18  
-        'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)',
19  
-        'FileField':         'varchar(%(max_length)s)',
20  
-        'FilePathField':     'varchar(%(max_length)s)',
21  
-        'FloatField':        'double precision',
22  
-        'IntegerField':      'integer',
23  
-        'BigIntegerField':   'bigint',
24  
-        'IPAddressField':    'inet',
  16
+        'DateField': 'date',
  17
+        'DateTimeField': 'timestamp with time zone',
  18
+        'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
  19
+        'FileField': 'varchar(%(max_length)s)',
  20
+        'FilePathField': 'varchar(%(max_length)s)',
  21
+        'FloatField': 'double precision',
  22
+        'IntegerField': 'integer',
  23
+        'BigIntegerField': 'bigint',
  24
+        'IPAddressField': 'inet',
25 25
         'GenericIPAddressField': 'inet',
26  
-        'NullBooleanField':  'boolean',
27  
-        'OneToOneField':     'integer',
  26
+        'NullBooleanField': 'boolean',
  27
+        'OneToOneField': 'integer',
28 28
         'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)',
29 29
         'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)',
30  
-        'SlugField':         'varchar(%(max_length)s)',
  30
+        'SlugField': 'varchar(%(max_length)s)',
31 31
         'SmallIntegerField': 'smallint',
32  
-        'TextField':         'text',
33  
-        'TimeField':         'time',
  32
+        'TextField': 'text',
  33
+        'TimeField': 'time',
34 34
     }
35 35
 
36 36
     def sql_table_creation_suffix(self):
@@ -54,7 +54,7 @@ def sql_indexes_for_field(self, model, f, style):
54 54
 
55 55
             def get_index_sql(index_name, opclass=''):
56 56
                 return (style.SQL_KEYWORD('CREATE INDEX') + ' ' +
57  
-                        style.SQL_TABLE(qn(truncate_name(index_name,self.connection.ops.max_name_length()))) + ' ' +
  57
+                        style.SQL_TABLE(qn(truncate_name(index_name, self.connection.ops.max_name_length()))) + ' ' +
58 58
                         style.SQL_KEYWORD('ON') + ' ' +
59 59
                         style.SQL_TABLE(qn(db_table)) + ' ' +
60 60
                         "(%s%s)" % (style.SQL_FIELD(qn(f.column)), opclass) +
6  django/db/backends/postgresql_psycopg2/introspection.py
@@ -25,7 +25,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
25 25
         1266: 'TimeField',
26 26
         1700: 'DecimalField',
27 27
     }
28  
-        
  28
+
29 29
     def get_table_list(self, cursor):
30 30
         "Returns a list of table names in the current database."
31 31
         cursor.execute("""
@@ -47,7 +47,7 @@ def get_table_description(self, cursor, table_name):
47 47
             WHERE table_name = %s""", [table_name])
48 48
         null_map = dict(cursor.fetchall())
49 49
         cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
50  
-        return [FieldInfo(*((force_text(line[0]),) + line[1:6] + (null_map[force_text(line[0])]=='YES',)))
  50
+        return [FieldInfo(*((force_text(line[0]),) + line[1:6] + (null_map[force_text(line[0])] == 'YES',)))
51 51
                 for line in cursor.description]
52 52
 
53 53
     def get_relations(self, cursor, table_name):
@@ -81,7 +81,7 @@ def get_key_columns(self, cursor, table_name):
81 81
                 ON ccu.constraint_catalog = tc.constraint_catalog
82 82
                     AND ccu.constraint_schema = tc.constraint_schema
83 83
                     AND ccu.constraint_name = tc.constraint_name
84  
-            WHERE kcu.table_name = %s AND tc.constraint_type = 'FOREIGN KEY'""" , [table_name])
  84
+            WHERE kcu.table_name = %s AND tc.constraint_type = 'FOREIGN KEY'""", [table_name])
85 85
         key_columns.extend(cursor.fetchall())
86 86
         return key_columns
87 87
 
6  django/db/backends/postgresql_psycopg2/operations.py
@@ -135,7 +135,7 @@ def sequence_reset_by_name_sql(self, style, sequences):
135 135
                 # This will be the case if it's an m2m using an autogenerated
136 136
                 # intermediate table (see BaseDatabaseIntrospection.sequence_list)
137 137
                 column_name = 'id'
138  
-            sql.append("%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" % \
  138
+            sql.append("%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" %
139 139
                 (style.SQL_KEYWORD('SELECT'),
140 140
                 style.SQL_TABLE(self.quote_name(table_name)),
141 141
                 style.SQL_FIELD(column_name))
@@ -161,7 +161,7 @@ def sequence_reset_sql(self, style, model_list):
161 161
 
162 162
             for f in model._meta.local_fields:
163 163
                 if isinstance(f, models.AutoField):
164  
-                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
  164
+                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" %
165 165
                         (style.SQL_KEYWORD('SELECT'),
166 166
                         style.SQL_TABLE(qn(model._meta.db_table)),
167 167
                         style.SQL_FIELD(f.column),
@@ -173,7 +173,7 @@ def sequence_reset_sql(self, style, model_list):
173 173
                     break # Only one AutoField is allowed per model, so don't bother continuing.
174 174
             for f in model._meta.many_to_many:
175 175
                 if not f.rel.through:
176  
-                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
  176
+                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" %
177 177
                         (style.SQL_KEYWORD('SELECT'),
178 178
                         style.SQL_TABLE(qn(f.m2m_db_table())),
179 179
                         style.SQL_FIELD('id'),
3  django/db/backends/postgresql_psycopg2/version.py
@@ -19,7 +19,8 @@ def _parse_version(text):
19 19
     try:
20 20
         return int(major) * 10000 + int(major2) * 100 + int(minor)
21 21
     except (ValueError, TypeError):
22  
-        return int(major) * 10000 +  int(major2) * 100
  22
+        return int(major) * 10000 + int(major2) * 100
  23
+
23 24
 
24 25
 def get_version(connection):
25 26
     """
17  django/db/backends/sqlite3/base.py
@@ -11,8 +11,10 @@
11 11
 import warnings
12 12
 import re
13 13
 
  14
+from django.conf import settings
14 15
 from django.db import utils
15  
-from django.db.backends import *
  16
+from django.db.backends import (util, BaseDatabaseFeatures,
  17
+    BaseDatabaseOperations, BaseDatabaseWrapper, BaseDatabaseValidation)
16 18
 from django.db.backends.sqlite3.client import DatabaseClient
17 19
 from django.db.backends.sqlite3.creation import DatabaseCreation
18 20
 from django.db.backends.sqlite3.introspection import DatabaseIntrospection
@@ -42,6 +44,7 @@
42 44
 DatabaseError = Database.DatabaseError
43 45
 IntegrityError = Database.IntegrityError
44 46
 
  47
+
45 48
 def parse_datetime_with_timezone_support(value):
46 49
     dt = parse_datetime(value)
47 50
     # Confirm that dt is naive before overwriting its tzinfo.
@@ -49,6 +52,7 @@ def parse_datetime_with_timezone_support(value):
49 52
         dt = dt.replace(tzinfo=timezone.utc)
50 53
     return dt
51 54
 
  55
+
52 56
 def adapt_datetime_with_timezone_support(value):
53 57
     # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
54 58
     if settings.USE_TZ:
@@ -61,6 +65,7 @@ def adapt_datetime_with_timezone_support(value):
61 65
         value = value.astimezone(timezone.utc).replace(tzinfo=None)
62 66
     return value.isoformat(str(" "))
63 67
 
  68
+
64 69
 def decoder(conv_func):
65 70
     """ The Python sqlite3 interface returns always byte strings.
66 71
         This function converts the received value to a regular string before
@@ -81,6 +86,7 @@ def decoder(conv_func):
81 86
 Database.register_adapter(str, lambda s: s.decode('utf-8'))
82 87
 Database.register_adapter(SafeBytes, lambda s: s.decode('utf-8'))
83 88
 
  89
+
84 90
 class DatabaseFeatures(BaseDatabaseFeatures):
85 91
     # SQLite cannot handle us only partially reading from a cursor's result set
86 92
     # and then writing the same rows to the database in another cursor. This
@@ -124,6 +130,7 @@ def supports_stddev(self):
124 130
     def has_zoneinfo_database(self):
125 131
         return pytz is not None
126 132
 
  133
+
127 134
 class DatabaseOperations(BaseDatabaseOperations):
128 135
     def bulk_batch_size(self, fields, objs):
129 136
         """
@@ -272,6 +279,7 @@ def bulk_insert_sql(self, fields, num_values):
272 279
         res.extend(["UNION ALL SELECT %s" % ", ".join(["%s"] * len(fields))] * (num_values - 1))
273 280
         return " ".join(res)
274 281
 
  282
+
275 283
 class DatabaseWrapper(BaseDatabaseWrapper):
276 284
     vendor = 'sqlite'
277 285
     # SQLite requires LIKE statements to include an ESCAPE clause if the value
@@ -426,6 +434,7 @@ def _start_transaction_under_autocommit(self):
426 434
 
427 435
 FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
428 436
 
  437
+
429 438
 class SQLiteCursorWrapper(Database.Cursor):
430 439
     """
431 440
     Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
@@ -445,6 +454,7 @@ def executemany(self, query, param_list):
445 454
     def convert_query(self, query):
446 455
         return FORMAT_QMARK_REGEX.sub('?', query).replace('%%', '%')
447 456
 
  457
+
448 458
 def _sqlite_date_extract(lookup_type, dt):
449 459
     if dt is None:
450 460
         return None
@@ -457,6 +467,7 @@ def _sqlite_date_extract(lookup_type, dt):
457 467
     else:
458 468
         return getattr(dt, lookup_type)
459 469
 
  470
+
460 471
 def _sqlite_date_trunc(lookup_type, dt):
461 472
     try:
462 473
         dt = util.typecast_timestamp(dt)
@@ -469,6 +480,7 @@ def _sqlite_date_trunc(lookup_type, dt):
469 480
     elif lookup_type == 'day':
470 481
         return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
471 482
 
  483
+
472 484
 def _sqlite_datetime_extract(lookup_type, dt, tzname):
473 485
     if dt is None:
474 486
         return None
@@ -483,6 +495,7 @@ def _sqlite_datetime_extract(lookup_type, dt, tzname):
483 495
     else:
484 496
         return getattr(dt, lookup_type)
485 497
 
  498
+
486 499
 def _sqlite_datetime_trunc(lookup_type, dt, tzname):
487 500
     try:
488 501
         dt = util.typecast_timestamp(dt)
@@ -503,6 +516,7 @@ def _sqlite_datetime_trunc(lookup_type, dt, tzname):
503 516
     elif lookup_type == 'second':
504 517
         return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
505 518
 
  519
+
506 520
 def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
507 521
     try:
508 522
         dt = util.typecast_timestamp(dt)
@@ -517,5 +531,6 @@ def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
517 531
     # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
518 532
     return str(dt)
519 533
 
  534
+
520 535
 def _sqlite_regexp(re_pattern, re_string):
521 536
     return bool(re.search(re_pattern, force_text(re_string))) if re_string is not None else False
2  django/db/backends/sqlite3/client.py
@@ -3,6 +3,7 @@
3 3
 
4 4
 from django.db.backends import BaseDatabaseClient
5 5
 
  6
+
6 7
 class DatabaseClient(BaseDatabaseClient):
7 8
     executable_name = 'sqlite3'
8 9
 
@@ -13,4 +14,3 @@ def runshell(self):
13 14
             sys.exit(os.system(" ".join(args)))
14 15
         else:
15 16
             os.execvp(self.executable_name, args)
16  
-
49  django/db/backends/sqlite3/creation.py
... ...
@@ -1,36 +1,38 @@
1 1
 import os
2 2
 import sys
  3
+
3 4
 from django.db.backends.creation import BaseDatabaseCreation
4 5
 from django.utils.six.moves import input
5 6
 
  7
+
6 8
 class DatabaseCreation(BaseDatabaseCreation):
7 9
     # SQLite doesn't actually support most of these types, but it "does the right
8 10
     # thing" given more verbose field definitions, so leave them as is so that
9 11
     # schema inspection is more useful.
10 12
     data_types = {
11  
-        'AutoField':                    'integer',
12  
-        'BinaryField':                  'BLOB',
13  
-        'BooleanField':                 'bool',
14  
-        'CharField':                    'varchar(%(max_length)s)',
15  
-        'CommaSeparatedIntegerField':   'varchar(%(max_length)s)',
16  
-        'DateField':                    'date',
17  
-        'DateTimeField':                'datetime',
18  
-        'DecimalField':                 'decimal',
19  
-        'FileField':                    'varchar(%(max_length)s)',
20  
-        'FilePathField':                'varchar(%(max_length)s)',
21  
-        'FloatField':                   'real',
22  
-        'IntegerField':                 'integer',
23  
-        'BigIntegerField':              'bigint',
24  
-        'IPAddressField':               'char(15)',
25  
-        'GenericIPAddressField':        'char(39)',
26  
-        'NullBooleanField':             'bool',
27  
-        'OneToOneField':                'integer',
28  
-        'PositiveIntegerField':         'integer unsigned',
29  
-        'PositiveSmallIntegerField':    'smallint unsigned',
30  
-        'SlugField':                    'varchar(%(max_length)s)',
31  
-        'SmallIntegerField':            'smallint',
32  
-        'TextField':                    'text',
33  
-        'TimeField':                    'time',
  13
+        'AutoField': 'integer',
  14
+        'BinaryField': 'BLOB',
  15
+        'BooleanField': 'bool',
  16
+        'CharField': 'varchar(%(max_length)s)',
  17
+        'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
  18
+        'DateField': 'date',
  19
+        'DateTimeField': 'datetime',
  20
+        'DecimalField': 'decimal',
  21
+        'FileField': 'varchar(%(max_length)s)',
  22
+        'FilePathField': 'varchar(%(max_length)s)',
  23
+        'FloatField': 'real',
  24
+        'IntegerField': 'integer',
  25
+        'BigIntegerField': 'bigint',
  26
+        'IPAddressField': 'char(15)',
  27
+        'GenericIPAddressField': 'char(39)',
  28
+        'NullBooleanField': 'bool',
  29
+        'OneToOneField': 'integer',
  30
+        'PositiveIntegerField': 'integer unsigned',
  31
+        'PositiveSmallIntegerField': 'smallint unsigned',
  32
+        'SlugField': 'varchar(%(max_length)s)',
  33
+        'SmallIntegerField': 'smallint',
  34
+        'TextField': 'text',
  35
+        'TimeField': 'time',
34 36
     }
35 37
 
36 38
     def sql_for_pending_references(self, model, style, pending_references):
@@ -80,7 +82,6 @@ def test_db_signature(self):
80 82
         SQLite since the databases will be distinct despite having the same
81 83
         TEST_NAME. See http://www.sqlite.org/inmemorydb.html
82 84
         """
83  
-        settings_dict = self.connection.settings_dict
84 85
         test_dbname = self._get_test_db_name()
85 86
         sig = [self.connection.settings_dict['NAME']]
86 87
         if test_dbname == ':memory:':
13  django/db/backends/sqlite3/introspection.py
... ...
@@ -1,8 +1,11 @@
1 1
 import re
  2
+
2 3
 from django.db.backends import BaseDatabaseIntrospection, FieldInfo
3 4
 
  5
+
4 6
 field_size_re = re.compile(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$')
5 7
 
  8
+
6 9
 def get_field_size(name):
7 10
     """ Extract the size number from a "varchar(11)" type name """
8 11
     m = field_size_re.search(name)
@@ -46,6 +49,7 @@ def __getitem__(self, key):
46 49
                 return ('CharField', {'max_length': size})
47 50
             raise KeyError
48 51
 
  52
+
49 53
 class DatabaseIntrospection(BaseDatabaseIntrospection):
50 54
     data_types_reverse = FlexibleFieldLookupDict()
51 55
 
@@ -76,7 +80,7 @@ def get_relations(self, cursor, table_name):
76 80
         # Schema for this table
77 81
         cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"])
78 82
         results = cursor.fetchone()[0].strip()
79  
-        results = results[results.index('(')+1:results.rindex(')')]
  83
+        results = results[results.index('(') + 1:results.rindex(')')]
80 84
 
81 85
         # Walk through and look for references to other tables. SQLite doesn't
82 86
         # really have enforced references, but since it echoes out the SQL used
@@ -96,8 +100,7 @@ def get_relations(self, cursor, table_name):
96 100
             result = cursor.fetchall()[0]
97 101
             other_table_results = result[0].strip()
98 102
             li, ri = other_table_results.index('('), other_table_results.rindex(')')
99  
-            other_table_results = other_table_results[li+1:ri]
100  
-
  103
+            other_table_results = other_table_results[li + 1:ri]
101 104
 
102 105
             for other_index, other_desc in enumerate(other_table_results.split(',')):
103 106
                 other_desc = other_desc.strip()
@@ -121,7 +124,7 @@ def get_key_columns(self, cursor, table_name):
121 124
         # Schema for this table
122 125
         cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"])
123 126
         results = cursor.fetchone()[0].strip()
124  
-        results = results[results.index('(')+1:results.rindex(')')]
  127
+        results = results[results.index('(') + 1:results.rindex(')')]
125 128
 
126 129
         # Walk through and look for references to other tables. SQLite doesn't
127 130
         # really have enforced references, but since it echoes out the SQL used
@@ -166,7 +169,7 @@ def get_primary_key_column(self, cursor, table_name):
166 169
         # Don't use PRAGMA because that causes issues with some transactions
167 170
         cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"])
168 171
         results = cursor.fetchone()[0].strip()
169  
-        results = results[results.index('(')+1:results.rindex(')')]
  172
+        results = results[results.index('(') + 1:results.rindex(')')]
170 173
         for field_desc in results.split(','):
171 174
             field_desc = field_desc.strip()
172 175
             m = re.search('"(.*)".*PRIMARY KEY$', field_desc)
19  django/db/backends/util.py
@@ -85,20 +85,25 @@ def executemany(self, sql, param_list):
85 85
 def typecast_date(s):
86 86
     return datetime.date(*map(int, s.split('-'))) if s else None # returns None if s is null
87 87
 
  88
+
88 89
 def typecast_time(s): # does NOT store time zone information
89  
-    if not s: return None
  90
+    if not s:
  91
+        return None
90 92
     hour, minutes, seconds = s.split(':')
91 93
     if '.' in seconds: # check whether seconds have a fractional part
92 94
         seconds, microseconds = seconds.split('.')
93 95
     else:
94 96
         microseconds = '0'
95  
-    return datetime.time(int(hour), int(minutes), int(seconds), int(float('.'+microseconds) * 1000000))
  97
+    return datetime.time(int(hour), int(minutes), int(seconds), int(float('.' + microseconds) * 1000000))
  98
+
96 99
 
97 100
 def typecast_timestamp(s): # does NOT store time zone information
98 101
     # "2005-07-29 15:48:00.590358-05"
99 102
     # "2005-07-29 09:56:00-05"
100  
-    if not s: return None
101  
-    if not ' ' in s: return typecast_date(s)
  103
+    if not s:
  104
+        return None
  105
+    if not ' ' in s:
  106
+        return typecast_date(s)
102 107
     d, t = s.split()
103 108
     # Extract timezone information, if it exists. Currently we just throw
104 109
     # it away, but in the future we may make use of it.
@@ -122,11 +127,13 @@ def typecast_timestamp(s): # does NOT store time zone information
122 127
         int(times[0]), int(times[1]), int(seconds),
123 128
         int((microseconds + '000000')[:6]), tzinfo)
124 129
 
  130
+
125 131
 def typecast_decimal(s):
126 132
     if s is None or s == '':
127 133
         return None
128 134
     return decimal.Decimal(s)
129 135
 
  136
+
130 137
 ###############################################
131 138
 # Converters from Python to database (string) #
132 139
 ###############################################
@@ -136,6 +143,7 @@ def rev_typecast_decimal(d):
136 143
         return None
137 144
     return str(d)
138 145
 
  146
+
139 147
 def truncate_name(name, length=None, hash_len=4):
140 148
     """Shortens a string to a repeatable mangled version with the given length.
141 149
     """
@@ -143,7 +151,8 @@ def truncate_name(name, length=None, hash_len=4):
143 151
         return name
144 152
 
145 153
     hsh = hashlib.md5(force_bytes(name)).hexdigest()[:hash_len]
146  
-    return '%s%s' % (name[:length-hash_len], hsh)
  154
+    return '%s%s' % (name[:length - hash_len], hsh)
  155
+
147 156
 
148