vinfo.py 5.9 KB

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