Would it be possible to dynamically build queries in TinyDB? Its logical query operation is like this:
>>> from tinydb import TinyDB, where
>>> db = TinyDB('db.json')
>>> # Logical AND:
>>> db.search((where('int') == 1) & (where('char') == 'b'))
[{'int': 1, 'char': 'b'}]
But I need to build the query dynamically from user's input conditions. The only way I can figure out is to concatenate the conditions into a string and exec
it like this:
#!/usr/bin/env python3
import shlex
from tinydb import TinyDB, where
# create db sample
db = TinyDB('test.json')
db.insert({'id': '1', 'name': 'Tom', 'age': '10', 'grade': '4'})
db.insert({'id': '2', 'name': 'Alice', 'age': '9', 'grade': '3'})
db.insert({'id': '3', 'name': 'John', 'age': '11', 'grade': '5'})
db.close()
# query test
db = TinyDB('test.json')
q = input("query for name/age/grade: ")
# name='Tom' grade='4'
qdict = dict(token.split('=') for token in shlex.split(q))
result = []
query = "result = db.search("
qlen = len(qdict)
count = 0
for key, value in qdict.items():
query += "(where('%s') == '%s')" % (key, value)
count += 1
if count < qlen:
query += " & "
query += ')'
exec(query)
print(result)
# [{'age': '10', 'id': '1', 'grade': '4', 'name': 'Tom'}]
Is there a better and elegant way to do that? Thanks a lot.