base.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from django.conf import settings
  2. from django.db.backends.base.base import NO_DB_ALIAS
  3. from django.db.backends.postgresql_psycopg2.base import \
  4. DatabaseWrapper as Psycopg2DatabaseWrapper
  5. from django.utils.functional import cached_property
  6. from .creation import PostGISCreation
  7. from .features import DatabaseFeatures
  8. from .introspection import PostGISIntrospection
  9. from .operations import PostGISOperations
  10. from .schema import PostGISSchemaEditor
  11. class DatabaseWrapper(Psycopg2DatabaseWrapper):
  12. SchemaEditorClass = PostGISSchemaEditor
  13. def __init__(self, *args, **kwargs):
  14. super(DatabaseWrapper, self).__init__(*args, **kwargs)
  15. if kwargs.get('alias', '') != NO_DB_ALIAS:
  16. self.features = DatabaseFeatures(self)
  17. self.creation = PostGISCreation(self)
  18. self.ops = PostGISOperations(self)
  19. self.introspection = PostGISIntrospection(self)
  20. @cached_property
  21. def template_postgis(self):
  22. template_postgis = getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis')
  23. with self._nodb_connection.cursor() as cursor:
  24. cursor.execute('SELECT 1 FROM pg_database WHERE datname = %s LIMIT 1;', (template_postgis,))
  25. if cursor.fetchone():
  26. return template_postgis
  27. return None
  28. def prepare_database(self):
  29. super(DatabaseWrapper, self).prepare_database()
  30. if self.template_postgis is None:
  31. # Check that postgis extension is installed on PostGIS >= 2
  32. with self.cursor() as cursor:
  33. cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis")