db.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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, 2012 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 -g" 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 -g'). 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. return parse_command('db.connect', flags = 'g')
  73. def db_select(sql = None, filename = None, table = None, **args):
  74. """!Perform SQL select statement
  75. Note: one of <em>sql</em>, <em>filename</em>, or <em>table</em>
  76. arguments must be provided.
  77. Examples:
  78. \code
  79. grass.db_select(sql = 'SELECT cat,CAMPUS FROM busstopsall WHERE cat < 4')
  80. (('1', 'Vet School'), ('2', 'West'), ('3', 'North'))
  81. \endcode
  82. \code
  83. grass.db_select(filename = '/path/to/sql/file')
  84. \endcode
  85. Simplyfied usage
  86. \code
  87. grass.db_select(table = 'busstopsall')
  88. \endcode
  89. performs <tt>SELECT * FROM busstopsall</tt>.
  90. @param sql SQL statement to perform (or None)
  91. @param filename name of file with SQL statements (or None)
  92. @param table name of table to query (or None)
  93. @param args see \gmod{db.select} arguments
  94. """
  95. fname = tempfile(create = False)
  96. if sql:
  97. args['sql'] = sql
  98. elif filename:
  99. args['input'] = filename
  100. elif table:
  101. args['table'] = table
  102. else:
  103. fatal(_("Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be provided") %
  104. {'sql': 'sql', 'filename': 'filename', 'table': 'table'} )
  105. if 'sep' not in args:
  106. args['sep'] = '|'
  107. ret = run_command('db.select', quiet = True,
  108. flags = 'c',
  109. output = fname,
  110. **args)
  111. if ret != 0:
  112. fatal(_("Fetching data failed"))
  113. ofile = open(fname)
  114. result = map(lambda x: tuple(x.rstrip(os.linesep).split(args['sep'])),
  115. ofile.readlines())
  116. ofile.close()
  117. try_remove(fname)
  118. return tuple(result)