|
| 1 | +from django.db.models.aggregates import Aggregate, Count, StdDev, Variance |
| 2 | +from django.db.models.functions.window import ( |
| 3 | + CumeDist, |
| 4 | + DenseRank, |
| 5 | + FirstValue, |
| 6 | + Lag, |
| 7 | + LastValue, |
| 8 | + Lead, |
| 9 | + NthValue, |
| 10 | + Ntile, |
| 11 | + PercentRank, |
| 12 | + Rank, |
| 13 | + RowNumber, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +def aggregate(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 18 | + agg_mql = self.as_mql_expr(compiler, connection) |
| 19 | + return {alias: {**agg_mql, "window": default_frame()}}, {} |
| 20 | + |
| 21 | + |
| 22 | +def count(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 23 | + # Count.as_mql_expr() returns {"$sum": lhs_mql} for non-distinct counts. |
| 24 | + # MongoDB's $count is a pipeline stage (not a window accumulator), so use |
| 25 | + # $sum instead. |
| 26 | + agg_mql = self.as_mql_expr(compiler, connection) |
| 27 | + return {alias: {**agg_mql, "window": default_frame()}}, {} |
| 28 | + |
| 29 | + |
| 30 | +def cume_dist(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 31 | + # CumeDist = (rank + group_size - 1) / total. Use $rank for the base rank |
| 32 | + # (1-based, same value for ties), range:[0, 0] for group_size (count of all |
| 33 | + # rows with identical sort key value), and full-partition sum for total. |
| 34 | + rank_alias = f"__wtemp{next(idx)}" |
| 35 | + group_size_alias = f"__wtemp{next(idx)}" |
| 36 | + total_alias = f"__wtemp{next(idx)}" |
| 37 | + output = { |
| 38 | + rank_alias: {"$rank": {}}, |
| 39 | + group_size_alias: {"$sum": 1, "window": {"range": [0, 0]}}, |
| 40 | + total_alias: {"$sum": 1, "window": {"documents": ["unbounded", "unbounded"]}}, |
| 41 | + } |
| 42 | + add_fields = { |
| 43 | + alias: { |
| 44 | + "$divide": [ |
| 45 | + {"$subtract": [{"$add": [f"${rank_alias}", f"${group_size_alias}"]}, 1]}, |
| 46 | + f"${total_alias}", |
| 47 | + ] |
| 48 | + } |
| 49 | + } |
| 50 | + return output, add_fields |
| 51 | + |
| 52 | + |
| 53 | +def dense_rank(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 54 | + return {alias: {"$denseRank": {}}}, {} |
| 55 | + |
| 56 | + |
| 57 | +def first_value(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 58 | + expr = self.get_source_expressions()[0] |
| 59 | + mql = expr.as_mql(compiler, connection, as_expr=True) |
| 60 | + return {alias: {"$first": mql, "window": default_frame()}}, {} |
| 61 | + |
| 62 | + |
| 63 | +def lag(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 64 | + exprs = self.get_source_expressions() |
| 65 | + expr_mql = exprs[0].as_mql(compiler, connection, as_expr=True) |
| 66 | + offset = exprs[1].value |
| 67 | + mql = {"output": expr_mql, "by": -offset} |
| 68 | + if len(exprs) > 2: |
| 69 | + mql["default"] = exprs[2].as_mql(compiler, connection, as_expr=True) |
| 70 | + return {alias: {"$shift": mql}}, {} |
| 71 | + |
| 72 | + |
| 73 | +def last_value(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 74 | + expr = self.get_source_expressions()[0] |
| 75 | + mql = expr.as_mql(compiler, connection, as_expr=True) |
| 76 | + return {alias: {"$last": mql, "window": default_frame()}}, {} |
| 77 | + |
| 78 | + |
| 79 | +def lead(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 80 | + exprs = self.get_source_expressions() |
| 81 | + expr_mql = exprs[0].as_mql(compiler, connection, as_expr=True) |
| 82 | + offset = exprs[1].value |
| 83 | + mql = {"output": expr_mql, "by": offset} |
| 84 | + if len(exprs) > 2: |
| 85 | + mql["default"] = exprs[2].as_mql(compiler, connection, as_expr=True) |
| 86 | + return {alias: {"$shift": mql}}, {} |
| 87 | + |
| 88 | + |
| 89 | +def nth_value(self, compiler, connection, alias, idx, default_frame): |
| 90 | + expr, nth_expr = self.get_source_expressions() |
| 91 | + mql = expr.as_mql(compiler, connection, as_expr=True) |
| 92 | + nth = nth_expr.value |
| 93 | + push_alias = f"__wtemp{next(idx)}" |
| 94 | + output = {push_alias: {"$push": mql, "window": default_frame()}} |
| 95 | + add_fields = { |
| 96 | + alias: { |
| 97 | + "$cond": { |
| 98 | + "if": {"$gte": [{"$size": f"${push_alias}"}, nth]}, |
| 99 | + "then": {"$arrayElemAt": [f"${push_alias}", nth - 1]}, |
| 100 | + "else": None, |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + return output, add_fields |
| 105 | + |
| 106 | + |
| 107 | +def ntile(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 108 | + num_buckets = self.get_source_expressions()[0].value |
| 109 | + doc_num_alias = f"__wtemp{next(idx)}" |
| 110 | + total_alias = f"__wtemp{next(idx)}" |
| 111 | + output = { |
| 112 | + doc_num_alias: {"$documentNumber": {}}, |
| 113 | + total_alias: {"$sum": 1, "window": {"documents": ["unbounded", "unbounded"]}}, |
| 114 | + } |
| 115 | + # SQL NTILE: rows 1..extra*(per+1) go to the first `extra` buckets (each |
| 116 | + # gets per+1 rows); remaining rows are distributed evenly across the rest. |
| 117 | + add_fields = { |
| 118 | + alias: { |
| 119 | + "$let": { |
| 120 | + "vars": { |
| 121 | + "per": {"$floor": {"$divide": [f"${total_alias}", num_buckets]}}, |
| 122 | + "xtra": {"$mod": [f"${total_alias}", num_buckets]}, |
| 123 | + }, |
| 124 | + "in": { |
| 125 | + "$let": { |
| 126 | + "vars": { |
| 127 | + "thr": {"$multiply": ["$$xtra", {"$add": ["$$per", 1]}]}, |
| 128 | + }, |
| 129 | + "in": { |
| 130 | + "$cond": { |
| 131 | + "if": {"$lte": [f"${doc_num_alias}", "$$thr"]}, |
| 132 | + "then": { |
| 133 | + "$add": [ |
| 134 | + { |
| 135 | + "$floor": { |
| 136 | + "$divide": [ |
| 137 | + {"$subtract": [f"${doc_num_alias}", 1]}, |
| 138 | + {"$add": ["$$per", 1]}, |
| 139 | + ] |
| 140 | + } |
| 141 | + }, |
| 142 | + 1, |
| 143 | + ] |
| 144 | + }, |
| 145 | + "else": { |
| 146 | + "$add": [ |
| 147 | + "$$xtra", |
| 148 | + { |
| 149 | + "$floor": { |
| 150 | + "$divide": [ |
| 151 | + { |
| 152 | + "$subtract": [ |
| 153 | + f"${doc_num_alias}", |
| 154 | + {"$add": ["$$thr", 1]}, |
| 155 | + ] |
| 156 | + }, |
| 157 | + # Guard against division by |
| 158 | + # zero when num_buckets > |
| 159 | + # total (per==0). |
| 160 | + {"$max": ["$$per", 1]}, |
| 161 | + ] |
| 162 | + } |
| 163 | + }, |
| 164 | + 1, |
| 165 | + ] |
| 166 | + }, |
| 167 | + } |
| 168 | + }, |
| 169 | + } |
| 170 | + }, |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + return output, add_fields |
| 175 | + |
| 176 | + |
| 177 | +def percent_rank(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 178 | + # Use document-position rank ($sum:1 docs unbounded-to-current) instead of |
| 179 | + # $rank, which MongoDB limits to a single sort field. |
| 180 | + row_num_alias = f"__wtemp{next(idx)}" |
| 181 | + count_alias = f"__wtemp{next(idx)}" |
| 182 | + output = { |
| 183 | + row_num_alias: {"$sum": 1, "window": {"documents": ["unbounded", "current"]}}, |
| 184 | + count_alias: {"$sum": 1, "window": {"documents": ["unbounded", "unbounded"]}}, |
| 185 | + } |
| 186 | + add_fields = { |
| 187 | + alias: { |
| 188 | + "$cond": { |
| 189 | + "if": {"$lte": [f"${count_alias}", 1]}, |
| 190 | + "then": {"$literal": 0.0}, |
| 191 | + "else": { |
| 192 | + "$divide": [ |
| 193 | + {"$subtract": [f"${row_num_alias}", 1]}, |
| 194 | + {"$subtract": [f"${count_alias}", 1]}, |
| 195 | + ] |
| 196 | + }, |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + return output, add_fields |
| 201 | + |
| 202 | + |
| 203 | +def rank(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 204 | + return {alias: {"$rank": {}}}, {} |
| 205 | + |
| 206 | + |
| 207 | +def row_number(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 208 | + return {alias: {"$documentNumber": {}}}, {} |
| 209 | + |
| 210 | + |
| 211 | +def stddev(self, compiler, connection, alias, idx, default_frame): # noqa: ARG001 |
| 212 | + agg_mql = self.as_mql_expr(compiler, connection) |
| 213 | + return {alias: {**agg_mql, "window": default_frame()}}, {} |
| 214 | + |
| 215 | + |
| 216 | +def variance(self, compiler, connection, alias, idx, default_frame): |
| 217 | + # MongoDB has no $varPop/$varSamp window accumulator; compute as stdDev². |
| 218 | + agg_mql = self.as_mql_expr(compiler, connection) |
| 219 | + stddev_alias = f"__wtemp{next(idx)}" |
| 220 | + output = {stddev_alias: {**agg_mql, "window": default_frame()}} |
| 221 | + add_fields = {alias: {"$pow": [f"${stddev_alias}", 2]}} |
| 222 | + return output, add_fields |
| 223 | + |
| 224 | + |
| 225 | +def register_window(): |
| 226 | + Aggregate.get_window_mql = aggregate |
| 227 | + Count.get_window_mql = count |
| 228 | + CumeDist.get_window_mql = cume_dist |
| 229 | + DenseRank.get_window_mql = dense_rank |
| 230 | + FirstValue.get_window_mql = first_value |
| 231 | + Lag.get_window_mql = lag |
| 232 | + LastValue.get_window_mql = last_value |
| 233 | + Lead.get_window_mql = lead |
| 234 | + NthValue.get_window_mql = nth_value |
| 235 | + Ntile.get_window_mql = ntile |
| 236 | + PercentRank.get_window_mql = percent_rank |
| 237 | + Rank.get_window_mql = rank |
| 238 | + RowNumber.get_window_mql = row_number |
| 239 | + StdDev.get_window_mql = stddev |
| 240 | + Variance.get_window_mql = variance |
0 commit comments