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