basic stuff
This commit is contained in:
50
src/database.rs
Normal file
50
src/database.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use log::{info, error};
|
||||
use sqlx::{pool, postgres::PgPoolOptions, PgPool, Pool, Postgres, query};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Database {
|
||||
conn_pool: Pool<Postgres>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub async fn init(host: &str, user: &str, pass: &str, db_name: &str) -> Database {
|
||||
match PgPoolOptions::new()
|
||||
.max_connections(10)
|
||||
.connect(&format!("postgres://{user}:{pass}@{host}/{db_name}"))
|
||||
.await
|
||||
{
|
||||
Ok(pool) => {
|
||||
info!("Connection to the database is successful!");
|
||||
Database { conn_pool: pool }
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to connect to the database: {:?}", err);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_telementry(&self){
|
||||
info!("Adding telementry")
|
||||
}
|
||||
|
||||
// Check if the necessary tables exist. If not, create them. TODO auto-migration
|
||||
pub async fn init_db(&self){
|
||||
info!("Checking if required tables exist");
|
||||
|
||||
let exists = query!(
|
||||
"SELECT count(*) FROM information_schema.tables WHERE table_name = 'dev';"
|
||||
).fetch_one(&self.conn_pool).await;
|
||||
|
||||
let exist = match exists {
|
||||
Ok(res) => res.count > Some(0),
|
||||
Err(err) => {
|
||||
error!("Error checking table existence: {:?}", err);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
info!("Table exists: {:?}", exist);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user