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