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

Last change on this file was 8124, checked in by Russ Tyndall, 13 years ago

First trac-12 version, changed db access to not close databases (now that its not good to do so) re #7259

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        if db: 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        if db: 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        if db: 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        if db: 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        if db: db.rollback();
97    try:
98        db.close()
99    except:
100        pass
101    return has_table
102
103def get_column_as_list(com, sql, col=0, *params):
104    data = get_all(com, sql, *params)[1] or ()
105    return [valueList[col] for valueList in data]
106
107def get_system_value(com, key):
108    return get_scalar(com, "SELECT value FROM system WHERE name=%s", 0, key)
109
110def set_system_value(com, key, value):
111    if get_system_value(com, key):
112        execute_non_query(com, "UPDATE system SET value=%s WHERE name=%s", value, key)
113    else:
114        execute_non_query(com, "INSERT INTO system (value, name) VALUES (%s, %s)",
115            value, key)
116
117
118def get_result_set(com, sql, *params):
119    """Executes the query and returns a Result Set"""
120    tpl = get_all(com, sql, *params);
121    if tpl and tpl[0] and tpl[1]:
122        return ResultSet(tpl)
123    else:
124        return None
125
126
127class ResultSet:
128    """ the result of calling getResultSet """
129    def __init__ (self, (columnDescription, rows)):
130        self.columnDescription, self.rows = columnDescription, rows
131        self.columnMap = self.get_column_map()
132
133    def get_column_map ( self ):
134        """This function will take the result set from getAll and will
135        return a hash of the column names to their index """
136        h = {}
137        i = 0
138        if self.columnDescription:
139            for col in self.columnDescription:
140                h[ col[0] ] = i
141                i+=1
142        return h;
143
144    def value(self, col, row ):
145        """ given a row(list or idx) and a column( name or idx ), retrieve the appropriate value"""
146        tcol = type(col)
147        trow = type(row)
148        if tcol == str:
149            if(trow == list or trow == tuple):
150                return row[self.columnMap[col]]
151            elif(trow == int):
152                return self.rows[row][self.columnMap[col]]
153            else:
154                print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
155        elif tcol == int:
156            if(trow == list or trow == tuple):
157                return row[col]
158            elif(trow == int):
159                return self.rows[row][col]
160            else:
161                print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
162        else:
163            print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
164
165    def json_out(self):
166        json = "[%s]" % ',\r\n'. join(
167            [("{%s}" % ','.join(
168            ["'%s':'%s'" %
169             (key, str(self.value(val, row)).
170              replace("'","\\'").
171              replace('"','\\"').
172              replace('\r','\\r').
173              replace('\n','\\n'))
174             for (key, val) in self.columnMap.items()]))
175             for row in self.rows])
176        #mylog.debug('serializing to json : %s'% json)
177        return json
Note: See TracBrowser for help on using the repository browser.