drizzle-cli 0.4.1

Command-line interface for drizzle-rs migrations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! Command-line flags that override `drizzle.config.toml` for one run
//! (connection settings and filters), and the `resolve_*` functions that
//! merge them with the config.

use std::path::PathBuf;

use crate::config::{
    Credentials, DatabaseConfig, Dialect, Driver, Extension, Filter, MySQLCreds, MySQLSslMode,
    PostgresCreds, PostgresSslMode,
};
use crate::error::CliError;

/// CLI overrides for database connection credentials.
///
/// Each field maps to a top-level `--{name}` flag. Embedded into commands
/// that talk to a live database via `#[command(flatten)]` so the connection
/// surface is defined once and reused across `push`, `introspect`/`pull`.
#[derive(clap::Args, Clone, Default)]
pub struct ConnectionOverrides {
    /// Rust database driver
    #[arg(long)]
    pub driver: Option<Driver>,

    /// Database connection URL
    #[arg(long)]
    pub url: Option<String>,

    /// Database host
    #[arg(long)]
    pub host: Option<String>,

    /// Database port
    #[arg(long)]
    pub port: Option<u16>,

    /// Database user
    #[arg(long)]
    pub user: Option<String>,

    /// Database password
    #[arg(long)]
    pub password: Option<String>,

    /// Database name
    #[arg(long)]
    pub database: Option<String>,

    /// SSL mode (true/false or require/prefer/verify-full/disable)
    #[arg(long)]
    pub ssl: Option<String>,

    /// Turso auth token
    #[arg(long = "authToken", alias = "auth-token")]
    pub auth_token: Option<String>,
}

impl std::fmt::Debug for ConnectionOverrides {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectionOverrides")
            .field("driver", &self.driver)
            .field("url", &self.url.as_ref().map(|_| "[REDACTED]"))
            .field("host", &self.host)
            .field("port", &self.port)
            .field("user", &self.user)
            .field("password", &self.password.as_ref().map(|_| "[REDACTED]"))
            .field("database", &self.database)
            .field("ssl", &self.ssl)
            .field(
                "auth_token",
                &self.auth_token.as_ref().map(|_| "[REDACTED]"),
            )
            .finish()
    }
}

/// CLI overrides for snapshot filters (tables/schemas/extensions).
///
/// Embedded into commands that read or push a snapshot via
/// `#[command(flatten)]`. Single source of truth for the filter surface.
#[derive(clap::Args, Debug, Clone, Default)]
pub struct FilterArgs {
    /// Table name filters
    #[arg(long = "tablesFilter", value_delimiter = ',')]
    pub tables_filter: Option<Vec<String>>,

    /// Schema name filters
    #[arg(long = "schemaFilters", alias = "schemaFilter", value_delimiter = ',')]
    pub schema_filters: Option<Vec<String>>,

    /// Extension filters (e.g. postgis)
    #[arg(long = "extensionsFilters", value_delimiter = ',', value_parser = parse_extension_arg)]
    pub extensions_filters: Option<Vec<Extension>>,
}

fn parse_extension_arg(s: &str) -> Result<Extension, String> {
    s.parse()
}

impl ConnectionOverrides {
    /// Returns `true` if any credential flag is set (`--driver` does not
    /// count).
    #[must_use]
    pub const fn has_any(&self) -> bool {
        self.url.is_some()
            || self.host.is_some()
            || self.port.is_some()
            || self.user.is_some()
            || self.password.is_some()
            || self.database.is_some()
            || self.ssl.is_some()
            || self.auth_token.is_some()
    }
}

/// A live database target: dialect, driver, and credentials, checked to fit
/// together.
///
/// Keeping the driver beside the credentials means the command and the code
/// that connects always agree on which driver to use.
#[derive(Debug, Clone)]
pub struct ResolvedConnection {
    /// Effective dialect.
    pub dialect: Dialect,
    /// Driver to connect with.
    pub driver: Driver,
    /// Resolved credentials.
    pub credentials: Credentials,
}

/// Returns `--dialect` if given, else the config's dialect.
#[must_use]
pub fn resolve_dialect(db: &DatabaseConfig, override_dialect: Option<Dialect>) -> Dialect {
    override_dialect.unwrap_or(db.dialect)
}

/// Returns `driver_override`, else the config's driver (`None` if neither is
/// set), after checking it is valid for `dialect`.
///
/// # Errors
///
/// Returns [`CliError`] if the chosen driver is not valid for `dialect` (for
/// example `rusqlite` with `postgresql`).
pub fn resolve_driver(
    db: &DatabaseConfig,
    dialect: Dialect,
    driver_override: Option<Driver>,
) -> Result<Option<Driver>, CliError> {
    let driver = driver_override.or(db.driver);
    if let Some(driver) = driver
        && !driver.is_valid_for(dialect)
    {
        return Err(CliError::Other(format!(
            "driver '{driver}' invalid for {dialect} dialect"
        )));
    }
    Ok(driver)
}

/// Builds credentials from the connection flags, or returns the config's
/// credentials when no credential flag is set.
///
/// Flags replace the config's `dbCredentials` entirely; they are not merged
/// field by field.
///
/// # Errors
///
/// Returns [`CliError`] if `dialect` differs from the config's dialect but no
/// credential flags are given, a flag does not apply to the dialect, a
/// required flag (such as `--url` for SQLite) is missing, `--ssl` is invalid,
/// or resolving the config's credentials fails (for example a missing
/// environment variable).
pub fn resolve_credentials(
    db: &DatabaseConfig,
    dialect: Dialect,
    overrides: &ConnectionOverrides,
) -> Result<Option<Credentials>, CliError> {
    if !overrides.has_any() {
        if dialect != db.dialect {
            return Err(CliError::Other(format!(
                "--dialect={dialect} requires matching credential flags (--url/--host/--database/etc)"
            )));
        }
        return db.credentials().map_err(Into::into);
    }

    let creds = match dialect {
        Dialect::Sqlite => {
            if overrides.host.is_some()
                || overrides.port.is_some()
                || overrides.user.is_some()
                || overrides.password.is_some()
                || overrides.database.is_some()
                || overrides.ssl.is_some()
                || overrides.auth_token.is_some()
            {
                return Err(CliError::Other(
                    "sqlite credentials only support --url for local database path".into(),
                ));
            }

            let path = overrides
                .url
                .clone()
                .ok_or_else(|| CliError::Other("sqlite requires --url".into()))?;

            Credentials::Sqlite {
                path: path.into_boxed_str(),
            }
        }
        Dialect::Turso => {
            if overrides.host.is_some()
                || overrides.port.is_some()
                || overrides.user.is_some()
                || overrides.password.is_some()
                || overrides.database.is_some()
                || overrides.ssl.is_some()
            {
                return Err(CliError::Other(
                    "turso credentials support --url and optional --authToken".into(),
                ));
            }

            let url = overrides
                .url
                .clone()
                .ok_or_else(|| CliError::Other("turso requires --url".into()))?;

            Credentials::Turso {
                url: url.into_boxed_str(),
                auth_token: overrides.auth_token.clone().map(String::into_boxed_str),
            }
        }
        Dialect::Postgresql => {
            if overrides.auth_token.is_some() {
                return Err(CliError::Other(
                    "postgresql does not support --authToken (use --password or --url)".into(),
                ));
            }

            if let Some(url) = overrides.url.clone() {
                if overrides.host.is_some()
                    || overrides.port.is_some()
                    || overrides.user.is_some()
                    || overrides.password.is_some()
                    || overrides.database.is_some()
                    || overrides.ssl.is_some()
                {
                    return Err(CliError::Other(
                        "postgresql credentials: use either --url OR --host/--database[/--port/...], not both"
                            .into(),
                    ));
                }

                Credentials::Postgres(PostgresCreds::Url(url.into_boxed_str()))
            } else {
                let host = overrides.host.clone().ok_or_else(|| {
                    CliError::Other("postgresql host credentials require --host".into())
                })?;
                let database = overrides.database.clone().ok_or_else(|| {
                    CliError::Other("postgresql host credentials require --database".into())
                })?;

                Credentials::Postgres(PostgresCreds::Host {
                    host: host.into_boxed_str(),
                    port: overrides.port.unwrap_or(5432),
                    user: overrides.user.clone().map(String::into_boxed_str),
                    password: overrides.password.clone().map(String::into_boxed_str),
                    database: database.into_boxed_str(),
                    ssl: parse_ssl_override(overrides.ssl.as_deref())?
                        .unwrap_or(PostgresSslMode::Disable),
                })
            }
        }
        Dialect::Mysql => {
            if overrides.auth_token.is_some() {
                return Err(CliError::Other(
                    "mysql does not support --authToken (use --password or --url)".into(),
                ));
            }

            if let Some(url) = overrides.url.clone() {
                if overrides.host.is_some()
                    || overrides.port.is_some()
                    || overrides.user.is_some()
                    || overrides.password.is_some()
                    || overrides.database.is_some()
                    || overrides.ssl.is_some()
                {
                    return Err(CliError::Other(
                        "mysql credentials: use either --url OR --host/--database[/--port/...], not both"
                            .into(),
                    ));
                }
                if !url.starts_with("mysql://") {
                    return Err(CliError::Other(
                        "mysql --url must start with mysql://".into(),
                    ));
                }
                Credentials::MySQL(MySQLCreds::Url(url.into_boxed_str()))
            } else {
                let host = overrides.host.clone().ok_or_else(|| {
                    CliError::Other("mysql host credentials require --host".into())
                })?;
                let database = overrides.database.clone().ok_or_else(|| {
                    CliError::Other("mysql host credentials require --database".into())
                })?;

                Credentials::MySQL(MySQLCreds::Host {
                    host: host.into_boxed_str(),
                    port: overrides.port.unwrap_or(3306),
                    user: overrides.user.clone().map(String::into_boxed_str),
                    password: overrides.password.clone().map(String::into_boxed_str),
                    database: database.into_boxed_str(),
                    ssl: parse_mysql_ssl_override(overrides.ssl.as_deref())?
                        .unwrap_or(MySQLSslMode::Disable),
                })
            }
        }
    };

    Ok(Some(creds))
}

/// Resolves credentials (see [`resolve_credentials`]) and picks the driver,
/// or returns `None` when there are no credentials.
///
/// The driver is `--driver`, else the config's driver (when the dialect is
/// not overridden), else a default for the credentials: `rusqlite`,
/// `d1-http`, `libsql` for a local Turso URL or `turso` for a remote one,
/// `aws-data-api`, `postgres-sync`, or `mysql-sync`.
///
/// # Errors
///
/// Returns [`CliError`] if resolving credentials fails or the driver does not
/// fit the dialect or the credentials.
pub fn resolve_connection(
    db: &DatabaseConfig,
    dialect: Dialect,
    overrides: &ConnectionOverrides,
) -> Result<Option<ResolvedConnection>, CliError> {
    let credentials = resolve_credentials(db, dialect, overrides)?;
    let Some(credentials) = credentials else {
        return Ok(None);
    };
    let configured_driver = overrides
        .driver
        .or_else(|| (dialect == db.dialect).then_some(db.driver).flatten());
    let driver = configured_driver.unwrap_or_else(|| default_driver(dialect, &credentials));
    if !driver.is_valid_for(dialect) {
        return Err(CliError::Other(format!(
            "driver '{driver}' invalid for {dialect} dialect"
        )));
    }
    if !driver_accepts_credentials(driver, &credentials) {
        return Err(CliError::Other(format!(
            "driver '{driver}' is incompatible with the resolved {dialect} credentials"
        )));
    }
    Ok(Some(ResolvedConnection {
        dialect,
        driver,
        credentials,
    }))
}

fn driver_accepts_credentials(driver: Driver, credentials: &Credentials) -> bool {
    matches!(
        (driver, credentials),
        (Driver::Rusqlite, Credentials::Sqlite { .. })
            | (Driver::Libsql | Driver::Turso, Credentials::Turso { .. })
            | (
                Driver::PostgresSync | Driver::TokioPostgres,
                Credentials::Postgres(_)
            )
            | (
                Driver::MysqlSync | Driver::MysqlAsync,
                Credentials::MySQL(_)
            )
            | (Driver::D1Http, Credentials::D1 { .. })
            | (Driver::AwsDataApi, Credentials::AwsDataApi { .. })
    )
}

fn default_driver(dialect: Dialect, credentials: &Credentials) -> Driver {
    match (dialect, credentials) {
        (Dialect::Sqlite, Credentials::D1 { .. }) => Driver::D1Http,
        (Dialect::Postgresql, Credentials::AwsDataApi { .. }) => Driver::AwsDataApi,
        (Dialect::Sqlite, _) => Driver::Rusqlite,
        (Dialect::Turso, Credentials::Turso { url, .. }) => {
            if is_local_libsql_url(url) {
                Driver::Libsql
            } else {
                Driver::Turso
            }
        }
        (Dialect::Postgresql, _) => Driver::PostgresSync,
        (Dialect::Mysql, _) => Driver::MysqlSync,
        // Config validation prevents these mismatches. Keep a deterministic
        // fallback so this remains total for hand-built values in tests.
        (Dialect::Turso, _) => Driver::Turso,
    }
}

fn is_local_libsql_url(url: &str) -> bool {
    !url.starts_with("libsql://") && !url.starts_with("http://") && !url.starts_with("https://")
}

fn parse_ssl_override(ssl: Option<&str>) -> Result<Option<PostgresSslMode>, CliError> {
    let Some(raw) = ssl else {
        return Ok(None);
    };

    PostgresSslMode::parse(raw).map(Some).map_err(|_| {
        CliError::Other(format!(
            "invalid --ssl value '{raw}'; expected one of: true,false,require,allow,prefer,verify-full,verify-ca,disable"
        ))
    })
}

fn parse_mysql_ssl_override(ssl: Option<&str>) -> Result<Option<MySQLSslMode>, CliError> {
    let Some(raw) = ssl else {
        return Ok(None);
    };

    MySQLSslMode::parse(raw).map(Some).map_err(|_| {
        CliError::Other(format!(
            "invalid --ssl value '{raw}' for mysql; expected one of: true,false,required,verify-ca,verify-identity,disable"
        ))
    })
}

/// Returns the `--tablesFilter`-style flag values if given (an empty flag
/// clears the filter), else the config's patterns.
#[must_use]
pub fn resolve_filter_list(cli: Option<&[String]>, config: Option<&Filter>) -> Option<Vec<String>> {
    if let Some(values) = cli {
        if values.is_empty() {
            return None;
        }
        return Some(values.to_vec());
    }

    config.map(|f| f.iter().map(ToOwned::to_owned).collect())
}

/// Like [`resolve_filter_list`] for `schemaFilter`, but PostgreSQL only
/// (`None` otherwise) and defaulting to `["public"]` when neither the flag nor
/// the config sets it.
#[must_use]
pub fn resolve_schema_filters(
    dialect: Dialect,
    cli: Option<&[String]>,
    config: Option<&Filter>,
) -> Option<Vec<String>> {
    if dialect != Dialect::Postgresql {
        return None;
    }
    let resolved = resolve_filter_list(cli, config);
    if resolved.is_some() {
        return resolved;
    }

    if matches!(dialect, Dialect::Postgresql) {
        Some(vec!["public".to_string()])
    } else {
        None
    }
}

/// Returns the `--extensionsFilters` values if given (an empty flag clears
/// the filter), else the config's list; always `None` outside PostgreSQL.
#[must_use]
pub fn resolve_extensions_filter(
    dialect: Dialect,
    cli: Option<&[Extension]>,
    config: Option<&[Extension]>,
) -> Option<Vec<Extension>> {
    if dialect != Dialect::Postgresql {
        return None;
    }
    if let Some(values) = cli {
        if values.is_empty() {
            return None;
        }
        return Some(values.to_vec());
    }

    config.map(<[Extension]>::to_vec)
}

/// Returns the `--schema` override joined for display, else the config's
/// schema paths.
#[must_use]
pub fn resolve_schema_display(db: &DatabaseConfig, schema_override: Option<&[String]>) -> String {
    match schema_override {
        Some(v) if !v.is_empty() => v.join(", "),
        _ => db.schema_display(),
    }
}

/// Resolves the schema files a command reads: the `--schema` override (paths
/// relative to the current directory) if given, else the config's `schema`
/// (relative to the config file).
///
/// # Errors
///
/// Returns [`CliError`] if a non-empty override resolves to zero files, if a
/// glob pattern is invalid, or if expanding the configured schema patterns
/// fails.
pub fn resolve_schema_files(
    db: &DatabaseConfig,
    schema_override: Option<&[String]>,
) -> Result<Vec<PathBuf>, CliError> {
    let Some(schema_patterns) = schema_override else {
        return db.schema_files().map_err(Into::into);
    };

    if schema_patterns.is_empty() {
        return Err(CliError::NoSchemaFiles("(empty schema override)".into()));
    }

    let files = crate::config::resolve_schema_patterns(schema_patterns.iter().map(String::as_str))?;

    if files.is_empty() {
        return Err(CliError::NoSchemaFiles(
            schema_patterns
                .iter()
                .map(std::string::String::as_str)
                .collect::<Vec<_>>()
                .join(", "),
        ));
    }

    Ok(files)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn load_db(config_toml: &str) -> (TempDir, DatabaseConfig) {
        let dir = TempDir::new().expect("temp dir");
        let path = dir.path().join("drizzle.config.toml");
        std::fs::write(&path, config_toml).expect("write config");
        let config = Config::load_from(&path).expect("load config");
        let db = config.default_database().expect("default db").clone();
        (dir, db)
    }

    #[test]
    fn resolve_filter_list_prefers_cli_values() {
        let config = Filter::Many(vec!["from_config".to_string()]);
        let cli = vec!["from_cli".to_string()];

        let resolved = resolve_filter_list(Some(&cli), Some(&config));
        assert_eq!(resolved, Some(vec!["from_cli".to_string()]));
    }

    #[test]
    fn resolve_filter_list_uses_config_when_cli_missing() {
        let config = Filter::Many(vec!["public".to_string(), "dev".to_string()]);
        let resolved = resolve_filter_list(None, Some(&config));
        assert_eq!(
            resolved,
            Some(vec!["public".to_string(), "dev".to_string()])
        );
    }

    #[test]
    fn resolve_schema_filters_defaults_to_public_for_postgres() {
        let resolved = resolve_schema_filters(Dialect::Postgresql, None, None);
        assert_eq!(resolved, Some(vec!["public".to_string()]));
    }

    #[test]
    fn resolve_schema_filters_does_not_default_for_sqlite() {
        let resolved = resolve_schema_filters(Dialect::Sqlite, None, None);
        assert_eq!(resolved, None);
    }

    #[test]
    fn non_postgres_filters_are_ignored_after_cli_warning() {
        let schemas = vec!["public".to_string()];
        let extensions = vec![Extension::Postgis];
        for dialect in [Dialect::Sqlite, Dialect::Turso, Dialect::Mysql] {
            assert_eq!(resolve_schema_filters(dialect, Some(&schemas), None), None);
            assert_eq!(
                resolve_extensions_filter(dialect, Some(&extensions), None),
                None
            );
        }
    }

    #[test]
    fn resolve_extensions_filter_prefers_cli_values() {
        let cli = vec![Extension::Postgis];
        let config = vec![];

        let resolved = resolve_extensions_filter(Dialect::Postgresql, Some(&cli), Some(&config));
        assert_eq!(resolved, Some(vec![Extension::Postgis]));
    }

    #[test]
    fn resolve_driver_rejects_invalid_override() {
        let (_dir, db) = load_db(
            r#"
dialect = "sqlite"
schema = "src/schema.rs"
"#,
        );

        let err = resolve_driver(&db, Dialect::Sqlite, Some(Driver::TokioPostgres))
            .expect_err("driver should be rejected");
        assert_eq!(
            err.to_string(),
            "driver 'tokio-postgres' invalid for sqlite dialect"
        );
    }

    #[test]
    fn resolve_credentials_requires_overrides_for_dialect_switch() {
        let (_dir, db) = load_db(
            r#"
dialect = "sqlite"
[dbCredentials]
url = "./dev.db"
"#,
        );

        let err = resolve_credentials(&db, Dialect::Postgresql, &ConnectionOverrides::default())
            .expect_err("dialect switch should require explicit credentials");
        assert_eq!(
            err.to_string(),
            "--dialect=postgresql requires matching credential flags (--url/--host/--database/etc)"
        );
    }

    #[test]
    fn resolve_credentials_sqlite_rejects_host_fields() {
        let (_dir, db) = load_db(
            r#"
dialect = "sqlite"
"#,
        );

        let overrides = ConnectionOverrides {
            host: Some("localhost".to_string()),
            ..Default::default()
        };

        let err = resolve_credentials(&db, Dialect::Sqlite, &overrides)
            .expect_err("sqlite should reject host-style credentials");
        assert_eq!(
            err.to_string(),
            "sqlite credentials only support --url for local database path"
        );
    }

    #[test]
    fn resolve_credentials_postgres_rejects_mixed_url_and_host_fields() {
        let (_dir, db) = load_db(
            r#"
dialect = "postgresql"
"#,
        );

        let overrides = ConnectionOverrides {
            url: Some("postgres://u:p@localhost:5432/db".to_string()),
            host: Some("localhost".to_string()),
            database: Some("db".to_string()),
            ..Default::default()
        };

        let err = resolve_credentials(&db, Dialect::Postgresql, &overrides)
            .expect_err("postgres should reject mixed credentials");
        assert_eq!(
            err.to_string(),
            "postgresql credentials: use either --url OR --host/--database[/--port/...], not both"
        );
    }

    #[test]
    fn resolve_credentials_postgres_requires_database_for_host_mode() {
        let (_dir, db) = load_db(
            r#"
dialect = "postgresql"
"#,
        );

        let overrides = ConnectionOverrides {
            host: Some("localhost".to_string()),
            ..Default::default()
        };

        let err = resolve_credentials(&db, Dialect::Postgresql, &overrides)
            .expect_err("postgres host credentials require database");
        assert_eq!(
            err.to_string(),
            "postgresql host credentials require --database"
        );
    }

    #[test]
    fn resolve_credentials_turso_accepts_url_with_optional_token() {
        let (_dir, db) = load_db(
            r#"
dialect = "turso"
"#,
        );

        let overrides = ConnectionOverrides {
            url: Some("libsql://example.turso.io".to_string()),
            auth_token: Some("secret".to_string()),
            ..Default::default()
        };

        let creds = resolve_credentials(&db, Dialect::Turso, &overrides)
            .expect("resolve creds")
            .expect("some creds");

        match creds {
            Credentials::Turso { url, auth_token } => {
                assert_eq!(url.as_ref(), "libsql://example.turso.io");
                assert_eq!(auth_token.as_deref(), Some("secret"));
            }
            _ => panic!("expected turso credentials"),
        }
    }

    #[test]
    fn resolve_credentials_postgres_host_mode_accepts_ssl_modes() {
        let (_dir, db) = load_db(
            r#"
dialect = "postgresql"
"#,
        );

        let require_ssl = ConnectionOverrides {
            host: Some("localhost".to_string()),
            database: Some("db".to_string()),
            ssl: Some("require".to_string()),
            ..Default::default()
        };
        let creds = resolve_credentials(&db, Dialect::Postgresql, &require_ssl)
            .expect("resolve")
            .expect("creds");
        match creds {
            Credentials::Postgres(PostgresCreds::Host { ssl, .. }) => {
                assert_eq!(ssl, PostgresSslMode::Require)
            }
            _ => panic!("expected postgres host creds"),
        }

        let disable_ssl = ConnectionOverrides {
            host: Some("localhost".to_string()),
            database: Some("db".to_string()),
            ssl: Some("disable".to_string()),
            ..Default::default()
        };
        let creds = resolve_credentials(&db, Dialect::Postgresql, &disable_ssl)
            .expect("resolve")
            .expect("creds");
        match creds {
            Credentials::Postgres(PostgresCreds::Host { ssl, .. }) => {
                assert_eq!(ssl, PostgresSslMode::Disable)
            }
            _ => panic!("expected postgres host creds"),
        }
    }

    #[test]
    fn resolve_credentials_postgres_host_mode_rejects_invalid_ssl_value() {
        let (_dir, db) = load_db(
            r#"
dialect = "postgresql"
"#,
        );

        let overrides = ConnectionOverrides {
            host: Some("localhost".to_string()),
            database: Some("db".to_string()),
            ssl: Some("maybe".to_string()),
            ..Default::default()
        };

        let err = resolve_credentials(&db, Dialect::Postgresql, &overrides)
            .expect_err("invalid ssl should fail");
        assert_eq!(
            err.to_string(),
            "invalid --ssl value 'maybe'; expected one of: true,false,require,allow,prefer,verify-full,verify-ca,disable"
        );
    }

    #[test]
    fn resolve_connection_preserves_explicit_mysql_async_driver() {
        let (_dir, db) = load_db(
            r#"
dialect = "mysql"
driver = "mysql-sync"
"#,
        );
        let overrides = ConnectionOverrides {
            driver: Some(Driver::MysqlAsync),
            host: Some("localhost".to_string()),
            database: Some("app".to_string()),
            ssl: Some("verify-ca".to_string()),
            ..Default::default()
        };
        let target = resolve_connection(&db, Dialect::Mysql, &overrides)
            .expect("resolve")
            .expect("target");
        assert_eq!(target.driver, Driver::MysqlAsync);
        assert_eq!(target.dialect, Dialect::Mysql);
        match target.credentials {
            Credentials::MySQL(MySQLCreds::Host { port, ssl, .. }) => {
                assert_eq!(port, 3306);
                assert_eq!(ssl, MySQLSslMode::VerifyCa);
            }
            other => panic!("unexpected credentials: {other:?}"),
        }
    }

    #[test]
    fn resolve_connection_defaults_mysql_to_sync() {
        let (_dir, db) = load_db(
            r#"
dialect = "mysql"
[dbCredentials]
url = "mysql://localhost/app"
"#,
        );
        let target = resolve_connection(&db, Dialect::Mysql, &ConnectionOverrides::default())
            .expect("resolve")
            .expect("target");
        assert_eq!(target.driver, Driver::MysqlSync);
    }

    #[test]
    fn resolve_connection_rejects_driver_with_wrong_credential_shape() {
        let (_dir, db) = load_db(
            r#"
dialect = "postgresql"
[dbCredentials]
url = "postgres://localhost/app"
"#,
        );
        let overrides = ConnectionOverrides {
            driver: Some(Driver::AwsDataApi),
            ..Default::default()
        };

        let error = resolve_connection(&db, Dialect::Postgresql, &overrides)
            .expect_err("AWS adapter cannot consume TCP credentials");
        assert!(error.to_string().contains("incompatible"));
    }

    #[test]
    fn dialect_switch_does_not_reuse_original_driver() {
        let (_dir, db) = load_db(
            r#"
dialect = "sqlite"
driver = "rusqlite"
"#,
        );
        let overrides = ConnectionOverrides {
            url: Some("mysql://localhost/app".to_string()),
            ..Default::default()
        };
        let target = resolve_connection(&db, Dialect::Mysql, &overrides)
            .expect("resolve switch")
            .expect("target");
        assert_eq!(target.driver, Driver::MysqlSync);
    }

    #[test]
    fn mysql_override_rejects_postgres_url_and_auth_token() {
        let (_dir, db) = load_db("dialect = \"mysql\"");
        let bad_url = ConnectionOverrides {
            url: Some("postgres://localhost/app".to_string()),
            ..Default::default()
        };
        assert!(
            resolve_credentials(&db, Dialect::Mysql, &bad_url)
                .expect_err("wrong scheme")
                .to_string()
                .contains("mysql://")
        );

        let auth_token = ConnectionOverrides {
            host: Some("localhost".to_string()),
            database: Some("app".to_string()),
            auth_token: Some("unsupported".to_string()),
            ..Default::default()
        };
        assert!(
            resolve_credentials(&db, Dialect::Mysql, &auth_token)
                .expect_err("auth token")
                .to_string()
                .contains("does not support --authToken")
        );
    }

    #[test]
    fn resolve_schema_filters_defaults_to_public_in_multi_db_postgres() {
        let dir = TempDir::new().expect("temp dir");
        let path = dir.path().join("drizzle.config.toml");
        std::fs::write(
            &path,
            r#"
[databases.pg]
dialect = "postgresql"

[databases.pg.dbCredentials]
url = "postgres://localhost/db"

[databases.sqlite]
dialect = "sqlite"

[databases.sqlite.dbCredentials]
url = "./dev.db"
"#,
        )
        .expect("write config");

        let config = Config::load_from(&path).expect("load config");
        let db = config.database(Some("pg")).expect("pg db");

        let resolved = resolve_schema_filters(Dialect::Postgresql, None, db.schema_filter.as_ref());
        assert_eq!(resolved, Some(vec!["public".to_string()]));
    }

    #[test]
    fn resolve_schema_files_uses_override_glob() {
        let (dir, db) = load_db(
            r#"
dialect = "sqlite"
schema = "src/schema.rs"
"#,
        );

        let a = dir.path().join("a.schema.rs");
        let b = dir.path().join("b.schema.rs");
        std::fs::write(&a, "pub struct A;").expect("write a");
        std::fs::write(&b, "pub struct B;").expect("write b");

        let pattern = format!("{}/*.schema.rs", dir.path().display()).replace('\\', "/");
        let override_patterns = vec![pattern];
        let files = resolve_schema_files(&db, Some(&override_patterns)).expect("resolve files");

        let paths: Vec<PathBuf> = files;
        assert_eq!(paths.len(), 2);
        assert!(paths.iter().any(|p| p.ends_with("a.schema.rs")));
        assert!(paths.iter().any(|p| p.ends_with("b.schema.rs")));
    }

    #[test]
    fn connection_overrides_debug_redacts_secrets() {
        let overrides = ConnectionOverrides {
            url: Some("postgres://alice:url-secret@localhost/app".into()),
            password: Some("password-secret".into()),
            auth_token: Some("token-secret".into()),
            ..ConnectionOverrides::default()
        };

        let rendered = format!("{overrides:?}");
        assert!(rendered.contains("[REDACTED]"));
        assert!(!rendered.contains("url-secret"));
        assert!(!rendered.contains("password-secret"));
        assert!(!rendered.contains("token-secret"));
    }
}