PageRenderTime 45ms CodeModel.GetById 29ms app.highlight 13ms RepoModel.GetById 0ms app.codeStats 1ms

/django/contrib/gis/db/backends/spatialite/creation.py

https://code.google.com/p/mango-py/
Python | 136 lines | 90 code | 18 blank | 28 comment | 12 complexity | 93df8988a0b7183d8877fa485713fbe5 MD5 | raw file
  1import os
  2from django.conf import settings
  3from django.core.cache import get_cache
  4from django.core.cache.backends.db import BaseDatabaseCache
  5from django.core.exceptions import ImproperlyConfigured
  6from django.db.backends.sqlite3.creation import DatabaseCreation
  7
  8class SpatiaLiteCreation(DatabaseCreation):
  9
 10    def create_test_db(self, verbosity=1, autoclobber=False):
 11        """
 12        Creates a test database, prompting the user for confirmation if the
 13        database already exists. Returns the name of the test database created.
 14
 15        This method is overloaded to load up the SpatiaLite initialization
 16        SQL prior to calling the `syncdb` command.
 17        """
 18        # Don't import django.core.management if it isn't needed.
 19        from django.core.management import call_command
 20
 21        test_database_name = self._get_test_db_name()
 22
 23        if verbosity >= 1:
 24            test_db_repr = ''
 25            if verbosity >= 2:
 26                test_db_repr = " ('%s')" % test_database_name
 27            print "Creating test database for alias '%s'%s..." % (self.connection.alias, test_db_repr)
 28
 29        self._create_test_db(verbosity, autoclobber)
 30
 31        self.connection.close()
 32        self.connection.settings_dict["NAME"] = test_database_name
 33
 34        # Confirm the feature set of the test database
 35        self.connection.features.confirm()
 36
 37        # Need to load the SpatiaLite initialization SQL before running `syncdb`.
 38        self.load_spatialite_sql()
 39
 40        # Report syncdb messages at one level lower than that requested.
 41        # This ensures we don't get flooded with messages during testing
 42        # (unless you really ask to be flooded)
 43        call_command('syncdb',
 44            verbosity=max(verbosity - 1, 0),
 45            interactive=False,
 46            database=self.connection.alias,
 47            load_initial_data=False)
 48
 49        # We need to then do a flush to ensure that any data installed by
 50        # custom SQL has been removed. The only test data should come from
 51        # test fixtures, or autogenerated from post_syncdb triggers.
 52        # This has the side effect of loading initial data (which was
 53        # intentionally skipped in the syncdb).
 54        call_command('flush',
 55            verbosity=max(verbosity - 1, 0),
 56            interactive=False,
 57            database=self.connection.alias)
 58
 59        # One effect of calling syncdb followed by flush is that the id of the
 60        # default site may or may not be 1, depending on how the sequence was
 61        # reset.  If the sites app is loaded, then we coerce it.
 62        from django.db.models import get_model
 63        Site = get_model('sites', 'Site')
 64        if Site is not None and Site.objects.using(self.connection.alias).count() == 1:
 65            Site.objects.using(self.connection.alias).update(id=settings.SITE_ID)
 66
 67        from django.core.cache import get_cache
 68        from django.core.cache.backends.db import BaseDatabaseCache
 69        for cache_alias in settings.CACHES:
 70            cache = get_cache(cache_alias)
 71            if isinstance(cache, BaseDatabaseCache):
 72                from django.db import router
 73                if router.allow_syncdb(self.connection.alias, cache.cache_model_class):
 74                    call_command('createcachetable', cache._table, database=self.connection.alias)
 75
 76        # Get a cursor (even though we don't need one yet). This has
 77        # the side effect of initializing the test database.
 78        cursor = self.connection.cursor()
 79
 80        return test_database_name
 81
 82    def sql_indexes_for_field(self, model, f, style):
 83        "Return any spatial index creation SQL for the field."
 84        from django.contrib.gis.db.models.fields import GeometryField
 85
 86        output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style)
 87
 88        if isinstance(f, GeometryField):
 89            gqn = self.connection.ops.geo_quote_name
 90            qn = self.connection.ops.quote_name
 91            db_table = model._meta.db_table
 92
 93            output.append(style.SQL_KEYWORD('SELECT ') +
 94                          style.SQL_TABLE('AddGeometryColumn') + '(' +
 95                          style.SQL_TABLE(gqn(db_table)) + ', ' +
 96                          style.SQL_FIELD(gqn(f.column)) + ', ' +
 97                          style.SQL_FIELD(str(f.srid)) + ', ' +
 98                          style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' +
 99                          style.SQL_KEYWORD(str(f.dim)) + ', ' +
100                          style.SQL_KEYWORD(str(int(not f.null))) +
101                          ');')
102
103            if f.spatial_index:
104                output.append(style.SQL_KEYWORD('SELECT ') +
105                              style.SQL_TABLE('CreateSpatialIndex') + '(' +
106                              style.SQL_TABLE(gqn(db_table)) + ', ' +
107                              style.SQL_FIELD(gqn(f.column)) + ');')
108
109        return output
110
111    def load_spatialite_sql(self):
112        """
113        This routine loads up the SpatiaLite SQL file.
114        """
115        # Getting the location of the SpatiaLite SQL file, and confirming
116        # it exists.
117        spatialite_sql = self.spatialite_init_file()
118        if not os.path.isfile(spatialite_sql):
119            raise ImproperlyConfigured('Could not find the required SpatiaLite initialization '
120                                       'SQL file (necessary for testing): %s' % spatialite_sql)
121
122        # Opening up the SpatiaLite SQL initialization file and executing
123        # as a script.
124        sql_fh = open(spatialite_sql, 'r')
125        try:
126            cur = self.connection._cursor()
127            cur.executescript(sql_fh.read())
128        finally:
129            sql_fh.close()
130
131    def spatialite_init_file(self):
132        # SPATIALITE_SQL may be placed in settings to tell GeoDjango
133        # to use a specific path to the SpatiaLite initilization SQL.
134        return getattr(settings, 'SPATIALITE_SQL',
135                       'init_spatialite-%s.%s.sql' %
136                       self.connection.ops.spatial_version[:2])