django-pyodbc-azure icon indicating copy to clipboard operation
django-pyodbc-azure copied to clipboard

Workaround issue #94: Using Substr with aggregate throws error

Open nattster opened this issue 7 years ago • 0 comments

As suggested by @shaib that Oracle backends encountered this issue as well, they workaround by grouping parameter with same value & type. Then send modified SQL & named parameter to Database engine.

This code transform following SQL:

cursor.execute('''
SELECT 
    SUBSTRING([auth_user].[username], ?, ?) AS [first_letter], 
    COUNT_BIG([auth_user].[id]) AS [user_count] 
FROM [auth_user] 
GROUP BY SUBSTRING([auth_user].[username], ?, ?) 
ORDER BY [first_letter] ASC
''', (1, 1, 1, 1)
)

into:

cursor.execute('''
DECLARE @args0 INT = ?
SELECT 
    SUBSTRING([auth_user].[username], @args0, @args0) AS [first_letter], 
    COUNT_BIG([auth_user].[id]) AS [user_count] 
FROM [auth_user] 
GROUP BY SUBSTRING([auth_user].[username], @args0, @args0) 
ORDER BY [first_letter] ASC
''', (1, )
)

Since, pyodbc does not support Named Parameter. I have to declare variable instead. I know that this pull request need a lot of code clean up.

It is working for me now, but would like you to help review it to improve, especially the part that map Python Data Type to SQL DataType. Suggestions/correction are greatly appreciated.

nattster avatar Jul 04 '17 03:07 nattster