3 Translates a given database name alias, and credentials taken from a file, into an oracle database string, then connects.
4 Also sets up ORM with SQLAlchemy.
9 from sqlalchemy
import create_engine, text, or_
10 from sqlalchemy.orm
import sessionmaker
12 from data_sources
import json_data_node
13 from copy
import deepcopy
20 connection_data =
None
22 netrc_authenticators =
None
31 except ImportError as e:
32 exit("cx_Oracle cannot be imported - try to run 'source /data/cmssw/setupEnv.sh' and 'source venv/bin/activate'.")"""
36 frontier_str_length = len(
"frontier://")
37 sqlite_str_length = len(
"sqlite:///")
38 if type(connection_data) == str
and connection_data[0:frontier_str_length] ==
"frontier://":
39 db_name = connection_data[frontier_str_length:].
split(
"/")[0]
40 schema = connection_data[frontier_str_length:].
split(
"/")[1]
42 connection_data[
"db_alias"] = db_name
43 connection_data[
"schema"] = schema
44 connection_data[
"host"] =
"frontier"
45 """elif type(connection_data) == str and connection_data[0:sqlite_str_length] == "sqlite:///":
46 db_name = connection_data[frontier_str_length:]
49 connection_data["db_alias"] = db_name
50 connection_data["schema"] = schema
51 connection_data["host"] = "sqlite"
54 headers = [
"login",
"account",
"password"]
58 self.
schema = connection_data[
"schema"]
64 if connection_data[
"host"] ==
"oracle":
65 self.
secrets =
dict(zip(headers, netrc.netrc(connection_data[
"secrets"]).authenticators(connection_data[
"host"])))
98 if self.
models[key].__class__ == sqlalchemy.ext.declarative.api.DeclarativeMeta\
99 and str(self.
models[key].__name__) !=
"Base":
106 tmp_models_dict[key.lower()] = self.
models[key]
107 tmp_models_dict[key.lower()].empty =
False
108 except AttributeError:
111 self.
models = tmp_models_dict
116 new_dict =
dict(model.__dict__)
117 new_dict[
"__table__"] = deepcopy(model.__dict__[
"__table__"])
118 return type(model.__class__.__name__, (), new_dict)
124 except Exception
as e:
130 return subprocess.Popen([
'cmsGetFnConnect',
'frontier://%s' % database], stdout = subprocess.PIPE).
communicate()[0].strip()
132 exit(
"Frontier connections can only be constructed when inside a CMSSW environment.")
141 return 'oracle://%s:%s@%s' % (user, pwd, db_name)
151 'oradev': (
lambda: self.
_cms_oracle_string(
'cms_conditions_002', pwd,
'cms_orcoff_prep')),
152 'oraboost': (
lambda: self.
_cms_oracle_string(
'cms_conditions', pwd,
'cms_orcon_adg')),
153 'oraboostprep': (
lambda: self.
_cms_oracle_string(
'cms_conditions_002', pwd,
'cms_orcoff_prep')),
159 if db_name
in mapping.keys():
160 database_url = mapping[db_name]()
162 print(
"Database name given isn't valid.")
166 url = sqlalchemy.engine.url.make_url(database_url)
167 if url.password
is None:
169 except sqlalchemy.exc.ArgumentError:
170 url = sqlalchemy.engine.url.make_url(
'sqlite:///%s' % db_name)
182 if db_name
in mapping.keys():
183 database_url = mapping[db_name]()
185 print(
"Database name given isn't valid.")
189 url = sqlalchemy.engine.url.make_url(database_url)
190 except sqlalchemy.exc.ArgumentError:
191 url = sqlalchemy.engine.url.make_url(
'sqlite:///%s' % db_name)
195 return "<connection db='%s'>" % self.
db_name
199 class_name = cls.__name__
200 all_upper_case =
True
201 for character
in class_name:
202 all_upper_case = character.isupper()
205 for n
in range(0, len(class_name)):
206 if class_name[n].isupper()
and n != 0:
207 class_name = str(class_name[0:n]) +
"".
join([
"_", class_name[n].lower()]) + str(class_name[n+1:])
208 elif class_name[n].isupper()
and n == 0:
209 class_name = str(class_name[0:n]) +
"".
join([class_name[n].lower()]) + str(class_name[n+1:])
214 if model_name.__class__ == sqlalchemy.ext.declarative.api.DeclarativeMeta:
215 model_name = model_name.__name__
216 model_name = model_name.replace(
"_",
"")
217 return self.
models[model_name]
225 model_data = self.session.query(model)
226 for pk
in pk_to_value:
227 model_data = model_data.filter(model.__dict__[pk] == pk_to_value[pk])
228 return model_data.first()
231 return self.factory.object(
"globaltag", **pkargs)
234 return self.factory.object(
"globaltagmap", **pkargs)
237 return self.factory.object(
"globaltagmaprequest", **pkargs)
240 return self.factory.object(
"tag", **pkargs)
243 return self.factory.object(
"iov", **pkargs)
246 return self.factory.object(
"payload", **pkargs)
249 return self.factory.object(
"payload", **pkargs)
253 return "%%%s%%" % string
259 gt = self.
model(
"globaltag")
260 global_tags = self.session.query(gt).
filter(or_(
261 gt.name.ilike(string),
262 gt.description.ilike(string),
263 gt.release.ilike(string)
265 tag = self.
model(
"tag")
266 tags = self.session.query(tag).
filter(or_(
267 tag.name.ilike(string),
268 tag.object_type.ilike(string),
269 tag.description.ilike(string))
271 iov = self.
model(
"iov")
272 iovs = self.session.query(iov).
filter(or_(
273 iov.tag_name.ilike(string),
274 iov.since.ilike(string),
275 iov.payload_hash.ilike(string),
276 iov.insertion_time.ilike(string)
278 payload = self.
model(
"payload")
279 payloads = self.session.query(payload).
filter(or_(
280 payload.hash.ilike(string),
281 payload.object_type.ilike(string),
282 payload.insertion_time.ilike(string)
285 return json_data_node.make({
286 "global_tags" : global_tags.all(),
289 "payloads" : payloads.all()
297 class_of_object = object.__class__
298 new_object = class_of_object(object.as_dicts(), convert_timestamps=
False)
299 new_object.__table__.schema = self.
schema
300 self.session.add(new_object)
303 print(
"Writing to non-sqlite databases currently not supported.")
308 self.session.commit()
310 print(
"Writing to non-sqlite databases currently not supported.")
328 from data_sources
import json_list
329 model = self.connection.model(class_name)
330 if self.connection.session ==
None:
332 model_data = self.connection.session.query(model)
333 if len(pkargs.items()) != 0:
335 if pkargs[pk].__class__ != list:
336 if pkargs[pk].__class__ == json_list:
337 pkargs[pk] = pkargs[pk].
data()
339 pkargs[pk] = [pkargs[pk]]
340 model_data = model_data.filter(model.__dict__[pk].in_(pkargs[pk]))
341 if model_data.count() > 1:
342 return json_list(model_data.all())
343 elif model_data.count() == 1:
344 return model_data.first()
349 new_object.empty =
True
353 con =
connection(connection_data=connection_data)
def global_tag_map_request
std::string print(const Track &, edm::Verbosity=edm::Concise)
Track print utility.
def _get_CMS_frontier_connection_string
static void * communicate(void *obj)
static std::string join(char **cmd)
char data[epos_bytes_allocation]