creation.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import os
  2. from django.conf import settings
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.db.backends.sqlite3.creation import DatabaseCreation
  5. class SpatiaLiteCreation(DatabaseCreation):
  6. def create_test_db(self, verbosity=1, autoclobber=False, serialize=True):
  7. """
  8. Creates a test database, prompting the user for confirmation if the
  9. database already exists. Returns the name of the test database created.
  10. This method is overloaded to load up the SpatiaLite initialization
  11. SQL prior to calling the `migrate` command.
  12. """
  13. # Don't import django.core.management if it isn't needed.
  14. from django.core.management import call_command
  15. test_database_name = self._get_test_db_name()
  16. if verbosity >= 1:
  17. test_db_repr = ''
  18. if verbosity >= 2:
  19. test_db_repr = " ('%s')" % test_database_name
  20. print("Creating test database for alias '%s'%s..." % (self.connection.alias, test_db_repr))
  21. self._create_test_db(verbosity, autoclobber)
  22. self.connection.close()
  23. self.connection.settings_dict["NAME"] = test_database_name
  24. # Need to load the SpatiaLite initialization SQL before running `migrate`.
  25. self.load_spatialite_sql()
  26. # Report migrate messages at one level lower than that requested.
  27. # This ensures we don't get flooded with messages during testing
  28. # (unless you really ask to be flooded)
  29. call_command('migrate',
  30. verbosity=max(verbosity - 1, 0),
  31. interactive=False,
  32. database=self.connection.alias,
  33. load_initial_data=False,
  34. test_flush=True)
  35. # We then serialize the current state of the database into a string
  36. # and store it on the connection. This slightly horrific process is so people
  37. # who are testing on databases without transactions or who are using
  38. # a TransactionTestCase still get a clean database on every test run.
  39. if serialize:
  40. self.connection._test_serialized_contents = self.serialize_db_to_string()
  41. call_command('createcachetable', database=self.connection.alias)
  42. # Ensure a connection for the side effect of initializing the test database.
  43. self.connection.ensure_connection()
  44. return test_database_name
  45. def sql_indexes_for_field(self, model, f, style):
  46. "Return any spatial index creation SQL for the field."
  47. from django.contrib.gis.db.models.fields import GeometryField
  48. output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style)
  49. if isinstance(f, GeometryField):
  50. gqn = self.connection.ops.geo_quote_name
  51. db_table = model._meta.db_table
  52. output.append(style.SQL_KEYWORD('SELECT ') +
  53. style.SQL_TABLE('AddGeometryColumn') + '(' +
  54. style.SQL_TABLE(gqn(db_table)) + ', ' +
  55. style.SQL_FIELD(gqn(f.column)) + ', ' +
  56. style.SQL_FIELD(str(f.srid)) + ', ' +
  57. style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' +
  58. style.SQL_KEYWORD(str(f.dim)) + ', ' +
  59. style.SQL_KEYWORD(str(int(not f.null))) +
  60. ');')
  61. if f.spatial_index:
  62. output.append(style.SQL_KEYWORD('SELECT ') +
  63. style.SQL_TABLE('CreateSpatialIndex') + '(' +
  64. style.SQL_TABLE(gqn(db_table)) + ', ' +
  65. style.SQL_FIELD(gqn(f.column)) + ');')
  66. return output
  67. def load_spatialite_sql(self):
  68. """
  69. This routine loads up the SpatiaLite SQL file.
  70. """
  71. if self.connection.ops.spatial_version[:2] >= (2, 4):
  72. # Spatialite >= 2.4 -- No need to load any SQL file, calling
  73. # InitSpatialMetaData() transparently creates the spatial metadata
  74. # tables
  75. cur = self.connection._cursor()
  76. cur.execute("SELECT InitSpatialMetaData()")
  77. else:
  78. # Spatialite < 2.4 -- Load the initial SQL
  79. # Getting the location of the SpatiaLite SQL file, and confirming
  80. # it exists.
  81. spatialite_sql = self.spatialite_init_file()
  82. if not os.path.isfile(spatialite_sql):
  83. raise ImproperlyConfigured('Could not find the required SpatiaLite initialization '
  84. 'SQL file (necessary for testing): %s' % spatialite_sql)
  85. # Opening up the SpatiaLite SQL initialization file and executing
  86. # as a script.
  87. with open(spatialite_sql, 'r') as sql_fh:
  88. cur = self.connection._cursor()
  89. cur.executescript(sql_fh.read())
  90. def spatialite_init_file(self):
  91. # SPATIALITE_SQL may be placed in settings to tell GeoDjango
  92. # to use a specific path to the SpatiaLite initialization SQL.
  93. return getattr(settings, 'SPATIALITE_SQL',
  94. 'init_spatialite-%s.%s.sql' %
  95. self.connection.ops.spatial_version[:2])