-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_lib.py
144 lines (113 loc) · 3.99 KB
/
db_lib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import sys, os
import logging
import mysql.connector as mycon
###########################################################
logger = logging.getLogger(__name__)
###########################################################
def _read(filename, dbname):
"""
Read the private file with the database credentials
@param filename: full path to the private file with the database credentials
@type filename: str
@param dbname: the name of the desired database to get the credentials
@type dbname: str
@return: dictionary with the credential as key/value pairs
@rtype: dict
"""
if not os.path.exists(filename):
logger.error('_read: the file {0} does not exist'.format(filename))
sys.exit(1)
if not check_dbname(dbname):
logger.error('_read: the specified database name is invalid')
sys.exit(1)
with open(filename, 'r') as r: lines = r.readlines()
dic = dict()
if dbname == 'hpc_thnkng_stats':
start = 0
end = 5
else:
start = 6
end = 11
lines = lines[start : end]
for line in lines:
key, val = line.rstrip('\r\n').split(':')
dic[key] = val
dic['port'] = int(dic['port'])
return dic
###########################################################
def get_dic_connections(dbname):
"""
This function returns a dictionary with the login info for the two databases.
The only two allowed database names (dbname) are:
- hpc_thnkng_stats
- hpc_thnkng_reps
@param dbname: the name of the desired database to connect to
@type dbname: str
@return: the connection arguments
@rtype: dict
"""
if not check_dbname(dbname):
logger.error('get_dic_connections: dbname:{0} is not accepted'.format(dbname))
sys.exit(1)
private = os.path.dirname(__file__) + '/private'
return _read(private, dbname)
###########################################################
class thnkng_db(object):
"""
A base class which creates the connection to any of the two ThinKing databases
"""
def __init__(self, dbname):
if not check_dbname(dbname):
logger.error('__init__: The dbname={0} is invalid'.format(dbname))
sys.exit(1)
self.dbname = dbname
self.dic_connection = get_dic_connections(dbname)
self.connection = None
self.cursor = None
# .........................
def __enter__(self):
return self
# .........................
def __exit__(self, type, value, traceback):
pass
# .........................
def get_connection(self):
""" Return the mysql.connector connection object """
if self.connection is not None: return self.connection
conn = mycon.connect(**self.dic_connection)
self.connection = conn
return conn
# .........................
def get_cursor(self):
""" Return the mysql.connector.connection.cursor object """
if isinstance(self.connection, type(None)):
logger.error('get_cursor: Not connected yet; first call: db.get_connection()')
sys.exit(1)
curs = self.connection.cursor()
self.cursor = curs
return curs
# .........................
def execute(self, cmnd, inputs=None):
""" Execute the command, together with parsing the inputs """
curs = self.cursor
if curs is None:
logger.error('execute: The cursor is not grabbed yet')
sys.exit(1)
curs.execute(cmnd, inputs)
# self.connection.commit()
# .........................
def get_table_column_names(self, table):
""" Get the list of column names of the desired table """
curs = self.cursor
if curs is None:
logger.error('get_table_column_names: cursor is not grabbed yet')
sys.exit(1)
cmnd = 'select * from {0};'.format(table)
self.execute(cmnd, None)
return self.cursor.column_names
# .........................
# .........................
###########################################################
def check_dbname(dbname):
""" Make sure the dbname is one of the two only valid dbnames"""
return dbname in ['hpc_thnkng_stats', 'hpc_thnkng_reps']