PageRenderTime 45ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/contrib/gis/db/backends/postgis/operations.py

http://github.com/JetBrains/intellij-community
Python | 589 lines | 421 code | 52 blank | 116 comment | 60 complexity | 49161eca7db8bde05a032b8e8c9a32b9 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. import re
  2. from decimal import Decimal
  3. from django.conf import settings
  4. from django.contrib.gis.db.backends.base import BaseSpatialOperations
  5. from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction
  6. from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter
  7. from django.contrib.gis.geometry.backend import Geometry
  8. from django.contrib.gis.measure import Distance
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.db.backends.postgresql_psycopg2.base import DatabaseOperations
  11. from django.db.utils import DatabaseError
  12. #### Classes used in constructing PostGIS spatial SQL ####
  13. class PostGISOperator(SpatialOperation):
  14. "For PostGIS operators (e.g. `&&`, `~`)."
  15. def __init__(self, operator):
  16. super(PostGISOperator, self).__init__(operator=operator)
  17. class PostGISFunction(SpatialFunction):
  18. "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)."
  19. def __init__(self, prefix, function, **kwargs):
  20. super(PostGISFunction, self).__init__(prefix + function, **kwargs)
  21. class PostGISFunctionParam(PostGISFunction):
  22. "For PostGIS functions that take another parameter (e.g. DWithin, Relate)."
  23. sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)'
  24. class PostGISDistance(PostGISFunction):
  25. "For PostGIS distance operations."
  26. dist_func = 'Distance'
  27. sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s'
  28. def __init__(self, prefix, operator):
  29. super(PostGISDistance, self).__init__(prefix, self.dist_func,
  30. operator=operator)
  31. class PostGISSpheroidDistance(PostGISFunction):
  32. "For PostGIS spherical distance operations (using the spheroid)."
  33. dist_func = 'distance_spheroid'
  34. sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s'
  35. def __init__(self, prefix, operator):
  36. # An extra parameter in `end_subst` is needed for the spheroid string.
  37. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func,
  38. operator=operator)
  39. class PostGISSphereDistance(PostGISDistance):
  40. "For PostGIS spherical distance operations."
  41. dist_func = 'distance_sphere'
  42. class PostGISRelate(PostGISFunctionParam):
  43. "For PostGIS Relate(<geom>, <pattern>) calls."
  44. pattern_regex = re.compile(r'^[012TF\*]{9}$')
  45. def __init__(self, prefix, pattern):
  46. if not self.pattern_regex.match(pattern):
  47. raise ValueError('Invalid intersection matrix pattern "%s".' % pattern)
  48. super(PostGISRelate, self).__init__(prefix, 'Relate')
  49. class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
  50. compiler_module = 'django.contrib.gis.db.models.sql.compiler'
  51. name = 'postgis'
  52. postgis = True
  53. version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)')
  54. valid_aggregates = dict([(k, None) for k in
  55. ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')])
  56. Adapter = PostGISAdapter
  57. Adaptor = Adapter # Backwards-compatibility alias.
  58. def __init__(self, connection):
  59. super(PostGISOperations, self).__init__(connection)
  60. # Trying to get the PostGIS version because the function
  61. # signatures will depend on the version used. The cost
  62. # here is a database query to determine the version, which
  63. # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple
  64. # comprising user-supplied values for the major, minor, and
  65. # subminor revision of PostGIS.
  66. try:
  67. if hasattr(settings, 'POSTGIS_VERSION'):
  68. vtup = settings.POSTGIS_VERSION
  69. if len(vtup) == 3:
  70. # The user-supplied PostGIS version.
  71. version = vtup
  72. else:
  73. # This was the old documented way, but it's stupid to
  74. # include the string.
  75. version = vtup[1:4]
  76. else:
  77. vtup = self.postgis_version_tuple()
  78. version = vtup[1:]
  79. # Getting the prefix -- even though we don't officially support
  80. # PostGIS 1.2 anymore, keeping it anyway in case a prefix change
  81. # for something else is necessary.
  82. if version >= (1, 2, 2):
  83. prefix = 'ST_'
  84. else:
  85. prefix = ''
  86. self.geom_func_prefix = prefix
  87. self.spatial_version = version
  88. except DatabaseError:
  89. raise ImproperlyConfigured('Cannot determine PostGIS version for database "%s". '
  90. 'GeoDjango requires at least PostGIS version 1.3. '
  91. 'Was the database created from a spatial database '
  92. 'template?' % self.connection.settings_dict['NAME']
  93. )
  94. except Exception, e:
  95. # TODO: Raise helpful exceptions as they become known.
  96. raise
  97. # PostGIS-specific operators. The commented descriptions of these
  98. # operators come from Section 7.6 of the PostGIS 1.4 documentation.
  99. self.geometry_operators = {
  100. # The "&<" operator returns true if A's bounding box overlaps or
  101. # is to the left of B's bounding box.
  102. 'overlaps_left' : PostGISOperator('&<'),
  103. # The "&>" operator returns true if A's bounding box overlaps or
  104. # is to the right of B's bounding box.
  105. 'overlaps_right' : PostGISOperator('&>'),
  106. # The "<<" operator returns true if A's bounding box is strictly
  107. # to the left of B's bounding box.
  108. 'left' : PostGISOperator('<<'),
  109. # The ">>" operator returns true if A's bounding box is strictly
  110. # to the right of B's bounding box.
  111. 'right' : PostGISOperator('>>'),
  112. # The "&<|" operator returns true if A's bounding box overlaps or
  113. # is below B's bounding box.
  114. 'overlaps_below' : PostGISOperator('&<|'),
  115. # The "|&>" operator returns true if A's bounding box overlaps or
  116. # is above B's bounding box.
  117. 'overlaps_above' : PostGISOperator('|&>'),
  118. # The "<<|" operator returns true if A's bounding box is strictly
  119. # below B's bounding box.
  120. 'strictly_below' : PostGISOperator('<<|'),
  121. # The "|>>" operator returns true if A's bounding box is strictly
  122. # above B's bounding box.
  123. 'strictly_above' : PostGISOperator('|>>'),
  124. # The "~=" operator is the "same as" operator. It tests actual
  125. # geometric equality of two features. So if A and B are the same feature,
  126. # vertex-by-vertex, the operator returns true.
  127. 'same_as' : PostGISOperator('~='),
  128. 'exact' : PostGISOperator('~='),
  129. # The "@" operator returns true if A's bounding box is completely contained
  130. # by B's bounding box.
  131. 'contained' : PostGISOperator('@'),
  132. # The "~" operator returns true if A's bounding box completely contains
  133. # by B's bounding box.
  134. 'bbcontains' : PostGISOperator('~'),
  135. # The "&&" operator returns true if A's bounding box overlaps
  136. # B's bounding box.
  137. 'bboverlaps' : PostGISOperator('&&'),
  138. }
  139. self.geometry_functions = {
  140. 'equals' : PostGISFunction(prefix, 'Equals'),
  141. 'disjoint' : PostGISFunction(prefix, 'Disjoint'),
  142. 'touches' : PostGISFunction(prefix, 'Touches'),
  143. 'crosses' : PostGISFunction(prefix, 'Crosses'),
  144. 'within' : PostGISFunction(prefix, 'Within'),
  145. 'overlaps' : PostGISFunction(prefix, 'Overlaps'),
  146. 'contains' : PostGISFunction(prefix, 'Contains'),
  147. 'intersects' : PostGISFunction(prefix, 'Intersects'),
  148. 'relate' : (PostGISRelate, basestring),
  149. }
  150. # Valid distance types and substitutions
  151. dtypes = (Decimal, Distance, float, int, long)
  152. def get_dist_ops(operator):
  153. "Returns operations for both regular and spherical distances."
  154. return {'cartesian' : PostGISDistance(prefix, operator),
  155. 'sphere' : PostGISSphereDistance(prefix, operator),
  156. 'spheroid' : PostGISSpheroidDistance(prefix, operator),
  157. }
  158. self.distance_functions = {
  159. 'distance_gt' : (get_dist_ops('>'), dtypes),
  160. 'distance_gte' : (get_dist_ops('>='), dtypes),
  161. 'distance_lt' : (get_dist_ops('<'), dtypes),
  162. 'distance_lte' : (get_dist_ops('<='), dtypes),
  163. }
  164. # Versions 1.2.2+ have KML serialization support.
  165. if version < (1, 2, 2):
  166. ASKML = False
  167. else:
  168. ASKML = 'ST_AsKML'
  169. self.geometry_functions.update(
  170. {'coveredby' : PostGISFunction(prefix, 'CoveredBy'),
  171. 'covers' : PostGISFunction(prefix, 'Covers'),
  172. })
  173. self.distance_functions['dwithin'] = (PostGISFunctionParam(prefix, 'DWithin'), dtypes)
  174. # Adding the distance functions to the geometries lookup.
  175. self.geometry_functions.update(self.distance_functions)
  176. # The union aggregate and topology operation use the same signature
  177. # in versions 1.3+.
  178. if version < (1, 3, 0):
  179. UNIONAGG = 'GeomUnion'
  180. UNION = 'Union'
  181. MAKELINE = False
  182. else:
  183. UNIONAGG = 'ST_Union'
  184. UNION = 'ST_Union'
  185. MAKELINE = 'ST_MakeLine'
  186. # Only PostGIS versions 1.3.4+ have GeoJSON serialization support.
  187. if version < (1, 3, 4):
  188. GEOJSON = False
  189. else:
  190. GEOJSON = prefix + 'AsGeoJson'
  191. # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4.
  192. if version >= (1, 4, 0):
  193. GEOHASH = 'ST_GeoHash'
  194. BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle'
  195. self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly')
  196. else:
  197. GEOHASH, BOUNDINGCIRCLE = False, False
  198. # Geography type support added in 1.5.
  199. if version >= (1, 5, 0):
  200. self.geography = True
  201. # Only a subset of the operators and functions are available
  202. # for the geography type.
  203. self.geography_functions = self.distance_functions.copy()
  204. self.geography_functions.update({
  205. 'coveredby' : self.geometry_functions['coveredby'],
  206. 'covers' : self.geometry_functions['covers'],
  207. 'intersects' : self.geometry_functions['intersects'],
  208. })
  209. self.geography_operators = {
  210. 'bboverlaps' : PostGISOperator('&&'),
  211. }
  212. # Creating a dictionary lookup of all GIS terms for PostGIS.
  213. gis_terms = ['isnull']
  214. gis_terms += self.geometry_operators.keys()
  215. gis_terms += self.geometry_functions.keys()
  216. self.gis_terms = dict([(term, None) for term in gis_terms])
  217. self.area = prefix + 'Area'
  218. self.bounding_circle = BOUNDINGCIRCLE
  219. self.centroid = prefix + 'Centroid'
  220. self.collect = prefix + 'Collect'
  221. self.difference = prefix + 'Difference'
  222. self.distance = prefix + 'Distance'
  223. self.distance_sphere = prefix + 'distance_sphere'
  224. self.distance_spheroid = prefix + 'distance_spheroid'
  225. self.envelope = prefix + 'Envelope'
  226. self.extent = prefix + 'Extent'
  227. self.extent3d = prefix + 'Extent3D'
  228. self.force_rhr = prefix + 'ForceRHR'
  229. self.geohash = GEOHASH
  230. self.geojson = GEOJSON
  231. self.gml = prefix + 'AsGML'
  232. self.intersection = prefix + 'Intersection'
  233. self.kml = ASKML
  234. self.length = prefix + 'Length'
  235. self.length3d = prefix + 'Length3D'
  236. self.length_spheroid = prefix + 'length_spheroid'
  237. self.makeline = MAKELINE
  238. self.mem_size = prefix + 'mem_size'
  239. self.num_geom = prefix + 'NumGeometries'
  240. self.num_points =prefix + 'npoints'
  241. self.perimeter = prefix + 'Perimeter'
  242. self.perimeter3d = prefix + 'Perimeter3D'
  243. self.point_on_surface = prefix + 'PointOnSurface'
  244. self.polygonize = prefix + 'Polygonize'
  245. self.reverse = prefix + 'Reverse'
  246. self.scale = prefix + 'Scale'
  247. self.snap_to_grid = prefix + 'SnapToGrid'
  248. self.svg = prefix + 'AsSVG'
  249. self.sym_difference = prefix + 'SymDifference'
  250. self.transform = prefix + 'Transform'
  251. self.translate = prefix + 'Translate'
  252. self.union = UNION
  253. self.unionagg = UNIONAGG
  254. def check_aggregate_support(self, aggregate):
  255. """
  256. Checks if the given aggregate name is supported (that is, if it's
  257. in `self.valid_aggregates`).
  258. """
  259. agg_name = aggregate.__class__.__name__
  260. return agg_name in self.valid_aggregates
  261. def convert_extent(self, box):
  262. """
  263. Returns a 4-tuple extent for the `Extent` aggregate by converting
  264. the bounding box text returned by PostGIS (`box` argument), for
  265. example: "BOX(-90.0 30.0, -85.0 40.0)".
  266. """
  267. ll, ur = box[4:-1].split(',')
  268. xmin, ymin = map(float, ll.split())
  269. xmax, ymax = map(float, ur.split())
  270. return (xmin, ymin, xmax, ymax)
  271. def convert_extent3d(self, box3d):
  272. """
  273. Returns a 6-tuple extent for the `Extent3D` aggregate by converting
  274. the 3d bounding-box text returnded by PostGIS (`box3d` argument), for
  275. example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)".
  276. """
  277. ll, ur = box3d[6:-1].split(',')
  278. xmin, ymin, zmin = map(float, ll.split())
  279. xmax, ymax, zmax = map(float, ur.split())
  280. return (xmin, ymin, zmin, xmax, ymax, zmax)
  281. def convert_geom(self, hex, geo_field):
  282. """
  283. Converts the geometry returned from PostGIS aggretates.
  284. """
  285. if hex:
  286. return Geometry(hex)
  287. else:
  288. return None
  289. def geo_db_type(self, f):
  290. """
  291. Return the database field type for the given geometry field.
  292. Typically this is `None` because geometry columns are added via
  293. the `AddGeometryColumn` stored procedure, unless the field
  294. has been specified to be of geography type instead.
  295. """
  296. if f.geography:
  297. if not self.geography:
  298. raise NotImplementedError('PostGIS 1.5 required for geography column support.')
  299. if f.srid != 4326:
  300. raise NotImplementedError('PostGIS 1.5 supports geography columns '
  301. 'only with an SRID of 4326.')
  302. return 'geography(%s,%d)'% (f.geom_type, f.srid)
  303. else:
  304. return None
  305. def get_distance(self, f, dist_val, lookup_type):
  306. """
  307. Retrieve the distance parameters for the given geometry field,
  308. distance lookup value, and the distance lookup type.
  309. This is the most complex implementation of the spatial backends due to
  310. what is supported on geodetic geometry columns vs. what's available on
  311. projected geometry columns. In addition, it has to take into account
  312. the newly introduced geography column type introudced in PostGIS 1.5.
  313. """
  314. # Getting the distance parameter and any options.
  315. if len(dist_val) == 1:
  316. value, option = dist_val[0], None
  317. else:
  318. value, option = dist_val
  319. # Shorthand boolean flags.
  320. geodetic = f.geodetic(self.connection)
  321. geography = f.geography and self.geography
  322. if isinstance(value, Distance):
  323. if geography:
  324. dist_param = value.m
  325. elif geodetic:
  326. if lookup_type == 'dwithin':
  327. raise ValueError('Only numeric values of degree units are '
  328. 'allowed on geographic DWithin queries.')
  329. dist_param = value.m
  330. else:
  331. dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
  332. else:
  333. # Assuming the distance is in the units of the field.
  334. dist_param = value
  335. if (not geography and geodetic and lookup_type != 'dwithin'
  336. and option == 'spheroid'):
  337. # using distance_spheroid requires the spheroid of the field as
  338. # a parameter.
  339. return [f._spheroid, dist_param]
  340. else:
  341. return [dist_param]
  342. def get_geom_placeholder(self, f, value):
  343. """
  344. Provides a proper substitution value for Geometries that are not in the
  345. SRID of the field. Specifically, this routine will substitute in the
  346. ST_Transform() function call.
  347. """
  348. if value is None or value.srid == f.srid:
  349. placeholder = '%s'
  350. else:
  351. # Adding Transform() to the SQL placeholder.
  352. placeholder = '%s(%%s, %s)' % (self.transform, f.srid)
  353. if hasattr(value, 'expression'):
  354. # If this is an F expression, then we don't really want
  355. # a placeholder and instead substitute in the column
  356. # of the expression.
  357. placeholder = placeholder % '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression]))
  358. return placeholder
  359. def _get_postgis_func(self, func):
  360. """
  361. Helper routine for calling PostGIS functions and returning their result.
  362. """
  363. cursor = self.connection._cursor()
  364. try:
  365. try:
  366. cursor.execute('SELECT %s()' % func)
  367. row = cursor.fetchone()
  368. except:
  369. # Responsibility of callers to perform error handling.
  370. raise
  371. finally:
  372. # Close out the connection. See #9437.
  373. self.connection.close()
  374. return row[0]
  375. def postgis_geos_version(self):
  376. "Returns the version of the GEOS library used with PostGIS."
  377. return self._get_postgis_func('postgis_geos_version')
  378. def postgis_lib_version(self):
  379. "Returns the version number of the PostGIS library used with PostgreSQL."
  380. return self._get_postgis_func('postgis_lib_version')
  381. def postgis_proj_version(self):
  382. "Returns the version of the PROJ.4 library used with PostGIS."
  383. return self._get_postgis_func('postgis_proj_version')
  384. def postgis_version(self):
  385. "Returns PostGIS version number and compile-time options."
  386. return self._get_postgis_func('postgis_version')
  387. def postgis_full_version(self):
  388. "Returns PostGIS version number and compile-time options."
  389. return self._get_postgis_func('postgis_full_version')
  390. def postgis_version_tuple(self):
  391. """
  392. Returns the PostGIS version as a tuple (version string, major,
  393. minor, subminor).
  394. """
  395. # Getting the PostGIS version
  396. version = self.postgis_lib_version()
  397. m = self.version_regex.match(version)
  398. if m:
  399. major = int(m.group('major'))
  400. minor1 = int(m.group('minor1'))
  401. minor2 = int(m.group('minor2'))
  402. else:
  403. raise Exception('Could not parse PostGIS version string: %s' % version)
  404. return (version, major, minor1, minor2)
  405. def proj_version_tuple(self):
  406. """
  407. Return the version of PROJ.4 used by PostGIS as a tuple of the
  408. major, minor, and subminor release numbers.
  409. """
  410. proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)')
  411. proj_ver_str = self.postgis_proj_version()
  412. m = proj_regex.search(proj_ver_str)
  413. if m:
  414. return tuple(map(int, [m.group(1), m.group(2), m.group(3)]))
  415. else:
  416. raise Exception('Could not determine PROJ.4 version from PostGIS.')
  417. def num_params(self, lookup_type, num_param):
  418. """
  419. Helper routine that returns a boolean indicating whether the number of
  420. parameters is correct for the lookup type.
  421. """
  422. def exactly_two(np): return np == 2
  423. def two_to_three(np): return np >= 2 and np <=3
  424. if (lookup_type in self.distance_functions and
  425. lookup_type != 'dwithin'):
  426. return two_to_three(num_param)
  427. else:
  428. return exactly_two(num_param)
  429. def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
  430. """
  431. Constructs spatial SQL from the given lookup value tuple a
  432. (alias, col, db_type), the lookup type string, lookup value, and
  433. the geometry field.
  434. """
  435. alias, col, db_type = lvalue
  436. # Getting the quoted geometry column.
  437. geo_col = '%s.%s' % (qn(alias), qn(col))
  438. if lookup_type in self.geometry_operators:
  439. if field.geography and not lookup_type in self.geography_operators:
  440. raise ValueError('PostGIS geography does not support the '
  441. '"%s" lookup.' % lookup_type)
  442. # Handling a PostGIS operator.
  443. op = self.geometry_operators[lookup_type]
  444. return op.as_sql(geo_col, self.get_geom_placeholder(field, value))
  445. elif lookup_type in self.geometry_functions:
  446. if field.geography and not lookup_type in self.geography_functions:
  447. raise ValueError('PostGIS geography type does not support the '
  448. '"%s" lookup.' % lookup_type)
  449. # See if a PostGIS geometry function matches the lookup type.
  450. tmp = self.geometry_functions[lookup_type]
  451. # Lookup types that are tuples take tuple arguments, e.g., 'relate' and
  452. # distance lookups.
  453. if isinstance(tmp, tuple):
  454. # First element of tuple is the PostGISOperation instance, and the
  455. # second element is either the type or a tuple of acceptable types
  456. # that may passed in as further parameters for the lookup type.
  457. op, arg_type = tmp
  458. # Ensuring that a tuple _value_ was passed in from the user
  459. if not isinstance(value, (tuple, list)):
  460. raise ValueError('Tuple required for `%s` lookup type.' % lookup_type)
  461. # Geometry is first element of lookup tuple.
  462. geom = value[0]
  463. # Number of valid tuple parameters depends on the lookup type.
  464. nparams = len(value)
  465. if not self.num_params(lookup_type, nparams):
  466. raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type)
  467. # Ensuring the argument type matches what we expect.
  468. if not isinstance(value[1], arg_type):
  469. raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1])))
  470. # For lookup type `relate`, the op instance is not yet created (has
  471. # to be instantiated here to check the pattern parameter).
  472. if lookup_type == 'relate':
  473. op = op(self.geom_func_prefix, value[1])
  474. elif lookup_type in self.distance_functions and lookup_type != 'dwithin':
  475. if not field.geography and field.geodetic(self.connection):
  476. # Geodetic distances are only availble from Points to
  477. # PointFields on PostGIS 1.4 and below.
  478. if not self.connection.ops.geography:
  479. if field.geom_type != 'POINT':
  480. raise ValueError('PostGIS spherical operations are only valid on PointFields.')
  481. if str(geom.geom_type) != 'Point':
  482. raise ValueError('PostGIS geometry distance parameter is required to be of type Point.')
  483. # Setting up the geodetic operation appropriately.
  484. if nparams == 3 and value[2] == 'spheroid':
  485. op = op['spheroid']
  486. else:
  487. op = op['sphere']
  488. else:
  489. op = op['cartesian']
  490. else:
  491. op = tmp
  492. geom = value
  493. # Calling the `as_sql` function on the operation instance.
  494. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom))
  495. elif lookup_type == 'isnull':
  496. # Handling 'isnull' lookup type
  497. return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or ''))
  498. raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type))
  499. def spatial_aggregate_sql(self, agg):
  500. """
  501. Returns the spatial aggregate SQL template and function for the
  502. given Aggregate instance.
  503. """
  504. agg_name = agg.__class__.__name__
  505. if not self.check_aggregate_support(agg):
  506. raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name)
  507. agg_name = agg_name.lower()
  508. if agg_name == 'union': agg_name += 'agg'
  509. sql_template = '%(function)s(%(field)s)'
  510. sql_function = getattr(self, agg_name)
  511. return sql_template, sql_function
  512. # Routines for getting the OGC-compliant models.
  513. def geometry_columns(self):
  514. from django.contrib.gis.db.backends.postgis.models import GeometryColumns
  515. return GeometryColumns
  516. def spatial_ref_sys(self):
  517. from django.contrib.gis.db.backends.postgis.models import SpatialRefSys
  518. return SpatialRefSys