Skip to content

Commit 4913f9c

Browse files
committed
Database connection
1 parent 5af53a2 commit 4913f9c

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

src/main.rs

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,24 @@ mod web;
6767

6868
compile_i18n!();
6969

70+
/// Initializes a database pool
71+
fn init_pool() -> Option<DbPool> {
72+
let manager = ConnectionManager::<Connection>::new(CONFIG.database_url.as_str());
73+
let pool = DbPool::builder()
74+
.connection_customizer(Box::new(PragmaForeignKey))
75+
.build(manager)
76+
.ok()?;
77+
Instance::cache_local(&pool.get().unwrap());
78+
Some(pool)
79+
}
80+
7081
fn main() -> std::io::Result<()> {
82+
match dotenv::dotenv() {
83+
Ok(path) => println!("Configuration read from {}", path.display()),
84+
Err(ref e) if e.not_found() => eprintln!("no .env was found"),
85+
e => e.map(|_| ()).unwrap(),
86+
}
87+
7188
if let Err(_) = std::env::var("RUST_LOG") {
7289
std::env::set_var("RUST_LOG", "debug");
7390
}
@@ -97,9 +114,29 @@ and https://docs.joinplu.me/installation/init for more info.
97114

98115
let mail = mail::init();
99116

100-
HttpServer::new(|| {
117+
let dbpool = init_pool().expect("main: database pool initialization error");
118+
if IMPORTED_MIGRATIONS
119+
.is_pending(&dbpool.get().unwrap())
120+
.unwrap_or(true)
121+
{
122+
panic!(
123+
r#"
124+
It appear your database migration does not run the migration required
125+
by this version of Plume. To fix this, you can run migrations via
126+
this command:
127+
128+
plm migration run
129+
130+
Then try to restart Plume.
131+
"#
132+
)
133+
}
134+
135+
136+
HttpServer::new(move || {
101137
ActixApp::new()
102138
.wrap(middleware::Logger::default())
139+
.data(dbpool.clone())
103140
.service(aweb::scope("/")
104141
.service(api::service())
105142
.service(web::service())

src/web/mod.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
use actix_web::{web, Scope};
1+
use actix_web::{web, Scope, HttpResponse};
22

33
pub fn service() -> Scope {
44
web::scope("/")
5+
.route("/test", web::get().to(|pool: web::Data<plume_models::db_conn::DbPool>| {
6+
let instance = plume_models::instance::Instance::get(&pool.get().unwrap(), 1).unwrap();
7+
HttpResponse::Ok().body(format!("Welcome on {}\n\n{}", instance.name, instance.short_description))
8+
}))
59
}

0 commit comments

Comments
 (0)