Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #19152 -- Allowed PostGIS tests to be run without template

From version 2, a PostGIS template is no longer required to create
a GIS-enabled database.
  • Loading branch information...
commit fbd1df8e16fc17a5d73f36136298c20b8ec3d618 1 parent 9d4baf8
Flavio Curella authored claudep committed
29  django/contrib/gis/db/backends/postgis/creation.py
... ...
@@ -1,12 +1,23 @@
1 1
 from django.conf import settings
2 2
 from django.core.exceptions import ImproperlyConfigured
3 3
 from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
  4
+from django.utils.functional import cached_property
  5
+
4 6
 
5 7
 class PostGISCreation(DatabaseCreation):
6 8
     geom_index_type = 'GIST'
7 9
     geom_index_ops = 'GIST_GEOMETRY_OPS'
8 10
     geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND'
9 11
 
  12
+    @cached_property
  13
+    def template_postgis(self):
  14
+        template_postgis = getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis')
  15
+        cursor = self.connection.cursor()
  16
+        cursor.execute('SELECT 1 FROM pg_database WHERE datname = %s LIMIT 1;', (template_postgis,))
  17
+        if cursor.fetchone():
  18
+            return template_postgis
  19
+        return None
  20
+
10 21
     def sql_indexes_for_field(self, model, f, style):
11 22
         "Return any spatial index creation SQL for the field."
12 23
         from django.contrib.gis.db.models.fields import GeometryField
@@ -67,5 +78,19 @@ def sql_indexes_for_field(self, model, f, style):
67 78
         return output
68 79
 
69 80
     def sql_table_creation_suffix(self):
70  
-        postgis_template = getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis')
71  
-        return ' TEMPLATE %s' % self.connection.ops.quote_name(postgis_template)
  81
+        if self.template_postgis is not None:
  82
+            return ' TEMPLATE %s' % (
  83
+                self.connection.ops.quote_name(self.template_postgis),)
  84
+        return ''
  85
+
  86
+    def _create_test_db(self, verbosity, autoclobber):
  87
+        test_database_name = super(PostGISCreation, self)._create_test_db(verbosity, autoclobber)
  88
+        if self.template_postgis is None:
  89
+            # Connect to the test database in order to create the postgis extension
  90
+            self.connection.close()
  91
+            self.connection.settings_dict["NAME"] = test_database_name
  92
+            cursor = self.connection.cursor()
  93
+            cursor.execute("CREATE EXTENSION postgis")
  94
+            cursor.commit()
  95
+
  96
+        return test_database_name

0 notes on commit fbd1df8

Please sign in to comment.
Something went wrong with that request. Please try again.