Package install :: Package MoSTBioDat :: Package DataBase :: Package ImportData :: Package Data2DB :: Module RemoveSDict2DB
[hide private]
[frames] | no frames]

Source Code for Module install.MoSTBioDat.DataBase.ImportData.Data2DB.RemoveSDict2DB

  1  #!/usr/bin/env python 
  2  ########################################### 
  3  # removeSDict2DB.py                       # 
  4  # Remove from table ChemComp or ProtStat  # 
  5  ########################################### 
  6   
  7  ###################################################### 
  8  # Copyright (c) 2007-2008 Andrzej Bak                # 
  9  # ARC Seibersdorf & University of Silesia            # 
 10  # Author: Andrzej Bak <Andrzej.Bak@us.edu.pl>        # 
 11  # License: GNU General Public License, version: 3    # 
 12  # URL: http://chemoinformatyka.us.edu.pl/mostbiodat/ # 
 13  # Version: 1, 06.01.2010                             # 
 14  ###################################################### 
 15   
 16  try: 
 17      import sys 
 18      import os 
 19      import shelve 
 20      import anydbm 
 21      from MoSTBioDat.DataBase.ImportData.Data2DB.TaBuilder import TaBuilder 
 22      from MoSTBioDat.DataBase.ImportData.Data2DB.DBFile import DBFile 
 23      from MoSTBioDat.DataBase.Query.UserQuery.UserQuery import UserQuery 
 24      from MoSTBioDat.DataBase.Query.SQLBuilder.sqlbuilder import * 
 25      from MoSTBioDat.DataBase.Query.SQLBuilder.QueryBuilder import queryBuilder 
 26  except ImportError,e: 
 27      print 'Error: %s' %e 
 28      sys.exit(1) 
 29  ########## Remove from DataBase  class ############## 
30 -class RemoveSDict2DB(DBFile,TaBuilder):
31 """ 32 Remove data from database imported from shelve dictionary 33 INPUT: 34 host - string, host to connect 35 user - string, user to connect as 36 passwd - string, password to use 37 db - string, database to use 38 port - integer, TCP/IP port to connect 39 log - boolen, logging flag 40 unix_socket - string, location of unix_socket to use 41 conv - conversion dictionary, see MySQLdb.converters 42 connect_timeout - number of seconds to wait before the connection attempt fails. 43 compress - if set, compression is enabled 44 named_pipe - if set, a named pipe is used to connect (Windows only) 45 init_command - command which is run once the connection is created 46 read_default_file - file from which default client values are read 47 read_default_group - configuration group to use from the default file 48 cursorclass - class object, used to create cursors (keyword only) 49 use_unicode - if True, text-like columns are returned as unicode objects 50 using the connection's character set. Otherwise, text-like 51 columns are returned as strings. columns are returned as 52 normal strings. Unicode objects will always be encoded to 53 the connection's character set regardless of this setting. 54 charset - if supplied, the connection character set will be changed 55 to this character set (MySQL-4.1 and newer). This implies 56 use_unicode=True. 57 sql_mode - if supplied, the session SQL mode will be changed to this 58 setting (MySQL-4.1 and newer). For more details and legal 59 values, see the MySQL documentation. 60 client_flag - integer, flags to use or 0 61 (see MySQL docs or constants/CLIENTS.py) 62 ssl - dictionary or mapping, contains SSL connection parameters; 63 see the MySQL documentation for more details 64 (mysql_ssl_set()). If this is set, and the client does not 65 support SSL, NotSupportedError will be raised. 66 local_infile - integer, non-zero enables LOAD LOCAL INFILE; zero disables 67 format - string format for log handler 68 filter - filter object from logger object 69 datefmt - data/time format 70 path - directory path to log file 71 filename - log filename, default log 72 filemode - mode to open log file, default='a' 73 level - set root logger level to specified level 74 logfilelevel- set level to log file 75 cache - create cache for query, default=True 76 scheme2file - Boolen - save database scheme to shelve file 77 78 dictpath - str - path to dictionary 79 dictfilename - str - dictionary filename 80 dbfile - str - database file path 81 temporary - str - path to temporary dictionary file 82 log - log flag, default=False 83 84 OUTPUT: 85 class object 86 """ 87
88 - def __init__(self,dbfilepath=None,host='localhost',db='Ligand',user=None,passwd=None,port=3306,log=False,**kwargs):
89 DBFile.__init__(self,dbfile=dbfilepath,dictpath=os.path.dirname(dbfilepath),dictfilename=os.path.basename(dbfilepath),**kwargs) 90 TaBuilder.__init__(self,host,db,user,passwd,port,log,**kwargs)
91
92 - def removeTab(self,baseRemove=False):
93 """ 94 remove data from table 95 INPUT: 96 class object 97 baseRemove - boolean, True - remove from ChemComp table, default False - remove from ProtStat table 98 OUTPUT: 99 ID - id table value 100 """ 101 ## ITERATE SHELVE DICTIONARY 102 self.openDict()#open dictionary 103 counter=0 104 for dictobj in self.retDict().itervalues():#iterate object in dictionary 105 counter+=1 106 if baseRemove: 107 ChemCompID=self.ChemComp(dictobj) 108 if not ChemCompID: 109 continue 110 print 'Removing from table: ChemComp, Id: %s'%ChemCompID[0] 111 else: 112 ChemCompID=self.ProtStat(dictobj) 113 self.closeDict()#close shelve dictionary 114 self.closeDB()#close database connection
115
116 - def ChemComp(self,dictobj=None,logdebug=False):
117 """ 118 remove data from Chemical Compound table 119 INPUT: 120 class object 121 dictobj - shelve dictionary object 122 logdebug - log debug in log file 123 OUTPUT: 124 ID - id table value 125 """ 126 ### settings ########################################## 127 tablename='ChemComp' 128 tabcol=[ 'Id', 'IsoSmi','ZINCode']#table columname list 129 mapdict=['autoincrement','isosmi','filename']# mapping dictionary object attributes 130 ######################################################## 131 if not dictobj: 132 print 'Error: Missing dictionary object!' 133 self.log.error('%s: Missing dictionary object',tablename) 134 sys.exit(1) 135 ## check if dictionary object has specified attributes 136 if not dictobj.hasAttr('isosmi'): 137 if logdebug: 138 self.log.debug('%s: Missing isosmi attribute: %s',tablename,dictobj.kwargs['filename']) 139 return 0 140 select='Select([table.'+ tablename +'.Id], where=OR(table.'+tablename+'.'+tabcol[1]+'==dictobj.kwargs[\''+mapdict[1]+'\']))' 141 sql=queryBuilder(eval(select))#build query 142 result=self.executeQuery(sql)#execute query 143 if result:#if record exists in table 144 ID=[]##get ID 145 for resitem in result:#iterate result dictionary 146 ID.append(resitem['Id'])#output ID list 147 sql=UserQuery().delRecord(tablename,'Id',ID[0]) 148 result=self.executeQuery(sql)#execute query 149 sql='SELECT max(Id) AS maxId from %s;'%tablename 150 result=self.executeQuery(sql)#execute query 151 if result:#if record exists in table 152 maxID=[]##get ID 153 for resitem in result:#iterate result dictionary 154 maxID.append(resitem['maxId'])#output ID list 155 sql='ALTER TABLE %s AUTO_INCREMENT=%s;'%(tablename,maxID[0]) 156 self.executeQuery(sql)#execute query 157 return ID 158 else: 159 return 0
160
161 - def ProtStat(self,dictobj=None,logdebug=False):
162 """ 163 remove data from Protomer/Tautomer table 164 INPUT: 165 class object 166 dictobj - shelve dictionary object 167 logdebug - log debug in log file 168 OUTPUT: 169 ID - id table value 170 """ 171 ### settings ########################################## 172 tablename='ProtStat' 173 tabcol=[ 'Id', 'IsoSmi','ChemCompIdFk']#table columname list 174 mapdict=['autoincrement','isosmi','ID']# mapping dictionary object attributes 175 ######################################################## 176 if not dictobj: 177 print 'Error: Missing dictionary object!' 178 self.log.error('%s: Missing dictionary object',tablename) 179 sys.exit(1) 180 ## check if dictionary object has specified attributes 181 if not dictobj.hasAttr('isosmi'): 182 if logdebug: 183 self.log.debug('%s: Missing isosmi attribute: %s',tablename,dictobj.kwargs['filename']) 184 return 0 185 select='Select([table.'+ tablename +'.Id], where=AND(table.'+tablename+'.'+tabcol[1]+'==dictobj.kwargs[\''+mapdict[1]+'\']))' 186 sql=queryBuilder(eval(select))#build query 187 result=self.executeQuery(sql)#execute query 188 if result:#if record exists in table 189 ID=[]##get ID 190 for resitem in result:#iterate result dictionary 191 ID.append(resitem['Id'])#output ID list 192 sql=UserQuery().delRecord(tablename,'Id',ID[0]) 193 result=self.executeQuery(sql)#execute query 194 sql='SELECT max(Id) AS maxId from %s;'%tablename 195 result=self.executeQuery(sql)#execute query 196 if result:#if record exists in table 197 maxID=[]##get ID 198 for resitem in result:#iterate result dictionary 199 maxID.append(resitem['maxId'])#output ID list 200 sql='ALTER TABLE %s AUTO_INCREMENT=%s;'%(tablename,maxID[0]) 201 self.executeQuery(sql)#execute query 202 return ID 203 else: 204 return 0
205 ################## End of class ######################################################## 206 ############## MAIN ################################################################ 207 ############ Example of usage ########################################################## 208 if __name__=='__main__': 209 pass 210 # print '*** Remove data from ZINC shelve dictionary *** ' 211 # ############ Remove data from database ################################# 212 # A=RemoveSDict2DB(dbfilepath='/tmp/InpuTest/ZINCStdInp', 213 # path='/tmp/Log',filename='RemoveTest', 214 # host='localhost',db='',user='',passwd='',log=False) 215 # A.removeTab(baseRemove=True) 216 # A.removeTab(baseRemove=False) 217