| 309 | // When mainSource is set (includes mode), include __correlationKey so that |
| 310 | // rows from different parents with the same group key aggregate separately. |
| 311 | const keyExtractor = ([, row]: [ |
| 312 | string, |
| 313 | NamespacedRow & { $selected?: any }, |
| 314 | ]) => { |
| 315 | // Use the original namespaced row for GROUP BY expressions, not $selected |
| 316 | const namespacedRow = { ...row } |
| 317 | delete (namespacedRow as any).$selected |
| 318 | |
| 319 | const key: Record<string, unknown> = {} |
| 320 | |
| 321 | // Use simple __key_X format for each groupBy expression |
| 322 | for (let i = 0; i < groupByClause.length; i++) { |
| 323 | const compiledExpr = compiledGroupByExpressions[i]! |
| 324 | const value = compiledExpr(namespacedRow) |
| 325 | key[`__key_${i}`] = value |
| 326 | } |
| 327 | |
| 328 | if (mainSource) { |
| 329 | key.__correlationKey = (row as any)?.[mainSource]?.__correlationKey |
| 330 | } |
| 331 | |
| 332 | return key |
| 333 | } |
| 334 | |
| 335 | // Create aggregate functions for any aggregated columns in the SELECT clause |
| 336 | const aggregates: Record<string, any> = virtualAggregates |