introspection.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. from django.contrib.gis.gdal import OGRGeomType
  2. from django.db.backends.postgresql.introspection import DatabaseIntrospection
  3. class GeoIntrospectionError(Exception):
  4. pass
  5. class PostGISIntrospection(DatabaseIntrospection):
  6. # Reverse dictionary for PostGIS geometry types not populated until
  7. # introspection is actually performed.
  8. postgis_types_reverse = {}
  9. ignored_tables = DatabaseIntrospection.ignored_tables + [
  10. 'geography_columns',
  11. 'geometry_columns',
  12. 'raster_columns',
  13. 'spatial_ref_sys',
  14. 'raster_overviews',
  15. ]
  16. # Overridden from parent to include raster indices in retrieval.
  17. # Raster indices have pg_index.indkey value 0 because they are an
  18. # expression over the raster column through the ST_ConvexHull function.
  19. # So the default query has to be adapted to include raster indices.
  20. _get_indexes_query = """
  21. SELECT DISTINCT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary
  22. FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index idx,
  23. pg_catalog.pg_attribute attr, pg_catalog.pg_type t
  24. WHERE
  25. c.oid = idx.indrelid
  26. AND idx.indexrelid = c2.oid
  27. AND attr.attrelid = c.oid
  28. AND t.oid = attr.atttypid
  29. AND (
  30. attr.attnum = idx.indkey[0] OR
  31. (t.typname LIKE 'raster' AND idx.indkey = '0')
  32. )
  33. AND attr.attnum > 0
  34. AND c.relname = %s"""
  35. def get_postgis_types(self):
  36. """
  37. Return a dictionary with keys that are the PostgreSQL object
  38. identification integers for the PostGIS geometry and/or
  39. geography types (if supported).
  40. """
  41. field_types = [
  42. ('geometry', 'GeometryField'),
  43. # The value for the geography type is actually a tuple
  44. # to pass in the `geography=True` keyword to the field
  45. # definition.
  46. ('geography', ('GeometryField', {'geography': True})),
  47. ]
  48. postgis_types = {}
  49. # The OID integers associated with the geometry type may
  50. # be different across versions; hence, this is why we have
  51. # to query the PostgreSQL pg_type table corresponding to the
  52. # PostGIS custom data types.
  53. oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
  54. with self.connection.cursor() as cursor:
  55. for field_type in field_types:
  56. cursor.execute(oid_sql, (field_type[0],))
  57. for result in cursor.fetchall():
  58. postgis_types[result[0]] = field_type[1]
  59. return postgis_types
  60. def get_field_type(self, data_type, description):
  61. if not self.postgis_types_reverse:
  62. # If the PostGIS types reverse dictionary is not populated, do so
  63. # now. In order to prevent unnecessary requests upon connection
  64. # initialization, the `data_types_reverse` dictionary is not updated
  65. # with the PostGIS custom types until introspection is actually
  66. # performed -- in other words, when this function is called.
  67. self.postgis_types_reverse = self.get_postgis_types()
  68. self.data_types_reverse.update(self.postgis_types_reverse)
  69. return super().get_field_type(data_type, description)
  70. def get_geometry_type(self, table_name, geo_col):
  71. """
  72. The geometry type OID used by PostGIS does not indicate the particular
  73. type of field that a geometry column is (e.g., whether it's a
  74. PointField or a PolygonField). Thus, this routine queries the PostGIS
  75. metadata tables to determine the geometry type.
  76. """
  77. with self.connection.cursor() as cursor:
  78. try:
  79. # First seeing if this geometry column is in the `geometry_columns`
  80. cursor.execute('SELECT "coord_dimension", "srid", "type" '
  81. 'FROM "geometry_columns" '
  82. 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
  83. (table_name, geo_col))
  84. row = cursor.fetchone()
  85. if not row:
  86. raise GeoIntrospectionError
  87. except GeoIntrospectionError:
  88. cursor.execute('SELECT "coord_dimension", "srid", "type" '
  89. 'FROM "geography_columns" '
  90. 'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
  91. (table_name, geo_col))
  92. row = cursor.fetchone()
  93. if not row:
  94. raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
  95. (table_name, geo_col))
  96. # OGRGeomType does not require GDAL and makes it easy to convert
  97. # from OGC geom type name to Django field.
  98. field_type = OGRGeomType(row[2]).django
  99. # Getting any GeometryField keyword arguments that are not the default.
  100. dim = row[0]
  101. srid = row[1]
  102. field_params = {}
  103. if srid != 4326:
  104. field_params['srid'] = srid
  105. if dim != 2:
  106. field_params['dim'] = dim
  107. return field_type, field_params