2023-10-10 19:45:18 +02:00
|
|
|
use sqlx::Pool;
|
2023-10-10 00:03:04 +02:00
|
|
|
use sqlx::Sqlite;
|
2023-10-20 22:49:09 +02:00
|
|
|
use sqlx::SqlitePool;
|
2023-10-10 00:03:04 +02:00
|
|
|
use sqlx::{self, sqlite};
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
2023-10-18 04:04:16 +02:00
|
|
|
pub struct ServerState {
|
2023-10-10 00:03:04 +02:00
|
|
|
pub pool: Pool<Sqlite>,
|
|
|
|
}
|
|
|
|
|
2023-10-18 04:04:16 +02:00
|
|
|
impl ServerState {
|
2023-10-10 00:03:04 +02:00
|
|
|
pub async fn new() -> Self {
|
2023-10-20 20:57:58 +02:00
|
|
|
// This is almost certainly bad practice for more reasons than I can count
|
|
|
|
dotenvy::dotenv().ok();
|
2023-10-20 22:49:09 +02:00
|
|
|
let db_url = dotenvy::var("DATABASE_URL").unwrap_or(":memory:".to_string());
|
2023-10-20 20:57:58 +02:00
|
|
|
|
2023-10-10 00:03:04 +02:00
|
|
|
let pool = sqlite::SqlitePoolOptions::new()
|
|
|
|
.max_connections(5)
|
2023-10-20 20:57:58 +02:00
|
|
|
.connect(&db_url)
|
2023-10-10 00:03:04 +02:00
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
sqlx::migrate!("./migrations").run(&pool).await.unwrap();
|
|
|
|
|
2023-10-20 22:49:09 +02:00
|
|
|
#[cfg(debug_assertions)]
|
|
|
|
debug_setup(&pool).await;
|
|
|
|
|
|
|
|
Self { pool }
|
2023-10-10 00:03:04 +02:00
|
|
|
}
|
|
|
|
}
|
2023-10-20 22:49:09 +02:00
|
|
|
|
|
|
|
// Inserts a bunch of dummy data into the database
|
|
|
|
// Mostly useful for debugging new posts, as we need to satisfy foreign key constraints.
|
|
|
|
#[cfg(debug_assertions)]
|
|
|
|
async fn debug_setup(pool: &SqlitePool) {
|
|
|
|
use chrono::NaiveDateTime;
|
|
|
|
use sqlx::query;
|
|
|
|
|
|
|
|
let now = NaiveDateTime::from_timestamp(0, 0);
|
|
|
|
|
|
|
|
query!(
|
|
|
|
"INSERT INTO users (username, password, created_at, updated_at) VALUES ('test', 'test', ?, ?)",
|
|
|
|
now,
|
|
|
|
now
|
|
|
|
)
|
|
|
|
.execute(pool)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
query!(
|
|
|
|
"INSERT INTO posts (user_id, content, created_at, updated_at) VALUES (1, 'Hello world!', ?, ?)",
|
|
|
|
now,
|
|
|
|
now
|
|
|
|
)
|
|
|
|
.execute(pool)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
}
|