db.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. # i18N
  20. import gettext
  21. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  22. def db_describe(table, **args):
  23. """!Return the list of columns for a database table
  24. (interface to `db.describe -c'). Example:
  25. \code
  26. >>> grass.db_describe('lakes')
  27. {'nrows': 15279, 'cols': [['cat', 'INTEGER', '11'], ['AREA', 'DOUBLE PRECISION', '20'],
  28. ['PERIMETER', 'DOUBLE PRECISION', '20'], ['FULL_HYDRO', 'DOUBLE PRECISION', '20'],
  29. ['FULL_HYDR2', 'DOUBLE PRECISION', '20'], ['FTYPE', 'CHARACTER', '24'],
  30. ['FCODE', 'INTEGER', '11'], ['NAME', 'CHARACTER', '99']], 'ncols': 8}
  31. \endcode
  32. @param table table name
  33. @param args
  34. @return parsed module output
  35. """
  36. s = read_command('db.describe', flags = 'c', table = table, **args)
  37. if not s:
  38. fatal(_("Unable to describe table <%s>") % table)
  39. cols = []
  40. result = {}
  41. for l in s.splitlines():
  42. f = l.split(':')
  43. key = f[0]
  44. f[1] = f[1].lstrip(' ')
  45. if key.startswith('Column '):
  46. n = int(key.split(' ')[1])
  47. cols.insert(n, f[1:])
  48. elif key in ['ncols', 'nrows']:
  49. result[key] = int(f[1])
  50. else:
  51. result[key] = f[1:]
  52. result['cols'] = cols
  53. return result
  54. # run "db.connect -p" and parse output
  55. def db_connection():
  56. """!Return the current database connection parameters
  57. (interface to `db.connect -p'). Example:
  58. \code
  59. >>> grass.db_connection()
  60. {'group': 'x', 'schema': '', 'driver': 'dbf', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'}
  61. \endcode
  62. @return parsed output of db.connect
  63. """
  64. s = read_command('db.connect', flags = 'p')
  65. return parse_key_val(s, sep = ':')
  66. def db_select(table, sql, file = False, **args):
  67. """!Perform SQL select statement
  68. @param table table name
  69. @param sql SQL select statement (string or file)
  70. @param file True if sql is filename
  71. @param args see db.select arguments
  72. """
  73. ofile = pytempfile.NamedTemporaryFile(mode = 'w+b')
  74. if not file:
  75. ret = run_command('db.select', quiet = True,
  76. flags = 'c',
  77. table = table,
  78. sql = sql,
  79. output = ofile.name)
  80. else: # -> sql is file
  81. ret = run_command('db.select', quiet = True,
  82. flags = 'c',
  83. table = table,
  84. input = sql,
  85. output = ofile.name)
  86. if ret != 0:
  87. fatal(_("Fetching data from table <%s> failed") % table)
  88. return ofile.readlines()