Debian Codegraph @

django/contrib/gis/db/models/fields.py

raw
1 from collections import defaultdict, namedtuple
2
3 from django.contrib.gis import forms, gdal
4 from django.contrib.gis.db.models.proxy import SpatialProxy
5 from django.contrib.gis.gdal.error import GDALException
6 from django.contrib.gis.geos import (
7 GeometryCollection,
8 GEOSException,
9 GEOSGeometry,
10 LineString,
11 MultiLineString,
12 MultiPoint,
13 MultiPolygon,
14 Point,
15 Polygon,
16 )
17 from django.core.exceptions import ImproperlyConfigured
18 from django.db.models import Field
19 from django.utils.translation import gettext_lazy as _
20
21 # Local cache of the spatial_ref_sys table, which holds SRID data for each
22 # spatial database alias. This cache exists so that the database isn't queried
23 # for SRID info each time a distance query is constructed.
24 _srid_cache = defaultdict(dict)
25
26
27 SRIDCacheEntry = namedtuple(
28 "SRIDCacheEntry", ["units", "units_name", "spheroid", "geodetic"]
29 )
30
31
32 def get_srid_info(srid, connection):
33 """
34 Return the units, unit name, and spheroid WKT associated with the
35 given SRID from the `spatial_ref_sys` (or equivalent) spatial database
36 table for the given database connection. These results are cached.
37 """
38 from django.contrib.gis.gdal import SpatialReference
39
40 try:
41 # The SpatialRefSys model for the spatial backend.
42 SpatialRefSys = connection.ops.spatial_ref_sys()
43 except NotImplementedError:
44 SpatialRefSys = None
45
46 alias, get_srs = (
47 (
48 connection.alias,
49 lambda srid: SpatialRefSys.objects.using(connection.alias)
50 .get(srid=srid)
51 .srs,
52 )
53 if SpatialRefSys
54 else (None, SpatialReference)
55 )
56 if srid not in _srid_cache[alias]:
57 srs = get_srs(srid)
58 units, units_name = srs.units
59 _srid_cache[alias][srid] = SRIDCacheEntry(
60 units=units,
61 units_name=units_name,
62 spheroid='SPHEROID["%s",%s,%s]'
63 % (srs["spheroid"], srs.semi_major, srs.inverse_flattening),
64 geodetic=srs.geographic,
65 )
66
67 return _srid_cache[alias][srid]
68
69
70 class BaseSpatialField(Field):
71 """
72 The Base GIS Field.
73
74 It's used as a base class for GeometryField and RasterField. Defines
75 properties that are common to all GIS fields such as the characteristics
76 of the spatial reference system of the field.
77 """
78
79 description = _("The base GIS field.")
80 empty_strings_allowed = False
81
82 def __init__(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs):
83 """
84 The initialization function for base spatial fields. Takes the following
85 as keyword arguments:
86
87 srid:
88 The spatial reference system identifier, an OGC standard.
89 Defaults to 4326 (WGS84).
90
91 spatial_index:
92 Indicates whether to create a spatial index. Defaults to True.
93 Set this instead of 'db_index' for geographic fields since index
94 creation is different for geometry columns.
95 """
96
97 # Setting the index flag with the value of the `spatial_index` keyword.
98 self.spatial_index = spatial_index
99
100 # Setting the SRID and getting the units. Unit information must be
101 # easily available in the field instance for distance queries.
102 self.srid = srid
103
104 # Setting the verbose_name keyword argument with the positional
105 # first parameter, so this works like normal fields.
106 kwargs["verbose_name"] = verbose_name
107
108 super().__init__(**kwargs)
109
110 def deconstruct(self):
111 name, path, args, kwargs = super().deconstruct()
112 # Always include SRID for less fragility; include spatial index if it's
113 # not the default value.
114 kwargs["srid"] = self.srid
115 if self.spatial_index is not True:
116 kwargs["spatial_index"] = self.spatial_index
117 return name, path, args, kwargs
118
119 def db_type(self, connection):
120 return connection.ops.geo_db_type(self)
121
122 def spheroid(self, connection):
123 return get_srid_info(self.srid, connection).spheroid
124
125 def units(self, connection):
126 return get_srid_info(self.srid, connection).units
127
128 def units_name(self, connection):
129 return get_srid_info(self.srid, connection).units_name
130
131 def geodetic(self, connection):
132 """
133 Return true if this field's SRID corresponds with a coordinate
134 system that uses non-projected units (e.g., latitude/longitude).
135 """
136 return get_srid_info(self.srid, connection).geodetic
137
138 def get_placeholder(self, value, compiler, connection):
139 """
140 Return the placeholder for the spatial column for the
141 given value.
142 """
143 return connection.ops.get_geom_placeholder(self, value, compiler)
144
145 def get_srid(self, obj):
146 """
147 Return the default SRID for the given geometry or raster, taking into
148 account the SRID set for the field. For example, if the input geometry
149 or raster doesn't have an SRID, then the SRID of the field will be
150 returned.
151 """
152 srid = obj.srid # SRID of given geometry.
153 if srid is None or self.srid == -1 or (srid == -1 and self.srid != -1):
154 return self.srid
155 else:
156 return srid
157
158 def get_db_prep_value(self, value, connection, *args, **kwargs):
159 if value is None:
160 return None
161 return connection.ops.Adapter(
162 super().get_db_prep_value(value, connection, *args, **kwargs),
163 **(
164 {"geography": True}
165 if self.geography and connection.features.supports_geography
166 else {}
167 ),
168 )
169
170 def get_raster_prep_value(self, value, is_candidate):
171 """
172 Return a GDALRaster if conversion is successful, otherwise return None.
173 """
174 if isinstance(value, gdal.GDALRaster):
175 return value
176 elif is_candidate:
177 try:
178 return gdal.GDALRaster(value)
179 except GDALException:
180 pass
181 elif isinstance(value, dict):
182 try:
183 return gdal.GDALRaster(value)
184 except GDALException:
185 raise ValueError(
186 "Couldn't create spatial object from lookup value '%s'." % value
187 )
188
189 def get_prep_value(self, value):
190 obj = super().get_prep_value(value)
191 if obj is None:
192 return None
193 # When the input is not a geometry or raster, attempt to construct one
194 # from the given string input.
195 if isinstance(obj, GEOSGeometry):
196 pass
197 else:
198 # Check if input is a candidate for conversion to raster or geometry.
199 is_candidate = isinstance(obj, (bytes, str)) or hasattr(
200 obj, "__geo_interface__"
201 )
202 # Try to convert the input to raster.
203 raster = self.get_raster_prep_value(obj, is_candidate)
204
205 if raster:
206 obj = raster
207 elif is_candidate:
208 try:
209 obj = GEOSGeometry(obj)
210 except (GEOSException, GDALException):
211 raise ValueError(
212 "Couldn't create spatial object from lookup value '%s'." % obj
213 )
214 else:
215 raise ValueError(
216 "Cannot use object with type %s for a spatial lookup parameter."
217 % type(obj).__name__
218 )
219
220 # Assigning the SRID value.
221 obj.srid = self.get_srid(obj)
222 return obj
223
224
225 class GeometryField(BaseSpatialField):
226 """
227 The base Geometry field -- maps to the OpenGIS Specification Geometry type.
228 """
229
230 description = _(
231 "The base Geometry field — maps to the OpenGIS Specification Geometry type."
232 )
233 form_class = forms.GeometryField
234 # The OpenGIS Geometry name.
235 geom_type = "GEOMETRY"
236 geom_class = None
237
238 def __init__(
239 self,
240 verbose_name=None,
241 dim=2,
242 geography=False,
243 *,
244 extent=(-180.0, -90.0, 180.0, 90.0),
245 tolerance=0.05,
246 **kwargs,
247 ):
248 """
249 The initialization function for geometry fields. In addition to the
250 parameters from BaseSpatialField, it takes the following as keyword
251 arguments:
252
253 dim:
254 The number of dimensions for this geometry. Defaults to 2.
255
256 extent:
257 Customize the extent, in a 4-tuple of WGS 84 coordinates, for the
258 geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults
259 to (-180.0, -90.0, 180.0, 90.0).
260
261 tolerance:
262 Define the tolerance, in meters, to use for the geometry field
263 entry in the `USER_SDO_GEOM_METADATA` table. Defaults to 0.05.
264 """
265 # Setting the dimension of the geometry field.
266 self.dim = dim
267
268 # Is this a geography rather than a geometry column?
269 self.geography = geography
270
271 # Oracle-specific private attributes for creating the entry in
272 # `USER_SDO_GEOM_METADATA`
273 self._extent = extent
274 self._tolerance = tolerance
275
276 super().__init__(verbose_name=verbose_name, **kwargs)
277
278 def deconstruct(self):
279 name, path, args, kwargs = super().deconstruct()
280 # Include kwargs if they're not the default values.
281 if self.dim != 2:
282 kwargs["dim"] = self.dim
283 if self.geography is not False:
284 kwargs["geography"] = self.geography
285 if self._extent != (-180.0, -90.0, 180.0, 90.0):
286 kwargs["extent"] = self._extent
287 if self._tolerance != 0.05:
288 kwargs["tolerance"] = self._tolerance
289 return name, path, args, kwargs
290
291 def contribute_to_class(self, cls, name, **kwargs):
292 super().contribute_to_class(cls, name, **kwargs)
293
294 # Setup for lazy-instantiated Geometry object.
295 setattr(
296 cls,
297 self.attname,
298 SpatialProxy(self.geom_class or GEOSGeometry, self, load_func=GEOSGeometry),
299 )
300
301 def formfield(self, **kwargs):
302 defaults = {
303 "form_class": self.form_class,
304 "geom_type": self.geom_type,
305 "srid": self.srid,
306 **kwargs,
307 }
308 if self.dim > 2 and not getattr(
309 defaults["form_class"].widget, "supports_3d", False
310 ):
311 defaults.setdefault("widget", forms.Textarea)
312 return super().formfield(**defaults)
313
314 def select_format(self, compiler, sql, params):
315 """
316 Return the selection format string, depending on the requirements
317 of the spatial backend. For example, Oracle and MySQL require custom
318 selection formats in order to retrieve geometries in OGC WKB.
319 """
320 if not compiler.query.subquery:
321 return compiler.connection.ops.select % sql, params
322 return sql, params
323
324
325 # The OpenGIS Geometry Type Fields
326 class PointField(GeometryField):
327 geom_type = "POINT"
328 geom_class = Point
329 form_class = forms.PointField
330 description = _("Point")
331
332
333 class LineStringField(GeometryField):
334 geom_type = "LINESTRING"
335 geom_class = LineString
336 form_class = forms.LineStringField
337 description = _("Line string")
338
339
340 class PolygonField(GeometryField):
341 geom_type = "POLYGON"
342 geom_class = Polygon
343 form_class = forms.PolygonField
344 description = _("Polygon")
345
346
347 class MultiPointField(GeometryField):
348 geom_type = "MULTIPOINT"
349 geom_class = MultiPoint
350 form_class = forms.MultiPointField
351 description = _("Multi-point")
352
353
354 class MultiLineStringField(GeometryField):
355 geom_type = "MULTILINESTRING"
356 geom_class = MultiLineString
357 form_class = forms.MultiLineStringField
358 description = _("Multi-line string")
359
360
361 class MultiPolygonField(GeometryField):
362 geom_type = "MULTIPOLYGON"
363 geom_class = MultiPolygon
364 form_class = forms.MultiPolygonField
365 description = _("Multi polygon")
366
367
368 class GeometryCollectionField(GeometryField):
369 geom_type = "GEOMETRYCOLLECTION"
370 geom_class = GeometryCollection
371 form_class = forms.GeometryCollectionField
372 description = _("Geometry collection")
373
374
375 class ExtentField(Field):
376 "Used as a return value from an extent aggregate"
377
378 description = _("Extent Aggregate Field")
379
380 def get_internal_type(self):
381 return "ExtentField"
382
383 def select_format(self, compiler, sql, params):
384 select = compiler.connection.ops.select_extent
385 return select % sql if select else sql, params
386
387
388 class RasterField(BaseSpatialField):
389 """
390 Raster field for GeoDjango -- evaluates into GDALRaster objects.
391 """
392
393 description = _("Raster Field")
394 geom_type = "RASTER"
395 geography = False
396
397 def _check_connection(self, connection):
398 # Make sure raster fields are used only on backends with raster support.
399 if (
400 not connection.features.gis_enabled
401 or not connection.features.supports_raster
402 ):
403 raise ImproperlyConfigured(
404 "Raster fields require backends with raster support."
405 )
406
407 def db_type(self, connection):
408 self._check_connection(connection)
409 return super().db_type(connection)
410
411 def from_db_value(self, value, expression, connection):
412 return connection.ops.parse_raster(value)
413
414 def contribute_to_class(self, cls, name, **kwargs):
415 super().contribute_to_class(cls, name, **kwargs)
416 # Setup for lazy-instantiated Raster object. For large querysets, the
417 # instantiation of all GDALRasters can potentially be expensive. This
418 # delays the instantiation of the objects to the moment of evaluation
419 # of the raster attribute.
420 setattr(cls, self.attname, SpatialProxy(gdal.GDALRaster, self))
421
422 def get_transform(self, name):
423 from django.contrib.gis.db.models.lookups import RasterBandTransform
424
425 try:
426 band_index = int(name)
427 return type(
428 "SpecificRasterBandTransform",
429 (RasterBandTransform,),
430 {"band_index": band_index},
431 )
432 except ValueError:
433 pass
434 return super().get_transform(name)