switchy_database_connection 0.3.0

Switchy database connection package
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
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
//! Database connection initialization and credential management.
//!
//! This crate provides a unified interface for initializing database connections
//! across multiple database backends, including `SQLite` (via rusqlite or sqlx),
//! `PostgreSQL` (via tokio-postgres or sqlx), and Turso. It supports various TLS
//! configurations and credential management through environment variables, URLs,
//! or AWS SSM parameters.
//!
//! # Features
//!
//! * Multiple database backends: `SQLite`, `PostgreSQL`, `Turso`
//! * TLS support for `PostgreSQL`: `OpenSSL`, native-tls, or no TLS
//! * Flexible credential management from URLs or environment
//! * Connection pooling with configurable pool sizes
//! * Feature-gated compilation for minimal dependencies
//!
//! # Examples
//!
//! ```rust,no_run
//! # use switchy_database_connection::{Credentials, init};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Parse credentials from a database URL
//! let creds = Credentials::from_url("postgres://user:pass@localhost:5432/mydb")?;
//!
//! // Initialize a database connection (parameters vary by feature)
//! # #[cfg(any(feature = "sqlite", feature = "duckdb"))]
//! let db = init(None, Some(creds)).await?;
//! # #[cfg(not(any(feature = "sqlite", feature = "duckdb")))]
//! # let db = init(Some(creds)).await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Feature Flags
//!
//! The crate uses feature flags to control which database backend is compiled:
//!
//! * `sqlite-rusqlite` - `SQLite` via rusqlite
//! * `sqlite-sqlx` - `SQLite` via sqlx
//! * `postgres-raw` - `PostgreSQL` via tokio-postgres
//! * `postgres-sqlx` - `PostgreSQL` via sqlx
//! * `postgres-native-tls` - `PostgreSQL` with native-tls
//! * `postgres-openssl` - `PostgreSQL` with `OpenSSL`
//! * `turso` - Turso database support
//! * `creds` - AWS SSM credential retrieval
//! * `simulator` - Test database simulator

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use switchy_database::Database;
use thiserror::Error;

#[cfg(feature = "creds")]
pub mod creds;

/// Database connection credentials
///
/// Contains host, database name, username, and optional password
/// for establishing database connections.
#[allow(unused)]
pub struct Credentials {
    host: String,
    port: Option<u16>,
    name: String,
    user: String,
    password: Option<String>,
}

/// Errors that can occur when parsing database credentials from a URL
#[derive(Debug, Error)]
pub enum CredentialsParseError {
    /// URL does not contain `://` separator
    #[error("Invalid URL format")]
    InvalidUrl,
    /// Host component is missing or empty in the URL
    #[error("Missing host")]
    MissingHost,
    /// Database name component is missing or empty in the URL
    #[error("Missing database name")]
    MissingDatabase,
    /// Username component is missing or empty in the URL
    #[error("Missing username")]
    MissingUsername,
    /// URL scheme is not supported (must be postgres, postgresql, or mysql)
    #[error("Unsupported scheme: {0}")]
    UnsupportedScheme(String),
}

impl Credentials {
    /// Creates new database credentials
    #[must_use]
    pub const fn new(
        host: String,
        port: Option<u16>,
        name: String,
        user: String,
        password: Option<String>,
    ) -> Self {
        Self {
            host,
            port,
            name,
            user,
            password,
        }
    }

    /// Parse credentials from a database URL
    ///
    /// Supports formats like:
    /// * `postgres://user:pass@host:port/dbname`
    /// * `mysql://user:pass@host:port/dbname`
    /// * `sqlite://path/to/db.sqlite`
    ///
    /// # Errors
    ///
    /// * [`CredentialsParseError::InvalidUrl`] when `url` does not contain `://`
    /// * [`CredentialsParseError::MissingDatabase`] when the database path segment is absent or empty
    /// * [`CredentialsParseError::MissingUsername`] when the username segment is absent or empty
    /// * [`CredentialsParseError::MissingHost`] when the host segment is absent or empty
    /// * [`CredentialsParseError::UnsupportedScheme`] when the URL scheme is not one of `postgres`, `postgresql`, or `mysql`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use switchy_database_connection::Credentials;
    ///
    /// let creds = Credentials::from_url("postgres://user:secret@localhost:5432/moosicbox")
    ///     .expect("URL should parse");
    ///
    /// assert_eq!(creds.host(), "localhost");
    /// assert_eq!(creds.port(), Some(5432));
    /// assert_eq!(creds.name(), "moosicbox");
    /// assert_eq!(creds.user(), "user");
    /// assert_eq!(creds.password(), Some("secret"));
    /// ```
    pub fn from_url(url: &str) -> Result<Self, CredentialsParseError> {
        // Simple URL parsing without external dependencies
        let url = url.trim();

        // Find scheme
        let scheme_end = url.find("://").ok_or(CredentialsParseError::InvalidUrl)?;
        let scheme = &url[..scheme_end];
        let rest = &url[scheme_end + 3..];

        match scheme {
            "postgres" | "postgresql" | "mysql" => {
                // Format: user:pass@host:port/dbname
                let (auth_host, dbname) = rest
                    .rsplit_once('/')
                    .ok_or(CredentialsParseError::MissingDatabase)?;

                let Some((auth, host_port)) = auth_host.rsplit_once('@') else {
                    return Err(CredentialsParseError::MissingUsername);
                };

                let (user, password) = if let Some((user, pass)) = auth.split_once(':') {
                    (user, Some(pass.to_string()))
                } else {
                    (auth, None)
                };

                // Split host and port
                let (host, port) = if let Some((h, p)) = host_port.rsplit_once(':') {
                    p.parse::<u16>()
                        .map_or((host_port, None), |port_num| (h, Some(port_num)))
                } else {
                    (host_port, None)
                };

                if user.is_empty() {
                    return Err(CredentialsParseError::MissingUsername);
                }
                if host.is_empty() {
                    return Err(CredentialsParseError::MissingHost);
                }
                if dbname.is_empty() {
                    return Err(CredentialsParseError::MissingDatabase);
                }

                Ok(Self::new(
                    host.to_string(),
                    port,
                    dbname.to_string(),
                    user.to_string(),
                    password,
                ))
            }
            _ => Err(CredentialsParseError::UnsupportedScheme(scheme.to_string())),
        }
    }

    /// Returns the database host
    #[must_use]
    pub fn host(&self) -> &str {
        &self.host
    }

    /// Returns the database port, if present
    #[allow(clippy::must_use_candidate)]
    pub const fn port(&self) -> Option<u16> {
        self.port
    }

    /// Returns the database name
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the username
    #[must_use]
    pub fn user(&self) -> &str {
        &self.user
    }

    /// Returns the password, if present
    #[allow(clippy::must_use_candidate)]
    pub fn password(&self) -> Option<&str> {
        self.password.as_deref()
    }
}

/// Errors that can occur when initializing a database connection
#[derive(Debug, Error)]
pub enum InitDbError {
    /// Error initializing `SQLite` via rusqlite
    #[cfg(feature = "sqlite-rusqlite")]
    #[error(transparent)]
    InitSqlite(#[from] InitSqliteRusqliteError),
    /// Error initializing `PostgreSQL` connection
    #[cfg(feature = "postgres")]
    #[error(transparent)]
    InitPostgres(#[from] InitPostgresError),
    /// Error initializing generic database connection
    #[cfg(feature = "postgres")]
    #[error(transparent)]
    InitDatabase(#[from] InitDatabaseError),
    /// Error initializing `SQLite` via sqlx
    #[cfg(any(
        feature = "sqlite-sqlx",
        all(
            feature = "sqlx",
            not(feature = "postgres"),
            not(feature = "postgres-sqlx"),
            not(feature = "sqlite-rusqlite")
        )
    ))]
    #[error(transparent)]
    InitSqliteSqlxDatabase(#[from] InitSqliteSqlxDatabaseError),
    /// Error initializing Turso database
    #[cfg(feature = "turso")]
    #[error(transparent)]
    InitTurso(#[from] InitTursoError),
    /// Error initializing `DuckDB` database
    #[cfg(feature = "duckdb")]
    #[error(transparent)]
    InitDuckDb(#[from] InitDuckDbError),
    /// Credentials were required but not provided
    #[error("Credentials are required")]
    CredentialsRequired,
    /// Generic database error
    #[error(transparent)]
    Database(#[from] switchy_database::DatabaseError),
}

/// Initializes a database connection based on active feature flags.
///
/// This function selects the appropriate database backend based on compile-time
/// features (e.g., `sqlite-rusqlite`, `postgres-raw`, `turso`) and returns a
/// boxed trait object implementing the `Database` interface.
///
/// # Panics
///
/// * If invalid features are specified for the crate
///
/// # Errors
///
/// * [`InitDbError::CredentialsRequired`] when a credentials-based backend is active and `creds` is `None`
/// * `InitDbError::InitSqlite` when `sqlite-rusqlite` initialization fails (when enabled)
/// * `InitDbError::InitPostgres` when `postgres` backend initialization fails (when enabled)
/// * `InitDbError::InitDatabase` when sqlx/raw `PostgreSQL` initialization fails (when enabled)
/// * `InitDbError::InitSqliteSqlxDatabase` when `sqlite-sqlx` initialization fails (when enabled)
/// * `InitDbError::InitTurso` when `turso` initialization fails (when enabled)
/// * `InitDbError::InitDuckDb` when `duckdb` initialization fails (when enabled)
/// * [`InitDbError::Database`] when simulator or backend database wrapping fails
///
/// # Examples
///
/// ```rust,no_run
/// use switchy_database_connection::{init, Credentials};
///
/// # async fn example() -> Result<(), switchy_database_connection::InitDbError> {
/// let creds = Credentials::from_url("postgres://user:pass@localhost:5432/moosicbox")
///     .expect("URL should parse");
///
/// # #[cfg(any(feature = "sqlite", feature = "duckdb"))]
/// let _db = init(None, Some(creds)).await?;
/// # #[cfg(not(any(feature = "sqlite", feature = "duckdb")))]
/// # let _db = init(Some(creds)).await?;
/// # Ok(())
/// # }
/// ```
#[allow(clippy::branches_sharing_code, clippy::unused_async)]
pub async fn init(
    #[cfg(any(feature = "sqlite", feature = "duckdb"))]
    #[allow(unused)]
    path: Option<&std::path::Path>,
    #[allow(unused)] creds: Option<Credentials>,
) -> Result<Box<dyn Database>, InitDbError> {
    #[cfg(feature = "simulator")]
    {
        // Convert Path to string for the simulator
        #[cfg(any(feature = "sqlite", feature = "duckdb"))]
        let path_str = path.as_ref().map(|p| p.to_string_lossy().to_string());
        Ok(Box::new(
            switchy_database::simulator::SimulationDatabase::new_for_path(
                #[cfg(any(feature = "sqlite", feature = "duckdb"))]
                path_str.as_deref(),
                #[cfg(not(any(feature = "sqlite", feature = "duckdb")))]
                None,
            )
            .unwrap(),
        ))
    }

    #[cfg(not(feature = "simulator"))]
    {
        if cfg!(all(
            feature = "postgres-native-tls",
            feature = "postgres-raw"
        )) {
            #[cfg(all(feature = "postgres-native-tls", feature = "postgres-raw"))]
            return Ok(init_postgres_raw_native_tls(
                creds.ok_or(InitDbError::CredentialsRequired)?,
            )
            .await?);
            #[cfg(not(all(feature = "postgres-native-tls", feature = "postgres-raw")))]
            panic!("Invalid database features")
        } else if cfg!(all(feature = "postgres-openssl", feature = "postgres-raw")) {
            #[cfg(all(feature = "postgres-openssl", feature = "postgres-raw"))]
            return Ok(
                init_postgres_raw_openssl(creds.ok_or(InitDbError::CredentialsRequired)?).await?,
            );
            #[cfg(not(all(feature = "postgres-openssl", feature = "postgres-raw")))]
            panic!("Invalid database features")
        } else if cfg!(feature = "postgres-raw") {
            #[cfg(feature = "postgres-raw")]
            return Ok(
                init_postgres_raw_no_tls(creds.ok_or(InitDbError::CredentialsRequired)?).await?,
            );
            #[cfg(not(feature = "postgres-raw"))]
            panic!("Invalid database features")
        } else if cfg!(feature = "postgres-sqlx") {
            #[cfg(feature = "postgres-sqlx")]
            return Ok(init_postgres_sqlx(creds.ok_or(InitDbError::CredentialsRequired)?).await?);
            #[cfg(not(feature = "postgres-sqlx"))]
            panic!("Invalid database features")
        } else if cfg!(feature = "turso") {
            #[cfg(feature = "turso")]
            return Ok(init_turso_local(path).await?);
            #[cfg(not(feature = "turso"))]
            panic!("Invalid database features")
        } else if cfg!(feature = "duckdb") {
            #[cfg(feature = "duckdb")]
            return Ok(init_duckdb(path)?);
            #[cfg(not(feature = "duckdb"))]
            panic!("Invalid database features")
        } else if cfg!(feature = "sqlite-rusqlite") {
            #[cfg(feature = "sqlite-rusqlite")]
            return Ok(init_sqlite_rusqlite(path)?);
            #[cfg(not(feature = "sqlite-rusqlite"))]
            panic!("Invalid database features")
        } else if cfg!(feature = "sqlite-sqlx") {
            #[cfg(all(not(feature = "postgres"), feature = "sqlite", feature = "sqlite-sqlx"))]
            return Ok(init_sqlite_sqlx(path).await?);
            #[cfg(not(all(
                not(feature = "postgres"),
                feature = "sqlite",
                feature = "sqlite-sqlx"
            )))]
            panic!("Invalid database features")
        } else {
            panic!("Invalid database features")
        }
    }
}

/// Initializes a non-SQLite database connection based on active feature flags.
///
/// This function is similar to `init` but specifically for non-SQLite backends
/// (e.g., `PostgreSQL`). It selects the appropriate database based on compile-time
/// features and returns a boxed trait object implementing the `Database` interface.
///
/// # Panics
///
/// * If invalid features are specified for the crate
///
/// # Errors
///
/// * [`InitDbError::CredentialsRequired`] when a credentials-based backend is active and `creds` is `None`
/// * `InitDbError::InitPostgres` when `postgres` backend initialization fails (when enabled)
/// * `InitDbError::InitDatabase` when sqlx/raw `PostgreSQL` initialization fails (when enabled)
///
/// # Examples
///
/// ```rust,no_run
/// use switchy_database_connection::{init_default_non_sqlite, Credentials};
///
/// # async fn example() -> Result<(), switchy_database_connection::InitDbError> {
/// let creds = Credentials::from_url("postgres://user:pass@localhost:5432/moosicbox")
///     .expect("URL should parse");
///
/// let _db = init_default_non_sqlite(Some(creds)).await?;
/// # Ok(())
/// # }
/// ```
#[allow(clippy::branches_sharing_code, clippy::unused_async)]
pub async fn init_default_non_sqlite(
    #[allow(unused)] creds: Option<Credentials>,
) -> Result<Box<dyn Database>, InitDbError> {
    if cfg!(all(
        feature = "postgres-native-tls",
        feature = "postgres-raw"
    )) {
        #[cfg(all(feature = "postgres-native-tls", feature = "postgres-raw"))]
        return Ok(
            init_postgres_raw_native_tls(creds.ok_or(InitDbError::CredentialsRequired)?).await?,
        );
        #[cfg(not(all(feature = "postgres-native-tls", feature = "postgres-raw")))]
        panic!("Invalid database features")
    } else if cfg!(all(feature = "postgres-openssl", feature = "postgres-raw")) {
        #[cfg(all(feature = "postgres-openssl", feature = "postgres-raw"))]
        return Ok(
            init_postgres_raw_openssl(creds.ok_or(InitDbError::CredentialsRequired)?).await?,
        );
        #[cfg(not(all(feature = "postgres-openssl", feature = "postgres-raw")))]
        panic!("Invalid database features")
    } else if cfg!(feature = "postgres-raw") {
        #[cfg(feature = "postgres-raw")]
        return Ok(init_postgres_raw_no_tls(creds.ok_or(InitDbError::CredentialsRequired)?).await?);
        #[cfg(not(feature = "postgres-raw"))]
        panic!("Invalid database features")
    } else if cfg!(feature = "postgres-sqlx") {
        #[cfg(feature = "postgres-sqlx")]
        return Ok(init_postgres_sqlx(creds.ok_or(InitDbError::CredentialsRequired)?).await?);
        #[cfg(not(feature = "postgres-sqlx"))]
        panic!("Invalid database features")
    }

    panic!("Invalid database features")
}

/// Errors that can occur when initializing a `SQLite` connection via `rusqlite`
#[cfg(feature = "sqlite-rusqlite")]
#[derive(Debug, Error)]
pub enum InitSqliteRusqliteError {
    /// Rusqlite database error
    #[error(transparent)]
    Sqlite(#[from] ::rusqlite::Error),
}

/// Errors that can occur when initializing a `DuckDB` connection
#[cfg(feature = "duckdb")]
#[derive(Debug, Error)]
pub enum InitDuckDbError {
    /// `DuckDB` database error
    #[error(transparent)]
    DuckDb(#[from] ::duckdb::Error),
    /// Invalid `DuckDB` option in environment variable
    #[error("Invalid DuckDB configuration: {0}")]
    InvalidConfig(String),
}

#[cfg(feature = "duckdb")]
fn parse_duckdb_mode(value: &str) -> Result<switchy_database::duckdb::DuckDbMode, InitDuckDbError> {
    match value.trim().to_ascii_lowercase().as_str() {
        "deterministic" => Ok(switchy_database::duckdb::DuckDbMode::Deterministic),
        "pooled" => Ok(switchy_database::duckdb::DuckDbMode::Pooled),
        _ => Err(InitDuckDbError::InvalidConfig(format!(
            "SWITCHY_DUCKDB_MODE must be 'deterministic' or 'pooled' (got '{value}')"
        ))),
    }
}

#[cfg(feature = "duckdb")]
fn parse_duckdb_consistency(
    value: &str,
) -> Result<switchy_database::duckdb::DuckDbConsistency, InitDuckDbError> {
    match value.trim().to_ascii_lowercase().as_str() {
        "strict" => Ok(switchy_database::duckdb::DuckDbConsistency::Strict),
        "relaxed" => Ok(switchy_database::duckdb::DuckDbConsistency::Relaxed),
        _ => Err(InitDuckDbError::InvalidConfig(format!(
            "SWITCHY_DUCKDB_CONSISTENCY must be 'strict' or 'relaxed' (got '{value}')"
        ))),
    }
}

#[cfg(feature = "duckdb")]
fn duckdb_config_from_env() -> Result<switchy_database::duckdb::DuckDbConfig, InitDuckDbError> {
    let mut config = switchy_database::duckdb::DuckDbConfig::default();

    if let Ok(mode) = std::env::var("SWITCHY_DUCKDB_MODE") {
        config.mode = parse_duckdb_mode(&mode)?;
    }

    if let Ok(consistency) = std::env::var("SWITCHY_DUCKDB_CONSISTENCY") {
        config.consistency = parse_duckdb_consistency(&consistency)?;
    }

    Ok(config)
}

/// Initializes a `DuckDB` database connection.
///
/// Creates a connection pool with 5 connections. If no path is provided,
/// creates an in-memory database.
///
/// # Errors
///
/// * Propagates [`InitDuckDbError::InvalidConfig`] when `SWITCHY_DUCKDB_MODE` or
///   `SWITCHY_DUCKDB_CONSISTENCY` is set to an unsupported value
/// * Propagates [`InitDuckDbError::DuckDb`] when opening one of the `DuckDB` connections fails
#[cfg(feature = "duckdb")]
pub fn init_duckdb(
    db_location: Option<&std::path::Path>,
) -> Result<Box<dyn Database>, InitDuckDbError> {
    init_duckdb_with_options(db_location, duckdb_config_from_env()?)
}

/// Initializes a `DuckDB` database connection with explicit backend options.
///
/// # Errors
///
/// * Propagates [`InitDuckDbError::DuckDb`] when opening one of the `DuckDB` connections fails
#[cfg(feature = "duckdb")]
pub fn init_duckdb_with_options(
    db_location: Option<&std::path::Path>,
    config: switchy_database::duckdb::DuckDbConfig,
) -> Result<Box<dyn Database>, InitDuckDbError> {
    use std::sync::Arc;

    use switchy_async::sync::Mutex;
    use switchy_database::duckdb::DuckDbMode;

    const CONNECTION_POOL_SIZE: u8 = 5;

    let connections = match config.mode {
        DuckDbMode::Deterministic => {
            let conn = if let Some(path) = db_location {
                ::duckdb::Connection::open(path)?
            } else {
                ::duckdb::Connection::open_in_memory()?
            };
            let shared = Arc::new(Mutex::new(conn));
            let mut connections = Vec::new();
            for _ in 0..CONNECTION_POOL_SIZE {
                connections.push(Arc::clone(&shared));
            }
            connections
        }
        DuckDbMode::Pooled => {
            let mut connections = Vec::new();
            for _ in 0..CONNECTION_POOL_SIZE {
                let conn = if let Some(path) = db_location {
                    ::duckdb::Connection::open(path)?
                } else {
                    ::duckdb::Connection::open_in_memory()?
                };
                connections.push(Arc::new(Mutex::new(conn)));
            }
            connections
        }
    };

    Ok(Box::new(
        switchy_database::duckdb::DuckDbDatabase::new_with_config(connections, config),
    ))
}

/// Initializes a read-only `DuckDB` database connection.
///
/// Creates a connection pool with 5 connections opened in read-only mode.
///
/// # Errors
///
/// * Propagates [`InitDuckDbError::InvalidConfig`] when `SWITCHY_DUCKDB_MODE` or
///   `SWITCHY_DUCKDB_CONSISTENCY` is set to an unsupported value
/// * Propagates [`InitDuckDbError::DuckDb`] when opening one of the read-only `DuckDB` connections fails
///
/// # Panics
///
/// * If the `DuckDB` access mode configuration fails (should not happen)
#[cfg(feature = "duckdb")]
pub fn init_duckdb_read_only(
    db_location: &std::path::Path,
) -> Result<Box<dyn Database>, InitDuckDbError> {
    init_duckdb_read_only_with_options(db_location, duckdb_config_from_env()?)
}

/// Initializes a read-only `DuckDB` database connection with explicit backend options.
///
/// # Errors
///
/// * Propagates [`InitDuckDbError::DuckDb`] when opening one of the read-only `DuckDB` connections fails
///
/// # Panics
///
/// * If the `DuckDB` access mode configuration fails (should not happen)
#[cfg(feature = "duckdb")]
pub fn init_duckdb_read_only_with_options(
    db_location: &std::path::Path,
    config: switchy_database::duckdb::DuckDbConfig,
) -> Result<Box<dyn Database>, InitDuckDbError> {
    use std::sync::Arc;

    use switchy_async::sync::Mutex;
    use switchy_database::duckdb::DuckDbMode;

    const CONNECTION_POOL_SIZE: u8 = 5;

    let connections = match config.mode {
        DuckDbMode::Deterministic => {
            let flags = ::duckdb::Config::default()
                .access_mode(::duckdb::AccessMode::ReadOnly)
                .expect("Failed to set DuckDB access mode");
            let conn = ::duckdb::Connection::open_with_flags(db_location, flags)?;
            let shared = Arc::new(Mutex::new(conn));
            let mut connections = Vec::new();
            for _ in 0..CONNECTION_POOL_SIZE {
                connections.push(Arc::clone(&shared));
            }
            connections
        }
        DuckDbMode::Pooled => {
            let mut connections = Vec::new();
            for _ in 0..CONNECTION_POOL_SIZE {
                let flags = ::duckdb::Config::default()
                    .access_mode(::duckdb::AccessMode::ReadOnly)
                    .expect("Failed to set DuckDB access mode");
                let conn = ::duckdb::Connection::open_with_flags(db_location, flags)?;
                connections.push(Arc::new(Mutex::new(conn)));
            }
            connections
        }
    };

    Ok(Box::new(
        switchy_database::duckdb::DuckDbDatabase::new_with_config(connections, config),
    ))
}

/// Initializes a `SQLite` database connection using rusqlite.
///
/// Creates a connection pool with 5 connections. If no path is provided,
/// creates an in-memory database with a unique identifier.
///
/// # Errors
///
/// * Propagates [`InitSqliteRusqliteError::Sqlite`] when opening or configuring a `rusqlite` connection fails
///
/// # Panics
///
/// * If the `simulator` db connection fails to be initialized
#[cfg(feature = "sqlite-rusqlite")]
#[allow(unused, unreachable_code)]
pub fn init_sqlite_rusqlite(
    db_location: Option<&std::path::Path>,
) -> Result<Box<dyn Database>, InitSqliteRusqliteError> {
    #[cfg(feature = "simulator")]
    {
        // Convert Path to string for the simulator
        let path_str = db_location
            .as_ref()
            .map(|p| p.to_string_lossy().to_string());
        return Ok(Box::new(
            switchy_database::simulator::SimulationDatabase::new_for_path(path_str.as_deref())
                .unwrap(),
        ));
    }

    let db_url = db_location.map_or_else(
        || {
            use std::sync::atomic::AtomicU64;

            static ID: AtomicU64 = AtomicU64::new(0);

            let id = ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos();

            format!("file:rusqlite_memdb_{id}_{timestamp}:?mode=memory&cache=shared&uri=true")
        },
        |p| p.to_string_lossy().into_owned(),
    );

    let mut connections = Vec::new();
    for _ in 0..5 {
        let conn = ::rusqlite::Connection::open(&db_url)?;
        conn.busy_timeout(std::time::Duration::from_millis(10))?;

        connections.push(std::sync::Arc::new(switchy_async::sync::Mutex::new(conn)));
    }

    Ok(Box::new(switchy_database::rusqlite::RusqliteDatabase::new(
        connections,
    )))
}

/// Errors that can occur when initializing a `PostgreSQL` connection
#[cfg(feature = "postgres")]
#[derive(Debug, Error)]
pub enum InitPostgresError {
    /// Tokio-postgres connection error
    #[cfg(feature = "postgres-raw")]
    #[error(transparent)]
    Postgres(#[from] tokio_postgres::Error),
    /// Sqlx `PostgreSQL` error
    #[cfg(feature = "postgres-sqlx")]
    #[error(transparent)]
    PostgresSqlx(#[from] sqlx::Error),
}

/// Errors that can occur when initializing a `SQLite` connection via `sqlx`
#[cfg(any(
    feature = "sqlite-sqlx",
    all(
        feature = "sqlx",
        not(feature = "postgres"),
        not(feature = "postgres-sqlx"),
        not(feature = "sqlite-rusqlite")
    )
))]
#[derive(Debug, Error)]
pub enum InitSqliteSqlxDatabaseError {
    /// Sqlx `SQLite` error
    #[error(transparent)]
    SqliteSqlx(#[from] sqlx::Error),
}

/// Initializes a `SQLite` database connection using sqlx.
///
/// Creates a connection pool with 5 connections. If no path is provided,
/// creates an in-memory database with a unique identifier.
///
/// # Errors
///
/// * Propagates [`InitSqliteSqlxDatabaseError::SqliteSqlx`] when creating the sqlx `SQLite` pool fails
///
/// # Panics
///
/// * If the `simulator` db connection fails to be initialized
#[cfg(feature = "sqlite-sqlx")]
#[allow(unused, unreachable_code)]
pub async fn init_sqlite_sqlx(
    db_location: Option<&std::path::Path>,
) -> Result<Box<dyn Database>, InitSqliteSqlxDatabaseError> {
    use std::sync::Arc;

    use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
    use switchy_database::sqlx::sqlite::SqliteSqlxDatabase;

    const CONNECTION_POOL_SIZE: u8 = 5;

    #[cfg(feature = "simulator")]
    {
        // Convert Path to string for the simulator
        let path_str = db_location
            .as_ref()
            .map(|p| p.to_string_lossy().to_string());
        return Ok(Box::new(
            switchy_database::simulator::SimulationDatabase::new_for_path(path_str.as_deref())
                .unwrap(),
        ));
    }

    let connect_options = SqliteConnectOptions::new();
    let mut connect_options = if let Some(db_location) = db_location {
        connect_options
            .filename(db_location)
            .create_if_missing(true)
    } else {
        use std::sync::atomic::AtomicU64;

        static ID: AtomicU64 = AtomicU64::new(0);

        let id = ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let db_url = format!("file:sqlx_memdb_{id}_{timestamp}:?mode=memory&cache=shared&uri=true");

        connect_options.filename(db_url)
    };

    let pool = SqlitePoolOptions::new()
        .max_connections(CONNECTION_POOL_SIZE.into())
        .connect_with(connect_options)
        .await?;

    Ok(Box::new(SqliteSqlxDatabase::new(Arc::new(
        switchy_async::sync::Mutex::new(pool),
    ))))
}

/// Errors that can occur when initializing a Turso database connection
#[cfg(feature = "turso")]
#[derive(Debug, Error)]
pub enum InitTursoError {
    /// Turso database error
    #[error(transparent)]
    Turso(#[from] switchy_database::turso::TursoDatabaseError),
}

/// Initializes a local Turso database connection.
///
/// If no path is provided, creates an in-memory database using `:memory:`.
///
/// # Errors
///
/// * Propagates [`InitTursoError::Turso`] when opening the local Turso database fails
#[cfg(feature = "turso")]
pub async fn init_turso_local(
    path: Option<&std::path::Path>,
) -> Result<Box<dyn Database>, InitTursoError> {
    let db_path = path.map_or_else(
        || ":memory:".to_string(),
        |p| p.to_string_lossy().to_string(),
    );

    let db = switchy_database::turso::TursoDatabase::new(&db_path).await?;

    Ok(Box::new(db))
}

/// Errors that can occur during database initialization
#[cfg(feature = "postgres")]
#[derive(Debug, Error)]
pub enum InitDatabaseError {
    /// `OpenSSL` error during TLS setup
    #[cfg(all(feature = "postgres-openssl", feature = "postgres-raw"))]
    #[error(transparent)]
    OpenSsl(#[from] openssl::error::ErrorStack),
    /// Native-tls error during TLS setup
    #[cfg(all(feature = "postgres-native-tls", feature = "postgres-raw"))]
    #[error(transparent)]
    NativeTls(#[from] native_tls::Error),
    /// Tokio-postgres connection error
    #[cfg(feature = "postgres-raw")]
    #[error(transparent)]
    Postgres(#[from] tokio_postgres::Error),
    /// Sqlx `PostgreSQL` error
    #[cfg(feature = "postgres-sqlx")]
    #[error(transparent)]
    PostgresSqlx(#[from] sqlx::Error),
    /// Deadpool connection pool build error
    #[cfg(feature = "postgres-raw")]
    #[error(transparent)]
    DeadpoolBuildError(#[from] deadpool_postgres::BuildError),
    /// Invalid connection options provided
    #[error("Invalid Connection Options")]
    InvalidConnectionOptions,
}

/// Initializes a `PostgreSQL` database connection using sqlx.
///
/// Creates a connection pool with 5 connections using the provided credentials.
///
/// # Errors
///
/// * Propagates [`InitDatabaseError::PostgresSqlx`] when creating the sqlx `PostgreSQL` pool fails
#[cfg(feature = "postgres-sqlx")]
#[allow(unused)]
pub async fn init_postgres_sqlx(
    creds: Credentials,
) -> Result<Box<dyn Database>, InitDatabaseError> {
    use std::sync::Arc;

    use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
    use switchy_database::sqlx::postgres::PostgresSqlxDatabase;

    let connect_options = PgConnectOptions::new();
    let mut connect_options = connect_options
        .host(&creds.host)
        .database(&creds.name)
        .username(&creds.user);

    if let Some(port) = creds.port {
        connect_options = connect_options.port(port);
    }

    if let Some(db_password) = &creds.password {
        connect_options = connect_options.password(db_password);
    }

    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect_with(connect_options)
        .await?;

    Ok(Box::new(PostgresSqlxDatabase::new(Arc::new(
        switchy_async::sync::Mutex::new(pool),
    ))))
}

/// Errors that can occur when initializing a `MySQL` connection via `sqlx`
#[cfg(feature = "mysql-sqlx")]
#[derive(Debug, Error)]
pub enum InitMySqlSqlxError {
    /// Sqlx `MySQL` error
    #[error(transparent)]
    MySqlSqlx(#[from] sqlx::Error),
}

/// Initializes a `MySQL` database connection using sqlx.
///
/// Creates a connection pool with 5 connections using the provided credentials.
///
/// # Errors
///
/// * Propagates [`InitMySqlSqlxError::MySqlSqlx`] when creating the sqlx `MySQL` pool fails
#[cfg(feature = "mysql-sqlx")]
#[allow(unused)]
pub async fn init_mysql_sqlx(creds: Credentials) -> Result<Box<dyn Database>, InitMySqlSqlxError> {
    use std::sync::Arc;

    use sqlx::mysql::{MySqlConnectOptions, MySqlPoolOptions};
    use switchy_database::sqlx::mysql::MySqlSqlxDatabase;

    let connect_options = MySqlConnectOptions::new()
        .host(&creds.host)
        .database(&creds.name)
        .username(&creds.user);

    let connect_options = if let Some(port) = creds.port {
        connect_options.port(port)
    } else {
        connect_options
    };

    let connect_options = if let Some(db_password) = &creds.password {
        connect_options.password(db_password)
    } else {
        connect_options
    };

    let pool = MySqlPoolOptions::new()
        .max_connections(5)
        .connect_with(connect_options)
        .await?;

    Ok(Box::new(MySqlSqlxDatabase::new(Arc::new(
        switchy_async::sync::Mutex::new(pool),
    ))))
}

/// Initializes a `PostgreSQL` database connection using tokio-postgres with native-tls.
///
/// Creates a connection pool with 5 connections. For localhost connections,
/// accepts invalid hostnames to support self-signed certificates.
///
/// # Errors
///
/// * Propagates [`InitDatabaseError::NativeTls`] when building the native TLS connector fails
/// * Propagates [`InitDatabaseError::Postgres`] when configuring the `PostgreSQL` manager fails
/// * Propagates [`InitDatabaseError::DeadpoolBuildError`] when building the connection pool fails
#[cfg(all(feature = "postgres-native-tls", feature = "postgres-raw"))]
#[allow(unused, clippy::unused_async)]
pub async fn init_postgres_raw_native_tls(
    creds: Credentials,
) -> Result<Box<dyn Database>, InitDatabaseError> {
    use deadpool_postgres::{ManagerConfig, RecyclingMethod};
    use postgres_native_tls::MakeTlsConnector;
    use switchy_database::postgres::postgres::PostgresDatabase;

    let mut config = tokio_postgres::Config::new();
    config
        .host(&creds.host)
        .dbname(&creds.name)
        .user(&creds.user);

    if let Some(port) = creds.port {
        config.port(port);
    }

    if let Some(db_password) = &creds.password {
        config.password(db_password);
    }

    let mut builder = native_tls::TlsConnector::builder();

    match creds.host.to_lowercase().as_str() {
        "localhost" | "127.0.0.1" | "0.0.0.0" => {
            builder.danger_accept_invalid_hostnames(true);
        }
        _ => {}
    }

    let connector = MakeTlsConnector::new(builder.build()?);

    let manager_config = ManagerConfig {
        recycling_method: RecyclingMethod::Fast,
    };
    let manager = deadpool_postgres::Manager::from_config(config, connector, manager_config);
    let pool = deadpool_postgres::Pool::builder(manager)
        .max_size(5)
        .build()?;

    Ok(Box::new(PostgresDatabase::new(pool)))
}

/// Initializes a `PostgreSQL` database connection using tokio-postgres with `OpenSSL`.
///
/// Creates a connection pool with 5 connections. For localhost connections,
/// disables certificate verification to support self-signed certificates.
///
/// # Errors
///
/// * Propagates [`InitDatabaseError::OpenSsl`] when building the OpenSSL TLS connector fails
/// * Propagates [`InitDatabaseError::Postgres`] when configuring the `PostgreSQL` manager fails
/// * Propagates [`InitDatabaseError::DeadpoolBuildError`] when building the connection pool fails
#[cfg(all(feature = "postgres-openssl", feature = "postgres-raw"))]
#[allow(unused, clippy::unused_async)]
pub async fn init_postgres_raw_openssl(
    creds: Credentials,
) -> Result<Box<dyn Database>, InitDatabaseError> {
    use deadpool_postgres::{ManagerConfig, RecyclingMethod};
    use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
    use postgres_openssl::MakeTlsConnector;
    use switchy_database::postgres::postgres::PostgresDatabase;

    let mut config = tokio_postgres::Config::new();
    config
        .host(&creds.host)
        .dbname(&creds.name)
        .user(&creds.user);

    if let Some(port) = creds.port {
        config.port(port);
    }

    if let Some(db_password) = &creds.password {
        config.password(db_password);
    }

    let mut builder = SslConnector::builder(SslMethod::tls())?;

    match creds.host.to_lowercase().as_str() {
        "localhost" | "127.0.0.1" | "0.0.0.0" => {
            builder.set_verify(SslVerifyMode::NONE);
        }
        _ => {}
    }

    let connector = MakeTlsConnector::new(builder.build());

    let manager_config = ManagerConfig {
        recycling_method: RecyclingMethod::Fast,
    };
    let manager = deadpool_postgres::Manager::from_config(config, connector, manager_config);
    let pool = deadpool_postgres::Pool::builder(manager)
        .max_size(5)
        .build()?;

    Ok(Box::new(PostgresDatabase::new(pool)))
}

/// Initializes a `PostgreSQL` database connection using tokio-postgres without TLS.
///
/// Creates a connection pool with 5 connections using the provided credentials.
///
/// # Errors
///
/// * Propagates [`InitDatabaseError::Postgres`] when configuring the `PostgreSQL` manager fails
/// * Propagates [`InitDatabaseError::DeadpoolBuildError`] when building the connection pool fails
#[cfg(feature = "postgres-raw")]
#[allow(unused, clippy::unused_async)]
pub async fn init_postgres_raw_no_tls(
    creds: Credentials,
) -> Result<Box<dyn Database>, InitDatabaseError> {
    use deadpool_postgres::{ManagerConfig, RecyclingMethod};
    use switchy_database::postgres::postgres::PostgresDatabase;

    let mut config = tokio_postgres::Config::new();
    config
        .host(&creds.host)
        .dbname(&creds.name)
        .user(&creds.user);

    if let Some(port) = creds.port {
        config.port(port);
    }

    if let Some(db_password) = &creds.password {
        config.password(db_password);
    }

    let connector = tokio_postgres::NoTls;

    let manager_config = ManagerConfig {
        recycling_method: RecyclingMethod::Fast,
    };
    let manager = deadpool_postgres::Manager::from_config(config, connector, manager_config);
    let pool = deadpool_postgres::Pool::builder(manager)
        .max_size(5)
        .build()?;

    Ok(Box::new(PostgresDatabase::new(pool)))
}

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

    #[test_log::test]
    fn test_credentials_from_url_postgres_with_password() {
        let url = "postgres://user:pass123@localhost:5432/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "localhost");
        assert_eq!(creds.port(), Some(5432));
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "user");
        assert_eq!(creds.password(), Some("pass123"));
    }

    #[test_log::test]
    fn test_credentials_from_url_postgres_without_password() {
        let url = "postgres://user@localhost:5432/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "localhost");
        assert_eq!(creds.port(), Some(5432));
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "user");
        assert_eq!(creds.password(), None);
    }

    #[test_log::test]
    fn test_credentials_from_url_postgresql_scheme() {
        let url = "postgresql://user:pass@host:1234/database";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "host");
        assert_eq!(creds.port(), Some(1234));
        assert_eq!(creds.name(), "database");
        assert_eq!(creds.user(), "user");
        assert_eq!(creds.password(), Some("pass"));
    }

    #[test_log::test]
    fn test_credentials_from_url_mysql_scheme() {
        let url = "mysql://dbuser:dbpass@dbhost:3306/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "dbhost");
        assert_eq!(creds.port(), Some(3306));
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "dbuser");
        assert_eq!(creds.password(), Some("dbpass"));
    }

    #[test_log::test]
    fn test_credentials_from_url_with_special_chars_in_password() {
        let url = "postgres://user:p@ss:w0rd!@localhost:5432/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "localhost");
        assert_eq!(creds.port(), Some(5432));
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "user");
        assert_eq!(creds.password(), Some("p@ss:w0rd!"));
    }

    #[test_log::test]
    fn test_credentials_from_url_with_trailing_whitespace() {
        let url = "  postgres://user:pass@localhost:5432/mydb  ";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "localhost");
        assert_eq!(creds.port(), Some(5432));
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "user");
        assert_eq!(creds.password(), Some("pass"));
    }

    #[test_log::test]
    fn test_credentials_from_url_invalid_no_scheme_separator() {
        let url = "postgresuser:pass@localhost:5432/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(result, Err(CredentialsParseError::InvalidUrl)));
    }

    #[test_log::test]
    fn test_credentials_from_url_missing_database() {
        let url = "postgres://user:pass@localhost:5432/";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::MissingDatabase)
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_missing_database_no_slash() {
        let url = "postgres://user:pass@localhost:5432";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::MissingDatabase)
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_missing_host() {
        let url = "postgres://user:pass@/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(result, Err(CredentialsParseError::MissingHost)));
    }

    #[test_log::test]
    fn test_credentials_from_url_missing_username() {
        let url = "postgres://@localhost:5432/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::MissingUsername)
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_missing_username_with_password() {
        let url = "postgres://:pass@localhost:5432/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::MissingUsername)
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_missing_auth() {
        let url = "postgres://localhost:5432/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::MissingUsername)
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_unsupported_scheme() {
        let url = "mongodb://user:pass@localhost:27017/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::UnsupportedScheme(_))
        ));

        if let Err(CredentialsParseError::UnsupportedScheme(scheme)) = result {
            assert_eq!(scheme, "mongodb");
        }
    }

    #[test_log::test]
    fn test_credentials_from_url_sqlite_scheme_unsupported() {
        let url = "sqlite:///path/to/db.sqlite";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::UnsupportedScheme(_))
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_http_scheme_unsupported() {
        let url = "http://user:pass@localhost/mydb";
        let result = Credentials::from_url(url);

        assert!(matches!(
            result,
            Err(CredentialsParseError::UnsupportedScheme(_))
        ));
    }

    #[test_log::test]
    fn test_credentials_from_url_complex_host_with_domain() {
        let url = "postgres://user:pass@db.example.com:5432/production";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "db.example.com");
        assert_eq!(creds.port(), Some(5432));
        assert_eq!(creds.name(), "production");
        assert_eq!(creds.user(), "user");
        assert_eq!(creds.password(), Some("pass"));
    }

    #[test_log::test]
    fn test_credentials_from_url_ipv4_host() {
        let url = "postgres://user:pass@192.168.1.100:5432/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "192.168.1.100");
        assert_eq!(creds.port(), Some(5432));
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "user");
    }

    #[test_log::test]
    fn test_credentials_from_url_localhost_without_port() {
        let url = "postgres://user:pass@localhost/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.host(), "localhost");
        assert_eq!(creds.port(), None);
        assert_eq!(creds.name(), "mydb");
        assert_eq!(creds.user(), "user");
    }

    #[test_log::test]
    fn test_credentials_from_url_database_with_underscore() {
        let url = "postgres://user:pass@localhost:5432/my_database_name";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.name(), "my_database_name");
    }

    #[test_log::test]
    fn test_credentials_from_url_username_with_underscore() {
        let url = "postgres://db_user:pass@localhost:5432/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.user(), "db_user");
    }

    #[test_log::test]
    fn test_credentials_from_url_empty_password() {
        let url = "postgres://user:@localhost:5432/mydb";
        let creds = Credentials::from_url(url).expect("Failed to parse URL");

        assert_eq!(creds.password(), Some(""));
    }

    #[cfg(feature = "duckdb")]
    #[test_log::test]
    fn test_parse_duckdb_mode_values() {
        assert_eq!(
            parse_duckdb_mode("deterministic").expect("mode should parse"),
            switchy_database::duckdb::DuckDbMode::Deterministic
        );
        assert_eq!(
            parse_duckdb_mode("pooled").expect("mode should parse"),
            switchy_database::duckdb::DuckDbMode::Pooled
        );
        assert_eq!(
            parse_duckdb_mode("POOLED").expect("mode should parse case-insensitively"),
            switchy_database::duckdb::DuckDbMode::Pooled
        );
    }

    #[cfg(feature = "duckdb")]
    #[test_log::test]
    fn test_parse_duckdb_mode_invalid() {
        let result = parse_duckdb_mode("fast");
        assert!(matches!(result, Err(InitDuckDbError::InvalidConfig(_))));
    }

    #[cfg(feature = "duckdb")]
    #[test_log::test]
    fn test_parse_duckdb_consistency_values() {
        assert_eq!(
            parse_duckdb_consistency("strict").expect("consistency should parse"),
            switchy_database::duckdb::DuckDbConsistency::Strict
        );
        assert_eq!(
            parse_duckdb_consistency("relaxed").expect("consistency should parse"),
            switchy_database::duckdb::DuckDbConsistency::Relaxed
        );
        assert_eq!(
            parse_duckdb_consistency("RELAXED")
                .expect("consistency should parse case-insensitively"),
            switchy_database::duckdb::DuckDbConsistency::Relaxed
        );
    }

    #[cfg(feature = "duckdb")]
    #[test_log::test]
    fn test_parse_duckdb_consistency_invalid() {
        let result = parse_duckdb_consistency("eventual");
        assert!(matches!(result, Err(InitDuckDbError::InvalidConfig(_))));
    }
}