GRASS Programmer's Manual  6.5.svn(2012)-r51648
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines
vinfo.py
Go to the documentation of this file.
00001 """
00002 @package dbmgr.vinfo
00003 
00004 @brief Support classes for Database Manager
00005 
00006 List of classes:
00007  - vinfo::VectorDBInfo
00008 
00009 (C) 2007-2011 by the GRASS Development Team
00010 
00011 This program is free software under the GNU General Public License
00012 (>=v2). Read the file COPYING that comes with GRASS for details.
00013 
00014 @author Martin Landa <landa.martin gmail.com>
00015 """
00016 
00017 import os
00018 import types
00019 
00020 import wx
00021 
00022 from gui_core.gselect import VectorDBInfo as VectorDBInfoBase
00023 from core.gcmd        import RunCommand
00024 from core.settings    import UserSettings
00025 
00026 import grass.script as grass
00027 
00028 def unicodeValue(value):
00029     """!Encode value"""
00030     if type(value) == types.UnicodeType:
00031         return value
00032     
00033     enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
00034     if enc:
00035         value = unicode(value, enc)
00036     elif 'GRASS_DB_ENCODING' in os.environ:
00037         value = unicode(value, os.environ['GRASS_DB_ENCODING'])
00038     else:
00039         try:
00040             value = unicode(value, 'ascii')
00041         except UnicodeDecodeError:
00042             value = _("Unable to decode value. Set encoding in GUI preferences ('Attributes').")
00043     
00044     return value
00045 
00046 def createDbInfoDesc(panel, mapDBInfo, layer):
00047     """!Create database connection information content"""
00048     infoFlexSizer = wx.FlexGridSizer (cols = 2, hgap = 1, vgap = 1)
00049     infoFlexSizer.AddGrowableCol(1)
00050     
00051     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00052                                          label = "Driver:"))
00053     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00054                                          label = mapDBInfo.layers[layer]['driver']))
00055     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00056                                          label = "Database:"))
00057     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00058                                          label = mapDBInfo.layers[layer]['database']))
00059     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00060                                          label = "Table:"))
00061     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00062                                          label = mapDBInfo.layers[layer]['table']))
00063     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00064                                          label = "Key:"))
00065     infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
00066                                          label = mapDBInfo.layers[layer]['key']))
00067     
00068     return infoFlexSizer
00069         
00070 class VectorDBInfo(VectorDBInfoBase):
00071     """!Class providing information about attribute tables
00072     linked to the vector map"""
00073     def __init__(self, map):
00074         VectorDBInfoBase.__init__(self, map)
00075         
00076     def GetColumns(self, table):
00077         """!Return list of columns names (based on their index)"""
00078         try:
00079             names = [''] * len(self.tables[table].keys())
00080         except KeyError:
00081             return []
00082         
00083         for name, desc in self.tables[table].iteritems():
00084             names[desc['index']] = name
00085         
00086         return names
00087 
00088     def SelectByPoint(self, queryCoords, qdist):
00089         """!Get attributes by coordinates (all available layers)
00090 
00091         Return line id or None if no line is found"""
00092         line = None
00093         nselected = 0
00094 
00095         data = grass.vector_what(map = self.map,
00096                                  coord = (float(queryCoords[0]), float(queryCoords[1])),
00097                                  distance = float(qdist))
00098 
00099         if len(data) < 1 or 'Table' not in data[0]:
00100             return None
00101         
00102         # process attributes
00103         table = data[0]['Table']
00104         for key, value in data[0]['Attributes'].iteritems():
00105             if len(value) < 1:
00106                 value = None
00107             else:
00108                 if self.tables[table][key]['ctype'] != types.StringType:
00109                     value = self.tables[table][key]['ctype'] (value)
00110                 else:
00111                     value = unicodeValue(value)
00112             self.tables[table][key]['values'].append(value)
00113         
00114         ret = dict()
00115         for key, value in data[0].iteritems():
00116             if key == 'Attributes':
00117                 continue
00118             ret[key] = list()
00119             ret[key].append(value)
00120         
00121         return ret
00122     
00123     def SelectFromTable(self, layer, cols = '*', where = None):
00124         """!Select records from the table
00125 
00126         Return number of selected records, -1 on error
00127         """
00128         if layer <= 0:
00129             return -1
00130 
00131         nselected = 0
00132 
00133         table = self.layers[layer]["table"] # get table desc
00134         # select values (only one record)
00135         if where is None or where is '':
00136             sql = "SELECT %s FROM %s" % (cols, table)
00137         else:
00138             sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
00139         
00140         ret = RunCommand('db.select',
00141                          parent = self,
00142                          read = True,
00143                          quiet = True,
00144                          flags = 'v',
00145                          sql= sql,
00146                          database = self.layers[layer]["database"],
00147                          driver = self.layers[layer]["driver"])
00148         
00149         # self.tables[table][key][1] = str(cat)
00150         if ret:
00151             for line in ret.splitlines():
00152                 name, value = line.split('|')
00153                 # casting ...
00154                 if value:
00155                     if self.tables[table][name]['ctype'] != type(''):
00156                         value = self.tables[table][name]['ctype'] (value)
00157                     else:
00158                         value = unicodeValue(value)
00159                 else:
00160                     value = None
00161                 self.tables[table][name]['values'].append(value)
00162                 nselected = 1
00163 
00164         return nselected