Commits

Andrew Godwin committed 53a6d4f

De-linting the core database modules

Comments (0)

Files changed (4)

south/db/generic.py

-
-import datetime
-import string
-import random
 import re
 import sys
 
 try:
     from django.utils.functional import cached_property
 except ImportError:
-   class cached_property(object):
-       """
-       Decorator that creates converts a method with a single
-       self argument into a property cached on the instance.
-       """
-       def __init__(self, func):
-           self.func = func
+    class cached_property(object):
+        """
+        Decorator that creates converts a method with a single
+        self argument into a property cached on the instance.
+        """
+        def __init__(self, func):
+            self.func = func
 
-       def __get__(self, instance, type):
-           res = instance.__dict__[self.func.__name__] = self.func(instance)
-           return res
+        def __get__(self, instance, type):
+            res = instance.__dict__[self.func.__name__] = self.func(instance)
+            return res
 
 from south.logger import get_logger
 
+
 def alias(attrname):
     """
     Returns a function which calls 'attrname' - for function aliasing.
         return getattr(self, attrname)(*args, **kwds)
     return func
 
+
 def invalidate_table_constraints(func):
     def _cache_clear(self, table, *args, **opts):
         self._set_cache(table, value=INVALID)
         return func(self, table, *args, **opts)
     return _cache_clear
 
+
 def delete_column_constraints(func):
     def _column_rm(self, table, column, *args, **opts):
         self._set_cache(table, column, value=[])
         return func(self, table, column, *args, **opts)
     return _column_rm
 
+
 def copy_column_constraints(func):
     def _column_cp(self, table, column_old, column_new, *args, **opts):
         db_name = self._get_setting('NAME')
         return func(self, table, column_old, column_new, *args, **opts)
     return _column_cp
 
+
 class INVALID(Exception):
     def __repr__(self):
         return 'INVALID'
 
+
 class DryRunError(ValueError):
     pass
 
+
 class DatabaseOperations(object):
     """
     Generic SQL implementation of the DatabaseOperations.
         try:
             ret = _lookup()
             return ret
-        except INVALID, e:
+        except INVALID:
             del self._constraint_cache[db_name][table_name]
             self._fill_constraint_cache(db_name, table_name)
-        except KeyError, e:
+        except KeyError:
             if self._is_valid_cache(db_name, table_name):
                 return []
             self._fill_constraint_cache(db_name, table_name)
             return False
 
     def _is_multidb(self):
-        try: 
+        try:
             from django.db import connections
+            connections  # Prevents "unused import" warning
         except ImportError:
             return False
         else:
             return True
 
-    def _get_connection(self): 
-        """ 
-        Returns a django connection for a given DB Alias 
+    def _get_connection(self):
+        """
+        Returns a django connection for a given DB Alias
         """
         if self._is_multidb():
-            from django.db import connections 
-            return connections[self.db_alias] 
+            from django.db import connections
+            return connections[self.db_alias]
         else:
-            from django.db import connection 
-            return connection 
+            from django.db import connection
+            return connection
 
     def _get_setting(self, setting_name):
         """
         Allows code to get a setting (like, for example, STORAGE_ENGINE)
         """
         setting_name = setting_name.upper()
-        connection = self._get_connection() 
+        connection = self._get_connection()
         if self._is_multidb():
             # Django 1.2 and above
-            return connection.settings_dict[setting_name] 
+            return connection.settings_dict[setting_name]
         else:
             # Django 1.1 and below
             return getattr(settings, "DATABASE_%s" % setting_name)
             return self._get_setting('schema')
         except (KeyError, AttributeError):
             return self.default_schema_name
-
     
     def _possibly_initialise(self):
         if not self._initialised:
         except:
             return []
 
-
     def execute_many(self, sql, regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)", comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
         """
         Takes a SQL file and executes it as many separate statements.
         for st in re.split(regex, sql)[1:][::2]:
             self.execute(st)
 
-
     def add_deferred_sql(self, sql):
         """
         Add a SQL statement to the deferred list, that won't be executed until
         """
         self.deferred_sql.append(sql)
 
-
     def execute_deferred_sql(self):
         """
         Executes all deferred SQL, resetting the deferred_sql list
 
         self.deferred_sql = []
 
-
     def clear_deferred_sql(self):
         """
         Resets the deferred_sql list to empty.
         """
         self.deferred_sql = []
 
-
     def clear_run_data(self, pending_creates = None):
         """
         Resets variables to how they should be before a run. Used for dry runs.
         self.clear_deferred_sql()
         self.pending_create_signals = pending_creates or []
 
-
     def get_pending_creates(self):
         return self.pending_create_signals
 
-
     @invalidate_table_constraints
     def create_table(self, table_name, fields):
         """
             ', '.join([col for col in columns if col]),
         ))
 
-    add_table = alias('create_table') # Alias for consistency's sake
-
+    add_table = alias('create_table')  # Alias for consistency's sake
 
     @invalidate_table_constraints
     def rename_table(self, old_table_name, table_name):
         # Invalidate the not-yet-indexed table
         self._set_cache(table_name, value=INVALID)
 
-
     @invalidate_table_constraints
     def delete_table(self, table_name, cascade=True):
         """
 
     drop_table = alias('delete_table')
 
-
     @invalidate_table_constraints
     def clear_table(self, table_name):
         """
         params = (self.quote_name(table_name), )
         self.execute('DELETE FROM %s;' % params)
 
-
-
     @invalidate_table_constraints
     def add_column(self, table_name, name, field, keep_default=True):
         """
                 field.default = NOT_PROVIDED
                 self.alter_column(table_name, name, field, explicit_name=False, ignore_constraints=True)
 
-
     def _db_type_for_alter_column(self, field):
         """
         Returns a field's type suitable for ALTER COLUMN.
         """
         pass
 
-    def _alter_set_defaults(self, field, name, params, sqls): 
+    def _alter_set_defaults(self, field, name, params, sqls):
         "Subcommand of alter_column that sets default values (overrideable)"
         # Next, set any default
         if not field.null and field.has_default():
 
     def _fill_constraint_cache(self, db_name, table_name):
 
-        schema = self._get_schema_name()            
+        schema = self._get_schema_name()
         ifsc_tables = ["constraint_column_usage", "key_column_usage"]
 
         self._constraint_cache.setdefault(db_name, {})
 
         cols = ", ".join(map(self.quote_name, columns))
         self.execute("ALTER TABLE %s ADD CONSTRAINT %s UNIQUE (%s)" % (
-            self.quote_name(table_name), 
-            self.quote_name(name), 
+            self.quote_name(table_name),
+            self.quote_name(name),
             cols,
         ))
         return name
             raise ValueError("Cannot find a UNIQUE constraint on table %s, columns %r" % (table_name, columns))
         for constraint in constraints:
             self.execute(self.delete_unique_sql % (
-                self.quote_name(table_name), 
+                self.quote_name(table_name),
                 self.quote_name(constraint),
             ))
 
-
     def column_sql(self, table_name, field_name, field, tablespace='', with_name=True, field_prepared=False):
         """
         Creates the SQL snippet for a column. Used by add_column and add_table.
         else:
             return None
 
-
     def _field_sanity(self, field):
         """
         Placeholder for DBMS-specific field alterations (some combos aren't valid,
         if isinstance(value, bool) and not self.has_booleans:
             return int(value)
         else:
-            return value 
+            return value
 
     def foreign_key_sql(self, from_table_name, from_column_name, to_table_name, to_column_name):
         """
             self.quote_name(from_column_name),
             self.quote_name(to_table_name),
             self.quote_name(to_column_name),
-            self._get_connection().ops.deferrable_sql() # Django knows this
+            self._get_connection().ops.deferrable_sql()  # Django knows this
         )
-    
 
     @invalidate_table_constraints
     def delete_foreign_key(self, table_name, column):
         if self.dry_run:
             if self.debug:
                 print '   - no dry run output for delete_foreign_key() due to dynamic DDL, sorry'
-            return # We can't look at the DB to get the constraints
+            return  # We can't look at the DB to get the constraints
         constraints = self._find_foreign_constraints(table_name, column)
         if not constraints:
             raise ValueError("Cannot find a FOREIGN KEY constraint on table %s, column %s" % (table_name, column))
         index_name = ('%s_%s%s%s' % (table_name, column_names[0], index_unique_name, suffix)).replace('"', '').replace('.', '_')
         if len(index_name) > self.max_index_name_length:
             part = ('_%s%s%s' % (column_names[0], index_unique_name, suffix))
-            index_name = '%s%s' % (table_name[:(self.max_index_name_length-len(part))], part)
+            index_name = '%s%s' % (table_name[:(self.max_index_name_length - len(part))], part)
 
         return index_name
 
-
     def create_index_sql(self, table_name, column_names, unique=False, db_tablespace=''):
         """
         Generates a create index statement on 'table_name' for a list of 'column_names'
         sql = self.create_index_sql(table_name, column_names, unique, db_tablespace)
         self.execute(sql)
 
-
     @invalidate_table_constraints
     def delete_index(self, table_name, column_names, db_tablespace=''):
         """
 
     drop_index = alias('delete_index')
 
-
     @delete_column_constraints
     def delete_column(self, table_name, name):
         """
         Deletes the column 'column_name' from the table 'table_name'.
         """
-        db_name = self._get_setting('NAME')
         params = (self.quote_name(table_name), self.quote_name(name))
         self.execute(self.delete_column_string % params, [])
 
     drop_column = alias('delete_column')
 
-
     def rename_column(self, table_name, old, new):
         """
         Renames the column 'old' from the table 'table_name' to 'new'.
         """
         raise NotImplementedError("rename_column has no generic SQL syntax")
 
-
     @invalidate_table_constraints
     def delete_primary_key(self, table_name):
         """
     
     drop_primary_key = alias('delete_primary_key')
 
-
     @invalidate_table_constraints
     def create_primary_key(self, table_name, columns):
         """
             columns = [columns]
         self.execute(self.create_primary_key_string % {
             "table": self.quote_name(table_name),
-            "constraint": self.quote_name(table_name+"_pkey"),
+            "constraint": self.quote_name(table_name + "_pkey"),
             "columns": ", ".join(map(self.quote_name, columns)),
         })
 
-
     def start_transaction(self):
         """
         Makes sure the following commands are inside a transaction.
         transaction.enter_transaction_management()
         transaction.managed(True)
 
-
     def commit_transaction(self):
         """
         Commits the current transaction.
         transaction.commit()
         transaction.leave_transaction_management()
 
-
     def rollback_transaction(self):
         """
         Rolls back the current transaction.
             # This means we are missing a COMMIT/ROLLBACK.
             transaction.leave_transaction_management()
 
-
     def send_create_signal(self, app_label, model_names):
         self.pending_create_signals.append((app_label, model_names))
 
-
     def send_pending_create_signals(self, verbosity=0, interactive=False):
         # Group app_labels together
         signals = SortedDict()
                                            interactive=interactive)
         self.pending_create_signals = []
 
-
     def really_send_create_signal(self, app_label, model_names,
                                   verbosity=0, interactive=False):
         """
                         interactive=interactive,
                     )
 
-
-    def mock_model(self, model_name, db_table, db_tablespace='', 
+    def mock_model(self, model_name, db_table, db_tablespace='',
                    pk_field_name='id', pk_field_type=models.AutoField,
                    pk_field_args=[], pk_field_kwargs={}):
         """
         """
         super(type(self), self)._alter_add_column_mods(field, name, params, sqls)
         if isinstance(field, (models.PositiveSmallIntegerField, models.PositiveIntegerField)):
-            uniq_hash = abs(hash(tuple(params.values()))) 
+            uniq_hash = abs(hash(tuple(params.values())))
             d = dict(
                      constraint = "CK_%s_PSTV_%s" % (name, hex(uniq_hash)[2:]),
                      check = "%s >= 0" % self.quote_name(name))
             sqls.append((self.add_check_constraint_fragment % d, []))
-    
 
 
 # Single-level flattening of lists

south/db/mysql.py

 # Original author: Andrew Godwin
 # Patches by: F. Gabriel Gosselin <gabrielNOSPAM@evidens.ca>
 
-from django.db import connection
-from django.conf import settings
 from south.db import generic
 from south.db.generic import DryRunError, INVALID
+from south.logger import get_logger
 
-from south.logger import get_logger
 
 def delete_column_constraints(func):
     """
         try:
             self.delete_foreign_key(table_name, column_name)
         except ValueError:
-            pass # If no foreign key on column, OK because it checks first
+            pass  # If no foreign key on column, OK because it checks first
         # Delete constraints referring to this column
         try:
             reverse = self._lookup_reverse_constraint(table_name, column_name)
         return func(self, table_name, column_name, *args, **opts)
     return _column_rm
 
+
 def copy_column_constraints(func):
     """
     Decorates column operation functions for MySQL.
                 get_logger().debug("Foreign key SQL: " + fk_sql)
                 self.add_deferred_sql(fk_sql)
         except IndexError:
-            pass # No constraint exists so ignore
+            pass  # No constraint exists so ignore
         except DryRunError:
             pass
         # Copy constraints referring to this column
         return func(self, table_name, column_old, column_new, *args, **opts)
     return _column_cp
 
+
 def invalidate_table_constraints(func):
     """
     For MySQL we grab all table constraints simultaneously, so this is
         return func(self, table, *args, **opts)
     return _cache_clear
 
+
 class DatabaseOperations(generic.DatabaseOperations):
     """
     MySQL implementation of database operations.
     has_check_constraints = False
 
     geom_types = ['geometry', 'point', 'linestring', 'polygon']
-    text_types = ['text', 'blob',]
+    text_types = ['text', 'blob']
 
     def __init__(self, db_alias):
         self._constraint_references = {}
                 return [(y, tuple(y)) for x, y in table.items()]
             else:
                 return tuple(table[column_name])
-        except KeyError, e:
+        except KeyError:
             return []
 
     def _field_sanity(self, field):
         """
         #  MySQL does not support defaults for geometry columns also
         type = self._db_type_for_alter_column(field).lower()
-        is_geom = True in [ type.find(t) > -1 for t in self.geom_types ]
-        is_text = True in [ type.find(t) > -1 for t in self.text_types ]
+        is_geom = True in [type.find(t) > -1 for t in self.geom_types]
+        is_text = True in [type.find(t) > -1 for t in self.text_types]
 
         if is_geom or is_text:
             field._suppress_default = True
         """
         type = params['type']
         #  MySQL does not support defaults for geometry columns also
-        is_geom = True in [ type.find(t) > -1 for t in self.geom_types ]
-        is_text = True in [ type.find(t) > -1 for t in self.text_types ]
+        is_geom = True in [type.find(t) > -1 for t in self.geom_types]
+        is_text = True in [type.find(t) > -1 for t in self.text_types]
         if not is_geom and not is_text:
             super(DatabaseOperations, self)._alter_set_defaults(field, name, params, sqls)
-

south/db/postgresql_psycopg2.py

+from south.db import generic
 
-from django.db import connection, models
-from south.db import generic
 
 class DatabaseOperations(generic.DatabaseOperations):
 
         self.commit_transaction()
         self.start_transaction()
         try:
-            generic.DatabaseOperations.rename_table(self, old_table_name+"_id_seq", table_name+"_id_seq")
+            generic.DatabaseOperations.rename_table(self, old_table_name + "_id_seq", table_name + "_id_seq")
         except:
             if self.debug:
                 print "   ~ No such sequence (ignoring error)"
         # the table that are used by django (e.g. foreign keys). Until
         # figure out how, you need to do this yourself.
         try:
-            generic.DatabaseOperations.rename_table(self, old_table_name+"_pkey", table_name+ "_pkey")
+            generic.DatabaseOperations.rename_table(self, old_table_name + "_pkey", table_name + "_pkey")
         except:
             if self.debug:
                 print "   ~ No such primary key (ignoring error)"
             self.commit_transaction()
         self.start_transaction()
 
-
     def rename_index(self, old_index_name, index_name):
         "Rename an index individually"
         generic.DatabaseOperations.rename_table(self, old_index_name, index_name)

south/db/sqlite3.py

-import inspect
-import re
+from south.db import generic
 
-from django.db.models import ForeignKey
-
-from south.db import generic
-from django.core.management.commands import inspectdb
     
 class DatabaseOperations(generic.DatabaseOperations):
 
         Adds a column.
         """
         # If it's not nullable, and has no default, raise an error (SQLite is picky)
-        if (not field.null and 
-            (not field.has_default() or field.get_default() is None) and
-            not field.empty_strings_allowed):
+        if (not field.null and
+           (not field.has_default() or field.get_default() is None) and
+           not field.empty_strings_allowed):
             raise ValueError("You cannot add a null=False column without a default value.")
         # Initialise the field.
         field.set_attributes_from_name(name)
-        # We add columns by remaking the table; even though SQLite supports 
+        # We add columns by remaking the table; even though SQLite supports
         # adding columns, it doesn't support adding PRIMARY KEY or UNIQUE cols.
         self._remake_table(table_name, added={
             field.column: self._column_sql_for_create(table_name, name, field, False),
         # We can't do that before since it's impossible to rename indexes
         # and index name scope is global
         self._make_multi_indexes(table_name, multi_indexes, renames=renames, deleted=deleted, uniques_deleted=uniques_deleted)
-
     
     def _copy_data(self, src, dst, field_renames={}):
         "Used to copy data into a new table"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.