summaryrefslogtreecommitdiff
path: root/django/contrib/gis/db/models/sql/aggregates.py
blob: fed2a2ea4db5c061c441c6f7e8bb7887823514a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django.db.models.sql.aggregates import *
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.gis.db.models.sql.conversion import GeomField

class GeoAggregate(Aggregate):
    # Default SQL template for spatial aggregates.
    sql_template = '%(function)s(%(field)s)'

    # Conversion class, if necessary.
    conversion_class = None

    # Flags for indicating the type of the aggregate.
    is_extent = False

    def __init__(self, col, source=None, is_summary=False, tolerance=0.05, **extra):
        super(GeoAggregate, self).__init__(col, source, is_summary, **extra)

        # Required by some Oracle aggregates.
        self.tolerance = tolerance

        # Can't use geographic aggregates on non-geometry fields.
        if not isinstance(self.source, GeometryField):
            raise ValueError('Geospatial aggregates only allowed on geometry fields.')

    def as_sql(self, qn, connection):
        "Return the aggregate, rendered as SQL."

        if connection.ops.oracle:
            self.extra['tolerance'] = self.tolerance

        if hasattr(self.col, 'as_sql'):
            field_name = self.col.as_sql(qn, connection)
        elif isinstance(self.col, (list, tuple)):
            field_name = '.'.join([qn(c) for c in self.col])
        else:
            field_name = self.col

        sql_template, sql_function = connection.ops.spatial_aggregate_sql(self)

        params = {
            'function': sql_function,
            'field': field_name
        }
        params.update(self.extra)

        return sql_template % params

class Collect(GeoAggregate):
    pass

class Extent(GeoAggregate):
    is_extent = '2D'

class Extent3D(GeoAggregate):
    is_extent = '3D'

class MakeLine(GeoAggregate):
    pass

class Union(GeoAggregate):
    pass