heliosdb-nano 3.22.3

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
//! Configuration for HeliosDB Lite
//!
//! This module provides comprehensive configuration options for the database.
//! Configuration can be loaded from TOML files or constructed programmatically.
//!
//! # Configuration Sections
//!
//! - [`StorageConfig`] - Database path, WAL, compression, caching
//! - [`EncryptionConfig`] - Encryption at rest with AES-256-GCM
//! - [`ServerConfig`] - Network settings, TLS, connection limits
//! - [`SessionConfig`] - Session timeouts and per-user limits
//! - [`LockConfig`] - Lock acquisition timeouts, deadlock detection
//! - [`DumpConfig`] - Backup scheduling and compression
//! - [`VectorConfig`] - Vector index settings (HNSW, PQ)
//!
//! # Example: TOML Configuration
//!
//! ```toml
//! [storage]
//! path = "./data"
//! memory_only = false
//! wal_enabled = true
//! compression = "Zstd"
//!
//! [server]
//! listen_addr = "0.0.0.0"
//! port = 5432
//! max_connections = 100
//!
//! [session]
//! timeout_secs = 3600
//! max_sessions_per_user = 10
//! ```
//!
//! # Example: Programmatic Configuration
//!
//! ```rust
//! use heliosdb_nano::Config;
//!
//! // In-memory database
//! let config = Config::in_memory();
//!
//! // Load from file
//! // let config = Config::from_file("heliosdb.toml")?;
//! ```

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Database configuration
///
/// The main configuration struct for HeliosDB Lite. All configuration
/// sections use sensible defaults and can be customized individually.
///
/// # Loading Configuration
///
/// ```rust,no_run
/// use heliosdb_nano::Config;
///
/// // Default configuration with file-based storage
/// let config = Config::default();
///
/// // In-memory database (for testing)
/// let config = Config::in_memory();
///
/// // Load from TOML file
/// let config = Config::from_file("heliosdb.toml")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Validation
///
/// Call [`validate()`](Config::validate) to check all configuration values
/// before using the configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Storage configuration
    #[serde(default)]
    pub storage: StorageConfig,
    /// Encryption configuration
    #[serde(default)]
    pub encryption: EncryptionConfig,
    /// Server configuration
    #[serde(default)]
    pub server: ServerConfig,
    /// Performance configuration
    #[serde(default)]
    pub performance: PerformanceConfig,
    /// Audit configuration
    #[serde(default)]
    pub audit: crate::audit::AuditConfig,
    /// Optimizer configuration (v2.1)
    #[serde(default)]
    pub optimizer: OptimizerConfig,
    /// Authentication configuration (v2.1)
    #[serde(default)]
    pub authentication: AuthenticationConfig,
    /// Compression configuration (v2.1)
    #[serde(default)]
    pub compression: CompressionConfig,
    /// Materialized view configuration (v2.1)
    #[serde(default)]
    pub materialized_views: MaterializedViewConfig,
    /// Vector index configuration (v2.1)
    #[serde(default)]
    pub vector: VectorConfig,
    /// Sync configuration (v2.3 - Experimental)
    #[serde(default)]
    pub sync: SyncConfig,
    /// Session configuration (v3.1.0)
    #[serde(default)]
    pub session: SessionConfig,
    /// Lock configuration (v3.1.0)
    #[serde(default)]
    pub locks: LockConfig,
    /// Dump configuration (v3.1.0)
    #[serde(default)]
    pub dump: DumpConfig,
    /// Resource quota configuration (v3.1.0)
    #[serde(default)]
    pub resource_quotas: ResourceQuotaConfig,
    /// BaaS REST API configuration (v3.2.0)
    #[serde(default)]
    pub api: ApiConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            storage: StorageConfig::default(),
            encryption: EncryptionConfig::default(),
            server: ServerConfig::default(),
            performance: PerformanceConfig::default(),
            audit: crate::audit::AuditConfig::default(),
            optimizer: OptimizerConfig::default(),
            authentication: AuthenticationConfig::default(),
            compression: CompressionConfig::default(),
            materialized_views: MaterializedViewConfig::default(),
            vector: VectorConfig::default(),
            sync: SyncConfig::default(),
            session: SessionConfig::default(),
            locks: LockConfig::default(),
            dump: DumpConfig::default(),
            resource_quotas: ResourceQuotaConfig::default(),
            api: ApiConfig::default(),
        }
    }
}

impl Config {
    /// Create in-memory configuration
    pub fn in_memory() -> Self {
        Self {
            storage: StorageConfig {
                path: None,
                memory_only: true,
                wal_enabled: false, // No WAL needed for in-memory mode
                ..Default::default()
            },
            audit: crate::audit::AuditConfig::default(),
            ..Default::default()
        }
    }

    /// Load configuration from file
    pub fn from_file(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let config: Config = toml::from_str(&content)
            .map_err(|e| crate::Error::config(format!("Failed to parse config: {}", e)))?;
        Ok(config)
    }

    /// Save configuration to file
    pub fn save_to_file(&self, path: impl AsRef<std::path::Path>) -> crate::Result<()> {
        let content = toml::to_string_pretty(self)
            .map_err(|e| crate::Error::config(format!("Failed to serialize config: {}", e)))?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Validate all configuration sections
    pub fn validate(&self) -> crate::Result<()> {
        self.session.validate()?;
        self.locks.validate()?;
        self.dump.validate()?;
        self.resource_quotas.validate()?;
        Ok(())
    }
}

/// Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StorageConfig {
    /// Database path (None for in-memory)
    pub path: Option<PathBuf>,
    /// Memory-only mode
    pub memory_only: bool,
    /// Write-ahead log enabled
    pub wal_enabled: bool,
    /// WAL synchronization mode (sync, async, or group_commit)
    pub wal_sync_mode: WalSyncModeConfig,
    /// Maximum memory for cache (bytes)
    pub cache_size: usize,
    /// Compression enabled
    pub compression: CompressionType,
    /// Automatic time-travel versioning enabled (default: true)
    ///
    /// When enabled, all insert/update operations automatically create
    /// versioned snapshots for time-travel queries. This enables AS OF
    /// TIMESTAMP/TRANSACTION/SCN queries with zero configuration.
    ///
    /// Set to false to disable automatic versioning and reduce write overhead
    /// for workloads that don't require time-travel queries.
    pub time_travel_enabled: bool,
    /// Query timeout in milliseconds (None for unlimited)
    ///
    /// If set, queries that exceed this duration will be automatically
    /// terminated to prevent resource exhaustion. Applies to the entire
    /// query execution from start to finish.
    ///
    /// Default: None (unlimited)
    /// Recommended: 30000 (30 seconds) for production environments
    pub query_timeout_ms: Option<u64>,
    /// Statement timeout in milliseconds (None for unlimited)
    ///
    /// If set, individual statement operations (e.g., a single scan or join)
    /// that exceed this duration will be terminated. This provides finer-grained
    /// timeout control than query_timeout_ms.
    ///
    /// Default: None (unlimited)
    /// Note: Currently not implemented, reserved for future use
    pub statement_timeout_ms: Option<u64>,
    /// Transaction isolation level
    ///
    /// Controls the visibility of concurrent transaction changes.
    /// Default: ReadCommitted (standard PostgreSQL default)
    pub transaction_isolation: TransactionIsolation,
    /// Slow query log threshold in milliseconds (None to disable)
    ///
    /// Queries exceeding this threshold are logged at WARN level with their
    /// SQL text (truncated to 200 chars), duration, and row count.
    ///
    /// Default: Some(1000) (1 second)
    #[serde(default = "default_slow_query_threshold")]
    pub slow_query_threshold_ms: Option<u64>,
}

fn default_slow_query_threshold() -> Option<u64> {
    Some(1000)
}

fn default_idle_timeout_secs() -> u64 {
    300 // 5 minutes
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            path: Some(PathBuf::from("./heliosdb-data")),
            memory_only: false,
            wal_enabled: true,
            wal_sync_mode: WalSyncModeConfig::Sync, // Safest default for single-user workloads
            cache_size: 512 * 1024 * 1024, // 512 MB
            compression: CompressionType::Zstd,
            time_travel_enabled: true, // Enable by default for zero-config transparency
            query_timeout_ms: None, // Unlimited by default
            statement_timeout_ms: None, // Unlimited by default
            transaction_isolation: TransactionIsolation::ReadCommitted, // PostgreSQL default
            slow_query_threshold_ms: Some(1000), // 1 second default
        }
    }
}

/// WAL synchronization mode configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WalSyncModeConfig {
    /// Synchronous - fsync on every write (safest, slowest)
    Sync,
    /// Asynchronous - OS-managed flush (faster, less safe)
    Async,
    /// Group commit - batch multiple operations (balanced)
    GroupCommit,
}

/// Compression type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompressionType {
    /// No compression
    None,
    /// Zstandard compression (recommended)
    Zstd,
    /// LZ4 compression (faster, lower ratio)
    Lz4,
}

/// Transaction isolation level
///
/// Controls how transactions see concurrent changes from other transactions.
/// HeliosDB-Lite implements snapshot isolation by default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionIsolation {
    /// Read Uncommitted (not recommended)
    ///
    /// Transactions can see uncommitted changes from other transactions (dirty reads).
    /// Not fully supported - maps to ReadCommitted for safety.
    ReadUncommitted,
    /// Read Committed (PostgreSQL default)
    ///
    /// Transactions only see committed changes from other transactions.
    /// Each statement sees a fresh snapshot at statement start.
    ReadCommitted,
    /// Repeatable Read
    ///
    /// Transactions see a consistent snapshot from transaction start.
    /// No dirty reads, non-repeatable reads, or phantom reads.
    RepeatableRead,
    /// Serializable (strictest)
    ///
    /// Transactions execute as if they run serially.
    /// Prevents all anomalies but may cause serialization failures.
    Serializable,
}

/// Encryption configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EncryptionConfig {
    /// Encryption enabled
    pub enabled: bool,
    /// Encryption algorithm
    pub algorithm: EncryptionAlgorithm,
    /// Key source
    pub key_source: KeySource,
    /// Key rotation interval (days)
    pub rotation_interval_days: u32,
    /// Zero-Knowledge Encryption mode (v3.5)
    #[serde(default)]
    pub zke: ZkeEncryptionConfig,
}

impl Default for EncryptionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            algorithm: EncryptionAlgorithm::Aes256Gcm,
            key_source: KeySource::Environment("HELIOSDB_ENCRYPTION_KEY".to_string()),
            rotation_interval_days: 90,
            zke: ZkeEncryptionConfig::default(),
        }
    }
}

/// Zero-Knowledge Encryption configuration (v3.5)
///
/// ZKE ensures encryption keys never leave the client. The server only
/// ever sees encrypted data and cannot decrypt without client-provided keys.
///
/// # Security Properties
///
/// - **Client-Side Encryption**: All data encrypted before transmission
/// - **Per-Request Keys**: Keys provided with each request, never stored
/// - **Key Hash Validation**: Server validates key via SHA-256 hash
/// - **Nonce-Based Replay Protection**: Each request has unique nonce
///
/// # Example Configuration
///
/// ```toml
/// [encryption.zke]
/// enabled = true
/// mode = "per_request"
/// require_key_hash = true
/// replay_protection = true
/// nonce_window_secs = 300
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZkeEncryptionConfig {
    /// Enable Zero-Knowledge Encryption mode
    pub enabled: bool,
    /// ZKE mode: "full", "hybrid", or "per_request"
    pub mode: ZkeMode,
    /// Require key hash validation on every request
    pub require_key_hash: bool,
    /// Enable nonce-based replay protection
    pub replay_protection: bool,
    /// Nonce validity window in seconds (default: 300 = 5 minutes)
    pub nonce_window_secs: u64,
    /// Maximum cached nonces for replay protection (default: 10000)
    pub max_cached_nonces: usize,
}

impl Default for ZkeEncryptionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            mode: ZkeMode::PerRequest,
            require_key_hash: true,
            replay_protection: true,
            nonce_window_secs: 300,
            max_cached_nonces: 10000,
        }
    }
}

/// Zero-Knowledge Encryption mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ZkeMode {
    /// Full zero-knowledge: client encrypts all data
    /// - No server-side search capabilities
    /// - Maximum privacy
    Full,
    /// Hybrid: metadata visible, row data encrypted
    /// - Table/column names unencrypted
    /// - Basic filtering possible
    Hybrid,
    /// Per-request decryption with client-provided key
    /// - Full SQL capabilities
    /// - Key zeroed after each request
    PerRequest,
}

/// Encryption algorithm
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EncryptionAlgorithm {
    /// AES-256-GCM (recommended)
    Aes256Gcm,
}

/// Encryption key source
///
/// Specifies where the encryption key is retrieved from. For security,
/// keys should never be stored in configuration files directly.
///
/// # Security Recommendations
///
/// - **Production**: Use `Kms` with a cloud provider for key management
/// - **Development**: Use `Environment` with a secure secret manager
/// - **Testing**: Use `File` with proper file permissions (chmod 600)
///
/// # Examples
///
/// ```toml
/// # Environment variable (recommended for development)
/// [encryption]
/// key_source = { Environment = "HELIOSDB_KEY" }
///
/// # AWS KMS (recommended for production)
/// [encryption]
/// key_source = { Kms = { provider = "aws", key_id = "arn:aws:kms:..." } }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeySource {
    /// Read key from environment variable
    Environment(String),
    /// Read key from file (ensure proper file permissions)
    File(PathBuf),
    /// Use cloud Key Management Service
    Kms {
        /// Cloud provider: "aws", "azure", or "gcp"
        provider: String,
        /// Key identifier (ARN for AWS, key URI for others)
        key_id: String,
    },
}

/// Server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ServerConfig {
    /// Listen address
    pub listen_addr: String,
    /// PostgreSQL protocol port
    pub port: u16,
    /// Oracle TNS protocol port (optional, disabled if None)
    pub oracle_port: Option<u16>,
    /// Maximum connections
    pub max_connections: usize,
    /// Idle connection timeout in seconds (0 = no timeout, default 300s = 5 min)
    #[serde(default = "default_idle_timeout_secs")]
    pub idle_timeout_secs: u64,
    /// TLS enabled
    pub tls_enabled: bool,
    /// TLS certificate path
    pub tls_cert_path: Option<PathBuf>,
    /// TLS key path
    pub tls_key_path: Option<PathBuf>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            listen_addr: "127.0.0.1".to_string(),
            port: 5432,
            oracle_port: Some(1521), // Enable Oracle protocol by default
            max_connections: 100,
            idle_timeout_secs: default_idle_timeout_secs(),
            tls_enabled: false,
            tls_cert_path: None,
            tls_key_path: None,
        }
    }
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PerformanceConfig {
    /// Worker threads
    pub worker_threads: usize,
    /// Query timeout (seconds)
    pub query_timeout_secs: u64,
    /// Enable SIMD
    pub simd_enabled: bool,
    /// Parallel query execution
    pub parallel_query: bool,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            worker_threads: num_cpus::get(),
            query_timeout_secs: 300,
            simd_enabled: true,
            parallel_query: true,
        }
    }
}

// Add num_cpus to dependencies
// For now use a simple fallback
mod num_cpus {
    pub fn get() -> usize {
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4)
    }
}

/// Optimizer configuration (v2.1)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct OptimizerConfig {
    /// Enable query optimizer
    pub enabled: bool,
    /// Enable sequential scan
    pub enable_seqscan: bool,
    /// Enable index scan
    pub enable_indexscan: bool,
    /// Enable hash join
    pub enable_hashjoin: bool,
    /// Enable merge join
    pub enable_mergejoin: bool,
    /// Enable nested loop join
    pub enable_nestloop: bool,
    /// Cost model parameters
    pub seq_page_cost: f64,
    pub random_page_cost: f64,
    pub cpu_tuple_cost: f64,
    pub cpu_index_tuple_cost: f64,
}

impl Default for OptimizerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            enable_seqscan: true,
            enable_indexscan: true,
            enable_hashjoin: true,
            enable_mergejoin: true,
            enable_nestloop: true,
            seq_page_cost: 1.0,
            random_page_cost: 4.0,
            cpu_tuple_cost: 0.01,
            cpu_index_tuple_cost: 0.005,
        }
    }
}

/// Authentication configuration (v2.1)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AuthenticationConfig {
    /// Enable authentication
    pub enabled: bool,
    /// Authentication method
    pub method: AuthMethod,
    /// JWT secret key (for JWT auth)
    pub jwt_secret: Option<String>,
    /// JWT expiration time (seconds)
    pub jwt_expiration_secs: u64,
    /// Password hash algorithm
    pub password_hash_algorithm: PasswordHashAlgorithm,
    /// Users file path (for file-based auth)
    pub users_file: Option<PathBuf>,
}

impl Default for AuthenticationConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            method: AuthMethod::Trust,
            jwt_secret: None,
            jwt_expiration_secs: 86400, // 24 hours
            password_hash_algorithm: PasswordHashAlgorithm::Argon2,
            users_file: None,
        }
    }
}

/// Authentication method
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthMethod {
    /// No authentication (dev mode)
    Trust,
    /// Password authentication
    Password,
    /// JWT authentication
    Jwt,
    /// LDAP authentication
    Ldap,
}

/// Password hash algorithm
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PasswordHashAlgorithm {
    /// Argon2 (recommended)
    Argon2,
    /// BCrypt
    Bcrypt,
    /// PBKDF2
    Pbkdf2,
}

/// Compression configuration (v2.1)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CompressionConfig {
    /// Default compression type
    pub default_type: CompressionType,
    /// Compression level (1-22 for zstd)
    pub level: i32,
    /// Enable ALP compression for numeric columns
    pub enable_alp: bool,
    /// Enable FSST compression for string columns
    pub enable_fsst: bool,
    /// Minimum data size to trigger compression (bytes)
    pub min_size_bytes: usize,
}

impl Default for CompressionConfig {
    fn default() -> Self {
        Self {
            default_type: CompressionType::Zstd,
            level: 3,
            enable_alp: true,
            enable_fsst: true,
            min_size_bytes: 1024, // 1KB
        }
    }
}

/// Materialized view configuration (v2.3 - Incremental MVs)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MaterializedViewConfig {
    /// Enable auto-refresh by default
    pub auto_refresh_default: bool,
    /// Default max CPU percentage for refresh
    pub default_max_cpu_percent: u8,
    /// Refresh check interval (seconds)
    pub refresh_check_interval_secs: u64,
    /// Maximum concurrent refreshes
    pub max_concurrent_refreshes: usize,
    /// Enable incremental refresh feature (v2.3.0)
    pub enable_incremental: bool,
    /// Enable delta tracking for base tables (v2.3.0)
    pub enable_delta_tracking: bool,
    /// Enable CPU-aware scheduling (v2.3.0)
    pub enable_scheduler: bool,
    /// Delta retention period in hours (purge old deltas)
    pub delta_retention_hours: u64,
}

impl Default for MaterializedViewConfig {
    fn default() -> Self {
        Self {
            auto_refresh_default: false,
            default_max_cpu_percent: 15,
            refresh_check_interval_secs: 60,
            max_concurrent_refreshes: 2,
            enable_incremental: false,  // Disabled by default, opt-in
            enable_delta_tracking: false,  // Disabled by default
            enable_scheduler: false,  // Disabled by default
            delta_retention_hours: 168,  // 7 days
        }
    }
}

/// Vector index configuration (v2.1)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct VectorConfig {
    /// Default vector index type
    pub default_index_type: VectorIndexType,
    /// HNSW ef_construction parameter
    pub hnsw_ef_construction: usize,
    /// HNSW M parameter (connections per layer)
    pub hnsw_m: usize,
    /// Enable product quantization
    pub enable_pq: bool,
    /// PQ subvector count
    pub pq_subvectors: usize,
    /// PQ bits per subvector
    pub pq_bits: usize,
}

impl Default for VectorConfig {
    fn default() -> Self {
        Self {
            default_index_type: VectorIndexType::Hnsw,
            hnsw_ef_construction: 200,
            hnsw_m: 16,
            enable_pq: true,
            pq_subvectors: 8,
            pq_bits: 8,
        }
    }
}

/// Vector index type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VectorIndexType {
    /// Flat (brute force, exact)
    Flat,
    /// HNSW (approximate, fast)
    Hnsw,
    /// IVF (inverted file)
    Ivf,
}

/// Sync configuration (v2.3 - Experimental)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SyncConfig {
    /// Enable sync protocol
    pub enabled: bool,
    /// Node ID for this instance (generated if None)
    pub node_id: Option<String>,
    /// Sync server URL (for clients)
    pub server_url: Option<String>,
    /// Client ID (for authentication)
    pub client_id: Option<String>,
    /// Sync interval in seconds
    pub sync_interval_secs: u64,
    /// Enable change log capture
    pub change_log_enabled: bool,
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            node_id: None,
            server_url: None,
            client_id: None,
            sync_interval_secs: 30,
            change_log_enabled: true,
        }
    }
}

/// Session configuration (v3.1.0)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionConfig {
    /// Session timeout in seconds (default: 3600 = 1 hour)
    pub timeout_secs: u64,
    /// Maximum sessions per user (default: 10)
    pub max_sessions_per_user: u32,
    /// Session cleanup interval in seconds (default: 300 = 5 minutes)
    pub cleanup_interval_secs: u64,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            timeout_secs: 3600,
            max_sessions_per_user: 10,
            cleanup_interval_secs: 300,
        }
    }
}

impl SessionConfig {
    /// Validate configuration values
    pub fn validate(&self) -> crate::Result<()> {
        if self.timeout_secs < 1 {
            return Err(crate::Error::config(
                "session.timeout_secs must be at least 1 second",
            ));
        }
        if self.max_sessions_per_user < 1 {
            return Err(crate::Error::config(
                "session.max_sessions_per_user must be at least 1",
            ));
        }
        if self.cleanup_interval_secs < 1 {
            return Err(crate::Error::config(
                "session.cleanup_interval_secs must be at least 1 second",
            ));
        }
        Ok(())
    }
}

/// Lock configuration (v3.1.0)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LockConfig {
    /// Lock acquisition timeout in milliseconds (default: 30000 = 30 seconds)
    pub timeout_ms: u32,
    /// Deadlock detection interval in milliseconds (default: 100)
    pub deadlock_check_interval_ms: u32,
    /// Maximum number of concurrent lock holders (default: 10000)
    pub max_lock_holders: u32,
}

impl Default for LockConfig {
    fn default() -> Self {
        Self {
            timeout_ms: 30000,
            deadlock_check_interval_ms: 100,
            max_lock_holders: 10000,
        }
    }
}

impl LockConfig {
    /// Validate configuration values
    pub fn validate(&self) -> crate::Result<()> {
        if self.timeout_ms < 100 {
            return Err(crate::Error::config(
                "locks.timeout_ms must be at least 100 milliseconds",
            ));
        }
        if self.deadlock_check_interval_ms < 10 {
            return Err(crate::Error::config(
                "locks.deadlock_check_interval_ms must be at least 10 milliseconds",
            ));
        }
        if self.max_lock_holders < 1 {
            return Err(crate::Error::config(
                "locks.max_lock_holders must be at least 1",
            ));
        }
        Ok(())
    }
}

/// Dump configuration (v3.1.0)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DumpConfig {
    /// Enable automatic dumps on a schedule (default: false)
    pub auto_dump_enabled: bool,
    /// Cron-style schedule for automatic dumps (e.g., "0 */6 * * *")
    pub schedule: String,
    /// Compression algorithm: "zstd", "gzip", "none" (default: "zstd")
    pub compression: String,
    /// Maximum size of a single dump file in MB before rolling (default: 10000)
    pub max_dump_size_mb: u64,
    /// Number of old dumps to keep (0 = keep all, default: 10)
    pub keep_dumps: usize,
    /// Directory to store dumps (default: ".dumps")
    pub dump_dir: String,
}

impl Default for DumpConfig {
    fn default() -> Self {
        Self {
            auto_dump_enabled: false,
            schedule: String::new(),
            compression: "zstd".to_string(),
            max_dump_size_mb: 10000,
            keep_dumps: 10,
            dump_dir: ".dumps".to_string(),
        }
    }
}

impl DumpConfig {
    /// Validate configuration values
    pub fn validate(&self) -> crate::Result<()> {
        // Validate compression type
        match self.compression.as_str() {
            "zstd" | "gzip" | "none" => {}
            _ => {
                return Err(crate::Error::config(format!(
                    "dump.compression must be 'zstd', 'gzip', or 'none', got '{}'",
                    self.compression
                )));
            }
        }

        // Validate max dump size
        if self.max_dump_size_mb < 1 {
            return Err(crate::Error::config(
                "dump.max_dump_size_mb must be at least 1 MB",
            ));
        }

        // Validate cron schedule if auto_dump_enabled
        if self.auto_dump_enabled && !self.schedule.is_empty() {
            Self::validate_cron_schedule(&self.schedule)?;
        }

        Ok(())
    }

    /// Validate cron schedule format (basic validation)
    fn validate_cron_schedule(schedule: &str) -> crate::Result<()> {
        let parts: Vec<&str> = schedule.split_whitespace().collect();
        if parts.len() != 5 {
            return Err(crate::Error::config(format!(
                "Invalid cron schedule format '{}'. Expected 5 fields: minute hour day month weekday",
                schedule
            )));
        }
        Ok(())
    }
}

/// Resource quota configuration (v3.1.0)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ResourceQuotaConfig {
    /// Memory limit per user in MB (default: 1024)
    pub memory_limit_per_user_mb: u64,
    /// Maximum concurrent queries per user (default: 100)
    pub max_concurrent_queries: u32,
    /// Query execution timeout in seconds (default: 300 = 5 minutes)
    pub query_timeout_secs: u64,
}

impl Default for ResourceQuotaConfig {
    fn default() -> Self {
        Self {
            memory_limit_per_user_mb: 1024,
            max_concurrent_queries: 100,
            query_timeout_secs: 300,
        }
    }
}

impl ResourceQuotaConfig {
    /// Validate configuration values
    pub fn validate(&self) -> crate::Result<()> {
        if self.memory_limit_per_user_mb < 1 {
            return Err(crate::Error::config(
                "resource_quotas.memory_limit_per_user_mb must be at least 1 MB",
            ));
        }
        if self.max_concurrent_queries < 1 {
            return Err(crate::Error::config(
                "resource_quotas.max_concurrent_queries must be at least 1",
            ));
        }
        if self.query_timeout_secs < 1 {
            return Err(crate::Error::config(
                "resource_quotas.query_timeout_secs must be at least 1 second",
            ));
        }
        Ok(())
    }
}

/// BaaS REST API configuration (v3.2.0)
///
/// Controls the PostgREST-compatible REST API layer that exposes tables
/// as RESTful endpoints at `/rest/v1/`.
///
/// # Example (TOML)
///
/// ```toml
/// [api]
/// jwt_secret = "super-secret-key"
/// anon_key = "eyJhbGciOi..."
/// service_role_key = "eyJhbGciOi..."
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ApiConfig {
    /// JWT secret used to sign and verify authentication tokens.
    ///
    /// If not set, a random 64-byte hex string is generated at startup.
    pub jwt_secret: String,
    /// Anonymous API key that grants unauthenticated read access.
    pub anon_key: Option<String>,
    /// Service-role API key that grants full admin access (bypasses RLS).
    pub service_role_key: Option<String>,
    /// OAuth2 provider configurations (Google, GitHub, etc.).
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [[api.oauth_providers]]
    /// name = "google"
    /// client_id = "123456.apps.googleusercontent.com"
    /// client_secret = "GOCSPX-..."
    /// redirect_uri = "http://localhost:8080/auth/v1/callback"
    ///
    /// [[api.oauth_providers]]
    /// name = "github"
    /// client_id = "Iv1.abc123"
    /// client_secret = "deadbeef..."
    /// redirect_uri = "http://localhost:8080/auth/v1/callback"
    /// ```
    #[serde(default)]
    pub oauth_providers: Vec<OAuthProviderConfig>,
}

/// Configuration for a single OAuth2 provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthProviderConfig {
    /// Provider name: `"google"` or `"github"`.
    pub name: String,
    /// OAuth2 Client ID issued by the provider.
    pub client_id: String,
    /// OAuth2 Client Secret issued by the provider.
    pub client_secret: String,
    /// The absolute URL the provider should redirect back to after authorization.
    pub redirect_uri: String,
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            jwt_secret: generate_random_secret(),
            anon_key: None,
            service_role_key: None,
            oauth_providers: Vec::new(),
        }
    }
}

/// Generate a random 64-character hex string for use as a JWT secret.
fn generate_random_secret() -> String {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hasher};

    // Use two independent random hashers to get 128 bits of randomness
    let s = RandomState::new();
    let h1 = s.build_hasher().finish();
    let h2 = RandomState::new().build_hasher().finish();
    format!("{h1:016x}{h2:016x}{h1:016x}{h2:016x}")
}

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

    #[test]
    fn test_session_config_default() {
        let config = SessionConfig::default();
        assert_eq!(config.timeout_secs, 3600);
        assert_eq!(config.max_sessions_per_user, 10);
        assert_eq!(config.cleanup_interval_secs, 300);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_session_config_validation() {
        let mut config = SessionConfig::default();

        // Valid config
        assert!(config.validate().is_ok());

        // Invalid timeout
        config.timeout_secs = 0;
        assert!(config.validate().is_err());
        config.timeout_secs = 3600;

        // Invalid max sessions
        config.max_sessions_per_user = 0;
        assert!(config.validate().is_err());
        config.max_sessions_per_user = 10;

        // Invalid cleanup interval
        config.cleanup_interval_secs = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_lock_config_default() {
        let config = LockConfig::default();
        assert_eq!(config.timeout_ms, 30000);
        assert_eq!(config.deadlock_check_interval_ms, 100);
        assert_eq!(config.max_lock_holders, 10000);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_lock_config_validation() {
        let mut config = LockConfig::default();

        // Valid config
        assert!(config.validate().is_ok());

        // Invalid timeout (too low)
        config.timeout_ms = 50;
        assert!(config.validate().is_err());
        config.timeout_ms = 30000;

        // Invalid deadlock check interval
        config.deadlock_check_interval_ms = 5;
        assert!(config.validate().is_err());
        config.deadlock_check_interval_ms = 100;

        // Invalid max lock holders
        config.max_lock_holders = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_dump_config_default() {
        let config = DumpConfig::default();
        assert!(!config.auto_dump_enabled);
        assert_eq!(config.schedule, "");
        assert_eq!(config.compression, "zstd");
        assert_eq!(config.max_dump_size_mb, 10000);
        assert_eq!(config.keep_dumps, 10);
        assert_eq!(config.dump_dir, ".dumps");
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_dump_config_validation() {
        let mut config = DumpConfig::default();

        // Valid config
        assert!(config.validate().is_ok());

        // Invalid compression type
        config.compression = "invalid".to_string();
        assert!(config.validate().is_err());
        config.compression = "zstd".to_string();

        // Valid compression types
        config.compression = "gzip".to_string();
        assert!(config.validate().is_ok());
        config.compression = "none".to_string();
        assert!(config.validate().is_ok());
        config.compression = "zstd".to_string();

        // Invalid max dump size
        config.max_dump_size_mb = 0;
        assert!(config.validate().is_err());
        config.max_dump_size_mb = 10000;

        // Valid cron schedule
        config.auto_dump_enabled = true;
        config.schedule = "0 */6 * * *".to_string();
        assert!(config.validate().is_ok());

        // Invalid cron schedule
        config.schedule = "invalid".to_string();
        assert!(config.validate().is_err());

        // Empty schedule with auto_dump_enabled is OK
        config.schedule = "".to_string();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_resource_quota_config_default() {
        let config = ResourceQuotaConfig::default();
        assert_eq!(config.memory_limit_per_user_mb, 1024);
        assert_eq!(config.max_concurrent_queries, 100);
        assert_eq!(config.query_timeout_secs, 300);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_resource_quota_config_validation() {
        let mut config = ResourceQuotaConfig::default();

        // Valid config
        assert!(config.validate().is_ok());

        // Invalid memory limit
        config.memory_limit_per_user_mb = 0;
        assert!(config.validate().is_err());
        config.memory_limit_per_user_mb = 1024;

        // Invalid max concurrent queries
        config.max_concurrent_queries = 0;
        assert!(config.validate().is_err());
        config.max_concurrent_queries = 100;

        // Invalid query timeout
        config.query_timeout_secs = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_with_new_sections() {
        let config = Config::default();

        // Verify new sections are initialized
        assert_eq!(config.session.timeout_secs, 3600);
        assert_eq!(config.locks.timeout_ms, 30000);
        assert_eq!(config.dump.compression, "zstd");
        assert_eq!(config.resource_quotas.memory_limit_per_user_mb, 1024);

        // Validate entire config
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::default();

        // Serialize to TOML
        let toml_str = toml::to_string(&config).expect("Failed to serialize config");

        // Should contain new sections
        assert!(toml_str.contains("[session]"));
        assert!(toml_str.contains("[locks]"));
        assert!(toml_str.contains("[dump]"));
        assert!(toml_str.contains("[resource_quotas]"));
    }

    #[test]
    fn test_config_deserialization() {
        let toml_str = r#"
            [storage]
            memory_only = true
            wal_enabled = false
            wal_sync_mode = "sync"
            cache_size = 536870912
            compression = "Zstd"
            time_travel_enabled = true
            transaction_isolation = "READ_COMMITTED"

            [session]
            timeout_secs = 7200
            max_sessions_per_user = 20
            cleanup_interval_secs = 600

            [locks]
            timeout_ms = 60000
            deadlock_check_interval_ms = 200
            max_lock_holders = 20000

            [dump]
            auto_dump_enabled = true
            schedule = "0 2 * * *"
            compression = "gzip"
            max_dump_size_mb = 5000
            keep_dumps = 5
            dump_dir = "/var/dumps"

            [resource_quotas]
            memory_limit_per_user_mb = 2048
            max_concurrent_queries = 200
            query_timeout_secs = 600
        "#;

        let config: Config = toml::from_str(toml_str).expect("Failed to deserialize config");

        // Verify session config
        assert_eq!(config.session.timeout_secs, 7200);
        assert_eq!(config.session.max_sessions_per_user, 20);
        assert_eq!(config.session.cleanup_interval_secs, 600);

        // Verify lock config
        assert_eq!(config.locks.timeout_ms, 60000);
        assert_eq!(config.locks.deadlock_check_interval_ms, 200);
        assert_eq!(config.locks.max_lock_holders, 20000);

        // Verify dump config
        assert!(config.dump.auto_dump_enabled);
        assert_eq!(config.dump.schedule, "0 2 * * *");
        assert_eq!(config.dump.compression, "gzip");
        assert_eq!(config.dump.max_dump_size_mb, 5000);
        assert_eq!(config.dump.keep_dumps, 5);
        assert_eq!(config.dump.dump_dir, "/var/dumps");

        // Verify resource quota config
        assert_eq!(config.resource_quotas.memory_limit_per_user_mb, 2048);
        assert_eq!(config.resource_quotas.max_concurrent_queries, 200);
        assert_eq!(config.resource_quotas.query_timeout_secs, 600);

        // Validate entire config
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_with_missing_sections() {
        // Config with only storage section (old format)
        let toml_str = r#"
            [storage]
            memory_only = true
            wal_enabled = false
            wal_sync_mode = "sync"
            cache_size = 536870912
            compression = "Zstd"
            time_travel_enabled = true
            transaction_isolation = "READ_COMMITTED"
        "#;

        let config: Config = toml::from_str(toml_str).expect("Failed to deserialize config");

        // New sections should have default values
        assert_eq!(config.session.timeout_secs, 3600);
        assert_eq!(config.locks.timeout_ms, 30000);
        assert_eq!(config.dump.compression, "zstd");
        assert_eq!(config.resource_quotas.memory_limit_per_user_mb, 1024);

        // Should still validate
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_cron_schedule_validation() {
        // Valid cron schedules
        assert!(DumpConfig::validate_cron_schedule("0 */6 * * *").is_ok());
        assert!(DumpConfig::validate_cron_schedule("0 2 * * *").is_ok());
        assert!(DumpConfig::validate_cron_schedule("*/15 * * * *").is_ok());
        assert!(DumpConfig::validate_cron_schedule("0 0 1 * *").is_ok());
        assert!(DumpConfig::validate_cron_schedule("30 3 * * 0").is_ok());

        // Invalid cron schedules
        assert!(DumpConfig::validate_cron_schedule("invalid").is_err());
        assert!(DumpConfig::validate_cron_schedule("0 * * *").is_err());  // Only 4 fields
        assert!(DumpConfig::validate_cron_schedule("0 * * * * *").is_err());  // 6 fields
        assert!(DumpConfig::validate_cron_schedule("").is_err());  // Empty
    }
}