-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuu.py
More file actions
298 lines (256 loc) · 8.01 KB
/
uu.py
File metadata and controls
298 lines (256 loc) · 8.01 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# -*- coding: utf-8 -*-
"""Script for updating user ids in target codelist and agenda tables."""
__version__ = '0.1.2'
__status__ = 'Beta'
__author__ = 'Libor Gabaj'
__copyright__ = 'Copyright 2019, ' + __author__
__credits__ = [__author__]
__license__ = 'MIT'
__maintainer__ = __author__
__email__ = 'libor.gabaj@gmail.com'
# Standard library modules
import os
import argparse
import logging
import mysql.connector as mysql
# Third party modules
import dbconfig as db
import sql
###############################################################################
# Script global variables
###############################################################################
cmdline = None # Object with command line arguments
logger = None # Object with standard logging
###############################################################################
# Enumeration and parameter classes
###############################################################################
class Script:
"""Script parameters."""
(
fullname, basename, name,
) = ('', '', '',)
class Target:
"""Status parameters of the data target."""
(
conn, query, cursor, table, database, codelists, agendas
) = (None, None, None, None, None, None, None,)
###############################################################################
# Actions
###############################################################################
def connect_db(config):
"""Connect to a database.
Arguments
---------
config : dict
Connection configuration to a database.
Returns
-------
connection : object
Connection object to a database.
Raises
-------
mysql.connector.Error
Native exception of the database connector.
"""
try:
conn = mysql.connect(**config)
logger.debug('Database %s connected', config['database'])
return conn
except mysql.Error as err:
if err.errno == mysql.errorcode.ER_ACCESS_DENIED_ERROR:
logger.error('Bad database %s credentials', config['database'])
elif err.errno == mysql.errorcode.ER_BAD_DB_ERROR:
logger.error('Database %s does not exist', config['database'])
else:
logger.error(err)
raise
def target_open():
"""Connect to a target database.
Returns
-------
boolean
Flag about successful processing.
"""
if Target.conn is None:
try:
Target.conn = connect_db(db.target_config)
except Exception:
logger.error(
'Cannot connect to the target database %s',
Target.database
)
return False
return True
def target_close():
"""Close cursor and connection to a target database."""
# Close cursor
if Target.cursor is not None:
Target.cursor.close()
# Close connection to database
if Target.conn is not None:
Target.conn.close()
###############################################################################
# Setup functions
###############################################################################
def setup_params():
"""Determine script operational parameters."""
Script.fullname = os.path.splitext(os.path.abspath(__file__))[0]
Script.basename = os.path.basename(__file__)
Script.name = os.path.splitext(Script.basename)[0]
def setup_cmdline():
"""Define command line arguments."""
parser = argparse.ArgumentParser(
description='Users update for entire code lists and agendas, version '
+ __version__
)
# Options
parser.add_argument(
'-V', '--version',
action='version',
version=__version__,
help='Current version of the script.'
)
parser.add_argument(
'-v', '--verbose',
choices=['debug', 'info', 'warning', 'error', 'critical'],
default='info',
help='Level of logging to the console.'
)
parser.add_argument(
'-c', '--codelists',
action='store_true',
help='Update all target codelist tables.'
)
parser.add_argument(
'-a', '--agendas',
action='store_true',
help='Update all target agenda tables.'
)
parser.add_argument(
'-u', '--user',
type=int,
help='Joomla! user id for table records.'
)
parser.add_argument(
'-l', '--list',
action='store_true',
help='List of target codelist and agenda tables.'
)
# Process command line arguments
global cmdline
cmdline = parser.parse_args()
def setup_logger():
"""Configure logging facility."""
global logger
logging.basicConfig(
level=getattr(logging, cmdline.verbose.upper()),
format='%(levelname)s:%(name)s: %(message)s',
)
logger = logging.getLogger(Script.name)
def tablelist(table_prefix):
"""List names of target table.
Arguments
---------
table_prefix : str
Prefix of tables.
Returns
-------
list : str
List of full table names.
"""
Target.query = sql.compose_tablelist(table_prefix)
Target.cursor = Target.conn.cursor()
try:
Target.cursor.execute(Target.query)
records = Target.cursor.fetchall()
logger.debug(
'Read %d tables for prefix %s.%s',
Target.cursor.rowcount,
Target.database,
table_prefix
)
return records
except mysql.Error as err:
logger.error(err)
return None
def update_users(table_list):
"""Update user ids in tables from provided list.
Arguments
---------
table_list : list of str
Names of tables to be updated.
Returns
-------
int
Number of updated tables.
"""
tables = 0
if not isinstance(table_list, list):
return tables
for table in table_list:
Target.table = table
Target.query = sql.compose_update(
table=Target.table,
fields=sql.target_users,
)
Target.cursor = Target.conn.cursor()
try:
Target.cursor.execute(Target.query, {'user': cmdline.user})
tables += 1
logger.debug(
'Updated %d records in table %s.%s with user %d',
Target.cursor.rowcount,
Target.database,
Target.table,
cmdline.user
)
except mysql.Error as err:
logger.error(err)
return tables
def main():
"""Fundamental control function."""
setup_params()
setup_cmdline()
setup_logger()
# Is there something to do?
if not (cmdline.codelists or cmdline.agendas or cmdline.list):
logger.warning('Nothing to do, see --help')
return
# Connect to target database
Target.database = db.target_config['database']
if not target_open():
return
# Codelist tables
records = tablelist(sql.target_table_prefix_codelist)
Target.codelists = [r[0] for r in records]
# Agenda tables
records = tablelist(sql.target_table_prefix_agenda)
Target.agendas = [r[0] for r in records]
# Print list of updated targets
if cmdline.list:
tables = ', '.join(Target.codelists)
print('Codelists: {}'.format(tables))
tables = ', '.join(Target.agendas)
print('Agendas: {}'.format(tables))
# Updates
if cmdline.codelists or cmdline.agendas:
if cmdline.user:
if cmdline.codelists:
tables = update_users(Target.codelists)
logger.info(
'Updated %d codelist tables with user %d',
tables,
cmdline.user,
)
if cmdline.agendas:
tables = update_users(Target.agendas)
logger.info(
'Updated %d agenda tables with user %d',
tables,
cmdline.user,
)
else:
logger.warning('No user id provided, see --help')
target_close()
if __name__ == '__main__':
main()