Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply fix for count of group by query #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions sql_server/pyodbc/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import os
import re
import time
import datetime
from decimal import Decimal
from uuid import UUID

from django.core.exceptions import ImproperlyConfigured
from django import VERSION
Expand Down Expand Up @@ -484,6 +487,36 @@ def __init__(self, cursor, connection):
self.last_sql = ''
self.last_params = ()

def _pytype_to_sqltype(self, typ, value):
if value is None:
return 'INT'
elif isinstance(value, str):
length = len(value)
if length == 0:
return 'NVARCHAR'
return 'NVARCHAR(%s)' % len(value)
elif typ == int:
if value < 0x7FFFFFFF and value > -0x7FFFFFFF:
return 'INT'
else:
return 'BIGINT'
elif typ == float:
return 'FLOAT'
elif typ == bool:
return 'BIT'
elif isinstance(value, Decimal):
return 'NUMERIC'
elif isinstance(value, datetime.date):
return 'DATE'
elif isinstance(value, datetime.time):
return 'TIME'
elif isinstance(value, datetime.datetime):
return 'TIMESTAMP'
elif isinstance(value, UUID):
return 'uniqueidentifier'
else:
raise NotImplementedError('not support type %s (%s)' % (type(value), repr(value)))

def close(self):
if self.active:
self.active = False
Expand Down Expand Up @@ -527,8 +560,31 @@ def format_params(self, params):

return tuple(fp)

def _fix_for_params(self, query, params, unify_by_values=False):
if params is None:
params = []
query = query
elif unify_by_values and len(params) > 0:
params = [(param, type(param)) for param in params]
params_dict = {param: '@arg%d' % i for i, param in enumerate(set(params))}
args = [params_dict[param] for param in params]

variables = []
params = []
for key, value in params_dict.items():
datatype = self._pytype_to_sqltype(key[1], key[0])
variables.append("%s %s = %%s " % (value, datatype))
params.append(key[0])
query = ('DECLARE %s \n' % ','.join(variables)) + (query % tuple(args))
params = tuple(params)
return query, params

def execute(self, sql, params=None):
self.last_sql = sql
if 'GROUP BY' in sql:
sql, params = self._fix_for_params(sql, params, unify_by_values=True)
# print ('sql is %s' % sql)
# print ('params is %s' % repr(params))
sql = self.format_sql(sql, params)
params = self.format_params(params)
self.last_params = params
Expand Down