dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
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
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! 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.

//! # Database Configuration
//!
//! This module provides database configuration types and settings for Ri.
//! It supports multiple database backends including MySQL, PostgreSQL, SQLite, and in-memory databases.
//!
//! ## Key Components
//!
//! - **RiDatabaseConfig**: Enum for different database configurations
//! - **DatabaseType**: Enum for supported database engines
//! - **PoolConfig**: Connection pool configuration settings
//!
//! ## Design Principles
//!
//! 1. **Type Safety**: Each database type has its own configuration variant
//! 2. **Flexible Pooling**: Configurable connection pool settings for performance
//! 3. **Backend-Agnostic**: Unified interface across different database engines
//! 4. **Default Values**: Sensible defaults for all configuration options
//!
//! ## Usage Example
//!
//! ```rust,ignore
//! use ri::database::{RiDatabaseConfig, DatabaseType, PoolConfig};
//!
//! let config = RiDatabaseConfig::new_mysql(
//!     "localhost",
//!     3306,
//!     "root",
//!     "password",
//!     "test_db",
//! );
//!
//! let pool_config = PoolConfig::new(10, 300, 600);
//! ```

use serde::{Deserialize, Serialize};
use std::env;

/// Enumeration of supported database engine types.
///
/// This enum represents the different database backends that Ri can connect to.
/// Each database type has specific connection requirements and may use different
/// underlying drivers or client libraries.
///
/// ## Currently Implemented
///
/// | Database Type | Feature Flag | Status |
/// |---------------|--------------|--------|
/// | PostgreSQL | `postgres` | ✅ Available |
/// | MySQL | `mysql` | ✅ Available |
/// | SQLite | `sqlite` | ✅ Available |
/// | MongoDB | `mongodb` | 🔜 Planned |
/// | Redis | `redis` | 🔜 Planned |
///
/// ## Roadmap
///
/// MongoDB and Redis support are planned for future releases. The enum variants
/// are reserved to maintain API stability when these features are added.
///
/// ## Usage
///
/// ```rust,ignore
/// use ri::database::DatabaseType;
///
/// fn get_preferred_db() -> DatabaseType {
///     DatabaseType::Postgres
/// }
/// ```
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DatabaseType {
    /// PostgreSQL database engine.
    ///
    /// PostgreSQL is a powerful, open source object-relational database system.
    /// It is known for its reliability, feature richness, and performance.
    /// Default port is 5432.
    ///
    /// ## Features
    ///
    /// - Full ACID compliance
    /// - Complex queries and joins
    /// - Foreign key support
    /// - Triggers and views
    /// - Stored procedures
    Postgres,
    /// MySQL database engine.
    ///
    /// MySQL is the world's most popular open source database.
    /// It is widely used for web applications and is known for its speed and reliability.
    /// Default port is 3306.
    ///
    /// ## Features
    ///
    /// - ACID compliance (with InnoDB)
    /// - Cross-platform support
    /// - Stored procedures and triggers
    /// - Full-text indexing
    MySQL,
    /// SQLite database engine.
    ///
    /// SQLite is a lightweight, file-based database engine.
    /// It requires no server and is embedded directly into the application.
    /// Suitable for development, testing, and desktop applications.
    ///
    /// ## Features
    ///
    /// - Serverless architecture
    /// - Zero-configuration
    /// - Single file storage
    /// - Full SQL support
    SQLite,
    /// MongoDB database engine.
    ///
    /// MongoDB is a document-oriented NoSQL database.
    /// It uses JSON-like documents with optional schemas.
    /// Default port is 27017.
    ///
    /// ## Features
    ///
    /// - Flexible document schema
    /// - Horizontal scaling
    /// - Rich query language
    /// - Automatic sharding
    MongoDB,
    /// Redis database engine.
    ///
    /// Redis is an in-memory data structure store.
    /// It can be used as a database, cache, and message broker.
    /// Default port is 6379.
    ///
    /// ## Features
    ///
    /// - In-memory storage
    /// - Data structures (strings, hashes, lists, sets)
    /// - Pub/Sub messaging
    /// - Persistence options
    Redis,
}

impl Default for DatabaseType {
    fn default() -> Self {
        DatabaseType::Postgres
    }
}

impl std::fmt::Display for DatabaseType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DatabaseType::Postgres => write!(f, "postgresql"),
            DatabaseType::MySQL => write!(f, "mysql"),
            DatabaseType::SQLite => write!(f, "sqlite"),
            DatabaseType::MongoDB => write!(f, "mongodb"),
            DatabaseType::Redis => write!(f, "redis"),
        }
    }
}

/// Configuration for database connections in Ri.
///
/// This struct encapsulates all configuration options needed to establish and manage
/// database connections. It supports multiple database backends through the `DatabaseType`
/// enum and provides a fluent builder API for configuration.
///
/// ## Connection Pooling
///
/// Ri uses connection pooling to efficiently manage database connections.
/// The pool maintains a set of connections that are reused across requests,
/// reducing the overhead of establishing new connections.
///
/// ## Configuration Methods
///
/// The struct provides several factory methods for creating configurations:
/// - [`postgres()`][RiDatabaseConfig::postgres] - PostgreSQL with default settings
/// - [`mysql()`][RiDatabaseConfig::mysql] - MySQL with default settings
/// - [`sqlite(path)`][RiDatabaseConfig::sqlite] - SQLite at specified path
///
/// ## Builder Pattern
///
/// Configuration can be customized using the builder pattern:
///
/// ```rust,ignore
/// use ri::database::{RiDatabaseConfig, SslMode};
///
/// let config = RiDatabaseConfig::postgres()
///     .host("db.example.com")
///     .port(5432)
///     .database("myapp")
///     .user("admin")
///     .password("secret")
///     .max_connections(20)
///     .ssl_mode(SslMode::Require)
///     .build();
/// ```
///
/// ## Environment Variables
///
/// Default values can be overridden using environment variables:
/// - `Ri_DB_HOST` - Database server hostname
/// - `Ri_DB_PORT` - Database server port
/// - `Ri_DB_NAME` - Database name
/// - `Ri_DB_USER` - Database username
/// - `Ri_DB_PASSWORD` - Database password
///
/// ## Thread Safety
///
/// This struct is clonable and can be shared across threads.
/// However, modifications should be done before the configuration is passed
/// to the database manager.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiDatabaseConfig {
    /// The type of database backend to connect to.
    ///
    /// This determines which driver and connection logic will be used.
    /// Common values are `DatabaseType::Postgres`, `DatabaseType::MySQL`,
    /// and `DatabaseType::SQLite`.
    pub database_type: DatabaseType,

    /// Hostname or IP address of the database server.
    ///
    /// For local development, this is typically `"localhost"` or `"127.0.0.1"`.
    /// For production, this should be the database server's hostname.
    ///
    /// ## Examples
    ///
    /// - `localhost` - Local database server
    /// - `db.example.com` - Remote database server
    /// - `192.168.1.100` - IP address of database server
    pub host: String,

    /// Port number for database connections.
    ///
    /// Each database type has a default port:
    /// - PostgreSQL: 5432
    /// - MySQL: 3306
    /// - MongoDB: 27017
    /// - Redis: 6379
    ///
    /// SQLite ignores this field as it uses file-based connections.
    pub port: u16,

    /// Name of the database to connect to.
    ///
    /// For PostgreSQL and MySQL, this is the name of a specific database
    /// within the database server.
    ///
    /// For SQLite, this is the file path (`:memory:` for in-memory database).
    pub database: String,

    /// Username for database authentication.
    ///
    /// This user must have sufficient privileges to perform the required
    /// database operations. For security, consider using environment variables
    /// or secrets management to provide this value.
    pub username: String,

    /// Password for database authentication.
    ///
    /// This password is used together with the username to authenticate
    /// with the database server. For security, consider using environment
    /// variables or secrets management to provide this value.
    pub password: String,

    /// Maximum number of concurrent database connections.
    ///
    /// This setting controls the upper bound of the connection pool.
    /// Higher values allow more concurrent database operations but increase
    /// resource usage on both the application and database server.
    ///
    /// ## Recommendations
    ///
    /// - Development: 5-10 connections
    /// - Production: 10-50 connections (depends on workload)
    /// - Consider database server's max_connections setting
    pub max_connections: u32,

    /// Minimum number of idle connections to maintain.
    ///
    /// The connection pool will maintain at least this many idle connections
    /// to reduce the latency of new database operations. These connections
    /// are still subject to the idle timeout.
    ///
    /// ## Default Value
    ///
    /// Typically 1-2 connections, depending on expected concurrency.
    pub min_idle_connections: u32,

    /// Timeout for establishing new connections in seconds.
    ///
    /// If a connection cannot be established within this time, the operation
    /// will fail with a timeout error. This prevents the application from
    /// hanging indefinitely when the database is unreachable.
    ///
    /// ## Common Values
    ///
    /// - 30 seconds for most scenarios
    /// - 5-10 seconds for latency-sensitive applications
    /// - 60+ seconds for distant database servers
    pub connection_timeout_secs: u64,

    /// Maximum time a connection can be idle before being closed.
    ///
    /// Idle connections that have not been used for this duration will be
    /// closed and removed from the pool. This helps free resources on both
    /// the application and database server.
    ///
    /// ## Recommendations
    ///
    /// - 600 seconds (10 minutes) for web applications
    /// - 300 seconds (5 minutes) for batch processing
    /// - Consider database server's connection timeout settings
    pub idle_timeout_secs: u64,

    /// Maximum lifetime of a connection in seconds.
    ///
    /// Connections older than this will be closed and replaced with new ones.
    /// This prevents connections from becoming stale due to:
    /// - Network interruptions
    /// - Database server restarts
    /// - Connection timeout on the database side
    ///
    /// ## Recommendations
    ///
    /// - 1800-3600 seconds (30-60 minutes) for most applications
    /// - Shorter values for long-running applications
    /// - Disable (use None) for very short-lived applications
    pub max_lifetime_secs: u64,

    /// SSL/TLS mode for encrypted connections.
    ///
    /// This setting controls whether and how SSL/TLS encryption is used
    /// for database connections. It is ignored by SQLite.
    ///
    /// ## Security
    ///
    /// Always use `SslMode::Require` in production environments to ensure
    /// all database traffic is encrypted.
    pub ssl_mode: SslMode,

    /// Maximum number of prepared statements to cache.
    ///
    /// Prepared statements are cached to reduce the overhead of repeated
    /// query compilation. Higher values improve performance for complex
    /// queries but increase memory usage.
    ///
    /// ## Recommendations
    ///
    /// - 100-500 for typical applications
    /// - 1000+ for applications with many repeated complex queries
    /// - 0 to disable statement caching
    pub statement_cache_size: u32,
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiDatabaseConfig {
    #[new]
    fn py_new(
        database_type: DatabaseType,
        host: String,
        port: u16,
        database: String,
        username: String,
        password: String,
        max_connections: u32,
        min_idle_connections: u32,
        connection_timeout_secs: u64,
        idle_timeout_secs: u64,
        max_lifetime_secs: u64,
        ssl_mode: SslMode,
        statement_cache_size: u32,
    ) -> Self {
        Self {
            database_type,
            host,
            port,
            database,
            username,
            password,
            max_connections,
            min_idle_connections,
            connection_timeout_secs,
            idle_timeout_secs,
            max_lifetime_secs,
            ssl_mode,
            statement_cache_size,
        }
    }

    #[staticmethod]
    fn create_postgres() -> Self {
        Self::postgres()
    }

    #[staticmethod]
    fn create_mysql() -> Self {
        Self::mysql()
    }

    #[staticmethod]
    fn create_sqlite() -> Self {
        Self::sqlite(":memory:")
    }

    fn get_database_type(&self) -> DatabaseType {
        self.database_type
    }

    fn set_database_type(&self, _database_type: DatabaseType) {
        // Can't modify in pyo3, use create functions instead
    }

    fn get_host(&self) -> String {
        self.host.clone()
    }

    fn set_host(&mut self, host: String) {
        self.host = host;
    }

    fn get_port(&self) -> u16 {
        self.port
    }

    fn set_port(&mut self, port: u16) {
        self.port = port;
    }

    fn get_database(&self) -> String {
        self.database.clone()
    }

    fn set_database(&mut self, database: String) {
        self.database = database;
    }

    fn get_username(&self) -> String {
        self.username.clone()
    }

    fn set_username(&mut self, username: String) {
        self.username = username;
    }

    fn get_password(&self) -> String {
        self.password.clone()
    }

    fn set_password(&mut self, password: String) {
        self.password = password;
    }

    fn get_max_connections(&self) -> u32 {
        self.max_connections
    }

    fn set_max_connections(&mut self, max_connections: u32) {
        self.max_connections = max_connections;
    }

    fn get_min_idle_connections(&self) -> u32 {
        self.min_idle_connections
    }

    fn set_min_idle_connections(&mut self, min_idle_connections: u32) {
        self.min_idle_connections = min_idle_connections;
    }
}

/// SSL/TLS connection mode for database connections.
///
/// This enum controls whether and how SSL/TLS encryption is used when
/// connecting to the database. SSL/TLS provides:
/// - **Confidentiality**: Encryption prevents eavesdropping on database traffic
/// - **Integrity**: Protection against data tampering during transmission
/// - **Authentication**: Verification of the database server's identity
///
/// ## Security Recommendations
///
/// | Environment | Recommended Mode | Reason |
/// |-------------|------------------|--------|
/// | Production | `Require` | Maximum security, prevents MITM attacks |
/// | Development | `Prefer` | Encryption when available |
/// | Testing | `Prefer` or `Disable` | Convenience during development |
///
/// ## Database Support
///
/// - **PostgreSQL**: Fully supports SSL with all modes
/// - **MySQL**: Fully supports SSL with all modes
/// - **MongoDB**: Supports SSL with all modes
/// - **SQLite**: Does not support SSL (ignored)
/// - **Redis**: Uses separate TLS configuration
///
/// ## Certificate Verification
///
/// When using `Require`, the client will verify the server's certificate.
/// This requires the server to have a valid certificate signed by a trusted
/// certificate authority. Self-signed certificates will fail verification.
///
/// For development with self-signed certificates, you may need to:
/// 1. Add the certificate to your system's trust store
/// 2. Configure the database client to trust the specific certificate
/// 3. Use `Prefer` mode (less secure, not recommended for production)
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SslMode {
    /// SSL/TLS is disabled. Connections are unencrypted.
    ///
    /// ## Use Cases
    ///
    /// - Local development with local database
    /// - Testing in isolated environments
    /// - Situations where encryption overhead is unacceptable
    ///
    /// ## Security Warning
    ///
    /// This mode provides no protection against eavesdropping or tampering.
    /// Never use in production or when transmitting sensitive data.
    Disable,

    /// SSL/TLS is preferred but not required.
    ///
    /// The client will attempt to establish an SSL connection if the server
    /// supports it. If SSL is not available, the connection will fall back
    /// to an unencrypted connection.
    ///
    /// ## Behavior
    ///
    /// 1. Client requests SSL connection
    /// 2. If server supports SSL, use encrypted connection
    /// 3. If server rejects SSL, use unencrypted connection
    ///
    /// ## Security Warning
    ///
    /// This mode allows fallback to unencrypted connections, which could
    /// be exploited in man-in-the-middle attacks. Consider using `Require`
    /// for better security.
    Prefer,

    /// SSL/TLS is required.
    ///
    /// The client will only establish connections that are encrypted with
    /// SSL/TLS. The connection will fail if SSL is not available or if
    /// certificate verification fails.
    ///
    /// ## Server Certificate Verification
    ///
    /// When `Require` mode is used, the client verifies:
    /// - The certificate is not expired
    /// - The certificate is signed by a trusted CA
    /// - The certificate hostname matches the server hostname
    ///
    /// ## Use Cases
    ///
    /// - Production environments
    /// - When transmitting sensitive data
    /// - Compliance with security regulations
    ///
    /// ## Common Errors
    ///
    /// - `certificate verify failed`: Certificate not trusted
    /// - `certificate expired`: Certificate has expired
    /// - `hostname mismatch`: Certificate not issued for this server
    Require,
}

impl Default for SslMode {
    fn default() -> Self {
        SslMode::Prefer
    }
}

impl RiDatabaseConfig {
    /// Creates a configuration for PostgreSQL with default settings.
    ///
    /// This factory method initializes a configuration with sensible defaults
    /// for PostgreSQL connections. Default values can be overridden using
    /// environment variables or the builder methods.
    ///
    /// ## Defaults
    ///
    /// - Host: `localhost` (or `Ri_DB_HOST` env var)
    /// - Port: `5432` (or `Ri_DB_PORT` env var)
    /// - Database: `ri` (or `Ri_DB_NAME` env var)
    /// - Username: `ri` (or `Ri_DB_USER` env var)
    /// - Password: empty (or `Ri_DB_PASSWORD` env var)
    /// - Max connections: 10
    /// - Min idle: 2
    /// - Connection timeout: 30 seconds
    /// - Idle timeout: 600 seconds
    /// - Max lifetime: 3600 seconds
    /// - SSL mode: `Prefer`
    /// - Statement cache: 100
    ///
    /// ## Environment Variable Override
    ///
    /// Default values are read from environment variables if available:
    /// ```bash
    /// export Ri_DB_HOST=db.example.com
    /// export Ri_DB_PORT=5432
    /// export Ri_DB_NAME=myapp
    /// export Ri_DB_USER=admin
    /// export Ri_DB_PASSWORD=secret
    /// ```
    ///
    /// # Returns
    ///
    /// A new `RiDatabaseConfig` instance configured for PostgreSQL
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// // Basic PostgreSQL configuration
    /// let config = RiDatabaseConfig::postgres();
    ///
    /// // With environment variable overrides
    /// // (assumes Ri_DB_* variables are set)
    /// let config = RiDatabaseConfig::postgres();
    /// ```
    pub fn postgres() -> Self {
        Self {
            database_type: DatabaseType::Postgres,
            host: env::var("Ri_DB_HOST").unwrap_or_else(|_| "localhost".to_string()),
            port: env::var("Ri_DB_PORT")
                .unwrap_or_else(|_| "5432".to_string())
                .parse()
                .unwrap_or(5432),
            database: env::var("Ri_DB_NAME").unwrap_or_else(|_| "ri".to_string()),
            username: env::var("Ri_DB_USER").unwrap_or_else(|_| "ri".to_string()),
            password: env::var("Ri_DB_PASSWORD").unwrap_or_else(|_| "".to_string()),
            max_connections: 10,
            min_idle_connections: 2,
            connection_timeout_secs: 30,
            idle_timeout_secs: 600,
            max_lifetime_secs: 3600,
            ssl_mode: SslMode::Prefer,
            statement_cache_size: 100,
        }
    }

    /// Creates a configuration for MySQL with default settings.
    ///
    /// This factory method initializes a configuration with sensible defaults
    /// for MySQL connections. Default values can be overridden using
    /// environment variables or the builder methods.
    ///
    /// ## Defaults
    ///
    /// - Host: `localhost` (or `Ri_DB_HOST` env var)
    /// - Port: `3306` (or `Ri_DB_PORT` env var)
    /// - Database: `ri` (or `Ri_DB_NAME` env var)
    /// - Username: `ri` (or `Ri_DB_USER` env var)
    /// - Password: empty (or `Ri_DB_PASSWORD` env var)
    /// - Max connections: 10
    /// - Min idle: 2
    /// - Connection timeout: 30 seconds
    /// - Idle timeout: 600 seconds
    /// - Max lifetime: 3600 seconds
    /// - SSL mode: `Prefer`
    /// - Statement cache: 100
    ///
    /// ## MySQL-Specific Notes
    ///
    /// - MySQL uses `mysql://` URI scheme in connection strings
    /// - MySQL 8.0+ uses `caching_sha2_password` by default
    /// - Consider using `SslMode::Require` for production
    ///
    /// # Returns
    ///
    /// A new `RiDatabaseConfig` instance configured for MySQL
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// // Basic MySQL configuration
    /// let config = RiDatabaseConfig::mysql();
    ///
    /// // Customized configuration
    /// let config = RiDatabaseConfig::mysql()
    ///     .host("db.example.com")
    ///     .database("myapp")
    ///     .user("app_user")
    ///     .password("secure_password");
    /// ```
    pub fn mysql() -> Self {
        Self {
            database_type: DatabaseType::MySQL,
            host: env::var("Ri_DB_HOST").unwrap_or_else(|_| "localhost".to_string()),
            port: env::var("Ri_DB_PORT")
                .unwrap_or_else(|_| "3306".to_string())
                .parse()
                .unwrap_or(3306),
            database: env::var("Ri_DB_NAME").unwrap_or_else(|_| "ri".to_string()),
            username: env::var("Ri_DB_USER").unwrap_or_else(|_| "ri".to_string()),
            password: env::var("Ri_DB_PASSWORD").unwrap_or_else(|_| "".to_string()),
            max_connections: 10,
            min_idle_connections: 2,
            connection_timeout_secs: 30,
            idle_timeout_secs: 600,
            max_lifetime_secs: 3600,
            ssl_mode: SslMode::Prefer,
            statement_cache_size: 100,
        }
    }

    /// Creates a configuration for SQLite at the specified path.
    ///
    /// This factory method initializes a configuration for SQLite database
    /// at the given file path. SQLite is a serverless database that stores
    /// data in a single file.
    ///
    /// ## Special Considerations
    ///
    /// - The `host` and `port` fields are ignored
    /// - The `username` and `password` fields are ignored
    /// - The `ssl_mode` field is ignored
    /// - File path can be `:memory:` for in-memory database
    ///
    /// ## Path Handling
    ///
    /// - Relative paths are resolved relative to the current working directory
    /// - Parent directories are created automatically if they don't exist
    /// - Use absolute paths for reliability in production
    ///
    /// ## File Permissions
    ///
    /// The SQLite file and its directory must be writable by the application.
    /// Consider the following:
    /// - The application user needs write permission to the database file
    /// - The directory containing the database must be writable (for journal files)
    /// - Consider file permissions (0600 recommended for the database file)
    ///
    /// # Arguments
    ///
    /// * `path` - File path for the SQLite database (or `:memory:` for in-memory)
    ///
    /// # Returns
    ///
    /// A new `RiDatabaseConfig` instance configured for SQLite
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// // File-based database
    /// let config = RiDatabaseConfig::sqlite("./data/myapp.db");
    ///
    /// // In-memory database (for testing)
    /// let config = RiDatabaseConfig::sqlite(":memory:");
    ///
    /// // Absolute path
    /// let config = RiDatabaseConfig::sqlite("/var/lib/ri/database.db");
    /// ```
    pub fn sqlite(path: &str) -> Self {
        Self {
            database_type: DatabaseType::SQLite,
            host: "".to_string(),
            port: 0,
            database: path.to_string(),
            username: "".to_string(),
            password: "".to_string(),
            max_connections: 10,
            min_idle_connections: 1,
            connection_timeout_secs: 30,
            idle_timeout_secs: 600,
            max_lifetime_secs: 3600,
            ssl_mode: SslMode::Disable,
            statement_cache_size: 100,
        }
    }

    /// Sets the database server hostname.
    ///
    /// This method configures the host address for database connections.
    /// It accepts hostnames, domain names, and IP addresses.
    ///
    /// # Arguments
    ///
    /// * `host` - The hostname or IP address of the database server
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// let config = RiDatabaseConfig::postgres()
    ///     .host("db.example.com");
    ///
    /// let config = RiDatabaseConfig::mysql()
    ///     .host("192.168.1.100");
    /// ```
    pub fn host(mut self, host: &str) -> Self {
        self.host = host.to_string();
        self
    }

    /// Sets the database server port.
    ///
    /// This method configures the port number for database connections.
    /// Each database type has a default port, but this can be overridden
    /// for non-standard configurations or when using database proxies.
    ///
    /// # Arguments
    ///
    /// * `port` - The port number for database connections (1-65535)
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Common Ports
    ///
    /// - PostgreSQL: 5432
    /// - MySQL: 3306
    /// - MongoDB: 27017
    /// - Redis: 6379
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// // Non-standard PostgreSQL port
    /// let config = RiDatabaseConfig::postgres()
    ///     .port(15432);
    /// ```
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Sets the database name.
    ///
    /// This method configures the name of the database to connect to.
    /// For PostgreSQL and MySQL, this is the logical database name.
    /// For SQLite, use the `sqlite()` constructor instead.
    ///
    /// # Arguments
    ///
    /// * `database` - The name of the database to connect to
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// let config = RiDatabaseConfig::postgres()
    ///     .database("production_db");
    /// ```
    pub fn database(mut self, database: &str) -> Self {
        self.database = database.to_string();
        self
    }

    /// Sets the database username.
    ///
    /// This method configures the username for database authentication.
    /// The specified user must have sufficient privileges to perform
    /// the required database operations.
    ///
    /// # Arguments
    ///
    /// * `user` - The username for database authentication
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Security Note
    ///
    /// For security, consider using environment variables instead of
    /// hardcoding credentials in your code:
    /// ```rust,ignore
    /// use std::env;
    ///
    /// let config = RiDatabaseConfig::postgres()
    ///     .user(&env::var("DB_USER").unwrap());
    /// ```
    pub fn user(mut self, user: &str) -> Self {
        self.username = user.to_string();
        self
    }

    /// Sets the database password.
    ///
    /// This method configures the password for database authentication.
    /// The password is used together with the username to authenticate
    /// with the database server.
    ///
    /// # Arguments
    ///
    /// * `password` - The password for database authentication
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Security Warning
    ///
    /// **Never** hardcode passwords in your source code. Use:
    /// - Environment variables
    /// - Secret management services (AWS Secrets Manager, HashiCorp Vault)
    /// - Configuration files with restricted permissions
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use std::env;
    /// use ri::database::RiDatabaseConfig;
    ///
    /// let config = RiDatabaseConfig::postgres()
    ///     .password(&env::var("DB_PASSWORD").unwrap());
    /// ```
    pub fn password(mut self, password: &str) -> Self {
        self.password = password.to_string();
        self
    }

    /// Sets the maximum number of concurrent connections.
    ///
    /// This method configures the upper bound of the connection pool.
    /// The pool will not create more than this number of connections,
    /// even under heavy load.
    ///
    /// # Arguments
    ///
    /// * `max` - Maximum number of concurrent connections (minimum 1)
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Performance Considerations
    ///
    /// - Higher values allow more concurrent database operations
    /// - Each connection consumes memory on both client and server
    /// - Database server has its own connection limits (e.g., PostgreSQL's `max_connections`)
    /// - Consider using connection pooling middleware for very high concurrency
    ///
    /// # Recommendations
    ///
    /// - Development: 5-10 connections
    /// - Production: 10-50 connections (depends on workload)
    /// - Monitor database server connection counts
    pub fn max_connections(mut self, max: u32) -> Self {
        self.max_connections = max;
        self
    }

    /// Sets the minimum number of idle connections.
    ///
    /// This method configures the minimum number of idle connections
    /// that the pool will maintain. Having idle connections ready reduces
    /// the latency of new database operations.
    ///
    /// # Arguments
    ///
    /// * `min` - Minimum number of idle connections (must be <= max_connections)
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Trade-offs
    ///
    /// - Benefits: Reduced latency for new operations
    /// - Cost: Increased memory usage and database server load
    ///
    /// # Recommendations
    ///
    /// - Set to expected concurrency level for best latency
    /// - Or use a small value (1-2) if memory is constrained
    pub fn min_idle_connections(mut self, min: u32) -> Self {
        self.min_idle_connections = min;
        self
    }

    /// Sets the connection timeout in seconds.
    ///
    /// This method configures the maximum time to wait when establishing
    /// a new database connection. If a connection cannot be established
    /// within this time, the operation will fail with a timeout error.
    ///
    /// # Arguments
    ///
    /// * `secs` - Timeout in seconds for connection establishment
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Considerations
    ///
    /// - Too short: May cause false failures under normal load
    /// - Too long: May hide database server problems
    /// - Consider network latency to database server
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// // 60 second timeout for distant databases
    /// let config = RiDatabaseConfig::postgres()
    ///     .connection_timeout_secs(60);
    /// ```
    pub fn connection_timeout_secs(mut self, secs: u64) -> Self {
        self.connection_timeout_secs = secs;
        self
    }

    /// Sets the idle connection timeout in seconds.
    ///
    /// This method configures how long an idle connection can exist
    /// before being closed. Idle connections are those that have been
    /// checked back into the pool but not reused.
    ///
    /// # Arguments
    ///
    /// * `secs` - Maximum idle time in seconds before connection is closed
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Purpose
    ///
    /// - Frees resources on both client and database server
    /// - Handles database server connection timeouts
    /// - Reconnects after network interruptions
    ///
    /// # Recommendations
    ///
    /// - 600 seconds (10 minutes) for typical web applications
    /// - 300 seconds (5 minutes) for batch processing
    /// - Consider database server's `wait_timeout` setting (MySQL)
    pub fn idle_timeout_secs(mut self, secs: u64) -> Self {
        self.idle_timeout_secs = secs;
        self
    }

    /// Sets the maximum connection lifetime in seconds.
    ///
    /// This method configures the maximum age of a connection.
    /// Connections older than this will be closed and replaced with
    /// new ones when they are returned to the pool.
    ///
    /// # Arguments
    ///
    /// * `secs` - Maximum connection lifetime in seconds
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Purpose
    ///
    /// - Prevents stale connections from database server timeouts
    /// - Handles database server restarts gracefully
    /// - Rotates connections to handle network interruptions
    ///
    /// # Recommendations
    ///
    /// - 1800-3600 seconds (30-60 minutes) for most applications
    /// - Shorter values for very long-running applications
    /// - Disable by using a very large value if needed
    pub fn max_lifetime_secs(mut self, secs: u64) -> Self {
        self.max_lifetime_secs = secs;
        self
    }

    /// Sets the SSL/TLS mode for connections.
    ///
    /// This method configures whether and how SSL/TLS encryption is used
    /// for database connections. For production environments, `SslMode::Require`
    /// is recommended to ensure all data is encrypted.
    ///
    /// # Arguments
    ///
    /// * `mode` - The SSL/TLS mode to use
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::{RiDatabaseConfig, SslMode};
    ///
    /// // Require SSL for production
    /// let config = RiDatabaseConfig::postgres()
    ///     .ssl_mode(SslMode::Require);
    /// ```
    pub fn ssl_mode(mut self, mode: SslMode) -> Self {
        self.ssl_mode = mode;
        self
    }

    /// Sets the prepared statement cache size.
    ///
    /// This method configures the maximum number of prepared statements
    /// to cache. Prepared statements are cached to reduce the overhead
    /// of repeated query compilation.
    ///
    /// # Arguments
    ///
    /// * `size` - Maximum number of prepared statements to cache (0 to disable)
    ///
    /// # Returns
    ///
    /// The updated configuration (for method chaining)
    ///
    /// # Performance Impact
    ///
    /// - Benefit: Reduces query compilation overhead for repeated queries
    /// - Cost: Increased memory usage for statement metadata
    /// - Trade-off: Balance between memory and CPU usage
    ///
    /// # Recommendations
    ///
    /// - 100-500 for typical applications
    /// - 1000+ for applications with many repeated complex queries
    /// - 0 to disable statement caching (for debugging)
    pub fn statement_cache_size(mut self, size: u32) -> Self {
        self.statement_cache_size = size;
        self
    }

    /// Builds the final configuration.
    ///
    /// This method finalizes the configuration and returns the complete
    /// `RiDatabaseConfig` instance. It is the terminal method in the
    /// builder chain.
    ///
    /// # Returns
    ///
    /// The complete configuration ready for use with `RiDatabaseManager`
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// let config = RiDatabaseConfig::postgres()
    ///     .host("localhost")
    ///     .database("myapp")
    ///     .user("app")
    ///     .password("secret")
    ///     .max_connections(10)
    ///     .build();
    /// ```
    pub fn build(self) -> RiDatabaseConfig {
        self
    }

    /// Generates a connection string for the configured database.
    ///
    /// This method creates a database-specific connection string URI
    /// that can be used with various database client libraries.
    ///
    /// # Returns
    ///
    /// A String containing the connection string
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use ri::database::RiDatabaseConfig;
    ///
    /// let config = RiDatabaseConfig::postgres()
    ///     .host("localhost")
    ///     .port(5432)
    ///     .database("myapp")
    ///     .user("app")
    ///     .password("secret");
    ///
    /// let connection_string = config.connection_string();
    /// // postgresql://app:secret@localhost:5432/myapp
    /// ```
    pub fn connection_string(&self) -> String {
        match self.database_type {
            DatabaseType::Postgres => {
                format!(
                    "postgresql://{}:{}@{}:{}/{}",
                    self.username, self.password, self.host, self.port, self.database
                )
            }
            DatabaseType::MySQL => {
                format!(
                    "mysql://{}:{}@{}:{}/{}",
                    self.username, self.password, self.host, self.port, self.database
                )
            }
            DatabaseType::SQLite => self.database.clone(),
            DatabaseType::MongoDB => {
                format!(
                    "mongodb://{}:{}@{}:{}/{}",
                    self.username, self.password, self.host, self.port, self.database
                )
            }
            DatabaseType::Redis => {
                format!(
                    "redis://{}:{}@{}:{}",
                    self.username, self.password, self.host, self.port
                )
            }
        }
    }
}

impl Default for RiDatabaseConfig {
    fn default() -> Self {
        Self::postgres()
    }
}