source: timingandestimationplugin/branches/trac1.0-Permissions/timingandestimationplugin/dbhelper.py

Last change on this file was 17249, checked in by Russ Tyndall, 5 years ago

Change db backend import stuff to allow running without all backends installed re #13462

File size: 6.8 KB
RevLine 
[11738]1import trac.db.pool
[17249]2SqliteCon, PGCon, MySqlCon = None,None,None
3try:
4    import trac.db.sqlite_backend
5    SqliteCon = trac.db.sqlite_backend.SQLiteConnection
6except:
7    pass
8try:
9    import trac.db.postgres_backend
10    PGCon = trac.db.postgres_backend.PostgreSQLConnection
11except:
12    pass
13try:
14    import trac.db.mysql_backend
15    MySqlCon = trac.db.mysql_backend.MySQLConnection
16except:
17    pass
[1119]18
[17249]19
[11738]20def is_db_type(db, typeToVerify):
21    cnx = db.cnx
22    t = type(cnx)
23    if t == trac.db.pool.PooledConnection:
24        t = type(cnx.cnx)
25    return typeToVerify == t
26
[8141]27def get_all(env, sql, *params):
[1119]28    """Executes the query and returns the (description, data)"""
[16688]29    with env.db_query as db:
30        cur = db.cursor()
31        desc = None
32        data = None
33        try:
34            cur.execute(sql, params)
35            data = list(cur.fetchall())
36            desc = cur.description
37        except Exception, e:
38            env.log.exception('There was a problem executing sql:%s \n \
39    with parameters:%s\nException:%s' % (sql, params, e))
[1119]40    return (desc, data)
41
[8141]42def execute_non_query(env, sql, *params):
[1119]43    """Executes the query on the given project"""
[8141]44    execute_in_trans(env, (sql, params))
45   
46def get_first_row(env, sql,*params):
[2824]47    """ Returns the first row of the query results as a tuple of values (or None)"""
[16688]48    data = None
49    with env.db_query as db:
50        cur = db.cursor()
51        try:
52            cur.execute(sql, params)
53            data = cur.fetchone();
54        except Exception, e:
55            env.log.exception('There was a problem executing sql:%s \n \
56            with parameters:%s\nException:%s' % (sql, params, e))
57    return data
[1119]58
[8141]59def get_scalar(env, sql, col=0, *params):
[2824]60    """ Gets a single value (in the specified column) from the result set of the query"""
[8141]61    data = get_first_row(env, sql, *params);
[2824]62    if data:
63        return data[col]
64    else:
65        return None;
[2785]66
[8141]67def execute_in_trans(env, *args):
[3119]68    result = True
[8141]69    c_sql =[None]
70    c_params = [None]
[1119]71    try:
[16688]72        with env.db_transaction as db:
[8141]73            cur = db.cursor()
74            for sql, params in args:
75                c_sql[0] = sql
76                c_params[0] = params
77                cur.execute(sql, params)
[8193]78    except Exception, e :
[8141]79        env.log.exception('There was a problem executing sql:%s \n \
[16688]80    with parameters:%s\nException:%s' % (c_sql[0], c_params[0], e));
[8193]81        raise e
[3119]82    return result
[1365]83
[8193]84def execute_in_nested_trans(env, name, *args):
85    result = True
86    c_sql =[None]
87    c_params = [None]
[16688]88    with self.env.db_transaction as db:
[9701]89        cur = None
90        try:
[8193]91            cur = db.cursor()
92            cur.execute("SAVEPOINT %s" % name)
93            for sql, params in args:
94                c_sql[0] = sql
95                c_params[0] = params
96                cur.execute(sql, params)
97            cur.execute("RELEASE SAVEPOINT %s" % name)
[9701]98        except Exception, e :
99            cur.execute("ROLLBACK TO SAVEPOINT %s" % name)
100            env.log.exception('There was a problem executing sql:%s \n \
[8193]101    with parameters:%s\nException:%s'%(c_sql[0], c_params[0], e));
[9701]102            raise e
[8193]103    return result
104
[11059]105def current_schema (env):
[16688]106    with env.db_query as db:
[17249]107        if is_db_type(db, SqliteCon):
[16688]108            return None
[17249]109        elif is_db_type(db, MySqlCon):
[16688]110            return get_scalar(env, 'SELECT schema();')
[17249]111        elif is_db_type(db, PGCon):
[16688]112            return get_scalar(env, 'SHOW search_path;')
[11059]113
[11260]114def _prep_schema(s):
[11383]115    #remove double quotes, escape single quotes
116    if not s: return "'<NOT VALID>'"
117    return ','.join(("'"+i.replace('"','').replace("'","''")+"'"
[11260]118                     for i in s.split(',')))
119
[8141]120def db_table_exists(env,  table):
[16688]121    cnt = 0
122    with env.db_query as db:
[17249]123        if is_db_type(db, SqliteCon):
[16688]124            sql = "select count(*) from sqlite_master where type = 'table' and name = %s"
125            cnt = get_scalar(env, sql, 0, table)
126        else:
127            sql = """SELECT count(*) FROM information_schema.tables
128                     WHERE table_name = %%s and table_schema in (%s)
129                  """ % _prep_schema(current_schema(env))
130            cnt = get_scalar(env, sql, 0, table)
131    return cnt
[1119]132
[8141]133def get_column_as_list(env, sql, col=0, *params):
134    data = get_all(env, sql, *params)[1] or ()
[2893]135    return [valueList[col] for valueList in data]
[1119]136
[8141]137def get_system_value(env, key):
138    return get_scalar(env, "SELECT value FROM system WHERE name=%s", 0, key)
[1119]139
[8141]140def set_system_value(env, key, value):
141    if get_system_value(env, key):
142        execute_non_query(env, "UPDATE system SET value=%s WHERE name=%s", value, key)       
[2774]143    else:
[8141]144        execute_non_query(env, "INSERT INTO system (value, name) VALUES (%s, %s)",
[2774]145            value, key)
146
147
[8141]148def get_result_set(env, sql, *params):
[1119]149    """Executes the query and returns a Result Set"""
[8141]150    tpl = get_all(env, sql, *params);
[3119]151    if tpl and tpl[0] and tpl[1]:
152        return ResultSet(tpl)
153    else:
154        return None
[1119]155
[2349]156
[1119]157class ResultSet:
158    """ the result of calling getResultSet """
159    def __init__ (self, (columnDescription, rows)):
[8141]160        self.columnDescription, self.rows = columnDescription, rows
[1119]161        self.columnMap = self.get_column_map()
162
163    def get_column_map ( self ):
164        """This function will take the result set from getAll and will
165        return a hash of the column names to their index """
166        h = {}
167        i = 0
168        if self.columnDescription:
169            for col in self.columnDescription:
170                h[ col[0] ] = i
171                i+=1
172        return h;
[8141]173   
[1119]174    def value(self, col, row ):
175        """ given a row(list or idx) and a column( name or idx ), retrieve the appropriate value"""
176        tcol = type(col)
177        trow = type(row)
178        if tcol == str:
179            if(trow == list or trow == tuple):
180                return row[self.columnMap[col]]
181            elif(trow == int):
182                return self.rows[row][self.columnMap[col]]
183            else:
184                print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
185        elif tcol == int:
186            if(trow == list or trow == tuple):
187                return row[col]
188            elif(trow == int):
189                return self.rows[row][col]
190            else:
191                print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
192        else:
193            print ("rs.value Type Failed col:%s  row:%s" % (type(col), type(row)))
[8141]194   
[3119]195    def json_out(self):
196        json = "[%s]" % ',\r\n'. join(
197            [("{%s}" % ','.join(
198            ["'%s':'%s'" %
[8141]199             (key, unicode(self.value(val, row)).
[3119]200              replace("'","\\'").
201              replace('"','\\"').
202              replace('\r','\\r').
203              replace('\n','\\n'))
204             for (key, val) in self.columnMap.items()]))
205             for row in self.rows])
206        #mylog.debug('serializing to json : %s'% json)
207        return json
Note: See TracBrowser for help on using the repository browser.