db.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. from utils import try_remove
  20. def db_describe(table, **args):
  21. """!Return the list of columns for a database table
  22. (interface to `db.describe -c'). Example:
  23. \code
  24. >>> grass.db_describe('lakes')
  25. {'nrows': 15279, 'cols': [['cat', 'INTEGER', '11'], ['AREA', 'DOUBLE PRECISION', '20'],
  26. ['PERIMETER', 'DOUBLE PRECISION', '20'], ['FULL_HYDRO', 'DOUBLE PRECISION', '20'],
  27. ['FULL_HYDR2', 'DOUBLE PRECISION', '20'], ['FTYPE', 'CHARACTER', '24'],
  28. ['FCODE', 'INTEGER', '11'], ['NAME', 'CHARACTER', '99']], 'ncols': 8}
  29. \endcode
  30. @param table table name
  31. @param args
  32. @return parsed module output
  33. """
  34. s = read_command('db.describe', flags = 'c', table = table, **args)
  35. if not s:
  36. fatal(_("Unable to describe table <%s>") % table)
  37. cols = []
  38. result = {}
  39. for l in s.splitlines():
  40. f = l.split(':')
  41. key = f[0]
  42. f[1] = f[1].lstrip(' ')
  43. if key.startswith('Column '):
  44. n = int(key.split(' ')[1])
  45. cols.insert(n, f[1:])
  46. elif key in ['ncols', 'nrows']:
  47. result[key] = int(f[1])
  48. else:
  49. result[key] = f[1:]
  50. result['cols'] = cols
  51. return result
  52. # run "db.connect -g" and parse output
  53. def db_table_exist(table, **args):
  54. """!Check if table exists.
  55. If no driver or database are given, then default settings is used
  56. (check db_connection()).
  57. @param table table name
  58. @param driver DB driver
  59. @param database DB to check
  60. @return True for success, False otherwise
  61. """
  62. nuldev = file(os.devnull, 'w+')
  63. ret = run_command('db.describe', flags = 'c', table = table,
  64. stdout = nuldev, stderr = nuldev, **args)
  65. nuldev.close()
  66. if ret == 0:
  67. return True
  68. return False
  69. def db_connection():
  70. """!Return the current database connection parameters
  71. (interface to `db.connect -g'). Example:
  72. \code
  73. >>> grass.db_connection()
  74. {'group': 'x', 'schema': '', 'driver': 'dbf', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'}
  75. \endcode
  76. @return parsed output of db.connect
  77. """
  78. return parse_command('db.connect', flags = 'g')
  79. def db_select(sql = None, filename = None, table = None, **args):
  80. """!Perform SQL select statement
  81. Note: one of <em>sql</em>, <em>filename</em>, or <em>table</em>
  82. arguments must be provided.
  83. Examples:
  84. \code
  85. grass.db_select(sql = 'SELECT cat,CAMPUS FROM busstopsall WHERE cat < 4')
  86. (('1', 'Vet School'), ('2', 'West'), ('3', 'North'))
  87. \endcode
  88. \code
  89. grass.db_select(filename = '/path/to/sql/file')
  90. \endcode
  91. Simplyfied usage
  92. \code
  93. grass.db_select(table = 'busstopsall')
  94. \endcode
  95. performs <tt>SELECT * FROM busstopsall</tt>.
  96. @param sql SQL statement to perform (or None)
  97. @param filename name of file with SQL statements (or None)
  98. @param table name of table to query (or None)
  99. @param args see \gmod{db.select} arguments
  100. """
  101. fname = tempfile(create = False)
  102. if sql:
  103. args['sql'] = sql
  104. elif filename:
  105. args['input'] = filename
  106. elif table:
  107. args['table'] = table
  108. else:
  109. fatal(_("Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be provided") %
  110. {'sql': 'sql', 'filename': 'filename', 'table': 'table'} )
  111. if 'sep' not in args:
  112. args['sep'] = '|'
  113. ret = run_command('db.select', quiet = True,
  114. flags = 'c',
  115. output = fname,
  116. **args)
  117. if ret != 0:
  118. fatal(_("Fetching data failed"))
  119. ofile = open(fname)
  120. result = map(lambda x: tuple(x.rstrip(os.linesep).split(args['sep'])),
  121. ofile.readlines())
  122. ofile.close()
  123. try_remove(fname)
  124. return tuple(result)
  125. def db_table_in_vector(table):
  126. """Return the name of vector connected to the table.
  127. It returns False if no vectors are connected to the table.
  128. Example
  129. @params table name of table to query
  130. """
  131. from vector import vector_db
  132. nuldev = file(os.devnull, 'w')
  133. used = []
  134. vects = list_strings('vect')
  135. for vect in vects:
  136. for f in vector_db(vect, stderr=nuldev).itervalues():
  137. if not f:
  138. continue
  139. if f['table'] == table:
  140. used.append(vect)
  141. break
  142. return used