desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors.'
def scale(self, x, y, z=0.0, **kwargs):
if connections[self.db].ops.spatialite: if (z != 0.0): raise NotImplementedError('SpatiaLite does not support 3D scaling.') s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s', 'procedure_args': {'x': x, 'y': y}, 'select_field': GeomField()} else: s = {'procedure_f...
'Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y sizes to snap the grid to. - 4 arguments: X, Y sizes and the X, Y origins.'
def snap_to_grid(self, *args, **kwargs):
if (False in [isinstance(arg, (float, int, long)) for arg in args]): raise TypeError('Size argument(s) for the grid must be a float or integer values.') nargs = len(args) if (nargs == 1): size = args[0] procedure_fmt = '%(geo_col)s,%(size)s' p...
'Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet. Keyword Arguments: `relative` => If set to True, this will evaluate the path in terms of relative moves (rather than absolute). `precision` => May be used to set the maximum number of decimal digits used in ou...
def svg(self, relative=False, precision=8, **kwargs):
relative = int(bool(relative)) if (not isinstance(precision, (int, long))): raise TypeError('SVG precision keyword argument must be an integer.') s = {'desc': 'SVG', 'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s', 'procedure_args': {'rel': relative, 'precision': precision}...
'Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet.'
def sym_difference(self, geom, **kwargs):
return self._geomset_attribute('sym_difference', geom, **kwargs)
'Translates the geometry to a new location using the given numeric parameters as offsets.'
def translate(self, x, y, z=0.0, **kwargs):
if connections[self.db].ops.spatialite: if (z != 0.0): raise NotImplementedError('SpatiaLite does not support 3D translation.') s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s', 'procedure_args': {'x': x, 'y': y}, 'select_field': GeomField()} else: s = {'procedu...
'Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84).'
def transform(self, srid=4326, **kwargs):
if (not isinstance(srid, (int, long))): raise TypeError('An integer SRID must be provided.') field_name = kwargs.get('field_name', None) (tmp, geo_field) = self._spatial_setup('transform', field_name=field_name) field_col = self._geocol_select(geo_field, field_name) geo_col = ...
'Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet.'
def union(self, geom, **kwargs):
return self._geomset_attribute('union', geom, **kwargs)
'Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only.'
def unionagg(self, **kwargs):
return self._spatial_aggregate(aggregates.Union, **kwargs)
'Performs set up for executing the spatial function.'
def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None):
connection = connections[self.db] func = getattr(connection.ops, att, False) if (desc is None): desc = att if (not func): raise NotImplementedError(('%s stored procedure not available on the %s backend.' % (desc, connection.ops.name))) procedure_args = {'funct...
'DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function.'
def _spatial_aggregate(self, aggregate, field_name=None, geo_field_type=None, tolerance=0.05):
geo_field = self.query._geo_field(field_name) if (not geo_field): raise TypeError(('%s aggregate only available on GeometryFields.' % aggregate.name)) if ((not (geo_field_type is None)) and (not isinstance(geo_field, geo_field_type))): raise TypeError(('%s aggregate may ...
'DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model. Arguments: att: The name of the spatial attribute that holds the spatial SQL function to call. settings: Dictonary of internal settings to customize for the spatial procedure. Public Keyword A...
def _spatial_attribute(self, att, settings, field_name=None, model_att=None):
settings.setdefault('desc', None) settings.setdefault('geom_args', ()) settings.setdefault('geom_field', None) settings.setdefault('procedure_args', {}) settings.setdefault('procedure_fmt', '%(geo_col)s') settings.setdefault('select_params', []) connection = connections[self.db] backend ...
'DRY routine for GeoQuerySet distance attribute routines.'
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
(procedure_args, geo_field) = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) connection = connections[self.db] geodetic = geo_field.geodetic(connection) geography = geo_field.geography if geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_fi...
'DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute (e.g., `centroid`, `point_on_surface`).'
def _geom_attribute(self, func, tolerance=0.05, **kwargs):
s = {'select_field': GeomField()} if connections[self.db].ops.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args'] = {'tolerance': tolerance} return self._spatial_attribute(func, s, **kwargs)
'DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute and takes a Geoemtry parameter. This is used for geometry set-like operations (e.g., intersection, difference, union, sym_difference).'
def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs):
s = {'geom_args': ('geom',), 'select_field': GeomField(), 'procedure_fmt': '%(geo_col)s,%(geom)s', 'procedure_args': {'geom': geom}} if connections[self.db].ops.oracle: s['procedure_fmt'] += ',%(tolerance)s' s['procedure_args']['tolerance'] = tolerance return self._spatial_attribute(func, s,...
'Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model.'
def _geocol_select(self, geo_field, field_name):
opts = self.model._meta if (not (geo_field in opts.fields)): self.query.add_select_related([field_name]) compiler = self.query.get_compiler(self.db) compiler.pre_sql_setup() (rel_table, rel_col) = self.query.related_select_cols[self.query.related_select_fields.index(geo_field)] ...
'Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. \'point, \'the_geom\', or a related lookup on a geographic field like \'address__point\'. If a GeometryField exists according to the given lookup on the model options, it will be retu...
@classmethod def _check_geo_field(cls, opts, lookup):
field_list = lookup.split(LOOKUP_SEP) field_list.reverse() fld_name = field_list.pop() try: geo_fld = opts.get_field(fld_name) while len(field_list): opts = geo_fld.rel.to._meta geo_fld = opts.get_field(field_list.pop()) except (FieldDoesNotExist, AttributeErr...
'Overloaded method so OracleQuery.convert_values doesn\'t balk.'
def get_internal_type(self):
return None
'Using the same routines that Oracle does we can convert our extra selection objects into Geometry and Distance objects. TODO: Make converted objects \'lazy\' for less overhead.'
def convert_values(self, value, field, connection):
if connection.ops.oracle: value = super(GeoQuery, self).convert_values(value, (field or GeomField()), connection) if (value is None): pass elif isinstance(field, DistanceField): value = Distance(**{field.distance_att: value}) elif isinstance(field, AreaField): value = Are...
'Overridden from GeoQuery\'s normalize to handle the conversion of GeoAggregate objects.'
def resolve_aggregate(self, value, aggregate, connection):
if isinstance(aggregate, self.aggregates_module.GeoAggregate): if aggregate.is_extent: if (aggregate.is_extent == '3D'): return connection.ops.convert_extent3d(value) else: return connection.ops.convert_extent(value) else: return co...
'Returns the first Geometry field encountered; or specified via the `field_name` keyword. The `field_name` may be a string specifying the geometry field on this GeoQuery\'s model, or a lookup string to a geometry field via a ForeignKey relation.'
def _geo_field(self, field_name=None):
if (field_name is None): for fld in self.model._meta.fields: if isinstance(fld, GeometryField): return fld return False else: return GeoWhereNode._check_geo_field(self.model._meta, field_name)
'Return the aggregate, rendered as SQL.'
def as_sql(self, qn, connection):
if connection.ops.oracle: self.extra['tolerance'] = self.tolerance if hasattr(self.col, 'as_sql'): field_name = self.col.as_sql(qn, connection) elif isinstance(self.col, (list, tuple)): field_name = '.'.join([qn(c) for c in self.col]) else: field_name = self.col (sql_...
'Return the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If \'with_aliases\' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguitity with...
def get_columns(self, with_aliases=False):
qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = [('(%s) AS %s' % ((self.get_extra_select_format(alias) % col[0]), qn2(alias))) for (alias, col) in self.query.extra_select.iteritems()] aliases = set(self.query.extra_select.keys()) if with_aliases: col_ali...
'Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL dire...
def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False):
result = [] if (opts is None): opts = self.query.model._meta aliases = set() only_load = self.deferred_to_columns() proxied_model = get_proxied_model(opts) if start_alias: seen = {None: start_alias} for (field, model) in opts.get_fields_with_model(): if (local_only an...
'This routine is necessary so that distances and geometries returned from extra selection SQL get resolved appropriately into Python objects.'
def resolve_columns(self, row, fields=()):
values = [] aliases = self.query.extra_select.keys() if self.query.aggregates: aliases.extend([None for i in xrange(len(self.query.aggregates))]) rn_offset = 0 if self.connection.ops.oracle: if ((self.query.high_mark is not None) or self.query.low_mark): rn_offset = 1 ...
'Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exac...
def get_field_select(self, field, alias=None, column=None):
sel_fmt = self.get_select_format(field) if (field in self.query.custom_select): field_sel = (sel_fmt % self.query.custom_select[field]) else: field_sel = (sel_fmt % self._field_column(field, alias, column)) return field_sel
'Returns the selection format string, depending on the requirements of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKT. For all other fields a simple \'%s\' format string is returned.'
def get_select_format(self, fld):
if (self.connection.ops.select and hasattr(fld, 'geom_type')): sel_fmt = self.connection.ops.select if (self.query.transformed_srid and (self.connection.ops.oracle or self.connection.ops.spatialite)): sel_fmt = ("'SRID=%d;'||%s" % (self.query.transformed_srid, sel_fmt)) else: ...
'Helper function that returns the database column for the given field. The table and column are returned (quoted) in the proper format, e.g., `"geoapp_city"."point"`. If `table_alias` is not specified, the database table associated with the model of this `GeoQuery` will be used. If `column` is specified, it will be u...
def _field_column(self, field, table_alias=None, column=None):
if (table_alias is None): table_alias = self.query.model._meta.db_table return ('%s.%s' % (self.quote_name_unless_alias(table_alias), self.connection.ops.quote_name((column or field.column))))
'Returns the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it\'s the same for all geometry types.'
def geo_db_type(self, f):
return 'MDSYS.SDO_GEOMETRY'
'Returns the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them.'
def get_distance(self, f, value, lookup_type):
if (not value): return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value if ...
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the SDO_CS.TRANSFORM() function call.'
def get_geom_placeholder(self, f, value):
if (value is None): return 'NULL' def transform_value(val, srid): return (val.srid != srid) if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) else: placeholder = '%s' ...
'Returns the SQL WHERE clause for use in Oracle spatial SQL construction.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) lookup_info = self.geometry_functions.get(lookup_type, False) if lookup_info: if isinstance(lookup_info, tuple): (sdo_op, arg_type) = lookup_info geom = value[0] if (not isinstance(value...
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__.lower() if (agg_name == 'union'): agg_name += 'agg' if agg.is_extent: sql_template = '%(function)s(%(field)s)' else: sql_template = '%(function)s(SDOAGGRTYPE(%(field)s,%(tolerance)s))' sql_function = getattr(self, agg_name) return ((self....
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'column_name'
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(OracleCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table ...
'Returns the database column type for the geometry field on the spatial backend.'
def geo_db_type(self, f):
raise NotImplementedError
'Returns the distance parameters for the given geometry field, lookup value, and lookup type.'
def get_distance(self, f, value, lookup_type):
raise NotImplementedError('Distance operations not available on this spatial backend.')
'Returns the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend.'
def get_geom_placeholder(self, f, value):
raise NotImplementedError
'Returns a GDAL SpatialReference object, if GDAL is installed.'
@property def srs(self):
if gdal.HAS_GDAL: if hasattr(self, '_srs'): return self._srs.clone() else: try: self._srs = gdal.SpatialReference(self.wkt) return self.srs except Exception as msg: pass try: self._srs = g...
'Returns a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening).'
@property def ellipsoid(self):
if gdal.HAS_GDAL: return self.srs.ellipsoid else: m = self.spheroid_regex.match(self.wkt) if m: return (float(m.group('major')), float(m.group('flattening'))) else: return None
'Returns the projection name.'
@property def name(self):
return self.srs.name
'Returns the spheroid name for this spatial reference.'
@property def spheroid(self):
return self.srs['spheroid']
'Returns the datum for this spatial reference.'
@property def datum(self):
return self.srs['datum']
'Is this Spatial Reference projected?'
@property def projected(self):
if gdal.HAS_GDAL: return self.srs.projected else: return self.wkt.startswith('PROJCS')
'Is this Spatial Reference local?'
@property def local(self):
if gdal.HAS_GDAL: return self.srs.local else: return self.wkt.startswith('LOCAL_CS')
'Is this Spatial Reference geographic?'
@property def geographic(self):
if gdal.HAS_GDAL: return self.srs.geographic else: return self.wkt.startswith('GEOGCS')
'Returns the linear units name.'
@property def linear_name(self):
if gdal.HAS_GDAL: return self.srs.linear_name elif self.geographic: return None else: m = self.units_regex.match(self.wkt) return m.group('unit_name')
'Returns the linear units.'
@property def linear_units(self):
if gdal.HAS_GDAL: return self.srs.linear_units elif self.geographic: return None else: m = self.units_regex.match(self.wkt) return m.group('unit')
'Returns the name of the angular units.'
@property def angular_name(self):
if gdal.HAS_GDAL: return self.srs.angular_name elif self.projected: return None else: m = self.units_regex.match(self.wkt) return m.group('unit_name')
'Returns the angular units.'
@property def angular_units(self):
if gdal.HAS_GDAL: return self.srs.angular_units elif self.projected: return None else: m = self.units_regex.match(self.wkt) return m.group('unit')
'Returns a tuple of the units and the name.'
@property def units(self):
if (self.projected or self.local): return (self.linear_units, self.linear_name) elif self.geographic: return (self.angular_units, self.angular_name) else: return (None, None)
'Class method used by GeometryField on initialization to retrive the units on the given WKT, without having to use any of the database fields.'
@classmethod def get_units(cls, wkt):
if gdal.HAS_GDAL: return gdal.SpatialReference(wkt).units else: m = cls.units_regex.match(wkt) return (m.group('unit'), m.group('unit_name'))
'Class method used by GeometryField on initialization to retrieve the `SPHEROID[..]` parameters from the given WKT.'
@classmethod def get_spheroid(cls, wkt, string=True):
if gdal.HAS_GDAL: srs = gdal.SpatialReference(wkt) sphere_params = srs.ellipsoid sphere_name = srs['spheroid'] else: m = cls.spheroid_regex.match(wkt) if m: sphere_params = (float(m.group('major')), float(m.group('flattening'))) sphere_name = m.gro...
'Returns the string representation. If GDAL is installed, it will be \'pretty\' OGC WKT.'
def __unicode__(self):
try: return unicode(self.srs) except: return unicode(self.wkt)
'Checks if the given aggregate name is supported (that is, if it\'s in `self.valid_aggregates`).'
def check_aggregate_support(self, aggregate):
agg_name = aggregate.__class__.__name__ return (agg_name in self.valid_aggregates)
'Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)".'
def convert_extent(self, box):
(ll, ur) = box[4:(-1)].split(',') (xmin, ymin) = map(float, ll.split()) (xmax, ymax) = map(float, ur.split()) return (xmin, ymin, xmax, ymax)
'Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)".'
def convert_extent3d(self, box3d):
(ll, ur) = box3d[6:(-1)].split(',') (xmin, ymin, zmin) = map(float, ll.split()) (xmax, ymax, zmax) = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax)
'Converts the geometry returned from PostGIS aggretates.'
def convert_geom(self, hex, geo_field):
if hex: return Geometry(hex) else: return None
'Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead.'
def geo_db_type(self, f):
if f.geography: if (not self.geography): raise NotImplementedError('PostGIS 1.5 required for geography column support.') if (f.srid != 4326): raise NotImplementedError('PostGIS 1.5 supports geography columns only with an SRID of ...
'Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what\'s available on projected geometry columns. In addition, it has to take int...
def get_distance(self, f, dist_val, lookup_type):
if (len(dist_val) == 1): (value, option) = (dist_val[0], None) else: (value, option) = dist_val geodetic = f.geodetic(self.connection) geography = (f.geography and self.geography) if isinstance(value, Distance): if geography: dist_param = value.m elif geod...
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call.'
def get_geom_placeholder(self, f, value):
if ((value is None) or (value.srid == f.srid)): placeholder = '%s' else: placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) if hasattr(value, 'expression'): placeholder = ((placeholder % '%s.%s') % tuple(map(self.quote_name, value.cols[value.expression]))) return placeho...
'Helper routine for calling PostGIS functions and returning their result.'
def _get_postgis_func(self, func):
cursor = self.connection._cursor() try: cursor.execute(('SELECT %s()' % func)) row = cursor.fetchone() except: raise finally: self.connection.close() return row[0]
'Returns the version of the GEOS library used with PostGIS.'
def postgis_geos_version(self):
return self._get_postgis_func('postgis_geos_version')
'Returns the version number of the PostGIS library used with PostgreSQL.'
def postgis_lib_version(self):
return self._get_postgis_func('postgis_lib_version')
'Returns the version of the PROJ.4 library used with PostGIS.'
def postgis_proj_version(self):
return self._get_postgis_func('postgis_proj_version')
'Returns PostGIS version number and compile-time options.'
def postgis_version(self):
return self._get_postgis_func('postgis_version')
'Returns PostGIS version number and compile-time options.'
def postgis_full_version(self):
return self._get_postgis_func('postgis_full_version')
'Returns the PostGIS version as a tuple (version string, major, minor, subminor).'
def postgis_version_tuple(self):
version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception(('Could not parse PostGIS version string: %s' % version))...
'Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers.'
def proj_version_tuple(self):
proj_regex = re.compile('(\\d+)\\.(\\d+)\\.(\\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostG...
'Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type.'
def num_params(self, lookup_type, num_param):
def exactly_two(np): return (np == 2) def two_to_three(np): return ((np >= 2) and (np <= 3)) if ((lookup_type in self.distance_functions) and (lookup_type != 'dwithin')): return two_to_three(num_param) else: return exactly_two(num_param)
'Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) if (lookup_type in self.geometry_operators): if (field.geography and (not (lookup_type in self.geography_operators))): raise ValueError(('PostGIS geography does not support the "%s" lookup.' % ...
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__ if (not self.check_aggregate_support(agg)): raise NotImplementedError(('%s spatial aggregate is not implmented for this backend.' % agg_name)) agg_name = agg_name.lower() if (agg_name == 'union'): agg_name += 'agg' sql_templat...
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'f_table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'f_geometry_column'
'Initializes on the geometry.'
def __init__(self, geom):
self.ewkb = str(geom.ewkb) self.srid = geom.srid
'Returns a properly quoted string for use in PostgreSQL/PostGIS.'
def getquoted(self):
return ('ST_GeomFromEWKB(E%s)' % Binary(self.ewkb))
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table ...
'Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported).'
def get_postgis_types(self):
cursor = self.connection.cursor() 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: ...
'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,'
def get_geometry_type(self, table_name, geo_col):
cursor = self.connection.cursor() try: try: 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): ...
'Checks if the given aggregate name is supported (that is, if it\'s in `self.valid_aggregates`).'
def check_aggregate_support(self, aggregate):
agg_name = aggregate.__class__.__name__ return (agg_name in self.valid_aggregates)
'Converts geometry WKT returned from a SpatiaLite aggregate.'
def convert_geom(self, wkt, geo_field):
if wkt: return Geometry(wkt, geo_field.srid) else: return None
'Returns None because geometry columnas are added via the `AddGeometryColumn` stored procedure on SpatiaLite.'
def geo_db_type(self, f):
return None
'Returns the distance parameters for the given geometry field, lookup value, and lookup type. SpatiaLite only supports regular cartesian-based queries (no spheroid/sphere calculations for point geometries like PostGIS).'
def get_distance(self, f, value, lookup_type):
if (not value): return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError('SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system. Distance ob...
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the Transform() and GeomFromText() function call(s).'
def get_geom_placeholder(self, f, value):
def transform_value(value, srid): return (not ((value is None) or (value.srid == srid))) if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) else: placeholder = '%s' return ((place...
'Helper routine for calling SpatiaLite functions and returning their result.'
def _get_spatialite_func(self, func):
cursor = self.connection._cursor() try: cursor.execute(('SELECT %s' % func)) row = cursor.fetchone() except: raise finally: cursor.close() return row[0]
'Returns the version of GEOS used by SpatiaLite as a string.'
def geos_version(self):
return self._get_spatialite_func('geos_version()')
'Returns the version of the PROJ.4 library used by SpatiaLite.'
def proj4_version(self):
return self._get_spatialite_func('proj4_version()')
'Returns the SpatiaLite library version as a string.'
def spatialite_version(self):
return self._get_spatialite_func('spatialite_version()')
'Returns the SpatiaLite version as a tuple (version string, major, minor, subminor).'
def spatialite_version_tuple(self):
try: version = self.spatialite_version() except DatabaseError: version = None try: tmp = self._get_spatialite_func("X(GeomFromText('POINT(1 1)'))") if (tmp == 1.0): version = '2.3.0' except DatabaseError: pass if (ver...
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__ if (not self.check_aggregate_support(agg)): raise NotImplementedError(('%s spatial aggregate is not implmented for this backend.' % agg_name)) agg_name = agg_name.lower() if (agg_name == 'union'): agg_name += 'agg' sql_templat...
'Returns the SpatiaLite-specific SQL for the given lookup value [a tuple of (alias, column, db_type)], lookup type, lookup value, the model field, and the quoting function.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) if (lookup_type in self.geometry_functions): tmp = self.geometry_functions[lookup_type] if isinstance(tmp, tuple): (op, arg_type) = tmp if (not isinstance(value, (tuple, list))): ...
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'f_table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'f_geometry_column'
'Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. This method is overloaded to load up the SpatiaLite initialization SQL prior to calling the `syncdb` command.'
def create_test_db(self, verbosity=1, autoclobber=False):
from django.core.management import call_command test_database_name = self._get_test_db_name() if (verbosity >= 1): test_db_repr = '' if (verbosity >= 2): test_db_repr = (" ('%s')" % test_database_name) print ("Creating test database for alias '%s'%s..." ...
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table ...
'This routine loads up the SpatiaLite SQL file.'
def load_spatialite_sql(self):
spatialite_sql = self.spatialite_init_file() if (not os.path.isfile(spatialite_sql)): raise ImproperlyConfigured(('Could not find the required SpatiaLite initialization SQL file (necessary for testing): %s' % spatialite_sql)) sql_fh = open(spatialite_sql, 'r') ...
'The placeholder here has to include MySQL\'s WKT constructor. Because MySQL does not support spatial transformations, there is no need to modify the placeholder based on the contents of the given value.'
def get_geom_placeholder(self, value, srid):
if hasattr(value, 'expression'): placeholder = ('%s.%s' % tuple(map(self.quote_name, value.cols[value.expression]))) else: placeholder = ('%s(%%s)' % self.from_text) return placeholder
'Test initialization of distance models.'
def test01_init(self):
self.assertEqual(9, SouthTexasCity.objects.count()) self.assertEqual(9, SouthTexasCityFt.objects.count()) self.assertEqual(11, AustraliaCity.objects.count()) self.assertEqual(4, SouthTexasZipcode.objects.count()) self.assertEqual(4, CensusZipcode.objects.count()) self.assertEqual(1, Interstate.o...
'Testing the `dwithin` lookup type.'
@no_spatialite def test02_dwithin(self):
tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)] au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)] tx_cities = ['Downtown Houston', 'Southside Place'] au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong'] for dist in tx_dists: if isinstance(dist, tuple): (d...
'Testing the `distance` GeoQuerySet method on projected coordinate systems.'
def test03a_distance_method(self):
lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326) m_distances = [147075.069813, 139630.198056, 140888.552826, 138809.684197, 158309.246259, 212183.594374, 70870.188967, 165337.758878, 139196.085105] ft_distances = [482528.79154625, 458103.408123001, 462231.860397575, 455411.438904354, 519386.2...