You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.4 KiB
Rust
75 lines
2.4 KiB
Rust
use sqlx::{Pool, Postgres};
|
|
|
|
pub mod objects;
|
|
use objects::{Board, Post, Site, Thread, User};
|
|
|
|
#[derive(Clone)]
|
|
pub struct DB {
|
|
connection_pool: Pool<Postgres>,
|
|
}
|
|
|
|
impl DB {
|
|
pub async fn init() -> Self {
|
|
let db_url =
|
|
std::env::var("DATABASE_URL").expect("Please provide DATABASE_URL in environment");
|
|
let pool = Pool::<Postgres>::connect(db_url.as_str())
|
|
.await
|
|
.expect("Could not connect to database");
|
|
|
|
sqlx::migrate!()
|
|
.run(&pool)
|
|
.await
|
|
.expect("Could not run database migrations");
|
|
|
|
DB {
|
|
connection_pool: pool,
|
|
}
|
|
}
|
|
|
|
pub async fn get_site_data(&self) -> Result<Site, String> {
|
|
let site = sqly::query_parsed!(
|
|
connection = &self.connection_pool,
|
|
query = r#"
|
|
select * from forum.site
|
|
left join forum.board on board_site = site_uuid
|
|
left join forum.thread on thread_board = board_uuid
|
|
left join forum.post on post_thread = thread_uuid
|
|
left join forum.user on post_author = user_uuid
|
|
"#,
|
|
// return_type = board_uuid
|
|
return_type = Site {
|
|
uuid: site_uuid,
|
|
title: site_title,
|
|
base_url: site_base_url,
|
|
theme: site_theme,
|
|
boards: Vec<Board {
|
|
uuid: board_uuid,
|
|
title: board_title,
|
|
description: board_description,
|
|
threads: Vec<Thread {
|
|
uuid: thread_uuid,
|
|
title: thread_title,
|
|
posts: Vec<Post {
|
|
uuid: post_uuid,
|
|
contents: post_contents,
|
|
author: User {
|
|
uuid: user_uuid,
|
|
username: user_username,
|
|
email: user_email,
|
|
password_hash: user_password_hash,
|
|
is_admin: user_is_admin
|
|
}
|
|
}>
|
|
}>
|
|
}>
|
|
}
|
|
);
|
|
|
|
if let Some(site) = site {
|
|
Ok(site)
|
|
} else {
|
|
Err("Could not find site in DB".to_string())
|
|
}
|
|
}
|
|
}
|