1
from django.db.models.fields import Field # Django base Field class
3
# Quotename & geographic quotename, respectively
4
from django.db import connection
5
qn = connection.ops.quote_name
6
from django.contrib.gis.db.backend.util import gqn
7
from django.contrib.gis.db.backend.spatialite.query import GEOM_FROM_TEXT, TRANSFORM
9
class SpatiaLiteField(Field):
11
The backend-specific geographic field for SpatiaLite.
14
def _add_geom(self, style, db_table):
16
Constructs the addition of the geometry to the table using the
17
AddGeometryColumn(...) OpenGIS stored procedure.
19
Takes the style object (provides syntax highlighting) and the
20
database table as parameters.
22
sql = (style.SQL_KEYWORD('SELECT ') +
23
style.SQL_TABLE('AddGeometryColumn') + '(' +
24
style.SQL_TABLE(gqn(db_table)) + ', ' +
25
style.SQL_FIELD(gqn(self.column)) + ', ' +
26
style.SQL_FIELD(str(self.srid)) + ', ' +
27
style.SQL_COLTYPE(gqn(self.geom_type)) + ', ' +
28
style.SQL_KEYWORD(str(self.dim)) + ', ' +
29
style.SQL_KEYWORD(str(int(not self.null))) +
33
def _geom_index(self, style, db_table):
34
"Creates a spatial index for this geometry field."
35
sql = (style.SQL_KEYWORD('SELECT ') +
36
style.SQL_TABLE('CreateSpatialIndex') + '(' +
37
style.SQL_TABLE(gqn(db_table)) + ', ' +
38
style.SQL_FIELD(gqn(self.column)) + ');')
41
def post_create_sql(self, style, db_table):
43
Returns SQL that will be executed after the model has been
44
created. Geometry columns must be added after creation with the
45
OpenGIS AddGeometryColumn() function.
47
# Getting the AddGeometryColumn() SQL necessary to create a OpenGIS
49
post_sql = self._add_geom(style, db_table)
51
# If the user wants to index this data, then get the indexing SQL as well.
52
if self.spatial_index:
53
return (post_sql, self._geom_index(style, db_table))
57
def _post_delete_sql(self, style, db_table):
58
"Drops the geometry column."
59
sql = (style.SQL_KEYWORD('SELECT ') +
60
style.SQL_KEYWORD('DropGeometryColumn') + '(' +
61
style.SQL_TABLE(gqn(db_table)) + ', ' +
62
style.SQL_FIELD(gqn(self.column)) + ');')
67
SpatiaLite geometry columns are added by stored procedures;
72
def get_placeholder(self, value):
74
Provides a proper substitution value for Geometries that are not in the
75
SRID of the field. Specifically, this routine will substitute in the
76
Transform() and GeomFromText() function call(s).
78
if value is None or value.srid == self.srid:
79
return '%s(%%s,%s)' % (GEOM_FROM_TEXT, self.srid)
81
# Adding Transform() to the SQL placeholder.
82
return '%s(%s(%%s,%s), %s)' % (TRANSFORM, GEOM_FROM_TEXT, value.srid, self.srid)