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
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
/*!
Configuration structs
*/

use std::collections::{BTreeMap, HashSet};
use std::env;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

use chrono::{self, TimeZone};
use toml;
use url;

use crate::drivers;
use crate::errors::*;
use crate::{
    encode, invalid_full_tag, invalid_optional_stamp_tag, open_file_in_fg, prompt, write_to_path,
    DbKind, Migratable, CONFIG_FILE, DT_FORMAT, MYSQL_CONFIG_TEMPLATE, PG_CONFIG_TEMPLATE,
    SQLITE_CONFIG_TEMPLATE,
};

#[derive(Debug, Clone)]
enum DatabaseConfigOptions {
    Sqlite(SqliteSettingsBuilder),
    Postgres(PostgresSettingsBuilder),
    MySql(MySqlSettingsBuilder),
}

#[derive(Debug, Clone)]
/// Project settings file builder to initialize a new settings file
pub struct SettingsFileInitializer {
    dir: PathBuf,
    interactive: bool,
    with_env_defaults: bool,
    database_options: Option<DatabaseConfigOptions>,
}
impl SettingsFileInitializer {
    /// Start a new `ConfigInitializer`
    fn new<T: AsRef<Path>>(dir: T) -> Self {
        Self {
            dir: dir.as_ref().to_owned(),
            interactive: true,
            with_env_defaults: false,
            database_options: None,
        }
    }

    /// Set interactive prompts, default is `true`
    pub fn interactive(&mut self, b: bool) -> &mut Self {
        self.interactive = b;
        self
    }

    /// Default all file values `env:<ENV_VAR>` if unspecified
    pub fn with_env_defaults(&mut self, b: bool) -> &mut Self {
        self.with_env_defaults = b;
        self
    }

    /// Specify Sqlite database options
    ///
    /// ## Example:
    ///
    /// ```rust,no_run
    /// # extern crate migrant_lib;
    /// # use std::env;
    /// use migrant_lib::Config;
    /// use migrant_lib::config::SqliteSettingsBuilder;
    /// # fn main() { run().unwrap() }
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// Config::init_in(env::current_dir()?)
    ///     .with_sqlite_options(
    ///         SqliteSettingsBuilder::empty()
    ///             .database_path("/abs/path/to/my.db")?)
    ///     .initialize()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_sqlite_options(&mut self, options: &SqliteSettingsBuilder) -> &mut Self {
        self.database_options = Some(DatabaseConfigOptions::Sqlite(options.clone()));
        self
    }

    /// Specify Postgres database options
    ///
    /// ## Example:
    ///
    /// ```rust,no_run
    /// # extern crate migrant_lib;
    /// # use std::env;
    /// use migrant_lib::Config;
    /// use migrant_lib::config::PostgresSettingsBuilder;
    /// # fn main() { run().unwrap() }
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// Config::init_in(env::current_dir()?)
    ///     .with_postgres_options(
    ///         PostgresSettingsBuilder::empty()
    ///             .database_name("my_db")
    ///             .database_user("me")
    ///             .database_port(4444))
    ///     .initialize()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_postgres_options(&mut self, options: &PostgresSettingsBuilder) -> &mut Self {
        self.database_options = Some(DatabaseConfigOptions::Postgres(options.clone()));
        self
    }

    /// Specify MySQL database options
    ///
    /// ## Example:
    ///
    /// ```rust,no_run
    /// # extern crate migrant_lib;
    /// # use std::env;
    /// use migrant_lib::Config;
    /// use migrant_lib::config::MySqlSettingsBuilder;
    /// # fn main() { run().unwrap() }
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// Config::init_in(env::current_dir()?)
    ///     .with_mysql_options(
    ///         MySqlSettingsBuilder::empty()
    ///             .database_name("my_db")
    ///             .database_user("me")
    ///             .database_port(4444))
    ///     .initialize()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_mysql_options(&mut self, options: &MySqlSettingsBuilder) -> &mut Self {
        self.database_options = Some(DatabaseConfigOptions::MySql(options.clone()));
        self
    }

    /// Determines whether new .migrant file location should be in
    /// the given directory or a user specified path
    fn confirm_new_config_location(dir: &Path) -> Result<PathBuf> {
        println!(
            " A new `{}` config file will be created at the following location: ",
            CONFIG_FILE
        );
        println!("   {:?}", dir.display());
        let ans = prompt(" Is this ok? [Y/n] ")?;
        if ans.is_empty() || ans.to_lowercase() == "y" {
            return Ok(dir.to_owned());
        }

        println!(" You can specify the absolute location now, or nothing to exit");
        let ans = prompt(" >> ")?;
        if ans.is_empty() {
            bail_fmt!(ErrorKind::Config, "No `{}` path provided", CONFIG_FILE)
        }

        let path = PathBuf::from(ans);
        if !path.is_absolute() || path.file_name().unwrap() != CONFIG_FILE {
            bail_fmt!(
                ErrorKind::Config,
                "Invalid absolute path: {}, must end in `{}`",
                path.display(),
                CONFIG_FILE
            );
        }
        Ok(path)
    }

    /// Generate a template config file using provided parameters or prompting the user.
    /// If running interactively, the file will be opened for editing and `Config::setup`
    /// will be run automatically.
    pub fn initialize(&self) -> Result<()> {
        let config_path = self.dir.join(CONFIG_FILE);
        let config_path = if !self.interactive {
            config_path
        } else {
            Self::confirm_new_config_location(&config_path).map_err(|e| {
                format_err!(
                    ErrorKind::Config,
                    "unable to create a `{}` config -> {}",
                    CONFIG_FILE,
                    e
                )
            })?
        };

        let (db_kind, db_options) = if let Some(ref options) = self.database_options {
            let kind = match options {
                &DatabaseConfigOptions::Sqlite(_) => DbKind::Sqlite,
                &DatabaseConfigOptions::Postgres(_) => DbKind::Postgres,
                &DatabaseConfigOptions::MySql(_) => DbKind::MySql,
            };
            (kind, options.clone())
        } else {
            if !self.interactive {
                bail_fmt!(ErrorKind::Config, "database type must be specified if running non-interactively with options specified")
            }
            println!("\n ** Gathering database information...");
            let db_kind = {
                let db_kind = prompt(" database type (sqlite|postgres|mysql) >> ")?;
                match db_kind.parse::<DbKind>() {
                    Ok(kind) => kind,
                    Err(_) => {
                        bail_fmt!(ErrorKind::Config, "unsupported database type: {}", db_kind)
                    }
                }
            };
            let options = match db_kind {
                DbKind::Sqlite => {
                    let mut options = SqliteSettingsBuilder::empty();
                    options.migration_location("migrations")?;
                    DatabaseConfigOptions::Sqlite(options)
                }
                DbKind::Postgres => {
                    let mut options = PostgresSettingsBuilder::empty();
                    options.migration_location("migrations")?;
                    DatabaseConfigOptions::Postgres(options)
                }
                DbKind::MySql => {
                    let mut options = MySqlSettingsBuilder::empty();
                    options.migration_location("migrations")?;
                    DatabaseConfigOptions::MySql(options)
                }
            };
            (db_kind, options)
        };

        println!(
            "\n ** Writing {} config template to {:?}",
            db_kind, config_path
        );
        match db_options {
            DatabaseConfigOptions::Postgres(ref opts) => {
                let mut content = PG_CONFIG_TEMPLATE
                    .replace(
                        "__DB_NAME__",
                        &opts.database_name.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_NAME")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__DB_USER__",
                        &opts.database_user.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_USER")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__DB_PASS__",
                        &opts.database_password.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_PASSWORD")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__DB_HOST__",
                        &opts.database_host.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_HOST")
                            } else {
                                String::from("localhost")
                            }
                        }),
                    )
                    .replace(
                        "__DB_PORT__",
                        &opts.database_port.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_PORT")
                            } else {
                                String::from("5432")
                            }
                        }),
                    )
                    .replace(
                        "__MIG_LOC__",
                        &opts
                            .migration_location
                            .as_ref()
                            .cloned()
                            .unwrap_or_else(|| {
                                if self.with_env_defaults {
                                    String::from("env:MIGRATION_LOCATION")
                                } else {
                                    String::from("migrations")
                                }
                            }),
                    );
                if let Some(ref params) = opts.database_params {
                    for (k, v) in params.iter() {
                        content.push_str(&format!("{} = {:?}\n", k, v));
                    }
                } else {
                    content.push('\n');
                }
                content.push('\n');
                write_to_path(&config_path, content.as_bytes())?;
            }
            DatabaseConfigOptions::MySql(ref opts) => {
                let mut content = MYSQL_CONFIG_TEMPLATE
                    .replace(
                        "__DB_NAME__",
                        &opts.database_name.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_NAME")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__DB_USER__",
                        &opts.database_user.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_USER")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__DB_PASS__",
                        &opts.database_password.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_PASSWORD")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__DB_HOST__",
                        &opts.database_host.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_HOST")
                            } else {
                                String::from("localhost")
                            }
                        }),
                    )
                    .replace(
                        "__DB_PORT__",
                        &opts.database_port.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_PORT")
                            } else {
                                String::from("3306")
                            }
                        }),
                    )
                    .replace(
                        "__MIG_LOC__",
                        &opts
                            .migration_location
                            .as_ref()
                            .cloned()
                            .unwrap_or_else(|| {
                                if self.with_env_defaults {
                                    String::from("env:MIGRATION_LOCATION")
                                } else {
                                    String::from("migrations")
                                }
                            }),
                    );
                if let Some(ref params) = opts.database_params {
                    for (k, v) in params.iter() {
                        content.push_str(&format!("{} = {:?}\n", k, v));
                    }
                } else {
                    content.push('\n');
                }
                content.push('\n');
                write_to_path(&config_path, content.as_bytes())?;
            }
            DatabaseConfigOptions::Sqlite(ref opts) => {
                let content = SQLITE_CONFIG_TEMPLATE
                    .replace(
                        "__CONFIG_DIR__",
                        config_path.parent().unwrap().to_str().unwrap(),
                    )
                    .replace(
                        "__DB_PATH__",
                        &opts.database_path.as_ref().cloned().unwrap_or_else(|| {
                            if self.with_env_defaults {
                                String::from("env:DATABASE_PATH")
                            } else {
                                String::new()
                            }
                        }),
                    )
                    .replace(
                        "__MIG_LOC__",
                        &opts
                            .migration_location
                            .as_ref()
                            .cloned()
                            .unwrap_or_else(|| {
                                if self.with_env_defaults {
                                    String::from("env:MIGRATION_LOCATION")
                                } else {
                                    String::from("migrations")
                                }
                            }),
                    );
                write_to_path(&config_path, content.as_bytes())?;
            }
        };

        println!(
            "\n ** Please update `{}` with your database credentials and run `setup`\n",
            CONFIG_FILE
        );

        if self.interactive {
            let editor = env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
            let file_path = config_path.to_str().unwrap();
            let command = format!("{} {}", editor, file_path);
            println!(
                " -- Your config file will be opened with the following command: `{}`",
                &command
            );
            println!(" -- After editing, the `setup` command will be run for you");
            let _ = prompt(&format!(
                " -- Press [ENTER] to open now or [CTRL+C] to exit and edit manually"
            ))?;
            open_file_in_fg(&editor, file_path)
                .map_err(|e| format_err!(ErrorKind::Config, "Error editing config file: {}", e))?;

            println!();
            let config = Config::from_settings_file(&config_path)?;
            let _setup = config.setup()?;
        }
        Ok(())
    }
}

/// Sqlite settings builder
#[derive(Debug, Clone, Default)]
pub struct SqliteSettingsBuilder {
    database_path: Option<String>,
    migration_location: Option<String>,
}
impl SqliteSettingsBuilder {
    /// Initialize an empty builder
    pub fn empty() -> Self {
        Self::default()
    }

    /// **Required** -- Set the absolute path of a database file.
    pub fn database_path<T: AsRef<Path>>(&mut self, p: T) -> Result<&mut Self> {
        let p = p.as_ref();
        let s = p
            .to_str()
            .ok_or_else(|| format_err!(ErrorKind::PathError, "Unicode path error: {:?}", p))?;
        self.database_path = Some(s.to_owned());
        Ok(self)
    }

    /// Set directory to look for migration files.
    ///
    /// This can be an absolute or relative path. An absolute path should be preferred.
    /// If a relative path is provided, the path will be assumed relative to either the
    /// settings file's directory if a settings file exists, or the current directory.
    pub fn migration_location<T: AsRef<Path>>(&mut self, p: T) -> Result<&mut Self> {
        let p = p.as_ref();
        let s = p
            .to_str()
            .ok_or_else(|| format_err!(ErrorKind::PathError, "Unicode path error: {:?}", p))?;
        self.migration_location = Some(s.to_owned());
        Ok(self)
    }

    /// Build a `Settings` object
    pub fn build(&self) -> Result<Settings> {
        let db_path = self
            .database_path
            .as_ref()
            .ok_or_else(|| format_err!(ErrorKind::Config, "Missing `database_path` parameter"))?
            .clone();
        {
            let p = Path::new(&db_path);
            if !p.is_absolute() {
                bail_fmt!(
                    ErrorKind::Config,
                    "Explicit settings database path must be absolute: {:?}",
                    p
                )
            }
        }
        let inner = ConfigurableSettings::Sqlite(SqliteSettings {
            database_type: "sqlite".into(),
            database_path: db_path,
            migration_location: self.migration_location.clone(),
        });
        Ok(Settings { inner })
    }
}

/// Postgres settings builder
#[derive(Debug, Clone, Default)]
pub struct PostgresSettingsBuilder {
    database_name: Option<String>,
    database_user: Option<String>,
    database_password: Option<String>,
    database_host: Option<String>,
    database_port: Option<String>,
    database_params: Option<BTreeMap<String, String>>,
    ssl_cert_file: Option<PathBuf>,
    migration_location: Option<String>,
}
impl PostgresSettingsBuilder {
    /// Initialize an empty builder
    pub fn empty() -> Self {
        Self::default()
    }

    /// **Required** -- Set the database name.
    pub fn database_name(&mut self, name: &str) -> &mut Self {
        self.database_name = Some(name.into());
        self
    }

    /// **Required** -- Set the database user.
    pub fn database_user(&mut self, user: &str) -> &mut Self {
        self.database_user = Some(user.into());
        self
    }

    /// **Required** -- Set the database password.
    pub fn database_password(&mut self, pass: &str) -> &mut Self {
        self.database_password = Some(pass.into());
        self
    }

    /// Set the database host.
    pub fn database_host(&mut self, host: &str) -> &mut Self {
        self.database_host = Some(host.into());
        self
    }

    /// Set the database port.
    pub fn database_port(&mut self, port: u16) -> &mut Self {
        self.database_port = Some(port.to_string());
        self
    }

    /// Set a collection of database connection parameters.
    pub fn database_params(&mut self, params: &[(&str, &str)]) -> &mut Self {
        let mut map = BTreeMap::new();
        for &(k, v) in params.iter() {
            map.insert(k.to_string(), v.to_string());
        }
        self.database_params = Some(map);
        self
    }

    /// Set a custom ssl cert file
    pub fn ssl_cert_file<P: AsRef<Path>>(&mut self, file: P) -> &mut Self {
        let file = file.as_ref().to_path_buf();
        self.ssl_cert_file = Some(file);
        self
    }

    /// Set directory to look for migration files.
    ///
    /// This can be an absolute or relative path. An absolute path should be preferred.
    /// If a relative path is provided, the path will be assumed relative to either the
    /// settings file's directory if a settings file exists, or the current directory.
    pub fn migration_location<T: AsRef<Path>>(&mut self, p: T) -> Result<&mut Self> {
        let p = p.as_ref();
        let s = p
            .to_str()
            .ok_or_else(|| format_err!(ErrorKind::PathError, "Unicode path error: {:?}", p))?;
        self.migration_location = Some(s.to_owned());
        Ok(self)
    }

    /// Build a `Settings` object
    pub fn build(&self) -> Result<Settings> {
        let inner = ConfigurableSettings::Postgres(PostgresSettings {
            database_type: "postgres".into(),
            database_name: self
                .database_name
                .as_ref()
                .ok_or_else(|| format_err!(ErrorKind::Config, "Missing `database_name` parameter"))?
                .clone(),
            database_user: self
                .database_user
                .as_ref()
                .ok_or_else(|| format_err!(ErrorKind::Config, "Missing `database_user` parameter"))?
                .clone(),
            database_password: self
                .database_password
                .as_ref()
                .ok_or_else(|| {
                    format_err!(ErrorKind::Config, "Missing `database_password` parameter")
                })?
                .clone(),
            database_host: self.database_host.clone(),
            database_port: self.database_port.clone(),
            database_params: self.database_params.clone(),
            ssl_cert_file: self.ssl_cert_file.clone(),
            migration_location: self.migration_location.clone(),
        });
        Ok(Settings { inner })
    }
}

/// MySQL settings builder
#[derive(Debug, Clone, Default)]
pub struct MySqlSettingsBuilder {
    database_name: Option<String>,
    database_user: Option<String>,
    database_password: Option<String>,
    database_host: Option<String>,
    database_port: Option<String>,
    database_params: Option<BTreeMap<String, String>>,
    migration_location: Option<String>,
}
impl MySqlSettingsBuilder {
    /// Initialize an empty builder
    pub fn empty() -> Self {
        Self::default()
    }

    /// **Required** -- Set the database name.
    pub fn database_name(&mut self, name: &str) -> &mut Self {
        self.database_name = Some(name.into());
        self
    }

    /// **Required** -- Set the database user.
    pub fn database_user(&mut self, user: &str) -> &mut Self {
        self.database_user = Some(user.into());
        self
    }

    /// **Required** -- Set the database password.
    pub fn database_password(&mut self, pass: &str) -> &mut Self {
        self.database_password = Some(pass.into());
        self
    }

    /// Set the database host.
    pub fn database_host(&mut self, host: &str) -> &mut Self {
        self.database_host = Some(host.into());
        self
    }

    /// Set the database port.
    pub fn database_port(&mut self, port: u16) -> &mut Self {
        self.database_port = Some(port.to_string());
        self
    }
    /// Set a collection of database connection parameters.
    pub fn database_params(&mut self, params: &[(&str, &str)]) -> &mut Self {
        let mut map = BTreeMap::new();
        for &(k, v) in params.iter() {
            map.insert(k.to_string(), v.to_string());
        }
        self.database_params = Some(map);
        self
    }

    /// Set directory to look for migration files.
    ///
    /// This can be an absolute or relative path. An absolute path should be preferred.
    /// If a relative path is provided, the path will be assumed relative to either the
    /// settings file's directory if a settings file exists, or the current directory.
    pub fn migration_location<T: AsRef<Path>>(&mut self, p: T) -> Result<&mut Self> {
        let p = p.as_ref();
        let s = p
            .to_str()
            .ok_or_else(|| format_err!(ErrorKind::PathError, "Unicode path error: {:?}", p))?;
        self.migration_location = Some(s.to_owned());
        Ok(self)
    }

    /// Build a `Settings` object
    pub fn build(&self) -> Result<Settings> {
        let inner = ConfigurableSettings::MySql(MySqlSettings {
            database_type: "mysql".into(),
            database_name: self
                .database_name
                .as_ref()
                .ok_or_else(|| format_err!(ErrorKind::Config, "Missing `database_name` parameter"))?
                .clone(),
            database_user: self
                .database_user
                .as_ref()
                .ok_or_else(|| format_err!(ErrorKind::Config, "Missing `database_user` parameter"))?
                .clone(),
            database_password: self
                .database_password
                .as_ref()
                .ok_or_else(|| {
                    format_err!(ErrorKind::Config, "Missing `database_password` parameter")
                })?
                .clone(),
            database_host: self.database_host.clone(),
            database_port: self.database_port.clone(),
            database_params: self.database_params.clone(),
            migration_location: self.migration_location.clone(),
        });
        Ok(Settings { inner })
    }
}

#[derive(Deserialize, Debug, Clone)]
pub(crate) struct PostgresSettings {
    pub(crate) database_type: String,
    pub(crate) database_name: String,
    pub(crate) database_user: String,
    pub(crate) database_password: String,
    pub(crate) database_host: Option<String>,
    pub(crate) database_port: Option<String>,
    pub(crate) database_params: Option<BTreeMap<String, String>>,
    pub(crate) ssl_cert_file: Option<PathBuf>,
    pub(crate) migration_location: Option<String>,
}
impl PostgresSettings {
    pub(crate) fn connect_string(&self) -> Result<String> {
        let host = self
            .database_host
            .clone()
            .unwrap_or_else(|| "localhost".to_string());
        let host = if host.is_empty() {
            "localhost".to_string()
        } else {
            host
        };
        let host = encode(&host);

        let port = self
            .database_port
            .clone()
            .unwrap_or_else(|| "5432".to_string());
        let port = if port.is_empty() {
            "5432".to_string()
        } else {
            port
        };
        let port = encode(&port);

        let s = format!(
            "postgres://{user}:{pass}@{host}:{port}/{db_name}",
            user = encode(&self.database_user),
            pass = encode(&self.database_password),
            host = host,
            port = port,
            db_name = encode(&self.database_name)
        );

        let mut url = url::Url::parse(&s)?;

        if let Some(ref params) = self.database_params {
            let mut pairs = vec![];
            for (k, v) in params.iter() {
                let k = encode(k);
                let v = encode(v);
                pairs.push((k, v));
            }
            if !pairs.is_empty() {
                let mut url = url.query_pairs_mut();
                for &(ref k, ref v) in &pairs {
                    url.append_pair(k, v);
                }
            }
        }
        Ok(url.into_string())
    }

    pub(crate) fn resolve_env_vars(&self) -> Self {
        let database_type = self.database_type.clone();

        let database_name = if self.database_name.starts_with("env:") {
            let var = self.database_name.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_name.to_string()
        };

        let database_user = if self.database_user.starts_with("env:") {
            let var = self.database_user.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_user.to_string()
        };

        let database_password = if self.database_password.starts_with("env:") {
            let var = self.database_password.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_password.to_string()
        };

        let database_host = self.database_host.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });

        let database_port = self.database_port.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });

        let database_params = self.database_params.as_ref().map(|vars| {
            vars.iter().fold(BTreeMap::new(), |mut acc, (k, v)| {
                let val = if v.starts_with("env:") {
                    let v = v.trim_start_matches("env:");
                    env::var(v).unwrap_or_else(|_| "".into())
                } else {
                    v.clone()
                };
                acc.insert(k.clone(), val);
                acc
            })
        });

        let ssl_cert_file = self.ssl_cert_file.clone();

        let migration_location = self.migration_location.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });

        Self {
            database_type,
            database_name,
            database_user,
            database_password,
            database_host,
            database_port,
            database_params,
            ssl_cert_file,
            migration_location,
        }
    }
}

#[derive(Deserialize, Debug, Clone)]
pub(crate) struct MySqlSettings {
    pub(crate) database_type: String,
    pub(crate) database_name: String,
    pub(crate) database_user: String,
    pub(crate) database_password: String,
    pub(crate) database_host: Option<String>,
    pub(crate) database_port: Option<String>,
    pub(crate) database_params: Option<BTreeMap<String, String>>,
    pub(crate) migration_location: Option<String>,
}
impl MySqlSettings {
    pub(crate) fn connect_string(&self) -> Result<String> {
        let host = self
            .database_host
            .clone()
            .unwrap_or_else(|| "localhost".to_string());
        let host = if host.is_empty() {
            "localhost".to_string()
        } else {
            host
        };
        let host = encode(&host);

        let port = self
            .database_port
            .clone()
            .unwrap_or_else(|| "3306".to_string());
        let port = if port.is_empty() {
            "3306".to_string()
        } else {
            port
        };
        let port = encode(&port);

        let s = format!(
            "mysql://{user}:{pass}@{host}:{port}/{db_name}",
            user = encode(&self.database_user),
            pass = encode(&self.database_password),
            host = host,
            port = port,
            db_name = encode(&self.database_name)
        );

        let mut url = url::Url::parse(&s)?;

        if let Some(ref params) = self.database_params {
            let mut pairs = vec![];
            for (k, v) in params.iter() {
                let k = encode(k);
                let v = encode(v);
                pairs.push((k, v));
            }
            if !pairs.is_empty() {
                let mut url = url.query_pairs_mut();
                for &(ref k, ref v) in &pairs {
                    url.append_pair(k, v);
                }
            }
        }
        Ok(url.into_string())
    }

    pub(crate) fn resolve_env_vars(&self) -> Self {
        let database_type = self.database_type.clone();

        let database_name = if self.database_name.starts_with("env:") {
            let var = self.database_name.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_name.to_string()
        };

        let database_user = if self.database_user.starts_with("env:") {
            let var = self.database_user.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_user.to_string()
        };

        let database_password = if self.database_password.starts_with("env:") {
            let var = self.database_password.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_password.to_string()
        };

        let database_host = self.database_host.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });

        let database_port = self.database_port.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });

        let database_params = self.database_params.as_ref().map(|vars| {
            vars.iter().fold(BTreeMap::new(), |mut acc, (k, v)| {
                let val = if v.starts_with("env:") {
                    let v = v.trim_start_matches("env:");
                    env::var(v).unwrap_or_else(|_| "".into())
                } else {
                    v.clone()
                };
                acc.insert(k.clone(), val);
                acc
            })
        });

        let migration_location = self.migration_location.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });

        Self {
            database_type,
            database_name,
            database_user,
            database_password,
            database_host,
            database_port,
            database_params,
            migration_location,
        }
    }
}

#[derive(Deserialize, Debug, Clone)]
pub(crate) struct SqliteSettings {
    pub(crate) database_type: String,
    pub(crate) database_path: String,
    pub(crate) migration_location: Option<String>,
}
impl SqliteSettings {
    pub(crate) fn resolve_env_vars(&self) -> Self {
        let database_type = self.database_type.clone();

        let database_path = if self.database_path.starts_with("env:") {
            let var = self.database_path.trim_start_matches("env:");
            env::var(var).unwrap_or_else(|_| "".into())
        } else {
            self.database_path.to_string()
        };

        let migration_location = self.migration_location.as_ref().map(|maybe_str| {
            if maybe_str.starts_with("env:") {
                let var = maybe_str.trim_start_matches("env:");
                env::var(var).unwrap_or_else(|_| "".into())
            } else {
                maybe_str.to_string()
            }
        });
        Self {
            database_type,
            database_path,
            migration_location,
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) enum ConfigurableSettings {
    Postgres(PostgresSettings),
    Sqlite(SqliteSettings),
    MySql(MySqlSettings),
}
impl ConfigurableSettings {
    pub(crate) fn db_kind(&self) -> DbKind {
        match *self {
            ConfigurableSettings::Sqlite(_) => DbKind::Sqlite,
            ConfigurableSettings::Postgres(_) => DbKind::Postgres,
            ConfigurableSettings::MySql(_) => DbKind::MySql,
        }
    }

    pub(crate) fn migration_location(&self) -> Option<PathBuf> {
        match *self {
            ConfigurableSettings::Sqlite(ref s) => s.migration_location.as_ref().map(PathBuf::from),
            ConfigurableSettings::Postgres(ref s) => {
                s.migration_location.as_ref().map(PathBuf::from)
            }
            ConfigurableSettings::MySql(ref s) => s.migration_location.as_ref().map(PathBuf::from),
        }
    }

    pub(crate) fn database_path(&self) -> Result<PathBuf> {
        match *self {
            ConfigurableSettings::Sqlite(ref s) => Ok(PathBuf::from(&s.database_path)),
            ConfigurableSettings::Postgres(ref s) => bail_fmt!(
                ErrorKind::Config,
                "Cannot generate database_path for database-type: {}",
                s.database_type
            ),
            ConfigurableSettings::MySql(ref s) => bail_fmt!(
                ErrorKind::Config,
                "Cannot generate database_path for database-type: {}",
                s.database_type
            ),
        }
    }

    pub(crate) fn connect_string(&self) -> Result<String> {
        match *self {
            ConfigurableSettings::Postgres(ref s) => s.connect_string(),
            ConfigurableSettings::MySql(ref s) => s.connect_string(),
            ConfigurableSettings::Sqlite(ref s) => bail_fmt!(
                ErrorKind::Config,
                "Cannot generate connect-string for database-type: {}",
                s.database_type
            ),
        }
    }

    pub(crate) fn ssl_cert_file(&self) -> Option<PathBuf> {
        match *self {
            ConfigurableSettings::Postgres(ref s) => s.ssl_cert_file.clone(),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
/// Project settings
///
/// These settings are serialized and saved in a project `Migrant.toml` config file
/// or defined explicitly in source using the provided builder methods.
pub struct Settings {
    pub(crate) inner: ConfigurableSettings,
}
impl Settings {
    /// Initialize from a serialized settings file
    pub fn from_file<T: AsRef<Path>>(path: T) -> Result<Self> {
        #[derive(Deserialize)]
        struct DbTypeField {
            database_type: String,
        }
        let mut f = fs::File::open(path.as_ref())?;
        let mut content = String::new();
        f.read_to_string(&mut content)?;

        let type_field = toml::from_str::<DbTypeField>(&content)?;
        let inner = match type_field.database_type.as_ref() {
            "sqlite" => {
                let settings = toml::from_str::<SqliteSettings>(&content)?;
                let settings = settings.resolve_env_vars();
                ConfigurableSettings::Sqlite(settings)
            }
            "postgres" => {
                let settings = toml::from_str::<PostgresSettings>(&content)?;
                let settings = settings.resolve_env_vars();
                ConfigurableSettings::Postgres(settings)
            }
            "mysql" => {
                let settings = toml::from_str::<MySqlSettings>(&content)?;
                let settings = settings.resolve_env_vars();
                ConfigurableSettings::MySql(settings)
            }
            t => bail_fmt!(ErrorKind::Config, "Invalid database_type: {:?}", t),
        };
        Ok(Self { inner })
    }

    /// Initialize a `SqliteSettingsBuilder` to be configured
    pub fn configure_sqlite() -> SqliteSettingsBuilder {
        SqliteSettingsBuilder::default()
    }

    /// Initialize a `PostgresSettingsBuilder` to be configured
    pub fn configure_postgres() -> PostgresSettingsBuilder {
        PostgresSettingsBuilder::default()
    }

    /// Initialize a `MySqlSettingsBuilder` to be configured
    pub fn configure_mysql() -> MySqlSettingsBuilder {
        MySqlSettingsBuilder::default()
    }
}

#[derive(Debug, Clone)]
/// Full project configuration
pub struct Config {
    pub(crate) settings: Settings,
    pub(crate) settings_path: Option<PathBuf>,
    pub(crate) applied: Vec<String>,
    pub(crate) migrations: Option<Vec<Box<dyn Migratable>>>,
    pub(crate) cli_compatible: bool,
}
impl Config {
    /// Define an explicit set of `Migratable` migrations to use.
    ///
    /// The order of definition is the order in which they will be applied.
    ///
    /// **Note:** When using explicit migrations, make sure any toggling of `Config::use_cli_compatible_tags`
    /// happens **before** the call to `Config::use_migrations`.
    ///
    /// # Example
    ///
    /// The following uses a migrant config file for connection configuration and
    /// explicitly defines migrations with `use_migrations`.
    ///
    /// ```rust,no_run
    /// extern crate migrant_lib;
    /// use migrant_lib::{
    ///     Config, search_for_settings_file,
    ///     EmbeddedMigration, FileMigration, FnMigration
    /// };
    ///
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// mod migrations {
    ///     use super::*;
    ///     pub struct Custom;
    ///     impl Custom {
    ///         pub fn up(_: migrant_lib::ConnConfig) -> Result<(), Box<dyn std::error::Error>> {
    ///             print!(" <[Up!]>");
    ///             Ok(())
    ///         }
    ///         pub fn down(_: migrant_lib::ConnConfig) -> Result<(), Box<dyn std::error::Error>> {
    ///             print!(" <[Down!]>");
    ///             Ok(())
    ///         }
    ///     }
    /// }
    ///
    /// let p = search_for_settings_file(&std::env::current_dir()?)
    ///     .ok_or_else(|| "Settings file not found")?;
    /// let mut config = Config::from_settings_file(&p)?;
    /// # #[cfg(any(feature="d-sqlite", feature="d-postgres", feature="d-mysql"))]
    /// config.use_migrations(&[
    ///     EmbeddedMigration::with_tag("create-users-table")
    ///         .up(include_str!("../migrations/embedded/create_users_table/up.sql"))
    ///         .down(include_str!("../migrations/embedded/create_users_table/down.sql"))
    ///         .boxed(),
    ///     FileMigration::with_tag("create-places-table")
    ///         .up("migrations/embedded/create_places_table/up.sql")?
    ///         .down("migrations/embedded/create_places_table/down.sql")?
    ///         .boxed(),
    ///     FnMigration::with_tag("custom")
    ///         .up(migrations::Custom::up)
    ///         .down(migrations::Custom::down)
    ///         .boxed(),
    /// ])?;
    ///
    /// // Load applied migrations
    /// let config = config.reload()?;
    /// # let _ = config;
    /// # Ok(())
    /// # }
    /// # fn main() { run().unwrap(); }
    /// ```
    pub fn use_migrations<T: AsRef<[Box<dyn Migratable>]>>(
        &mut self,
        migrations: T,
    ) -> Result<&mut Self> {
        let migrations = migrations.as_ref();
        let mut set = HashSet::with_capacity(migrations.len());
        let mut migs = Vec::with_capacity(migrations.len());
        for mig in migrations {
            let tag = mig.tag();
            if self.cli_compatible {
                if invalid_full_tag(&tag) {
                    bail_fmt!(
                        ErrorKind::TagError,
                        "When `cli_compatible=true` tags must be timestamped, \
                         following: `[0-9]{{14}}_[a-z0-9-]+`. Found tag: `{}`",
                        tag
                    )
                }
            } else if invalid_optional_stamp_tag(&tag) {
                bail_fmt!(
                    ErrorKind::TagError,
                    "When `cli_compatible=false` (default) tags may only contain, \
                     `[a-z0-9-]` and may be optionally prefixed with a timestamp \
                     following: `([0-9]{{14}}_)?[a-z0-9-]+`. Found tag: `{}`",
                    tag
                )
            }
            if set.contains(&tag) {
                bail_fmt!(
                    ErrorKind::TagError,
                    "Tags must be unique. Found duplicate: {}",
                    tag
                )
            }
            set.insert(tag);
            migs.push(mig.clone());
        }
        self.migrations = Some(migs);
        Ok(self)
    }

    /// Migrations are explicitly defined
    pub fn is_explicit(&self) -> bool {
        self.migrations.is_some()
    }

    /// Toggle cli compatible tag validation.
    ///
    /// **Note:** Make sure any calls to `Config::use_cli_compatible_tags` happen
    /// **before** any calls to `Config::reload` or `Config::use_migrations` since
    /// this is dependent on the tag format being used.
    ///
    /// Defaults to `false`. When `cli_compatible` is set to `true`, migration
    /// tags will be validated in a manner compatible with the migrant CLI tool.
    /// Tags must be prefixed with a timestamp, following: `[0-9]{14}_[a-z0-9-]+`.
    /// When not enabled (the default), tag timestamps are optional and
    /// the migrant CLI tool will not be able to identify tags.
    pub fn use_cli_compatible_tags(&mut self, compat: bool) {
        self.cli_compatible = compat;
    }

    /// Check the current cli compatibility
    pub fn is_cli_compatible(&self) -> bool {
        self.cli_compatible
    }

    /// Check that migration tags conform to naming requirements.
    /// If CLI compatibility is enabled, then tags must be prefixed with a timestamp
    /// following: `[0-9]{14}_[a-z0-9-]+` which is the format generated by the migrant
    /// CLI tool and `migrant_lib::new`. When CLI compatibility is disabled (default).
    /// tags may only contain `[a-z0-9-]`, but can still be optionally prefixed with
    /// a timestamp following: `([0-9]{14}_)?[a-z0-9-]+`.
    fn check_saved_tag(&self, tag: &str) -> Result<()> {
        if self.cli_compatible {
            if invalid_full_tag(tag) {
                bail_fmt!(
                    ErrorKind::Migration,
                    "Found a non-conforming tag in the database: `{}`. \
                     Generated/CLI-compatible tags must follow `[0-9]{{14}}_[a-z0-9-]+`",
                    tag
                )
            }
        } else if invalid_optional_stamp_tag(&tag) {
            bail_fmt!(
                ErrorKind::Migration,
                "Found a non-conforming tag in the database: `{}`. \
                 Managed/embedded tags may contain `[a-z0-9-]+`",
                tag
            )
        }
        Ok(())
    }

    /// Queries the database to reload the current applied migrations.
    ///
    /// **Note:** Make sure any calls to `Config::use_cli_compatible_tags` happen
    /// **before** any calls to `Config::reload` since this is dependent on the
    /// tag format being used.
    ///
    /// If the `Config` was initialized from a settings file, the settings
    /// will also be reloaded from the file. Returns a new `Config` instance.
    pub fn reload(&self) -> Result<Config> {
        let mut config = match self.settings_path.as_ref() {
            Some(path) => Config::from_settings_file(path)?,
            None => self.clone(),
        };
        config.cli_compatible = self.cli_compatible;
        config.migrations = self.migrations.clone();
        let applied = config.load_applied()?;
        config.applied = applied;
        Ok(config)
    }

    /// Initialize a `Config` from a settings file at the given path.
    /// This does not query the database for applied migrations.
    pub fn from_settings_file<T: AsRef<Path>>(path: T) -> Result<Config> {
        let path = path.as_ref();
        let settings = Settings::from_file(path)?;
        Ok(Config {
            settings_path: Some(path.to_owned()),
            settings: settings,
            applied: vec![],
            migrations: None,
            cli_compatible: false,
        })
    }

    /// Initialize a `Config` using an explicitly created `Settings` object.
    /// This alleviates the need for a settings file.
    /// This does not query the database for applied migrations.
    ///
    /// ```rust,no_run
    /// # extern crate migrant_lib;
    /// # use migrant_lib::{Settings, Config};
    /// # fn main() { run().unwrap(); }
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let settings = Settings::configure_sqlite()
    ///     .database_path("/absolute/path/to/db.db")?
    ///     .migration_location("/absolute/path/to/migration_dir")?
    ///     .build()?;
    /// let config = Config::with_settings(&settings);
    /// // Setup migrations table
    /// config.setup()?;
    ///
    /// // Reload config, ping the database for applied migrations
    /// let config = config.reload()?;
    /// # let _ = config;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_settings(s: &Settings) -> Config {
        Config {
            settings: s.clone(),
            settings_path: None,
            applied: vec![],
            migrations: None,
            cli_compatible: false,
        }
    }

    /// Load the applied migrations from the database migration table
    pub(crate) fn load_applied(&self) -> Result<Vec<String>> {
        if !self.migration_table_exists()? {
            bail_fmt!(
                ErrorKind::Migration,
                "`__migrant_migrations` table is missing, maybe try re-setting-up? -> `setup`"
            )
        }

        let applied = match self.settings.inner.db_kind() {
            DbKind::Sqlite => drivers::sqlite::select_migrations(&self.database_path_string()?)?,
            DbKind::Postgres => drivers::pg::select_migrations(
                self.ssl_cert_file().as_deref(),
                &self.connect_string()?,
            )?,
            DbKind::MySql => drivers::mysql::select_migrations(&self.connect_string()?)?,
        };
        let mut tags = vec![];
        for tag in applied.into_iter() {
            self.check_saved_tag(&tag)?;
            tags.push(tag);
        }
        let tags = if !self.cli_compatible {
            tags
        } else {
            let mut stamped = tags
                .into_iter()
                .map(|tag| {
                    let stamp = tag.split('_').next().ok_or_else(|| {
                        format_err!(ErrorKind::TagError, "Invalid tag format: {:?}", tag)
                    })?;
                    let stamp = chrono::Utc.datetime_from_str(stamp, DT_FORMAT)?;
                    Ok((stamp, tag.clone()))
                })
                .collect::<Result<Vec<_>>>()?;
            stamped.sort_by(|a, b| a.0.cmp(&b.0));
            stamped.into_iter().map(|tup| tup.1).collect::<Vec<_>>()
        };
        Ok(tags)
    }

    /// Check if a __migrant_migrations table exists
    pub(crate) fn migration_table_exists(&self) -> Result<bool> {
        match self.settings.inner.db_kind() {
            DbKind::Sqlite => {
                drivers::sqlite::migration_table_exists(&self.database_path_string()?)
            }
            DbKind::Postgres => drivers::pg::migration_table_exists(
                self.ssl_cert_file().as_deref(),
                &self.connect_string()?,
            ),
            DbKind::MySql => drivers::mysql::migration_table_exists(&self.connect_string()?),
        }
    }

    /// Insert given tag into database migration table
    pub(crate) fn insert_migration_tag(&self, tag: &str) -> Result<()> {
        match self.settings.inner.db_kind() {
            DbKind::Sqlite => {
                drivers::sqlite::insert_migration_tag(&self.database_path_string()?, tag)?
            }
            DbKind::Postgres => drivers::pg::insert_migration_tag(
                self.ssl_cert_file().as_deref(),
                &self.connect_string()?,
                tag,
            )?,
            DbKind::MySql => drivers::mysql::insert_migration_tag(&self.connect_string()?, tag)?,
        };
        Ok(())
    }

    /// Remove a given tag from the database migration table
    pub(crate) fn delete_migration_tag(&self, tag: &str) -> Result<()> {
        match self.settings.inner.db_kind() {
            DbKind::Sqlite => {
                drivers::sqlite::remove_migration_tag(&self.database_path_string()?, tag)?
            }
            DbKind::Postgres => drivers::pg::remove_migration_tag(
                self.ssl_cert_file().as_deref(),
                &self.connect_string()?,
                tag,
            )?,
            DbKind::MySql => drivers::mysql::remove_migration_tag(&self.connect_string()?, tag)?,
        };
        Ok(())
    }

    /// Initialize a new settings file in the given directory
    pub fn init_in<T: AsRef<Path>>(dir: T) -> SettingsFileInitializer {
        SettingsFileInitializer::new(dir.as_ref())
    }

    /// Confirm the database can be accessed and setup the database
    /// migrations table if it doesn't already exist
    pub fn setup(&self) -> Result<bool> {
        debug!(" ** Confirming database credentials...");
        match &self.settings.inner {
            &ConfigurableSettings::Sqlite(_) => {
                let created = drivers::sqlite::create_file_if_missing(&self.database_path()?)?;
                debug!("    - checking if db file already exists...");
                if created {
                    debug!("    - db not found... creating now... ✓")
                } else {
                    debug!("    - db already exists ✓");
                }
            }
            &ConfigurableSettings::Postgres(ref s) => {
                let conn_str = s.connect_string()?;
                let can_connect = drivers::pg::can_connect(s.ssl_cert_file.as_deref(), &conn_str)?;
                if !can_connect {
                    error!(" ERROR: Unable to connect to {}", conn_str);
                    error!("        Please initialize your database and user and then run `setup`");
                    error!("\n  ex) sudo -u postgres createdb {}", s.database_name);
                    error!("      sudo -u postgres createuser {}", s.database_user);
                    error!(
                        "      sudo -u postgres psql -c \"alter user {} with password '****'\"",
                        s.database_user
                    );
                    error!("");
                    bail_fmt!(
                        ErrorKind::Config,
                        "Cannot connect to postgres database with connection string: {:?}. \
                         Do the database & user exist?",
                        conn_str
                    );
                } else {
                    debug!("    - Connection confirmed ✓");
                }
            }
            &ConfigurableSettings::MySql(ref s) => {
                let conn_str = s.connect_string()?;
                let can_connect = drivers::mysql::can_connect(&conn_str)?;
                if !can_connect {
                    let localhost = String::from("localhost");
                    error!(" ERROR: Unable to connect to {}", conn_str);
                    error!("        Please initialize your database and user and then run `setup`");
                    error!(
                        "\n  ex) mysql -u root -p -e \"create database {};\"",
                        s.database_name
                    );
                    error!("      mysql -u root -p -e \"create user '{}'@'{}' identified by '*****';\"",
                           s.database_user, s.database_host.as_ref().unwrap_or(&localhost));
                    error!(
                        "      mysql -u root -p e \"grant all privileges on {}.* to '{}'@'{}';\"",
                        s.database_name,
                        s.database_user,
                        s.database_host.as_ref().unwrap_or(&localhost)
                    );
                    error!("      mysql -u root -p e \"flush privileges;\"");
                    error!("");
                    bail_fmt!(
                        ErrorKind::Config,
                        "Cannot connect to mysql database with connection string: {:?}. \
                         Do the database & user exist?",
                        conn_str
                    );
                } else {
                    debug!("    - Connection confirmed ✓");
                }
            }
        }

        debug!("\n ** Setting up migrations table");
        let table_created = match &self.settings.inner {
            &ConfigurableSettings::Sqlite(_) => {
                drivers::sqlite::migration_setup(&self.database_path()?)?
            }
            &ConfigurableSettings::Postgres(ref s) => {
                let conn_str = s.connect_string()?;
                drivers::pg::migration_setup(self.ssl_cert_file().as_deref(), &conn_str)?
            }
            &ConfigurableSettings::MySql(ref s) => {
                let conn_str = s.connect_string()?;
                drivers::mysql::migration_setup(&conn_str)?
            }
        };

        if table_created {
            debug!("    - migrations table missing");
            debug!("    - `__migrant_migrations` table created ✓");
            Ok(true)
        } else {
            debug!("    - `__migrant_migrations` table already exists ✓");
            Ok(false)
        }
    }

    /// Return the absolute path to the directory containing migration folders
    ///
    /// The location returned is dependent on whether an absolute or relative path
    /// was provided to `migration_location` in either a settings file or settings builder.
    /// If an absolute path was provided, that same path is returned.
    /// If a relative path was provided, the path returned will be relative
    /// to either the settings file's directory if a settings file exists, or
    /// the current directory.
    #[deprecated(since = "0.18.1", note = "renamed to `migration_location`")]
    pub fn migration_dir(&self) -> Result<PathBuf> {
        let path = self
            .settings
            .inner
            .migration_location()
            .unwrap_or_else(|| PathBuf::from("migrations"));
        Ok(if path.is_absolute() {
            path
        } else {
            let cur_dir = env::current_dir()?;
            let base_path = match self.settings_path.as_ref() {
                Some(s_path) => s_path.parent().ok_or_else(|| {
                    format_err!(
                        ErrorKind::PathError,
                        "Unable to determine parent path: {:?}",
                        s_path
                    )
                })?,
                None => &cur_dir,
            };
            base_path.join(path)
        })
    }

    /// Return the absolute path to the directory containing migration folders
    ///
    /// The location returned is dependent on whether an absolute or relative path
    /// was provided to `migration_location` in either a settings file or settings builder.
    /// If an absolute path was provided, that same path is returned.
    /// If a relative path was provided, the path returned will be relative
    /// to either the settings file's directory if a settings file exists, or
    /// the current directory.
    pub fn migration_location(&self) -> Result<PathBuf> {
        let path = self
            .settings
            .inner
            .migration_location()
            .unwrap_or_else(|| PathBuf::from("migrations"));
        Ok(if path.is_absolute() {
            path
        } else {
            let cur_dir = env::current_dir()?;
            let base_path = match self.settings_path.as_ref() {
                Some(s_path) => s_path.parent().ok_or_else(|| {
                    format_err!(
                        ErrorKind::PathError,
                        "Unable to determine parent path: {:?}",
                        s_path
                    )
                })?,
                None => &cur_dir,
            };
            base_path.join(path)
        })
    }

    /// Return the database type
    pub fn database_type(&self) -> DbKind {
        self.settings.inner.db_kind()
    }

    fn database_path_string(&self) -> Result<String> {
        let path = self.database_path()?;
        let path = path
            .to_str()
            .ok_or_else(|| format_err!(ErrorKind::PathError, "Invalid utf8 path: {:?}", path))?
            .to_owned();
        Ok(path)
    }

    /// Return the absolute path to the database file. This is intended for
    /// sqlite databases only
    pub fn database_path(&self) -> Result<PathBuf> {
        let path = self.settings.inner.database_path()?;
        if path.is_absolute() {
            Ok(path)
        } else {
            let spath =
                Path::new(self.settings_path.as_ref().ok_or_else(|| {
                    format_err!(ErrorKind::Config, "Settings path not specified")
                })?);
            let spath = spath.parent().ok_or_else(|| {
                format_err!(
                    ErrorKind::PathError,
                    "Unable to determine parent path: {:?}",
                    spath
                )
            })?;
            Ok(spath.join(&path))
        }
    }

    /// Generate a database connection string.
    /// Not intended for file-based databases (sqlite)
    pub fn connect_string(&self) -> Result<String> {
        self.settings.inner.connect_string()
    }

    pub fn ssl_cert_file(&self) -> Option<PathBuf> {
        self.settings.inner.ssl_cert_file()
    }
}