stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
Documentation
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! RANK and DENSE_RANK window functions

use crate::core::{Result, Value};
use crate::functions::{
    FunctionDataType, FunctionInfo, FunctionSignature, FunctionType, WindowFunction,
};

/// RANK window function
///
/// Returns the rank of the current row within the partition, with gaps.
/// Rows with equal values receive the same rank, and the next rank
/// is the row number (leaving gaps).
///
/// Example: If two rows tie for rank 1, the next row gets rank 3 (not 2).
#[derive(Default)]
pub struct RankFunction;

impl WindowFunction for RankFunction {
    fn name(&self) -> &str {
        "RANK"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "RANK",
            FunctionType::Window,
            "Returns the rank of the current row within the partition, with gaps for ties",
            FunctionSignature::new(FunctionDataType::Integer, vec![], 0, 0),
        )
    }

    fn process(
        &self,
        partition: &[Value],
        _order_by: &[Value],
        current_row: usize,
    ) -> Result<Value> {
        // RANK assigns the same rank to equal values, with gaps
        // Count how many values before current_row are less than current value
        if partition.is_empty() || current_row >= partition.len() {
            return Ok(Value::Integer((current_row + 1) as i64));
        }

        let current_value = &partition[current_row];
        let mut rank = 1i64;

        // Count rows that come before this one in the ordering
        for (i, value) in partition.iter().enumerate() {
            if i >= current_row {
                break;
            }
            if is_less_than(value, current_value) {
                rank += 1;
            }
        }

        Ok(Value::Integer(rank))
    }

    fn clone_box(&self) -> Box<dyn WindowFunction> {
        Box::new(RankFunction)
    }
}

/// DENSE_RANK window function
///
/// Returns the rank of the current row within the partition, without gaps.
/// Rows with equal values receive the same rank, and the next rank
/// is incremented by 1 (no gaps).
///
/// Example: If two rows tie for rank 1, the next row gets rank 2.
#[derive(Default)]
pub struct DenseRankFunction;

impl WindowFunction for DenseRankFunction {
    fn name(&self) -> &str {
        "DENSE_RANK"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "DENSE_RANK",
            FunctionType::Window,
            "Returns the rank of the current row within the partition, without gaps for ties",
            FunctionSignature::new(FunctionDataType::Integer, vec![], 0, 0),
        )
    }

    fn process(
        &self,
        partition: &[Value],
        _order_by: &[Value],
        current_row: usize,
    ) -> Result<Value> {
        // DENSE_RANK assigns the same rank to equal values, without gaps
        if partition.is_empty() || current_row >= partition.len() {
            return Ok(Value::Integer((current_row + 1) as i64));
        }

        let current_value = &partition[current_row];

        // Count distinct values that are less than current value
        let mut seen_values: Vec<&Value> = Vec::new();
        for (i, value) in partition.iter().enumerate() {
            if i >= current_row {
                break;
            }
            if is_less_than(value, current_value)
                && !seen_values.iter().any(|v| values_equal(v, value))
            {
                seen_values.push(value);
            }
        }

        Ok(Value::Integer(seen_values.len() as i64 + 1))
    }

    fn clone_box(&self) -> Box<dyn WindowFunction> {
        Box::new(DenseRankFunction)
    }
}

/// Compare two values for less than
fn is_less_than(a: &Value, b: &Value) -> bool {
    if a.is_null() || b.is_null() {
        return false;
    }
    match (a, b) {
        (Value::Integer(a), Value::Integer(b)) => a < b,
        (Value::Float(a), Value::Float(b)) => a < b,
        (Value::Integer(a), Value::Float(b)) => (*a as f64) < *b,
        (Value::Float(a), Value::Integer(b)) => *a < (*b as f64),
        (Value::Text(a), Value::Text(b)) => a < b,
        (Value::Boolean(a), Value::Boolean(b)) => !a && *b, // false < true
        (Value::Timestamp(a), Value::Timestamp(b)) => a < b,
        _ => false,
    }
}

/// Check if two values are equal
fn values_equal(a: &Value, b: &Value) -> bool {
    if a.is_null() && b.is_null() {
        return true;
    }
    match (a, b) {
        (Value::Integer(a), Value::Integer(b)) => a == b,
        (Value::Float(a), Value::Float(b)) => a == b,
        (Value::Integer(a), Value::Float(b)) => (*a as f64) == *b,
        (Value::Float(a), Value::Integer(b)) => *a == (*b as f64),
        (Value::Text(a), Value::Text(b)) => a == b,
        (Value::Boolean(a), Value::Boolean(b)) => a == b,
        (Value::Timestamp(a), Value::Timestamp(b)) => a == b,
        _ => false,
    }
}

/// PERCENT_RANK window function
///
/// Returns the relative rank of the current row: (rank - 1) / (total_rows - 1).
/// The result is always between 0 and 1. The first row always has PERCENT_RANK of 0.
///
/// Formula: (rank - 1) / (n - 1), where n is the number of rows in the partition.
#[derive(Default)]
pub struct PercentRankFunction;

impl WindowFunction for PercentRankFunction {
    fn name(&self) -> &str {
        "PERCENT_RANK"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "PERCENT_RANK",
            FunctionType::Window,
            "Returns the relative rank of the current row: (rank - 1) / (total_rows - 1)",
            FunctionSignature::new(FunctionDataType::Float, vec![], 0, 0),
        )
    }

    fn process(
        &self,
        partition: &[Value],
        _order_by: &[Value],
        current_row: usize,
    ) -> Result<Value> {
        let n = partition.len();

        // If only one row or empty, return 0
        if n <= 1 {
            return Ok(Value::Float(0.0));
        }

        if current_row >= n {
            return Ok(Value::Float(0.0));
        }

        let current_value = &partition[current_row];

        // Calculate rank (same as RANK function)
        let mut rank = 1i64;
        for (i, value) in partition.iter().enumerate() {
            if i >= current_row {
                break;
            }
            if is_less_than(value, current_value) {
                rank += 1;
            }
        }

        // PERCENT_RANK = (rank - 1) / (n - 1)
        let percent_rank = (rank - 1) as f64 / (n - 1) as f64;
        Ok(Value::Float(percent_rank))
    }

    fn clone_box(&self) -> Box<dyn WindowFunction> {
        Box::new(PercentRankFunction)
    }
}

/// CUME_DIST window function
///
/// Returns the cumulative distribution of a value within a partition.
/// Formula: (number of rows <= current row) / (total rows)
///
/// The result is always between 0 and 1 (exclusive of 0, inclusive of 1).
#[derive(Default)]
pub struct CumeDistFunction;

impl WindowFunction for CumeDistFunction {
    fn name(&self) -> &str {
        "CUME_DIST"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "CUME_DIST",
            FunctionType::Window,
            "Returns the cumulative distribution of a value: (rows <= current) / total_rows",
            FunctionSignature::new(FunctionDataType::Float, vec![], 0, 0),
        )
    }

    fn process(
        &self,
        partition: &[Value],
        _order_by: &[Value],
        current_row: usize,
    ) -> Result<Value> {
        let n = partition.len();

        if n == 0 {
            return Ok(Value::Float(1.0));
        }

        if current_row >= n {
            return Ok(Value::Float(1.0));
        }

        let current_value = &partition[current_row];

        // Count rows that are <= current value (including ties after current row)
        let mut count = 0i64;
        for value in partition.iter() {
            if is_less_than(value, current_value) || values_equal(value, current_value) {
                count += 1;
            }
        }

        // CUME_DIST = count / n
        let cume_dist = count as f64 / n as f64;
        Ok(Value::Float(cume_dist))
    }

    fn clone_box(&self) -> Box<dyn WindowFunction> {
        Box::new(CumeDistFunction)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rank_unique_values() {
        let f = RankFunction;
        // Partition with unique values, sorted
        let partition = vec![Value::Integer(10), Value::Integer(20), Value::Integer(30)];
        let order_by = vec![];

        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Integer(2)
        );
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Integer(3)
        );
    }

    #[test]
    fn test_rank_with_ties() {
        let f = RankFunction;
        // Partition with ties
        let partition = vec![Value::Integer(10), Value::Integer(10), Value::Integer(30)];
        let order_by = vec![];

        // Both first rows have value 10, so they get rank 1
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Integer(1)
        );
        // Third row with value 30 gets rank 3 (gap after the tie)
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Integer(3)
        );
    }

    #[test]
    fn test_dense_rank_unique_values() {
        let f = DenseRankFunction;
        let partition = vec![Value::Integer(10), Value::Integer(20), Value::Integer(30)];
        let order_by = vec![];

        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Integer(2)
        );
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Integer(3)
        );
    }

    #[test]
    fn test_dense_rank_with_ties() {
        let f = DenseRankFunction;
        // Partition with ties
        let partition = vec![Value::Integer(10), Value::Integer(10), Value::Integer(30)];
        let order_by = vec![];

        // Both first rows have value 10, so they get rank 1
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Integer(1)
        );
        // Third row with value 30 gets rank 2 (no gap)
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Integer(2)
        );
    }

    #[test]
    fn test_rank_empty_partition() {
        let f = RankFunction;
        let partition = vec![];
        let order_by = vec![];

        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
    }

    #[test]
    fn test_dense_rank_empty_partition() {
        let f = DenseRankFunction;
        let partition = vec![];
        let order_by = vec![];

        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
    }

    #[test]
    fn test_rank_strings() {
        let f = RankFunction;
        let partition = vec![
            Value::text("apple"),
            Value::text("banana"),
            Value::text("cherry"),
        ];
        let order_by = vec![];

        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Integer(2)
        );
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Integer(3)
        );
    }

    #[test]
    fn test_percent_rank_unique_values() {
        let f = PercentRankFunction;
        // 4 unique values
        let partition = vec![
            Value::Integer(10),
            Value::Integer(20),
            Value::Integer(30),
            Value::Integer(40),
        ];
        let order_by = vec![];

        // PERCENT_RANK = (rank - 1) / (n - 1)
        // Row 0: (1-1)/(4-1) = 0/3 = 0.0
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Float(0.0)
        );
        // Row 1: (2-1)/(4-1) = 1/3 ≈ 0.333
        if let Value::Float(v) = f.process(&partition, &order_by, 1).unwrap() {
            assert!((v - 0.3333333333333333).abs() < 0.0001);
        } else {
            panic!("Expected float");
        }
        // Row 2: (3-1)/(4-1) = 2/3 ≈ 0.667
        if let Value::Float(v) = f.process(&partition, &order_by, 2).unwrap() {
            assert!((v - 0.6666666666666666).abs() < 0.0001);
        } else {
            panic!("Expected float");
        }
        // Row 3: (4-1)/(4-1) = 3/3 = 1.0
        assert_eq!(
            f.process(&partition, &order_by, 3).unwrap(),
            Value::Float(1.0)
        );
    }

    #[test]
    fn test_percent_rank_with_ties() {
        let f = PercentRankFunction;
        // Values: 10, 10, 30 (two ties at rank 1)
        let partition = vec![Value::Integer(10), Value::Integer(10), Value::Integer(30)];
        let order_by = vec![];

        // Both first rows have rank 1: (1-1)/(3-1) = 0
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Float(0.0)
        );
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Float(0.0)
        );
        // Third row has rank 3: (3-1)/(3-1) = 1.0
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Float(1.0)
        );
    }

    #[test]
    fn test_percent_rank_single_row() {
        let f = PercentRankFunction;
        let partition = vec![Value::Integer(10)];
        let order_by = vec![];

        // Single row always has PERCENT_RANK of 0
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Float(0.0)
        );
    }

    #[test]
    fn test_cume_dist_unique_values() {
        let f = CumeDistFunction;
        // 4 unique values
        let partition = vec![
            Value::Integer(10),
            Value::Integer(20),
            Value::Integer(30),
            Value::Integer(40),
        ];
        let order_by = vec![];

        // CUME_DIST = (rows <= current) / total
        // Row 0 (value 10): 1/4 = 0.25
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Float(0.25)
        );
        // Row 1 (value 20): 2/4 = 0.5
        assert_eq!(
            f.process(&partition, &order_by, 1).unwrap(),
            Value::Float(0.5)
        );
        // Row 2 (value 30): 3/4 = 0.75
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Float(0.75)
        );
        // Row 3 (value 40): 4/4 = 1.0
        assert_eq!(
            f.process(&partition, &order_by, 3).unwrap(),
            Value::Float(1.0)
        );
    }

    #[test]
    fn test_cume_dist_with_ties() {
        let f = CumeDistFunction;
        // Values: 10, 10, 30 (two ties)
        let partition = vec![Value::Integer(10), Value::Integer(10), Value::Integer(30)];
        let order_by = vec![];

        // Both rows with value 10: 2/3 ≈ 0.667 (2 rows have value <= 10)
        if let Value::Float(v) = f.process(&partition, &order_by, 0).unwrap() {
            assert!((v - 0.6666666666666666).abs() < 0.0001);
        } else {
            panic!("Expected float");
        }
        if let Value::Float(v) = f.process(&partition, &order_by, 1).unwrap() {
            assert!((v - 0.6666666666666666).abs() < 0.0001);
        } else {
            panic!("Expected float");
        }
        // Row with value 30: 3/3 = 1.0
        assert_eq!(
            f.process(&partition, &order_by, 2).unwrap(),
            Value::Float(1.0)
        );
    }

    #[test]
    fn test_cume_dist_single_row() {
        let f = CumeDistFunction;
        let partition = vec![Value::Integer(10)];
        let order_by = vec![];

        // Single row always has CUME_DIST of 1.0
        assert_eq!(
            f.process(&partition, &order_by, 0).unwrap(),
            Value::Float(1.0)
        );
    }
}