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
// 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.

//! Schema types for Stoolap - table and column definitions
//!
//! This module defines SchemaColumn and Schema types for table structure.

use std::fmt;
use std::sync::{Arc, OnceLock};

use chrono::{DateTime, Utc};

use crate::common::{CompactArc, StringMap};

use super::error::{Error, Result};
use super::types::{DataType, ForeignKeyAction};

/// A column definition in a table schema
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaColumn {
    /// Unique identifier for the column (0-based index)
    pub id: usize,

    /// Column name
    pub name: String,

    /// Pre-computed lowercase column name for case-insensitive lookups
    pub name_lower: String,

    /// Data type of the column
    pub data_type: DataType,

    /// Whether the column can contain NULL values
    pub nullable: bool,

    /// Whether this column is part of the primary key
    pub primary_key: bool,

    /// Whether this column auto-increments (generates sequential IDs for NULL values)
    pub auto_increment: bool,

    /// Default value expression as a string (to be parsed and evaluated during INSERT)
    pub default_expr: Option<String>,

    /// Pre-computed default value for schema evolution (used when adding column to existing rows)
    pub default_value: Option<super::Value>,

    /// CHECK constraint expression as a string (to be parsed and evaluated during INSERT)
    pub check_expr: Option<String>,

    /// Number of dimensions for VECTOR columns (0 = not a vector column)
    pub vector_dimensions: u16,
}

impl SchemaColumn {
    /// Create a new column definition
    pub fn new(
        id: usize,
        name: impl Into<String>,
        data_type: DataType,
        nullable: bool,
        primary_key: bool,
    ) -> Self {
        let name_str = name.into();
        let name_lower = name_str.to_lowercase();
        Self {
            id,
            name: name_str,
            name_lower,
            data_type,
            nullable,
            primary_key,
            auto_increment: false,
            default_expr: None,
            default_value: None,
            check_expr: None,
            vector_dimensions: 0,
        }
    }

    /// Set vector dimensions (for VECTOR columns)
    pub fn with_vector_dimensions(mut self, dims: u16) -> Self {
        self.vector_dimensions = dims;
        self
    }

    /// Create a new column definition with all options
    #[allow(clippy::too_many_arguments)]
    pub fn with_constraints(
        id: usize,
        name: impl Into<String>,
        data_type: DataType,
        nullable: bool,
        primary_key: bool,
        auto_increment: bool,
        default_expr: Option<String>,
        check_expr: Option<String>,
    ) -> Self {
        let name_str = name.into();
        let name_lower = name_str.to_lowercase();
        Self {
            id,
            name: name_str,
            name_lower,
            data_type,
            nullable,
            primary_key,
            auto_increment,
            default_expr,
            default_value: None,
            check_expr,
            vector_dimensions: 0,
        }
    }

    /// Create a new column definition with pre-computed default value
    #[allow(clippy::too_many_arguments)]
    pub fn with_default_value(
        id: usize,
        name: impl Into<String>,
        data_type: DataType,
        nullable: bool,
        primary_key: bool,
        auto_increment: bool,
        default_expr: Option<String>,
        default_value: Option<super::Value>,
        check_expr: Option<String>,
    ) -> Self {
        let name_str = name.into();
        let name_lower = name_str.to_lowercase();
        Self {
            id,
            name: name_str,
            name_lower,
            data_type,
            nullable,
            primary_key,
            auto_increment,
            default_expr,
            default_value,
            check_expr,
            vector_dimensions: 0,
        }
    }

    /// Create a simple non-nullable, non-primary-key column
    pub fn simple(id: usize, name: impl Into<String>, data_type: DataType) -> Self {
        Self::new(id, name, data_type, false, false)
    }

    /// Create a nullable column
    pub fn nullable(id: usize, name: impl Into<String>, data_type: DataType) -> Self {
        Self::new(id, name, data_type, true, false)
    }

    /// Create a primary key column
    pub fn primary_key(id: usize, name: impl Into<String>, data_type: DataType) -> Self {
        Self::new(id, name, data_type, false, true)
    }
}

impl fmt::Display for SchemaColumn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.data_type == DataType::Vector && self.vector_dimensions > 0 {
            write!(f, "{} VECTOR({})", self.name, self.vector_dimensions)?;
        } else {
            write!(f, "{} {}", self.name, self.data_type)?;
        }
        if self.primary_key {
            write!(f, " PRIMARY KEY")?;
        }
        if !self.nullable && !self.primary_key {
            write!(f, " NOT NULL")?;
        }
        Ok(())
    }
}

/// Foreign key constraint metadata
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForeignKeyConstraint {
    /// Index of the FK column in this table's schema
    pub column_index: usize,
    /// FK column name (for error messages)
    pub column_name: String,
    /// Referenced parent table name (lowercase)
    pub referenced_table: String,
    /// Referenced parent column name (lowercase)
    pub referenced_column: String,
    /// Action when parent row is deleted
    pub on_delete: ForeignKeyAction,
    /// Action when parent PK is updated
    pub on_update: ForeignKeyAction,
}

/// Table schema definition
///

#[derive(Debug)]
pub struct Schema {
    /// Name of the table
    pub table_name: String,

    /// Pre-computed lowercase table name for case-insensitive lookups
    pub table_name_lower: String,

    /// Column definitions
    pub columns: Vec<SchemaColumn>,

    /// Foreign key constraints
    pub foreign_keys: Vec<ForeignKeyConstraint>,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Last update timestamp
    pub updated_at: DateTime<Utc>,

    /// Cached column names (computed lazily on first access, Arc for zero-copy sharing)
    column_names_cache: OnceLock<CompactArc<Vec<String>>>,

    /// Cached primary key column index (computed lazily on first access)
    /// None means not computed yet, Some(None) means no PK, Some(Some(idx)) means PK at idx
    pk_column_index_cache: OnceLock<Option<usize>>,

    /// Cached column index map (lowercase name -> index) for O(1) column lookup
    column_index_map_cache: OnceLock<StringMap<usize>>,

    /// Cached primary key indices (computed lazily on first access)
    pk_indices_cache: OnceLock<Arc<Vec<usize>>>,

    /// Cached lowercase column names (computed lazily on first access)
    column_names_lower_cache: OnceLock<CompactArc<Vec<String>>>,
}

impl Clone for Schema {
    fn clone(&self) -> Self {
        // Clone caches if already computed to avoid recomputation
        let column_names_cache = OnceLock::new();
        if let Some(names) = self.column_names_cache.get() {
            // CompactArc clone is O(1) - just increments ref count
            let _ = column_names_cache.set(CompactArc::clone(names));
        }

        let pk_column_index_cache = OnceLock::new();
        if let Some(pk_idx) = self.pk_column_index_cache.get() {
            let _ = pk_column_index_cache.set(*pk_idx);
        }

        let column_index_map_cache = OnceLock::new();
        if let Some(map) = self.column_index_map_cache.get() {
            let _ = column_index_map_cache.set(map.clone());
        }

        let pk_indices_cache = OnceLock::new();
        if let Some(indices) = self.pk_indices_cache.get() {
            let _ = pk_indices_cache.set(Arc::clone(indices));
        }

        let column_names_lower_cache = OnceLock::new();
        if let Some(names) = self.column_names_lower_cache.get() {
            let _ = column_names_lower_cache.set(CompactArc::clone(names));
        }

        Self {
            table_name: self.table_name.clone(),
            table_name_lower: self.table_name_lower.clone(),
            columns: self.columns.clone(),
            foreign_keys: self.foreign_keys.clone(),
            created_at: self.created_at,
            updated_at: self.updated_at,
            column_names_cache,
            pk_column_index_cache,
            column_index_map_cache,
            pk_indices_cache,
            column_names_lower_cache,
        }
    }
}

impl PartialEq for Schema {
    fn eq(&self, other: &Self) -> bool {
        self.table_name == other.table_name
            && self.columns == other.columns
            && self.foreign_keys == other.foreign_keys
            && self.created_at == other.created_at
            && self.updated_at == other.updated_at
    }
}

impl Eq for Schema {}

impl Schema {
    /// Create a new schema with the given table name and columns
    pub fn new(table_name: impl Into<String>, columns: Vec<SchemaColumn>) -> Self {
        Self::with_foreign_keys(table_name, columns, Vec::new())
    }

    /// Create a new schema with columns and foreign key constraints
    pub fn with_foreign_keys(
        table_name: impl Into<String>,
        columns: Vec<SchemaColumn>,
        foreign_keys: Vec<ForeignKeyConstraint>,
    ) -> Self {
        let now = Utc::now();
        let name = table_name.into();
        let name_lower = name.to_lowercase();

        // Eagerly compute caches to avoid recomputation on clone
        let column_names_cache = OnceLock::new();
        let _ = column_names_cache.set(CompactArc::new(
            columns.iter().map(|c| c.name.clone()).collect(),
        ));

        let pk_column_index_cache = OnceLock::new();
        let pk_idx = columns
            .iter()
            .enumerate()
            .find(|(_, col)| col.primary_key && col.data_type == DataType::Integer)
            .map(|(i, _)| i);
        let _ = pk_column_index_cache.set(pk_idx);

        let column_index_map_cache = OnceLock::new();
        let _ = column_index_map_cache.set(
            columns
                .iter()
                .enumerate()
                .map(|(i, c)| (c.name_lower.clone(), i))
                .collect(),
        );

        let pk_indices_cache = OnceLock::new();
        let _ = pk_indices_cache.set(Arc::new(
            columns
                .iter()
                .enumerate()
                .filter(|(_, c)| c.primary_key)
                .map(|(i, _)| i)
                .collect(),
        ));

        let column_names_lower_cache = OnceLock::new();
        let _ = column_names_lower_cache.set(CompactArc::new(
            columns.iter().map(|c| c.name_lower.clone()).collect(),
        ));

        Self {
            table_name: name,
            table_name_lower: name_lower,
            columns,
            foreign_keys,
            created_at: now,
            updated_at: now,
            column_names_cache,
            pk_column_index_cache,
            column_index_map_cache,
            pk_indices_cache,
            column_names_lower_cache,
        }
    }

    /// Create a new schema with explicit timestamps
    pub fn with_timestamps(
        table_name: impl Into<String>,
        columns: Vec<SchemaColumn>,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
    ) -> Self {
        Self::with_timestamps_and_foreign_keys(
            table_name,
            columns,
            Vec::new(),
            created_at,
            updated_at,
        )
    }

    /// Create a new schema with explicit timestamps and foreign key constraints
    pub fn with_timestamps_and_foreign_keys(
        table_name: impl Into<String>,
        columns: Vec<SchemaColumn>,
        foreign_keys: Vec<ForeignKeyConstraint>,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
    ) -> Self {
        let name = table_name.into();
        let name_lower = name.to_lowercase();

        // Eagerly compute caches to avoid recomputation on clone
        let column_names_cache = OnceLock::new();
        let _ = column_names_cache.set(CompactArc::new(
            columns.iter().map(|c| c.name.clone()).collect(),
        ));

        let pk_column_index_cache = OnceLock::new();
        let pk_idx = columns
            .iter()
            .enumerate()
            .find(|(_, col)| col.primary_key && col.data_type == DataType::Integer)
            .map(|(i, _)| i);
        let _ = pk_column_index_cache.set(pk_idx);

        let column_index_map_cache = OnceLock::new();
        let _ = column_index_map_cache.set(
            columns
                .iter()
                .enumerate()
                .map(|(i, c)| (c.name_lower.clone(), i))
                .collect(),
        );

        let pk_indices_cache = OnceLock::new();
        let _ = pk_indices_cache.set(Arc::new(
            columns
                .iter()
                .enumerate()
                .filter(|(_, c)| c.primary_key)
                .map(|(i, _)| i)
                .collect(),
        ));

        let column_names_lower_cache = OnceLock::new();
        let _ = column_names_lower_cache.set(CompactArc::new(
            columns.iter().map(|c| c.name_lower.clone()).collect(),
        ));

        Self {
            table_name: name,
            table_name_lower: name_lower,
            columns,
            foreign_keys,
            created_at,
            updated_at,
            column_names_cache,
            pk_column_index_cache,
            column_index_map_cache,
            pk_indices_cache,
            column_names_lower_cache,
        }
    }

    /// Get the number of columns
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// Check if the schema has any columns
    pub fn is_empty(&self) -> bool {
        self.columns.is_empty()
    }

    /// Find a column by name (case-insensitive)
    /// Returns the column index and reference
    /// OPTIMIZATION: Uses cached column_index_map for O(1) lookup
    pub fn find_column(&self, name: &str) -> Option<(usize, &SchemaColumn)> {
        let name_lower = name.to_lowercase();
        self.column_index_map()
            .get(&name_lower)
            .map(|&idx| (idx, &self.columns[idx]))
    }

    /// Get a column by index
    pub fn get_column(&self, index: usize) -> Option<&SchemaColumn> {
        self.columns.get(index)
    }

    /// Get a column by name (case-insensitive)
    pub fn get_column_by_name(&self, name: &str) -> Option<&SchemaColumn> {
        self.find_column(name).map(|(_, col)| col)
    }

    /// Get the column index by name (case-insensitive)
    pub fn get_column_index(&self, name: &str) -> Option<usize> {
        self.find_column(name).map(|(idx, _)| idx)
    }

    /// Get the data type of a column by name
    pub fn get_column_type(&self, name: &str) -> Option<DataType> {
        self.get_column_by_name(name).map(|col| col.data_type)
    }

    /// Check if a column exists by name
    pub fn has_column(&self, name: &str) -> bool {
        self.find_column(name).is_some()
    }

    /// Get all column names as borrowed strings (allocates Vec but not strings)
    pub fn column_names(&self) -> Vec<&str> {
        self.columns.iter().map(|c| c.name.as_str()).collect()
    }

    /// Get all column names as owned strings (cached - only clones once)
    ///
    /// This is more efficient than calling `.columns.iter().map(|c| c.name.clone()).collect()`
    /// repeatedly, as the result is computed once and cached.
    #[inline]
    pub fn column_names_owned(&self) -> &[String] {
        self.column_names_cache
            .get_or_init(|| CompactArc::new(self.columns.iter().map(|c| c.name.clone()).collect()))
    }

    /// Get column names as Arc for zero-copy sharing with results
    ///
    /// This is the most efficient way to pass column names to `ExecutorResult::with_arc_columns`
    /// as it avoids any string cloning after the first call.
    #[inline]
    pub fn column_names_arc(&self) -> CompactArc<Vec<String>> {
        CompactArc::clone(
            self.column_names_cache.get_or_init(|| {
                CompactArc::new(self.columns.iter().map(|c| c.name.clone()).collect())
            }),
        )
    }

    /// Get lowercase column names as Arc for zero-copy sharing
    ///
    /// Uses the pre-computed `name_lower` from each SchemaColumn, avoiding
    /// per-query `to_lowercase()` calls.
    #[inline]
    pub fn column_names_lower_arc(&self) -> CompactArc<Vec<String>> {
        CompactArc::clone(self.column_names_lower_cache.get_or_init(|| {
            CompactArc::new(self.columns.iter().map(|c| c.name_lower.clone()).collect())
        }))
    }

    /// Get a cached map of lowercase column names to their indices
    /// OPTIMIZATION: Cached to avoid creating this map on every query
    #[inline]
    pub fn column_index_map(&self) -> &StringMap<usize> {
        self.column_index_map_cache.get_or_init(|| {
            self.columns
                .iter()
                .enumerate()
                .map(|(i, c)| (c.name_lower.clone(), i))
                .collect()
        })
    }

    /// Get the primary key columns
    pub fn primary_key_columns(&self) -> Vec<&SchemaColumn> {
        self.columns.iter().filter(|c| c.primary_key).collect()
    }

    /// Check if the schema has a primary key
    pub fn has_primary_key(&self) -> bool {
        self.columns.iter().any(|c| c.primary_key)
    }

    /// Get the primary key column indices (cached for performance)
    /// OPTIMIZATION: Cached to avoid allocating Vec on every call
    #[inline]
    pub fn primary_key_indices(&self) -> &[usize] {
        self.pk_indices_cache.get_or_init(|| {
            Arc::new(
                self.columns
                    .iter()
                    .enumerate()
                    .filter(|(_, c)| c.primary_key)
                    .map(|(i, _)| i)
                    .collect(),
            )
        })
    }

    /// Get the single primary key column index (cached for performance)
    /// Returns None if there's no PK or if PK is not an integer type
    /// OPTIMIZATION: Cached to avoid iteration on every INSERT
    #[inline]
    pub fn pk_column_index(&self) -> Option<usize> {
        *self.pk_column_index_cache.get_or_init(|| {
            for (i, col) in self.columns.iter().enumerate() {
                if col.primary_key && col.data_type == DataType::Integer {
                    return Some(i);
                }
            }
            None
        })
    }

    /// Validate column count matches expected value
    pub fn validate_column_count(&self, expected: usize) -> Result<()> {
        if self.columns.len() != expected {
            return Err(Error::table_columns_not_match(expected, self.columns.len()));
        }
        Ok(())
    }

    /// Mark the schema as updated (sets updated_at to now)
    pub fn mark_updated(&mut self) {
        self.updated_at = Utc::now();
    }

    /// Rebuild all caches after schema mutation
    /// This replaces the OnceLock fields with fresh ones containing updated values
    fn rebuild_caches(&mut self) {
        // Rebuild column names cache
        self.column_names_cache = OnceLock::new();
        let _ = self.column_names_cache.set(CompactArc::new(
            self.columns.iter().map(|c| c.name.clone()).collect(),
        ));

        // Rebuild PK cache
        self.pk_column_index_cache = OnceLock::new();
        let pk_idx = self
            .columns
            .iter()
            .enumerate()
            .find(|(_, col)| col.primary_key && col.data_type == DataType::Integer)
            .map(|(i, _)| i);
        let _ = self.pk_column_index_cache.set(pk_idx);

        // Rebuild column index map cache
        self.column_index_map_cache = OnceLock::new();
        let _ = self.column_index_map_cache.set(
            self.columns
                .iter()
                .enumerate()
                .map(|(i, c)| (c.name_lower.clone(), i))
                .collect(),
        );

        // Rebuild primary key indices cache
        self.pk_indices_cache = OnceLock::new();
        let _ = self.pk_indices_cache.set(Arc::new(
            self.columns
                .iter()
                .enumerate()
                .filter(|(_, c)| c.primary_key)
                .map(|(i, _)| i)
                .collect(),
        ));

        // Rebuild lowercase column names cache
        self.column_names_lower_cache = OnceLock::new();
        let _ = self.column_names_lower_cache.set(CompactArc::new(
            self.columns.iter().map(|c| c.name_lower.clone()).collect(),
        ));
    }

    /// Add a column to the schema
    pub fn add_column(&mut self, column: SchemaColumn) -> Result<()> {
        // Check for duplicate column name
        if self.has_column(&column.name) {
            return Err(Error::DuplicateColumn);
        }
        self.columns.push(column);
        self.mark_updated();
        self.rebuild_caches();
        Ok(())
    }

    /// Remove a column by name
    pub fn remove_column(&mut self, name: &str) -> Result<SchemaColumn> {
        let idx = self
            .get_column_index(name)
            .ok_or_else(|| Error::ColumnNotFound(name.to_string()))?;
        let column = self.columns.remove(idx);

        // Re-index remaining columns
        for (i, col) in self.columns.iter_mut().enumerate() {
            col.id = i;
        }

        self.mark_updated();
        self.rebuild_caches();
        Ok(column)
    }

    /// Rename a column
    pub fn rename_column(&mut self, old_name: &str, new_name: impl Into<String>) -> Result<()> {
        let new_name = new_name.into();

        // Check new name doesn't exist
        if self.has_column(&new_name) {
            return Err(Error::DuplicateColumn);
        }

        let idx = self
            .get_column_index(old_name)
            .ok_or_else(|| Error::ColumnNotFound(old_name.to_string()))?;

        self.columns[idx].name_lower = new_name.to_lowercase();
        self.columns[idx].name = new_name;
        self.mark_updated();
        self.rebuild_caches();
        Ok(())
    }

    /// Modify a column's properties (except name)
    pub fn modify_column(
        &mut self,
        name: &str,
        data_type: Option<DataType>,
        nullable: Option<bool>,
    ) -> Result<()> {
        let idx = self
            .get_column_index(name)
            .ok_or_else(|| Error::ColumnNotFound(name.to_string()))?;

        if let Some(dt) = data_type {
            self.columns[idx].data_type = dt;
        }
        if let Some(n) = nullable {
            self.columns[idx].nullable = n;
        }

        self.mark_updated();
        self.rebuild_caches();
        Ok(())
    }
}

impl Default for Schema {
    fn default() -> Self {
        Self::new("", Vec::new())
    }
}

impl fmt::Display for Schema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CREATE TABLE {} (", self.table_name)?;
        for (i, col) in self.columns.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}", col)?;
        }
        write!(f, ")")
    }
}

/// Builder for creating schemas more ergonomically
pub struct SchemaBuilder {
    table_name: String,
    columns: Vec<SchemaColumn>,
    foreign_keys: Vec<ForeignKeyConstraint>,
}

impl SchemaBuilder {
    /// Create a new schema builder
    pub fn new(table_name: impl Into<String>) -> Self {
        Self {
            table_name: table_name.into(),
            columns: Vec::new(),
            foreign_keys: Vec::new(),
        }
    }

    /// Add a column
    pub fn column(
        mut self,
        name: impl Into<String>,
        data_type: DataType,
        nullable: bool,
        primary_key: bool,
    ) -> Self {
        let id = self.columns.len();
        self.columns.push(SchemaColumn::new(
            id,
            name,
            data_type,
            nullable,
            primary_key,
        ));
        self
    }

    /// Add a simple non-nullable column
    pub fn add(self, name: impl Into<String>, data_type: DataType) -> Self {
        self.column(name, data_type, false, false)
    }

    /// Add a nullable column
    pub fn add_nullable(self, name: impl Into<String>, data_type: DataType) -> Self {
        self.column(name, data_type, true, false)
    }

    /// Add a primary key column
    pub fn add_primary_key(self, name: impl Into<String>, data_type: DataType) -> Self {
        self.column(name, data_type, false, true)
    }

    /// Add a column with full constraints (default, check)
    #[allow(clippy::too_many_arguments)]
    pub fn add_with_constraints(
        mut self,
        name: impl Into<String>,
        data_type: DataType,
        nullable: bool,
        primary_key: bool,
        auto_increment: bool,
        default_expr: Option<String>,
        check_expr: Option<String>,
    ) -> Self {
        let id = self.columns.len();
        self.columns.push(SchemaColumn::with_constraints(
            id,
            name,
            data_type,
            nullable,
            primary_key,
            auto_increment,
            default_expr,
            check_expr,
        ));
        self
    }

    /// Set vector dimensions on the last added column
    pub fn set_last_vector_dimensions(mut self, dims: u16) -> Self {
        if let Some(col) = self.columns.last_mut() {
            col.vector_dimensions = dims;
        }
        self
    }

    /// Find column index by name (case-insensitive)
    pub fn column_index(&self, name: &str) -> Option<usize> {
        let lower = name.to_lowercase();
        self.columns
            .iter()
            .position(|c| c.name.to_lowercase() == lower)
    }

    /// Check if a column is nullable by index
    pub fn is_column_nullable(&self, idx: usize) -> bool {
        self.columns.get(idx).is_some_and(|c| c.nullable)
    }

    /// Add a foreign key constraint
    pub fn add_foreign_key(mut self, fk: ForeignKeyConstraint) -> Self {
        self.foreign_keys.push(fk);
        self
    }

    /// Build the schema
    pub fn build(self) -> Schema {
        Schema::with_foreign_keys(self.table_name, self.columns, self.foreign_keys)
    }
}

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

    fn create_test_schema() -> Schema {
        SchemaBuilder::new("users")
            .add_primary_key("id", DataType::Integer)
            .add("name", DataType::Text)
            .add_nullable("email", DataType::Text)
            .add("active", DataType::Boolean)
            .build()
    }

    #[test]
    fn test_schema_column_creation() {
        let col = SchemaColumn::new(0, "id", DataType::Integer, false, true);
        assert_eq!(col.id, 0);
        assert_eq!(col.name, "id");
        assert_eq!(col.data_type, DataType::Integer);
        assert!(!col.nullable);
        assert!(col.primary_key);
    }

    #[test]
    fn test_schema_column_helpers() {
        let simple = SchemaColumn::simple(0, "name", DataType::Text);
        assert!(!simple.nullable);
        assert!(!simple.primary_key);

        let nullable = SchemaColumn::nullable(1, "email", DataType::Text);
        assert!(nullable.nullable);
        assert!(!nullable.primary_key);

        let pk = SchemaColumn::primary_key(2, "id", DataType::Integer);
        assert!(!pk.nullable);
        assert!(pk.primary_key);
    }

    #[test]
    fn test_schema_creation() {
        let schema = create_test_schema();
        assert_eq!(schema.table_name, "users");
        assert_eq!(schema.column_count(), 4);
        assert!(!schema.is_empty());
    }

    #[test]
    fn test_schema_find_column() {
        let schema = create_test_schema();

        // Find by exact name
        let (idx, col) = schema.find_column("name").unwrap();
        assert_eq!(idx, 1);
        assert_eq!(col.name, "name");

        // Case-insensitive
        let (idx, _) = schema.find_column("NAME").unwrap();
        assert_eq!(idx, 1);

        // Not found
        assert!(schema.find_column("nonexistent").is_none());
    }

    #[test]
    fn test_schema_get_column() {
        let schema = create_test_schema();

        let col = schema.get_column(0).unwrap();
        assert_eq!(col.name, "id");

        let col = schema.get_column_by_name("email").unwrap();
        assert_eq!(col.data_type, DataType::Text);
        assert!(col.nullable);

        assert!(schema.get_column(100).is_none());
    }

    #[test]
    fn test_schema_column_names() {
        let schema = create_test_schema();
        let names = schema.column_names();
        assert_eq!(names, vec!["id", "name", "email", "active"]);
    }

    #[test]
    fn test_schema_primary_key() {
        let schema = create_test_schema();

        assert!(schema.has_primary_key());

        let pk_cols = schema.primary_key_columns();
        assert_eq!(pk_cols.len(), 1);
        assert_eq!(pk_cols[0].name, "id");

        let pk_indices = schema.primary_key_indices();
        assert_eq!(pk_indices, vec![0]);
    }

    #[test]
    fn test_schema_validate_column_count() {
        let schema = create_test_schema();

        assert!(schema.validate_column_count(4).is_ok());

        let err = schema.validate_column_count(3).unwrap_err();
        assert!(matches!(
            err,
            Error::TableColumnsNotMatch {
                expected: 3,
                got: 4
            }
        ));
    }

    #[test]
    fn test_schema_add_column() {
        let mut schema = create_test_schema();
        let original_count = schema.column_count();

        schema
            .add_column(SchemaColumn::simple(
                original_count,
                "age",
                DataType::Integer,
            ))
            .unwrap();

        assert_eq!(schema.column_count(), original_count + 1);
        assert!(schema.has_column("age"));

        // Duplicate column should fail
        let err = schema
            .add_column(SchemaColumn::simple(0, "age", DataType::Integer))
            .unwrap_err();
        assert!(matches!(err, Error::DuplicateColumn));
    }

    #[test]
    fn test_schema_remove_column() {
        let mut schema = create_test_schema();

        let removed = schema.remove_column("email").unwrap();
        assert_eq!(removed.name, "email");
        assert_eq!(schema.column_count(), 3);
        assert!(!schema.has_column("email"));

        // Column IDs should be re-indexed
        assert_eq!(schema.columns[2].id, 2);

        // Removing non-existent column should fail
        assert!(schema.remove_column("nonexistent").is_err());
    }

    #[test]
    fn test_schema_rename_column() {
        let mut schema = create_test_schema();

        schema.rename_column("name", "full_name").unwrap();
        assert!(schema.has_column("full_name"));
        assert!(!schema.has_column("name"));

        // Renaming to existing name should fail
        let err = schema.rename_column("full_name", "id").unwrap_err();
        assert!(matches!(err, Error::DuplicateColumn));

        // Renaming non-existent column should fail
        assert!(schema.rename_column("nonexistent", "new_name").is_err());
    }

    #[test]
    fn test_schema_modify_column() {
        let mut schema = create_test_schema();

        schema
            .modify_column("name", Some(DataType::Json), Some(true))
            .unwrap();

        let col = schema.get_column_by_name("name").unwrap();
        assert_eq!(col.data_type, DataType::Json);
        assert!(col.nullable);

        // Modifying non-existent column should fail
        assert!(schema
            .modify_column("nonexistent", None, Some(true))
            .is_err());
    }

    #[test]
    fn test_schema_column_display() {
        let col = SchemaColumn::new(0, "id", DataType::Integer, false, true);
        assert_eq!(col.to_string(), "id INTEGER PRIMARY KEY");

        let col = SchemaColumn::new(1, "name", DataType::Text, false, false);
        assert_eq!(col.to_string(), "name TEXT NOT NULL");

        let col = SchemaColumn::new(2, "email", DataType::Text, true, false);
        assert_eq!(col.to_string(), "email TEXT");
    }

    #[test]
    fn test_schema_display() {
        let schema = SchemaBuilder::new("users")
            .add_primary_key("id", DataType::Integer)
            .add("name", DataType::Text)
            .build();

        let expected = "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)";
        assert_eq!(schema.to_string(), expected);
    }

    #[test]
    fn test_schema_builder() {
        let schema = SchemaBuilder::new("products")
            .add_primary_key("id", DataType::Integer)
            .add("name", DataType::Text)
            .add_nullable("description", DataType::Text)
            .add("price", DataType::Float)
            .build();

        assert_eq!(schema.table_name, "products");
        assert_eq!(schema.column_count(), 4);
        assert!(schema.get_column_by_name("id").unwrap().primary_key);
        assert!(schema.get_column_by_name("description").unwrap().nullable);
    }

    #[test]
    fn test_schema_timestamps() {
        let schema1 = Schema::new("test", vec![]);
        std::thread::sleep(std::time::Duration::from_millis(10));
        let schema2 = Schema::new("test", vec![]);

        // Different creation times
        assert!(schema2.created_at >= schema1.created_at);
    }

    #[test]
    fn test_schema_get_column_type() {
        let schema = create_test_schema();

        assert_eq!(schema.get_column_type("id"), Some(DataType::Integer));
        assert_eq!(schema.get_column_type("name"), Some(DataType::Text));
        assert_eq!(schema.get_column_type("active"), Some(DataType::Boolean));
        assert_eq!(schema.get_column_type("nonexistent"), None);
    }
}