Skip to content

Commit b2b1234

Browse files
authored
FEAT: Support 5.1 - Handled empty order-by clause by defaulting it to SELECT NULL (#457)
* Handled empty order-by clause by defaulting it to SELECT NULL * removed sql
1 parent 66fec95 commit b2b1234

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

mssql/compiler.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,18 @@ def _as_sql_variance(self, compiler, connection):
133133
return self.as_sql(compiler, connection, function=function)
134134

135135
def _as_sql_window(self, compiler, connection, template=None):
136+
# Get the expressions supported by the backend
136137
connection.ops.check_expression_support(self)
138+
# Raise an error if window expressions are not supported.
137139
if not connection.features.supports_over_clause:
138140
raise NotSupportedError("This backend does not support window expressions.")
141+
# Compile the source expression for the window function.
139142
expr_sql, params = compiler.compile(self.source_expression)
143+
# Initialize window SQL parts and parameters.
140144
window_sql, window_params = [], ()
141-
145+
# Handle PARTITION BY clause if present.
142146
if self.partition_by is not None:
147+
# Compile the PARTITION BY clause.
143148
sql_expr, sql_params = self.partition_by.as_sql(
144149
compiler=compiler,
145150
connection=connection,
@@ -148,21 +153,30 @@ def _as_sql_window(self, compiler, connection, template=None):
148153
window_sql.append(sql_expr)
149154
window_params += tuple(sql_params)
150155

156+
# Handle ORDER BY clause if present.
151157
if self.order_by is not None:
158+
# Compile the ORDER BY clause.
152159
order_sql, order_params = compiler.compile(self.order_by)
160+
# Handles cases where order_by compiles to empty
161+
if not order_sql.strip():
162+
order_sql = "ORDER BY (SELECT NULL)"
163+
order_params = ()
153164
window_sql.append(order_sql)
154165
window_params += tuple(order_params)
155166
else:
156-
# MSSQL window functions require an OVER clause with ORDER BY
167+
# Default to ORDER BY (SELECT NULL) if no order_by is specified.
157168
window_sql.append('ORDER BY (SELECT NULL)')
158169

170+
# Handle frame specification if present.
159171
if self.frame:
172+
# Compile the frame clause.
160173
frame_sql, frame_params = compiler.compile(self.frame)
161174
window_sql.append(frame_sql)
162175
window_params += tuple(frame_params)
163176

177+
# Use provided template or default to self.template.
164178
template = template or self.template
165-
179+
# Return the formatted SQL and combined parameters.
166180
return (
167181
template % {"expression": expr_sql, "window": " ".join(window_sql).strip()},
168182
(*params, *window_params),

0 commit comments

Comments
 (0)