CMS 3D CMS Logo

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