Django

Code

Changeset 6439

Show
Ignore:
Timestamp:
09/29/07 23:19:31 (1 year ago)
Author:
jbronn
Message:

gis: PostGIS backend improvements: test spatial databases may now be created on NT platforms; changed exception style.

Files:

Legend:

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

    r6026 r6439  
    99       the GeoQuerySet. 
    1010       
    11   Currently only PostGIS is supported, but someday backends will be aded for 
    12    additional spatial databases
     11  Currently only PostGIS is supported, but someday backends will be added for 
     12   additional spatial databases (e.g., Oracle, DB2)
    1313""" 
    1414from django.conf import settings 
     
    2121    # PostGIS is the spatial database, getting the rquired modules, renaming as necessary. 
    2222    from django.contrib.gis.db.backend.postgis import \ 
    23         PostGISField as GeoBackendField,
    24         POSTGIS_TERMS as GIS_TERMS, \ 
    25         create_spatial_db, geo_quotename, get_geo_where_clause 
     23        PostGISField as GeoBackendField, POSTGIS_TERMS as GIS_TERMS,
     24        create_spatial_db, geo_quotename, get_geo_where_clause, \ 
     25        ASGML, ASKML, UNION 
    2626else: 
    27     raise NotImplementedError, 'No Geographic Backend exists for %s' % settings.DATABASE_NAME 
     27    raise NotImplementedError('No Geographic Backend exists for %s' % settings.DATABASE_NAME) 
    2828 
    2929####    query.py overloaded functions    #### 
  • django/branches/gis/django/contrib/gis/db/backend/postgis/creation.py

    r6427 r6439  
    33from django.db import connection 
    44from django.test.utils import _set_autocommit, TEST_DATABASE_PREFIX 
    5 from commands import getstatusoutput 
    65import os, re, sys 
     6 
     7def getstatusoutput(cmd): 
     8    "A simpler version of getstatusoutput that works on win32 platforms." 
     9    stdin, stdout, stderr = os.popen3(cmd) 
     10    output = stdout.read() 
     11    if output.endswith('\n'): output = output[:-1] 
     12    status = stdin.close() 
     13    return status, output 
    714 
    815def create_lang(db_name, verbosity=1): 
     
    2128 
    2229    # Checking the status of the command, 0 => execution successful 
    23     if status != 0
    24         raise Exception, "Error executing 'plpgsql' command: %s\n" % output 
     30    if status
     31        raise Exception("Error executing 'plpgsql' command: %s\n" % output) 
    2532 
    2633def _create_with_cursor(db_name, verbosity=1, autoclobber=False): 
     
    4956            cursor.execute(create_sql) 
    5057        else: 
    51             raise Exception, 'Spatial Database Creation canceled.' 
     58            raise Exception('Spatial Database Creation canceled.') 
    5259     
    5360created_regex = re.compile(r'^createdb: database creation failed: ERROR:  database ".+" already exists') 
     
    6673    # Attempting to create the database. 
    6774    status, output = getstatusoutput(create_cmd) 
    68     if status != 0: 
     75 
     76    if status: 
    6977        if created_regex.match(output): 
    7078            if not autoclobber: 
     
    7583                status, output = getstatusoutput(drop_cmd) 
    7684                if status != 0:  
    77                     raise Exception, 'Could not drop database %s: %s' % (db_name, output
     85                    raise Exception('Could not drop database %s: %s' % (db_name, output)
    7886                if verbosity >= 1: print 'Creating new spatial database...' 
    7987                status, output = getstatusoutput(create_cmd) 
    8088                if status != 0: 
    81                     raise Exception, 'Could not create database after dropping: %s' % output 
     89                    raise Exception('Could not create database after dropping: %s' % output) 
    8290            else: 
    83                 raise Exception, 'Spatial Database Creation canceled.' 
     91                raise Exception('Spatial Database Creation canceled.') 
    8492        else: 
    85             raise Exception, 'Unknown error occurred in creating database: %s' % output 
     93            raise Exception('Unknown error occurred in creating database: %s' % output) 
    8694 
    8795def create_spatial_db(test=False, verbosity=1, autoclobber=False, interactive=False): 
     
    9098    # Making sure we're using PostgreSQL and psycopg2 
    9199    if settings.DATABASE_ENGINE != 'postgresql_psycopg2': 
    92         raise Exception, 'Spatial database creation only supported postgresql_psycopg2 platform.' 
    93  
    94     # This routine depends on getstatusoutput(), which does not work on Windows. 
    95     # TODO: Consider executing shell commands with popen for Windows compatibility 
    96     if os.name == 'nt': 
    97         raise Exception, 'Automatic spatial database creation only supported on *NIX platforms.' 
     100        raise Exception('Spatial database creation only supported postgresql_psycopg2 platform.') 
    98101 
    99102    # Getting the spatial database name 
     
    105108        _create_with_shell(db_name, verbosity=verbosity, autoclobber=autoclobber) 
    106109 
    107     # Creating the db language. 
    108     create_lang(db_name, verbosity=verbosity) 
     110    # Creating the db language, does not need to be done on NT platforms 
     111    #  since the PostGIS installer enables this capability. 
     112    if os.name != 'nt': 
     113        create_lang(db_name, verbosity=verbosity) 
    109114 
    110115    # Now adding in the PostGIS routines. 
     
    119124    # Syncing the database 
    120125    call_command('syncdb', verbosity=verbosity, interactive=interactive) 
    121  
    122     # Get a cursor (even though we don't need one yet). This has 
    123     # the side effect of initializing the test database. 
    124     cursor = connection.cursor() 
    125126     
    126127def drop_db(db_name=False, test=False): 
    127128    """ 
    128     Drops the given database (defaults to what is returned from get_spatial_db(). 
    129      All exceptions are propagated up to the caller. 
     129    Drops the given database (defaults to what is returned from 
     130     get_spatial_db()). All exceptions are propagated up to the caller. 
    130131    """ 
    131132    if not db_name: db_name = get_spatial_db(test=test) 
    132133    cursor = connection.cursor() 
    133     cursor.execute("DROP DATABASE %s" % connection.ops.quote_name(db_name)) 
     134    cursor.execute('DROP DATABASE %s' % connection.ops.quote_name(db_name)) 
    134135 
    135136def get_cmd_options(db_name): 
     
    160161    else: 
    161162        if not settings.DATABASE_NAME: 
    162             raise Exception, 'must configure DATABASE_NAME in settings.py' 
     163            raise Exception('must configure DATABASE_NAME in settings.py') 
    163164        return settings.DATABASE_NAME 
    164165 
     
    172173    try: 
    173174        # POSTGIS_SQL_PATH may be placed in settings to tell GeoDjango where the  
    174         #   PostGIS SQL files are located 
     175        #  PostGIS SQL files are located.  This is especially useful on Win32 
     176        #  platforms since the output of pg_config looks like "C:/PROGRA~1/..". 
    175177        sql_path = settings.POSTGIS_SQL_PATH 
    176178    except AttributeError: 
    177179        status, sql_path = getstatusoutput('pg_config --sharedir') 
    178         if status != 0
     180        if status
    179181            sql_path = '/usr/local/share' 
    180182 
    181183    # The PostGIS SQL post-creation files. 
    182184    lwpostgis_file = os.path.join(sql_path, 'lwpostgis.sql') 
    183     srefsys_file   = os.path.join(sql_path, 'spatial_ref_sys.sql') 
     185    srefsys_file = os.path.join(sql_path, 'spatial_ref_sys.sql') 
    184186    if not os.path.isfile(lwpostgis_file): 
    185         raise Exception, 'Could not find PostGIS function definitions in %s' % lwpostgis_file 
     187        raise Exception('Could not find PostGIS function definitions in %s' % lwpostgis_file) 
    186188    if not os.path.isfile(srefsys_file): 
    187         raise Exception, 'Could not find PostGIS spatial reference system definitions in %s' % srefsys_file 
    188  
    189     # Getting the psql command-line options
     189        raise Exception('Could not find PostGIS spatial reference system definitions in %s' % srefsys_file) 
     190 
     191    # Getting the psql command-line options, and command format
    190192    options = get_cmd_options(db_name) 
     193    cmd_fmt = 'psql %s-f "%%s"' % options 
    191194     
    192195    # Now trying to load up the PostGIS functions 
    193     cmd = 'psql %s-f %s' % (options, lwpostgis_file) 
     196    cmd = cmd_fmt % lwpostgis_file 
    194197    if verbosity >= 1: print cmd 
    195198    status, output = getstatusoutput(cmd) 
    196     if status != 0
    197         raise Exception, 'Error in loading PostGIS lwgeometry routines.' 
     199    if status
     200        raise Exception('Error in loading PostGIS lwgeometry routines.') 
    198201 
    199202    # Now trying to load up the Spatial Reference System table 
    200     cmd = 'psql %s-f %s' % (options, srefsys_file) 
     203    cmd = cmd_fmt % srefsys_file 
    201204    if verbosity >= 1: print cmd 
    202205    status, output = getstatusoutput(cmd) 
    203     if status !=0: 
    204         raise Exception, 'Error in loading PostGIS spatial_ref_sys table.' 
    205      
     206    if status: 
     207        raise Exception('Error in loading PostGIS spatial_ref_sys table.') 
     208 
     209    # Setting the permissions because on Windows platforms the owner 
     210    #  of the spatial_ref_sys and geometry_columns tables is always 
     211    #  the postgres user, regardless of how the db is created. 
     212    if os.name == 'nt': set_permissions(db_name)  
     213     
     214def set_permissions(db_name): 
     215    """ 
     216    Sets the permissions on the given database to that of the user specified 
     217     in the settings.  Needed specifically for PostGIS on Win32 platforms. 
     218    """ 
     219    cursor = connection.cursor() 
     220    user = settings.DATABASE_USER 
     221    cursor.execute('ALTER TABLE geometry_columns OWNER TO %s' % user) 
     222    cursor.execute('ALTER TABLE spatial_ref_sys OWNER TO %s' % user) 
  • django/branches/gis/django/contrib/gis/db/backend/postgis/field.py

    r5881 r6439  
    66class PostGISField(Field): 
    77    def _add_geom(self, style, db_table): 
    8         """Constructs the addition of the geometry to the table using the 
     8        """ 
     9        Constructs the addition of the geometry to the table using the 
    910        AddGeometryColumn(...) PostGIS (and OGC standard) stored procedure. 
    1011 
     
    99100            return value 
    100101        else: 
    101             return ("SRID=%d;%s" % (self._srid, wkt)
     102            raise TypeError('Geometry Proxy should only return GEOSGeometry objects.'
    102103 
    103104    def get_placeholder(self, value): 
    104         "Provides a proper substitution value for " 
     105        """ 
     106        Provides a proper substitution value for Geometries that are not in the 
     107         SRID of the field.  Specifically, this routine will substitute in the 
     108         ST_Transform() function call. 
     109        """ 
    105110        if isinstance(value, GEOSGeometry) and value.srid != self._srid: 
    106111            # Adding Transform() to the SQL placeholder. 
  • django/branches/gis/django/contrib/gis/db/backend/postgis/__init__.py

    r6427 r6439  
    99from django.contrib.gis.db.backend.postgis.field import PostGISField 
    1010 
    11 # Whether PostGIS has AsKML() support
     11# Functions used by GeoManager methods, and not via lookup types
    1212if MAJOR_VERSION == 1: 
    13     # AsKML() only supported in versions 1.2.1+ 
    1413    if MINOR_VERSION1 == 3: 
    1514        ASKML = 'ST_AsKML' 
     15        ASGML = 'ST_AsGML' 
     16        UNION = 'ST_Union' 
    1617    elif MINOR_VERSION1 == 2 and MINOR_VERSION2 >= 1: 
    1718        ASKML = 'AsKML' 
     19        ASGML = 'AsGML' 
     20        UNION = 'GeomUnion' 
     21         
     22 
    1823     
  • django/branches/gis/django/contrib/gis/db/backend/postgis/management.py

    r5881 r6439  
    11""" 
    2   This utility module is for obtaining information about the PostGIS installation. 
     2  This utility module is for obtaining information about the PostGIS 
     3   installation. 
    34 
    45  See PostGIS docs at Ch. 6.2.1 for more information on these functions. 
     
    4950        minor2 = int(m.group('minor2')) 
    5051    else: 
    51         raise Exception, 'Could not parse PostGIS version string: %s' % version 
     52        raise Exception('Could not parse PostGIS version string: %s' % version) 
    5253 
    5354    return (version, major, minor1, minor2) 
    54  
    55  
    56      
  • django/branches/gis/django/contrib/gis/db/backend/postgis/query.py

    r6018 r6439  
    1515#        Versions <= 1.0.x do not use GEOS C API, and will not be supported. 
    1616if MAJOR_VERSION != 1 or (MAJOR_VERSION == 1 and MINOR_VERSION1 < 1): 
    17     raise Exception, 'PostGIS version %s not supported.' % POSTGIS_VERSION 
     17    raise Exception('PostGIS version %s not supported.' % POSTGIS_VERSION) 
    1818 
    1919# PostGIS-specific operators. The commented descriptions of these 
     
    146146            # Ensuring that a tuple _value_ was passed in from the user 
    147147            if not isinstance(value, tuple) or len(value) != 2:  
    148                 raise TypeError, '2-element tuple required for %s lookup type.' % lookup_type 
     148                raise TypeError('2-element tuple required for %s lookup type.' % lookup_type) 
    149149             
    150150            # Ensuring the argument type matches what we expect. 
    151151            if not isinstance(value[1], arg_type): 
    152                 raise TypeError, 'Argument type should be %s, got %s instead.' % (arg_type, type(value[1])) 
     152                raise TypeError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) 
    153153             
    154154            return "%s(%s%s, %%s, %%s)" % (func, table_prefix, field_name) 
     
    162162        return "%s%s IS %sNULL" % (table_prefix, field_name, (not value and 'NOT ' or '')) 
    163163 
    164     raise TypeError, "Got invalid lookup_type: %s" % repr(lookup_type
     164    raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)
    165165 
    166166def geo_quotename(value, dbl=False):