db.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. # run "db.describe -c ..." and parse output
  21. def db_describe(table, **args):
  22. """Return the list of columns for a database table
  23. (interface to `db.describe -c').
  24. """
  25. s = read_command('db.describe', flags = 'c', table = table, **args)
  26. if not s:
  27. return None
  28. cols = []
  29. result = {}
  30. for l in s.splitlines():
  31. f = l.split(':')
  32. key = f[0]
  33. f[1] = f[1].lstrip(' ')
  34. if key.startswith('Column '):
  35. n = int(key.split(' ')[1])
  36. cols.insert(n, f[1:])
  37. elif key in ['ncols', 'nrows']:
  38. result[key] = int(f[1])
  39. else:
  40. result[key] = f[1:]
  41. result['cols'] = cols
  42. return result
  43. # run "db.connect -p" and parse output
  44. def db_connection():
  45. """Return the current database connection parameters
  46. (interface to `db.connect -p').
  47. """
  48. s = read_command('db.connect', flags = 'p')
  49. return parse_key_val(s, sep = ':')