Embed and handle db migrations in the binary

In order to create and update the database schema the binary now
handles database migrations.
This commit is contained in:
finga 2023-02-05 08:58:09 +01:00
parent a4a1234f06
commit 169a4988b6
3 changed files with 78 additions and 20 deletions

View file

@ -1,10 +1,11 @@
use anyhow::{Error, Result};
use anyhow::{anyhow, Error, Result};
use axum::{routing::post, Router};
use clap::Parser;
use diesel::{
prelude::*,
r2d2::{ConnectionManager, Pool},
};
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use lettre::{Message, SmtpTransport, Transport};
use std::{env, net::SocketAddr, sync::Arc, thread::JoinHandle, time::Duration};
use time::OffsetDateTime;
@ -22,6 +23,8 @@ use args::Args;
use config::Config;
use models::{NewReminder, Reminder};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
fn get_connection_pool(config: &Config) -> Result<Pool<ConnectionManager<PgConnection>>> {
Ok(
Pool::builder().build(ConnectionManager::<PgConnection>::new(format!(
@ -104,6 +107,11 @@ async fn main() -> Result<()> {
let config = Config::load_config(args.config)?;
let mut db_pool = get_connection_pool(&config)?;
trace!(migrations = ?db_pool
.get()?
.run_pending_migrations(MIGRATIONS)
.map_err(|e| anyhow!(e)), "running database migrations");
let reminder = std::thread::spawn(move || -> Result<(), Error> {
let mailer = SmtpTransport::unencrypted_localhost();
@ -111,6 +119,7 @@ async fn main() -> Result<()> {
remind(&mut db_pool, &mailer)?;
}
});
let db_pool = get_connection_pool(&config)?;
let app = Router::new()
.route("/v1/reminder", post(api::create_reminder))