PageRenderTime 28ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

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