File: aggregates.py

package info (click to toggle)
python-django 1.7.11-1%2Bdeb8u3
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 45,624 kB
  • sloc: python: 171,189; xml: 713; sh: 203; makefile: 199; sql: 11
file content (72 lines) | stat: -rw-r--r-- 1,956 bytes parent folder | download | duplicates (3)
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
62
63
64
65
66
67
68
69
70
71
72
from django.db.models.sql import aggregates
from django.db.models.sql.aggregates import *  # NOQA
from django.contrib.gis.db.models.fields import GeometryField


__all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'] + aggregates.__all__


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 with parameters."

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

        params = []

        if hasattr(self.col, 'as_sql'):
            field_name, params = 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)

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

        return sql_template % substitutions, 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