query.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import warnings
  2. from django.contrib.gis.db.models import aggregates
  3. from django.contrib.gis.db.models.fields import (
  4. GeometryField, LineStringField, PointField, get_srid_info,
  5. )
  6. from django.contrib.gis.db.models.lookups import GISLookup
  7. from django.contrib.gis.db.models.sql import (
  8. AreaField, DistanceField, GeomField, GMLField,
  9. )
  10. from django.contrib.gis.geometry.backend import Geometry
  11. from django.contrib.gis.measure import Area, Distance
  12. from django.db import connections
  13. from django.db.models.expressions import RawSQL
  14. from django.db.models.fields import Field
  15. from django.db.models.query import QuerySet
  16. from django.utils import six
  17. from django.utils.deprecation import (
  18. RemovedInDjango20Warning, RemovedInDjango110Warning,
  19. )
  20. class GeoQuerySet(QuerySet):
  21. "The Geographic QuerySet."
  22. # ### GeoQuerySet Methods ###
  23. def area(self, tolerance=0.05, **kwargs):
  24. """
  25. Returns the area of the geographic field in an `area` attribute on
  26. each element of this GeoQuerySet.
  27. """
  28. # Performing setup here rather than in `_spatial_attribute` so that
  29. # we can get the units for `AreaField`.
  30. procedure_args, geo_field = self._spatial_setup(
  31. 'area', field_name=kwargs.get('field_name'))
  32. s = {'procedure_args': procedure_args,
  33. 'geo_field': geo_field,
  34. 'setup': False,
  35. }
  36. connection = connections[self.db]
  37. backend = connection.ops
  38. if backend.oracle:
  39. s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
  40. s['procedure_args']['tolerance'] = tolerance
  41. s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters.
  42. elif backend.postgis or backend.spatialite:
  43. if backend.geography:
  44. # Geography fields support area calculation, returns square meters.
  45. s['select_field'] = AreaField('sq_m')
  46. elif not geo_field.geodetic(connection):
  47. # Getting the area units of the geographic field.
  48. s['select_field'] = AreaField(Area.unit_attname(geo_field.units_name(connection)))
  49. else:
  50. # TODO: Do we want to support raw number areas for geodetic fields?
  51. raise Exception('Area on geodetic coordinate systems not supported.')
  52. return self._spatial_attribute('area', s, **kwargs)
  53. def centroid(self, **kwargs):
  54. """
  55. Returns the centroid of the geographic field in a `centroid`
  56. attribute on each element of this GeoQuerySet.
  57. """
  58. return self._geom_attribute('centroid', **kwargs)
  59. def collect(self, **kwargs):
  60. """
  61. Performs an aggregate collect operation on the given geometry field.
  62. This is analogous to a union operation, but much faster because
  63. boundaries are not dissolved.
  64. """
  65. warnings.warn(
  66. "The collect GeoQuerySet method is deprecated. Use the Collect() "
  67. "aggregate in an aggregate() or annotate() method.",
  68. RemovedInDjango110Warning, stacklevel=2
  69. )
  70. return self._spatial_aggregate(aggregates.Collect, **kwargs)
  71. def difference(self, geom, **kwargs):
  72. """
  73. Returns the spatial difference of the geographic field in a `difference`
  74. attribute on each element of this GeoQuerySet.
  75. """
  76. return self._geomset_attribute('difference', geom, **kwargs)
  77. def distance(self, geom, **kwargs):
  78. """
  79. Returns the distance from the given geographic field name to the
  80. given geometry in a `distance` attribute on each element of the
  81. GeoQuerySet.
  82. Keyword Arguments:
  83. `spheroid` => If the geometry field is geodetic and PostGIS is
  84. the spatial database, then the more accurate
  85. spheroid calculation will be used instead of the
  86. quicker sphere calculation.
  87. `tolerance` => Used only for Oracle. The tolerance is
  88. in meters -- a default of 5 centimeters (0.05)
  89. is used.
  90. """
  91. return self._distance_attribute('distance', geom, **kwargs)
  92. def envelope(self, **kwargs):
  93. """
  94. Returns a Geometry representing the bounding box of the
  95. Geometry field in an `envelope` attribute on each element of
  96. the GeoQuerySet.
  97. """
  98. return self._geom_attribute('envelope', **kwargs)
  99. def extent(self, **kwargs):
  100. """
  101. Returns the extent (aggregate) of the features in the GeoQuerySet. The
  102. extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).
  103. """
  104. warnings.warn(
  105. "The extent GeoQuerySet method is deprecated. Use the Extent() "
  106. "aggregate in an aggregate() or annotate() method.",
  107. RemovedInDjango110Warning, stacklevel=2
  108. )
  109. return self._spatial_aggregate(aggregates.Extent, **kwargs)
  110. def extent3d(self, **kwargs):
  111. """
  112. Returns the aggregate extent, in 3D, of the features in the
  113. GeoQuerySet. It is returned as a 6-tuple, comprising:
  114. (xmin, ymin, zmin, xmax, ymax, zmax).
  115. """
  116. warnings.warn(
  117. "The extent3d GeoQuerySet method is deprecated. Use the Extent3D() "
  118. "aggregate in an aggregate() or annotate() method.",
  119. RemovedInDjango110Warning, stacklevel=2
  120. )
  121. return self._spatial_aggregate(aggregates.Extent3D, **kwargs)
  122. def force_rhr(self, **kwargs):
  123. """
  124. Returns a modified version of the Polygon/MultiPolygon in which
  125. all of the vertices follow the Right-Hand-Rule. By default,
  126. this is attached as the `force_rhr` attribute on each element
  127. of the GeoQuerySet.
  128. """
  129. return self._geom_attribute('force_rhr', **kwargs)
  130. def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
  131. """
  132. Returns a GeoJSON representation of the geometry field in a `geojson`
  133. attribute on each element of the GeoQuerySet.
  134. The `crs` and `bbox` keywords may be set to True if the user wants
  135. the coordinate reference system and the bounding box to be included
  136. in the GeoJSON representation of the geometry.
  137. """
  138. backend = connections[self.db].ops
  139. if not backend.geojson:
  140. raise NotImplementedError('Only PostGIS 1.3.4+ and SpatiaLite 3.0+ '
  141. 'support GeoJSON serialization.')
  142. if not isinstance(precision, six.integer_types):
  143. raise TypeError('Precision keyword must be set with an integer.')
  144. options = 0
  145. if crs and bbox:
  146. options = 3
  147. elif bbox:
  148. options = 1
  149. elif crs:
  150. options = 2
  151. s = {'desc': 'GeoJSON',
  152. 'procedure_args': {'precision': precision, 'options': options},
  153. 'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s',
  154. }
  155. return self._spatial_attribute('geojson', s, **kwargs)
  156. def geohash(self, precision=20, **kwargs):
  157. """
  158. Returns a GeoHash representation of the given field in a `geohash`
  159. attribute on each element of the GeoQuerySet.
  160. The `precision` keyword may be used to custom the number of
  161. _characters_ used in the output GeoHash, the default is 20.
  162. """
  163. s = {'desc': 'GeoHash',
  164. 'procedure_args': {'precision': precision},
  165. 'procedure_fmt': '%(geo_col)s,%(precision)s',
  166. }
  167. return self._spatial_attribute('geohash', s, **kwargs)
  168. def gml(self, precision=8, version=2, **kwargs):
  169. """
  170. Returns GML representation of the given field in a `gml` attribute
  171. on each element of the GeoQuerySet.
  172. """
  173. backend = connections[self.db].ops
  174. s = {'desc': 'GML', 'procedure_args': {'precision': precision}}
  175. if backend.postgis:
  176. s['procedure_fmt'] = '%(version)s,%(geo_col)s,%(precision)s'
  177. s['procedure_args'] = {'precision': precision, 'version': version}
  178. if backend.oracle:
  179. s['select_field'] = GMLField()
  180. return self._spatial_attribute('gml', s, **kwargs)
  181. def intersection(self, geom, **kwargs):
  182. """
  183. Returns the spatial intersection of the Geometry field in
  184. an `intersection` attribute on each element of this
  185. GeoQuerySet.
  186. """
  187. return self._geomset_attribute('intersection', geom, **kwargs)
  188. def kml(self, **kwargs):
  189. """
  190. Returns KML representation of the geometry field in a `kml`
  191. attribute on each element of this GeoQuerySet.
  192. """
  193. s = {'desc': 'KML',
  194. 'procedure_fmt': '%(geo_col)s,%(precision)s',
  195. 'procedure_args': {'precision': kwargs.pop('precision', 8)},
  196. }
  197. return self._spatial_attribute('kml', s, **kwargs)
  198. def length(self, **kwargs):
  199. """
  200. Returns the length of the geometry field as a `Distance` object
  201. stored in a `length` attribute on each element of this GeoQuerySet.
  202. """
  203. return self._distance_attribute('length', None, **kwargs)
  204. def make_line(self, **kwargs):
  205. """
  206. Creates a linestring from all of the PointField geometries in the
  207. this GeoQuerySet and returns it. This is a spatial aggregate
  208. method, and thus returns a geometry rather than a GeoQuerySet.
  209. """
  210. warnings.warn(
  211. "The make_line GeoQuerySet method is deprecated. Use the MakeLine() "
  212. "aggregate in an aggregate() or annotate() method.",
  213. RemovedInDjango110Warning, stacklevel=2
  214. )
  215. return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs)
  216. def mem_size(self, **kwargs):
  217. """
  218. Returns the memory size (number of bytes) that the geometry field takes
  219. in a `mem_size` attribute on each element of this GeoQuerySet.
  220. """
  221. return self._spatial_attribute('mem_size', {}, **kwargs)
  222. def num_geom(self, **kwargs):
  223. """
  224. Returns the number of geometries if the field is a
  225. GeometryCollection or Multi* Field in a `num_geom`
  226. attribute on each element of this GeoQuerySet; otherwise
  227. the sets with None.
  228. """
  229. return self._spatial_attribute('num_geom', {}, **kwargs)
  230. def num_points(self, **kwargs):
  231. """
  232. Returns the number of points in the first linestring in the
  233. Geometry field in a `num_points` attribute on each element of
  234. this GeoQuerySet; otherwise sets with None.
  235. """
  236. return self._spatial_attribute('num_points', {}, **kwargs)
  237. def perimeter(self, **kwargs):
  238. """
  239. Returns the perimeter of the geometry field as a `Distance` object
  240. stored in a `perimeter` attribute on each element of this GeoQuerySet.
  241. """
  242. return self._distance_attribute('perimeter', None, **kwargs)
  243. def point_on_surface(self, **kwargs):
  244. """
  245. Returns a Point geometry guaranteed to lie on the surface of the
  246. Geometry field in a `point_on_surface` attribute on each element
  247. of this GeoQuerySet; otherwise sets with None.
  248. """
  249. return self._geom_attribute('point_on_surface', **kwargs)
  250. def reverse_geom(self, **kwargs):
  251. """
  252. Reverses the coordinate order of the geometry, and attaches as a
  253. `reverse` attribute on each element of this GeoQuerySet.
  254. """
  255. s = {'select_field': GeomField()}
  256. kwargs.setdefault('model_att', 'reverse_geom')
  257. if connections[self.db].ops.oracle:
  258. s['geo_field_type'] = LineStringField
  259. return self._spatial_attribute('reverse', s, **kwargs)
  260. def scale(self, x, y, z=0.0, **kwargs):
  261. """
  262. Scales the geometry to a new size by multiplying the ordinates
  263. with the given x,y,z scale factors.
  264. """
  265. if connections[self.db].ops.spatialite:
  266. if z != 0.0:
  267. raise NotImplementedError('SpatiaLite does not support 3D scaling.')
  268. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
  269. 'procedure_args': {'x': x, 'y': y},
  270. 'select_field': GeomField(),
  271. }
  272. else:
  273. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
  274. 'procedure_args': {'x': x, 'y': y, 'z': z},
  275. 'select_field': GeomField(),
  276. }
  277. return self._spatial_attribute('scale', s, **kwargs)
  278. def snap_to_grid(self, *args, **kwargs):
  279. """
  280. Snap all points of the input geometry to the grid. How the
  281. geometry is snapped to the grid depends on how many arguments
  282. were given:
  283. - 1 argument : A single size to snap both the X and Y grids to.
  284. - 2 arguments: X and Y sizes to snap the grid to.
  285. - 4 arguments: X, Y sizes and the X, Y origins.
  286. """
  287. if False in [isinstance(arg, (float,) + six.integer_types) for arg in args]:
  288. raise TypeError('Size argument(s) for the grid must be a float or integer values.')
  289. nargs = len(args)
  290. if nargs == 1:
  291. size = args[0]
  292. procedure_fmt = '%(geo_col)s,%(size)s'
  293. procedure_args = {'size': size}
  294. elif nargs == 2:
  295. xsize, ysize = args
  296. procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s'
  297. procedure_args = {'xsize': xsize, 'ysize': ysize}
  298. elif nargs == 4:
  299. xsize, ysize, xorigin, yorigin = args
  300. procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s'
  301. procedure_args = {'xsize': xsize, 'ysize': ysize,
  302. 'xorigin': xorigin, 'yorigin': yorigin}
  303. else:
  304. raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.')
  305. s = {'procedure_fmt': procedure_fmt,
  306. 'procedure_args': procedure_args,
  307. 'select_field': GeomField(),
  308. }
  309. return self._spatial_attribute('snap_to_grid', s, **kwargs)
  310. def svg(self, relative=False, precision=8, **kwargs):
  311. """
  312. Returns SVG representation of the geographic field in a `svg`
  313. attribute on each element of this GeoQuerySet.
  314. Keyword Arguments:
  315. `relative` => If set to True, this will evaluate the path in
  316. terms of relative moves (rather than absolute).
  317. `precision` => May be used to set the maximum number of decimal
  318. digits used in output (defaults to 8).
  319. """
  320. relative = int(bool(relative))
  321. if not isinstance(precision, six.integer_types):
  322. raise TypeError('SVG precision keyword argument must be an integer.')
  323. s = {
  324. 'desc': 'SVG',
  325. 'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s',
  326. 'procedure_args': {
  327. 'rel': relative,
  328. 'precision': precision,
  329. }
  330. }
  331. return self._spatial_attribute('svg', s, **kwargs)
  332. def sym_difference(self, geom, **kwargs):
  333. """
  334. Returns the symmetric difference of the geographic field in a
  335. `sym_difference` attribute on each element of this GeoQuerySet.
  336. """
  337. return self._geomset_attribute('sym_difference', geom, **kwargs)
  338. def translate(self, x, y, z=0.0, **kwargs):
  339. """
  340. Translates the geometry to a new location using the given numeric
  341. parameters as offsets.
  342. """
  343. if connections[self.db].ops.spatialite:
  344. if z != 0.0:
  345. raise NotImplementedError('SpatiaLite does not support 3D translation.')
  346. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
  347. 'procedure_args': {'x': x, 'y': y},
  348. 'select_field': GeomField(),
  349. }
  350. else:
  351. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
  352. 'procedure_args': {'x': x, 'y': y, 'z': z},
  353. 'select_field': GeomField(),
  354. }
  355. return self._spatial_attribute('translate', s, **kwargs)
  356. def transform(self, srid=4326, **kwargs):
  357. """
  358. Transforms the given geometry field to the given SRID. If no SRID is
  359. provided, the transformation will default to using 4326 (WGS84).
  360. """
  361. if not isinstance(srid, six.integer_types):
  362. raise TypeError('An integer SRID must be provided.')
  363. field_name = kwargs.get('field_name')
  364. self._spatial_setup('transform', field_name=field_name)
  365. self.query.add_context('transformed_srid', srid)
  366. return self._clone()
  367. def union(self, geom, **kwargs):
  368. """
  369. Returns the union of the geographic field with the given
  370. Geometry in a `union` attribute on each element of this GeoQuerySet.
  371. """
  372. return self._geomset_attribute('union', geom, **kwargs)
  373. def unionagg(self, **kwargs):
  374. """
  375. Performs an aggregate union on the given geometry field. Returns
  376. None if the GeoQuerySet is empty. The `tolerance` keyword is for
  377. Oracle backends only.
  378. """
  379. warnings.warn(
  380. "The unionagg GeoQuerySet method is deprecated. Use the Union() "
  381. "aggregate in an aggregate() or annotate() method.",
  382. RemovedInDjango110Warning, stacklevel=2
  383. )
  384. return self._spatial_aggregate(aggregates.Union, **kwargs)
  385. # ### Private API -- Abstracted DRY routines. ###
  386. def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None):
  387. """
  388. Performs set up for executing the spatial function.
  389. """
  390. # Does the spatial backend support this?
  391. connection = connections[self.db]
  392. func = getattr(connection.ops, att, False)
  393. if desc is None:
  394. desc = att
  395. if not func:
  396. raise NotImplementedError('%s stored procedure not available on '
  397. 'the %s backend.' %
  398. (desc, connection.ops.name))
  399. # Initializing the procedure arguments.
  400. procedure_args = {'function': func}
  401. # Is there a geographic field in the model to perform this
  402. # operation on?
  403. geo_field = self._geo_field(field_name)
  404. if not geo_field:
  405. raise TypeError('%s output only available on GeometryFields.' % func)
  406. # If the `geo_field_type` keyword was used, then enforce that
  407. # type limitation.
  408. if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
  409. raise TypeError('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__))
  410. # Setting the procedure args.
  411. procedure_args['geo_col'] = self._geocol_select(geo_field, field_name)
  412. return procedure_args, geo_field
  413. def _spatial_aggregate(self, aggregate, field_name=None,
  414. geo_field_type=None, tolerance=0.05):
  415. """
  416. DRY routine for calling aggregate spatial stored procedures and
  417. returning their result to the caller of the function.
  418. """
  419. # Getting the field the geographic aggregate will be called on.
  420. geo_field = self._geo_field(field_name)
  421. if not geo_field:
  422. raise TypeError('%s aggregate only available on GeometryFields.' % aggregate.name)
  423. # Checking if there are any geo field type limitations on this
  424. # aggregate (e.g. ST_Makeline only operates on PointFields).
  425. if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
  426. raise TypeError('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__))
  427. # Getting the string expression of the field name, as this is the
  428. # argument taken by `Aggregate` objects.
  429. agg_col = field_name or geo_field.name
  430. # Adding any keyword parameters for the Aggregate object. Oracle backends
  431. # in particular need an additional `tolerance` parameter.
  432. agg_kwargs = {}
  433. if connections[self.db].ops.oracle:
  434. agg_kwargs['tolerance'] = tolerance
  435. # Calling the QuerySet.aggregate, and returning only the value of the aggregate.
  436. return self.aggregate(geoagg=aggregate(agg_col, **agg_kwargs))['geoagg']
  437. def _spatial_attribute(self, att, settings, field_name=None, model_att=None):
  438. """
  439. DRY routine for calling a spatial stored procedure on a geometry column
  440. and attaching its output as an attribute of the model.
  441. Arguments:
  442. att:
  443. The name of the spatial attribute that holds the spatial
  444. SQL function to call.
  445. settings:
  446. Dictonary of internal settings to customize for the spatial procedure.
  447. Public Keyword Arguments:
  448. field_name:
  449. The name of the geographic field to call the spatial
  450. function on. May also be a lookup to a geometry field
  451. as part of a foreign key relation.
  452. model_att:
  453. The name of the model attribute to attach the output of
  454. the spatial function to.
  455. """
  456. warnings.warn(
  457. "The %s GeoQuerySet method is deprecated. See GeoDjango Functions "
  458. "documentation to find the expression-based replacement." % att,
  459. RemovedInDjango20Warning, stacklevel=2
  460. )
  461. # Default settings.
  462. settings.setdefault('desc', None)
  463. settings.setdefault('geom_args', ())
  464. settings.setdefault('geom_field', None)
  465. settings.setdefault('procedure_args', {})
  466. settings.setdefault('procedure_fmt', '%(geo_col)s')
  467. settings.setdefault('select_params', [])
  468. connection = connections[self.db]
  469. # Performing setup for the spatial column, unless told not to.
  470. if settings.get('setup', True):
  471. default_args, geo_field = self._spatial_setup(
  472. att, desc=settings['desc'], field_name=field_name,
  473. geo_field_type=settings.get('geo_field_type'))
  474. for k, v in six.iteritems(default_args):
  475. settings['procedure_args'].setdefault(k, v)
  476. else:
  477. geo_field = settings['geo_field']
  478. # The attribute to attach to the model.
  479. if not isinstance(model_att, six.string_types):
  480. model_att = att
  481. # Special handling for any argument that is a geometry.
  482. for name in settings['geom_args']:
  483. # Using the field's get_placeholder() routine to get any needed
  484. # transformation SQL.
  485. geom = geo_field.get_prep_value(settings['procedure_args'][name])
  486. params = geo_field.get_db_prep_lookup('contains', geom, connection=connection)
  487. geom_placeholder = geo_field.get_placeholder(geom, None, connection)
  488. # Replacing the procedure format with that of any needed
  489. # transformation SQL.
  490. old_fmt = '%%(%s)s' % name
  491. new_fmt = geom_placeholder % '%%s'
  492. settings['procedure_fmt'] = settings['procedure_fmt'].replace(old_fmt, new_fmt)
  493. settings['select_params'].extend(params)
  494. # Getting the format for the stored procedure.
  495. fmt = '%%(function)s(%s)' % settings['procedure_fmt']
  496. # If the result of this function needs to be converted.
  497. if settings.get('select_field'):
  498. select_field = settings['select_field']
  499. if connection.ops.oracle:
  500. select_field.empty_strings_allowed = False
  501. else:
  502. select_field = Field()
  503. # Finally, setting the extra selection attribute with
  504. # the format string expanded with the stored procedure
  505. # arguments.
  506. self.query.add_annotation(
  507. RawSQL(fmt % settings['procedure_args'], settings['select_params'], select_field),
  508. model_att)
  509. return self
  510. def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
  511. """
  512. DRY routine for GeoQuerySet distance attribute routines.
  513. """
  514. # Setting up the distance procedure arguments.
  515. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name'))
  516. # If geodetic defaulting distance attribute to meters (Oracle and
  517. # PostGIS spherical distances return meters). Otherwise, use the
  518. # units of the geometry field.
  519. connection = connections[self.db]
  520. geodetic = geo_field.geodetic(connection)
  521. geography = geo_field.geography
  522. if geodetic:
  523. dist_att = 'm'
  524. else:
  525. dist_att = Distance.unit_attname(geo_field.units_name(connection))
  526. # Shortcut booleans for what distance function we're using and
  527. # whether the geometry field is 3D.
  528. distance = func == 'distance'
  529. length = func == 'length'
  530. perimeter = func == 'perimeter'
  531. if not (distance or length or perimeter):
  532. raise ValueError('Unknown distance function: %s' % func)
  533. geom_3d = geo_field.dim == 3
  534. # The field's get_db_prep_lookup() is used to get any
  535. # extra distance parameters. Here we set up the
  536. # parameters that will be passed in to field's function.
  537. lookup_params = [geom or 'POINT (0 0)', 0]
  538. # Getting the spatial backend operations.
  539. backend = connection.ops
  540. # If the spheroid calculation is desired, either by the `spheroid`
  541. # keyword or when calculating the length of geodetic field, make
  542. # sure the 'spheroid' distance setting string is passed in so we
  543. # get the correct spatial stored procedure.
  544. if spheroid or (backend.postgis and geodetic and
  545. (not geography) and length):
  546. lookup_params.append('spheroid')
  547. lookup_params = geo_field.get_prep_value(lookup_params)
  548. params = geo_field.get_db_prep_lookup('distance_lte', lookup_params, connection=connection)
  549. # The `geom_args` flag is set to true if a geometry parameter was
  550. # passed in.
  551. geom_args = bool(geom)
  552. if backend.oracle:
  553. if distance:
  554. procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s'
  555. elif length or perimeter:
  556. procedure_fmt = '%(geo_col)s,%(tolerance)s'
  557. procedure_args['tolerance'] = tolerance
  558. else:
  559. # Getting whether this field is in units of degrees since the field may have
  560. # been transformed via the `transform` GeoQuerySet method.
  561. srid = self.query.get_context('transformed_srid')
  562. if srid:
  563. u, unit_name, s = get_srid_info(srid, connection)
  564. geodetic = unit_name.lower() in geo_field.geodetic_units
  565. if geodetic and not connection.features.supports_distance_geodetic:
  566. raise ValueError(
  567. 'This database does not support linear distance '
  568. 'calculations on geodetic coordinate systems.'
  569. )
  570. if distance:
  571. if srid:
  572. # Setting the `geom_args` flag to false because we want to handle
  573. # transformation SQL here, rather than the way done by default
  574. # (which will transform to the original SRID of the field rather
  575. # than to what was transformed to).
  576. geom_args = False
  577. procedure_fmt = '%s(%%(geo_col)s, %s)' % (backend.transform, srid)
  578. if geom.srid is None or geom.srid == srid:
  579. # If the geom parameter srid is None, it is assumed the coordinates
  580. # are in the transformed units. A placeholder is used for the
  581. # geometry parameter. `GeomFromText` constructor is also needed
  582. # to wrap geom placeholder for SpatiaLite.
  583. if backend.spatialite:
  584. procedure_fmt += ', %s(%%%%s, %s)' % (backend.from_text, srid)
  585. else:
  586. procedure_fmt += ', %%s'
  587. else:
  588. # We need to transform the geom to the srid specified in `transform()`,
  589. # so wrapping the geometry placeholder in transformation SQL.
  590. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText`
  591. # constructor.
  592. if backend.spatialite:
  593. procedure_fmt += (', %s(%s(%%%%s, %s), %s)' % (
  594. backend.transform, backend.from_text,
  595. geom.srid, srid))
  596. else:
  597. procedure_fmt += ', %s(%%%%s, %s)' % (backend.transform, srid)
  598. else:
  599. # `transform()` was not used on this GeoQuerySet.
  600. procedure_fmt = '%(geo_col)s,%(geom)s'
  601. if not geography and geodetic:
  602. # Spherical distance calculation is needed (because the geographic
  603. # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid()
  604. # procedures may only do queries from point columns to point geometries
  605. # some error checking is required.
  606. if not backend.geography:
  607. if not isinstance(geo_field, PointField):
  608. raise ValueError('Spherical distance calculation only supported on PointFields.')
  609. if not str(Geometry(six.memoryview(params[0].ewkb)).geom_type) == 'Point':
  610. raise ValueError(
  611. 'Spherical distance calculation only supported with '
  612. 'Point Geometry parameters'
  613. )
  614. # The `function` procedure argument needs to be set differently for
  615. # geodetic distance calculations.
  616. if spheroid:
  617. # Call to distance_spheroid() requires spheroid param as well.
  618. procedure_fmt += ",'%(spheroid)s'"
  619. procedure_args.update({'function': backend.distance_spheroid, 'spheroid': params[1]})
  620. else:
  621. procedure_args.update({'function': backend.distance_sphere})
  622. elif length or perimeter:
  623. procedure_fmt = '%(geo_col)s'
  624. if not geography and geodetic and length:
  625. # There's no `length_sphere`, and `length_spheroid` also
  626. # works on 3D geometries.
  627. procedure_fmt += ",'%(spheroid)s'"
  628. procedure_args.update({'function': backend.length_spheroid, 'spheroid': params[1]})
  629. elif geom_3d and connection.features.supports_3d_functions:
  630. # Use 3D variants of perimeter and length routines on supported backends.
  631. if perimeter:
  632. procedure_args.update({'function': backend.perimeter3d})
  633. elif length:
  634. procedure_args.update({'function': backend.length3d})
  635. # Setting up the settings for `_spatial_attribute`.
  636. s = {'select_field': DistanceField(dist_att),
  637. 'setup': False,
  638. 'geo_field': geo_field,
  639. 'procedure_args': procedure_args,
  640. 'procedure_fmt': procedure_fmt,
  641. }
  642. if geom_args:
  643. s['geom_args'] = ('geom',)
  644. s['procedure_args']['geom'] = geom
  645. elif geom:
  646. # The geometry is passed in as a parameter because we handled
  647. # transformation conditions in this routine.
  648. s['select_params'] = [backend.Adapter(geom)]
  649. return self._spatial_attribute(func, s, **kwargs)
  650. def _geom_attribute(self, func, tolerance=0.05, **kwargs):
  651. """
  652. DRY routine for setting up a GeoQuerySet method that attaches a
  653. Geometry attribute (e.g., `centroid`, `point_on_surface`).
  654. """
  655. s = {'select_field': GeomField()}
  656. if connections[self.db].ops.oracle:
  657. s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
  658. s['procedure_args'] = {'tolerance': tolerance}
  659. return self._spatial_attribute(func, s, **kwargs)
  660. def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs):
  661. """
  662. DRY routine for setting up a GeoQuerySet method that attaches a
  663. Geometry attribute and takes a Geoemtry parameter. This is used
  664. for geometry set-like operations (e.g., intersection, difference,
  665. union, sym_difference).
  666. """
  667. s = {
  668. 'geom_args': ('geom',),
  669. 'select_field': GeomField(),
  670. 'procedure_fmt': '%(geo_col)s,%(geom)s',
  671. 'procedure_args': {'geom': geom},
  672. }
  673. if connections[self.db].ops.oracle:
  674. s['procedure_fmt'] += ',%(tolerance)s'
  675. s['procedure_args']['tolerance'] = tolerance
  676. return self._spatial_attribute(func, s, **kwargs)
  677. def _geocol_select(self, geo_field, field_name):
  678. """
  679. Helper routine for constructing the SQL to select the geographic
  680. column. Takes into account if the geographic field is in a
  681. ForeignKey relation to the current model.
  682. """
  683. compiler = self.query.get_compiler(self.db)
  684. opts = self.model._meta
  685. if geo_field not in opts.fields:
  686. # Is this operation going to be on a related geographic field?
  687. # If so, it'll have to be added to the select related information
  688. # (e.g., if 'location__point' was given as the field name).
  689. # Note: the operation really is defined as "must add select related!"
  690. self.query.add_select_related([field_name])
  691. # Call pre_sql_setup() so that compiler.select gets populated.
  692. compiler.pre_sql_setup()
  693. for col, _, _ in compiler.select:
  694. if col.output_field == geo_field:
  695. return col.as_sql(compiler, compiler.connection)[0]
  696. raise ValueError("%r not in compiler's related_select_cols" % geo_field)
  697. elif geo_field not in opts.local_fields:
  698. # This geographic field is inherited from another model, so we have to
  699. # use the db table for the _parent_ model instead.
  700. parent_model = geo_field.model._meta.concrete_model
  701. return self._field_column(compiler, geo_field, parent_model._meta.db_table)
  702. else:
  703. return self._field_column(compiler, geo_field)
  704. # Private API utilities, subject to change.
  705. def _geo_field(self, field_name=None):
  706. """
  707. Returns the first Geometry field encountered or the one specified via
  708. the `field_name` keyword. The `field_name` may be a string specifying
  709. the geometry field on this GeoQuerySet's model, or a lookup string
  710. to a geometry field via a ForeignKey relation.
  711. """
  712. if field_name is None:
  713. # Incrementing until the first geographic field is found.
  714. for field in self.model._meta.fields:
  715. if isinstance(field, GeometryField):
  716. return field
  717. return False
  718. else:
  719. # Otherwise, check by the given field name -- which may be
  720. # a lookup to a _related_ geographic field.
  721. return GISLookup._check_geo_field(self.model._meta, field_name)
  722. def _field_column(self, compiler, field, table_alias=None, column=None):
  723. """
  724. Helper function that returns the database column for the given field.
  725. The table and column are returned (quoted) in the proper format, e.g.,
  726. `"geoapp_city"."point"`. If `table_alias` is not specified, the
  727. database table associated with the model of this `GeoQuerySet` will be
  728. used. If `column` is specified, it will be used instead of the value
  729. in `field.column`.
  730. """
  731. if table_alias is None:
  732. table_alias = compiler.query.get_meta().db_table
  733. return "%s.%s" % (compiler.quote_name_unless_alias(table_alias),
  734. compiler.connection.ops.quote_name(column or field.column))