1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use crate::ast::{
Expr, OrderByExpr, SelectItem, WindowFrame, WindowFrameBound, WindowFrameExtent,
WindowFrameUnits, WindowFunc,
};
use crate::error::DbError;
use crate::types::Value;
use super::aggregates::dispatch_aggregate;
use super::clock::Clock;
use super::context::ExecutionContext;
use super::evaluator::eval_expr;
use super::model::{Group, JoinedRow};
use super::value_helpers::value_to_f64;
use super::value_ops::compare_values;
use std::cmp::Ordering;
use std::collections::HashMap;
pub struct WindowExecutor<'a> {
catalog: &'a dyn crate::catalog::Catalog,
storage: &'a dyn crate::storage::Storage,
clock: &'a dyn Clock,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct WindowSpec {
partition_by: Vec<Expr>,
order_by: Vec<OrderByExpr>,
frame: Option<WindowFrame>,
}
/// A wrapper around a row and its pre-evaluated sort keys for window processing.
struct WindowRow<'a> {
original_idx: usize,
row: &'a JoinedRow,
partition_values: Vec<Value>,
order_values: Vec<Value>,
}
impl<'a> WindowExecutor<'a> {
pub fn new(
catalog: &'a dyn crate::catalog::Catalog,
storage: &'a dyn crate::storage::Storage,
clock: &'a dyn Clock,
) -> Self {
Self {
catalog,
storage,
clock,
}
}
pub fn execute(
&self,
projection: &[SelectItem],
rows: Vec<JoinedRow>,
ctx: &mut ExecutionContext,
) -> Result<super::result::QueryResult, DbError> {
let has_window = projection
.iter()
.any(|item| has_window_function(&item.expr));
if !has_window {
return self.execute_regular_select(projection, rows, ctx);
}
// Group all unique window functions by their window specification
let mut window_specs: Vec<(WindowSpec, Vec<Expr>)> = Vec::new();
for item in projection {
self.collect_window_exprs(&item.expr, &mut window_specs);
}
// Map to store calculated values: results_map[window_expr_debug_string][row_idx] = value
let mut results_map: HashMap<String, Vec<Value>> = HashMap::new();
// Process each window specification group
for (spec, win_exprs) in &window_specs {
// 1. Pre-evaluate all partition and order expressions (Schwartzian Transform)
let mut window_rows: Vec<WindowRow> = rows
.iter()
.enumerate()
.map(|(idx, row)| {
let p_vals = spec
.partition_by
.iter()
.map(|e| {
eval_expr(e, row, ctx, self.catalog, self.storage, self.clock)
.unwrap_or(Value::Null)
})
.collect();
let o_vals = spec
.order_by
.iter()
.map(|o| {
eval_expr(&o.expr, row, ctx, self.catalog, self.storage, self.clock)
.unwrap_or(Value::Null)
})
.collect();
WindowRow {
original_idx: idx,
row,
partition_values: p_vals,
order_values: o_vals,
}
})
.collect();
// 2. Sort rows based on cached PARTITION BY and ORDER BY values
window_rows.sort_by(|a, b| {
// First by partition
for i in 0..spec.partition_by.len() {
let ord = compare_values(&a.partition_values[i], &b.partition_values[i]);
if ord != Ordering::Equal {
return ord;
}
}
// Then by order
for (i, order_expr) in spec.order_by.iter().enumerate() {
let ord = compare_values(&a.order_values[i], &b.order_values[i]);
if ord != Ordering::Equal {
return if order_expr.asc { ord } else { ord.reverse() };
}
}
// Stable sort by original index
a.original_idx.cmp(&b.original_idx)
});
// 3. Identify partition boundaries
let mut partition_starts = Vec::new();
if !window_rows.is_empty() {
partition_starts.push(0);
for i in 1..window_rows.len() {
let mut in_same_partition = true;
for j in 0..spec.partition_by.len() {
if compare_values(
&window_rows[i - 1].partition_values[j],
&window_rows[i].partition_values[j],
) != Ordering::Equal
{
in_same_partition = false;
break;
}
}
if !in_same_partition {
partition_starts.push(i);
}
}
}
partition_starts.push(window_rows.len());
// 4. Calculate window functions for each partition
for p in 0..partition_starts.len() - 1 {
let start = partition_starts[p];
let end = partition_starts[p + 1];
let partition = &window_rows[start..end];
let mut current_rank = 1;
let mut current_dense_rank = 1;
for (i, w_row) in partition.iter().enumerate() {
// Update rank/dense_rank if not the first row and not a peer of the previous row
if i > 0 {
let is_peer = self.are_peers(&partition[i - 1], w_row);
if !is_peer {
current_rank = (i + 1) as i32;
current_dense_rank += 1;
}
}
for win_expr in win_exprs {
let val = match win_expr {
Expr::WindowFunction { func, args, .. } => match func {
WindowFunc::RowNumber => Value::Int((i + 1) as i32),
WindowFunc::Rank => Value::Int(current_rank),
WindowFunc::DenseRank => Value::Int(current_dense_rank),
WindowFunc::Lag => {
let offset = args
.get(1)
.and_then(|e| {
if let Expr::Integer(n) = e {
Some(*n as usize)
} else {
None
}
})
.unwrap_or(1);
if i >= offset {
eval_expr(
&args[0],
partition[i - offset].row,
ctx,
self.catalog,
self.storage,
self.clock,
)
.unwrap_or(Value::Null)
} else {
args.get(2)
.map(|e| {
eval_expr(
e,
w_row.row,
ctx,
self.catalog,
self.storage,
self.clock,
)
.unwrap_or(Value::Null)
})
.unwrap_or(Value::Null)
}
}
WindowFunc::Lead => {
let offset = args
.get(1)
.and_then(|e| {
if let Expr::Integer(n) = e {
Some(*n as usize)
} else {
None
}
})
.unwrap_or(1);
if i + offset < partition.len() {
eval_expr(
&args[0],
partition[i + offset].row,
ctx,
self.catalog,
self.storage,
self.clock,
)
.unwrap_or(Value::Null)
} else {
args.get(2)
.map(|e| {
eval_expr(
e,
w_row.row,
ctx,
self.catalog,
self.storage,
self.clock,
)
.unwrap_or(Value::Null)
})
.unwrap_or(Value::Null)
}
}
WindowFunc::FirstValue => {
let frame_rows = self.get_frame_rows_optimized(
partition,
i,
&spec.frame,
&spec.order_by,
ctx,
);
if frame_rows.is_empty() {
Value::Null
} else {
eval_expr(
&args[0],
frame_rows[0],
ctx,
self.catalog,
self.storage,
self.clock,
)
.unwrap_or(Value::Null)
}
}
WindowFunc::LastValue => {
let frame_rows = self.get_frame_rows_optimized(
partition,
i,
&spec.frame,
&spec.order_by,
ctx,
);
if frame_rows.is_empty() {
Value::Null
} else {
eval_expr(
&args[0],
frame_rows[frame_rows.len() - 1],
ctx,
self.catalog,
self.storage,
self.clock,
)
.unwrap_or(Value::Null)
}
}
WindowFunc::NTile => {
let n_buckets = if let Some(e) = args.first() {
match eval_expr(
e,
w_row.row,
ctx,
self.catalog,
self.storage,
self.clock,
) {
Ok(Value::Int(n)) => n as i64,
Ok(Value::BigInt(n)) => n,
Ok(Value::TinyInt(n)) => n as i64,
Ok(Value::SmallInt(n)) => n as i64,
_ => 1,
}
} else {
1
};
if n_buckets <= 0 {
Value::Null
} else {
let partition_size = partition.len() as i64;
let bucket_size = partition_size / n_buckets;
let remainder = partition_size % n_buckets;
let mut current_row = 0i64;
let mut found_bucket = 1i64;
for b in 1..=n_buckets {
let rows_in_this_bucket =
bucket_size + if b <= remainder { 1 } else { 0 };
if (i as i64) >= current_row
&& (i as i64) < current_row + rows_in_this_bucket
{
found_bucket = b;
break;
}
current_row += rows_in_this_bucket;
}
Value::BigInt(found_bucket)
}
}
WindowFunc::PercentileCont | WindowFunc::PercentileDisc => {
let percentile = if let Some(e) = args.first() {
match eval_expr(
e,
w_row.row,
ctx,
self.catalog,
self.storage,
self.clock,
) {
Ok(Value::Float(v)) => f64::from_bits(v),
Ok(v) => value_to_f64(&v).unwrap_or(f64::NAN),
_ => f64::NAN,
}
} else {
f64::NAN
};
if percentile.is_nan() || !(0.0..=1.0).contains(&percentile) {
Value::Null
} else {
let mut values: Vec<f64> = Vec::new();
for p_row in partition.iter() {
if !p_row.order_values.is_empty() {
if let Ok(f) = value_to_f64(&p_row.order_values[0])
{
values.push(f);
}
}
}
values.sort_by(|a, b| {
a.partial_cmp(b).unwrap_or(Ordering::Equal)
});
if values.is_empty() {
Value::Null
} else {
let n = values.len();
let exact_index = percentile * (n - 1) as f64;
let lo = exact_index.floor() as usize;
let hi = exact_index.ceil() as usize;
if func == &WindowFunc::PercentileDisc {
Value::Float(values[hi].to_bits())
} else if lo == hi {
Value::Float(values[lo].to_bits())
} else {
let frac = exact_index - lo as f64;
let result =
values[lo] * (1.0 - frac) + values[hi] * frac;
Value::Float(result.to_bits())
}
}
}
}
WindowFunc::PercentileRank => {
if partition.len() <= 1 {
Value::Float(0.0f64.to_bits())
} else {
let result = (current_rank - 1) as f64
/ (partition.len() - 1) as f64;
Value::Float(result.to_bits())
}
}
WindowFunc::Aggregate(name) => {
let frame_rows = self.get_frame_rows_optimized(
partition,
i,
&spec.frame,
&spec.order_by,
ctx,
);
let group = Group {
key: vec![],
rows: frame_rows.into_iter().cloned().collect(),
};
let res = dispatch_aggregate(
name.as_str(),
args,
&group,
ctx,
self.catalog,
self.storage,
self.clock,
);
match res {
Some(Ok(v)) => v,
Some(Err(e)) => return Err(e),
None => Value::Null,
}
}
},
_ => Value::Null,
};
let key = format!("{:?}", win_expr);
results_map
.entry(key)
.or_insert_with(|| vec![Value::Null; rows.len()])[w_row.original_idx] =
val;
}
}
}
}
// 5. Final pass to evaluate all projected expressions
let mut final_projected_rows = Vec::with_capacity(rows.len());
let wc = super::context::WindowContext {
results: results_map,
row_idx: 0,
};
ctx.row.window_context = Some(wc);
for (idx, row) in rows.iter().enumerate() {
ctx.row.window_context.as_mut().unwrap().row_idx = idx;
let mut projected_row = Vec::with_capacity(projection.len());
for item in projection {
projected_row.push(eval_expr(
&item.expr,
row,
ctx,
self.catalog,
self.storage,
self.clock,
)?);
}
final_projected_rows.push(projected_row);
}
ctx.row.window_context = None;
let mut column_types =
vec![crate::types::DataType::VarChar { max_len: 4000 }; projection.len()];
for col_idx in 0..projection.len() {
for row in &final_projected_rows {
if !row[col_idx].is_null() {
column_types[col_idx] = row[col_idx]
.data_type()
.unwrap_or(crate::types::DataType::VarChar { max_len: 4000 });
break;
}
}
}
if final_projected_rows.is_empty() {
column_types =
vec![crate::types::DataType::VarChar { max_len: 4000 }; projection.len()];
}
let columns: Vec<String> = projection
.iter()
.map(|i| {
i.alias
.clone()
.unwrap_or_else(|| super::projection::expr_label(&i.expr))
})
.collect();
let column_nullabilities = vec![true; columns.len()];
Ok(super::result::QueryResult {
columns,
column_types,
column_nullabilities,
rows: final_projected_rows,
is_procedure: false,
return_status: None,
})
}
fn are_peers(&self, a: &WindowRow, b: &WindowRow) -> bool {
if a.order_values.len() != b.order_values.len() {
return false;
}
for i in 0..a.order_values.len() {
if compare_values(&a.order_values[i], &b.order_values[i]) != Ordering::Equal {
return false;
}
}
true
}
fn collect_window_exprs(&self, expr: &Expr, window_specs: &mut Vec<(WindowSpec, Vec<Expr>)>) {
match expr {
Expr::WindowFunction {
partition_by,
order_by,
frame,
..
} => {
let spec = WindowSpec {
partition_by: partition_by.clone(),
order_by: order_by.clone(),
frame: frame.clone(),
};
if let Some(existing) = window_specs.iter_mut().find(|(s, _)| s == &spec) {
if !existing.1.contains(expr) {
existing.1.push(expr.clone());
}
} else {
window_specs.push((spec, vec![expr.clone()]));
}
}
Expr::Binary { left, right, .. } => {
self.collect_window_exprs(left, window_specs);
self.collect_window_exprs(right, window_specs);
}
Expr::Unary { expr: inner, .. } => {
self.collect_window_exprs(inner, window_specs);
}
Expr::IsNull(inner)
| Expr::IsNotNull(inner)
| Expr::Cast { expr: inner, .. }
| Expr::Convert { expr: inner, .. }
| Expr::TryCast { expr: inner, .. }
| Expr::TryConvert { expr: inner, .. } => {
self.collect_window_exprs(inner, window_specs);
}
Expr::Case {
operand,
when_clauses,
else_result,
} => {
if let Some(op) = operand {
self.collect_window_exprs(op, window_specs);
}
for wc in when_clauses {
self.collect_window_exprs(&wc.condition, window_specs);
self.collect_window_exprs(&wc.result, window_specs);
}
if let Some(el) = else_result {
self.collect_window_exprs(el, window_specs);
}
}
Expr::FunctionCall { args, .. } => {
for arg in args {
self.collect_window_exprs(arg, window_specs);
}
}
Expr::InList {
expr: inner, list, ..
} => {
self.collect_window_exprs(inner, window_specs);
for item in list {
self.collect_window_exprs(item, window_specs);
}
}
Expr::Between {
expr: inner,
low,
high,
..
} => {
self.collect_window_exprs(inner, window_specs);
self.collect_window_exprs(low, window_specs);
self.collect_window_exprs(high, window_specs);
}
Expr::Like {
expr: inner,
pattern,
..
} => {
self.collect_window_exprs(inner, window_specs);
self.collect_window_exprs(pattern, window_specs);
}
Expr::InSubquery { expr: inner, .. } => {
self.collect_window_exprs(inner, window_specs);
}
_ => {}
}
}
fn get_frame_rows_optimized<'b>(
&self,
partition: &'b [WindowRow<'a>],
current_idx: usize,
frame_spec: &Option<WindowFrame>,
order_by: &[OrderByExpr],
_ctx: &mut ExecutionContext,
) -> Vec<&'a JoinedRow> {
let (start_idx, end_idx) = match frame_spec {
None => {
if order_by.is_empty() {
(0, partition.len())
} else {
(
0,
self.resolve_bound_optimized(
partition,
current_idx,
&WindowFrameBound::CurrentRow,
true,
WindowFrameUnits::Range,
),
)
}
}
Some(f) => match &f.extent {
WindowFrameExtent::Bound(b) => (
self.resolve_bound_optimized(partition, current_idx, b, false, f.units),
self.resolve_bound_optimized(
partition,
current_idx,
&WindowFrameBound::CurrentRow,
true,
f.units,
),
),
WindowFrameExtent::Between(b1, b2) => (
self.resolve_bound_optimized(partition, current_idx, b1, false, f.units),
self.resolve_bound_optimized(partition, current_idx, b2, true, f.units),
),
},
};
let start_clamped = start_idx.min(partition.len());
let end_clamped = end_idx.min(partition.len());
if start_clamped >= end_clamped {
return vec![];
}
partition[start_clamped..end_clamped]
.iter()
.map(|w| w.row)
.collect()
}
fn resolve_bound_optimized(
&self,
partition: &[WindowRow],
current_idx: usize,
bound: &WindowFrameBound,
is_end: bool,
units: WindowFrameUnits,
) -> usize {
match units {
WindowFrameUnits::Rows => match bound {
WindowFrameBound::UnboundedPreceding => 0,
WindowFrameBound::Preceding(n) => {
current_idx.saturating_sub(n.unwrap_or(0) as usize)
}
WindowFrameBound::CurrentRow => {
if is_end {
current_idx + 1
} else {
current_idx
}
}
WindowFrameBound::Following(n) => current_idx + n.unwrap_or(0) as usize + 1,
WindowFrameBound::UnboundedFollowing => partition.len(),
},
WindowFrameUnits::Range | WindowFrameUnits::Groups => match bound {
WindowFrameBound::UnboundedPreceding => 0,
WindowFrameBound::UnboundedFollowing => partition.len(),
WindowFrameBound::CurrentRow => {
if is_end {
let mut i = current_idx;
while i + 1 < partition.len()
&& self.are_peers(&partition[i], &partition[i + 1])
{
i += 1;
}
i + 1
} else {
let mut i = current_idx;
while i > 0 && self.are_peers(&partition[i], &partition[i - 1]) {
i -= 1;
}
i
}
}
_ => {
if is_end {
current_idx + 1
} else {
current_idx
}
}
},
}
}
fn execute_regular_select(
&self,
projection: &[SelectItem],
rows: Vec<JoinedRow>,
ctx: &mut ExecutionContext,
) -> Result<super::result::QueryResult, DbError> {
let mut result = Vec::new();
for row in &rows {
let mut out = Vec::new();
for item in projection {
match &item.expr {
Expr::Wildcard => {
for ct in row {
if let Some(r) = &ct.row {
out.extend(r.values.clone());
}
}
}
expr => {
out.push(
eval_expr(expr, row, ctx, self.catalog, self.storage, self.clock)
.unwrap_or(Value::Null),
);
}
}
}
result.push(out);
}
let columns: Vec<String> = projection
.iter()
.map(|i| i.alias.clone().unwrap_or_else(|| "".to_string()))
.collect();
let mut column_types = Vec::new();
if !result.is_empty() {
for val in &result[0] {
column_types.push(
val.data_type()
.unwrap_or(crate::types::DataType::VarChar { max_len: 4000 }),
);
}
} else {
column_types = vec![crate::types::DataType::VarChar { max_len: 4000 }; columns.len()];
}
let column_nullabilities = vec![true; columns.len()];
Ok(super::result::QueryResult {
columns,
column_types,
column_nullabilities,
rows: result,
is_procedure: false,
return_status: None,
})
}
}
pub fn has_window_function(expr: &Expr) -> bool {
match expr {
Expr::WindowFunction { .. } => true,
Expr::Binary { left, right, .. } => has_window_function(left) || has_window_function(right),
Expr::Unary { expr: inner, .. } => has_window_function(inner),
Expr::Cast { expr: inner, .. }
| Expr::Convert { expr: inner, .. }
| Expr::TryCast { expr: inner, .. }
| Expr::TryConvert { expr: inner, .. }
| Expr::IsNull(inner)
| Expr::IsNotNull(inner) => has_window_function(inner),
Expr::Case {
operand,
when_clauses,
else_result,
} => {
let has_in_operand = operand.as_ref().is_some_and(|e| has_window_function(e));
let has_in_when = when_clauses
.iter()
.any(|wc| has_window_function(&wc.condition) || has_window_function(&wc.result));
let has_in_else = else_result.as_ref().is_some_and(|e| has_window_function(e));
has_in_operand || has_in_when || has_in_else
}
Expr::FunctionCall { args, .. } => args.iter().any(has_window_function),
Expr::InList {
expr: inner, list, ..
} => has_window_function(inner) || list.iter().any(has_window_function),
Expr::Between {
expr: inner,
low,
high,
..
} => has_window_function(inner) || has_window_function(low) || has_window_function(high),
Expr::Like {
expr: inner,
pattern,
..
} => has_window_function(inner) || has_window_function(pattern),
Expr::InSubquery { expr: inner, .. } => has_window_function(inner),
_ => false,
}
}