vinfo.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. """
  2. @package dbmgr.vinfo
  3. @brief Support classes for Database Manager
  4. List of classes:
  5. - vinfo::VectorDBInfo
  6. (C) 2007-2013 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Martin Landa <landa.martin gmail.com>
  10. """
  11. import os
  12. import types
  13. import sys
  14. import six
  15. import wx
  16. from gui_core.gselect import VectorDBInfo as VectorDBInfoBase
  17. from gui_core.wrap import StaticText
  18. from core.gcmd import RunCommand, GError
  19. from core.settings import UserSettings
  20. from core.utils import _
  21. import grass.script as grass
  22. if sys.version_info.major >= 3:
  23. unicode = str
  24. def GetUnicodeValue(value):
  25. """Get unicode value
  26. :param value: value to be recoded
  27. :return: unicode value
  28. """
  29. if isinstance(value, unicode):
  30. return value
  31. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  32. if not enc and 'GRASS_DB_ENCODING' in os.environ:
  33. enc = os.environ['GRASS_DB_ENCODING']
  34. else:
  35. enc = 'utf-8' # assuming UTF-8
  36. return unicode(str(value), enc, errors='replace')
  37. def CreateDbInfoDesc(panel, mapDBInfo, layer):
  38. """Create database connection information content"""
  39. infoFlexSizer = wx.FlexGridSizer(cols=2, hgap=1, vgap=1)
  40. infoFlexSizer.AddGrowableCol(1)
  41. infoFlexSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
  42. label="Driver:"))
  43. infoFlexSizer.Add(
  44. StaticText(
  45. parent=panel,
  46. id=wx.ID_ANY,
  47. label=mapDBInfo.layers[layer]['driver']))
  48. infoFlexSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
  49. label="Database:"))
  50. infoFlexSizer.Add(
  51. StaticText(
  52. parent=panel,
  53. id=wx.ID_ANY,
  54. label=mapDBInfo.layers[layer]['database']))
  55. infoFlexSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
  56. label="Table:"))
  57. infoFlexSizer.Add(
  58. StaticText(
  59. parent=panel,
  60. id=wx.ID_ANY,
  61. label=mapDBInfo.layers[layer]['table']))
  62. infoFlexSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
  63. label="Key:"))
  64. infoFlexSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
  65. label=mapDBInfo.layers[layer]['key']))
  66. return infoFlexSizer
  67. class VectorDBInfo(VectorDBInfoBase):
  68. """Class providing information about attribute tables
  69. linked to the vector map"""
  70. def __init__(self, map):
  71. VectorDBInfoBase.__init__(self, map)
  72. def GetColumns(self, table):
  73. """Return list of columns names (based on their index)"""
  74. try:
  75. names = [''] * len(self.tables[table].keys())
  76. except KeyError:
  77. return []
  78. for name, desc in six.iteritems(self.tables[table]):
  79. names[desc['index']] = name
  80. return names
  81. def SelectByPoint(self, queryCoords, qdist):
  82. """Get attributes by coordinates (all available layers)
  83. Return line id or None if no line is found"""
  84. line = None
  85. nselected = 0
  86. try:
  87. data = grass.vector_what(
  88. map=self.map, coord=(
  89. float(
  90. queryCoords[0]), float(
  91. queryCoords[1])), distance=float(qdist))
  92. except grass.ScriptError:
  93. GError(
  94. parent=None, message=_(
  95. "Failed to query vector map <{map}>. "
  96. "Check database settings and topology.").format(
  97. map=self.map))
  98. if len(data) < 1 or all(('Table' not in record) for record in data):
  99. return None
  100. # process attributes
  101. ret = dict()
  102. for key in ['Category', 'Layer', 'Table', 'Id']:
  103. ret[key] = list()
  104. for record in data:
  105. if not 'Table' in record:
  106. continue
  107. table = record['Table']
  108. for key, value in six.iteritems(record['Attributes']):
  109. if len(value) < 1:
  110. value = None
  111. else:
  112. if self.tables[table][key]['ctype'] != types.StringType:
  113. value = self.tables[table][key]['ctype'](value)
  114. else:
  115. value = GetUnicodeValue(value)
  116. self.tables[table][key]['values'].append(value)
  117. for key, value in six.iteritems(record):
  118. if key == 'Attributes':
  119. continue
  120. if key in ret:
  121. ret[key].append(value)
  122. if 'Id' not in record.keys():
  123. ret['Id'].append(None)
  124. return ret
  125. def SelectFromTable(self, layer, cols='*', where=None):
  126. """Select records from the table
  127. Return number of selected records, -1 on error
  128. """
  129. if layer <= 0:
  130. return -1
  131. nselected = 0
  132. table = self.layers[layer]["table"] # get table desc
  133. # select values (only one record)
  134. if where is None or where is '':
  135. sql = "SELECT %s FROM %s" % (cols, table)
  136. else:
  137. sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
  138. ret = RunCommand('db.select',
  139. read=True,
  140. quiet=True,
  141. flags='v',
  142. sql=sql,
  143. database=self.layers[layer]["database"],
  144. driver=self.layers[layer]["driver"])
  145. # self.tables[table][key][1] = str(cat)
  146. if ret:
  147. for line in ret.splitlines():
  148. name, value = line.split('|')
  149. # casting ...
  150. if value:
  151. if not isinstance('', self.tables[table][name]['ctype']):
  152. value = self.tables[table][name]['ctype'](value)
  153. else:
  154. value = GetUnicodeValue(value)
  155. else:
  156. value = None
  157. self.tables[table][name]['values'].append(value)
  158. nselected = 1
  159. return nselected