PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/gis/db/backends/postgis/operations.py

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