/django/contrib/gis/db/backends/postgis/creation.py

https://code.google.com/p/mango-py/ · Python · 60 lines · 45 code · 9 blank · 6 comment · 7 complexity · 957c7e5ebd6bac2b4e6984cf6b785a6f MD5 · raw file

  1. from django.conf import settings
  2. from django.db.backends.postgresql.creation import DatabaseCreation
  3. class PostGISCreation(DatabaseCreation):
  4. geom_index_type = 'GIST'
  5. geom_index_opts = 'GIST_GEOMETRY_OPS'
  6. def sql_indexes_for_field(self, model, f, style):
  7. "Return any spatial index creation SQL for the field."
  8. from django.contrib.gis.db.models.fields import GeometryField
  9. output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style)
  10. if isinstance(f, GeometryField):
  11. gqn = self.connection.ops.geo_quote_name
  12. qn = self.connection.ops.quote_name
  13. db_table = model._meta.db_table
  14. if f.geography:
  15. # Geogrophy columns are created normally.
  16. pass
  17. else:
  18. # Geometry columns are created by `AddGeometryColumn`
  19. # stored procedure.
  20. output.append(style.SQL_KEYWORD('SELECT ') +
  21. style.SQL_TABLE('AddGeometryColumn') + '(' +
  22. style.SQL_TABLE(gqn(db_table)) + ', ' +
  23. style.SQL_FIELD(gqn(f.column)) + ', ' +
  24. style.SQL_FIELD(str(f.srid)) + ', ' +
  25. style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' +
  26. style.SQL_KEYWORD(str(f.dim)) + ');')
  27. if not f.null:
  28. # Add a NOT NULL constraint to the field
  29. output.append(style.SQL_KEYWORD('ALTER TABLE ') +
  30. style.SQL_TABLE(qn(db_table)) +
  31. style.SQL_KEYWORD(' ALTER ') +
  32. style.SQL_FIELD(qn(f.column)) +
  33. style.SQL_KEYWORD(' SET NOT NULL') + ';')
  34. if f.spatial_index:
  35. # Spatial indexes created the same way for both Geometry and
  36. # Geography columns
  37. if f.geography:
  38. index_opts = ''
  39. else:
  40. index_opts = ' ' + style.SQL_KEYWORD(self.geom_index_opts)
  41. output.append(style.SQL_KEYWORD('CREATE INDEX ') +
  42. style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) +
  43. style.SQL_KEYWORD(' ON ') +
  44. style.SQL_TABLE(qn(db_table)) +
  45. style.SQL_KEYWORD(' USING ') +
  46. style.SQL_COLTYPE(self.geom_index_type) + ' ( ' +
  47. style.SQL_FIELD(qn(f.column)) + index_opts + ' );')
  48. return output
  49. def sql_table_creation_suffix(self):
  50. qn = self.connection.ops.quote_name
  51. return ' TEMPLATE %s' % qn(getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis'))