added database_pool crate, for pool handling and migrations
This commit is contained in:
parent
27d02a0d5c
commit
f60eb616d3
11 changed files with 197 additions and 0 deletions
|
|
@ -8,3 +8,6 @@ rocket = "0.5.0-rc.2"
|
|||
rocket_db_pools = { version = "0.1.0-rc.2", features = ["sqlx_sqlite"] }
|
||||
rocket_dyn_templates = { version = "0.1.0-rc.2", features = ["tera"] }
|
||||
infer = { version = "0.12.0", default-features = false }
|
||||
|
||||
# local crates
|
||||
database_pool = { path = "../database_pool" }
|
||||
2
crates/ezidam/Rocket.toml
Normal file
2
crates/ezidam/Rocket.toml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
[default.databases.ezidam]
|
||||
url = "../../database/ezidam.sqlite"
|
||||
36
crates/ezidam/src/database.rs
Normal file
36
crates/ezidam/src/database.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
use database_pool::run_migrations;
|
||||
use rocket::fairing::AdHoc;
|
||||
use rocket::{error, fairing, info, Build, Rocket};
|
||||
use rocket_db_pools::{sqlx, Database as RocketDatabase};
|
||||
|
||||
#[derive(RocketDatabase)]
|
||||
#[database("ezidam")]
|
||||
pub struct Database(sqlx::SqlitePool);
|
||||
|
||||
impl Database {
|
||||
pub fn rocket(rocket_builder: Rocket<Build>) -> Rocket<Build> {
|
||||
rocket_builder
|
||||
// Init
|
||||
.attach(Self::init())
|
||||
// SQL Migrations
|
||||
.attach(AdHoc::try_on_ignite("SQL Startup", Self::startup))
|
||||
}
|
||||
|
||||
async fn startup(rocket: Rocket<Build>) -> fairing::Result {
|
||||
let Some(db) = Self::fetch(&rocket) else {
|
||||
error!("Failed to get database");
|
||||
return Err(rocket);
|
||||
};
|
||||
|
||||
match run_migrations(&db.0).await {
|
||||
Ok(()) => {
|
||||
info!("Migrations ran successfully");
|
||||
Ok(rocket)
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to run migrations: {}", e);
|
||||
Err(rocket)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
mod database;
|
||||
mod shutdown;
|
||||
|
||||
// see for using rocket with main function https://github.com/intellij-rust/intellij-rust/issues/5975#issuecomment-920620289
|
||||
|
|
@ -6,6 +7,9 @@ async fn main() -> std::result::Result<(), rocket::Error> {
|
|||
// Build server
|
||||
let rocket_builder = rocket::build();
|
||||
|
||||
// Database
|
||||
let rocket_builder = database::Database::rocket(rocket_builder);
|
||||
|
||||
// Shutdown
|
||||
let rocket_builder = shutdown::shutdown(rocket_builder);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue