'Search for queries.'

@has_access
@expose(u'/search_queries')
@log_this
def search_queries(self):

    query = db.session.query(Query)
    search_user_id = request.args.get(u'user_id')
    database_id = request.args.get(u'database_id')
    search_text = request.args.get(u'search_text')
    status = request.args.get(u'status')
    from_time = request.args.get(u'from')
    to_time = request.args.get(u'to')
    if search_user_id:
        query = query.filter((Query.user_id == search_user_id))
    if database_id:
        query = query.filter((Query.database_id == database_id))
    if status:
        query = query.filter((Query.status == status))
    if search_text:
        query = query.filter(Query.sql.like(u'%{}%'.format(search_text)))
    if from_time:
        query = query.filter((Query.start_time > int(from_time)))
    if to_time:
        query = query.filter((Query.start_time < int(to_time)))
    query_limit = config.get(u'QUERY_SEARCH_LIMIT', 1000)
    sql_queries = query.order_by(Query.start_time.asc()).limit(query_limit).all()
    dict_queries = [q.to_dict() for q in sql_queries]
    return Response(json.dumps(dict_queries, default=utils.json_int_dttm_ser), status=200, mimetype=u'application/json')
