db.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """
  2. @package grass.script.db
  3. @brief GRASS Python scripting module
  4. Database related functions to be used in Python scripts.
  5. Usage:
  6. @code
  7. from grass.script import core, db as grass
  8. grass.parser()
  9. grass.db_describe(table)
  10. ...
  11. @endcode
  12. (C) 2008-2009 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Glynn Clements
  17. @author Martin Landa <landa.martin gmail.com>
  18. """
  19. from core import *
  20. def db_describe(table, **args):
  21. """Return the list of columns for a database table
  22. (interface to `db.describe -c'). Example:
  23. \code
  24. >>> grass.db_describe('lakes')
  25. {'nrows': 15279, 'cols': [['cat', 'INTEGER', '11'], ['AREA', 'DOUBLE PRECISION', '20'],
  26. ['PERIMETER', 'DOUBLE PRECISION', '20'], ['FULL_HYDRO', 'DOUBLE PRECISION', '20'],
  27. ['FULL_HYDR2', 'DOUBLE PRECISION', '20'], ['FTYPE', 'CHARACTER', '24'],
  28. ['FCODE', 'INTEGER', '11'], ['NAME', 'CHARACTER', '99']], 'ncols': 8}
  29. \endcode
  30. @param table table name
  31. @param args
  32. @return parsed module output
  33. """
  34. s = read_command('db.describe', flags = 'c', table = table, **args)
  35. if not s:
  36. return None
  37. cols = []
  38. result = {}
  39. for l in s.splitlines():
  40. f = l.split(':')
  41. key = f[0]
  42. f[1] = f[1].lstrip(' ')
  43. if key.startswith('Column '):
  44. n = int(key.split(' ')[1])
  45. cols.insert(n, f[1:])
  46. elif key in ['ncols', 'nrows']:
  47. result[key] = int(f[1])
  48. else:
  49. result[key] = f[1:]
  50. result['cols'] = cols
  51. return result
  52. # run "db.connect -p" and parse output
  53. def db_connection():
  54. """Return the current database connection parameters
  55. (interface to `db.connect -p'). Example:
  56. \code
  57. >>> grass.db_connection()
  58. {'group': 'x', 'schema': '', 'driver': 'dbf', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'}
  59. \endcode
  60. @return parsed output of db.connect
  61. """
  62. s = read_command('db.connect', flags = 'p')
  63. return parse_key_val(s, sep = ':')