Skip to content

Commit 1f56db5

Browse files
committed
Version 0.7.7
Cleaned up imports, no more "from X import *". Made constants ALL CAPS.
1 parent 90d9a71 commit 1f56db5

14 files changed

+258
-673
lines changed

DBClient.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@
44
55
AUTHOR: David J. Lambert
66
7-
VERSION: 0.7.5
7+
VERSION: 0.7.6
88
9-
DATE: Apr 20, 2020
9+
DATE: Jul 9, 2020
1010
"""
11-
from OutputWriter import *
11+
from constants import ACCESS, ORACLE, SQLSERVER # MYSQL, POSTGRESQL, SQLITE
12+
from OutputWriter import OutputWriter
1213
import MyQueries as mq
13-
from DBInstance import *
14+
from functions import print_stacktrace, pick_one, is_skip_operation
1415

1516

16-
# noinspection PyUnresolvedReferences
1717
class DBClient(object):
1818
""" Get text of a SQL program with bind variables, then execute it.
1919
@@ -114,7 +114,7 @@ def run_sql(self) -> (list, list, int):
114114
try:
115115
# Execute SQL.
116116
if len(self.bind_vars) > 0:
117-
if self.db_type == access:
117+
if self.db_type == ACCESS:
118118
print('NO BIND VARIABLES ALLOWED IN MICROSOFT ACCESS.')
119119
self.clean_up()
120120
exit(1)
@@ -172,9 +172,9 @@ def _skip_op_msg(self, sql_x: str, object_str: str) -> str:
172172
Returns:
173173
msg (str): complete message to print.
174174
"""
175-
if sql_x == mq.not_implemented:
175+
if sql_x == mq.NOT_IMPLEMENTED:
176176
msg = '\n' + sql_x.format(object_str, self.db_type.upper())
177-
elif sql_x == mq.not_possible_sql:
177+
elif sql_x == mq.NOT_POSSIBLE_SQL:
178178
msg = sql_x.format(self.db_type.upper(), self.db_lib_name.upper())
179179
else:
180180
msg = "Problem in _skip_op_msg!"
@@ -195,8 +195,7 @@ def db_table_schema(self, colsep='|') -> None:
195195
Returns:
196196
"""
197197
# Find tables.
198-
skip_op, table_col_names, table_rows = self._data_dict_fetch(mq.tables,
199-
'')
198+
skip_op, table_col_names, table_rows = self._data_dict_fetch(mq.TABLES, '')
200199
if skip_op:
201200
return
202201

@@ -219,7 +218,7 @@ def db_table_schema(self, colsep='|') -> None:
219218

220219
# Find and print columns in this table.
221220
skip_op, columns_col_names, columns_rows = self._data_dict_fetch(
222-
mq.tab_col, my_table_name)
221+
mq.TAB_COL, my_table_name)
223222

224223
# Write output.
225224
writer1 = OutputWriter(out_file_name='', align_col=True, col_sep=colsep)
@@ -228,7 +227,7 @@ def db_table_schema(self, colsep='|') -> None:
228227

229228
# Find all indexes in this table.
230229
skip_op, indexes_col_names, indexes_rows = self._data_dict_fetch(
231-
mq.indexes, my_table_name)
230+
mq.INDEXES, my_table_name)
232231
if skip_op:
233232
return
234233

@@ -243,8 +242,7 @@ def db_table_schema(self, colsep='|') -> None:
243242
# Go through indexes, add index_columns to end of each index/row.
244243
for item_num, index_row in enumerate(indexes_rows):
245244
index_name = index_row[columns['index_name']]
246-
skip_op, _, ind_col_rows = self._data_dict_fetch(mq.ind_col,
247-
index_name)
245+
skip_op, _, ind_col_rows = self._data_dict_fetch(mq.IND_COL, index_name)
248246
if skip_op:
249247
return
250248
# Concatenate names of columns in index.
@@ -274,7 +272,7 @@ def db_view_schema(self, colsep='|') -> None:
274272
"""
275273
# Find views
276274
# TODO need to use all fields and make return values consistent.
277-
skip_op, view_col_names, view_rows = self._data_dict_fetch(mq.views, '')
275+
skip_op, view_col_names, view_rows = self._data_dict_fetch(mq.VIEWS, '')
278276
if skip_op:
279277
return
280278

@@ -303,7 +301,7 @@ def db_view_schema(self, colsep='|') -> None:
303301
# Find and print columns in this view.
304302
print('\nHere are the columns for view {}:'.format(my_view_name))
305303
skip_op, columns_col_names, columns_rows = self._data_dict_fetch(
306-
mq.view_col, my_view_name)
304+
mq.VIEW_COL, my_view_name)
307305

308306
# Write output.
309307
writer1 = OutputWriter(out_file_name='', align_col=True, col_sep=colsep)
@@ -313,8 +311,7 @@ def db_view_schema(self, colsep='|') -> None:
313311
return
314312
# End of method db_view_schema.
315313

316-
def _data_dict_fetch(self, obj_type: str, obj_name: str) -> (bool, list,
317-
list):
314+
def _data_dict_fetch(self, obj_type: str, obj_name: str) -> (bool, list, list):
318315
""" Find data dictionary information about a type of object.
319316
320317
Parameters:
@@ -358,8 +355,7 @@ def get_data_type(self, table: str, column: str) -> (str, str):
358355
data_type_group (str): the data type's group.
359356
"""
360357
# Get the columns for this table.
361-
skip_op, columns_col_names, columns_rows = self._data_dict_fetch(
362-
mq.tab_col, table)
358+
skip_op, columns_col_names, columns_rows = self._data_dict_fetch(mq.TAB_COL, table)
363359
if skip_op:
364360
return 'NOT FOUND', 'NOT FOUND'
365361

@@ -380,12 +376,12 @@ def get_data_type(self, table: str, column: str) -> (str, str):
380376
(data_type_low.find('nvarchar') > -1) or
381377
(data_type_low.find('nclob') > -1)):
382378
data_type_group = 'UNICODE'
383-
elif ((data_type_low.find('bit') > -1 and self.db_type != sqlserver) or
379+
elif ((data_type_low.find('bit') > -1 and self.db_type != SQLSERVER) or
384380
(data_type_low.find('raw') > -1) or
385381
(data_type_low.find('image') > -1) or
386382
(data_type_low.find('binary') > -1) or
387383
(data_type_low.find('blob') > -1) or
388-
(data_type_low.find('byte') > -1 and self.db_type != oracle)):
384+
(data_type_low.find('byte') > -1 and self.db_type != ORACLE)):
389385
# Includes Oracle Long Raw, listed before Long.
390386
# Image is Sql server
391387
data_type_group = 'BINARY'
@@ -410,7 +406,7 @@ def get_data_type(self, table: str, column: str) -> (str, str):
410406
(data_type_low.find('year') > -1)):
411407
data_type_group = 'DATETIME'
412408
elif ((data_type_low.find('bool') > -1) or
413-
(data_type_low.find('bit') > -1 and self.db_type == sqlserver)):
409+
(data_type_low.find('bit') > -1 and self.db_type == SQLSERVER)):
414410
data_type_group = 'BOOLEAN'
415411
else:
416412
data_type_group = 'OTHER'

DBInstance.py

Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
55
AUTHOR: David J. Lambert
66
7-
VERSION: 0.7.5
7+
VERSION: 0.7.6
88
9-
DATE: Apr 20, 2020
9+
DATE: Jul 9, 2020
1010
"""
11-
from MyConstants import *
12-
from MyFunctions import *
11+
from functions import print_stacktrace, is_file_in_path
12+
from constants import ACCESS, MYSQL, ORACLE, POSTGRESQL, SQLITE, SQLSERVER
13+
import constants as c
1314

1415

15-
# noinspection PyUnresolvedReferences
1616
class DBInstance(object):
1717
""" Class containing database connection utilities and information
1818
about one database instance (referred to as "this database").
@@ -68,20 +68,20 @@ def __init__(self,
6868
self.instance: str = instance
6969

7070
# Check if db_type valid.
71-
if self.db_type not in db_types:
71+
if self.db_type not in c.DB_TYPES:
7272
print('Invalid database type "{}".'.format(self.db_type))
7373
# Nothing to clean up.
7474
exit(1)
7575

7676
# Import appropriate database library.
77-
self.db_lib_name = lib_name_for_db[self.db_type]
77+
self.db_lib_name = c.LIB_NAME_FOR_DB[self.db_type]
7878
self.db_lib_obj = __import__(self.db_lib_name)
7979

8080
# Appropriate database client executable.
81-
self.db_client_exe = db_client_exes[self.db_type]
81+
self.db_client_exe = c.DB_CLIENT_EXES[self.db_type]
8282

8383
# Get database library version.
84-
if self.db_lib_name in {psycopg2, pymysql}:
84+
if self.db_lib_name in {c.PSYCOPG2, c.PYMYSQL}:
8585
self.db_lib_version = self.db_lib_obj.__version__
8686
else:
8787
self.db_lib_version = self.db_lib_obj.version
@@ -95,22 +95,22 @@ def __init__(self,
9595
# paramstyle = 'pyformat': pymysql and psycopg2.
9696

9797
# Get the parameter style we're using.
98-
self.paramstyle = paramstyle_for_lib[self.db_lib_name]
99-
if self.db_type == access:
100-
self.paramstyle = nobindvars
98+
self.paramstyle = c.PARAMSTYLE_FOR_LIB[self.db_lib_name]
99+
if self.db_type == ACCESS:
100+
self.paramstyle = c.NOBINDVARS
101101

102102
# Initialize bind_vars.
103-
if self.paramstyle in {named, pyformat}:
103+
if self.paramstyle in {c.NAMED, c.PYFORMAT}:
104104
self.bind_vars = dict()
105-
elif self.paramstyle == qmark:
105+
elif self.paramstyle == c.QMARK:
106106
self.bind_vars = tuple()
107107
else:
108108
self.bind_vars = None
109109

110110
# Connect to database instance.
111111
self.connection = None
112112
try:
113-
if db_type in uses_connection_string:
113+
if db_type in c.USES_CONNECTION_STRING:
114114
z = self.get_db_connection_string()
115115
self.connection = self.db_lib_obj.connect(z)
116116
else:
@@ -151,7 +151,7 @@ def close_connection(self, del_cursors: bool = False) -> None:
151151
else:
152152
print('Dependent DBClients exist, will not close connection.')
153153

154-
if self.db_type in file_databases:
154+
if self.db_type in c.FILE_DATABASES:
155155
z = '\n{} from database at "{}".'
156156
z = z.format('{}', self.db_path)
157157
else:
@@ -209,7 +209,7 @@ def get_connection_status(self) -> str:
209209
Parameters:
210210
Returns:
211211
"""
212-
if self.db_type in file_databases:
212+
if self.db_type in c.FILE_DATABASES:
213213
z = 'Connection status for the database at "{}": {}connected.'
214214
z = z.format(self.db_path, '{}')
215215
else:
@@ -270,21 +270,21 @@ def get_db_software_version(self) -> str:
270270
db_software_version (str): database software version.
271271
"""
272272
sql = {
273-
mysql: 'SELECT version()',
274-
postgresql: 'SELECT version()',
275-
oracle: "SELECT * FROM v$version WHERE banner LIKE 'Oracle%'",
276-
sqlite: 'SELECT sqlite_version()',
277-
sqlserver: 'SELECT @@VERSION'}.get(self.db_type, 'Nada')
273+
MYSQL: 'SELECT version()',
274+
POSTGRESQL: 'SELECT version()',
275+
ORACLE: "SELECT * FROM v$version WHERE banner LIKE 'Oracle%'",
276+
SQLITE: 'SELECT sqlite_version()',
277+
SQLSERVER: 'SELECT @@VERSION'}.get(self.db_type, 'Nada')
278278

279279
if sql[0:6] == 'SELECT':
280280
cursor = self.connection.cursor()
281281
cursor.execute(sql)
282282
version = cursor.fetchone()[0]
283283
cursor.close()
284284
del cursor
285-
elif self.db_type == access:
285+
elif self.db_type == ACCESS:
286286
version = "unavailable for MS Access through SQL"
287-
elif self.db_lib_name != pyodbc:
287+
elif self.db_lib_name != c.PYODBC:
288288
# This is for future use.
289289
version = self.connection.version
290290
else:
@@ -300,32 +300,32 @@ def get_db_connection_string(self) -> str:
300300
db_software_version (str): database software version.
301301
"""
302302
z = ''
303-
if self.db_lib_name == cx_Oracle:
303+
if self.db_lib_name == c.CX_ORACLE:
304304
z = '{}/{}@{}:{}/{}'
305-
elif self.db_lib_name == psycopg2:
305+
elif self.db_lib_name == c.PSYCOPG2:
306306
z = "user='{}' password='{}' host='{}' port='{}' dbname='{}'"
307-
elif self.db_lib_name == pymysql:
307+
elif self.db_lib_name == c.PYMYSQL:
308308
z = ''
309-
elif self.db_lib_name == pyodbc:
310-
if self.db_type == access:
309+
elif self.db_lib_name == c.PYODBC:
310+
if self.db_type == ACCESS:
311311
z = ('DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};'
312312
'DBQ={};')
313-
elif self.db_type == sqlserver:
313+
elif self.db_type == c.SQLSERVER:
314314
z = ('DRIVER={{SQL Server}};'
315315
'UID={};PWD={};SERVER={};PORT={};DATABASE={}')
316-
elif self.db_lib_name == sqlite3:
316+
elif self.db_lib_name == c.SQLITE3:
317317
z = '{}'
318318
else:
319319
print('Unknown db library "{}", aborting.'.format(self.db_lib_name))
320320
self.close_connection()
321321
exit(1)
322322

323-
if self.db_type in {oracle, postgresql, sqlserver}:
323+
if self.db_type in {ORACLE, POSTGRESQL, SQLSERVER}:
324324
z = z.format(self.username, self.password, self.hostname,
325325
self.port_num, self.instance)
326-
elif self.db_type in file_databases:
326+
elif self.db_type in c.FILE_DATABASES:
327327
z = z.format(self.db_path)
328-
elif self.db_type == mysql:
328+
elif self.db_type == MYSQL:
329329
pass
330330

331331
return z
@@ -340,7 +340,7 @@ def print_all_connection_parameters(self) -> None:
340340
print('The database type is "{}".'.format(self.db_type))
341341
z = 'The database software version is {}.'
342342
print(z.format(self.db_software_version))
343-
if self.db_type in file_databases:
343+
if self.db_type in c.FILE_DATABASES:
344344
print('The database path is "{}".'.format(self.db_path))
345345
else:
346346
print('The database username is "{}".'.format(self.username))
@@ -361,26 +361,26 @@ def get_cmdline_list(self) -> list:
361361
args = (self.username, self.password, self.hostname,
362362
self.port_num, self.instance)
363363

364-
if self.db_type == access or self.db_client_exe == '':
364+
if self.db_type == ACCESS or self.db_client_exe == '':
365365
z = '{} DOES NOT HAVE A COMMAND LINE INTERFACE.'
366366
z = z.format(self.db_type).upper()
367367
cmd = ['Error', z]
368368
elif not is_file_in_path(self.os, self.db_client_exe):
369369
z = 'Did not find {} in PATH.'.format(self.db_client_exe)
370370
cmd = ['Error', z]
371-
elif self.db_type == mysql:
371+
elif self.db_type == MYSQL:
372372
conn_str = '--uri={}:{}@{}:{}/{}'.format(*args)
373373
cmd = [self.db_client_exe, conn_str,
374374
'--table', '--sql', '--quiet-start']
375-
elif self.db_type == oracle:
375+
elif self.db_type == ORACLE:
376376
conn_str = '{}/{}@{}:{}/{}'.format(*args)
377377
cmd = [self.db_client_exe, conn_str]
378-
elif self.db_type == postgresql:
378+
elif self.db_type == POSTGRESQL:
379379
conn_str = 'postgresql://{}:{}@{}:{}/{}'.format(*args)
380380
cmd = [self.db_client_exe, '-d', conn_str]
381-
elif self.db_type == sqlite:
381+
elif self.db_type == SQLITE:
382382
cmd = [self.db_client_exe, self.db_path]
383-
elif self.db_type == sqlserver:
383+
elif self.db_type == SQLSERVER:
384384
host_port = '{},{}'.format(self.hostname, self.port_num)
385385
cmd = [self.db_client_exe, '-U', self.username, '-P', self.password,
386386
'-S', host_port, '-d', self.instance]

0 commit comments

Comments
 (0)