vinfo.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """
  2. @package dbmgr.vinfo
  3. @brief Support classes for Database Manager
  4. List of classes:
  5. - vinfo::VectorDBInfo
  6. (C) 2007-2011 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 wx
  14. from gui_core.gselect import VectorDBInfo as VectorDBInfoBase
  15. from core.gcmd import RunCommand
  16. from core.settings import UserSettings
  17. import grass.script as grass
  18. def unicodeValue(value):
  19. """!Encode value"""
  20. if type(value) == types.UnicodeType:
  21. return value
  22. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  23. if enc:
  24. value = unicode(value, enc)
  25. elif 'GRASS_DB_ENCODING' in os.environ:
  26. value = unicode(value, os.environ['GRASS_DB_ENCODING'])
  27. else:
  28. try:
  29. value = unicode(value, 'ascii')
  30. except UnicodeDecodeError:
  31. value = _("Unable to decode value. Set encoding in GUI preferences ('Attributes').")
  32. return value
  33. def createDbInfoDesc(panel, mapDBInfo, layer):
  34. """!Create database connection information content"""
  35. infoFlexSizer = wx.FlexGridSizer (cols = 2, hgap = 1, vgap = 1)
  36. infoFlexSizer.AddGrowableCol(1)
  37. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  38. label = "Driver:"))
  39. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  40. label = mapDBInfo.layers[layer]['driver']))
  41. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  42. label = "Database:"))
  43. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  44. label = mapDBInfo.layers[layer]['database']))
  45. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  46. label = "Table:"))
  47. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  48. label = mapDBInfo.layers[layer]['table']))
  49. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  50. label = "Key:"))
  51. infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  52. label = mapDBInfo.layers[layer]['key']))
  53. return infoFlexSizer
  54. class VectorDBInfo(VectorDBInfoBase):
  55. """!Class providing information about attribute tables
  56. linked to the vector map"""
  57. def __init__(self, map):
  58. VectorDBInfoBase.__init__(self, map)
  59. def GetColumns(self, table):
  60. """!Return list of columns names (based on their index)"""
  61. try:
  62. names = [''] * len(self.tables[table].keys())
  63. except KeyError:
  64. return []
  65. for name, desc in self.tables[table].iteritems():
  66. names[desc['index']] = name
  67. return names
  68. def SelectByPoint(self, queryCoords, qdist):
  69. """!Get attributes by coordinates (all available layers)
  70. Return line id or None if no line is found"""
  71. line = None
  72. nselected = 0
  73. data = grass.vector_what(map = self.map,
  74. coord = (float(queryCoords[0]), float(queryCoords[1])),
  75. distance = float(qdist))
  76. if len(data) < 1 or all(('Table' not in record) for record in data):
  77. return None
  78. # process attributes
  79. ret = dict()
  80. for key in ['Category', 'Layer', 'Table', 'Id']:
  81. ret[key] = list()
  82. for record in data:
  83. if not 'Table' in record:
  84. continue
  85. table = record['Table']
  86. for key, value in record['Attributes'].iteritems():
  87. if len(value) < 1:
  88. value = None
  89. else:
  90. if self.tables[table][key]['ctype'] != types.StringType:
  91. value = self.tables[table][key]['ctype'] (value)
  92. else:
  93. value = unicodeValue(value)
  94. self.tables[table][key]['values'].append(value)
  95. for key, value in record.iteritems():
  96. if key == 'Attributes':
  97. continue
  98. if key in ret:
  99. ret[key].append(value)
  100. if 'Id' not in record.keys():
  101. ret['Id'].append(None)
  102. return ret
  103. def SelectFromTable(self, layer, cols = '*', where = None):
  104. """!Select records from the table
  105. Return number of selected records, -1 on error
  106. """
  107. if layer <= 0:
  108. return -1
  109. nselected = 0
  110. table = self.layers[layer]["table"] # get table desc
  111. # select values (only one record)
  112. if where is None or where is '':
  113. sql = "SELECT %s FROM %s" % (cols, table)
  114. else:
  115. sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
  116. ret = RunCommand('db.select',
  117. parent = self,
  118. read = True,
  119. quiet = True,
  120. flags = 'v',
  121. sql= sql,
  122. database = self.layers[layer]["database"],
  123. driver = self.layers[layer]["driver"])
  124. # self.tables[table][key][1] = str(cat)
  125. if ret:
  126. for line in ret.splitlines():
  127. name, value = line.split('|')
  128. # casting ...
  129. if value:
  130. if self.tables[table][name]['ctype'] != type(''):
  131. value = self.tables[table][name]['ctype'] (value)
  132. else:
  133. value = unicodeValue(value)
  134. else:
  135. value = None
  136. self.tables[table][name]['values'].append(value)
  137. nselected = 1
  138. return nselected