CMS 3D CMS Logo

dbUtil.py
Go to the documentation of this file.
1 import coral
2 from RecoLuminosity.LumiDB import nameDealer
3 class dbUtil(object):
4  """Class wrap up all the database operations.\n
5  """
6  def __init__( self , schema):
7  """
8  Input: coral schema handle.
9  """
10  self.__schema = schema
11 
12  def listIndex(self,tablename):
13  mytable=self.__schema.tableHandle(tablename)
14  print 'numberofindices ', mytable.description().numberOfIndices()
15  for i in range(0,mytable.description().numberOfIndices()):
16  index=mytable.description().index(i)
17  print ' ', index.name(),' -> '
18  for iColumn in index.columnNames():
19  print iColumn
20  print ' (tablespace : ',index.tableSpaceName(),')'
21  def describeSchema(self):
22  """
23  Print out the overview of the schema
24  """
25  try:
26  tablelist=self.__schema.listTables()
27  for t in tablelist:
28  table = self.__schema.tableHandle(t)
29  print 'table ===',t,'==='
30  n=table.description().numberOfColumns()
31  for i in range(0,n):
32  columndesp=table.description().columnDescription(i)
33  print '\t',columndesp.name(),columndesp.type()
34  if table.description().hasPrimaryKey():
35  print 'Primary Key : '
36  print '\t',table.description().primaryKey().columnNames()
37  print 'Indices : '
38  self.listIndex(t)
39  viewlist=self.__schema.listViews()
40  for v in viewlist:
41  myview = self.__schema.viewHandle('V0')
42  print 'definition : ',myview.definition()
43  n=myview.numberOfColumns()
44  for i in range(0,n):
45  columndesp=view.column(i)
46  print '\t',columndesp.name(),columndesp.type()
47  except Exception as e:
48  raise Exception(str(e))
49  def existRow( self, tableName, condition, conditionDefDict,conditionDict):
50  """
51  Return true if one row fulfills the selection criteria
52  """
53  try:
54  tableHandle = self.__schema.tableHandle(tableName)
55  query = tableHandle.newQuery()
56  queryBind=coral.AttributeList()
57  for colname,coltype in conditionDefDict.items():
58  queryBind.extend(colname,coltype)
59  queryBind[colname].setData(conditionDict[colname])
60  query.setCondition(condition,queryBind)
61  cursor = query.execute()
62  result=False
63  while ( next(cursor) ):
64  result=True
65  cursor.close()
66  del query
67  return result
68  except Exception as e:
69  raise Exception(str(e))
70  def insertOneRow( self, tableName, tabrowDefDict, tabrowValueDict ):
71  """
72  Insert row
73  """
74  try:
75  tableHandle = self.__schema.tableHandle(tableName)
76  editor = tableHandle.dataEditor()
77  inputData = coral.AttributeList()
78  for name,type in tabrowDefDict.items():
79  # print name, type
80  inputData.extend( name, type )
81  inputData[name].setData(tabrowValueDict[name])
82  editor.insertRow( inputData )
83  except Exception as e:
84  raise Exception('dbUtil.insertOneRow:'+str(e))
85 
86  def singleUpdate( self,tableName,setClause,updateCondition,inputData):
87  try:
88  dataEditor=self.__schema.tableHandle(tableName).dataEditor()
89  n=dataEditor.updateRows(setClause,updateCondition,inputData)
90  return n
91  except Exception as e:
92  raise RuntimeError('dbUtil.updateOneRow:'+str(e))
93 
94  def updateRows( self,tableName,updateAction,updateCondition,bindvarDef,bulkinput):
95  '''
96  update rows, note update must be ordered
97  input :
98  tableName, string
99  updateAction,string e.g. flag=:newflag
100  conditionstring, string ,e.g. runnum=:runnum and cmslsnum=:cmslsnum
101  bindvarDef,[('newflag','string'),('runnum','unsigned int'),('cmslsnum','unsigned int')]
102  bulkinput,[[('newflag','GOOD'),('runnum',1234),('cmslsnum',1)],[]]
103  '''
104  try:
105  dataEditor=self.__schema.tableHandle(tableName).dataEditor()
106  updateData=coral.AttributeList()
107  for (columnname,columntype) in bindvarDef:
108  updateData.extend(columnname,columntype)
109  bulkOperation=dataEditor.bulkUpdateRows(updateAction,updateCondition,updateData,len(bulkinput))
110  for valuelist in bulkinput:
111  for (columnname,columnvalue) in valuelist:
112  updateData[columnname].setData(columnvalue)
113  bulkOperation.processNextIteration()
114  bulkOperation.flush()
115  del bulkOperation
116  except Exception as e:
117  raise Exception('dbUtil.updateRows:'+str(e))
118  def bulkInsert( self, tableName, tabrowDef, bulkinput):
119  """
120  input:
121  tableName, string
122  tabrowDef,[('RUNNUM':'unsigned int'),('CMSLSNUM','unsigned int'),('FLAG','string'),('COMMENT','string')]
123  bulkinput,[[('RUNNUM',1234),('CMSLSNUM',1234),('FLAG','GOOD'),('COMMENT','coment')],[]]
124  """
125  try:
126  dataEditor=self.__schema.tableHandle(tableName).dataEditor()
127  insertdata=coral.AttributeList()
128  for (columnname,columntype) in tabrowDef:
129  insertdata.extend(columnname,columntype)
130  bulkOperation=dataEditor.bulkInsert(insertdata,len(bulkinput))
131  for valuelist in bulkinput:
132  for (columnname,columnvalue) in valuelist:
133 # print 'columnname ',columnname,' columnvalue ',columnvalue
134  insertdata[columnname].setData(columnvalue)
135  bulkOperation.processNextIteration()
136  bulkOperation.flush()
137  del bulkOperation
138  except:
139  raise
140 
141  def deleteRows( self, tableName, condition, conditionbindDict ):
142  """
143  Delete row(s)
144  """
145  try:
146  tableHandle = self.__schema.tableHandle(tableName)
147  editor = tableHandle.dataEditor()
148  editor.deleteRows( condition, conditionbindDict )
149  except Exception as e:
150  raise Exception(str(e))
151 
152  def dropTable( self, tableName ):
153  """
154  Drop specified table.If associated Id table exists, drop also Id table
155  """
156  try:
157  self.__schema.dropIfExistsTable( tableName )
158  self.__schema.dropIfExistsTable( nameDealer.idTableName(tableName) )
159  except Exception as e:
160  raise Exception(str(e))
161 
162  def dropAllTables( self ):
163  """
164  Drop all tables can be listed by schema.listTables
165  """
166  try:
167  for t in self.__schema.listTables():
168  self.__schema.dropTable(t)
169  except Exception as e:
170  raise Exception(str(e))
171 
172  def createTable( self,description,withIdTable=False,withEntryTables=False,withRevMapTable=False):
173  """
174  Create table if non-existing, create Id table if required
175  """
176  try:
177  tableHandle=self.__schema.createTable(description)
178  tableName=tableHandle.description().name()
179  tableHandle.privilegeManager().grantToPublic(coral.privilege_Select)
180  if withIdTable is True:
181  self.createIDTable(tableName,True)
182  if withEntryTables is True:
183  entrytableName=nameDealer.entryTableName(tableName)
184  self.createEntryTable(tableName,True)
185  self.createIDTable(entrytableName,True)
186  if withRevMapTable is True:
187  self.createRevMapTable(tableName,True)
188  except Exception as e:
189  raise RuntimeError('dbUtil.createTable'+str(e))
190 
191  def tableExists( self,tableName ):
192  """
193  Tell whether table exists
194  """
195  try:
196  self.__schema.tableHandle(tableName)
197  return True
198  except coral.Exception as e:
199  return False
200 
201  def createIDTable( self, tableName, deleteOld=True ):
202  """
203  Create ID table for the given table.\n
204  Input: name of the table which needs new associated id table
205  Output: name of the id table created
206  """
207  try:
208  idtableName=nameDealer.idTableName(tableName)
209  if deleteOld is True:
210  self.__schema.dropIfExistsTable(idtableName)
211  else:
212  if self.__schema.existsTable(idtableName):
213  print 'table '+idtableName+' exists, do nothing'
214  return
215  description = coral.TableDescription()
216  description.setName( idtableName )
217  description.setPrimaryKey( nameDealer.idTableColumnDefinition()[0] )
218  description.insertColumn( nameDealer.idTableColumnDefinition()[0], nameDealer.idTableColumnDefinition()[1])
219  idtableHandle=self.__schema.createTable( description )
220  idtableHandle.privilegeManager().grantToPublic( coral.privilege_Select )
221  inputData = coral.AttributeList()
222  editor = idtableHandle.dataEditor()
223  editor.rowBuffer( inputData )
224  inputData[ nameDealer.idTableColumnDefinition()[0] ].setData(0)
225  editor.insertRow( inputData )
226  except Exception as e:
227  raise RuntimeError('dbUtil.createIDTable'+str(e))
228 
229  def createEntryTable( self, tableName, deleteOld=True ):
230  """
231  Create Entry table for the given table.\n
232  Input: name of the table which needs new associated id table
233  Output: name of the id table created
234  """
235  try:
236  entrytableName=nameDealer.entryTableName(tableName)
237  if deleteOld is True:
238  self.__schema.dropIfExistsTable(entrytableName)
239  else:
240  if self.__schema.existsTable(entrytableName):
241  print 'table '+entrytableName+' exists, do nothing'
242  return
243  description = coral.TableDescription()
244  description.setName( entrytableName )
245  description.insertColumn( 'ENTRY_ID' ,'unsigned long long')
246  description.insertColumn( 'REVISION_ID' ,'unsigned long long')
247  description.insertColumn( 'NAME' ,'string',56,False)
248  tableHandle=self.__schema.createTable( description )
249  tableHandle.privilegeManager().grantToPublic(coral.privilege_Select)
250  except Exception as e:
251  raise RuntimeError(' dbUtil.createEntryTable '+str(e))
252 
253  def createRevMapTable( self, tableName, deleteOld=True ):
254  """
255  Create Rev table for the given table.\n
256  Input: name of the table
257  Output: name of the id table
258  """
259  try:
260  revmaptableName=nameDealer.revmapTableName(tableName)
261  if deleteOld is True:
262  self.__schema.dropIfExistsTable(revmaptableName)
263  else:
264  if self.__schema.existsTable(revmaptableName):
265  print 'table '+revmaptableName+' exists, do nothing'
266  return
267  description = coral.TableDescription()
268  description.setName( revmaptableName )
269  description.insertColumn( 'DATA_ID','unsigned long long')
270  description.insertColumn( 'REVISION_ID' ,'unsigned long long')
271  tableHandle=self.__schema.createTable( description )
272  tableHandle.privilegeManager().grantToPublic(coral.privilege_Select)
273  except Exception as e:
274  raise RuntimeError(' dbUtil.createRevMapTable '+str(e))
275 
276 if __name__ == "__main__":
277  pass
def listIndex(self, tablename)
Definition: dbUtil.py:12
def createRevMapTable(self, tableName, deleteOld=True)
Definition: dbUtil.py:253
def bulkInsert(self, tableName, tabrowDef, bulkinput)
Definition: dbUtil.py:118
def tableExists(self, tableName)
Definition: dbUtil.py:191
def dropTable(self, tableName)
Definition: dbUtil.py:152
def createIDTable(self, tableName, deleteOld=True)
Definition: dbUtil.py:201
def entryTableName(dataTableName)
Definition: nameDealer.py:103
def __init__(self, schema)
Definition: dbUtil.py:6
def existRow(self, tableName, condition, conditionDefDict, conditionDict)
Definition: dbUtil.py:49
def describeSchema(self)
Definition: dbUtil.py:21
def revmapTableName(dataTableName)
Definition: nameDealer.py:100
def idTableColumnDefinition()
Definition: nameDealer.py:97
def singleUpdate(self, tableName, setClause, updateCondition, inputData)
Definition: dbUtil.py:86
def deleteRows(self, tableName, condition, conditionbindDict)
Definition: dbUtil.py:141
def updateRows(self, tableName, updateAction, updateCondition, bindvarDef, bulkinput)
Definition: dbUtil.py:94
def dropAllTables(self)
Definition: dbUtil.py:162
def idTableName(dataTableName)
Definition: nameDealer.py:94
def createTable(self, description, withIdTable=False, withEntryTables=False, withRevMapTable=False)
Definition: dbUtil.py:172
def insertOneRow(self, tableName, tabrowDefDict, tabrowValueDict)
Definition: dbUtil.py:70
def createEntryTable(self, tableName, deleteOld=True)
Definition: dbUtil.py:229