Skip to content

Commit ec70257

Browse files
fix: handle dotenvy errors and create db file if none exist
1 parent 90a23ad commit ec70257

File tree

1 file changed

+41
-9
lines changed

1 file changed

+41
-9
lines changed

src/main.rs

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,13 @@ mod utils;
1010
use std::env;
1111
use std::fs::File;
1212
use std::io::BufReader;
13+
use std::str::FromStr;
1314

1415
use poise::serenity_prelude::{self as serenity, GatewayIntents, GuildId};
1516
use poise::Command;
17+
use sqlx::sqlite::SqliteConnectOptions;
1618
use sqlx::SqlitePool;
17-
use tracing::{debug, info};
19+
use tracing::{debug, error, info};
1820

1921
use custom_types::command::{Data, Error, KeywordResponse, PartialData, SerenityCtxData};
2022
use events::Handler;
@@ -58,7 +60,23 @@ impl<'a> CommandRegistering {
5860
async fn main() {
5961
// Init logging
6062
logging::log_init();
61-
dotenvy::dotenv().unwrap();
63+
let d_env_result = dotenvy::dotenv();
64+
65+
if let Err(err) = d_env_result {
66+
match err {
67+
dotenvy::Error::Io(io_error) => match io_error.kind() {
68+
std::io::ErrorKind::NotFound => {
69+
info!("could not find .env file . . . skipping")
70+
}
71+
_ => {
72+
error!("io error during .env check: {}", io_error)
73+
}
74+
},
75+
_ => {
76+
error!("error occurred during .env check: {}", err)
77+
}
78+
}
79+
}
6280

6381
info!("Loading Johnson Bot v{VERSION}");
6482

@@ -70,14 +88,28 @@ async fn main() {
7088
| GatewayIntents::MESSAGE_CONTENT
7189
| GatewayIntents::GUILD_MEMBERS;
7290

73-
let pool =
74-
SqlitePool::connect(&env::var("DATABASE_URL").expect("missing DATABASE_URL env")).await;
75-
let pool = pool.expect("could not init sqlite pool");
91+
let db_url = env::var("DATABASE_URL").expect("missing DATABASE_URL env");
92+
info!("attempting to connect db to {}", db_url);
7693

77-
sqlx::migrate!("./migrations")
78-
.run(&pool)
79-
.await
80-
.expect("could not migrate sqlite");
94+
let connect_options = match SqliteConnectOptions::from_str(&db_url) {
95+
Ok(new_options) => new_options.create_if_missing(true),
96+
Err(err) => {
97+
error!("failed to parse database URL: {}", err);
98+
return;
99+
}
100+
};
101+
102+
let pool = match SqlitePool::connect_with(connect_options).await {
103+
Ok(pool) => pool,
104+
Err(err) => {
105+
error!("failed to connect to sqlite db: {}", err);
106+
return;
107+
}
108+
};
109+
110+
if let Err(err) = sqlx::migrate!("./migrations").run(&pool).await {
111+
error!("failed to migrate database: {}", err);
112+
}
81113

82114
// let music_commands = vec![
83115
// commands::music::play(),

0 commit comments

Comments
 (0)