[GRASS-SVN] r33602 - in grass/trunk: lib/python scripts/db.dropcol scripts/db.droptable scripts/db.in.ogr scripts/i.image.mosaic scripts/i.landsat.rgb scripts/r.in.aster scripts/v.db.addcol scripts/v.db.addtable scripts/v.db.dropcol scripts/v.db.droptable scripts/v.db.join scripts/v.db.reconnect.all scripts/v.db.renamecol scripts/v.db.update scripts/v.dissolve scripts/v.in.e00 scripts/v.in.geonames scripts/v.in.gns scripts/v.rast.stats scripts/v.report

svn_grass at osgeo.org svn_grass at osgeo.org
Mon Sep 29 19:46:48 EDT 2008


Author: glynn
Date: 2008-09-29 19:46:48 -0400 (Mon, 29 Sep 2008)
New Revision: 33602

Added:
   grass/trunk/scripts/v.db.addtable/v.db.addtable.py
Modified:
   grass/trunk/lib/python/grass.py
   grass/trunk/scripts/db.dropcol/db.dropcol.py
   grass/trunk/scripts/db.droptable/db.droptable.py
   grass/trunk/scripts/db.in.ogr/db.in.ogr.py
   grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py
   grass/trunk/scripts/i.landsat.rgb/i.landsat.rgb.py
   grass/trunk/scripts/r.in.aster/r.in.aster.py
   grass/trunk/scripts/v.db.addcol/v.db.addcol.py
   grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py
   grass/trunk/scripts/v.db.droptable/v.db.droptable.py
   grass/trunk/scripts/v.db.join/v.db.join.py
   grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py
   grass/trunk/scripts/v.db.renamecol/v.db.renamecol.py
   grass/trunk/scripts/v.db.update/v.db.update.py
   grass/trunk/scripts/v.dissolve/v.dissolve.py
   grass/trunk/scripts/v.in.e00/v.in.e00.py
   grass/trunk/scripts/v.in.geonames/v.in.geonames.py
   grass/trunk/scripts/v.in.gns/v.in.gns.py
   grass/trunk/scripts/v.rast.stats/v.rast.stats.py
   grass/trunk/scripts/v.report/v.report.py
Log:
Convert v.db.addtable to Python
Add, use several utility wrappers:
 vector_db (v.db.connect -g)
 db_describe (db.describe -c)
 db_connection (db.connect -p)
 vector_columns (v.info -c)
 vector_history (v.support cmdhist=)
 raster_history (r.support history=)


Modified: grass/trunk/lib/python/grass.py
===================================================================
--- grass/trunk/lib/python/grass.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/lib/python/grass.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -273,6 +273,15 @@
     owstr = 'GRASS_OVERWRITE'
     return owstr in os.environ and os.environ[owstr] != '0'
 
+# check GRASS_VERBOSE
+
+def verbosity():
+    vbstr = 'GRASS_VERBOSE'
+    if vbstr:
+	return int(vbstr)
+    else:
+	return 0
+
 ## various utilities, not specific to GRASS
 
 # basename inc. extension stripping
@@ -314,3 +323,67 @@
     except:
 	pass
 
+# run "v.db.connect -g ..." and parse output
+
+def vector_db(map, layer = None, **args):
+    s = read_command('v.db.connect', flags = 'g', map = map, layer = layer, **args)
+    result = []
+    for l in s.splitlines():
+	f = l.split(' ')
+	if len(f) != 5:
+	    continue
+	if layer and int(layer) == int(f[0]):
+	    return f
+	result.append(f)
+    if not layer:
+	return result
+
+# run "db.describe -c ..." and parse output
+
+def db_describe(table, **args):
+    s = read_command('db.describe', flags = 'c', table = table, **args)
+    if not s:
+	return None
+    cols = []
+    result = {}
+    for l in s.splitlines():
+	f = l.split(':')
+	key = f[0]
+	f[1] = f[1].lstrip(' ')
+	if key.startswith('Column '):
+	    n = int(key.split(' ')[1])
+	    cols.insert(n, f[1:])
+	elif key in ['ncols', 'nrows']:
+	    result[key] = int(f[1])
+	else:
+	    result[key] = f[1:]
+    result['cols'] = cols
+    return result
+
+# run "db.connect -p" and parse output
+
+def db_connection():
+    s = read_command('db.connect', flags = 'p')
+    return parse_key_val(s, sep = ':')
+
+# run "v.info -c ..." and parse output
+
+def vector_columns(map, layer = None, **args):
+    s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
+    result = []
+    for line in s.splitlines():
+	f = line.split('|')
+	if len(f) == 2:
+	    result.append(f)
+    return result
+
+# add vector history
+
+def vector_history(map):
+    run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+
+# add raster history
+
+def raster_history(map):
+    run_command('r.support', map = map, history = os.environ['CMDLINE'])
+

Modified: grass/trunk/scripts/db.dropcol/db.dropcol.py
===================================================================
--- grass/trunk/scripts/db.dropcol/db.dropcol.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/db.dropcol/db.dropcol.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -57,8 +57,7 @@
     # check if DB parameters are set, and if not set them.
     grass.run_command('db.connect', flags = 'c')
 
-    s = grass.read_command('db.connect', flags = 'p')
-    kv = grass.parse_key_val(s, sep = ':')
+    kv = grass.db_connection()
     database = kv['database']
     driver = kv['driver']
     # schema needed for PG?
@@ -69,8 +68,7 @@
     if column == "cat":
 	grass.warning("Deleting <%s> column which may be needed to keep table connected to a vector map" % column)
 
-    s = grass.read_command('db.describe', flags = 'c', table = table)
-    cols = [l.split(':')[1].lstrip() for l in s.splitlines() if l.startswith('Column ')]
+    cols = [f[0] for f in grass.db_describe()['cols']]
     if column not in cols:
 	grass.fatal("Column <%s> not found in table" % column)
 
@@ -85,16 +83,11 @@
 	# http://www.sqlite.org/faq.html#q13
 	colnames = []
 	coltypes = []
-	s = grass.read_command('db.describe', flags = 'c', table = table)
-	for l in s.splitlines():
-	    if not l.startswith('Column '):
+	for f in grass.db_describe()['cols']:
+	    if f[0] == column:
 		continue
-	    f = l.split(':')
-	    f[1] = f[1].lstrip()
-	    if f[1] == column:
-		continue
-	    colnames.append(f[1])
-	    coltypes.append("%s %s" % (f[1], f[2]))
+	    colnames.append(f[0])
+	    coltypes.append("%s %s" % (f[0], f[1]))
 
 	colnames = ", ".join(colnames)
 	coltypes = ", ".join(coltypes)

Modified: grass/trunk/scripts/db.droptable/db.droptable.py
===================================================================
--- grass/trunk/scripts/db.droptable/db.droptable.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/db.droptable/db.droptable.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -45,8 +45,7 @@
     # check if DB parameters are set, and if not set them.
     grass.run_command('db.connect', flags = 'c')
 
-    s = grass.read_command('db.connect', flags = 'p')
-    kv = grass.parse_key_val(s, sep = ':')
+    kv = grass.db_connection()
     database = kv['database']
     driver = kv['driver']
     # schema needed for PG?
@@ -56,19 +55,16 @@
 
     # check if table exists
     nuldev = file(os.devnull, 'w')
-    if grass.run_command('db.describe', flags = 'c', table = table,
-			 stdout = nuldev, stderr = nuldev):
+    if not grass.db_describe(table, stdout = nuldev, stderr = nuldev):
 	grass.fatal("Table <%s> not found in current mapset" % table)
 
     # check if table is used somewhere (connected to vector map)
     used = []
     vects = grass.list_strings('vect')
     for vect in vects:
-	s = grass.read_command('v.db.connect', flags = 'g', map = vect, stderr = nuldev)
-	if not s:
-	    continue
-	for l in s.splitlines():
-	    f = l.split()
+	for f in vector_db(vect, stderr = nuldev):
+	    if not f:
+		continue
 	    if f[1] == table:
 		used.append(vect)
 		break

Modified: grass/trunk/scripts/db.in.ogr/db.in.ogr.py
===================================================================
--- grass/trunk/scripts/db.in.ogr/db.in.ogr.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/db.in.ogr/db.in.ogr.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -111,9 +111,7 @@
     grass.run_command('db.dropcol', quiet = True, flags = 'f', table = output,
 		      colum = 'cat', stdout = nuldev, stderr = nuldev)
 
-    s = grass.read_command('db.describe', flags = 'c', table = output)
-    kv = grass.parse_key_val(s, sep = ':')
-    records = int(kv['nrows'].strip())
+    records = grass.db_describe(output)['nrows']
     grass.message("Imported table <%s> with %d rows" % (output, records))
 
 if __name__ == "__main__":

Modified: grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py
===================================================================
--- grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -108,7 +108,7 @@
     grass.message("Ready. File %s created." % output)
 
     # write cmd history:
-    grass.run_command('r.support', map = output, history = os.environ['CMDLINE'])
+    raster_history(output)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/i.landsat.rgb/i.landsat.rgb.py
===================================================================
--- grass/trunk/scripts/i.landsat.rgb/i.landsat.rgb.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/i.landsat.rgb/i.landsat.rgb.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -132,7 +132,7 @@
 
     # write cmd history:
     for i in [red, green, blue]:
-	grass.run_command('r.support', map = i, history = os.environ['CMDLINE'])
+	raster_history(i)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/r.in.aster/r.in.aster.py
===================================================================
--- grass/trunk/scripts/r.in.aster/r.in.aster.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/r.in.aster/r.in.aster.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -172,8 +172,7 @@
     grass.run_command("r.in.gdal", overwrite = flags['o'], input = tempfile, output = outfile)
 
     # write cmd history
-    grass.run_command('r.support', map = outfile, history = os.environ['CMDLINE'])
-    #r.support "$GIS_OPT_OUTPUT" history="${CMDLINE}"
+    raster_history(outfile)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.db.addcol/v.db.addcol.py
===================================================================
--- grass/trunk/scripts/v.db.addcol/v.db.addcol.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.addcol/v.db.addcol.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -62,10 +62,9 @@
     if not exists:
 	grass.fatal("Vector map <%s> not found in current mapset" % map)
 
-    s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer)
-    if not s:
+    f = grass.vector_db(map, layer)
+    if not f:
 	grass.fatal("There is no table connected to this map. Run v.db.connect or v.db.addtable first.")
-    f = s.split()
     table = f[1]
     database = f[3]
     driver = f[4]
@@ -83,7 +82,7 @@
 	    grass.fatal("Unable to add column <%s>." % col)
 
     # write cmd history:
-    grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(map)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Added: grass/trunk/scripts/v.db.addtable/v.db.addtable.py
===================================================================
--- grass/trunk/scripts/v.db.addtable/v.db.addtable.py	                        (rev 0)
+++ grass/trunk/scripts/v.db.addtable/v.db.addtable.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -0,0 +1,152 @@
+#!/usr/bin/env python
+#
+############################################################################
+#
+# MODULE:       v.db.addtable
+# AUTHOR(S):   	Markus Neteler 
+#               Converted to Python by Glynn Clements
+# PURPOSE:      interface to db.execute to creates and add a new table to given vector map
+# COPYRIGHT:    (C) 2005, 2007, 2008  by Markus Neteler & the GRASS Development Team
+#
+#               This program is free software under the GNU General Public
+#               License (>=v2). Read the file COPYING that comes with GRASS
+#               for details.
+#
+#############################################################################
+
+#%Module
+#%  description: Creates and adds a new attribute table to a given layer of an existing vector map.
+#%  keywords: vector, database, attribute table
+#%End
+#%option
+#% key: map
+#% type: string
+#% gisprompt: old,vector,vector
+#% description: Vector map for which to add new attribute table
+#% required : yes
+#% key_desc : name
+#%end
+#%option
+#% key: table
+#% type: string
+#% description: Name of new attribute table (default: vector map name)
+#% required : no
+#%end
+#%option
+#% key: layer
+#% type: integer
+#% description: Layer where to add new attribute table
+#% answer: 1
+#% required : no
+#%end
+#%option
+#% key: columns
+#% type: string
+#% description: Name and type of the new column(s) (types depend on database backend, but all support VARCHAR(), INT, DOUBLE PRECISION and DATE)
+#% answer: cat integer
+#% required : no
+#% multiple : yes
+#% key_desc : name type
+#%end
+
+import sys
+import os
+import grass
+
+def main():
+    map = options['map']
+    table = options['table']
+    layer = options['layer']
+    columns = options['columns']
+
+    mapset = grass.gisenv()['MAPSET']
+
+    # does map exist in CURRENT mapset?
+    if not grass.find_file(map, element = 'vector', mapset = mapset)['file']:
+	grass.fatal("Vector map <%s> not found in current mapset" % map)
+
+    map_name = map.split('@')[0]
+
+    if not table:
+	if layer == '1':
+	    grass.message("Using vector map name as table name: " + map_name)
+	    table = map_name
+	else:
+	    # to avoid tables with identical names on higher layers
+	    grass.message("Using vector map name extended by layer number as table name: %s_%s" % (map_name, layer))
+	    table = "%s_%s" % (map_name, layer)
+    else:
+	grass.message("Using user specified table name: " + table)
+
+    # check if DB parameters are set, and if not set them.
+    grass.run_command('db.connect', flags = 'c')
+
+    #check if anything is connected:
+    nuldev = file(os.devnull, 'w')
+    db = grass.vector_db(map, stderr = nuldev)
+    if db:
+	f = db[0]
+	database = f[3]
+	driver = f[4]
+    else:
+	# nothing defined
+	grass.message("Creating new DB connection based on default mapset settings...")
+	kv = grass.db_connection()
+	database = kv['database']
+	driver = kv['driver']
+
+    # maybe there is already a table linked to the selected layer?
+    if grass.vector_db(map, layer, stderr = nuldev):
+	grass.fatal("There is already a table linked to layer <%s>" % layer)
+
+    # maybe there is already a table with that name?
+    found = False
+    p = grass.pipe_command('db.tables', database = database, driver = driver, stderr = nuldev)
+    for line in p.stdout:
+	if line.rstrip('\r\n') == table:
+	    found = True
+	    break
+    p.wait()
+
+    if not found:
+	column_def = [col.strip().lower() for col in columns.split(',')]
+
+	#if not existing, create it:
+	if "cat integer" not in column_def:
+	    column_def.append("cat integer")
+	column_def = ','.join(column_def)
+
+	grass.message("Creating table with columns (%s)" % column_def)
+
+	# take care if the DBF directory is missing (heck, the DBF driver should take care!)
+	if driver == "dbf":
+	    env = grass.gisenv()
+	    path = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], "dbf")
+	    if not os.path.isdir(path):
+		grass.message("Creating missing DBF directory in mapset <%s>" % env['MAPSET'])
+		os.mkdir(path)
+		grass.run_command('db.connect', driver = dbf, database = '$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/')
+
+    sql = "CREATE TABLE %s (%s)" % (table, column_def)
+
+    if grass.write_command('db.execute', database = database, driver = driver, stdin = sql) != 0:
+	grass.fatal("Cannot continue.")
+
+    # connect the map to the DB:
+    grass.run_command('v.db.connect', map = map, database = database, driver = driver,
+		      layer = layer, table = table, key = 'cat')
+
+    # finally we have to add cats into the attribute DB to make modules such as v.what.rast happy:
+    # (creates new row for each vector line):
+    grass.run_command('v.to.db', map = map, layer = layer, option = 'cat', col = 'cat')
+
+    if grass.verbosity() > 0:
+	grass.message("Current attribute table links:")
+	grass.run_command('v.db.connect', flags = 'p', map = map)
+
+    # write cmd history:
+    grass.vector_history(map)
+
+if __name__ == "__main__":
+    options, flags = grass.parser()
+    main()


Property changes on: grass/trunk/scripts/v.db.addtable/v.db.addtable.py
___________________________________________________________________
Name: svn:executable
   + *

Modified: grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py
===================================================================
--- grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -63,10 +63,9 @@
     if not grass.find_file(map, element = 'vector', mapset = mapset):
 	grass.fatal("Vector map <%s> not found in current mapset" % map)
 
-    s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer);
-    if not s:
+    f = grass.vector_db(map, layer)
+    if not f:
 	grass.fatal("An error occured while running v.db.connect")
-    f = s.split()
     table = f[1]
     keycol = f[2]
     database = f[3]
@@ -78,8 +77,7 @@
     if column == keycol:
 	grass.fatal("Cannot delete <$col> column as it is needed to keep table <%s> connected to the input vector map <%s>" % (table, map))
 
-    s = grass.read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True)
-    if column not in [l.split('|')[1].lstrip() for l in s.splitlines()]:
+    if column not in [f[1] for f in grass.vector_columns(map, layer)]:
 	grass.fatal("Column <%s> not found in table <%s>" % (column, table))
 
     if driver == "sqlite":
@@ -87,16 +85,11 @@
 	# http://www.sqlite.org/faq.html#q13
 	colnames = []
 	coltypes = []
-	s = grass.read_command('db.describe', flags = 'c', table = table)
-	for l in s.splitlines():
-	    if not l.startswith('Column '):
+	for f in grass.db_describe(table):
+	    if f[0] == column:
 		continue
-	    f = l.split(':')
-	    f[1] = f[1].lstrip()
-	    if f[1] == column:
-		continue
-	    colnames.append(f[1])
-	    coltypes.append("%s %s" % (f[1], f[2]))
+	    colnames.append(f[0])
+	    coltypes.append("%s %s" % (f[0], f[1]))
 
 	colnames = ", ".join(colnames)
 	coltypes = ", ".join(coltypes)
@@ -121,7 +114,7 @@
 	grass.fatal("Cannot continue (problem deleting column).")
 
     # write cmd history:
-    grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(map)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.db.droptable/v.db.droptable.py
===================================================================
--- grass/trunk/scripts/v.db.droptable/v.db.droptable.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.droptable/v.db.droptable.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -55,10 +55,10 @@
     layer = options['layer']
 
     # do some paranoia tests as well:
-    s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer);
-    if not s:
+    f = grass.vector_db(map, layer)
+    if not f:
 	grass.fatal("An error occured while running v.db.connect")
-    f = s.split()
+
     if not table:
 	# Removing table name connected to selected layer
 	table = f[1]
@@ -100,7 +100,7 @@
 	grass.run_command('v.db.connect', flags ='p', map = map)
 
     # write cmd history:
-    grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(map)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.db.join/v.db.join.py
===================================================================
--- grass/trunk/scripts/v.db.join/v.db.join.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.join/v.db.join.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -69,8 +69,9 @@
     otable = options['otable']
     ocolumn = options['ocolumn']
 
-    s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer)
-    f = s.split()
+    f = grass.vector_db(map, layer)
+    if not f:
+	grass.fatal("An error occured while running v.db.connect")
     maptable = f[1]
     database = f[3]
     driver = f[4]
@@ -81,31 +82,23 @@
     if not maptable:
 	grass.fatal("There is no table connected to this map. Cannot join any column.")
 
-    found = False
-    s = grass.read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True)
-    for line in s.splitlines():
-	f = line.split('|')
-	if len(f) > 1 and f[1] == column:
-	    found = True
-    if not found:
+    if column not in [f[1] for f in grass.vector_columns(map, layer)]:
 	grass.fatal("Column <%> not found in table <%s> at layer <%s>" % (column, map, layer))
 
-    s = grass.read_command('db.describe', flags = 'c', driver = driver,
-			   database = database, table = otable)
-    cols = [l.split(':') for l in s.splitlines() if l.startswith('Column ')]
+    cols = grass.db_describe(otable, driver = driver, database = database)['cols']
 
     select = "SELECT $colname FROM $otable WHERE $otable.$ocolumn=$table.$column"
     template = string.Template("UPDATE $table SET $colname=(%s);" % select)
 
     for col in cols:
-	colname = col[1].lstrip()
-	if len(col) > 3:
-	    coltype = "%s(%s)" % (col[2], col[3])
+	colname = col[0]
+	if len(col) > 2:
+	    coltype = "%s(%s)" % (col[1], col[2])
 	else:
-	    coltype = "%s" % col[2]
+	    coltype = "%s" % col[1]
 	colspec = "%s %s" % (colname, coltype)
 
-	if grass.run_command('v.db.addcol', map = map, col = colspec) != 0:
+	if grass.run_command('v.db.addcol', map = map, columns = colspec) != 0:
 	    grass.fatal("Error creating column <%s>." % colname)
 
 	stmt = template.substitute(table = maptable, column = column,
@@ -116,7 +109,7 @@
 	    grass.fatal("Error filling column <%s>." % colname)
 
     # write cmd history:
-    grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(map)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py
===================================================================
--- grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -60,9 +60,7 @@
     for vect in grass.list_grouped('vect')[mapset]:
 	vect = "%s@%s" % (vect, mapset)
 	grass.message("Reconnecting vector <%s>" % vect)
-	s = grass.read_command('v.db.connect', flags = 'g', map = vect, stderr = nuldev)
-	for link in s.splitlines():
-	    f = link.split()
+	for f in grass.vector_db(map, stderr = nuldev):
 	    layer = f[0]
 	    schema_table = f[1]
 	    key = f[2]

Modified: grass/trunk/scripts/v.db.renamecol/v.db.renamecol.py
===================================================================
--- grass/trunk/scripts/v.db.renamecol/v.db.renamecol.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.renamecol/v.db.renamecol.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -62,10 +62,9 @@
     if not grass.find_file(map, element = 'vector', mapset = mapset):
 	grass.fatal("Vector map <%s> not found in current mapset" % map)
 
-    s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer);
-    if not s:
+    f = grass.vector_db(map, layer)
+    if not f:
 	grass.fatal("An error occured while running v.db.connect")
-    f = s.split()
     table = f[1]
     keycol = f[2]
     database = f[3]
@@ -87,15 +86,11 @@
 
     # describe old col
     oldcoltype = None
-    s = grass.read_command('db.describe', flags = 'c', table = table)
-    for l in s.splitlines():
-	if not l.startswith('Column '):
+    for f in grass.db_describe(table):
+	if f[0] != oldcol:
 	    continue
-	f = l.split(':')
-	if f[1].lstrip() != oldcol:
-	    continue
-	oldcoltype = f[2]
-	oldcollength = f[3]
+	oldcoltype = f[1]
+	oldcollength = f[2]
 
     # old col there?
     if not oldcol:
@@ -117,7 +112,7 @@
 	grass.write_command('db.execute', database = database, driver = driver, stdin = sql)
 
     # write cmd history:
-    grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(map)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.db.update/v.db.update.py
===================================================================
--- grass/trunk/scripts/v.db.update/v.db.update.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.db.update/v.db.update.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -76,9 +76,8 @@
     if not grass.find_file(map, element = 'vector', mapset = mapset)['file']:
 	grass.fatal("Vector map '$GIS_OPT_MAP' not found in current mapset")
 
-    s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer)
-    f = s.rstrip('\r\n').split(' ')
-    if len(s) < 2:
+    f = grass.vector_db(map, layer)
+    if not f:
 	grass.fatal('There is no table connected to this map. Run v.db.connect or v.db.addtable first.')
 
     table = f[1]
@@ -87,11 +86,7 @@
 
     # checking column types
     coltype = None
-    s = grass.read_command('v.info', flags = 'c', map = map, quiet = True)
-    for l in s.splitlines():
-	f = l.split('|')
-	if len(f) < 2:
-	    continue
+    for f in grass.vector_columns(map, layer):
 	if f[1] == column:
 	    coltype = f[0]
 
@@ -117,7 +112,7 @@
     grass.write_command('db.execute', database = database, driver = driver, stdin = cmd)
 
     # write cmd history:
-    grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(map)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.dissolve/v.dissolve.py
===================================================================
--- grass/trunk/scripts/v.dissolve/v.dissolve.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.dissolve/v.dissolve.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -71,27 +71,26 @@
 
     # does map exist?
     if not grass.find_file(input, element = 'vector')['file']:
-	grass.fatal("Vector map '$GIS_OPT_INPUT' not found in mapset search path")
+	grass.fatal("Vector map <%s> not found in mapset search path", input)
 
     if not column:
 	grass.run_command('v.extract', flags = 'd', input = input,
 			  output = output, type = 'area', layer = layer)
     else:
 	coltype = ''
-	s = grass.read_command('v.info', flags = 'c', map = input, quiet = True)
-	for line in s.splitlines():
-	    f = line.split('|')
-	    if len(f) > 1 and f[1] == column:
+	for f in grass.vector_columns(map, layer):
+	    if f[1] == column:
 		coltype = f[0]
 
 	if coltype not in ['INTEGER', 'CHARACTER']:
 	    grass.fatal("Key column must be of type integer or string")
 
-	s = grass.read_command('v.db.connect', flags = 'g', map = input, layer = layer)
-	table = s.split()[1]
-	if not table:
+	f = grass.vector_db(input, layer)
+	if not f:
 	    grass.fatal("There is no table connected to this map")
 
+	table = f[1]
+
 	tmpfile = '%s_%s' % (output, tmp)
 
 	grass.run_command('v.reclass', input = input, output = tmpfile,
@@ -101,7 +100,7 @@
 			  output = output, type = 'area', layer = layer)
 
     # write cmd history:
-    grass.run_command('v.support', map = output, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(output)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.in.e00/v.in.e00.py
===================================================================
--- grass/trunk/scripts/v.in.e00/v.in.e00.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.in.e00/v.in.e00.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -168,7 +168,7 @@
     grass.message("Done.")
 
     # write cmd history:
-    grass.run_command('v.support', map = name, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(name)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.in.geonames/v.in.geonames.py
===================================================================
--- grass/trunk/scripts/v.in.geonames/v.in.geonames.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.in.geonames/v.in.geonames.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -66,8 +66,7 @@
 	grass.fatal("File <%s> not found" % infile)
 
     # DBF doesn't support lengthy text fields
-    s = grass.read_command('db.connect', flags = 'p')
-    kv = grass.parse_key_val(s, ':')
+    kv = grass.db_connection()
     dbfdriver = kv['driver'] == 'dbf'
     if dbfdriver:
 	grass.warning("Since DBF driver is used, the content of the 'alternatenames' column might be cut with respect to the original Geonames.org column content")
@@ -145,7 +144,7 @@
     grass.try_remove(tmpfile)
 
     # write cmd history:
-    grass.run_command('v.support', map = outfile, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(outfile)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.in.gns/v.in.gns.py
===================================================================
--- grass/trunk/scripts/v.in.gns/v.in.gns.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.in.gns/v.in.gns.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -147,7 +147,7 @@
     grass.try_remove(tmpfile)
 
     # write cmd history:
-    grass.run_command('v.support', map = filevect, cmdhist = os.environ['CMDLINE'])
+    grass.vector_history(filevect)
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.rast.stats/v.rast.stats.py
===================================================================
--- grass/trunk/scripts/v.rast.stats/v.rast.stats.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.rast.stats/v.rast.stats.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -71,14 +71,7 @@
 import grass
 
 def has_column(vector, col):
-    s = grass.read_command('v.info', flags = 'c', map = vector, quiet = True)
-    for l in s.splitlines():
-	f = l.split('|')
-	if len(f) < 2:
-	    continue
-	if f[1] == col:
-	    return True
-    return False
+    return 
 
 def cleanup():
     grass.run_command('g.remove', rast = '%s_%s' % (vector, tmpname), quiet = True)
@@ -163,9 +156,10 @@
 	grass.fatal("No categories found in raster map")
 
     #check if DBF driver used, in this case cut to 10 chars col names:
-    s = grass.read_command('v.db.connect', flags = 'g', map = vector, layer = layer)
+    f = grass.vector_db(vector, layer)
+    if not f:
+	grass.fatal('There is no table connected to this map. Run v.db.connect or v.db.addtable first.')
     # we need this for non-DBF driver:
-    f = s.split()
     table = f[1]
     db_database = f[3]
     db_sqldriver = f[4]
@@ -173,7 +167,7 @@
 
     #Find out which table is linked to the vector map on the given layer
     if not table:
-	grass.fatal('There is no table connected to this map! Run v.db.connect or v.db.addtable first.')
+	grass.fatal('There is no table connected to this map. Run v.db.connect or v.db.addtable first.')
 
     basecols = ['n', 'min', 'max', 'range', 'mean', 'stddev', 'variance', 'cf_var', 'sum']
 
@@ -200,7 +194,7 @@
 	if dbfdriver:
 	    currcolumn = currcolumn[:10]
 
-	if has_column(vector, currcolumn):
+	if currcolumn in [f[1] for f in grass.vector_columns(vector, layer)]:
 	    if not flags['c']:
 		grass.fatal(("Cannot create column <%s> (already present)." % currcolumn) +
 			    "Use -c flag to update values in this column.")

Modified: grass/trunk/scripts/v.report/v.report.py
===================================================================
--- grass/trunk/scripts/v.report/v.report.py	2008-09-29 19:41:44 UTC (rev 33601)
+++ grass/trunk/scripts/v.report/v.report.py	2008-09-29 23:46:48 UTC (rev 33602)
@@ -58,14 +58,6 @@
 import os
 import grass
 
-def find_key(map, layer):
-    s = grass.read_command('v.db.connect', flags = 'g', map = map);
-    for line in s.splitlines():
-	fields = line.split()
-	if fields[0] == layer:
-	    return fields[3]
-    return '<unknown>'
-
 def uniq(l):
     result = []
     last = None
@@ -89,18 +81,10 @@
     if not grass.find_file(mapname, 'vector')['file']:
 	grass.fatal("Vector map '%s' not found in mapset search path." % mapname)
 
-    table_exists = grass.run_command('v.info', flags = 'c', map = mapname,
-				     layer = layer, stdout = nuldev,
-				     stderr = nuldev) == 0
+    table_exists = grass.vector_columns(mapname, layer, stderr = nuldev)
 
     if table_exists:
-	p = grass.pipe_command('v.info', flags = 'c', map = mapname, layer = layer, stderr = nuldev)
-	colnames = []
-	for line in p.stdout:
-	    if '|' not in line:
-		continue
-	    colnames.append(line.rstrip('\r\n').split('|')[1])
-	p.wait()
+	colnames = [f[1] for f in grass.vector_columns(mapname, layer, stderr = nuldev)]
     else:
 	colnames = ['cat']
 
@@ -132,7 +116,8 @@
 	records1.sort()
 
 	if len(records1) == 0:
-	    key = find_key(mapname, layer)
+	    f = grass.vector_db(mapname, layer)
+	    key = f[2]
 	    grass.fatal("There is a table connected to input vector map '%s', but" +
 			"there are no categories present in the key column '%s'. Consider using" +
 			"v.to.db to correct this." % (mapname, key))



More information about the grass-commit mailing list