CMS 3D CMS Logo

o2o_db_manager.py
Go to the documentation of this file.
1 import sqlalchemy
2 import sqlalchemy.ext.declarative
3 import logging
4 
5 import CondCore.Utilities.credentials as auth
6 
7 prod_db_service = ['cms_orcon_prod', 'cms_orcon_prod/cms_cond_general_w']
8 dev_db_service = ['cms_orcoff_prep', 'cms_orcoff_prep/cms_test_conditions']
9 schema_dict = {'cms_orcon_prod':'cms_cond_o2o', 'cms_orcoff_prep':'cms_cond_strip'}
10 sqlalchemy_tpl = 'oracle://%s:%s@%s'
11 coral_tpl = 'oracle://%s/%s'
12 private_db = 'sqlite:///post_o2o.db'
13 authPathEnvVar = 'COND_AUTH_PATH'
14 
15 _Base = sqlalchemy.ext.declarative.declarative_base()
16 
17 def make_dbtype(base_class, schema=None):
18  import re
19  name = re.sub('Def$', '', base_class.__name__)
20  members = {}
21  members['__tablename__'] = base_class.__tablename__
22  members['__table_args__'] = None
23  if schema:
24  name = name + schema
25  members['__table_args__'] = {'schema' : schema}
26  dbType = type(name, (_Base, base_class), members)
27  return dbType
28 
29 
31  def __init__(self, db, authFile=None):
32  self.authFile = authFile
33  if db == 'prod':
34  self.db_service = prod_db_service
35  elif db == 'dev':
36  self.db_service = dev_db_service
37  elif db == 'private':
38  self.db_service = None
39  else:
40  raise RuntimeError('Option db(=%s) is not in the supported database list: [prod, dev, private]' % db)
41 
42  logging.info('Connecting to %s database' % self.db_service[0] if self.db_service else private_db)
43 
44  self.schema = schema_dict[self.db_service[0]] if self.db_service else None
45 
46  def get_url(self, force_schema=False):
47  if self.db_service == None:
48  url = private_db
49  else:
50  authEntry = self.db_service[1]
51  if force_schema and self.schema:
52  authEntry = '%s/%s' % (self.db_service[0], self.schema)
53  username, _, pwd = auth.get_credentials(authPathEnvVar, authEntry, self.authFile)
54  url = sqlalchemy_tpl % (username, pwd, self.db_service[0])
55  return url
56 
57  def check_table(self, table_def, table_class):
58  self.engine = sqlalchemy.create_engine(self.get_url())
59  if not self.engine.has_table(table_def.__tablename__, self.schema):
60  logging.info('Creating table %s on %s' % (table_def.__tablename__,
61  self.db_service[0] if self.db_service else private_db))
62  self.engine = sqlalchemy.create_engine(self.get_url(True))
63  table_class.__table__.create(bind=self.engine)
64  self.session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=self.engine))
65 
66  def connect(self, url=None):
67  engine = sqlalchemy.create_engine(url) if url else self.engine
68  session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=engine))
69  return session
70 
def connect(self, url=None)
def check_table(self, table_def, table_class)
def __init__(self, db, authFile=None)
def get_url(self, force_schema=False)
def make_dbtype(base_class, schema=None)