introspection.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
  2. from django.contrib.gis.gdal import OGRGeomType
  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. def get_postgis_types(self):
  17. """
  18. Returns a dictionary with keys that are the PostgreSQL object
  19. identification integers for the PostGIS geometry and/or
  20. geography types (if supported).
  21. """
  22. cursor = self.connection.cursor()
  23. # The OID integers associated with the geometry type may
  24. # be different across versions; hence, this is why we have
  25. # to query the PostgreSQL pg_type table corresponding to the
  26. # PostGIS custom data types.
  27. oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
  28. try:
  29. cursor.execute(oid_sql, ('geometry',))
  30. GEOM_TYPE = cursor.fetchone()[0]
  31. postgis_types = {GEOM_TYPE: 'GeometryField'}
  32. if self.connection.ops.geography:
  33. cursor.execute(oid_sql, ('geography',))
  34. GEOG_TYPE = cursor.fetchone()[0]
  35. # The value for the geography type is actually a tuple
  36. # to pass in the `geography=True` keyword to the field
  37. # definition.
  38. postgis_types[GEOG_TYPE] = ('GeometryField', {'geography': True})
  39. finally:
  40. cursor.close()
  41. return postgis_types
  42. def get_field_type(self, data_type, description):
  43. if not self.postgis_types_reverse:
  44. # If the PostGIS types reverse dictionary is not populated, do so
  45. # now. In order to prevent unnecessary requests upon connection
  46. # initialization, the `data_types_reverse` dictionary is not updated
  47. # with the PostGIS custom types until introspection is actually
  48. # performed -- in other words, when this function is called.
  49. self.postgis_types_reverse = self.get_postgis_types()
  50. self.data_types_reverse.update(self.postgis_types_reverse)
  51. return super(PostGISIntrospection, self).get_field_type(data_type, description)
  52. def get_geometry_type(self, table_name, geo_col):
  53. """
  54. The geometry type OID used by PostGIS does not indicate the particular
  55. type of field that a geometry column is (e.g., whether it's a
  56. PointField or a PolygonField). Thus, this routine queries the PostGIS
  57. metadata tables to determine the geometry type,
  58. """
  59. cursor = self.connection.cursor()
  60. try:
  61. try:
  62. # First seeing if this geometry column is in the `geometry_columns`
  63. cursor.execute('SELECT "coord_dimension", "srid", "type" '
  64. 'FROM "geometry_columns" '
  65. 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
  66. (table_name, geo_col))
  67. row = cursor.fetchone()
  68. if not row:
  69. raise GeoIntrospectionError
  70. except GeoIntrospectionError:
  71. if self.connection.ops.geography:
  72. cursor.execute('SELECT "coord_dimension", "srid", "type" '
  73. 'FROM "geography_columns" '
  74. 'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
  75. (table_name, geo_col))
  76. row = cursor.fetchone()
  77. if not row:
  78. raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
  79. (table_name, geo_col))
  80. # OGRGeomType does not require GDAL and makes it easy to convert
  81. # from OGC geom type name to Django field.
  82. field_type = OGRGeomType(row[2]).django
  83. # Getting any GeometryField keyword arguments that are not the default.
  84. dim = row[0]
  85. srid = row[1]
  86. field_params = {}
  87. if srid != 4326:
  88. field_params['srid'] = srid
  89. if dim != 2:
  90. field_params['dim'] = dim
  91. finally:
  92. cursor.close()
  93. return field_type, field_params