I've got a python file which has a bunch of sql queries in it depending on the arguments that are being passed example would be like this:
if args.monitor == 'Argument One':
sql_query = """select a, b, c from tableA where a = 123"""
elif args.monitor == 'Argument Two':
sql_query = """select d, e, f from TableA where d = 456"""
elif ....
This continues on for about 10 different queries with different complexities.
Obviously this makes a mess of code, and to update and/or add SQL queries involves touching a lot of code. What I'd like to do is part the queries/arguments into some sort of dict. Is it possible to use a config file for this purpose where I could do something like the following?
[query]
Argument A = select a, b, c from tableA where a = 123
Argument B = select d, e, f from TableA where d = 456
And then call via ConfigParser. My concern is that some of the queries are quite long (10 lines max) so how would I represent that in a config file?
Or do I go the route of saving each query as ArgumentA.sql and then list the directory and if the argument matches then use that sql?
Has anyone approached a scenario like this before?
-
Is it important that the queries stay human-readable (i.e. with line breaks)?lucasnadalutti– lucasnadalutti2016年03月14日 21:06:05 +00:00Commented Mar 14, 2016 at 21:06
-
The intention is that they would have to be maintained so yeah, need to maintain human readability.whoisearth– whoisearth2016年03月14日 21:08:11 +00:00Commented Mar 14, 2016 at 21:08
1 Answer 1
A dict which associates each argument with the respective query does seem the best idea. Considering this, I see several approaches for this
1) Having a constant at the top of the file which contains this dict. E.g.:
ARGUMENTS_DICT = {
'Argument One': (
'select *'
'from table'
'where etc'
),
...
}
2) Having the same constant from 1 in another file (Python module) and importing it to the current module. E.g.:
from .arguments_dict import ARGUMENTS_DICT
3) Having this dict as a JSON object in a JSON file and using Python's json module to load it as a dict. The downside here is that, to maintain the query's readability, each query would need to be split in elements of a list and joined when loaded in Python. E.g.:
// arguments_dict.json
{
'Argument One': [
'select *',
'from table',
'where etc'
],
...
}