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
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
// 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.

//! Bitmap Index implementation for low-cardinality columns
//!
//! This module provides a bitmap-based index optimized for columns with
//! few distinct values (< 1000). Uses RoaringBitmap for compression.
//!
//! ## Performance characteristics:
//! - INSERT: O(1)
//! - DELETE: O(1)
//! - FIND exact: O(1) bitmap lookup
//! - AND/OR operations: O(n/64) bitwise operations
//!
//! ## When to use BitmapIndex:
//! - BOOLEAN columns (only 2 values)
//! - Status/state columns (pending, active, completed, etc.)
//! - Category columns with few values
//! - Any column with < 1000 distinct values
//!
//! ## When NOT to use BitmapIndex:
//! - High-cardinality columns (use Hash or BTree)
//! - Range queries on numeric data (use BTree)
//! - Unique columns (use Hash or BTree)
//!
//! ## Key advantage:
//! Multi-predicate queries (WHERE a = 1 AND b = 2 AND c = 3) can be
//! answered with O(n/64) bitwise AND operations instead of O(n) scans.
//!
//! ## Implementation:
//! Uses `roaring` crate (RoaringBitmap) - same as Lucene, Druid, Spark.
//! Automatic compression: array for sparse, bitmap for dense, RLE for runs.

use parking_lot::RwLock;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};

use ahash::AHashMap;
use roaring::RoaringTreemap;

use crate::common::{CompactArc, I64Map};
use crate::core::{DataType, Error, IndexEntry, IndexType, Operator, Result, RowIdVec, Value};
use crate::storage::expression::Expression;
use crate::storage::traits::Index;

/// Warning threshold for cardinality
const HIGH_CARDINALITY_WARNING_THRESHOLD: usize = 1000;

/// Bitmap Index for low-cardinality columns
///
/// Optimized for BOOLEAN, status, and category columns where the number
/// of distinct values is small (< 1000).
///
/// ## Key features:
/// - One RoaringBitmap per distinct value
/// - O(n/64) AND/OR/NOT operations for multi-predicate queries
/// - Automatic compression (array, bitmap, or RLE per 8KB chunk)
/// - Thread-safe with RwLock
///
/// ## Memory efficiency:
/// For 1M rows with 10 distinct values:
/// - B-tree: ~80 MB
/// - Bitmap: ~500KB - 2.5MB (30-160x savings)
///
/// ## Row ID Support:
/// Uses RoaringTreemap which supports full i64 row IDs (up to u64::MAX).
/// This is implemented as a BTreeMap of RoaringBitmaps for efficient
/// storage while supporting the full 64-bit range.
pub struct BitmapIndex {
    name: String,
    table_name: String,
    column_names: Vec<String>,
    column_ids: Vec<i32>,
    data_types: Vec<DataType>,
    is_unique: bool,
    closed: AtomicBool,

    /// One bitmap per distinct value
    /// Maps CompactArc<Value> -> RoaringTreemap of row IDs (supports full u64 range)
    /// Uses CompactArc<Value> keys for memory efficiency (8 bytes per key)
    /// AHash for HashDoS resistance (user-controlled indexed values)
    bitmaps: RwLock<AHashMap<CompactArc<Value>, RoaringTreemap>>,

    /// Reverse mapping: row_id -> CompactArc<Value> for efficient removal
    /// Uses I64Map for fast O(1) lookups and CompactArc<Value> (8 bytes per entry)
    row_to_value: RwLock<I64Map<CompactArc<Value>>>,

    /// Track cardinality for warnings
    distinct_count: AtomicUsize,
}

impl std::fmt::Debug for BitmapIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BitmapIndex")
            .field("name", &self.name)
            .field("table_name", &self.table_name)
            .field("column_names", &self.column_names)
            .field("column_ids", &self.column_ids)
            .field("is_unique", &self.is_unique)
            .field(
                "distinct_count",
                &self.distinct_count.load(AtomicOrdering::Relaxed),
            )
            .field("closed", &self.closed.load(AtomicOrdering::Relaxed))
            .finish_non_exhaustive()
    }
}

impl BitmapIndex {
    /// Create a new BitmapIndex
    ///
    /// # Arguments
    /// * `expected_rows` - Hint for initial capacity of row_to_value map.
    ///   Pass 0 if unknown; the map will grow automatically.
    pub fn new(
        name: String,
        table_name: String,
        column_names: Vec<String>,
        column_ids: Vec<i32>,
        data_types: Vec<DataType>,
        is_unique: bool,
        expected_rows: usize,
    ) -> Self {
        Self {
            name,
            table_name,
            column_names,
            column_ids,
            data_types,
            is_unique,
            closed: AtomicBool::new(false),
            bitmaps: RwLock::new(AHashMap::default()),
            row_to_value: RwLock::new(if expected_rows > 0 {
                I64Map::with_capacity(expected_rows)
            } else {
                I64Map::new()
            }),
            distinct_count: AtomicUsize::new(0),
        }
    }

    /// Get the current cardinality (number of distinct values)
    pub fn cardinality(&self) -> usize {
        self.distinct_count.load(AtomicOrdering::Relaxed)
    }

    /// Check if cardinality is too high for efficient bitmap operations
    pub fn is_high_cardinality(&self) -> bool {
        self.cardinality() > HIGH_CARDINALITY_WARNING_THRESHOLD
    }

    /// Get the bitmap for a specific value (for AND/OR operations)
    pub fn get_bitmap(&self, value: &Value) -> Option<RoaringTreemap> {
        // Intern value to get Arc for lookup
        let arc_key = self.value_to_arc_key(std::slice::from_ref(value));
        let bitmaps = self.bitmaps.read();
        bitmaps.get(&arc_key).cloned()
    }

    /// Perform AND operation on multiple values (for multi-predicate queries)
    /// Returns row IDs that match ALL values
    pub fn and_values(&self, values: &[Value]) -> RoaringTreemap {
        let bitmaps = self.bitmaps.read();
        let mut result: Option<RoaringTreemap> = None;

        for value in values {
            let arc_key = self.value_to_arc_key(std::slice::from_ref(value));
            if let Some(bitmap) = bitmaps.get(&arc_key) {
                result = Some(match result {
                    Some(r) => r & bitmap,
                    None => bitmap.clone(),
                });
            } else {
                // Value not found - result is empty
                return RoaringTreemap::new();
            }
        }

        result.unwrap_or_default()
    }

    /// Perform OR operation on multiple values
    /// Returns row IDs that match ANY value
    pub fn or_values(&self, values: &[Value]) -> RoaringTreemap {
        let bitmaps = self.bitmaps.read();
        let mut result = RoaringTreemap::new();

        for value in values {
            let arc_key = self.value_to_arc_key(std::slice::from_ref(value));
            if let Some(bitmap) = bitmaps.get(&arc_key) {
                result |= bitmap;
            }
        }

        result
    }

    /// Perform NOT operation on a value
    /// Returns row IDs that do NOT match the value
    /// Note: Requires knowing all row IDs in the table
    pub fn not_value(&self, value: &Value) -> RoaringTreemap {
        let arc_key = self.value_to_arc_key(std::slice::from_ref(value));
        let bitmaps = self.bitmaps.read();

        // Get all row IDs (union of all bitmaps)
        let mut all_rows = RoaringTreemap::new();
        for bitmap in bitmaps.values() {
            all_rows |= bitmap;
        }

        // Subtract the matching bitmap
        if let Some(bitmap) = bitmaps.get(&arc_key) {
            all_rows - bitmap
        } else {
            all_rows
        }
    }

    /// Convert values to an CompactArc<Value> key
    /// For single-column indexes, wraps the value in Arc
    /// For multi-column indexes, creates a composite key
    fn value_to_arc_key(&self, values: &[Value]) -> CompactArc<Value> {
        if values.len() == 1 {
            CompactArc::new(values[0].clone())
        } else {
            // For multi-column bitmap index, create a composite key
            // This is less common but supported
            let composite = Value::Text(
                values
                    .iter()
                    .map(|v| format!("{:?}", v))
                    .collect::<Vec<_>>()
                    .join("||")
                    .into(),
            );
            CompactArc::new(composite)
        }
    }

    /// Slow path for multi-column indexes (rare case)
    /// Creates composite key and handles add operation
    #[cold]
    fn add_multi_column_slow(
        &self,
        values: &[Value],
        row_id: i64,
        row_id_u64: u64,
        mut bitmaps: parking_lot::RwLockWriteGuard<'_, AHashMap<CompactArc<Value>, RoaringTreemap>>,
        mut row_to_value: parking_lot::RwLockWriteGuard<'_, I64Map<CompactArc<Value>>>,
    ) -> Result<()> {
        // Create composite key for multi-column lookup
        let arc_key = self.value_to_arc_key(values);

        // Check uniqueness constraint
        if self.is_unique {
            let has_null = values.iter().any(|v| v.is_null());
            if !has_null {
                if let Some(bitmap) = bitmaps.get(&arc_key) {
                    let existing_count = if bitmap.contains(row_id_u64) {
                        bitmap.len() - 1
                    } else {
                        bitmap.len()
                    };
                    if existing_count > 0 {
                        let values_str: Vec<String> =
                            values.iter().map(|v| format!("{:?}", v)).collect();
                        return Err(Error::unique_constraint(
                            &self.name,
                            self.column_names.join(", "),
                            format!("[{}]", values_str.join(", ")),
                        ));
                    }
                }
            }
        }

        // Check if row already exists with a different value
        if let Some(old_arc_key) = row_to_value.get(row_id).cloned() {
            if !CompactArc::ptr_eq(&old_arc_key, &arc_key) {
                if let Some(old_bitmap) = bitmaps.get_mut(&old_arc_key) {
                    old_bitmap.remove(row_id_u64);
                    if old_bitmap.is_empty() {
                        bitmaps.remove(&old_arc_key);
                        self.distinct_count.fetch_sub(1, AtomicOrdering::Relaxed);
                    }
                }
            }
        }

        // Add to bitmap
        let is_new_value = !bitmaps.contains_key(&arc_key);
        let bitmap = bitmaps.entry(CompactArc::clone(&arc_key)).or_default();
        bitmap.insert(row_id_u64);

        // Update reverse mapping
        row_to_value.insert(row_id, arc_key);

        if is_new_value {
            self.distinct_count.fetch_add(1, AtomicOrdering::Relaxed);
        }

        Ok(())
    }
}

impl Index for BitmapIndex {
    fn name(&self) -> &str {
        &self.name
    }

    fn table_name(&self) -> &str {
        &self.table_name
    }

    fn build(&mut self) -> Result<()> {
        Ok(())
    }

    fn add(&self, values: &[Value], row_id: i64, _ref_id: i64) -> Result<()> {
        if self.closed.load(AtomicOrdering::Acquire) {
            return Err(Error::IndexClosed);
        }

        // Validate row_id is non-negative (can be safely converted to u64)
        if row_id < 0 {
            return Err(Error::internal(format!(
                "bitmap index: row_id must be non-negative, got {}",
                row_id
            )));
        }
        let row_id_u64 = row_id as u64;

        let num_cols = self.column_ids.len();
        if values.len() != num_cols {
            return Err(Error::internal(format!(
                "expected {} values, got {}",
                num_cols,
                values.len()
            )));
        }

        // Acquire write locks
        let mut bitmaps = self.bitmaps.write();
        let mut row_to_value = self.row_to_value.write();

        // Build lookup key (for single-column, just the first value)
        let lookup_value = if values.len() == 1 {
            &values[0]
        } else {
            // For multi-column, we need to create a composite key for lookup
            // This is less common but supported
            return self.add_multi_column_slow(values, row_id, row_id_u64, bitmaps, row_to_value);
        };

        // Check uniqueness constraint (using Borrow trait for &Value lookup)
        if self.is_unique && !lookup_value.is_null() {
            if let Some(bitmap) = bitmaps.get(lookup_value) {
                // Check if there's already a row with this value (excluding current row)
                let existing_count = if bitmap.contains(row_id_u64) {
                    bitmap.len() - 1
                } else {
                    bitmap.len()
                };
                if existing_count > 0 {
                    return Err(Error::unique_constraint(
                        &self.name,
                        self.column_names.join(", "),
                        format!("{:?}", lookup_value),
                    ));
                }
            }
        }

        // Try to reuse existing Arc if value already exists (O(1) clone)
        // Only create new Arc if this is a new unique value
        let (arc_key, is_new_value) =
            if let Some((existing_arc, _)) = bitmaps.get_key_value(lookup_value) {
                // Value exists - reuse the existing Arc (O(1) atomic refcount bump)
                (CompactArc::clone(existing_arc), false)
            } else {
                // New unique value - create Arc once
                (CompactArc::new(lookup_value.clone()), true)
            };

        // Check if row already exists with a different value (for updates)
        if let Some(old_arc_key) = row_to_value.get(row_id).cloned() {
            // Compare Arc pointers - if same Arc, same value
            if !CompactArc::ptr_eq(&old_arc_key, &arc_key) {
                // Remove from old bitmap
                if let Some(old_bitmap) = bitmaps.get_mut(&old_arc_key) {
                    old_bitmap.remove(row_id_u64);
                    if old_bitmap.is_empty() {
                        bitmaps.remove(&old_arc_key);
                        self.distinct_count.fetch_sub(1, AtomicOrdering::Relaxed);
                    }
                }
            }
        }

        // Add to bitmap
        let bitmap = bitmaps.entry(CompactArc::clone(&arc_key)).or_default();
        bitmap.insert(row_id_u64);

        // Update reverse mapping with Arc reference
        row_to_value.insert(row_id, arc_key);

        // Update cardinality if this is a new distinct value
        if is_new_value {
            self.distinct_count.fetch_add(1, AtomicOrdering::Relaxed);
        }

        Ok(())
    }

    fn add_batch(&self, entries: &I64Map<Vec<Value>>) -> Result<()> {
        for (row_id, values) in entries.iter() {
            self.add(values, row_id, 0)?;
        }
        Ok(())
    }

    fn remove(&self, values: &[Value], row_id: i64, _ref_id: i64) -> Result<()> {
        if self.closed.load(AtomicOrdering::Acquire) {
            return Err(Error::IndexClosed);
        }

        // Validate row_id is non-negative
        if row_id < 0 {
            return Err(Error::internal(format!(
                "bitmap index: row_id must be non-negative, got {}",
                row_id
            )));
        }
        let row_id_u64 = row_id as u64;

        // Intern value to get Arc key for lookup
        let arc_key = self.value_to_arc_key(values);

        let mut bitmaps = self.bitmaps.write();
        let mut row_to_value = self.row_to_value.write();

        // Remove from bitmap
        if let Some(bitmap) = bitmaps.get_mut(&arc_key) {
            bitmap.remove(row_id_u64);
            if bitmap.is_empty() {
                bitmaps.remove(&arc_key);
                self.distinct_count.fetch_sub(1, AtomicOrdering::Relaxed);
            }
        }

        // Remove from reverse mapping
        row_to_value.remove(row_id);

        Ok(())
    }

    fn remove_batch(&self, entries: &I64Map<Vec<Value>>) -> Result<()> {
        for (row_id, values) in entries.iter() {
            self.remove(values, row_id, 0)?;
        }
        Ok(())
    }

    /// Optimized batch add with single lock acquisition
    fn add_batch_slice(&self, entries: &[(i64, &[Value])]) -> Result<()> {
        if entries.is_empty() {
            return Ok(());
        }

        if self.closed.load(AtomicOrdering::Acquire) {
            return Err(Error::IndexClosed);
        }

        let num_cols = self.column_ids.len();

        // Acquire write locks ONCE for entire batch
        let mut bitmaps = self.bitmaps.write();
        let mut row_to_value = self.row_to_value.write();

        // Reserve capacity
        row_to_value.reserve(entries.len());

        // PRE-CHECK PHASE: Validate all unique constraints BEFORE modifying anything
        // This prevents partial batch execution on failure
        if self.is_unique {
            // Track keys seen in this batch for intra-batch duplicate detection
            let mut batch_keys: AHashMap<CompactArc<Value>, i64> =
                AHashMap::with_capacity(entries.len());

            for &(row_id, values) in entries {
                if row_id < 0 || values.len() != num_cols {
                    continue;
                }

                // NULL values don't violate uniqueness
                if values.iter().any(|v| v.is_null()) {
                    continue;
                }

                let row_id_u64 = row_id as u64;
                let arc_key = self.value_to_arc_key(values);

                // Check intra-batch duplicates
                if let Some(&existing_row_id) = batch_keys.get(&arc_key) {
                    if existing_row_id != row_id {
                        return Err(Error::unique_constraint(
                            &self.name,
                            self.column_names.join(", "),
                            format!("{:?}", values),
                        ));
                    }
                }

                // Check against existing index
                if let Some(bitmap) = bitmaps.get(&arc_key) {
                    let existing_count = if bitmap.contains(row_id_u64) {
                        bitmap.len() - 1
                    } else {
                        bitmap.len()
                    };
                    if existing_count > 0 {
                        return Err(Error::unique_constraint(
                            &self.name,
                            self.column_names.join(", "),
                            format!("{:?}", values),
                        ));
                    }
                }

                batch_keys.insert(arc_key, row_id);
            }
        }

        // MODIFICATION PHASE: All constraints checked, now safe to modify
        for &(row_id, values) in entries {
            if row_id < 0 {
                continue; // Skip invalid row IDs
            }
            let row_id_u64 = row_id as u64;

            if values.len() != num_cols {
                continue;
            }

            let arc_key = self.value_to_arc_key(values);

            // Try to reuse existing Arc
            let (final_arc_key, is_new_value) =
                if let Some((existing_arc, _)) = bitmaps.get_key_value(&arc_key) {
                    (CompactArc::clone(existing_arc), false)
                } else {
                    (arc_key, true)
                };

            // Handle update case - remove from old bitmap
            if let Some(old_arc_key) = row_to_value.get(row_id).cloned() {
                if !CompactArc::ptr_eq(&old_arc_key, &final_arc_key) {
                    if let Some(old_bitmap) = bitmaps.get_mut(&old_arc_key) {
                        old_bitmap.remove(row_id_u64);
                        if old_bitmap.is_empty() {
                            bitmaps.remove(&old_arc_key);
                            self.distinct_count.fetch_sub(1, AtomicOrdering::Relaxed);
                        }
                    }
                }
            }

            // Add to bitmap
            let bitmap = bitmaps
                .entry(CompactArc::clone(&final_arc_key))
                .or_default();
            bitmap.insert(row_id_u64);

            // Update reverse mapping
            row_to_value.insert(row_id, final_arc_key);

            if is_new_value {
                self.distinct_count.fetch_add(1, AtomicOrdering::Relaxed);
            }
        }

        Ok(())
    }

    /// Optimized batch remove with single lock acquisition
    fn remove_batch_slice(&self, entries: &[(i64, &[Value])]) -> Result<()> {
        if entries.is_empty() {
            return Ok(());
        }

        if self.closed.load(AtomicOrdering::Acquire) {
            return Err(Error::IndexClosed);
        }

        // Acquire write locks ONCE for entire batch
        let mut bitmaps = self.bitmaps.write();
        let mut row_to_value = self.row_to_value.write();

        for &(row_id, values) in entries {
            if row_id < 0 {
                continue;
            }
            let row_id_u64 = row_id as u64;

            let arc_key = self.value_to_arc_key(values);

            // Remove from bitmap
            if let Some(bitmap) = bitmaps.get_mut(&arc_key) {
                bitmap.remove(row_id_u64);
                if bitmap.is_empty() {
                    bitmaps.remove(&arc_key);
                    self.distinct_count.fetch_sub(1, AtomicOrdering::Relaxed);
                }
            }

            // Remove from reverse mapping
            row_to_value.remove(row_id);
        }

        Ok(())
    }

    fn column_ids(&self) -> &[i32] {
        &self.column_ids
    }

    fn column_names(&self) -> &[String] {
        &self.column_names
    }

    fn data_types(&self) -> &[DataType] {
        &self.data_types
    }

    fn index_type(&self) -> IndexType {
        IndexType::Bitmap
    }

    fn is_unique(&self) -> bool {
        self.is_unique
    }

    fn find(&self, values: &[Value]) -> Result<Vec<IndexEntry>> {
        if self.closed.load(AtomicOrdering::Acquire) {
            return Err(Error::IndexClosed);
        }

        if values.len() != self.column_ids.len() {
            return Err(Error::internal(
                "bitmap index requires exact match on all columns",
            ));
        }

        // Intern value to get Arc key for lookup
        let arc_key = self.value_to_arc_key(values);
        let bitmaps = self.bitmaps.read();

        if let Some(bitmap) = bitmaps.get(&arc_key) {
            Ok(bitmap
                .iter()
                .map(|row_id| IndexEntry {
                    row_id: row_id as i64,
                    ref_id: 0,
                })
                .collect())
        } else {
            Ok(vec![])
        }
    }

    fn find_range(
        &self,
        _min: &[Value],
        _max: &[Value],
        _min_inclusive: bool,
        _max_inclusive: bool,
    ) -> Result<Vec<IndexEntry>> {
        // Bitmap index doesn't efficiently support range queries
        // For ordered values, we could iterate through bitmaps, but it's not optimal
        Err(Error::internal(
            "bitmap index does not efficiently support range queries; use btree index instead",
        ))
    }

    fn find_with_operator(&self, op: Operator, values: &[Value]) -> Result<Vec<IndexEntry>> {
        match op {
            Operator::Eq => self.find(values),
            Operator::Ne => {
                // Use NOT operation
                if values.len() != self.column_ids.len() {
                    return Err(Error::internal(
                        "bitmap index requires exact match on all columns",
                    ));
                }
                // not_value() takes &Value, not the key directly
                // For single column, pass the value; for multi, create composite
                let result = if values.len() == 1 {
                    self.not_value(&values[0])
                } else {
                    let composite = Value::Text(
                        values
                            .iter()
                            .map(|v| format!("{:?}", v))
                            .collect::<Vec<_>>()
                            .join("||")
                            .into(),
                    );
                    self.not_value(&composite)
                };
                Ok(result
                    .iter()
                    .map(|row_id| IndexEntry {
                        row_id: row_id as i64,
                        ref_id: 0,
                    })
                    .collect())
            }
            _ => Err(Error::internal(format!(
                "bitmap index only supports = and != operators, not {:?}",
                op
            ))),
        }
    }

    fn get_row_ids_equal_into(&self, values: &[Value], buffer: &mut Vec<i64>) {
        if self.closed.load(AtomicOrdering::Acquire) {
            return;
        }

        if values.len() != self.column_ids.len() {
            return;
        }

        // Intern value to get Arc key for lookup
        let arc_key = self.value_to_arc_key(values);
        let bitmaps = self.bitmaps.read();

        if let Some(bitmap) = bitmaps.get(&arc_key) {
            // RoaringTreemap iteration is efficient
            buffer.extend(bitmap.iter().map(|row_id| row_id as i64));
        }
    }

    fn get_row_ids_in_range_into(
        &self,
        _min_value: &[Value],
        _max_value: &[Value],
        _include_min: bool,
        _include_max: bool,
        _buffer: &mut Vec<i64>,
    ) {
        // Bitmap index doesn't support range queries efficiently - do nothing
    }

    fn get_filtered_row_ids(&self, expr: &dyn Expression) -> RowIdVec {
        // For complex expressions, return all row IDs and let caller filter
        let bitmaps = self.bitmaps.read();
        let mut all_rows = RoaringTreemap::new();
        for bitmap in bitmaps.values() {
            all_rows |= bitmap;
        }
        let _ = expr;
        let collected: Vec<i64> = all_rows.iter().map(|id| id as i64).collect();
        RowIdVec::from_vec(collected)
    }

    fn get_all_values(&self) -> Vec<Value> {
        let bitmaps = self.bitmaps.read();
        // Dereference CompactArc<Value> to clone inner Value
        bitmaps.keys().map(|arc| (**arc).clone()).collect()
    }

    fn clear(&self) -> Result<()> {
        self.bitmaps.write().clear();
        self.row_to_value.write().clear();
        self.distinct_count.store(0, AtomicOrdering::Relaxed);
        Ok(())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn close(&mut self) -> Result<()> {
        self.closed.store(true, AtomicOrdering::Release);
        self.clear()
    }
}

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

    #[test]
    fn test_bitmap_index_basic() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        // Add entries
        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        index.add(&[Value::Text("pending".into())], 2, 0).unwrap();
        index.add(&[Value::Text("shipped".into())], 3, 0).unwrap();
        index.add(&[Value::Text("shipped".into())], 4, 0).unwrap();
        index.add(&[Value::Text("delivered".into())], 5, 0).unwrap();

        // Check cardinality
        assert_eq!(index.cardinality(), 3);

        // Find by status
        let results = index.find(&[Value::Text("pending".into())]).unwrap();
        assert_eq!(results.len(), 2);

        let results = index.find(&[Value::Text("shipped".into())]).unwrap();
        assert_eq!(results.len(), 2);

        let results = index.find(&[Value::Text("delivered".into())]).unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_bitmap_index_boolean() {
        let index = BitmapIndex::new(
            "idx_active".to_string(),
            "users".to_string(),
            vec!["active".to_string()],
            vec![1],
            vec![DataType::Boolean],
            false,
            0,
        );

        // Add boolean values
        index.add(&[Value::Boolean(true)], 1, 0).unwrap();
        index.add(&[Value::Boolean(true)], 2, 0).unwrap();
        index.add(&[Value::Boolean(true)], 3, 0).unwrap();
        index.add(&[Value::Boolean(false)], 4, 0).unwrap();
        index.add(&[Value::Boolean(false)], 5, 0).unwrap();

        // Only 2 distinct values
        assert_eq!(index.cardinality(), 2);

        let active = index.find(&[Value::Boolean(true)]).unwrap();
        assert_eq!(active.len(), 3);

        let inactive = index.find(&[Value::Boolean(false)]).unwrap();
        assert_eq!(inactive.len(), 2);
    }

    #[test]
    fn test_bitmap_index_and_operation() {
        // Note: AND operation is for combining multiple bitmap indexes
        // Here we test the single-index AND which isn't as useful
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        index.add(&[Value::Text("shipped".into())], 2, 0).unwrap();

        // AND of different values in same column = empty (row can't have two values)
        let result =
            index.and_values(&[Value::Text("pending".into()), Value::Text("shipped".into())]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_bitmap_index_or_operation() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        index.add(&[Value::Text("pending".into())], 2, 0).unwrap();
        index.add(&[Value::Text("shipped".into())], 3, 0).unwrap();
        index.add(&[Value::Text("delivered".into())], 4, 0).unwrap();

        // OR of pending and shipped
        let result =
            index.or_values(&[Value::Text("pending".into()), Value::Text("shipped".into())]);
        assert_eq!(result.len(), 3); // rows 1, 2, 3
    }

    #[test]
    fn test_bitmap_index_not_operation() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        index.add(&[Value::Text("pending".into())], 2, 0).unwrap();
        index.add(&[Value::Text("shipped".into())], 3, 0).unwrap();
        index.add(&[Value::Text("delivered".into())], 4, 0).unwrap();

        // NOT pending = shipped + delivered
        let result = index.not_value(&Value::Text("pending".into()));
        assert_eq!(result.len(), 2); // rows 3, 4
    }

    #[test]
    fn test_bitmap_index_remove() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        index.add(&[Value::Text("pending".into())], 2, 0).unwrap();

        assert_eq!(index.cardinality(), 1);

        // Remove one
        index
            .remove(&[Value::Text("pending".into())], 1, 0)
            .unwrap();

        let results = index.find(&[Value::Text("pending".into())]).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].row_id, 2);

        // Remove last one - cardinality should decrease
        index
            .remove(&[Value::Text("pending".into())], 2, 0)
            .unwrap();
        assert_eq!(index.cardinality(), 0);
    }

    #[test]
    fn test_bitmap_index_update() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        // Initial value
        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        assert_eq!(index.cardinality(), 1);

        // Update to new value
        index.add(&[Value::Text("shipped".into())], 1, 0).unwrap();
        assert_eq!(index.cardinality(), 1); // Old empty bitmap removed

        // Old value should be gone
        let pending = index.find(&[Value::Text("pending".into())]).unwrap();
        assert!(pending.is_empty());

        // New value should be found
        let shipped = index.find(&[Value::Text("shipped".into())]).unwrap();
        assert_eq!(shipped.len(), 1);
        assert_eq!(shipped[0].row_id, 1);
    }

    #[test]
    fn test_bitmap_index_not_equal() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();
        index.add(&[Value::Text("shipped".into())], 2, 0).unwrap();
        index.add(&[Value::Text("delivered".into())], 3, 0).unwrap();

        // != pending should return shipped and delivered
        let results = index
            .find_with_operator(Operator::Ne, &[Value::Text("pending".into())])
            .unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_bitmap_index_high_cardinality_check() {
        let index = BitmapIndex::new(
            "idx_id".to_string(),
            "items".to_string(),
            vec!["id".to_string()],
            vec![1],
            vec![DataType::Integer],
            false,
            0,
        );

        // Add many distinct values
        for i in 0..HIGH_CARDINALITY_WARNING_THRESHOLD + 100 {
            index.add(&[Value::Integer(i as i64)], i as i64, 0).unwrap();
        }

        assert!(index.is_high_cardinality());
    }

    #[test]
    fn test_bitmap_index_null_handling() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        index.add(&[Value::Null(DataType::Text)], 1, 0).unwrap();
        index.add(&[Value::Null(DataType::Text)], 2, 0).unwrap();
        index.add(&[Value::Text("active".into())], 3, 0).unwrap();

        let nulls = index.find(&[Value::Null(DataType::Text)]).unwrap();
        assert_eq!(nulls.len(), 2);
    }

    #[test]
    fn test_bitmap_index_unique_constraint() {
        let index = BitmapIndex::new(
            "idx_status_unique".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            true, // unique
            0,
        );

        index.add(&[Value::Text("pending".into())], 1, 0).unwrap();

        // Try to add duplicate - should fail
        let result = index.add(&[Value::Text("pending".into())], 2, 0);
        assert!(result.is_err());

        // NULL doesn't violate uniqueness
        index.add(&[Value::Null(DataType::Text)], 3, 0).unwrap();
        index.add(&[Value::Null(DataType::Text)], 4, 0).unwrap();
    }

    #[test]
    fn test_bitmap_index_large_row_ids() {
        // Test that bitmap index correctly handles row IDs > u32::MAX
        // This uses RoaringTreemap (64-bit) instead of RoaringBitmap (32-bit)
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        // Use row IDs beyond u32::MAX
        let large_row_id_1: i64 = (u32::MAX as i64) + 1; // 4,294,967,296
        let large_row_id_2: i64 = (u32::MAX as i64) + 1000; // 4,294,968,295
        let large_row_id_3: i64 = i64::MAX / 2; // Very large value

        index
            .add(&[Value::Text("active".into())], large_row_id_1, 0)
            .unwrap();
        index
            .add(&[Value::Text("active".into())], large_row_id_2, 0)
            .unwrap();
        index
            .add(&[Value::Text("inactive".into())], large_row_id_3, 0)
            .unwrap();

        // Verify we can find them
        let results = index.find(&[Value::Text("active".into())]).unwrap();
        assert_eq!(results.len(), 2);
        assert!(results.iter().any(|e| e.row_id == large_row_id_1));
        assert!(results.iter().any(|e| e.row_id == large_row_id_2));

        let results = index.find(&[Value::Text("inactive".into())]).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].row_id, large_row_id_3);

        // Verify removal works
        index
            .remove(&[Value::Text("active".into())], large_row_id_1, 0)
            .unwrap();
        let results = index.find(&[Value::Text("active".into())]).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].row_id, large_row_id_2);
    }

    #[test]
    fn test_bitmap_index_rejects_negative_row_ids() {
        let index = BitmapIndex::new(
            "idx_status".to_string(),
            "orders".to_string(),
            vec!["status".to_string()],
            vec![1],
            vec![DataType::Text],
            false,
            0,
        );

        // Negative row IDs should be rejected
        let result = index.add(&[Value::Text("pending".into())], -1, 0);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("non-negative"));

        let result = index.add(&[Value::Text("pending".into())], i64::MIN, 0);
        assert!(result.is_err());

        // Removal of negative row ID should also be rejected
        let result = index.remove(&[Value::Text("pending".into())], -1, 0);
        assert!(result.is_err());
    }
}