microsoft / mssql-django

The Microsoft Django backend for SQL Server provides a connectivity layer for Django on SQL Server or Azure SQL DB.
Other
350 stars 115 forks source link

Named filter not working #386

Open delcroip opened 7 months ago

delcroip commented 7 months ago

There are some features which are not supported yet. Please check the Limitations first to see if your bug is listed.

Software versions

.venv/lib/python3.10/site-packages/mssql/base.py", line 637, in format_group_by_params
    query = ('DECLARE %s \n' % ','.join(variables)) + (query % tuple(args))
TypeError: format requires a mapping

proposed solution in case params is a dict, it generate an list of param taking the order from the sql

def manage_named_parameters(sql, params):
    if isinstance(params, dict):
        import re

        params = [
            params[p]
            for p in re.findall(r"%\(([\w]+)\)", sql)
        ]
        sql = re.sub(r"%\([\w]+\)", "%", sql)
        return sql, params
    else:
        return sql, params
mShan0 commented 7 months ago

Hi @delcroip, can you provide an example so I can try to reproduce this locally?

delcroip commented 7 months ago

with this data

sql = '''SELECT prod."ProdID" as "ProdID"
    FROM "tblProduct" prod 
    WHERE  prod."LocationId" = %(LocationId)s OR %(LocationId)s = 0 ;'''
params = {"LocationId": locationId}

This fails

cur.execute(sql, params)

this doesn't

cur.execute(*manage_named_parameters(sql,params))

hope it helps (the table can be change to anything the key to reproduce is to have a dict as params ) Note: regarding the error management it param[p] should throw a KeyError as it should that why no error management was added