CMS 3D CMS Logo

conddblib.py
Go to the documentation of this file.
1 '''CMS Conditions DB Python library.
2 '''
3 
4 __author__ = 'Miguel Ojeda'
5 __copyright__ = 'Copyright 2013, CERN'
6 __credits__ = ['Giacomo Govi', 'Miguel Ojeda', 'Andreas Pfeiffer']
7 __license__ = 'Unknown'
8 __maintainer__ = 'Giacomo Govi'
9 __email__ = 'mojedasa@cern.ch'
10 
11 
12 import os
13 import hashlib
14 import logging
15 
16 import sqlalchemy
17 import sqlalchemy.ext.declarative
18 import enum
19 from sqlalchemy import Enum
20 
21 schema_name = 'CMS_CONDITIONS'
22 dbuser_name = 'cms_conditions'
23 dbreader_user_name = 'cms_cond_general_r'
24 dbwriter_user_name = 'cms_cond_general_w'
25 logger = logging.getLogger(__name__)
26 
27 #authentication/authorization params
28 authPathEnvVar = 'COND_AUTH_PATH'
29 dbkey_filename = 'db.key'
30 dbkey_folder = os.path.join('.cms_cond',dbkey_filename)
31 
32 # frontier services
33 PRO ='PromptProd'
34 ARC ='FrontierArc'
35 INT ='FrontierInt'
36 DEV ='FrontierPrep'
37 # oracle read only services
38 ORAPRO = 'cms_orcon_adg'
39 ORAARC = 'cmsarc_lb'
40 # oracle masters
41 ORAINT = 'cms_orcoff_int'
42 ORADEV = 'cms_orcoff_prep'
43 ONLINEORAPRO = 'cms_orcon_prod'
44 ONLINEORAINT = 'cmsintr_lb'
45 
46 # Set initial level to WARN. This so that log statements don't occur in
47 # the absense of explicit logging being enabled.
48 if logger.level == logging.NOTSET:
49  logger.setLevel(logging.WARN)
50 
51 # Utility functions
52 def hash(data):
53  return hashlib.sha1(data.encode('ascii')).hexdigest()
54 
55 
56 # Constants
57 empty_label = '-'
58 
59 name_length = 100
60 description_length = 4000
61 hash_length = len(hash(''))
62 
63 web_experts_email = 'cms-cond-dev@cern.ch'
64 offline_db_experts_email = 'cms-offlinedb-exp@cern.ch'
65 offline_db_experts_phone = '+41 22 76 70817, or 70817 from CERN; check https://twiki.cern.ch/twiki/bin/viewauth/CMS/DBShifterHelpPage if it does not work; availability depends on the state of the LHC'
66 
67 contact_help = 'If you need assistance, please write an email to %s and %s. If you need immediate/urgent assistance, you can call the Offline DB expert on call (%s).' % (offline_db_experts_email, web_experts_email, offline_db_experts_phone)
68 database_help = '''
69  The database parameter (--db) refers to the database where the tool
70  will connect to read all the data. By default, the production account
71  (through Frontier) will be used.
72 
73  In subcommands which take a source and a destination, --db always refers to
74  the source, and --destdb to the destination. For both of them the following
75  rules apply.
76 
77  The database parameter can be an official alias, a filename or any
78  valid SQLAlchemy URL.
79 
80  The official aliases are the following strings (first column):
81 
82  Alias Level Database RO/RW Notes
83  ------------ ----------- ------------- ---------- -------------------------------
84 
85  pro Production Frontier (ADG) read-only Default.
86  arc Archive Frontier read-only
87  int Integration Frontier read-only
88  dev Development Frontier read-only
89  boost Production Frontier read-only
90  boostprep Development Frontier read-only
91 
92  orapro Production Oracle (ADG) read-only Password required.
93  oraarc Archive Oracle read-only Password required.
94  oraint Integration Oracle read-write Password required.
95  oradev Development Oracle read-write Password required.
96 
97  onlineorapro Production Oracle read-write Password required. Online only.
98  onlineoraint Online Int Oracle read-write Password required. Online only.
99 
100  Most of the time, if you are a regular user, you will want to read/copy
101  conditions from the Frontier production account. Therefore, you can omit
102  the --db parameter, unless you want to read from somewhere else,
103  e.g. from your local SQLite file.
104 
105  In addition, the parameter may be a filename (path) pointing to a local
106  SQLite file, e.g.
107 
108  file.db
109  relative/path/to/file.db
110  /absolute/path/to/file.db
111 
112  Finally, any valid SQLAlchemy URL can be used. This allows full
113  flexibility in cases where it may be needed, e.g.
114 
115  sqlite:// In-memory, volatile SQLite DB.
116  oracle://user@devdb11 Your private Oracle DB in devdb11 [*]
117 
118  [*] See https://account.cern.ch/ -> Services for more information
119  on personal Oracle accounts.
120 
121  For the official aliases, the password will be asked automatically
122  interactively. The same applies for Oracle URLs where the password
123  was not provided inside it, e.g.:
124 
125  oracle://user@devdb11 The tool will prompt you for the password.
126  oracle://user:pass@devdb11 Password inlined. [+]
127 
128  [+] Caution: Never write passwords in command-line parameters in
129  multi-user machines (e.g. lxplus), since other users can see them
130  in the process table (e.g. ps).
131 
132  This means that both the official aliases and the filenames are shortcuts
133  to the full SQLAlchemy URL equivalents, e.g. the following are the same:
134 
135  relative/path/to/file.db === sqlite:///relative/path/to/file.db
136  /absolute/path/to/file.db === sqlite:////absolute/path/to/file.db
137 '''
138 
139 def oracle_connection_string(db_service, db_schema ):
140  return 'oracle://%s/%s'%(db_service,db_schema)
141 
142 class Synchronization(enum.Enum):
143  any = 'any'
144  validation = 'validation'
145  mc = 'mc'
146  runmc = 'runmc'
147  hlt = 'hlt'
148  express = 'express'
149  prompt = 'prompt'
150  pcl = 'pcl'
151  offline = 'offline'
152 
153 class TimeType(enum.Enum):
154  Run = 'Run'
155  Time = 'Time'
156  Lumi = 'Lumi'
157  Hash = 'Hash'
158  User = 'User'
159 
160 
161 # Schema definition
162 _Base = sqlalchemy.ext.declarative.declarative_base()
163 
164 def fq_name( schema_name, table_name ):
165  name = table_name
166  if schema_name is not None:
167  name = '%s.%s' %(schema_name, table_name)
168  return name
169 
170 db_models = {}
171 
172 class _Col(Enum):
173  nullable = 0
174  notNull = 1
175  pk = 2
176 
177 class DbRef:
178  def __init__(self,refType, refColumn):
179  self.rtype = refType
180  self.rcol = refColumn
181 
182 def fq_col( schema, table, column ):
183  fqn = '%s.%s' %(table, column)
184  if schema is not None:
185  fqn = '%s.%s' %(schema,fqn)
186  return fqn
187 
188 def make_dbtype( backendName, schemaName, baseType ):
189  members = {}
190  deps_reg = set()
191  dbtype_name = '%s_%s' %(baseType.__name__,backendName)
192  members['__tablename__'] = baseType.__tablename__
193  members['__table_args__'] = None
194  if schemaName is not None:
195  members['__table_args__'] = {'schema': schemaName }
196  for k,v in baseType.columns.items():
197  if isinstance(v[0],DbRef):
198  refColDbt = v[0].rtype.columns[v[0].rcol][0]
199  pk = (True if v[1]==_Col.pk else False)
200  if v[1]==_Col.pk:
201  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),primary_key=True)
202  else:
203  nullable = (False if v[1] == _Col.notNull else True)
204  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),nullable=nullable)
205  if v[0].rtype.__name__ not in deps_reg:
206  deps_reg.add(v[0].rtype.__name__)
207  reftype_name = '%s_%s' %(v[0].rtype.__name__,backendName)
208  members[(v[0].rtype.__name__).lower()] = sqlalchemy.orm.relationship(reftype_name)
209  else:
210  if v[1]==_Col.pk:
211  members[k] = sqlalchemy.Column(v[0],primary_key=True)
212  else:
213  nullable = (True if v[1]==_Col.nullable else False)
214  members[k] = sqlalchemy.Column(v[0],nullable=nullable)
215  dbType = type(dbtype_name,(_Base,),members)
216 
217  if backendName not in db_models.keys():
218  db_models[backendName] = {}
219  db_models[backendName][baseType.__name__] = dbType
220  return dbType
221 
222 def getSchema(tp):
223  if tp.__table_args__ is not None:
224  return tp.__table_args__['schema']
225  return None
226 
227 class Tag:
228  __tablename__ = 'TAG'
229  columns = { 'name': (sqlalchemy.String(name_length),_Col.pk),
230  'time_type': (sqlalchemy.Enum(*tuple(TimeType.__members__.keys())),_Col.notNull),
231  'object_type': (sqlalchemy.String(name_length),_Col.notNull),
232  'synchronization': (sqlalchemy.Enum(*tuple(Synchronization.__members__.keys())),_Col.notNull),
233  'description': (sqlalchemy.String(description_length),_Col.notNull),
234  'last_validated_time':(sqlalchemy.BIGINT,_Col.notNull),
235  'end_of_validity':(sqlalchemy.BIGINT,_Col.notNull),
236  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
237  'modification_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
238 
240  __tablename__ = 'TAG_METADATA'
241  columns = { 'tag_name': (DbRef(Tag,'name'),_Col.pk),
242  'min_serialization_v': (sqlalchemy.String(20),_Col.notNull),
243  'min_since': (sqlalchemy.BIGINT,_Col.notNull),
244  'modification_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
245 
246 class Payload:
247  __tablename__ = 'PAYLOAD'
248  columns = { 'hash': (sqlalchemy.CHAR(hash_length),_Col.pk),
249  'object_type': (sqlalchemy.String(name_length),_Col.notNull),
250  'data': (sqlalchemy.BLOB,_Col.notNull),
251  'streamer_info':(sqlalchemy.BLOB,_Col.notNull),
252  'version':(sqlalchemy.String(20),_Col.notNull),
253  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
254 
255 
256 class IOV:
257  __tablename__ = 'IOV'
258  columns = { 'tag_name':(DbRef(Tag,'name'),_Col.pk),
259  'since':(sqlalchemy.BIGINT,_Col.pk),
260  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.pk),
261  'payload_hash':(DbRef(Payload,'hash'),_Col.notNull) }
262 
263 
264 class GlobalTag:
265  __tablename__ = 'GLOBAL_TAG'
266  columns = { 'name':(sqlalchemy.String(name_length),_Col.pk),
267  'validity': (sqlalchemy.BIGINT,_Col.notNull),
268  'description':(sqlalchemy.String(description_length),_Col.notNull),
269  'release':(sqlalchemy.String(name_length),_Col.notNull),
270  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
271  'snapshot_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
272 
274  __tablename__ = 'GLOBAL_TAG_MAP'
275  columns = { 'global_tag_name':(DbRef(GlobalTag,'name'),_Col.pk),
276  'record':(sqlalchemy.String(name_length),_Col.pk),
277  'label':(sqlalchemy.String(name_length),_Col.pk),
278  'tag_name':(DbRef(Tag,'name'),_Col.notNull) }
279 
280 
281 
282 class TagLog:
283  __tablename__ = 'TAG_LOG'
284  columns = { 'tag_name':(DbRef(Tag,'name'),_Col.pk),
285  'event_time':(sqlalchemy.TIMESTAMP,_Col.pk),
286  'action':(sqlalchemy.String(100),_Col.pk),
287  'user_name':(sqlalchemy.String(100),_Col.notNull),
288  'host_name':(sqlalchemy.String(100),_Col.notNull),
289  'command':(sqlalchemy.String(500),_Col.notNull),
290  'user_text':(sqlalchemy.String(4000),_Col.notNull) }
291 
292 class RunInfo:
293  __tablename__ = 'RUN_INFO'
294  columns = { 'run_number':(sqlalchemy.BIGINT,_Col.pk),
295  'start_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
296  'end_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
297 
299  __tablename__ = 'BOOST_RUN_MAP'
300  columns = { 'run_number':(sqlalchemy.BIGINT,_Col.pk),
301  'run_start_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
302  'boost_version': (sqlalchemy.String(20),_Col.notNull) }
303 
304 # CondDB object
306 
307  def __init__(self, url):
308  # Workaround to avoid creating files if not present.
309  # Python's sqlite3 module does not use sqlite3_open_v2(),
310  # and therefore we cannot disable SQLITE_OPEN_CREATE.
311  # Only in the case of creating a new database we skip the check.
312  if url.drivername == 'sqlite':
313 
314  self.engine = sqlalchemy.create_engine(url)
315 
316  enabled_foreign_keys = self.engine.execute('pragma foreign_keys').scalar()
317  supports_foreign_keys = enabled_foreign_keys is not None
318  if not supports_foreign_keys:
319  logger.warning('Your SQLite database does not support foreign keys, so constraints will not be checked. Please upgrade.')
320  elif not enabled_foreign_keys:
321  self.engine.execute('pragma foreign_keys = on')
322 
323  else:
324  self.engine = sqlalchemy.create_engine(url)
325 
326  self._session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=self.engine))
327 
328  self._is_frontier = url.drivername == 'oracle+frontier'
329  self._is_oracle = url.drivername == 'oracle'
330  self._is_sqlite = url.drivername == 'sqlite'
331 
332  self._is_read_only = self._is_frontier or url.host in {
333  'cms_orcon_adg',
334  'cmsarc_lb',
335  }
336 
337  self._is_official = self._is_frontier or url.host in {
338  'cms_orcon_adg',
339  'cmsarc_lb',
340  'cms_orcoff_int',
341  'cms_orcoff_prep',
342  'cms_orcon_prod',
343  'cmsintr_lb',
344  }
345  self._url = url
346  self._backendName = ('sqlite' if self._is_sqlite else 'oracle' )
347  self._schemaName = ( None if self._is_sqlite else schema_name )
348  logging.debug('Loading db types...')
349  self.get_dbtype(Tag).__name__
350  self.get_dbtype(Payload)
351  self.get_dbtype(IOV)
352  self.get_dbtype(TagLog)
353  self.get_dbtype(GlobalTag)
354  self.get_dbtype(GlobalTagMap)
355  self.get_dbtype(RunInfo)
356  if not self._is_sqlite:
357  self.get_dbtype(TagMetadata)
358  self.get_dbtype(BoostRunMap)
359  self._is_valid = self.is_valid()
360 
361  def get_dbtype(self,theType):
362  basename = theType.__name__
363  if self._backendName not in db_models.keys() or basename not in db_models[self._backendName].keys():
364  return make_dbtype( self._backendName, self._schemaName, theType )
365  else:
366  return db_models[self._backendName][basename]
367 
368  def session(self):
369  s = self._session()
370  s.get_dbtype = self.get_dbtype
371  s._is_sqlite = self._is_sqlite
372  s.is_oracle = self.is_oracle
373  s._url = self._url
374  return s
375 
376  @property
377  def metadata(self):
378  return _Base.metadata
379 
380  @property
381  def is_frontier(self):
382  return self._is_frontier
383 
384  @property
385  def is_oracle(self):
386  return self._is_oracle
387 
388  @property
389  def is_sqlite(self):
390  return self._is_sqlite
391 
392  @property
393  def is_read_only(self):
394  return self._is_read_only
395 
396  @property
397  def is_official(self):
398  return self._is_official
399 
400  def is_valid(self):
401  '''Tests whether the current DB looks like a valid CMS Conditions one.
402  '''
403  engine_connection = self.engine.connect()
404  # temporarely avoid the check on the GT tables - there are releases in use where C++ does not create these tables.
405  _Tag = self.get_dbtype(Tag)
406  _IOV = self.get_dbtype(IOV)
407  _Payload = self.get_dbtype(Payload)
408  ret = all([self.engine.dialect.has_table(engine_connection, table.__tablename__,getSchema(table)) for table in [_Tag, _IOV, _Payload]])
409  engine_connection.close()
410  return ret
411 
412  def init(self, drop=False):
413  '''Initializes a database.
414  '''
415  logging.info('Initializing database...')
416  if drop:
417  logging.debug('Dropping tables...')
418  self.metadata.drop_all(self.engine)
419  self._is_valid = False
420  else:
421  if not self._is_valid:
422  logging.debug('Creating tables...')
423  self.get_dbtype(Tag).__table__.create(bind = self.engine)
424  self.get_dbtype(Payload).__table__.create(bind = self.engine)
425  self.get_dbtype(IOV).__table__.create(bind = self.engine)
426  self.get_dbtype(TagLog).__table__.create(bind = self.engine)
427  self.get_dbtype(GlobalTag).__table__.create(bind = self.engine)
428  self.get_dbtype(GlobalTagMap).__table__.create(bind = self.engine)
429  self._is_valid = True
430 
431 def getSessionOnMasterDB( session1, session2 ):
432  key = '%s/%s'
433  sessiondict = { }
434  sessiondict[key %(session1._url.drivername,session1._url.host)] = session1
435  sessiondict[key %(session2._url.drivername,session2._url.host)] = session2
436  masterkey = key %('oracle',ONLINEORAPRO)
437  if masterkey in sessiondict.keys():
438  return sessiondict[masterkey]
439  adgkey = key %('oracle',ORAPRO)
440  if adgkey in sessiondict.keys():
441  return sessiondict[adgkey]
442  frontierkey = key %('frontier',PRO)
443  if frontierkey in sessiondict.keys():
444  return sessiondict[frontierkey]
445  # default case: frontier on pro
446  conn = Connection(make_url())
447  session = conn.session()
448  # is it required?
449  session._conn = conn
450  return session
451 
452 # Connection helpers
454  import subprocess
455  return subprocess.Popen(['cmsGetFnConnect', 'frontier://%s' % database], stdout = subprocess.PIPE).communicate()[0].strip()
456 
457 def _getCMSSQLAlchemyConnectionString(technology,service,schema_name):
458  if technology == 'frontier':
459  import urllib
460  import sys
461  py3k = sys.version_info >= (3, 0)
462  if py3k:
463  return '%s://@%s/%s' % ('oracle+frontier', urllib.parse.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
464  else:
465  return '%s://@%s/%s' % ('oracle+frontier', urllib.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
466  elif technology == 'oracle':
467  return '%s://%s@%s' % (technology, schema_name, service)
468 
469 # Entry point
470 def make_url(database='pro',read_only = True):
471  if database.startswith('sqlite:') or database.startswith('sqlite_file:'):
472  ignore, database = database.split(':',1)
473 
474  if ':' in database and '://' not in database: # check if we really got a shortcut like "pro:<schema>" (and not a url like proto://...), if so, disentangle
475  database, schema = database.split(':')
476 
477  officialdbs = {
478  # frontier
479  'pro' : ('frontier','PromptProd', { 'R': schema_name }, ),
480  'arc' : ('frontier','FrontierArc', { 'R': schema_name }, ),
481  'int' : ('frontier','FrontierInt', { 'R': schema_name }, ),
482  'dev' : ('frontier','FrontierPrep', { 'R': schema_name }, ),
483  # oracle adg
484  'orapro': ('oracle', 'cms_orcon_adg', { 'R': dbreader_user_name }, ),
485  'oraarc': ('oracle', 'cmsarc_lb', { 'R': dbreader_user_name }, ),
486  # oracle masters
487  'oraint': ('oracle', 'cms_orcoff_int', { 'R': dbreader_user_name,
488  'W': dbwriter_user_name }, ),
489  'oradev': ('oracle', 'cms_orcoff_prep', { 'R': dbreader_user_name,
490  'W': dbwriter_user_name }, ),
491  'onlineorapro': ('oracle', 'cms_orcon_prod', { 'R': dbreader_user_name,
492  'W': dbwriter_user_name }, ),
493  'onlineoraint': ('oracle', 'cmsintr_lb', { 'R': dbreader_user_name,
494  'W': dbwriter_user_name }, ),
495  }
496 
497  if database in officialdbs.keys():
498  key = ('R' if read_only else 'W')
499  mapping = officialdbs[database]
500  tech = mapping[0]
501  service = mapping[1]
502  schema_dict = mapping[2]
503  if key in schema_dict.keys():
504  database = _getCMSSQLAlchemyConnectionString(tech,service,schema_dict[key])
505  else:
506  raise Exception("Read-only database %s://%s cannot be accessed in update mode." %(tech,service))
507 
508  logging.debug('connection string set to "%s"' % database)
509 
510  try:
511  url = sqlalchemy.engine.url.make_url(database)
512  except sqlalchemy.exc.ArgumentError:
513  url = sqlalchemy.engine.url.make_url('sqlite:///%s' % database)
514  return url
515 
516 def connect(url, authPath=None, verbose=0):
517  '''Returns a Connection instance to the CMS Condition DB.
518 
519  See database_help for the description of the database parameter.
520 
521  The verbosity level is as follows:
522 
523  0 = No output (default).
524  1 = SQL statements issued, including their parameters.
525  2 = In addition, results of the queries (all rows and the column headers).
526  '''
527 
528  if url.drivername == 'oracle':
529  if url.username is None:
530  logging.error('Could not resolve the username for the connection %s. Please provide a connection in the format oracle://[user]:[pass]@[host]' %url )
531  raise Exception('Connection format error: %s' %url )
532  if url.password is None:
533  if authPath is None:
534  if authPathEnvVar in os.environ:
535  authPath = os.environ[authPathEnvVar]
536  explicit_auth = False
537  if authPath is not None:
538  dbkey_path = os.path.join(authPath,dbkey_folder)
539  if not os.path.exists(dbkey_path):
540  authFile = os.path.join(authPath,'.netrc')
541  if os.path.exists(authFile):
542  entryKey = url.host.lower()+"/"+url.username.lower()
543  logging.debug('Looking up credentials for %s in file %s ' %(entryKey,authFile) )
544  import netrc
545  params = netrc.netrc( authFile ).authenticators(entryKey)
546  if params is not None:
547  (username, account, password) = params
548  url.username = username
549  url.password = password
550  else:
551  msg = 'The entry %s has not been found in the .netrc file.' %entryKey
552  raise TypeError(msg)
553  else:
554  explicit_auth =True
555  else:
556  import pluginCondDBPyBind11Interface as credential_store
557  connect_for_update = ( url.username == dbwriter_user_name )
558  connection_string = oracle_connection_string(url.host.lower(),schema_name)
559  logging.debug('Using db key to get credentials for %s' %connection_string )
560  (username,password) = credential_store.get_db_credentials(connection_string,connect_for_update,authPath)
561  url.username = username
562  url.password = password
563  else:
564  import getpass
565  pwd = getpass.getpass('Password for %s: ' % str(url))
566  if pwd is None or pwd == '':
567  pwd = getpass.getpass('Password for %s: ' % str(url))
568  if pwd is None or pwd == '':
569  raise Exception('Empty password provided, bailing out...')
570  url.password = pwd
571 
572  if verbose >= 1:
573  logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
574 
575  if verbose >= 2:
576  logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
577 
578  return Connection(url)
579 
580 
581 def _exists(session, primary_key, value):
582  ret = None
583  try:
584  ret = session.query(primary_key).\
585  filter(primary_key == value).\
586  count() != 0
587  except sqlalchemy.exc.OperationalError:
588  pass
589 
590  return ret
591 
592 def _inserted_before(timestamp):
593  '''To be used inside filter().
594  '''
595 
596  if timestamp is None:
597  # XXX: Returning None does not get optimized (skipped) by SQLAlchemy,
598  # and returning True does not work in Oracle (generates "and 1"
599  # which breaks Oracle but not SQLite). For the moment just use
600  # this dummy condition.
601  return sqlalchemy.literal(True) == sqlalchemy.literal(True)
602 
603  return conddb.IOV.insertion_time <= _parse_timestamp(timestamp)
604 
605 def listObject(session, name, snapshot=None):
606 
607  is_tag = _exists(session, Tag.name, name)
608  result = {}
609  if is_tag:
610  result['type'] = 'Tag'
611  result['name'] = session.query(Tag).get(name).name
612  result['timeType'] = session.query(Tag.time_type).\
613  filter(Tag.name == name).\
614  scalar()
615 
616  result['iovs'] = session.query(IOV.since, IOV.insertion_time, IOV.payload_hash, Payload.object_type).\
617  join(IOV.payload).\
618  filter(
619  IOV.tag_name == name,
620  _inserted_before(snapshot),
621  ).\
622  order_by(IOV.since.desc(), IOV.insertion_time.desc()).\
623  from_self().\
624  order_by(IOV.since, IOV.insertion_time).\
625  all()
626 
627  try:
628  is_global_tag = _exists(session, GlobalTag.name, name)
629  if is_global_tag:
630  result['type'] = 'GlobalTag'
631  result['name'] = session.query(GlobalTag).get(name)
632  result['tags'] = session.query(GlobalTagMap.record, GlobalTagMap.label, GlobalTagMap.tag_name).\
633  filter(GlobalTagMap.global_tag_name == name).\
634  order_by(GlobalTagMap.record, GlobalTagMap.label).\
635  all()
636  except sqlalchemy.exc.OperationalError:
637  sys.stderr.write("No table for GlobalTags found in DB.\n\n")
638 
639  if not is_tag and not is_global_tag:
640  raise Exception('There is no tag or global tag named %s in the database.' % name)
641 
642  return result
643 
644 def getPayload(session, hash):
645  # get payload from DB:
646  data, payloadType = session.query(Payload.data, Payload.object_type).filter(Payload.hash == hash).one()
647  return data
conddblib.Connection._url
_url
Definition: conddblib.py:345
conddblib.TagLog
Definition: conddblib.py:282
conddblib.GlobalTag
Definition: conddblib.py:264
conddblib.make_dbtype
def make_dbtype(backendName, schemaName, baseType)
Definition: conddblib.py:188
conddblib.DbRef
Definition: conddblib.py:177
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
SiPixelPI::one
Definition: SiPixelPayloadInspectorHelper.h:39
conddblib.Tag
Definition: conddblib.py:227
digitizers_cfi.strip
strip
Definition: digitizers_cfi.py:19
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
conddblib.Connection.__init__
def __init__(self, url)
Definition: conddblib.py:307
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
conddblib.Connection._backendName
_backendName
Definition: conddblib.py:346
python.cmstools.all
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:26
conddblib.GlobalTagMap
Definition: conddblib.py:273
conddblib.DbRef.rcol
rcol
Definition: conddblib.py:180
conddblib.fq_col
def fq_col(schema, table, column)
Definition: conddblib.py:182
conddblib.Payload
Definition: conddblib.py:246
conddblib.Connection.get_dbtype
def get_dbtype(self, theType)
Definition: conddblib.py:361
conddblib.fq_name
def fq_name(schema_name, table_name)
Definition: conddblib.py:164
conddblib.Connection._is_official
_is_official
Definition: conddblib.py:337
conddblib.BoostRunMap
Definition: conddblib.py:298
conddblib.getPayload
def getPayload(session, hash)
Definition: conddblib.py:644
conddblib._inserted_before
def _inserted_before(timestamp)
Definition: conddblib.py:592
conddblib._getCMSSQLAlchemyConnectionString
def _getCMSSQLAlchemyConnectionString(technology, service, schema_name)
Definition: conddblib.py:457
conddblib.Connection.is_frontier
def is_frontier(self)
Definition: conddblib.py:381
conddblib.hash
def hash(data)
Definition: conddblib.py:52
str
#define str(s)
Definition: TestProcessor.cc:51
submitPVResolutionJobs.count
count
Definition: submitPVResolutionJobs.py:352
communicate
static void * communicate(void *obj)
Definition: DQMNet.cc:1049
hitfit::scalar
double scalar(const CLHEP::HepGenMatrix &m)
Return the matrix as a scalar. Raise an assertion if the matris is not .
Definition: matutil.cc:166
conddblib.oracle_connection_string
def oracle_connection_string(db_service, db_schema)
Definition: conddblib.py:139
ALCARECOTkAlBeamHalo_cff.filter
filter
Definition: ALCARECOTkAlBeamHalo_cff.py:27
conddblib.TimeType
Definition: conddblib.py:153
conddblib.Connection._is_read_only
_is_read_only
Definition: conddblib.py:332
conddblib.Synchronization
Definition: conddblib.py:142
conddblib.Connection._session
_session
Definition: conddblib.py:326
conddblib.Connection._is_valid
_is_valid
Definition: conddblib.py:359
conddblib.getSessionOnMasterDB
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:431
conddblib.DbRef.__init__
def __init__(self, refType, refColumn)
Definition: conddblib.py:178
conddblib.Connection.session
def session(self)
Definition: conddblib.py:368
Exception
conddblib.Connection._schemaName
_schemaName
Definition: conddblib.py:347
conddblib.Connection.metadata
def metadata(self)
Definition: conddblib.py:377
conddblib.DbRef.rtype
rtype
Definition: conddblib.py:179
conddblib.TagMetadata
Definition: conddblib.py:239
conddblib.getSchema
def getSchema(tp)
Definition: conddblib.py:222
conddblib.Connection.is_read_only
def is_read_only(self)
Definition: conddblib.py:393
conddblib.connect
def connect(url, authPath=None, verbose=0)
Definition: conddblib.py:516
conddblib.Connection._is_sqlite
_is_sqlite
Definition: conddblib.py:330
conddblib.Connection.is_valid
def is_valid(self)
Definition: conddblib.py:400
conddblib.listObject
def listObject(session, name, snapshot=None)
Definition: conddblib.py:605
conddblib.Connection.is_sqlite
def is_sqlite(self)
Definition: conddblib.py:389
conddblib.Connection._is_oracle
_is_oracle
Definition: conddblib.py:329
conddblib.IOV
Definition: conddblib.py:256
conddblib.Connection.init
def init(self, drop=False)
Definition: conddblib.py:412
conddblib._Col
Definition: conddblib.py:172
conddblib.Connection.engine
engine
Definition: conddblib.py:314
conddblib.Connection
Definition: conddblib.py:305
conddblib.Connection.is_official
def is_official(self)
Definition: conddblib.py:397
conddblib.Connection.is_oracle
def is_oracle(self)
Definition: conddblib.py:385
conddblib._exists
def _exists(session, primary_key, value)
Definition: conddblib.py:581
conddblib.RunInfo
Definition: conddblib.py:292
conddblib._getCMSFrontierConnectionString
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:453
conddblib.Connection._is_frontier
_is_frontier
Definition: conddblib.py:328
conddblib.make_url
def make_url(database='pro', read_only=True)
Definition: conddblib.py:470