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.

92 lines
3.2 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 = joinrs::query_parsed!(
connection = &self.connection_pool,
query = r#"
select
site_uuid as "site_uuid!",
site_title as "site_title!",
site_base_url as "site_base_url!",
site_theme as "site_theme!",
board_uuid as "board_uuid!",
board_title as "board_title!",
board_description as "board_description!",
thread_uuid as "thread_uuid!",
thread_title as "thread_title!",
post_uuid as "post_uuid!",
post_contents as "post_contents!",
user_uuid as "user_uuid!",
user_email as "user_email!",
user_username as "user_username!",
user_password_hash as "user_password_hash!",
user_is_admin as "user_is_admin!"
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 Ok(site) = site {
Ok(site)
} else {
Err("Could not find site in DB".to_string())
}
}
}