Debian Codegraph @

django/contrib/gis/db/backends/spatialite/operations.py

raw
1 """
2 SQL functions reference lists:
3 https://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html
4 """
5
6 from django.contrib.gis.db import models
7 from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations
8 from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter
9 from django.contrib.gis.db.backends.utils import SpatialOperator
10 from django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase
11 from django.contrib.gis.geos.prototypes.io import wkb_r
12 from django.contrib.gis.measure import Distance
13 from django.core.exceptions import ImproperlyConfigured
14 from django.db.backends.sqlite3.operations import DatabaseOperations
15 from django.utils.functional import cached_property
16 from django.utils.version import get_version_tuple
17
18
19 class SpatialiteNullCheckOperator(SpatialOperator):
20 def as_sql(self, connection, lookup, template_params, sql_params):
21 sql, params = super().as_sql(connection, lookup, template_params, sql_params)
22 return "%s > 0" % sql, params
23
24
25 class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations):
26 name = "spatialite"
27 spatialite = True
28
29 Adapter = SpatiaLiteAdapter
30
31 collect = "Collect"
32 extent = "Extent"
33 makeline = "MakeLine"
34 unionagg = "GUnion"
35
36 from_text = "GeomFromText"
37
38 gis_operators = {
39 # Binary predicates
40 "equals": SpatialiteNullCheckOperator(func="Equals"),
41 "disjoint": SpatialiteNullCheckOperator(func="Disjoint"),
42 "touches": SpatialiteNullCheckOperator(func="Touches"),
43 "crosses": SpatialiteNullCheckOperator(func="Crosses"),
44 "within": SpatialiteNullCheckOperator(func="Within"),
45 "overlaps": SpatialiteNullCheckOperator(func="Overlaps"),
46 "contains": SpatialiteNullCheckOperator(func="Contains"),
47 "intersects": SpatialiteNullCheckOperator(func="Intersects"),
48 "relate": SpatialiteNullCheckOperator(func="Relate"),
49 "coveredby": SpatialiteNullCheckOperator(func="CoveredBy"),
50 "covers": SpatialiteNullCheckOperator(func="Covers"),
51 # Returns true if B's bounding box completely contains A's bounding box.
52 "contained": SpatialOperator(func="MbrWithin"),
53 # Returns true if A's bounding box completely contains B's bounding box.
54 "bbcontains": SpatialOperator(func="MbrContains"),
55 # Returns true if A's bounding box overlaps B's bounding box.
56 "bboverlaps": SpatialOperator(func="MbrOverlaps"),
57 # These are implemented here as synonyms for Equals
58 "same_as": SpatialiteNullCheckOperator(func="Equals"),
59 "exact": SpatialiteNullCheckOperator(func="Equals"),
60 # Distance predicates
61 "dwithin": SpatialOperator(func="PtDistWithin"),
62 }
63
64 disallowed_aggregates = (models.Extent3D,)
65
66 select = "CAST (AsEWKB(%s) AS BLOB)"
67
68 function_names = {
69 "AsWKB": "St_AsBinary",
70 "BoundingCircle": "GEOSMinimumBoundingCircle",
71 "ForcePolygonCW": "ST_ForceLHR",
72 "FromWKB": "ST_GeomFromWKB",
73 "FromWKT": "ST_GeomFromText",
74 "Length": "ST_Length",
75 "LineLocatePoint": "ST_Line_Locate_Point",
76 "NumPoints": "ST_NPoints",
77 "Reverse": "ST_Reverse",
78 "Scale": "ScaleCoords",
79 "Translate": "ST_Translate",
80 "Union": "ST_Union",
81 }
82
83 @cached_property
84 def unsupported_functions(self):
85 unsupported = {"GeometryDistance", "IsEmpty", "MemSize"}
86 if not self.geom_lib_version():
87 unsupported |= {"Azimuth", "GeoHash", "MakeValid"}
88 if self.spatial_version < (5, 1):
89 unsupported |= {"BoundingCircle"}
90 return unsupported
91
92 @cached_property
93 def spatial_version(self):
94 """Determine the version of the SpatiaLite library."""
95 try:
96 version = self.spatialite_version_tuple()[1:]
97 except Exception as exc:
98 raise ImproperlyConfigured(
99 'Cannot determine the SpatiaLite version for the "%s" database. '
100 "Was the SpatiaLite initialization SQL loaded on this database?"
101 % (self.connection.settings_dict["NAME"],)
102 ) from exc
103 if version < (4, 3, 0):
104 raise ImproperlyConfigured("GeoDjango supports SpatiaLite 4.3.0 and above.")
105 return version
106
107 def convert_extent(self, box):
108 """
109 Convert the polygon data received from SpatiaLite to min/max values.
110 """
111 if box is None:
112 return None
113 shell = GEOSGeometry(box).shell
114 xmin, ymin = shell[0][:2]
115 xmax, ymax = shell[2][:2]
116 return (xmin, ymin, xmax, ymax)
117
118 def geo_db_type(self, f):
119 """
120 Return None because geometry columns are added via the
121 `AddGeometryColumn` stored procedure on SpatiaLite.
122 """
123 return None
124
125 def get_distance(self, f, value, lookup_type):
126 """
127 Return the distance parameters for the given geometry field,
128 lookup value, and lookup type.
129 """
130 if not value:
131 return []
132 value = value[0]
133 if isinstance(value, Distance):
134 if f.geodetic(self.connection):
135 if lookup_type == "dwithin":
136 raise ValueError(
137 "Only numeric values of degree units are allowed on "
138 "geographic DWithin queries."
139 )
140 dist_param = value.m
141 else:
142 dist_param = getattr(
143 value, Distance.unit_attname(f.units_name(self.connection))
144 )
145 else:
146 dist_param = value
147 return [dist_param]
148
149 def _get_spatialite_func(self, func):
150 """
151 Helper routine for calling SpatiaLite functions and returning
152 their result.
153 Any error occurring in this method should be handled by the caller.
154 """
155 cursor = self.connection._cursor()
156 try:
157 cursor.execute("SELECT %s" % func)
158 row = cursor.fetchone()
159 finally:
160 cursor.close()
161 return row[0]
162
163 def geos_version(self):
164 "Return the version of GEOS used by SpatiaLite as a string."
165 return self._get_spatialite_func("geos_version()")
166
167 def proj_version(self):
168 """Return the version of the PROJ library used by SpatiaLite."""
169 return self._get_spatialite_func("proj4_version()")
170
171 def lwgeom_version(self):
172 """Return the version of LWGEOM library used by SpatiaLite."""
173 return self._get_spatialite_func("lwgeom_version()")
174
175 def rttopo_version(self):
176 """Return the version of RTTOPO library used by SpatiaLite."""
177 return self._get_spatialite_func("rttopo_version()")
178
179 def geom_lib_version(self):
180 """
181 Return the version of the version-dependant geom library used by
182 SpatiaLite.
183 """
184 if self.spatial_version >= (5,):
185 return self.rttopo_version()
186 else:
187 return self.lwgeom_version()
188
189 def spatialite_version(self):
190 "Return the SpatiaLite library version as a string."
191 return self._get_spatialite_func("spatialite_version()")
192
193 def spatialite_version_tuple(self):
194 """
195 Return the SpatiaLite version as a tuple (version string, major,
196 minor, subminor).
197 """
198 version = self.spatialite_version()
199 return (version,) + get_version_tuple(version)
200
201 def spatial_aggregate_name(self, agg_name):
202 """
203 Return the spatial aggregate SQL template and function for the
204 given Aggregate instance.
205 """
206 agg_name = "unionagg" if agg_name.lower() == "union" else agg_name.lower()
207 return getattr(self, agg_name)
208
209 # Routines for getting the OGC-compliant models.
210 def geometry_columns(self):
211 from django.contrib.gis.db.backends.spatialite.models import (
212 SpatialiteGeometryColumns,
213 )
214
215 return SpatialiteGeometryColumns
216
217 def spatial_ref_sys(self):
218 from django.contrib.gis.db.backends.spatialite.models import (
219 SpatialiteSpatialRefSys,
220 )
221
222 return SpatialiteSpatialRefSys
223
224 def get_geometry_converter(self, expression):
225 geom_class = expression.output_field.geom_class
226 read = wkb_r().read
227
228 def converter(value, expression, connection):
229 return None if value is None else GEOSGeometryBase(read(value), geom_class)
230
231 return converter