operations.py 16 KB

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