/[thuban]/branches/WIP-pyshapelib-bramz/test/postgissupport.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/test/postgissupport.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1634 by bh, Fri Aug 22 16:55:19 2003 UTC revision 1662 by bh, Wed Aug 27 13:51:01 2003 UTC
# Line 229  class PostgreSQLServer: Line 229  class PostgreSQLServer:
229    
230      def get_default_static_data_db(self):      def get_default_static_data_db(self):
231          dbname = "PostGISStaticTests"          dbname = "PostGISStaticTests"
232          tables = [("landmarks", os.path.join("..", "Data", "iceland",          tables = [
233                                               "cultural_landmark-point.shp")),              # Direct copies of the shapefiles. The shapeids are exactly
234                    ("political", os.path.join("..", "Data", "iceland",              # the same.
235                ("landmarks", os.path.join("..", "Data", "iceland",
236                                           "cultural_landmark-point.shp"),
237                 [("gid_offset", 1000)]),
238                ("political", os.path.join("..", "Data", "iceland",
239                                               "political.shp")),                                               "political.shp")),
240                    ("roads", os.path.join("..", "Data", "iceland",              ("roads", os.path.join("..", "Data", "iceland",
241                                           "roads-line.shp"))]                                           "roads-line.shp")),
242    
243                # The polygon data as a MULTIPOLYGON geometry type
244                ("political_multi", os.path.join("..", "Data", "iceland",
245                                                 "political.shp"),
246                 [("force_wkt_type", "MULTIPOLYGON")]),
247                ]
248          return self.get_static_data_db(dbname, tables)          return self.get_static_data_db(dbname, tables)
249    
250      def connection_params(self, user):      def connection_params(self, user):
# Line 314  class PostGISDatabase: Line 324  class PostGISDatabase:
324      """A PostGIS database in a PostgreSQLServer"""      """A PostGIS database in a PostgreSQLServer"""
325    
326      def __init__(self, server, postgis_sql, dbname, tables = None):      def __init__(self, server, postgis_sql, dbname, tables = None):
327            """Initialize the PostGISDatabase
328    
329            Parameters:
330    
331                server -- The PostgreSQLServer instance containing the
332                    database
333    
334                postgis_sql -- Filename of the postgis.sql file with the
335                    postgis initialization code
336    
337                dbname -- The name of the database
338    
339                tables -- Optional description of tables to create in the
340                    new database. If given it should be a list of
341                    (tablename, shapefilename) pairs meaning that a table
342                    tablename will be created with the contents of the given
343                    shapefile or (tablename, shapefilename, extraargs)
344                    triples. The extraargs should be a list of key, value
345                    pairs to use as keyword arguments to upload_shapefile.
346            """
347          self.server = server          self.server = server
348          self.postgis_sql = postgis_sql          self.postgis_sql = postgis_sql
349          self.dbname = dbname          self.dbname = dbname
# Line 345  class PostGISDatabase: Line 375  class PostGISDatabase:
375                                  "GRANT SELECT ON geometry_columns TO PUBLIC;")                                  "GRANT SELECT ON geometry_columns TO PUBLIC;")
376    
377          if self.tables is not None:          if self.tables is not None:
378              for tablename, shapefile in self.tables:              def unpack(item):
379                  upload_shapefile(shapefile, self, tablename)                  extra = {"force_wkt_type": None, "gid_offset": 0}
380                    if len(info) == 2:
381                        tablename, shapefile = info
382                    else:
383                        tablename, shapefile, kw = info
384                        for key, val in kw:
385                            extra[key] = val
386                    return tablename, shapefile, extra
387    
388                for info in self.tables:
389                    tablename, shapefile, kw = unpack(info)
390                    upload_shapefile(shapefile, self, tablename, **kw)
391    
392      def has_data(self, tables):      def has_data(self, tables):
393          return self.tables == tables          return self.tables == tables
# Line 440  def skip_if_no_postgis(): Line 481  def skip_if_no_postgis():
481      if _cannot_run_postgis_tests:      if _cannot_run_postgis_tests:
482          raise support.SkipTest(_cannot_run_postgis_tests)          raise support.SkipTest(_cannot_run_postgis_tests)
483    
484  def point_to_wkt(coords):  def coords_to_point(coords):
485      """Return string with a WKT representation of the point in coords"""      """Return string with a WKT representation of the point in coords"""
486      x, y = coords[0]      x, y = coords[0]
487      return "POINT(%r %r)" % (x, y)      return "POINT(%r %r)" % (x, y)
488    
489  def polygon_to_wkt(coords):  def coords_to_polygon(coords):
490      """Return string with a WKT representation of the polygon in coords"""      """Return string with a WKT representation of the polygon in coords"""
491      poly = []      poly = []
492      for ring in coords:      for ring in coords:
493          poly.append(", ".join(["%r %r" % p for p in ring]))          poly.append(", ".join(["%r %r" % p for p in ring]))
494      return "POLYGON((%s))" % "), (".join(poly)      return "POLYGON((%s))" % "), (".join(poly)
495    
496  def arc_to_wkt(coords):  def coords_to_multilinestring(coords):
497      """Return string with a WKT representation of the arc in coords"""      """Return string with a WKT representation of the arc in coords"""
498      poly = []      poly = []
499      for ring in coords:      for ring in coords:
500          poly.append(", ".join(["%r %r" % p for p in ring]))          poly.append(", ".join(["%r %r" % p for p in ring]))
501      return "MULTILINESTRING((%s))" % "), (".join(poly)      return "MULTILINESTRING((%s))" % "), (".join(poly)
502    
503  def upload_shapefile(filename, db, tablename):  def coords_to_multipolygon(coords):
504        """Return string with a WKT representation of the polygon in coords"""
505        poly = []
506        for ring in coords:
507            poly.append(", ".join(["%r %r" % p for p in ring]))
508        return "MULTIPOLYGON(((%s)))" % ")), ((".join(poly)
509    
510    wkt_converter = {
511        "POINT": coords_to_point,
512        "MULTILINESTRING": coords_to_multilinestring,
513        "POLYGON": coords_to_polygon,
514        "MULTIPOLYGON": coords_to_multipolygon,
515        }
516    
517    def upload_shapefile(filename, db, tablename, force_wkt_type = None,
518                         gid_offset = 0):
519        """Upload a shapefile into a new database table
520    
521        Parameters:
522    
523        filename -- The name of the shapefile
524    
525        db -- The PostGISDatabase instance representing the database
526    
527        tablename -- The name of the table to create and into which the data
528                    is to be inserted
529    
530        force_wkt_type -- If given the real WKT geometry type to use instead
531                    of the default that would be chosen based on the type of
532                    the shapefile
533    
534        gid_offset -- A number to add to the shapeid to get the value for
535                    the gid column (default 0)
536        """
537      import dbflib, shapelib      import dbflib, shapelib
538    
539        # We build this map here because we need shapelib which can only be
540        # imported after support.initthuban has been called which we can't
541        # easily do in this module because it's imported by support.
542        shp_to_wkt = {
543            shapelib.SHPT_POINT: "POINT",
544            shapelib.SHPT_ARC: "MULTILINESTRING",
545            shapelib.SHPT_POLYGON: "POLYGON",
546            }
547    
548      server = db.server      server = db.server
549      dbname = db.dbname      dbname = db.dbname
550      conn = psycopg.connect("dbname=%s " % dbname      conn = psycopg.connect("dbname=%s " % dbname
# Line 486  def upload_shapefile(filename, db, table Line 569  def upload_shapefile(filename, db, table
569      #print stmt      #print stmt
570    
571      numshapes, shapetype, mins, maxs = shp.info()      numshapes, shapetype, mins, maxs = shp.info()
572      if shapetype == shapelib.SHPT_POINT:      wkttype =  shp_to_wkt[shapetype]
573          convert = point_to_wkt      if force_wkt_type:
574          wkttype = "POINT"          wkttype = force_wkt_type
575      elif shapetype == shapelib.SHPT_POLYGON:      convert = wkt_converter[wkttype]
         convert = polygon_to_wkt  
         wkttype = "POLYGON"  
     elif shapetype == shapelib.SHPT_ARC:  
         convert = arc_to_wkt  
         wkttype = "MULTILINESTRING"  
     else:  
         raise ValueError("Unsupported Shapetype %r" % shapetype)  
576    
577      cursor.execute("select AddGeometryColumn('%(dbname)s',"      cursor.execute("select AddGeometryColumn('%(dbname)s',"
578                     "'%(tablename)s', 'the_geom', '-1', '%(wkttype)s', 2);"                     "'%(tablename)s', 'the_geom', '-1', '%(wkttype)s', 2);"
# Line 510  def upload_shapefile(filename, db, table Line 586  def upload_shapefile(filename, db, table
586      for i in range(numshapes):      for i in range(numshapes):
587          data = dbf.read_record(i)          data = dbf.read_record(i)
588          data["tablename"] = tablename          data["tablename"] = tablename
589          data["gid"] = i          data["gid"] = i + gid_offset
590          data["the_geom"] = convert(shp.read_object(i).vertices())          data["the_geom"] = convert(shp.read_object(i).vertices())
591          #print insert % data          #print insert % data
592          cursor.execute(insert, data)          cursor.execute(insert, data)

Legend:
Removed from v.1634  
changed lines
  Added in v.1662

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26