introspection.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from django.contrib.gis.gdal import OGRGeomType
  2. from django.db.backends.sqlite3.introspection import DatabaseIntrospection, FlexibleFieldLookupDict
  3. from django.utils import six
  4. class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict):
  5. """
  6. Sublcass that includes updates the `base_data_types_reverse` dict
  7. for geometry field types.
  8. """
  9. base_data_types_reverse = FlexibleFieldLookupDict.base_data_types_reverse.copy()
  10. base_data_types_reverse.update(
  11. {'point': 'GeometryField',
  12. 'linestring': 'GeometryField',
  13. 'polygon': 'GeometryField',
  14. 'multipoint': 'GeometryField',
  15. 'multilinestring': 'GeometryField',
  16. 'multipolygon': 'GeometryField',
  17. 'geometrycollection': 'GeometryField',
  18. })
  19. class SpatiaLiteIntrospection(DatabaseIntrospection):
  20. data_types_reverse = GeoFlexibleFieldLookupDict()
  21. def get_geometry_type(self, table_name, geo_col):
  22. cursor = self.connection.cursor()
  23. try:
  24. # Querying the `geometry_columns` table to get additional metadata.
  25. type_col = 'type' if self.connection.ops.spatial_version < (4, 0, 0) else 'geometry_type'
  26. cursor.execute('SELECT coord_dimension, srid, %s '
  27. 'FROM geometry_columns '
  28. 'WHERE f_table_name=%%s AND f_geometry_column=%%s' % type_col,
  29. (table_name, geo_col))
  30. row = cursor.fetchone()
  31. if not row:
  32. raise Exception('Could not find a geometry column for "%s"."%s"' %
  33. (table_name, geo_col))
  34. # OGRGeomType does not require GDAL and makes it easy to convert
  35. # from OGC geom type name to Django field.
  36. field_type = OGRGeomType(row[2]).django
  37. # Getting any GeometryField keyword arguments that are not the default.
  38. dim = row[0]
  39. srid = row[1]
  40. field_params = {}
  41. if srid != 4326:
  42. field_params['srid'] = srid
  43. if isinstance(dim, six.string_types) and 'Z' in dim:
  44. field_params['dim'] = 3
  45. finally:
  46. cursor.close()
  47. return field_type, field_params