dbm_base.py 5.7 KB

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