operations.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import re
  2. from django.conf import settings
  3. from django.contrib.gis.db.backends.base.operations import \
  4. BaseSpatialOperations
  5. from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter
  6. from django.contrib.gis.db.backends.utils import SpatialOperator
  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.operations import \
  11. DatabaseOperations
  12. from django.db.utils import ProgrammingError
  13. from django.utils.functional import cached_property
  14. from .models import PostGISGeometryColumns, PostGISSpatialRefSys
  15. class PostGISOperator(SpatialOperator):
  16. def __init__(self, geography=False, **kwargs):
  17. # Only a subset of the operators and functions are available
  18. # for the geography type.
  19. self.geography = geography
  20. super(PostGISOperator, self).__init__(**kwargs)
  21. def as_sql(self, connection, lookup, *args):
  22. if lookup.lhs.output_field.geography and not self.geography:
  23. raise ValueError('PostGIS geography does not support the "%s" '
  24. 'function/operator.' % (self.func or self.op,))
  25. return super(PostGISOperator, self).as_sql(connection, lookup, *args)
  26. class PostGISDistanceOperator(PostGISOperator):
  27. sql_template = '%(func)s(%(lhs)s, %(rhs)s) %(op)s %%s'
  28. def as_sql(self, connection, lookup, template_params, sql_params):
  29. if not lookup.lhs.output_field.geography and lookup.lhs.output_field.geodetic(connection):
  30. sql_template = self.sql_template
  31. if len(lookup.rhs) == 3 and lookup.rhs[-1] == 'spheroid':
  32. template_params.update({'op': self.op, 'func': 'ST_Distance_Spheroid'})
  33. sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s) %(op)s %%s'
  34. else:
  35. template_params.update({'op': self.op, 'func': 'ST_Distance_Sphere'})
  36. return sql_template % template_params, sql_params
  37. return super(PostGISDistanceOperator, self).as_sql(connection, lookup, template_params, sql_params)
  38. class PostGISOperations(BaseSpatialOperations, DatabaseOperations):
  39. name = 'postgis'
  40. postgis = True
  41. geography = True
  42. geom_func_prefix = 'ST_'
  43. version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)')
  44. Adapter = PostGISAdapter
  45. Adaptor = Adapter # Backwards-compatibility alias.
  46. gis_operators = {
  47. 'bbcontains': PostGISOperator(op='~'),
  48. 'bboverlaps': PostGISOperator(op='&&', geography=True),
  49. 'contained': PostGISOperator(op='@'),
  50. 'contains': PostGISOperator(func='ST_Contains'),
  51. 'overlaps_left': PostGISOperator(op='&<'),
  52. 'overlaps_right': PostGISOperator(op='&>'),
  53. 'overlaps_below': PostGISOperator(op='&<|'),
  54. 'overlaps_above': PostGISOperator(op='|&>'),
  55. 'left': PostGISOperator(op='<<'),
  56. 'right': PostGISOperator(op='>>'),
  57. 'strictly_below': PostGISOperator(op='<<|'),
  58. 'stricly_above': PostGISOperator(op='|>>'),
  59. 'same_as': PostGISOperator(op='~='),
  60. 'exact': PostGISOperator(op='~='), # alias of same_as
  61. 'contains_properly': PostGISOperator(func='ST_ContainsProperly'),
  62. 'coveredby': PostGISOperator(func='ST_CoveredBy', geography=True),
  63. 'covers': PostGISOperator(func='ST_Covers', geography=True),
  64. 'crosses': PostGISOperator(func='ST_Crosses'),
  65. 'disjoint': PostGISOperator(func='ST_Disjoint'),
  66. 'equals': PostGISOperator(func='ST_Equals'),
  67. 'intersects': PostGISOperator(func='ST_Intersects', geography=True),
  68. 'overlaps': PostGISOperator(func='ST_Overlaps'),
  69. 'relate': PostGISOperator(func='ST_Relate'),
  70. 'touches': PostGISOperator(func='ST_Touches'),
  71. 'within': PostGISOperator(func='ST_Within'),
  72. 'dwithin': PostGISOperator(func='ST_DWithin', geography=True),
  73. 'distance_gt': PostGISDistanceOperator(func='ST_Distance', op='>', geography=True),
  74. 'distance_gte': PostGISDistanceOperator(func='ST_Distance', op='>=', geography=True),
  75. 'distance_lt': PostGISDistanceOperator(func='ST_Distance', op='<', geography=True),
  76. 'distance_lte': PostGISDistanceOperator(func='ST_Distance', op='<=', geography=True),
  77. }
  78. unsupported_functions = set()
  79. function_names = {
  80. 'BoundingCircle': 'ST_MinimumBoundingCircle',
  81. 'MemSize': 'ST_Mem_Size',
  82. 'NumPoints': 'ST_NPoints',
  83. }
  84. def __init__(self, connection):
  85. super(PostGISOperations, self).__init__(connection)
  86. prefix = self.geom_func_prefix
  87. self.area = prefix + 'Area'
  88. self.bounding_circle = prefix + 'MinimumBoundingCircle'
  89. self.centroid = prefix + 'Centroid'
  90. self.collect = prefix + 'Collect'
  91. self.difference = prefix + 'Difference'
  92. self.distance = prefix + 'Distance'
  93. self.distance_sphere = prefix + 'distance_sphere'
  94. self.distance_spheroid = prefix + 'distance_spheroid'
  95. self.envelope = prefix + 'Envelope'
  96. self.extent = prefix + 'Extent'
  97. self.extent3d = prefix + '3DExtent'
  98. self.force_rhr = prefix + 'ForceRHR'
  99. self.geohash = prefix + 'GeoHash'
  100. self.geojson = prefix + 'AsGeoJson'
  101. self.gml = prefix + 'AsGML'
  102. self.intersection = prefix + 'Intersection'
  103. self.kml = prefix + 'AsKML'
  104. self.length = prefix + 'Length'
  105. self.length3d = prefix + '3DLength'
  106. self.length_spheroid = prefix + 'length_spheroid'
  107. self.makeline = prefix + 'MakeLine'
  108. self.mem_size = prefix + 'mem_size'
  109. self.num_geom = prefix + 'NumGeometries'
  110. self.num_points = prefix + 'npoints'
  111. self.perimeter = prefix + 'Perimeter'
  112. self.perimeter3d = prefix + '3DPerimeter'
  113. self.point_on_surface = prefix + 'PointOnSurface'
  114. self.polygonize = prefix + 'Polygonize'
  115. self.reverse = prefix + 'Reverse'
  116. self.scale = prefix + 'Scale'
  117. self.snap_to_grid = prefix + 'SnapToGrid'
  118. self.svg = prefix + 'AsSVG'
  119. self.sym_difference = prefix + 'SymDifference'
  120. self.transform = prefix + 'Transform'
  121. self.translate = prefix + 'Translate'
  122. self.union = prefix + 'Union'
  123. self.unionagg = prefix + 'Union'
  124. @cached_property
  125. def spatial_version(self):
  126. """Determine the version of the PostGIS library."""
  127. # Trying to get the PostGIS version because the function
  128. # signatures will depend on the version used. The cost
  129. # here is a database query to determine the version, which
  130. # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple
  131. # comprising user-supplied values for the major, minor, and
  132. # subminor revision of PostGIS.
  133. if hasattr(settings, 'POSTGIS_VERSION'):
  134. version = settings.POSTGIS_VERSION
  135. else:
  136. try:
  137. vtup = self.postgis_version_tuple()
  138. except ProgrammingError:
  139. raise ImproperlyConfigured(
  140. 'Cannot determine PostGIS version for database "%s". '
  141. 'GeoDjango requires at least PostGIS version 2.0. '
  142. 'Was the database created from a spatial database '
  143. 'template?' % self.connection.settings_dict['NAME']
  144. )
  145. version = vtup[1:]
  146. return version
  147. def convert_extent(self, box, srid):
  148. """
  149. Returns a 4-tuple extent for the `Extent` aggregate by converting
  150. the bounding box text returned by PostGIS (`box` argument), for
  151. example: "BOX(-90.0 30.0, -85.0 40.0)".
  152. """
  153. if box is None:
  154. return None
  155. ll, ur = box[4:-1].split(',')
  156. xmin, ymin = map(float, ll.split())
  157. xmax, ymax = map(float, ur.split())
  158. return (xmin, ymin, xmax, ymax)
  159. def convert_extent3d(self, box3d, srid):
  160. """
  161. Returns a 6-tuple extent for the `Extent3D` aggregate by converting
  162. the 3d bounding-box text returned by PostGIS (`box3d` argument), for
  163. example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)".
  164. """
  165. if box3d is None:
  166. return None
  167. ll, ur = box3d[6:-1].split(',')
  168. xmin, ymin, zmin = map(float, ll.split())
  169. xmax, ymax, zmax = map(float, ur.split())
  170. return (xmin, ymin, zmin, xmax, ymax, zmax)
  171. def convert_geom(self, hex, geo_field):
  172. """
  173. Converts the geometry returned from PostGIS aggretates.
  174. """
  175. if hex:
  176. return Geometry(hex, srid=geo_field.srid)
  177. else:
  178. return None
  179. def geo_db_type(self, f):
  180. """
  181. Return the database field type for the given geometry field.
  182. Typically this is `None` because geometry columns are added via
  183. the `AddGeometryColumn` stored procedure, unless the field
  184. has been specified to be of geography type instead.
  185. """
  186. if f.geography:
  187. if f.srid != 4326:
  188. raise NotImplementedError('PostGIS only supports geography columns with an SRID of 4326.')
  189. return 'geography(%s,%d)' % (f.geom_type, f.srid)
  190. else:
  191. # Type-based geometries.
  192. # TODO: Support 'M' extension.
  193. if f.dim == 3:
  194. geom_type = f.geom_type + 'Z'
  195. else:
  196. geom_type = f.geom_type
  197. return 'geometry(%s,%d)' % (geom_type, f.srid)
  198. def get_distance(self, f, dist_val, lookup_type):
  199. """
  200. Retrieve the distance parameters for the given geometry field,
  201. distance lookup value, and the distance lookup type.
  202. This is the most complex implementation of the spatial backends due to
  203. what is supported on geodetic geometry columns vs. what's available on
  204. projected geometry columns. In addition, it has to take into account
  205. the geography column type.
  206. """
  207. # Getting the distance parameter and any options.
  208. if len(dist_val) == 1:
  209. value, option = dist_val[0], None
  210. else:
  211. value, option = dist_val
  212. # Shorthand boolean flags.
  213. geodetic = f.geodetic(self.connection)
  214. geography = f.geography
  215. if isinstance(value, Distance):
  216. if geography:
  217. dist_param = value.m
  218. elif geodetic:
  219. if lookup_type == 'dwithin':
  220. raise ValueError('Only numeric values of degree units are '
  221. 'allowed on geographic DWithin queries.')
  222. dist_param = value.m
  223. else:
  224. dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
  225. else:
  226. # Assuming the distance is in the units of the field.
  227. dist_param = value
  228. if (not geography and geodetic and lookup_type != 'dwithin'
  229. and option == 'spheroid'):
  230. # using distance_spheroid requires the spheroid of the field as
  231. # a parameter.
  232. return [f._spheroid, dist_param]
  233. else:
  234. return [dist_param]
  235. def get_geom_placeholder(self, f, value, compiler):
  236. """
  237. Provides a proper substitution value for Geometries that are not in the
  238. SRID of the field. Specifically, this routine will substitute in the
  239. ST_Transform() function call.
  240. """
  241. if value is None or value.srid == f.srid:
  242. placeholder = '%s'
  243. else:
  244. # Adding Transform() to the SQL placeholder.
  245. placeholder = '%s(%%s, %s)' % (self.transform, f.srid)
  246. if hasattr(value, 'as_sql'):
  247. # If this is an F expression, then we don't really want
  248. # a placeholder and instead substitute in the column
  249. # of the expression.
  250. sql, _ = compiler.compile(value)
  251. placeholder = placeholder % sql
  252. return placeholder
  253. def _get_postgis_func(self, func):
  254. """
  255. Helper routine for calling PostGIS functions and returning their result.
  256. """
  257. # Close out the connection. See #9437.
  258. with self.connection.temporary_connection() as cursor:
  259. cursor.execute('SELECT %s()' % func)
  260. return cursor.fetchone()[0]
  261. def postgis_geos_version(self):
  262. "Returns the version of the GEOS library used with PostGIS."
  263. return self._get_postgis_func('postgis_geos_version')
  264. def postgis_lib_version(self):
  265. "Returns the version number of the PostGIS library used with PostgreSQL."
  266. return self._get_postgis_func('postgis_lib_version')
  267. def postgis_proj_version(self):
  268. "Returns the version of the PROJ.4 library used with PostGIS."
  269. return self._get_postgis_func('postgis_proj_version')
  270. def postgis_version(self):
  271. "Returns PostGIS version number and compile-time options."
  272. return self._get_postgis_func('postgis_version')
  273. def postgis_full_version(self):
  274. "Returns PostGIS version number and compile-time options."
  275. return self._get_postgis_func('postgis_full_version')
  276. def postgis_version_tuple(self):
  277. """
  278. Returns the PostGIS version as a tuple (version string, major,
  279. minor, subminor).
  280. """
  281. # Getting the PostGIS version
  282. version = self.postgis_lib_version()
  283. m = self.version_regex.match(version)
  284. if m:
  285. major = int(m.group('major'))
  286. minor1 = int(m.group('minor1'))
  287. minor2 = int(m.group('minor2'))
  288. else:
  289. raise Exception('Could not parse PostGIS version string: %s' % version)
  290. return (version, major, minor1, minor2)
  291. def proj_version_tuple(self):
  292. """
  293. Return the version of PROJ.4 used by PostGIS as a tuple of the
  294. major, minor, and subminor release numbers.
  295. """
  296. proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)')
  297. proj_ver_str = self.postgis_proj_version()
  298. m = proj_regex.search(proj_ver_str)
  299. if m:
  300. return tuple(map(int, [m.group(1), m.group(2), m.group(3)]))
  301. else:
  302. raise Exception('Could not determine PROJ.4 version from PostGIS.')
  303. def spatial_aggregate_name(self, agg_name):
  304. if agg_name == 'Extent3D':
  305. return self.extent3d
  306. else:
  307. return self.geom_func_prefix + agg_name
  308. # Routines for getting the OGC-compliant models.
  309. def geometry_columns(self):
  310. return PostGISGeometryColumns
  311. def spatial_ref_sys(self):
  312. return PostGISSpatialRefSys