db.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 db as grass
  7. grass.db_describe(table)
  8. ...
  9. @endcode
  10. (C) 2008-2009 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Glynn Clements
  15. @author Martin Landa <landa.martin gmail.com>
  16. """
  17. import tempfile as pytempfile # conflict with core.tempfile
  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. grass.fatal(_("Unable to describe table <%s>") % table)
  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 = ':')
  63. def db_select(table, sql, file = False, **args):
  64. """!Perform SQL select statement
  65. @param table table name
  66. @param sql SQL select statement (string or file)
  67. @param file True if sql is filename
  68. @param args see db.select arguments
  69. """
  70. ofile = pytempfile.NamedTemporaryFile(mode = 'w+b')
  71. if not file:
  72. ret = run_command('db.select', quiet = True,
  73. flags = 'c',
  74. table = table,
  75. sql = sql,
  76. output = ofile.name)
  77. else: # -> sql is file
  78. ret = run_command('db.select', quiet = True,
  79. flags = 'c',
  80. table = table,
  81. input = sql,
  82. output = ofile.name)
  83. if ret != 0:
  84. fatal(_("Fetching data from table <%s> failed") % table)
  85. return ofile.readlines()