File: dbm_base.py

package info (click to toggle)
grass 6.4.2-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 96,212 kB
  • sloc: ansic: 412,640; python: 54,987; tcl: 45,923; cpp: 29,790; sh: 18,410; makefile: 6,878; xml: 3,390; yacc: 561; perl: 559; lex: 480; sed: 66; objc: 7
file content (165 lines) | stat: -rw-r--r-- 5,805 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""
@package dbm_base.py

@brief Support classes for dbm.py

List of classes:
 - VectorDBInfo

(C) 2007-2011 by the GRASS Development Team

This program is free software under the GNU General Public
License (>=v2). Read the file COPYING that comes with GRASS
for details.

@author Martin Landa <landa.martin gmail.com>
"""

import os
import types

import wx

import gselect
import gcmd
from preferences import globalSettings as UserSettings

import grass.script as grass

def unicodeValue(value):
    """!Encode value"""
    if type(value) == types.UnicodeType:
        return value
    
    enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
    if enc:
        value = unicode(value, enc)
    elif 'GRASS_DB_ENCODING' in os.environ:
        value = unicode(value, os.environ['GRASS_DB_ENCODING'])
    else:
        try:
            value = unicode(value, 'ascii')
        except UnicodeDecodeError:
            value = _("Unable to decode value. Set encoding in GUI preferences ('Attributes').")
    
    return value

def createDbInfoDesc(panel, mapDBInfo, layer):
    """!Create database connection information content"""
    infoFlexSizer = wx.FlexGridSizer (cols = 2, hgap = 1, vgap = 1)
    infoFlexSizer.AddGrowableCol(1)
    
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = "Driver:"))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = mapDBInfo.layers[layer]['driver']))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = "Database:"))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = mapDBInfo.layers[layer]['database']))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = "Table:"))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = mapDBInfo.layers[layer]['table']))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = "Key:"))
    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
                                         label = mapDBInfo.layers[layer]['key']))
    
    return infoFlexSizer
        
class VectorDBInfo(gselect.VectorDBInfo):
    """!Class providing information about attribute tables
    linked to the vector map"""
    def __init__(self, map):
        gselect.VectorDBInfo.__init__(self, map)
        
    def GetColumns(self, table):
        """!Return list of columns names (based on their index)"""
        try:
            names = [''] * len(self.tables[table].keys())
        except KeyError:
            return []
        
        for name, desc in self.tables[table].iteritems():
            names[desc['index']] = name
        
        return names

    def SelectByPoint(self, queryCoords, qdist):
        """!Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        data = grass.vector_what(map = self.map,
                                 coord = (float(queryCoords[0]), float(queryCoords[1])),
                                 distance = float(qdist))

        if len(data) < 1 or 'Table' not in data[0]:
            return None
        
        # process attributes
        table = data[0]['Table']
        for key, value in data[0]['Attributes'].iteritems():
            if len(value) < 1:
                value = None
            else:
                if self.tables[table][key]['ctype'] != types.StringType:
                    value = self.tables[table][key]['ctype'] (value)
                else:
                    value = unicodeValue(value)
            self.tables[table][key]['values'].append(value)
        
        ret = dict()
        for key, value in data[0].iteritems():
            if key == 'Attributes':
                continue
            ret[key] = list()
            ret[key].append(value)
        
        return ret
    
    def SelectFromTable(self, layer, cols = '*', where = None):
        """!Select records from the table

        Return number of selected records, -1 on error
        """
        if layer <= 0:
            return -1

        nselected = 0

        table = self.layers[layer]["table"] # get table desc
        # select values (only one record)
        if where is None or where is '':
            sql = "SELECT %s FROM %s" % (cols, table)
        else:
            sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
        
        ret = gcmd.RunCommand('db.select',
                              parent = self,
                              read = True,
                              quiet = True,
                              flags = 'v',
                              sql= sql,
                              database = self.layers[layer]["database"],
                              driver = self.layers[layer]["driver"])
        
        # self.tables[table][key][1] = str(cat)
        if ret:
            for line in ret.splitlines():
                name, value = line.split('|')
                # casting ...
                if value:
                    if self.tables[table][name]['ctype'] != type(''):
                        value = self.tables[table][name]['ctype'] (value)
                    else:
                        value = unicodeValue(value)
                else:
                    value = None
                self.tables[table][name]['values'].append(value)
                nselected = 1

        return nselected