From ec5a8c8a6e330a9677dc8eae0734d9a001149ae8 Mon Sep 17 00:00:00 2001
From: prescientmoon <git@moonythm.dev>
Date: Thu, 22 Aug 2024 22:25:17 +0200
Subject: [PATCH] Move sql initialization in context creation

---
 src/context.rs | 33 ++++++++++++++++++++++++++++++---
 src/main.rs    | 35 ++---------------------------------
 2 files changed, 32 insertions(+), 36 deletions(-)

diff --git a/src/context.rs b/src/context.rs
index 45b5a84..bb047b7 100644
--- a/src/context.rs
+++ b/src/context.rs
@@ -1,5 +1,9 @@
+use include_dir::{include_dir, Dir};
+use r2d2::Pool;
 use r2d2_sqlite::SqliteConnectionManager;
+use rusqlite_migration::Migrations;
 use std::fs;
+use std::sync::LazyLock;
 
 use crate::{
 	arcaea::{chart::SongCache, jacket::JacketCache},
@@ -30,10 +34,35 @@ pub struct UserContext {
 
 impl UserContext {
 	#[inline]
-	pub async fn new(db: DbConnection) -> Result<Self, Error> {
+	pub async fn new() -> Result<Self, Error> {
 		timed!("create_context", {
 			fs::create_dir_all(get_data_dir())?;
 
+			// {{{ Connect to database
+			let db = timed!("create_sqlite_pool", {
+				Pool::new(
+					SqliteConnectionManager::file(&format!(
+						"{}/db.sqlite",
+						get_data_dir().to_str().unwrap()
+					))
+					.with_init(|conn| {
+						static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
+						static MIGRATIONS: LazyLock<Migrations> = LazyLock::new(|| {
+							Migrations::from_directory(&MIGRATIONS_DIR)
+								.expect("Could not load migrations")
+						});
+
+						MIGRATIONS
+							.to_latest(conn)
+							.expect("Could not run migrations");
+
+						Ok(())
+					}),
+				)
+				.expect("Could not open sqlite database.")
+			});
+			// }}}
+
 			let mut song_cache = timed!("make_song_cache", { SongCache::new(&db)? });
 			let jacket_cache = timed!("make_jacket_cache", { JacketCache::new(&mut song_cache)? });
 			let ui_measurements = timed!("read_ui_measurements", { UIMeasurements::read()? });
@@ -51,8 +80,6 @@ impl UserContext {
 				.with_borrow_mut(|font| CharMeasurements::from_text(font, WHITELIST, Some(700)))?;
 			// }}}
 
-			println!("Created user context");
-
 			Ok(Self {
 				db,
 				song_cache,
diff --git a/src/main.rs b/src/main.rs
index a0b547b..28ed47e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -20,18 +20,9 @@ mod transform;
 mod user;
 
 use arcaea::play::generate_missing_scores;
-use assets::get_data_dir;
 use context::{Error, UserContext};
-use include_dir::{include_dir, Dir};
 use poise::serenity_prelude::{self as serenity};
-use r2d2::Pool;
-use r2d2_sqlite::SqliteConnectionManager;
-use rusqlite_migration::Migrations;
-use std::{
-	env::var,
-	sync::{Arc, LazyLock},
-	time::Duration,
-};
+use std::{env::var, sync::Arc, time::Duration};
 
 // {{{ Error handler
 async fn on_error(error: poise::FrameworkError<'_, UserContext, Error>) {
@@ -47,28 +38,6 @@ async fn on_error(error: poise::FrameworkError<'_, UserContext, Error>) {
 
 #[tokio::main]
 async fn main() {
-	let pool = Pool::new(
-		SqliteConnectionManager::file(&format!("{}/db.sqlite", get_data_dir().to_str().unwrap()))
-			.with_init(|conn| {
-				static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
-				static MIGRATIONS: LazyLock<Migrations> = LazyLock::new(|| {
-					timed!("create_migration_structure", {
-						Migrations::from_directory(&MIGRATIONS_DIR)
-							.expect("Could not load migrations")
-					})
-				});
-
-				timed!("run_migrations", {
-					MIGRATIONS
-						.to_latest(conn)
-						.expect("Could not run migrations");
-				});
-
-				Ok(())
-			}),
-	)
-	.expect("Could not open sqlite database.");
-
 	// {{{ Poise options
 	let options = poise::FrameworkOptions {
 		commands: vec![
@@ -110,7 +79,7 @@ async fn main() {
 			Box::pin(async move {
 				println!("Logged in as {}", _ready.user.name);
 				poise::builtins::register_globally(ctx, &framework.options().commands).await?;
-				let ctx = UserContext::new(pool).await?;
+				let ctx = UserContext::new().await?;
 
 				if var("SHIMMERING_REGEN_SCORES").unwrap_or_default() == "1" {
 					timed!("generate_missing_scores", {