Django

Code

Changeset 6524

Show
Ignore:
Timestamp:
10/16/07 01:41:16 (7 months ago)
Author:
jbronn
Message:

gis: Added preliminary spatial backend for Oracle; added GEOS routine fromfile.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/gis/django/contrib/gis/db/backend/__init__.py

    r6508 r6524  
    3636        create_spatial_db, get_geo_where_clause, gqn, \ 
    3737        ASGML, ASKML, GEOM_SELECT, TRANSFORM, UNION 
     38    SPATIAL_BACKEND = 'postgis' 
     39elif settings.DATABASE_ENGINE == 'oracle': 
     40    from django.contrib.gis.db.backend.oracle import \ 
     41         OracleSpatialField as GeoBackendField, \ 
     42         ORACLE_SPATIAL_TERMS as GIS_TERMS, \ 
     43         create_spatial_db, get_geo_where_clause, gqn, \ 
     44         ASGML, GEOM_SELECT, TRANSFORM, UNION 
     45    SPATIAL_BACKEND = 'oracle' 
    3846else: 
    39     raise NotImplementedError('No Geographic Backend exists for %s' % settings.DATABASE_NAME) 
     47    raise NotImplementedError('No Geographic Backend exists for %s' % settings.DATABASE_ENGINE) 
    4048 
    4149def geo_quotename(value): 
  • django/branches/gis/django/contrib/gis/db/backend/postgis/field.py

    r6508 r6524  
    120120                # to perform a geometry transformation. 
    121121                return GeoFieldSQL(['%s(%%s,%%s)' % TRANSFORM], 
    122                                        [adapt, self._srid]) 
     122                                   [adapt, self._srid]) 
    123123            else: 
    124124                return GeoFieldSQL(['%s'], [adapt]) 
  • django/branches/gis/django/contrib/gis/db/backend/postgis/models.py

    r6467 r6524  
    2727 
    2828    @classmethod 
    29     def table_name(self): 
    30         "Class method for returning the table name field for this model." 
     29    def table_name_col(self): 
     30        "Class method for returning the table name column for this model." 
    3131        return 'f_table_name' 
    3232 
  • django/branches/gis/django/contrib/gis/db/backend/postgis/query.py

    r6508 r6524  
    106106# These are the PostGIS-customized QUERY_TERMS -- a list of the lookup types 
    107107#  allowed for geographic queries. 
    108 POSTGIS_TERMS = list(POSTGIS_OPERATORS.keys()) # Getting the operators first 
    109 POSTGIS_TERMS += list(POSTGIS_GEOMETRY_FUNCTIONS.keys()) # Adding on the Geometry Functions 
     108POSTGIS_TERMS = POSTGIS_OPERATORS.keys() # Getting the operators first 
     109POSTGIS_TERMS += POSTGIS_GEOMETRY_FUNCTIONS.keys() # Adding on the Geometry Functions 
    110110POSTGIS_TERMS += MISC_TERMS # Adding any other miscellaneous terms (e.g., 'isnull') 
    111111POSTGIS_TERMS = tuple(POSTGIS_TERMS) # Making immutable 
  • django/branches/gis/django/contrib/gis/db/models/query.py

    r6508 r6524  
    77from django.contrib.gis.db.models.fields import GeometryField 
    88# parse_lookup depends on the spatial database backend. 
    9 from django.contrib.gis.db.backend import parse_lookup, ASGML, ASKML, GEOM_SELECT, TRANSFORM, UNION 
     9from django.contrib.gis.db.backend import parse_lookup, ASGML, ASKML, GEOM_SELECT, SPATIAL_BACKEND, TRANSFORM, UNION 
    1010from django.contrib.gis.geos import GEOSGeometry 
    1111 
     
    5252        return clone 
    5353 
    54     def _get_sql_clause(self): 
     54    def _get_sql_clause(self, get_full_query=False): 
    5555        qn = connection.ops.quote_name 
    5656        opts = self.model._meta 
     
    148148 
    149149        # LIMIT and OFFSET clauses 
    150         if self._limit is not None: 
    151             sql.append("%s " % connection.ops.limit_offset_sql(self._limit, self._offset)) 
    152         else: 
    153             assert self._offset is None, "'offset' is not allowed without 'limit'" 
    154  
    155         return select, " ".join(sql), params 
     150        if SPATIAL_BACKEND != 'oracle': 
     151            if self._limit is not None: 
     152                sql.append("%s " % connection.ops.limit_offset_sql(self._limit, self._offset)) 
     153            else: 
     154                assert self._offset is None, "'offset' is not allowed without 'limit'" 
     155 
     156            return select, " ".join(sql), params 
     157        else: 
     158            # To support limits and offsets, Oracle requires some funky rewriting of an otherwise normal looking query. 
     159            select_clause = ",".join(select) 
     160            distinct = (self._distinct and "DISTINCT " or "") 
     161 
     162            if order_by: 
     163                order_by_clause = " OVER (ORDER BY %s )" % (", ".join(order_by)) 
     164            else: 
     165                #Oracle's row_number() function always requires an order-by clause. 
     166                #So we need to define a default order-by, since none was provided. 
     167                order_by_clause = " OVER (ORDER BY %s.%s)" % \ 
     168                                  (qn(opts.db_table), qn(opts.fields[0].db_column or opts.fields[0].column)) 
     169            # limit_and_offset_clause 
     170            if self._limit is None: 
     171                assert self._offset is None, "'offset' is not allowed without 'limit'" 
     172 
     173            if self._offset is not None: 
     174                offset = int(self._offset) 
     175            else: 
     176                offset = 0 
     177            if self._limit is not None: 
     178                limit = int(self._limit) 
     179            else: 
     180                limit = None 
     181 
     182            limit_and_offset_clause = '' 
     183            if limit is not None: 
     184                limit_and_offset_clause = "WHERE rn > %s AND rn <= %s" % (offset, limit+offset) 
     185            elif offset: 
     186                limit_and_offset_clause = "WHERE rn > %s" % (offset) 
     187 
     188            if len(limit_and_offset_clause) > 0: 
     189                fmt = \ 
     190    """SELECT * FROM 
     191      (SELECT %s%s, 
     192              ROW_NUMBER()%s AS rn 
     193       %s) 
     194    %s""" 
     195                full_query = fmt % (distinct, select_clause, 
     196                                        order_by_clause, ' '.join(sql).strip(), 
     197                                        limit_and_offset_clause) 
     198            else: 
     199                full_query = None 
     200 
     201            if get_full_query: 
     202                return select, " ".join(sql), params, full_query 
     203            else: 
     204                return select, " ".join(sql), params 
    156205 
    157206    def _clone(self, klass=None, **kwargs): 
     
    193242            raise TypeError('GML output only available on GeometryFields') 
    194243 
    195         # Adding AsGML function call to SELECT part of the SQL. 
    196         return self.extra(select={'gml':'%s(%s,%s,%s)' % (ASGML, field_col, precision, version)}) 
     244        if SPATIAL_BACKEND == 'oracle': 
     245            gml_select = {'gml':'%s(%s)' % (ASGML, field_col)} 
     246        else: 
     247            gml_select = {'gml':'%s(%s,%s,%s)' % (ASGML, field_col, precision, version)} 
     248 
     249        # Adding GML function call to SELECT part of the SQL. 
     250        return self.extra(select=gml_select) 
    197251 
    198252    def kml(self, field_name, precision=8): 
     
    228282        # Setting the key for the field's column with the custom SELECT SQL to  
    229283        #  override the geometry column returned from the database. 
    230         self._custom_select[field.column] = \ 
    231             '(%s(%s, %s)) AS %s' % (TRANSFORM, col, srid, 
    232                                     connection.ops.quote_name(field.column)) 
     284        if SPATIAL_BACKEND == 'oracle': 
     285            custom_sel = '%s(%s, %s)' % (TRANSFORM, col, srid) 
     286        else: 
     287            custom_sel = '(%s(%s, %s)) AS %s' % \ 
     288                         (TRANSFORM, col, srid, connection.ops.quote_name(field.column)) 
     289        self._custom_select[field.column] = custom_sel 
    233290        return self._clone() 
    234291 
    235     def union(self, field_name): 
     292    def union(self, field_name, tolerance=0.0005): 
    236293        """ 
    237294        Performs an aggregate union on the given geometry field.  Returns 
    238         None if the GeoQuerySet is empty. 
     295        None if the GeoQuerySet is empty.  The `tolerance` keyword is for 
     296        Oracle backends only. 
    239297        """ 
    240298        # Making sure backend supports the Union stored procedure 
     
    255313        # Replacing the select with a call to the ST_Union stored procedure 
    256314        #  on the geographic field column. 
    257         union_sql = ('SELECT %s(%s)' % (UNION, field_col)) + sql 
     315        if SPATIAL_BACKEND == 'oracle': 
     316            union_sql = 'SELECT %s' % self._geo_fmt 
     317            union_sql = union_sql % ('%s(SDOAGGRTYPE(%s,%s))' % (UNION, field_col, tolerance)) 
     318            union_sql += sql 
     319        else: 
     320            union_sql = ('SELECT %s(%s)' % (UNION, field_col)) + sql 
     321 
     322        # Getting a cursor, executing the query. 
    258323        cursor = connection.cursor() 
    259324        cursor.execute(union_sql, params) 
    260325 
    261         # Pulling the HEXEWKB from the returned cursor. 
    262         hex = cursor.fetchone()[0] 
    263         if hex: return GEOSGeometry(hex) 
     326        if SPATIAL_BACKEND == 'oracle': 
     327            # On Oracle have to read out WKT from CLOB first. 
     328            clob = cursor.fetchone()[0] 
     329            if clob: u = clob.read() 
     330            else: u = None 
     331        else: 
     332            u = cursor.fetchone()[0] 
     333 
     334        if u: return GEOSGeometry(u) 
    264335        else: return None 
  • django/branches/gis/django/contrib/gis/geos/__init__.py

    r6024 r6524  
    3030""" 
    3131 
    32 from django.contrib.gis.geos.base import GEOSGeometry 
     32from django.contrib.gis.geos.base import GEOSGeometry, wkt_regex, hex_regex 
    3333from django.contrib.gis.geos.geometries import Point, LineString, LinearRing, Polygon, HAS_NUMPY 
    3434from django.contrib.gis.geos.collections import GeometryCollection, MultiPoint, MultiLineString, MultiPolygon 
    3535from django.contrib.gis.geos.error import GEOSException, GEOSGeometryIndexError 
    3636from django.contrib.gis.geos.libgeos import geos_version 
     37 
     38def fromfile(file_name): 
     39    """ 
     40    Given a string file name, returns a GEOSGeometry. The file may contain WKB, 
     41    WKT, or HEX. 
     42    """ 
     43    fh = open(file_name, 'rb') 
     44    buf = fh.read() 
     45    fh.close() 
     46    if wkt_regex.match(buf) or hex_regex.match(buf): 
     47        return GEOSGeometry(buf) 
     48    else: 
     49        return GEOSGeometry(buffer(buf)) 
    3750 
    3851def fromstr(wkt_or_hex, **kwargs): 
  • django/branches/gis/django/contrib/gis/models.py

    r6467 r6524  
    121121if settings.DATABASE_ENGINE == 'postgresql_psycopg2': 
    122122    from django.contrib.gis.db.backend.postgis.models import GeometryColumns, SpatialRefSys 
     123elif settings.DATABASE_ENGINE == 'oracle': 
     124    from django.contrib.gis.db.backend.oracle.models import GeometryColumns, SpatialRefSys 
    123125else: 
    124126    raise NotImplementedError('No SpatialRefSys or GeometryColumns models for backend: %s' % settings.DATABASE_ENGINE) 
  • django/branches/gis/django/contrib/gis/tests/geoapp/tests.py

    r6467 r6524  
    1 import unittest 
     1import os, unittest 
    22from models import Country, City, State, Feature 
     3from django.contrib.gis import gdal 
    34from django.contrib.gis.geos import * 
    4 from django.contrib.gis import gdal 
     5from django.contrib.gis.tests.utils import no_oracle, no_postgis, oracle, postgis 
    56 
    67class GeoModelTest(unittest.TestCase): 
     
    89    def test01_initial_sql(self): 
    910        "Testing geographic initial SQL." 
     11        if oracle: 
     12            # Oracle doesn't allow strings longer than 4000 characters 
     13            # in SQL files, and I'm stumped on how to use Oracle BFILE's 
     14            # in PLSQL, so we set up the larger geometries manually, rather 
     15            # than relying on the initial SQL.  
     16 
     17            # Routine for returning the path to the data files. 
     18            data_dir = os.path.join(os.path.dirname(__file__), 'sql') 
     19            def get_file(wkt_file): 
     20                return os.path.join(data_dir, wkt_file) 
     21 
     22            co = State(name='Colorado', poly=fromfile(get_file('co.wkt'))) 
     23            co.save() 
     24            ks = State(name='Kansas', poly=fromfile(get_file('ks.wkt'))) 
     25            ks.save() 
     26            tx = Country(name='Texas', mpoly=fromfile(get_file('tx.wkt'))) 
     27            tx.save() 
     28            nz = Country(name='New Zealand', mpoly=fromfile(get_file('nz.wkt'))) 
     29            nz.save() 
     30 
    1031        # Ensuring that data was loaded from initial SQL. 
    1132        self.assertEqual(2, Country.objects.count()) 
     
    81102        nullstate.delete() 
    82103 
     104    @no_oracle # Oracle does not support KML. 
    83105    def test03a_kml(self): 
    84106        "Testing KML output from the database using GeoManager.kml()." 
     
    99121        self.assertRaises(TypeError, qs.gml, 'name') 
    100122        ptown = City.objects.gml('point', precision=9).get(name='Pueblo') 
    101         self.assertEqual('<gml:Point srsName="EPSG:4326"><gml:coordinates>-104.609252,38.255001</gml:coordinates></gml:Point>', ptown.gml) 
     123        if oracle: 
     124            # No precision parameter for Oracle :-/ 
     125            import re 
     126            gml_regex = re.compile(r'<gml:Point srsName="SDO:4326" xmlns:gml="http://www.opengis.net/gml"><gml:coordinates decimal="\." cs="," ts=" ">-104.60925199\d+,38.25500\d+ </gml:coordinates></gml:Point>') 
     127            self.assertEqual(True, bool(gml_regex.match(ptown.gml))) 
     128        else: 
     129            self.assertEqual('<gml:Point srsName="EPSG:4326"><gml:coordinates>-104.609252,38.255001</gml:coordinates></gml:Point>', ptown.gml) 
    102130 
    103131    def test04_transform(self): 
     
    108136 
    109137        # Asserting the result of the transform operation with the values in 
    110         #  the pre-transformed points. 
    111         h = City.objects.transform('point', srid=htown.srid).get(name='Houston') 
    112         self.assertAlmostEqual(htown.x, h.point.x, 8) 
    113         self.assertAlmostEqual(htown.y, h.point.y, 8) 
     138        #  the pre-transformed points.  Oracle does not have the 3084 SRID. 
     139        if not oracle: 
     140            h = City.objects.transform('point', srid=htown.srid).get(name='Houston') 
     141            self.assertAlmostEqual(htown.x, h.point.x, 8) 
     142            self.assertAlmostEqual(htown.y, h.point.y, 8) 
    114143 
    115144        p = City.objects.transform('point', srid=ptown.srid).get(name='Pueblo') 
    116         self.assertAlmostEqual(ptown.x, p.point.x, 8
    117         self.assertAlmostEqual(ptown.y, p.point.y, 8
     145        self.assertAlmostEqual(ptown.x, p.point.x, 7
     146        self.assertAlmostEqual(ptown.y, p.point.y, 7
    118147 
    119148    def test10_contains_contained(self): 
     
    125154        #  and Oklahoma City because 'contained' only checks on the 
    126155        #  _bounding box_ of the Geometries. 
    127         qs = City.objects.filter(point__contained=texas.mpoly) 
    128         self.assertEqual(3, qs.count()) 
    129         cities = ['Houston', 'Dallas', 'Oklahoma City'] 
    130         for c in qs: self.assertEqual(True, c.name in cities) 
     156        if not oracle: 
     157            qs = City.objects.filter(point__contained=texas.mpoly) 
     158            self.assertEqual(3, qs.count()) 
     159            cities = ['Houston', 'Dallas', 'Oklahoma City'] 
     160            for c in qs: self.assertEqual(True, c.name in cities) 
    131161 
    132162        # Pulling out some cities. 
     
    152182 
    153183        # OK City is contained w/in bounding box of Texas. 
    154         qs = Country.objects.filter(mpoly__bbcontains=okcity.point) 
    155         self.assertEqual(1, len(qs)) 
    156         self.assertEqual('Texas', qs[0].name) 
     184        if not oracle: 
     185            qs = Country.objects.filter(mpoly__bbcontains=okcity.point) 
     186            self.assertEqual(1, len(qs)) 
     187            self.assertEqual('Texas', qs[0].name) 
    157188 
    158189    def test11_lookup_insert_transform(self): 
    159190        "Testing automatic transform for lookups and inserts." 
    160         # San Antonio in 'WGS84' (SRID 4326) and 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) 
     191        # San Antonio in 'WGS84' (SRID 4326) 
    161192        sa_4326 = 'POINT (-98.493183 29.424170)' 
    162         sa_3084 = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform 
    163  
    164         # Constructing & querying with a point from a different SRID 
    165193        wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 
    166         nad_pnt = fromstr(sa_3084, srid=3084) 
    167         tx = Country.objects.get(mpoly__intersects=nad_pnt) 
     194 
     195        # Oracle doesn't have SRID 3084, using 41157. 
     196        if oracle: 
     197            # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) 
     198            # Used the following Oracle SQL to get this value: 
     199            #  SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL; 
     200            nad_wkt  = 'POINT (300662.034646583 5416427.45974934)' 
     201            nad_srid = 41157 
     202        else: 
     203            # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) 
     204            nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform 
     205            nad_srid = 3084 
     206 
     207        # Constructing & querying with a point from a different SRID. Oracle 
     208        # `SDO_OVERLAPBDYINTERSECT` operates differently from 
     209        # `ST_Intersects`, so contains is used instead. 
     210        nad_pnt = fromstr(nad_wkt, srid=nad_srid) 
     211        if oracle: 
     212            tx = Country.objects.get(mpoly__contains=nad_pnt)  
     213        else: 
     214            tx = Country.objects.get(mpoly__intersects=nad_pnt) 
    168215        self.assertEqual('Texas', tx.name) 
    169216         
     
    178225 
    179226    def test12_null_geometries(self): 
    180         "Testing NULL geometry support." 
     227        "Testing NULL geometry support, and the `isnull` lookup type." 
    181228        # Querying for both NULL and Non-NULL values. 
    182229        nullqs = State.objects.filter(poly__isnull=True) 
     
    194241 
    195242        # Saving another commonwealth w/a NULL geometry. 
    196         nmi = State(name='Northern Mariana Islands', poly=None) 
    197         nmi.save() 
    198      
     243        if not oracle: 
     244            # TODO: Fix saving w/NULL geometry on Oracle. 
     245            nmi = State(name='Northern Mariana Islands', poly=None) 
     246            nmi.save() 
     247 
     248    @no_oracle # No specific `left` or `right` operators in Oracle. 
    199249    def test13_left_right(self): 
    200250        "Testing the 'left' and 'right' lookup types." 
     
    241291        for c in [c1, c2, c3]: self.assertEqual('Houston', c.name) 
    242292 
     293    @no_oracle # Oracle SDO_RELATE() uses a different system. 
    243294    def test15_relate(self): 
    244295        "Testing the 'relate' lookup type." 
  • django/branches/gis/django/contrib/gis/tests/test_spatialrefsys.py

    r6021 r6524  
    11import unittest 
    22from django.contrib.gis.models import SpatialRefSys 
     3from django.contrib.gis.tests.utils import oracle, postgis 
    34 
    45test_srs = ({'srid' : 4326, 
    5              'auth_name' : 'EPSG'
     6             'auth_name' : ('EPSG', True)
    67             'auth_srid' : 4326, 
    78             'srtext' : 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', 
     
    1314             }, 
    1415            {'srid' : 32140, 
    15              'auth_name' : 'EPSG'
     16             'auth_name' : ('EPSG', False)
    1617             'auth_srid' : 32140, 
    1718             'srtext' : 'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",30.28333333333333],PARAMETER["standard_parallel_2",28.38333333333333],PARAMETER["latitude_of_origin",27.83333333333333],PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],PARAMETER["false_northing",4000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32140"]]', 
     
    3132            srs = SpatialRefSys.objects.get(srid=sd['srid']) 
    3233            self.assertEqual(sd['srid'], srs.srid) 
    33             self.assertEqual(sd['auth_name'], srs.auth_name) 
     34 
     35            # Some of the authority names are borked on Oracle, e.g., SRID=32140. 
     36            #  also, Oracle Spatial seems to add extraneous info to fields, hence the 
     37            #  the testing with the 'startswith' flag. 
     38            auth_name, oracle_flag = sd['auth_name'] 
     39            if postgis or (oracle and oracle_flag): 
     40                self.assertEqual(True, srs.auth_name.startswith(auth_name)) 
     41                 
    3442            self.assertEqual(sd['auth_srid'], srs.auth_srid) 
    35             self.assertEqual(sd['srtext'], srs.srtext) 
    36             self.assertEqual(sd['proj4'], srs.proj4text) 
     43 
     44            # No proj.4 and different srtext on oracle backends :( 
     45            if postgis: 
     46                self.assertEqual(sd['srtext'], srs.wkt) 
     47                self.assertEqual(sd['proj4'], srs.proj4text) 
    3748 
    3849    def test02_osr(self): 
     
    4051        for sd in test_srs: 
    4152            sr = SpatialRefSys.objects.get(srid=sd['srid']) 
    42             self.assertEqual(sd['spheroid'], sr.spheroid
     53            self.assertEqual(True, sr.spheroid.startswith(sd['spheroid'])
    4354            self.assertEqual(sd['geographic'], sr.geographic) 
    4455            self.assertEqual(sd['projected'], sr.projected) 
    45             self.assertEqual(sd['name'], sr.name
     56            self.assertEqual(True, sr.name.startswith(sd['name'])
    4657 
    4758            # Testing the SpatialReference object directly. 
    48             srs = sr.srs 
    49             self.assertEqual(sd['proj4'], srs.proj4) 
    50             self.assertEqual(sd['srtext'], srs.wkt) 
     59            if postgis: 
     60                srs = sr.srs 
     61                self.assertEqual(sd['proj4'], srs.proj4) 
     62                self.assertEqual(sd['srtext'], srs.wkt) 
    5163 
    5264    def test03_ellipsoid(self): 
  • django/branches/gis/django/contrib/gis/utils/__init__.py

    r6423 r6524  
    99    from django.contrib.gis.utils.ogrinfo import ogrinfo, sample 
    1010    from django.contrib.gis.utils.layermapping import LayerMapping 
    11  
     11     
    1212# Importing GeoIP 
    1313try: 
     
    1616except: 
    1717    HAS_GEOIP = False 
     18 
  • django/branches/gis/django/contrib/gis/utils/layermapping.py

    r6422 r6524  
    100100from types import StringType, TupleType 
    101101from datetime import datetime 
     102from django.contrib.gis.db.backend import SPATIAL_BACKEND 
    102103from django.contrib.gis.gdal import \ 
    103104     OGRGeometry, OGRGeomType, SpatialReference, CoordTransform, \ 
     
    177178            model_type = model_fields[model_field[:-3]] 
    178179        else: 
    179             raise Exception, 'Given mapping field "%s" not in given Model fields!' % model_field 
     180            raise Exception('Given mapping field "%s" not in given Model fields!' % model_field) 
    180181 
    181182        ### Handling if we get a geometry in the Field ### 
     
    183184            # At this time, no more than one geographic field per model =( 
    184185            if HAS_GEO: 
    185                 raise Exception, 'More than one geographic field in mapping not allowed (yet).' 
     186                raise Exception('More than one geographic field in mapping not allowed (yet).') 
    186187            else: 
    187188                HAS_GEO = ogr_field 
     
    189190            # Making sure this geometry field type is a valid Django GIS field. 
    190191            if not model_type in gis_fields: 
    191                 raise Exception, 'Unknown Django GIS field type "%s"' % model_type 
     192                raise Exception('Unknown Django GIS field type "%s"' % model_type) 
    192193             
    193194            # Getting the OGRGeometry, it's type (an integer) and it's name (a string) 
     
    203204                pass 
    204205            else: 
    205                 raise Exception, 'Invalid mapping geometry; model has %s, feature has %s' % (model_type, gtype
     206                raise Exception('Invalid mapping geometry; model has %s, feature has %s' % (model_type, gtype)
    206207 
    207208        ## Handling other fields  
     
    209210            # Making sure the model field is 
    210211            if not model_type in field_types: 
    211                 raise Exception, 'Django field type "%s" has no OGR mapping (yet).' % model_type 
     212                raise Exception('Django field type "%s" has no OGR mapping (yet).' % model_type) 
    212213 
    213214            # Otherwise, we've got an OGR Field.  Making sure that an 
     
    216217                fi = feat.index(ogr_field) 
    217218            except: 
    218                 raise Exception, 'Given mapping OGR field "%s" not in given OGR layer feature!' % ogr_field 
     219                raise Exception('Given mapping OGR field "%s" not in given OGR layer feature!' % ogr_field) 
    219220                     
    220221def check_layer(layer, fields, mapping): 
     
    235236        sr = layer.srs 
    236237    if not sr: 
    237         raise Exception, 'No source reference system defined.' 
     238        raise Exception('No source reference system defined.') 
    238239    else: 
    239240        return sr 
     
    281282        # Getting the GeometryColumn object. 
    282283        try: 
    283             geo_col = GeometryColumns.objects.get(f_table_name=self.model._meta.db_table) 
     284            db_table = self.model._meta.db_table 
     285            if SPATIAL_BACKEND == 'oracle': db_table = db_table.upper() 
     286            gc_kwargs = {GeometryColumns.table_name_col() : db_table} 
     287            geo_col = GeometryColumns.objects.get(**gc_kwargs) 
    284288        except: 
    285             raise Exception, 'Geometry column does not exist. (did you run syncdb?)' 
     289            raise Exception('Geometry column does not exist. (did you run syncdb?)') 
    286290         
    287291        # Getting the coordinate system needed for transformation (with CoordTransform)   
     
    293297            ct = CoordTransform(self.source_srs, target_srs) 
    294298        except Exception, msg: 
    295             raise Exception, 'Could not translate between the data source and model geometry: %s' % msg 
     299            raise Exception('Could not translate between the data source and model geometry: %s' % msg) 
    296300 
    297301        for feat in self.layer: 
  • django/branches/gis/django/db/backends/oracle/base.py

    r6394 r6524  
    446446 
    447447    def _format_params(self, params): 
     448        sz_kwargs = {} 
    448449        if isinstance(params, dict): 
    449450            result = {} 
     
    451452            for key, value in params.items(): 
    452453                result[smart_str(key, charset)] = smart_str(value, charset) 
    453             return result 
     454                if hasattr(value, 'oracle_type'): sz_kwargs[key] = value.oracle_type() 
    454455        else: 
    455             return tuple([smart_str(p, self.charset, True) for p in params]) 
     456            result = {} 
     457            for i in xrange(len(params)): 
     458                key = 'arg%d' % i 
     459                result[key] = smart_str(params[i], self.charset, True) 
     460                if hasattr(params[i], 'oracle_type'): sz_kwargs[key] = params[i].oracle_type() 
     461 
     462        # If any of the parameters had an `oracle_type` method, then we set 
     463        # the inputsizes for those parameters using the returned type 
     464        if sz_kwargs: self.setinputsizes(**sz_kwargs) 
     465        return result 
    456466 
    457467    def execute(self, query, params=None): 
     
    472482    def executemany(self, query, params=None): 
    473483        try: 
    474           args = [(':arg%d' % i) for i in range(len(params[0]))] 
     484            args = [(':arg%d' % i) for i in range(len(params[0]))] 
    475485        except (IndexError, TypeError): 
    476486          # No params given, nothing to do 
  • django/branches/gis/django/db/models/base.py

    r6394 r6524  
    229229            if cursor.fetchone(): 
    230230                db_values = [f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, False)) for f in non_pks] 
     231                placeholders = [f.get_placeholder(raw and getattr(self, f.attname) or f.pre_save(self, False)) for f in non_pks] 
    231232                if db_values: 
    232233                    cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \ 
    233234                        (qn(self._meta.db_table), 
    234                         ','.join(['%s=%%s' % qn(f.column) for f in non_pks]), 
     235                        ','.join(['%s=%s' % (qn(f.column), placeholders[i]) for i, f in enumerate(non_pks)]), 
    235236                        qn(self._meta.pk.column)), 
    236237                        db_values + self._meta.pk.get_db_prep_lookup('exact', pk_val))