Permalink
Browse files

Fixed #12637 -- GeoDjango's `inspectdb` command is now a subclass of …

…Django's, and works with all spatial backends (Oracle and SpatiaLite did work before). This changeset introduces new introspection modules for all of the spatial backends and adds hooks to the original `inspectdb.Command` class to enable reuse.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@12257 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 58440c0 commit a1fbc0dc3696500cdc2391da3fbc6694a2a4841e @jbronn jbronn committed Jan 18, 2010
@@ -1,6 +1,7 @@
from django.db.backends.mysql.base import *
from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper
from django.contrib.gis.db.backends.mysql.creation import MySQLCreation
+from django.contrib.gis.db.backends.mysql.introspection import MySQLIntrospection
from django.contrib.gis.db.backends.mysql.operations import MySQLOperations
class DatabaseWrapper(MySQLDatabaseWrapper):
@@ -9,3 +10,4 @@ def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.creation = MySQLCreation(self)
self.ops = MySQLOperations()
+ self.introspection = MySQLIntrospection(self)
@@ -0,0 +1,32 @@
+from MySQLdb.constants import FIELD_TYPE
+
+from django.contrib.gis.gdal import OGRGeomType
+from django.db.backends.mysql.introspection import DatabaseIntrospection
+
+class MySQLIntrospection(DatabaseIntrospection):
+ # Updating the data_types_reverse dictionary with the appropriate
+ # type for Geometry fields.
+ data_types_reverse = DatabaseIntrospection.data_types_reverse.copy()
+ data_types_reverse[FIELD_TYPE.GEOMETRY] = 'GeometryField'
+
+ def get_geometry_type(self, table_name, geo_col):
+ cursor = self.connection.cursor()
+ try:
+ # In order to get the specific geometry type of the field,
+ # we introspect on the table definition using `DESCRIBE`.
+ cursor.execute('DESCRIBE %s' %
+ self.connection.ops.quote_name(table_name))
+ # Increment over description info until we get to the geometry
+ # column.
+ for column, typ, null, key, default, extra in cursor.fetchall():
+ if column == geo_col:
+ # Using OGRGeomType to convert from OGC name to Django field.
+ # MySQL does not support 3D or SRIDs, so the field params
+ # are empty.
+ field_type = OGRGeomType(typ).django
+ field_params = {}
+ break
+ finally:
+ cursor.close()
+
+ return field_type, field_params
@@ -1,10 +1,12 @@
from django.db.backends.oracle.base import *
from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper
from django.contrib.gis.db.backends.oracle.creation import OracleCreation
+from django.contrib.gis.db.backends.oracle.introspection import OracleIntrospection
from django.contrib.gis.db.backends.oracle.operations import OracleOperations
class DatabaseWrapper(OracleDatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
- self.creation = OracleCreation(self)
self.ops = OracleOperations(self)
+ self.creation = OracleCreation(self)
+ self.introspection = OracleIntrospection(self)
@@ -0,0 +1,39 @@
+import cx_Oracle
+from django.db.backends.oracle.introspection import DatabaseIntrospection
+
+class OracleIntrospection(DatabaseIntrospection):
+ # Associating any OBJECTVAR instances with GeometryField. Of course,
+ # this won't work right on Oracle objects that aren't MDSYS.SDO_GEOMETRY,
+ # but it is the only object type supported within Django anyways.
+ data_types_reverse = DatabaseIntrospection.data_types_reverse.copy()
+ data_types_reverse[cx_Oracle.OBJECT] = 'GeometryField'
+
+ def get_geometry_type(self, table_name, geo_col):
+ cursor = self.connection.cursor()
+ try:
+ # Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information.
+ try:
+ cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s',
+ (table_name.upper(), geo_col.upper()))
+ row = cursor.fetchone()
+ except Exception, msg:
+ raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
+ 'Error message: %s.' % (table_name, geo_col, msg))
+
+ # TODO: Research way to find a more specific geometry field type for
+ # the column's contents.
+ field_type = 'GeometryField'
+
+ # Getting the field parameters.
+ field_params = {}
+ dim, srid = row
+ if srid != 4326:
+ field_params['srid'] = srid
+ # Length of object array ( SDO_DIM_ARRAY ) is number of dimensions.
+ dim = len(dim)
+ if dim != 2:
+ field_params['dim'] = dim
+ finally:
+ cursor.close()
+
+ return field_type, field_params
@@ -1,10 +1,12 @@
from django.db.backends.postgresql_psycopg2.base import *
from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper
from django.contrib.gis.db.backends.postgis.creation import PostGISCreation
+from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection
from django.contrib.gis.db.backends.postgis.operations import PostGISOperations
class DatabaseWrapper(Psycopg2DatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.creation = PostGISCreation(self)
self.ops = PostGISOperations(self)
+ self.introspection = PostGISIntrospection(self)
@@ -0,0 +1,95 @@
+from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
+from django.contrib.gis.gdal import OGRGeomType
+
+class GeoIntrospectionError(Exception):
+ pass
+
+class PostGISIntrospection(DatabaseIntrospection):
+ # Reverse dictionary for PostGIS geometry types not populated until
+ # introspection is actually performed.
+ postgis_types_reverse = {}
+
+ def get_postgis_types(self):
+ """
+ Returns a dictionary with keys that are the PostgreSQL object
+ identification integers for the PostGIS geometry and/or
+ geography types (if supported).
+ """
+ cursor = self.connection.cursor()
+ # The OID integers associated with the geometry type may
+ # be different across versions; hence, this is why we have
+ # to query the PostgreSQL pg_type table corresponding to the
+ # PostGIS custom data types.
+ oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
+ try:
+ cursor.execute(oid_sql, ('geometry',))
+ GEOM_TYPE = cursor.fetchone()[0]
+ postgis_types = { GEOM_TYPE : 'GeometryField' }
+ if self.connection.ops.geography:
+ cursor.execute(oid_sql, ('geography',))
+ GEOG_TYPE = cursor.fetchone()[0]
+ # The value for the geography type is actually a tuple
+ # to pass in the `geography=True` keyword to the field
+ # definition.
+ postgis_types[GEOG_TYPE] = ('GeometryField', {'geography' : True})
+ finally:
+ cursor.close()
+
+ return postgis_types
+
+ def get_field_type(self, data_type, description):
+ if not self.postgis_types_reverse:
+ # If the PostGIS types reverse dictionary is not populated, do so
+ # now. In order to prevent unnecessary requests upon connection
+ # intialization, the `data_types_reverse` dictionary is not updated
+ # with the PostGIS custom types until introspection is actually
+ # performed -- in other words, when this function is called.
+ self.postgis_types_reverse = self.get_postgis_types()
+ self.data_types_reverse.update(self.postgis_types_reverse)
+ return super(PostGISIntrospection, self).get_field_type(data_type, description)
+
+ def get_geometry_type(self, table_name, geo_col):
+ """
+ The geometry type OID used by PostGIS does not indicate the particular
+ type of field that a geometry column is (e.g., whether it's a
+ PointField or a PolygonField). Thus, this routine queries the PostGIS
+ metadata tables to determine the geometry type,
+ """
+ cursor = self.connection.cursor()
+ try:
+ try:
+ # First seeing if this geometry column is in the `geometry_columns`
+ cursor.execute('SELECT "coord_dimension", "srid", "type" '
+ 'FROM "geometry_columns" '
+ 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
+ (table_name, geo_col))
+ row = cursor.fetchone()
+ if not row: raise GeoIntrospectionError
+ except GeoIntrospectionError:
+ if self.connection.ops.geography:
+ cursor.execute('SELECT "coord_dimension", "srid", "type" '
+ 'FROM "geography_columns" '
+ 'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
+ (table_name, geo_col))
+ row = cursor.fetchone()
+
+ if not row:
+ raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
+ (table_name, geo_col))
+
+ # OGRGeomType does not require GDAL and makes it easy to convert
+ # from OGC geom type name to Django field.
+ field_type = OGRGeomType(row[2]).django
+
+ # Getting any GeometryField keyword arguments that are not the default.
+ dim = row[0]
+ srid = row[1]
+ field_params = {}
+ if srid != 4326:
+ field_params['srid'] = srid
+ if dim != 2:
+ field_params['dim'] = dim
+ finally:
+ cursor.close()
+
+ return field_type, field_params
@@ -7,6 +7,7 @@
_sqlite_extract, _sqlite_date_trunc, _sqlite_regexp
from django.contrib.gis.db.backends.spatialite.client import SpatiaLiteClient
from django.contrib.gis.db.backends.spatialite.creation import SpatiaLiteCreation
+from django.contrib.gis.db.backends.spatialite.introspection import SpatiaLiteIntrospection
from django.contrib.gis.db.backends.spatialite.operations import SpatiaLiteOperations
class DatabaseWrapper(SqliteDatabaseWrapper):
@@ -32,6 +33,7 @@ def __init__(self, *args, **kwargs):
self.ops = SpatiaLiteOperations(self)
self.client = SpatiaLiteClient(self)
self.creation = SpatiaLiteCreation(self)
+ self.introspection = SpatiaLiteIntrospection(self)
def _cursor(self):
if self.connection is None:
@@ -0,0 +1,51 @@
+from django.contrib.gis.gdal import OGRGeomType
+from django.db.backends.sqlite3.introspection import DatabaseIntrospection, FlexibleFieldLookupDict
+
+class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict):
+ """
+ Sublcass that includes updates the `base_data_types_reverse` dict
+ for geometry field types.
+ """
+ base_data_types_reverse = FlexibleFieldLookupDict.base_data_types_reverse.copy()
+ base_data_types_reverse.update(
+ {'point' : 'GeometryField',
+ 'linestring' : 'GeometryField',
+ 'polygon' : 'GeometryField',
+ 'multipoint' : 'GeometryField',
+ 'multilinestring' : 'GeometryField',
+ 'multipolygon' : 'GeometryField',
+ 'geometrycollection' : 'GeometryField',
+ })
+
+class SpatiaLiteIntrospection(DatabaseIntrospection):
+ data_types_reverse = GeoFlexibleFieldLookupDict()
+
+ def get_geometry_type(self, table_name, geo_col):
+ cursor = self.connection.cursor()
+ try:
+ # Querying the `geometry_columns` table to get additional metadata.
+ cursor.execute('SELECT "coord_dimension", "srid", "type" '
+ 'FROM "geometry_columns" '
+ 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
+ (table_name, geo_col))
+ row = cursor.fetchone()
+ if not row:
+ raise Exception('Could not find a geometry column for "%s"."%s"' %
+ (table_name, geo_col))
+
+ # OGRGeomType does not require GDAL and makes it easy to convert
+ # from OGC geom type name to Django field.
+ field_type = OGRGeomType(row[2]).django
+
+ # Getting any GeometryField keyword arguments that are not the default.
+ dim = row[0]
+ srid = row[1]
+ field_params = {}
+ if srid != 4326:
+ field_params['srid'] = srid
+ if isinstance(dim, basestring) and 'Z' in dim:
+ field_params['dim'] = 3
+ finally:
+ cursor.close()
+
+ return field_type, field_params
Oops, something went wrong.

0 comments on commit a1fbc0d

Please sign in to comment.