Skip to content

Commit 66fec95

Browse files
authored
FEAT: Support 5.1 - Enhance SQL Compilation and Parameterization for sqlserver_mod (#456)
* made mod() function comapatible with 5.1 * added comment * modified the template calculation * modified the logic
1 parent 37f7dd9 commit 66fec95

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

mssql/functions.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,32 @@ def sqlserver_power(self, compiler, connection, **extra_context):
9494
)
9595

9696
def sqlserver_mod(self, compiler, connection):
97-
# MSSQL doesn't have keyword MOD
97+
# MSSQL doesn't have the MOD keyword
98+
# Get the source expressions (the two arguments to the Mod function)
9899
expr = self.get_source_expressions()
99-
number_a = compiler.compile(expr[0])
100-
number_b = compiler.compile(expr[1])
101-
return self.as_sql(
102-
compiler, connection,
103-
function="",
104-
template='(ABS({a}) - FLOOR(ABS({a}) / ABS({b})) * ABS({b})) * SIGN({a}) * SIGN({b})'.format(
105-
a=number_a[0], b=number_b[0]),
106-
arg_joiner=""
107-
)
108-
100+
# Compile the left-hand side (lhs) expression to SQL and parameters.
101+
lhs_sql, lhs_params = compiler.compile(expr[0])
102+
# Compile the right-hand side (rhs) expression to SQL and parameters.
103+
rhs_sql, rhs_params = compiler.compile(expr[1])
104+
# Build the SQL template for modulo using ABS, FLOOR, and SIGN functions.
105+
template = '(ABS(%s) - FLOOR(ABS(%s) / ABS(%s)) * ABS(%s)) * SIGN(%s) * SIGN(%s)'
106+
# Substitute the compiled SQL expressions into the template.
107+
sql = template % (lhs_sql, lhs_sql, rhs_sql, rhs_sql, lhs_sql, rhs_sql)
108+
# Combine all parameters in the correct order for the SQL statement.
109+
params = lhs_params + lhs_params + rhs_params + rhs_params + lhs_params + rhs_params
110+
try:
111+
# return sql,params
112+
return sql, params
113+
except TypeError:
114+
# Fallback for older Django handling
115+
return self.as_sql(
116+
compiler,
117+
connection,
118+
function="",
119+
template=sql,
120+
arg_joiner="",
121+
params=params
122+
)
109123

110124
def sqlserver_nth_value(self, compiler, connection, **extra_content):
111125
raise NotSupportedError('This backend does not support the NthValue function')

0 commit comments

Comments
 (0)