Debian Codegraph @

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

raw
1 from decimal import Decimal
2
3 from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField
4 from django.contrib.gis.db.models.sql import AreaField, DistanceField
5 from django.contrib.gis.geos import GEOSGeometry
6 from django.core.exceptions import FieldError
7 from django.db import NotSupportedError
8 from django.db.models import (
9 BinaryField,
10 BooleanField,
11 FloatField,
12 Func,
13 IntegerField,
14 TextField,
15 Transform,
16 Value,
17 )
18 from django.db.models.functions import Cast
19 from django.utils.functional import cached_property
20
21 NUMERIC_TYPES = (int, float, Decimal)
22
23
24 class GeoFuncMixin:
25 function = None
26 geom_param_pos = (0,)
27
28 def __init__(self, *expressions, **extra):
29 super().__init__(*expressions, **extra)
30
31 # Ensure that value expressions are geometric.
32 for pos in self.geom_param_pos:
33 expr = self.source_expressions[pos]
34 if not isinstance(expr, Value):
35 continue
36 try:
37 output_field = expr.output_field
38 except FieldError:
39 output_field = None
40 geom = expr.value
41 if (
42 not isinstance(geom, GEOSGeometry)
43 or output_field
44 and not isinstance(output_field, GeometryField)
45 ):
46 raise TypeError(
47 "%s function requires a geometric argument in position %d."
48 % (self.name, pos + 1)
49 )
50 if not geom.srid and not output_field:
51 raise ValueError("SRID is required for all geometries.")
52 if not output_field:
53 self.source_expressions[pos] = Value(
54 geom, output_field=GeometryField(srid=geom.srid)
55 )
56
57 @property
58 def name(self):
59 return self.__class__.__name__
60
61 @cached_property
62 def geo_field(self):
63 return self.source_expressions[self.geom_param_pos[0]].field
64
65 def as_sql(self, compiler, connection, function=None, **extra_context):
66 if self.function is None and function is None:
67 function = connection.ops.spatial_function_name(self.name)
68 return super().as_sql(compiler, connection, function=function, **extra_context)
69
70 def resolve_expression(self, *args, **kwargs):
71 res = super().resolve_expression(*args, **kwargs)
72 if not self.geom_param_pos:
73 return res
74
75 # Ensure that expressions are geometric.
76 source_fields = res.get_source_fields()
77 for pos in self.geom_param_pos:
78 field = source_fields[pos]
79 if not isinstance(field, GeometryField):
80 raise TypeError(
81 "%s function requires a GeometryField in position %s, got %s."
82 % (
83 self.name,
84 pos + 1,
85 type(field).__name__,
86 )
87 )
88
89 base_srid = res.geo_field.srid
90 for pos in self.geom_param_pos[1:]:
91 expr = res.source_expressions[pos]
92 expr_srid = expr.output_field.srid
93 if expr_srid != base_srid:
94 # Automatic SRID conversion so objects are comparable.
95 res.source_expressions[pos] = Transform(
96 expr, base_srid
97 ).resolve_expression(*args, **kwargs)
98 return res
99
100 def _handle_param(self, value, param_name="", check_types=None):
101 if not hasattr(value, "resolve_expression"):
102 if check_types and not isinstance(value, check_types):
103 raise TypeError(
104 "The %s parameter has the wrong type: should be %s."
105 % (param_name, check_types)
106 )
107 return value
108
109
110 class GeoFunc(GeoFuncMixin, Func):
111 pass
112
113
114 class GeomOutputGeoFunc(GeoFunc):
115 @cached_property
116 def output_field(self):
117 return GeometryField(srid=self.geo_field.srid)
118
119
120 class SQLiteDecimalToFloatMixin:
121 """
122 By default, Decimal values are converted to str by the SQLite backend, which
123 is not acceptable by the GIS functions expecting numeric values.
124 """
125
126 def as_sqlite(self, compiler, connection, **extra_context):
127 copy = self.copy()
128 copy.set_source_expressions(
129 [
130 (
131 Value(float(expr.value))
132 if hasattr(expr, "value") and isinstance(expr.value, Decimal)
133 else expr
134 )
135 for expr in copy.get_source_expressions()
136 ]
137 )
138 return copy.as_sql(compiler, connection, **extra_context)
139
140
141 class OracleToleranceMixin:
142 tolerance = 0.05
143
144 def as_oracle(self, compiler, connection, **extra_context):
145 tolerance = Value(
146 self._handle_param(
147 self.extra.get("tolerance", self.tolerance),
148 "tolerance",
149 NUMERIC_TYPES,
150 )
151 )
152 clone = self.copy()
153 clone.set_source_expressions([*self.get_source_expressions(), tolerance])
154 return clone.as_sql(compiler, connection, **extra_context)
155
156
157 class Area(OracleToleranceMixin, GeoFunc):
158 arity = 1
159
160 @cached_property
161 def output_field(self):
162 return AreaField(self.geo_field)
163
164 def as_sql(self, compiler, connection, **extra_context):
165 if not connection.features.supports_area_geodetic and self.geo_field.geodetic(
166 connection
167 ):
168 raise NotSupportedError(
169 "Area on geodetic coordinate systems not supported."
170 )
171 return super().as_sql(compiler, connection, **extra_context)
172
173 def as_sqlite(self, compiler, connection, **extra_context):
174 if self.geo_field.geodetic(connection):
175 extra_context["template"] = "%(function)s(%(expressions)s, %(spheroid)d)"
176 extra_context["spheroid"] = True
177 return self.as_sql(compiler, connection, **extra_context)
178
179
180 class Azimuth(GeoFunc):
181 output_field = FloatField()
182 arity = 2
183 geom_param_pos = (0, 1)
184
185
186 class AsGeoJSON(GeoFunc):
187 output_field = TextField()
188
189 def __init__(self, expression, bbox=False, crs=False, precision=8, **extra):
190 expressions = [expression]
191 if precision is not None:
192 expressions.append(self._handle_param(precision, "precision", int))
193 options = 0
194 if crs and bbox:
195 options = 3
196 elif bbox:
197 options = 1
198 elif crs:
199 options = 2
200 expressions.append(options)
201 super().__init__(*expressions, **extra)
202
203 def as_oracle(self, compiler, connection, **extra_context):
204 source_expressions = self.get_source_expressions()
205 clone = self.copy()
206 clone.set_source_expressions(source_expressions[:1])
207 return super(AsGeoJSON, clone).as_sql(compiler, connection, **extra_context)
208
209
210 class AsGML(GeoFunc):
211 geom_param_pos = (1,)
212 output_field = TextField()
213
214 def __init__(self, expression, version=2, precision=8, **extra):
215 expressions = [version, expression]
216 if precision is not None:
217 expressions.append(self._handle_param(precision, "precision", int))
218 super().__init__(*expressions, **extra)
219
220 def as_oracle(self, compiler, connection, **extra_context):
221 source_expressions = self.get_source_expressions()
222 version = source_expressions[0]
223 clone = self.copy()
224 clone.set_source_expressions([source_expressions[1]])
225 extra_context["function"] = (
226 "SDO_UTIL.TO_GML311GEOMETRY"
227 if version.value == 3
228 else "SDO_UTIL.TO_GMLGEOMETRY"
229 )
230 return super(AsGML, clone).as_sql(compiler, connection, **extra_context)
231
232
233 class AsKML(GeoFunc):
234 output_field = TextField()
235
236 def __init__(self, expression, precision=8, **extra):
237 expressions = [expression]
238 if precision is not None:
239 expressions.append(self._handle_param(precision, "precision", int))
240 super().__init__(*expressions, **extra)
241
242
243 class AsSVG(GeoFunc):
244 output_field = TextField()
245
246 def __init__(self, expression, relative=False, precision=8, **extra):
247 relative = (
248 relative if hasattr(relative, "resolve_expression") else int(relative)
249 )
250 expressions = [
251 expression,
252 relative,
253 self._handle_param(precision, "precision", int),
254 ]
255 super().__init__(*expressions, **extra)
256
257
258 class AsWKB(GeoFunc):
259 output_field = BinaryField()
260 arity = 1
261
262
263 class AsWKT(GeoFunc):
264 output_field = TextField()
265 arity = 1
266
267
268 class BoundingCircle(OracleToleranceMixin, GeomOutputGeoFunc):
269 def __init__(self, expression, num_seg=48, **extra):
270 super().__init__(expression, num_seg, **extra)
271
272 def as_oracle(self, compiler, connection, **extra_context):
273 clone = self.copy()
274 clone.set_source_expressions([self.get_source_expressions()[0]])
275 return super(BoundingCircle, clone).as_oracle(
276 compiler, connection, **extra_context
277 )
278
279 def as_sqlite(self, compiler, connection, **extra_context):
280 clone = self.copy()
281 clone.set_source_expressions([self.get_source_expressions()[0]])
282 return super(BoundingCircle, clone).as_sqlite(
283 compiler, connection, **extra_context
284 )
285
286
287 class Centroid(OracleToleranceMixin, GeomOutputGeoFunc):
288 arity = 1
289
290
291 class ClosestPoint(GeomOutputGeoFunc):
292 arity = 2
293 geom_param_pos = (0, 1)
294
295
296 class Difference(OracleToleranceMixin, GeomOutputGeoFunc):
297 arity = 2
298 geom_param_pos = (0, 1)
299
300
301 class DistanceResultMixin:
302 @cached_property
303 def output_field(self):
304 return DistanceField(self.geo_field)
305
306 def source_is_geography(self):
307 return self.geo_field.geography and self.geo_field.srid == 4326
308
309
310 class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
311 geom_param_pos = (0, 1)
312 spheroid = None
313
314 def __init__(self, expr1, expr2, spheroid=None, **extra):
315 expressions = [expr1, expr2]
316 if spheroid is not None:
317 self.spheroid = self._handle_param(spheroid, "spheroid", bool)
318 super().__init__(*expressions, **extra)
319
320 def as_postgresql(self, compiler, connection, **extra_context):
321 clone = self.copy()
322 function = None
323 expr2 = clone.source_expressions[1]
324 geography = self.source_is_geography()
325 if expr2.output_field.geography != geography:
326 if isinstance(expr2, Value):
327 expr2.output_field.geography = geography
328 else:
329 clone.source_expressions[1] = Cast(
330 expr2,
331 GeometryField(srid=expr2.output_field.srid, geography=geography),
332 )
333
334 if not geography and self.geo_field.geodetic(connection):
335 # Geometry fields with geodetic (lon/lat) coordinates need special
336 # distance functions.
337 if self.spheroid:
338 # DistanceSpheroid is more accurate and resource intensive than
339 # DistanceSphere.
340 function = connection.ops.spatial_function_name("DistanceSpheroid")
341 # Replace boolean param by the real spheroid of the base field
342 clone.source_expressions.append(
343 Value(self.geo_field.spheroid(connection))
344 )
345 else:
346 function = connection.ops.spatial_function_name("DistanceSphere")
347 return super(Distance, clone).as_sql(
348 compiler, connection, function=function, **extra_context
349 )
350
351 def as_sqlite(self, compiler, connection, **extra_context):
352 if self.geo_field.geodetic(connection):
353 # SpatiaLite returns NULL instead of zero on geodetic coordinates
354 extra_context["template"] = (
355 "COALESCE(%(function)s(%(expressions)s, %(spheroid)s), 0)"
356 )
357 extra_context["spheroid"] = int(bool(self.spheroid))
358 return super().as_sql(compiler, connection, **extra_context)
359
360
361 class Envelope(GeomOutputGeoFunc):
362 arity = 1
363
364
365 class ForcePolygonCW(GeomOutputGeoFunc):
366 arity = 1
367
368
369 class FromWKB(GeoFunc):
370 arity = 2
371 geom_param_pos = ()
372
373 def __init__(self, expression, srid=0, **extra):
374 expressions = [
375 expression,
376 self._handle_param(srid, "srid", int),
377 ]
378 if "output_field" not in extra:
379 extra["output_field"] = GeometryField(srid=srid)
380 super().__init__(*expressions, **extra)
381
382 def as_oracle(self, compiler, connection, **extra_context):
383 # Oracle doesn't support the srid parameter.
384 source_expressions = self.get_source_expressions()
385 clone = self.copy()
386 clone.set_source_expressions(source_expressions[:1])
387 return super(FromWKB, clone).as_sql(compiler, connection, **extra_context)
388
389
390 class FromWKT(FromWKB):
391 pass
392
393
394 class GeoHash(GeoFunc):
395 output_field = TextField()
396
397 def __init__(self, expression, precision=None, **extra):
398 expressions = [expression]
399 if precision is not None:
400 expressions.append(self._handle_param(precision, "precision", int))
401 super().__init__(*expressions, **extra)
402
403 def as_mysql(self, compiler, connection, **extra_context):
404 clone = self.copy()
405 # If no precision is provided, set it to the maximum.
406 if len(clone.source_expressions) < 2:
407 clone.source_expressions.append(Value(100))
408 return clone.as_sql(compiler, connection, **extra_context)
409
410
411 class GeometryDistance(GeoFunc):
412 output_field = FloatField()
413 arity = 2
414 function = ""
415 arg_joiner = " <-> "
416 geom_param_pos = (0, 1)
417
418
419 class Intersection(OracleToleranceMixin, GeomOutputGeoFunc):
420 arity = 2
421 geom_param_pos = (0, 1)
422
423
424 @BaseSpatialField.register_lookup
425 class IsEmpty(GeoFuncMixin, Transform):
426 lookup_name = "isempty"
427 output_field = BooleanField()
428
429
430 @BaseSpatialField.register_lookup
431 class IsValid(OracleToleranceMixin, GeoFuncMixin, Transform):
432 lookup_name = "isvalid"
433 output_field = BooleanField()
434
435 def as_oracle(self, compiler, connection, **extra_context):
436 sql, params = super().as_oracle(compiler, connection, **extra_context)
437 return "CASE %s WHEN 'TRUE' THEN 1 ELSE 0 END" % sql, params
438
439
440 class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
441 def __init__(self, expr1, spheroid=True, **extra):
442 self.spheroid = spheroid
443 super().__init__(expr1, **extra)
444
445 def as_sql(self, compiler, connection, **extra_context):
446 if (
447 self.geo_field.geodetic(connection)
448 and not connection.features.supports_length_geodetic
449 ):
450 raise NotSupportedError(
451 "This backend doesn't support Length on geodetic fields"
452 )
453 return super().as_sql(compiler, connection, **extra_context)
454
455 def as_postgresql(self, compiler, connection, **extra_context):
456 clone = self.copy()
457 function = None
458 if self.source_is_geography():
459 clone.source_expressions.append(Value(self.spheroid))
460 elif self.geo_field.geodetic(connection):
461 # Geometry fields with geodetic (lon/lat) coordinates need length_spheroid
462 function = connection.ops.spatial_function_name("LengthSpheroid")
463 clone.source_expressions.append(Value(self.geo_field.spheroid(connection)))
464 else:
465 dim = min(f.dim for f in self.get_source_fields() if f)
466 if dim > 2:
467 function = connection.ops.length3d
468 return super(Length, clone).as_sql(
469 compiler, connection, function=function, **extra_context
470 )
471
472 def as_sqlite(self, compiler, connection, **extra_context):
473 function = None
474 if self.geo_field.geodetic(connection):
475 function = "GeodesicLength" if self.spheroid else "GreatCircleLength"
476 return super().as_sql(compiler, connection, function=function, **extra_context)
477
478
479 class LineLocatePoint(GeoFunc):
480 output_field = FloatField()
481 arity = 2
482 geom_param_pos = (0, 1)
483
484
485 class MakeValid(GeomOutputGeoFunc):
486 pass
487
488
489 class MemSize(GeoFunc):
490 output_field = IntegerField()
491 arity = 1
492
493
494 class NumGeometries(GeoFunc):
495 output_field = IntegerField()
496 arity = 1
497
498
499 class NumPoints(GeoFunc):
500 output_field = IntegerField()
501 arity = 1
502
503
504 class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
505 arity = 1
506
507 def as_postgresql(self, compiler, connection, **extra_context):
508 function = None
509 if self.geo_field.geodetic(connection) and not self.source_is_geography():
510 raise NotSupportedError(
511 "ST_Perimeter cannot use a non-projected non-geography field."
512 )
513 dim = min(f.dim for f in self.get_source_fields())
514 if dim > 2:
515 function = connection.ops.perimeter3d
516 return super().as_sql(compiler, connection, function=function, **extra_context)
517
518 def as_sqlite(self, compiler, connection, **extra_context):
519 if self.geo_field.geodetic(connection):
520 raise NotSupportedError("Perimeter cannot use a non-projected field.")
521 return super().as_sql(compiler, connection, **extra_context)
522
523
524 class PointOnSurface(OracleToleranceMixin, GeomOutputGeoFunc):
525 arity = 1
526
527
528 class Reverse(GeoFunc):
529 arity = 1
530
531
532 class Scale(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc):
533 def __init__(self, expression, x, y, z=0.0, **extra):
534 expressions = [
535 expression,
536 self._handle_param(x, "x", NUMERIC_TYPES),
537 self._handle_param(y, "y", NUMERIC_TYPES),
538 ]
539 if z != 0.0:
540 expressions.append(self._handle_param(z, "z", NUMERIC_TYPES))
541 super().__init__(*expressions, **extra)
542
543
544 class SnapToGrid(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc):
545 def __init__(self, expression, *args, **extra):
546 nargs = len(args)
547 expressions = [expression]
548 if nargs in (1, 2):
549 expressions.extend(
550 [self._handle_param(arg, "", NUMERIC_TYPES) for arg in args]
551 )
552 elif nargs == 4:
553 # Reverse origin and size param ordering
554 expressions += [
555 *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[2:]),
556 *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[0:2]),
557 ]
558 else:
559 raise ValueError("Must provide 1, 2, or 4 arguments to `SnapToGrid`.")
560 super().__init__(*expressions, **extra)
561
562
563 class SymDifference(OracleToleranceMixin, GeomOutputGeoFunc):
564 arity = 2
565 geom_param_pos = (0, 1)
566
567
568 class Transform(GeomOutputGeoFunc):
569 def __init__(self, expression, srid, **extra):
570 expressions = [
571 expression,
572 self._handle_param(srid, "srid", int),
573 ]
574 if "output_field" not in extra:
575 extra["output_field"] = GeometryField(srid=srid)
576 super().__init__(*expressions, **extra)
577
578
579 class Translate(Scale):
580 def as_sqlite(self, compiler, connection, **extra_context):
581 clone = self.copy()
582 if len(self.source_expressions) < 4:
583 # Always provide the z parameter for ST_Translate
584 clone.source_expressions.append(Value(0))
585 return super(Translate, clone).as_sqlite(compiler, connection, **extra_context)
586
587
588 class Union(OracleToleranceMixin, GeomOutputGeoFunc):
589 arity = 2
590 geom_param_pos = (0, 1)