db.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """
  2. Database related functions to be used in Python scripts.
  3. Usage:
  4. ::
  5. from grass.script import db as grass
  6. grass.db_describe(table)
  7. ...
  8. (C) 2008-2009, 2012 by the GRASS Development Team
  9. This program is free software under the GNU General Public
  10. License (>=v2). Read the file COPYING that comes with GRASS
  11. for details.
  12. .. sectionauthor:: Glynn Clements
  13. .. sectionauthor:: Martin Landa <landa.martin gmail.com>
  14. """
  15. from core import *
  16. from utils import try_remove
  17. def db_describe(table, **args):
  18. """Return the list of columns for a database table
  19. (interface to `db.describe -c`). Example:
  20. >>> run_command('g.copy', vect='firestations,myfirestations')
  21. 0
  22. >>> db_describe('myfirestations') # doctest: +ELLIPSIS
  23. {'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22}
  24. >>> run_command('g.remove', flags='f', type='vect', pattern='myfirestations')
  25. 0
  26. :param str table: table name
  27. :param list args:
  28. :return: parsed module output
  29. """
  30. s = read_command('db.describe', flags='c', table=table, **args)
  31. if not s:
  32. fatal(_("Unable to describe table <%s>") % table)
  33. cols = []
  34. result = {}
  35. for l in s.splitlines():
  36. f = l.split(':')
  37. key = f[0]
  38. f[1] = f[1].lstrip(' ')
  39. if key.startswith('Column '):
  40. n = int(key.split(' ')[1])
  41. cols.insert(n, f[1:])
  42. elif key in ['ncols', 'nrows']:
  43. result[key] = int(f[1])
  44. else:
  45. result[key] = f[1:]
  46. result['cols'] = cols
  47. return result
  48. def db_table_exist(table, **args):
  49. """Check if table exists.
  50. If no driver or database are given, then default settings is used
  51. (check db_connection()).
  52. >>> run_command('g.copy', vect='firestations,myfirestations')
  53. 0
  54. >>> db_table_exist('myfirestations')
  55. True
  56. >>> run_command('g.remove', flags='f', type='vect', pattern='myfirestations')
  57. 0
  58. :param str table: table name
  59. :param args:
  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. >>> db_connection()
  73. {'group': '', 'schema': '', 'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'}
  74. :return: parsed output of db.connect
  75. """
  76. return parse_command('db.connect', flags='g')
  77. def db_select(sql=None, filename=None, table=None, **args):
  78. """Perform SQL select statement
  79. Note: one of <em>sql</em>, <em>filename</em>, or <em>table</em>
  80. arguments must be provided.
  81. Examples:
  82. >>> run_command('g.copy', vect='firestations,myfirestations')
  83. 0
  84. >>> db_select(sql = 'SELECT cat,CITY FROM myfirestations WHERE cat < 4')
  85. (('1', 'Morrisville'), ('2', 'Morrisville'), ('3', 'Apex'))
  86. Simplyfied usage (it performs <tt>SELECT * FROM myfirestations</tt>.)
  87. >>> db_select(table = 'myfirestations') # doctest: +ELLIPSIS
  88. (('1', '24', 'Morrisville #3', ... 'HS2A', '1.37'))
  89. >>> run_command('g.remove', flags='f', type='vect', pattern='myfirestations')
  90. 0
  91. :param str sql: SQL statement to perform (or None)
  92. :param str filename: name of file with SQL statements (or None)
  93. :param str table: name of table to query (or None)
  94. :param str args: see \gmod{db.select} arguments
  95. """
  96. fname = tempfile(create=False)
  97. if sql:
  98. args['sql'] = sql
  99. elif filename:
  100. args['input'] = filename
  101. elif table:
  102. args['table'] = table
  103. else:
  104. fatal(_("Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be provided") %
  105. {'sql': 'sql', 'filename': 'filename', 'table': 'table'} )
  106. if 'sep' not in args:
  107. args['sep'] = '|'
  108. ret = run_command('db.select', quiet=True, flags='c',
  109. output=fname, **args)
  110. if ret != 0:
  111. fatal(_("Fetching data failed"))
  112. ofile = open(fname)
  113. result = map(lambda x: tuple(x.rstrip(os.linesep).split(args['sep'])),
  114. ofile.readlines())
  115. ofile.close()
  116. try_remove(fname)
  117. return tuple(result)
  118. def db_table_in_vector(table):
  119. """Return the name of vector connected to the table.
  120. It returns None if no vectors are connected to the table.
  121. >>> run_command('g.copy', vect='firestations,myfirestations')
  122. 0
  123. >>> db_table_in_vector('myfirestations')
  124. ['myfirestations@user1']
  125. >>> db_table_in_vector('mfirestations')
  126. >>> run_command('g.remove', flags='f', type='vect', pattern='myfirestations')
  127. 0
  128. :param str table: name of table to query
  129. """
  130. from vector import vector_db
  131. nuldev = file(os.devnull, 'w')
  132. used = []
  133. vects = list_strings('vect')
  134. for vect in vects:
  135. for f in vector_db(vect, stderr=nuldev).itervalues():
  136. if not f:
  137. continue
  138. if f['table'] == table:
  139. used.append(vect)
  140. break
  141. if len(used) > 0:
  142. return used
  143. else:
  144. return None