db.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """!@package grass.script.db
  2. @brief GRASS Python scripting module (database functions)
  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. 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_table_exist(table, **args):
  53. """!Return True if database table exists, False otherwise
  54. @param table table name
  55. @param args
  56. @return True for success, False otherwise
  57. """
  58. result = run_command('db.describe', flags = 'c', table = table, **args)
  59. if result == 0:
  60. return True
  61. else:
  62. return False
  63. def db_connection():
  64. """!Return the current database connection parameters
  65. (interface to `db.connect -p'). Example:
  66. \code
  67. >>> grass.db_connection()
  68. {'group': 'x', 'schema': '', 'driver': 'dbf', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'}
  69. \endcode
  70. @return parsed output of db.connect
  71. """
  72. s = read_command('db.connect', flags = 'p')
  73. return parse_key_val(s, sep = ':')
  74. def db_select(table, sql, file = False, **args):
  75. """!Perform SQL select statement
  76. @param table table name
  77. @param sql SQL select statement (string or file)
  78. @param file True if sql is filename
  79. @param args see db.select arguments
  80. """
  81. fname = tempfile(create = False)
  82. if not file:
  83. ret = run_command('db.select', quiet = True,
  84. flags = 'c',
  85. table = table,
  86. sql = sql,
  87. output = fname,
  88. **args)
  89. else: # -> sql is file
  90. ret = run_command('db.select', quiet = True,
  91. flags = 'c',
  92. table = table,
  93. input = sql,
  94. output = fname,
  95. **args)
  96. if ret != 0:
  97. fatal(_("Fetching data from table <%s> failed") % table)
  98. ofile = open(fname)
  99. result = map(lambda x: x.rstrip(os.linesep), ofile.readlines())
  100. ofile.close()
  101. try_remove(fname)
  102. return result