dbm_base.py 6.0 KB

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