Search code examples
pythonflaskcx-oracle

Conditionally add WHERE clause in Python for cx_Oracle


I have the following Python code :

    params = {}
    query = 'SELECT * FROM LOGS '
    if(date_from and date_to):
        query += ' WHERE LOG_DATE BETWEEN TO_DATE(:date_start, "MM-DD-YYYY") AND LOG_DATE <= TO_DATE(:date_end, "MM-DD-YYYY")'
        params['date_start'] = date_from
        params['date_end'] = date_to
    if(structure):
        query += ' AND STRUCTURE=:structure_val'
        params['structure_val'] = structure
    if(status):
        query += ' AND STATUS =:status'
        params['status'] = status

    cursor.execute(query, params)

Here I am conditionally adding the WHERE clause to the query. But there is an issue when I don't have value for the dates as it will not take the WHERE and will add AND without WHERE. If I add the where clause with the query, if there is no filter, then it will give the wrong query. Is there any better way to do this ? I have been using Laravel for sometime and it's query builder has a method when, which will help to add conditional where clauses. Anything like this in Python for cx_Oracle ?


Solution

  • params = {}
    query = 'SELECT * FROM LOGS '
    query_conditions = []
    
    if(date_from and date_to):
        query_conditions.apend(' WHERE LOG_DATE BETWEEN TO_DATE(:date_start, "MM-DD-YYYY") AND LOG_DATE <= TO_DATE(:date_end, "MM-DD-YYYY")')
        params['date_start'] = date_from
        params['date_end'] = date_to
    if(structure):
        query_conditions.append('STRUCTURE=:structure_val')
        params['structure_val'] = structure
    if(status):
         query_conditions.append('STATUS =:status')
        params['status'] = status
    if query_conditions:
        query += " AND ".join(query_conditions)
    
    cursor.execute(query, params)
    

    add them in list and join values with AND