How to convert dictionary to SQL Query?

119 Views Asked by At

I have a payload from which I need to generate SQL Query.

payload={
    'Tables':['A', 'B'],
    'Cols':{"A":["Product_Name","Product_Desc","Sales"],
            "B":['Product_Size', 'Product_Desc']},
     'Function': {
         'agg': [{'Type': 'sum', 'Value': 'Enrollments'}],
        "groupby": ['Product_Name','Product_Desc']
}}

I need to read the above Payload and convert into SQL Query dynamically.

Output:

Query={'A':"SELECT Product_Name, Product_Desc,` SUM(Sales) from A GROUP B Product_Name,Product_Desc;"
      ,'B': "SELECT Product_Size, Pro FROM B"}

But I am not getting the correct result

if 'groupby' in payload['Function'].keys():
    groupby_cols = payload['Function']['groupby']
    col_info = payload['Cols']
    for i in col_info:
        if all(item in col_info[i] for item in groupby_cols):
            col_info[i]='GROUP BY ' + ", ".join(groupby_cols)
        else:
            None
    print(col_info)
1

There are 1 best solutions below

0
zoldxk On BEST ANSWER
def convert_to_sql_query(payload):
    sql_queries = {}
    
    for table in payload['Tables']:
        columns = payload['Cols'][table]
        agg_functions = payload['Function'].get('agg', [])
        groupby_cols = payload['Function'].get('groupby', [])
        
        select_clause = ", ".join(columns)
        
        if agg_functions:
            for agg_func in agg_functions:
                agg_type = agg_func['Type']
                agg_column = agg_func['Value']
                select_clause += f", {agg_type.upper()}({agg_column})"

        if groupby_cols:
            groupby_clause = "GROUP BY " + ", ".join(groupby_cols)
        else:
            groupby_clause = ""
            
        query = f"SELECT {select_clause} FROM {table} {groupby_clause};"
        sql_queries[table] = query
        
    return sql_queries

# Example usage:
payload = {
    'Tables': ['A', 'B'],
    'Cols': {
        "A": ["Product_Name", "Product_Desc", "Sales"],
        "B": ['Product_Size', 'Product_Desc']
    },
    'Function': {
        'agg': [{'Type': 'sum', 'Value': 'Enrollments'}],
        "groupby": ['Product_Name', 'Product_Desc']
    }
}

queries = convert_to_sql_query(payload)
print(queries)

Output:

{'A': 'SELECT Product_Name, Product_Desc, Sales, SUM(Enrollments) FROM A GROUP BY Product_Name, Product_Desc;', 'B': 'SELECT Product_Size, Product_Desc, SUM(Enrollments) FROM B GROUP BY Product_Name, Product_Desc;'}