db.py 2.0 KB

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