@@ -133,13 +133,18 @@ def _as_sql_variance(self, compiler, connection):
133
133
return self .as_sql (compiler , connection , function = function )
134
134
135
135
def _as_sql_window (self , compiler , connection , template = None ):
136
+ # Get the expressions supported by the backend
136
137
connection .ops .check_expression_support (self )
138
+ # Raise an error if window expressions are not supported.
137
139
if not connection .features .supports_over_clause :
138
140
raise NotSupportedError ("This backend does not support window expressions." )
141
+ # Compile the source expression for the window function.
139
142
expr_sql , params = compiler .compile (self .source_expression )
143
+ # Initialize window SQL parts and parameters.
140
144
window_sql , window_params = [], ()
141
-
145
+ # Handle PARTITION BY clause if present.
142
146
if self .partition_by is not None :
147
+ # Compile the PARTITION BY clause.
143
148
sql_expr , sql_params = self .partition_by .as_sql (
144
149
compiler = compiler ,
145
150
connection = connection ,
@@ -148,21 +153,30 @@ def _as_sql_window(self, compiler, connection, template=None):
148
153
window_sql .append (sql_expr )
149
154
window_params += tuple (sql_params )
150
155
156
+ # Handle ORDER BY clause if present.
151
157
if self .order_by is not None :
158
+ # Compile the ORDER BY clause.
152
159
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 = ()
153
164
window_sql .append (order_sql )
154
165
window_params += tuple (order_params )
155
166
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.
157
168
window_sql .append ('ORDER BY (SELECT NULL)' )
158
169
170
+ # Handle frame specification if present.
159
171
if self .frame :
172
+ # Compile the frame clause.
160
173
frame_sql , frame_params = compiler .compile (self .frame )
161
174
window_sql .append (frame_sql )
162
175
window_params += tuple (frame_params )
163
176
177
+ # Use provided template or default to self.template.
164
178
template = template or self .template
165
-
179
+ # Return the formatted SQL and combined parameters.
166
180
return (
167
181
template % {"expression" : expr_sql , "window" : " " .join (window_sql ).strip ()},
168
182
(* params , * window_params ),
0 commit comments