(
&mut self,
transforms: Vec<SqlTransform<RelationExpr, ()>>,
)
| 319 | } |
| 320 | |
| 321 | fn fold_sql_transforms( |
| 322 | &mut self, |
| 323 | transforms: Vec<SqlTransform<RelationExpr, ()>>, |
| 324 | ) -> Result<Vec<SqlTransform<RelationExpr, ()>>> { |
| 325 | let mut sorting = Vec::new(); |
| 326 | // Track whether sorting originated from DISTINCT ON (internal row selection). |
| 327 | // Per PRQL spec, `group` resets order - internal sorts don't define output order. |
| 328 | let mut sorting_from_distinct_on = false; |
| 329 | |
| 330 | let mut result = Vec::with_capacity(transforms.len() + 1); |
| 331 | |
| 332 | for mut transform in transforms { |
| 333 | match transform { |
| 334 | SqlTransform::From(mut expr) => { |
| 335 | match expr.kind { |
| 336 | RelationExprKind::Ref(ref tid) => { |
| 337 | // infer sorting from referenced pipeline |
| 338 | if let Some(cte_sorting) = self.ctes_sorting.get(tid) { |
| 339 | sorting.clone_from(&cte_sorting.sorting); |
| 340 | sorting_from_distinct_on = cte_sorting.from_distinct_on; |
| 341 | } else { |
| 342 | sorting.clear(); |
| 343 | sorting_from_distinct_on = false; |
| 344 | }; |
| 345 | } |
| 346 | RelationExprKind::SubQuery(rel) => { |
| 347 | let rel = self.fold_sql_relation(rel)?; |
| 348 | |
| 349 | // infer sorting from sub-query |
| 350 | sorting = self.last_sorting.drain(..).collect(); |
| 351 | sorting_from_distinct_on = self.last_sorting_from_distinct_on; |
| 352 | |
| 353 | expr.kind = RelationExprKind::SubQuery(rel); |
| 354 | } |
| 355 | } |
| 356 | sorting = |
| 357 | CidRedirector::redirect_sorts(sorting, &expr.riid, &mut self.ctx.anchor); |
| 358 | transform = SqlTransform::From(expr); |
| 359 | } |
| 360 | |
| 361 | // just store sorting and don't emit Sort |
| 362 | SqlTransform::Sort(expr) => { |
| 363 | sorting.clone_from(&expr); |
| 364 | // A new explicit Sort clears the DISTINCT ON flag - this is a |
| 365 | // user-requested ordering, not an internal DISTINCT ON sort. |
| 366 | sorting_from_distinct_on = false; |
| 367 | continue; |
| 368 | } |
| 369 | |
| 370 | // clear sorting |
| 371 | SqlTransform::Distinct | SqlTransform::Aggregate { .. } => { |
| 372 | sorting.clear(); |
| 373 | sorting_from_distinct_on = false; |
| 374 | } |
| 375 | |
| 376 | // Per PRQL spec: `group` resets order, `join` retains left's order. |
| 377 | // DISTINCT ON sorting is internal to the group (for row selection), |
| 378 | // so it must not propagate past joins. Explicit user sorts are preserved. |
no test coverage detected