Debian Codegraph @

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

raw
1 from django.contrib.gis.db.models.fields import (
2 ExtentField,
3 GeometryCollectionField,
4 GeometryField,
5 LineStringField,
6 )
7 from django.db.models import Aggregate, Func, Value
8 from django.utils.functional import cached_property
9
10 __all__ = ["Collect", "Extent", "Extent3D", "MakeLine", "Union"]
11
12
13 class GeoAggregate(Aggregate):
14 function = None
15 is_extent = False
16
17 @cached_property
18 def output_field(self):
19 return self.output_field_class(self.source_expressions[0].output_field.srid)
20
21 def as_sql(self, compiler, connection, function=None, **extra_context):
22 # this will be called again in parent, but it's needed now - before
23 # we get the spatial_aggregate_name
24 connection.ops.check_expression_support(self)
25 return super().as_sql(
26 compiler,
27 connection,
28 function=function or connection.ops.spatial_aggregate_name(self.name),
29 **extra_context,
30 )
31
32 def as_oracle(self, compiler, connection, **extra_context):
33 if not self.is_extent:
34 tolerance = self.extra.get("tolerance") or getattr(self, "tolerance", 0.05)
35 clone = self.copy()
36 source_expressions = self.get_source_expressions()
37 source_expressions.pop() # Don't wrap filters with SDOAGGRTYPE().
38 spatial_type_expr = Func(
39 *source_expressions,
40 Value(tolerance),
41 function="SDOAGGRTYPE",
42 output_field=self.output_field,
43 )
44 source_expressions = [spatial_type_expr, self.filter]
45 clone.set_source_expressions(source_expressions)
46 return clone.as_sql(compiler, connection, **extra_context)
47 return self.as_sql(compiler, connection, **extra_context)
48
49 def resolve_expression(
50 self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
51 ):
52 c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
53 for field in c.get_source_fields():
54 if not hasattr(field, "geom_type"):
55 raise ValueError(
56 "Geospatial aggregates only allowed on geometry fields."
57 )
58 return c
59
60
61 class Collect(GeoAggregate):
62 name = "Collect"
63 output_field_class = GeometryCollectionField
64
65
66 class Extent(GeoAggregate):
67 name = "Extent"
68 is_extent = "2D"
69
70 def __init__(self, expression, **extra):
71 super().__init__(expression, output_field=ExtentField(), **extra)
72
73 def convert_value(self, value, expression, connection):
74 return connection.ops.convert_extent(value)
75
76
77 class Extent3D(GeoAggregate):
78 name = "Extent3D"
79 is_extent = "3D"
80
81 def __init__(self, expression, **extra):
82 super().__init__(expression, output_field=ExtentField(), **extra)
83
84 def convert_value(self, value, expression, connection):
85 return connection.ops.convert_extent3d(value)
86
87
88 class MakeLine(GeoAggregate):
89 name = "MakeLine"
90 output_field_class = LineStringField
91
92
93 class Union(GeoAggregate):
94 name = "Union"
95 output_field_class = GeometryField