Skip to content

Instantly share code, notes, and snippets.

@dkuku
Last active September 12, 2019 18:40
Show Gist options
  • Save dkuku/a9555ee702e61ac13544b91155af023e to your computer and use it in GitHub Desktop.
Save dkuku/a9555ee702e61ac13544b91155af023e to your computer and use it in GitHub Desktop.
simple sql query generator
string_rules_p = {
"asd": ['asd', 'zxc'],
"zxc": ['asd', 'zxc'],
"qwe": ['asd', 'zxc', 'qwe'],
}
ranged_rules_p = {
"rty" : {"inc": 1, "dec": 5},
"fgh" : {"inc": 2, "dec": 3},
"vbn" : {"inc": 3, "dec": 10},
}
row={}
query = "SELECT * FROM table WHERE "
def generate_sql(query, string_rules_p, ranged_rules_p):
not_first= False
for k,v in ranged_rules_p.items():
query += " AND " if not_first else ''
not_first=True
query += generate_lg(k, v)
for k,v in string_rules_p.items():
query += " AND "
query += generate_in(k, v)
return query
def generate_in(key ,values):
return '{key} in ({values})'.format(key = key, values=", ".join(values))
def generate_lg(key ,values):
return '{key} BETWEEN {inc} AND {dec}'.format(key = key, inc = values['inc'], dec=values['dec'])
query = generate_sql(query, string_rules_p, ranged_rules_p)
print(query)
@dkuku
Copy link
Author

dkuku commented Sep 12, 2019

SELECT * FROM table WHERE rty BETWEEN 1 AND 5 AND fgh BETWEEN 2 AND 3 AND vbn BETWEEN 3 AND 10 AND asd in (asd, zxc) AND zxc in (asd, zxc) AND qwe in (asd, zxc, qwe)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment