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