source: timingandestimationplugin/branches/trac0.10/timingandestimationplugin/dbhelper.py

Last change on this file was 3785, checked in by Russ Tyndall, 15 years ago

closes #3131
closes #3074
T&E(trac 10) 0.6.6

I brought the trac 10 branch up to the same version number of the plugin so that hopefully there is less confusion on my part about versions.

Fixes horrible bug relating to database access (due to my misunderstanding of which things were stateful in trac/python).

Fixed some bugs in the way billable values were being compared in the reports file (strong vs weak typed databases)

File size: 5.2 KB
Line 
1
2def get_all(com, sql, *params):
3    """Executes the query and returns the (description, data)"""
4    db = com.env.get_db_cnx()
5    cur = db.cursor()
6    desc  = None
7    data = None
8    try:
9        cur.execute(sql, params)
10        data = list(cur.fetchall())
11        desc = cur.description
12        db.commit();
13    except Exception, e:
14        com.log.error('There was a problem executing sql:%s \n \
15with parameters:%s\nException:%s'%(sql, params, e));
16        db.rollback();
17    try:
18        db.close()
19    except:
20        pass
21
22    return (desc, data)
23
24def execute_non_query(com,  sql, *params):
25    """Executes the query on the given project"""
26    db = com.env.get_db_cnx()
27    cur = db.cursor()
28    try:
29        cur.execute(sql, params)
30        db.commit()
31    except Exception, e:
32        com.log.error('There was a problem executing sql:%s \n \
33with parameters:%s\nException:%s'%(sql, params, e));
34        db.rollback();
35    try:
36        db.close()
37    except:
38        pass
39
40def get_first_row(com,  sql,*params):
41    """ Returns the first row of the query results as a tuple of values (or None)"""
42    db = com.env.get_db_cnx()
43    cur = db.cursor()
44    data = None;
45    try:
46        cur.execute(sql, params)
47        data = cur.fetchone();
48        db.commit();
49    except Exception, e:
50        com.log.error('There was a problem executing sql:%s \n \
51        with parameters:%s\nException:%s'%(sql, params, e));
52        db.rollback()
53    try:
54        db.close()
55    except:
56        pass
57    return data;
58
59def get_scalar(com, sql, col=0, *params):
60    """ Gets a single value (in the specified column) from the result set of the query"""
61    data = get_first_row(com, sql, *params);
62    if data:
63        return data[col]
64    else:
65        return None;
66
67def execute_in_trans(com, *args):
68    db = com.env.get_db_cnx()
69    cur = db.cursor()
70    result = True
71    try:
72        for sql, params in args:
73            cur.execute(sql, params)
74        db.commit()
75    except Exception, e:
76        com.log.error('There was a problem executing sql:%s \n \
77        with parameters:%s\nException:%s'%(sql, params, e));
78        db.rollback();
79        result = e
80    try:
81        db.close()
82    except:
83        pass
84    return result
85
86def db_table_exists(com,  table):
87    db = com.env.get_db_cnx()
88    sql = "SELECT * FROM %s LIMIT 1" % table;
89    cur = db.cursor()
90    has_table = True;
91    try:
92        cur.execute(sql)
93        db.commit()
94    except Exception, e:
95        has_table = False
96        db.rollback()
97
98    try:
99        db.close()
100    except:
101        pass
102    return has_table
103
104def get_column_as_list(com, sql, col=0, *params):
105    data = get_all(com, sql, *params)[1] or ()
106    return [valueList[col] for valueList in data]
107
108def get_system_value(com, key):
109    return get_scalar(com, "SELECT value FROM system WHERE name=%s", 0, key)
110
111def set_system_value(com, key, value):
112    if get_system_value(com, key):
113        execute_non_query(com, "UPDATE system SET value=%s WHERE name=%s", value, key)
114    else:
115        execute_non_query(com, "INSERT INTO system (value, name) VALUES (%s, %s)",
116            value, key)
117
118
119def get_result_set(com, sql, *params):
120    """Executes the query and returns a Result Set"""
121    tpl = get_all(com, sql, *params);
122    if tpl and tpl[0] and tpl[1]:
123        return ResultSet(tpl)
124    else:
125        return None
126
127
128class ResultSet:
129    """ the result of calling getResultSet """
130    def __init__ (self, (columnDescription, rows)):
131        self.columnDescription, self.rows = columnDescription, rows
132        self.columnMap = self.get_column_map()
133
134    def get_column_map ( self ):
135        """This function will take the result set from getAll and will
136        return a hash of the column names to their index """
137        h = {}
138        i = 0
139        if self.columnDescription:
140            for col in self.columnDescription:
141                h[ col[0] ] = i
142                i+=1
143        return h;
144
145    def value(self, col, row ):
146        """ given a row(list or idx) and a column( name or idx ), retrieve the appropriate value"""
147        tcol = type(col)
148        trow = type(row)
149        if tcol == str:
150            if(trow == list or trow == tuple):
151                return row[self.columnMap[col]]
152            elif(trow == int):
153                return self.rows[row][self.columnMap[col]]
154            else:
155                print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
156        elif tcol == int:
157            if(trow == list or trow == tuple):
158                return row[col]
159            elif(trow == int):
160                return self.rows[row][col]
161            else:
162                print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
163        else:
164            print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
165
166    def json_out(self):
167        json = "[%s]" % ',\r\n'. join(
168            [("{%s}" % ','.join(
169            ["'%s':'%s'" %
170             (key, str(self.value(val, row)).
171              replace("'","\\'").
172              replace('"','\\"').
173              replace('\r','\\r').
174              replace('\n','\\n'))
175             for (key, val) in self.columnMap.items()]))
176             for row in self.rows])
177        #mylog.debug('serializing to json : %s'% json)
178        return json
Note: See TracBrowser for help on using the repository browser.