Package obitools :: Package obischemas :: Package kb :: Module extern
[hide private]
[frames] | no frames]

Source Code for Module obitools.obischemas.kb.extern

 1  """ 
 2  Module : KB.extern 
 3  Author : Eric Coissac 
 4  Date   : 03/05/2004 
 5   
 6  Module wrapping psycopg interface module to allow connection 
 7  to a postgresql databases with the same interface from 
 8  backend and external script. 
 9   
10  This module define a class usable from external script  
11  """ 
12   
13   
14  import psycopg2 
15  import sys 
16  from obischemas import kb 
17   
18 -class Connection(kb.Connection):
19
20 - def __init__(self,*connectParam,**kconnectParam):
21 if connectParam: 22 self.connectParam=={'dsn':connectParam} 23 else: 24 self.connectParam=kconnectParam 25 print self.connectParam 26 self.db = psycopg2.connect(**(self.connectParam))
27
28 - def restart(self):
29 ok=1 30 while (ok and ok < 1000): 31 try: 32 self.db = psycopg2.connect(**self.connectParam) 33 except: 34 ok+=1 35 else: 36 ok=0
37 38
39 - def cursor(self):
40 curs = Cursor(self.db) 41 if hasattr(self,'autocommit') and self.autocommit: 42 curs.autocommit = self.autocommit 43 return curs
44
45 - def commit(self):
46 self.db.commit()
47
48 - def rollback(self):
49 if hasattr(self,'db'): 50 self.db.rollback()
51
52 - def __del__(self):
53 if hasattr(self,'db'): 54 self.rollback()
55
56 -class Cursor(kb.Cursor):
57
58 - def __init__(self,db):
59 self.db = db 60 self.curs = db.cursor()
61
62 - def execute(self,query):
63 try: 64 self.curs.execute(query) 65 if hasattr(self,'autocommit') and self.autocommit: 66 self.db.commit() 67 except psycopg2.ProgrammingError,e: 68 print >>sys.stderr,"===> %s" % query 69 raise e 70 except psycopg2.IntegrityError,e: 71 print >>sys.stderr,"---> %s" % query 72 raise e 73 try: 74 label = [x[0] for x in self.curs.description] 75 return [dict(map(None,label,y)) 76 for y in self.curs.fetchall()] 77 except TypeError: 78 return []
79