fsqlite-func 0.1.3

Built-in scalar, aggregate, and window functions
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
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
//! Collation callback trait, built-in collations, and registry (§9.4, §13.6).
//!
//! Collations are pure comparators used by ORDER BY, GROUP BY, DISTINCT,
//! and index traversal. They are open extension points.
//!
//! `compare` is intentionally CPU-only and does not accept `&Cx`.
//!
//! The [`CollationRegistry`] maps case-insensitive names to collation
//! implementations and is pre-populated with the three built-in collations.
//!
//! # Contract
//!
//! Implementations **must** be:
//! - **Deterministic**: same inputs always produce the same output.
//! - **Antisymmetric**: `compare(a, b)` is the reverse of `compare(b, a)`.
//! - **Transitive**: if `a < b` and `b < c`, then `a < c`.
#![allow(clippy::unnecessary_literal_bound)]

use std::cmp::Ordering;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

use tracing::{debug, info};

/// A collation comparator.
///
/// Implementations define total ordering over UTF-8 byte strings.
///
/// Built-in collations: [`BinaryCollation`] (memcmp), [`NoCaseCollation`]
/// (ASCII case-insensitive), [`RtrimCollation`] (trailing-space-insensitive).
pub trait CollationFunction: Send + Sync {
    /// Collation name (for `COLLATE name`).
    fn name(&self) -> &str;

    /// Compare two UTF-8 byte slices.
    ///
    /// Must be deterministic, antisymmetric, and transitive.
    fn compare(&self, left: &[u8], right: &[u8]) -> Ordering;
}

// ── Built-in collations ──────────────────────────────────────────────────

/// BINARY collation: raw `memcmp` byte comparison.
///
/// This is SQLite's default collation. Comparison is byte-by-byte with no
/// locale or case folding.
pub struct BinaryCollation;

impl CollationFunction for BinaryCollation {
    fn name(&self) -> &str {
        "BINARY"
    }

    fn compare(&self, left: &[u8], right: &[u8]) -> Ordering {
        left.cmp(right)
    }
}

/// NOCASE collation: ASCII case-insensitive comparison.
///
/// Only folds ASCII letters (`a-z` → `A-Z`). Non-ASCII bytes are compared
/// as-is. For full Unicode case folding, use the ICU extension (§14.6).
pub struct NoCaseCollation;

impl CollationFunction for NoCaseCollation {
    fn name(&self) -> &str {
        "NOCASE"
    }

    fn compare(&self, left: &[u8], right: &[u8]) -> Ordering {
        let l = left.iter().map(u8::to_ascii_uppercase);
        let r = right.iter().map(u8::to_ascii_uppercase);
        l.cmp(r)
    }
}

/// RTRIM collation: trailing-space-insensitive comparison.
///
/// Trailing ASCII spaces (`0x20`) are stripped before comparison.
/// All other characters (including tabs, non-breaking spaces) are significant.
pub struct RtrimCollation;

impl CollationFunction for RtrimCollation {
    fn name(&self) -> &str {
        "RTRIM"
    }

    fn compare(&self, left: &[u8], right: &[u8]) -> Ordering {
        let l = strip_trailing_spaces(left);
        let r = strip_trailing_spaces(right);
        l.cmp(r)
    }
}

fn strip_trailing_spaces(s: &[u8]) -> &[u8] {
    let mut end = s.len();
    while end > 0 && s[end - 1] == b' ' {
        end -= 1;
    }
    &s[..end]
}

fn builtin_collation(name: &str) -> Option<Arc<dyn CollationFunction>> {
    type BuiltinCollations = (
        Arc<dyn CollationFunction>,
        Arc<dyn CollationFunction>,
        Arc<dyn CollationFunction>,
    );

    static BUILTINS: OnceLock<BuiltinCollations> = OnceLock::new();
    let (binary, nocase, rtrim) = BUILTINS.get_or_init(|| {
        (
            Arc::new(BinaryCollation) as Arc<dyn CollationFunction>,
            Arc::new(NoCaseCollation) as Arc<dyn CollationFunction>,
            Arc::new(RtrimCollation) as Arc<dyn CollationFunction>,
        )
    });
    match name {
        "BINARY" => Some(Arc::clone(binary)),
        "NOCASE" => Some(Arc::clone(nocase)),
        "RTRIM" => Some(Arc::clone(rtrim)),
        _ => None,
    }
}

// ── Collation registry ─────────────────────────────────────────────────

/// Registry for collation functions, keyed by case-insensitive name.
///
/// Pre-populated with the three built-in collations: BINARY, NOCASE, RTRIM.
/// Custom collations can be registered via [`CollationRegistry::register`].
#[derive(Clone)]
pub struct CollationRegistry {
    custom_collations: HashMap<String, Arc<dyn CollationFunction>>,
}

impl std::fmt::Debug for CollationRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CollationRegistry")
            .field("collations", &self.names())
            .finish()
    }
}

impl Default for CollationRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl CollationRegistry {
    /// Create a new registry pre-populated with BINARY, NOCASE, and RTRIM.
    #[must_use]
    pub fn new() -> Self {
        Self {
            custom_collations: HashMap::new(),
        }
    }

    /// Register a custom collation. Returns the previous collation with the
    /// same name if one existed (overwrites).
    ///
    /// Collation names are case-insensitive.
    pub fn register<C: CollationFunction + 'static>(
        &mut self,
        collation: C,
    ) -> Option<Arc<dyn CollationFunction>> {
        let name = collation.name().to_ascii_uppercase();
        info!(collation_name = %name, deterministic = true, "custom collation registration");
        self.custom_collations
            .insert(name.clone(), Arc::new(collation))
            .or_else(|| builtin_collation(&name))
    }

    /// Look up a collation by name (case-insensitive).
    ///
    /// Returns `None` if no collation with the given name is registered.
    #[must_use]
    pub fn find(&self, name: &str) -> Option<Arc<dyn CollationFunction>> {
        let canon = name.to_ascii_uppercase();
        let result = self
            .custom_collations
            .get(&canon)
            .cloned()
            .or_else(|| builtin_collation(&canon));
        debug!(
            collation = %canon,
            hit = result.is_some(),
            "collation registry lookup"
        );
        result
    }

    /// Check whether a collation with the given name is registered.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        let canon = name.to_ascii_uppercase();
        self.custom_collations.contains_key(&canon) || builtin_collation(&canon).is_some()
    }

    /// Return registered collation names in stable display order.
    ///
    /// Built-ins always appear first (`BINARY`, `NOCASE`, `RTRIM`) so pragma
    /// output is deterministic; custom collations follow in case-insensitive
    /// sorted order.
    #[must_use]
    pub fn names(&self) -> Vec<String> {
        let mut names = vec!["BINARY".to_owned(), "NOCASE".to_owned(), "RTRIM".to_owned()];
        let mut custom: Vec<String> = self
            .custom_collations
            .keys()
            .filter(|name| !matches!(name.as_str(), "BINARY" | "NOCASE" | "RTRIM"))
            .cloned()
            .collect();
        custom.sort_unstable_by_key(|name| name.to_ascii_uppercase());
        names.extend(custom);
        names
    }
}

// ── Collation selection ─────────────────────────────────────────────────

/// Source of a collation for precedence resolution (§13.6).
///
/// When two operands in a comparison have different collation sources,
/// the higher-precedence source wins.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CollationSource {
    /// Explicit `COLLATE` clause in the expression (highest precedence).
    Explicit,
    /// Column schema collation (`CREATE TABLE ... COLLATE NOCASE`).
    Schema,
    /// Default (BINARY) when no other source applies (lowest precedence).
    Default,
}

/// An operand's collation annotation: the collation name and where it came from.
#[derive(Debug, Clone)]
pub struct CollationAnnotation {
    /// Collation name (e.g. "BINARY", "NOCASE").
    pub name: String,
    /// Where this collation was specified.
    pub source: CollationSource,
}

/// Resolve which collation to use for a binary comparison (§13.6).
///
/// Precedence rules:
/// 1. Explicit `COLLATE` clause wins. If both operands have explicit
///    collations, the leftmost (LHS) wins.
/// 2. Schema collation from column definition.
/// 3. Default BINARY.
///
/// Returns the collation name to use for the comparison.
#[must_use]
pub fn resolve_collation(lhs: &CollationAnnotation, rhs: &CollationAnnotation) -> String {
    // Precedence: Explicit > Schema > Default. Ties go to LHS (leftmost).
    let result = match (lhs.source, rhs.source) {
        (_, CollationSource::Explicit) if lhs.source != CollationSource::Explicit => &rhs.name,
        (CollationSource::Default, CollationSource::Schema) => &rhs.name,
        _ => &lhs.name,
    };
    debug!(
        collation = %result,
        lhs_source = ?lhs.source,
        rhs_source = ?rhs.source,
        context = "COMPARE",
        "collation selection"
    );
    result.clone()
}

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

    // ── Built-in collation tests (bd-1dc9 + bd-ef4j) ───────────────────

    #[test]
    fn test_collation_binary_memcmp() {
        let coll = BinaryCollation;
        assert_eq!(coll.compare(b"abc", b"abc"), Ordering::Equal);
        assert_eq!(coll.compare(b"abc", b"abd"), Ordering::Less);
        assert_eq!(coll.compare(b"abd", b"abc"), Ordering::Greater);
        // Mixed case: uppercase < lowercase in byte ordering
        assert_eq!(coll.compare(b"ABC", b"abc"), Ordering::Less);
        // Non-ASCII UTF-8: multibyte sequences
        assert_eq!(
            coll.compare("café".as_bytes(), "café".as_bytes()),
            Ordering::Equal
        );
        assert_ne!(coll.compare("über".as_bytes(), b"uber"), Ordering::Equal);
    }

    #[test]
    fn test_collation_binary_basic() {
        let coll = BinaryCollation;
        // 'ABC' < 'abc' under BINARY (uppercase bytes 0x41-0x5A < 0x61-0x7A)
        assert_eq!(coll.compare(b"ABC", b"abc"), Ordering::Less);
        // Byte-by-byte, not character-aware
        assert_eq!(coll.compare(b"\x00", b"\x01"), Ordering::Less);
        assert_eq!(coll.compare(b"\xff", b"\x00"), Ordering::Greater);
    }

    #[test]
    fn test_collation_nocase_ascii() {
        let coll = NoCaseCollation;
        assert_eq!(coll.compare(b"ABC", b"abc"), Ordering::Equal);
        assert_eq!(coll.compare(b"Alice", b"alice"), Ordering::Equal);
        // `[` (0x5B) < `a` (0x61) normally, but NOCASE: `[` (0x5B) > `A` (0x41)
        assert_eq!(coll.compare(b"[", b"a"), Ordering::Greater);
    }

    #[test]
    fn test_collation_nocase_ascii_only() {
        let coll = NoCaseCollation;
        // Non-ASCII bytes are NOT folded — 'Ä' (0xC3 0x84) != 'ä' (0xC3 0xA4)
        assert_ne!(
            coll.compare("Ä".as_bytes(), "ä".as_bytes()),
            Ordering::Equal,
            "NOCASE must NOT fold non-ASCII"
        );
        // Only ASCII A-Z are folded
        assert_eq!(coll.compare(b"Z", b"z"), Ordering::Equal);
        assert_eq!(coll.compare(b"[", b"["), Ordering::Equal);
        // 0x5B '[' is just past 'Z' (0x5A) — must NOT be folded
        assert_ne!(coll.compare(b"[", b"{"), Ordering::Equal);
    }

    #[test]
    fn test_collation_rtrim() {
        let coll = RtrimCollation;
        // Trailing spaces are ignored
        assert_eq!(coll.compare(b"hello   ", b"hello"), Ordering::Equal);
        assert_eq!(coll.compare(b"hello", b"hello   "), Ordering::Equal);
        assert_eq!(coll.compare(b"hello   ", b"hello   "), Ordering::Equal);
        // Non-space trailing chars are NOT ignored
        assert_ne!(coll.compare(b"hello!", b"hello"), Ordering::Equal);
        // Trailing space + different content
        assert_ne!(coll.compare(b"hello ", b"hello!"), Ordering::Equal);
    }

    #[test]
    fn test_collation_rtrim_tabs_not_stripped() {
        let coll = RtrimCollation;
        // Only 0x20 spaces are stripped, NOT tabs (0x09)
        assert_ne!(
            coll.compare(b"hello\t", b"hello"),
            Ordering::Equal,
            "RTRIM must NOT strip tabs"
        );
        // Not non-breaking space either
        assert_ne!(
            coll.compare(b"hello\xc2\xa0", b"hello"),
            Ordering::Equal,
            "RTRIM must NOT strip non-breaking spaces"
        );
    }

    #[test]
    fn test_collation_properties_antisymmetric() {
        let collations: Vec<Box<dyn CollationFunction>> = vec![
            Box::new(BinaryCollation),
            Box::new(NoCaseCollation),
            Box::new(RtrimCollation),
        ];

        let pairs: &[(&[u8], &[u8])] = &[
            (b"abc", b"def"),
            (b"hello", b"world"),
            (b"ABC", b"abc"),
            (b"hello   ", b"hello"),
        ];

        for coll in &collations {
            for &(a, b) in pairs {
                let forward = coll.compare(a, b);
                let reverse = coll.compare(b, a);
                assert_eq!(
                    forward,
                    reverse.reverse(),
                    "{}: compare({:?}, {:?}) = {forward:?}, but reverse = {reverse:?}",
                    coll.name(),
                    std::str::from_utf8(a).unwrap_or("?"),
                    std::str::from_utf8(b).unwrap_or("?"),
                );
            }
        }
    }

    #[test]
    fn test_collation_properties_transitive() {
        let coll = BinaryCollation;
        let a = b"apple";
        let b = b"banana";
        let c = b"cherry";

        // a < b and b < c => a < c
        assert_eq!(coll.compare(a, b), Ordering::Less);
        assert_eq!(coll.compare(b, c), Ordering::Less);
        assert_eq!(coll.compare(a, c), Ordering::Less);
    }

    #[test]
    fn test_collation_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<BinaryCollation>();
        assert_send_sync::<NoCaseCollation>();
        assert_send_sync::<RtrimCollation>();
    }

    // ── Registry tests (bd-ef4j) ────────────────────────────────────────

    #[test]
    fn test_registry_preloaded_builtins() {
        let reg = CollationRegistry::new();
        assert!(reg.contains("BINARY"));
        assert!(reg.contains("NOCASE"));
        assert!(reg.contains("RTRIM"));

        let binary = reg.find("BINARY").expect("BINARY must be pre-registered");
        assert_eq!(binary.compare(b"a", b"b"), Ordering::Less);

        let nocase = reg.find("NOCASE").expect("NOCASE must be pre-registered");
        assert_eq!(nocase.compare(b"ABC", b"abc"), Ordering::Equal);

        let rtrim = reg.find("RTRIM").expect("RTRIM must be pre-registered");
        assert_eq!(rtrim.compare(b"x  ", b"x"), Ordering::Equal);
    }

    struct ReverseCollation;

    impl CollationFunction for ReverseCollation {
        fn name(&self) -> &str {
            "REVERSE"
        }

        fn compare(&self, left: &[u8], right: &[u8]) -> Ordering {
            right.cmp(left)
        }
    }

    #[test]
    fn test_registry_custom_collation_registration() {
        let mut reg = CollationRegistry::new();

        let prev = reg.register(ReverseCollation);
        assert!(prev.is_none(), "no prior REVERSE collation");
        assert!(reg.contains("REVERSE"));

        let coll = reg.find("reverse").expect("case-insensitive lookup");
        assert_eq!(coll.compare(b"a", b"z"), Ordering::Greater);
    }

    struct AlwaysEqualCollation;

    impl CollationFunction for AlwaysEqualCollation {
        fn name(&self) -> &str {
            "BINARY"
        }

        fn compare(&self, _left: &[u8], _right: &[u8]) -> Ordering {
            Ordering::Equal
        }
    }

    #[test]
    fn test_registry_overwrite_builtin() {
        let mut reg = CollationRegistry::new();

        let prev = reg.register(AlwaysEqualCollation);
        assert!(prev.is_some(), "should return previous BINARY collation");

        let coll = reg.find("BINARY").unwrap();
        assert_eq!(
            coll.compare(b"a", b"z"),
            Ordering::Equal,
            "custom overwrite must take effect"
        );
    }

    #[test]
    fn test_registry_unregistered_returns_none() {
        let reg = CollationRegistry::new();
        assert!(reg.find("NONEXISTENT").is_none());
        assert!(!reg.contains("NONEXISTENT"));
    }

    #[test]
    fn test_registry_name_case_insensitive() {
        let reg = CollationRegistry::new();
        // BINARY = binary = Binary
        assert!(reg.find("BINARY").is_some());
        assert!(reg.find("binary").is_some());
        assert!(reg.find("Binary").is_some());
        assert!(reg.find("bInArY").is_some());

        // Contains is also case-insensitive
        assert!(reg.contains("nocase"));
        assert!(reg.contains("NOCASE"));
        assert!(reg.contains("NoCase"));
    }

    // ── Collation selection / precedence tests (bd-ef4j) ────────────────

    fn ann(name: &str, source: CollationSource) -> CollationAnnotation {
        CollationAnnotation {
            name: name.to_owned(),
            source,
        }
    }

    #[test]
    fn test_collation_selection_explicit_wins() {
        // Explicit COLLATE NOCASE on LHS vs default BINARY on RHS
        let result = resolve_collation(
            &ann("NOCASE", CollationSource::Explicit),
            &ann("BINARY", CollationSource::Default),
        );
        assert_eq!(result, "NOCASE");
    }

    #[test]
    fn test_collation_selection_explicit_rhs_wins_over_default() {
        let result = resolve_collation(
            &ann("BINARY", CollationSource::Default),
            &ann("RTRIM", CollationSource::Explicit),
        );
        assert_eq!(result, "RTRIM");
    }

    #[test]
    fn test_collation_selection_leftmost_explicit_wins() {
        // When both operands have explicit COLLATE, leftmost (LHS) wins
        let result = resolve_collation(
            &ann("NOCASE", CollationSource::Explicit),
            &ann("RTRIM", CollationSource::Explicit),
        );
        assert_eq!(result, "NOCASE");
    }

    #[test]
    fn test_collation_selection_schema_over_default() {
        let result = resolve_collation(
            &ann("NOCASE", CollationSource::Schema),
            &ann("BINARY", CollationSource::Default),
        );
        assert_eq!(result, "NOCASE");
    }

    #[test]
    fn test_collation_selection_schema_rhs_over_default() {
        let result = resolve_collation(
            &ann("BINARY", CollationSource::Default),
            &ann("NOCASE", CollationSource::Schema),
        );
        assert_eq!(result, "NOCASE");
    }

    #[test]
    fn test_collation_selection_explicit_over_schema() {
        let result = resolve_collation(
            &ann("RTRIM", CollationSource::Explicit),
            &ann("NOCASE", CollationSource::Schema),
        );
        assert_eq!(result, "RTRIM");
    }

    #[test]
    fn test_collation_selection_default_binary() {
        let result = resolve_collation(
            &ann("BINARY", CollationSource::Default),
            &ann("BINARY", CollationSource::Default),
        );
        assert_eq!(result, "BINARY");
    }

    // ── min/max respect collation tests (bd-ef4j) ───────────────────────

    #[test]
    fn test_min_respects_collation() {
        // Under BINARY: 'ABC' < 'abc' (uppercase bytes < lowercase bytes)
        let binary = BinaryCollation;
        let binary_min = if binary.compare(b"ABC", b"abc") == Ordering::Less {
            "ABC"
        } else {
            "abc"
        };
        assert_eq!(binary_min, "ABC");

        // Under NOCASE: 'ABC' == 'abc', so min could be either (both equal)
        let nocase = NoCaseCollation;
        assert_eq!(nocase.compare(b"ABC", b"abc"), Ordering::Equal);
    }

    #[test]
    fn test_max_respects_collation() {
        let binary = BinaryCollation;
        // Under BINARY: 'abc' > 'ABC'
        let binary_max = if binary.compare(b"abc", b"ABC") == Ordering::Greater {
            "abc"
        } else {
            "ABC"
        };
        assert_eq!(binary_max, "abc");
    }

    #[test]
    fn test_collation_aware_sort() {
        // Simulate ORDER BY with NOCASE collation
        let nocase = NoCaseCollation;
        let mut data: Vec<&[u8]> = vec![b"Banana", b"apple", b"Cherry", b"date"];
        data.sort_by(|a, b| nocase.compare(a, b));

        // NOCASE sort: apple < banana < cherry < date
        assert_eq!(data[0], b"apple");
        assert_eq!(data[1], b"Banana");
        assert_eq!(data[2], b"Cherry");
        assert_eq!(data[3], b"date");
    }

    #[test]
    fn test_collation_aware_group_by() {
        // Under NOCASE, 'ABC' and 'abc' are the same group
        let nocase = NoCaseCollation;
        let items: Vec<&[u8]> = vec![b"ABC", b"abc", b"Abc", b"def", b"DEF"];
        let mut groups: Vec<Vec<&[u8]>> = Vec::new();

        // Simple grouping by sorting then collecting equal runs
        let mut sorted = items;
        sorted.sort_by(|a, b| nocase.compare(a, b));

        let mut current_group: Vec<&[u8]> = vec![sorted[0]];
        for window in sorted.windows(2) {
            if nocase.compare(window[0], window[1]) != Ordering::Equal {
                groups.push(std::mem::take(&mut current_group));
            }
            current_group.push(window[1]);
        }
        groups.push(current_group);

        // Two groups: {ABC, abc, Abc} and {def, DEF}
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[0].len(), 3);
        assert_eq!(groups[1].len(), 2);
    }

    #[test]
    fn test_collation_aware_distinct() {
        // Under NOCASE, SELECT DISTINCT should deduplicate 'ABC' and 'abc'
        let nocase = NoCaseCollation;
        let items: Vec<&[u8]> = vec![b"ABC", b"abc", b"Abc", b"def", b"DEF"];

        let mut distinct: Vec<&[u8]> = Vec::new();
        for item in &items {
            let already = distinct
                .iter()
                .any(|d| nocase.compare(d, item) == Ordering::Equal);
            if !already {
                distinct.push(item);
            }
        }

        // Should have 2 distinct values: one from {ABC/abc/Abc} and one from {def/DEF}
        assert_eq!(distinct.len(), 2);
    }

    #[test]
    fn test_registry_default_impl() {
        // Verify Default trait implementation
        let reg = CollationRegistry::default();
        assert!(reg.contains("BINARY"));
        assert!(reg.contains("NOCASE"));
        assert!(reg.contains("RTRIM"));
    }

    #[test]
    fn test_collation_annotation_debug() {
        let ann = CollationAnnotation {
            name: "NOCASE".to_owned(),
            source: CollationSource::Explicit,
        };
        let debug_str = format!("{ann:?}");
        assert!(debug_str.contains("NOCASE"));
        assert!(debug_str.contains("Explicit"));
    }

    #[test]
    fn test_collation_source_equality() {
        assert_eq!(CollationSource::Explicit, CollationSource::Explicit);
        assert_ne!(CollationSource::Explicit, CollationSource::Schema);
        assert_ne!(CollationSource::Schema, CollationSource::Default);
    }
}