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_cond_general_w']
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 
14 _Base = sqlalchemy.ext.declarative.declarative_base()
15 
16 def make_dbtype(base_class, schema=None):
17  import re
18  name = re.sub('Def$', '', base_class.__name__)
19  members = {}
20  members['__tablename__'] = base_class.__tablename__
21  members['__table_args__'] = None
22  if schema:
23  name = name + schema
24  members['__table_args__'] = {'schema' : schema}
25  dbType = type(name, (_Base, base_class), members)
26  return dbType
27 
28 
30  def __init__(self, db, authPath=None):
31  self.authPath = authPath
32  if db == 'prod':
33  self.db_service = prod_db_service
34  elif db == 'dev':
35  self.db_service = dev_db_service
36  elif db == 'private':
37  self.db_service = None
38  else:
39  raise RuntimeError('Option db(=%s) is not in the supported database list: [prod, dev, private]' % db)
40 
41  logging.info('Connecting to %s database' % self.db_service[0] if self.db_service else private_db)
42 
43  self.schema = schema_dict[self.db_service[0]] if self.db_service else None
44 
45  def get_url(self, force_schema=False):
46  if self.db_service == None:
47  url = private_db
48  else:
49  authEntry = self.db_service[1]
50  if force_schema and self.schema:
51  authEntry = '%s/%s' % (self.db_service[0], self.schema)
52  username, _, pwd = auth.get_credentials( authEntry, self.authPath)
53  url = sqlalchemy_tpl % (username, pwd, self.db_service[0])
54  return url
55 
56  def check_table(self, table_def, table_class):
57  self.engine = sqlalchemy.create_engine(self.get_url())
58  if not self.engine.has_table(table_def.__tablename__, self.schema):
59  logging.info('Creating table %s on %s' % (table_def.__tablename__,
60  self.db_service[0] if self.db_service else private_db))
61  self.engine = sqlalchemy.create_engine(self.get_url(True))
62  table_class.__table__.create(bind=self.engine)
63  self.session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=self.engine))
64 
65  def connect(self, url=None):
66  engine = sqlalchemy.create_engine(url) if url else self.engine
67  session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=engine))
68  return session
69 
def connect(self, url=None)
def check_table(self, table_def, table_class)
def __init__(self, db, authPath=None)
def get_url(self, force_schema=False)
def make_dbtype(base_class, schema=None)