mirror of
				https://gitlab.com/comunic/comunicapiv3
				synced 2025-11-04 09:34:04 +00:00 
			
		
		
		
	Add connection to the database
This commit is contained in:
		
							
								
								
									
										28
									
								
								src/helpers/database.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								src/helpers/database.rs
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,28 @@
 | 
			
		||||
use std::error::Error;
 | 
			
		||||
use std::sync::{Mutex, Arc};
 | 
			
		||||
use crate::data::config::DatabaseConfig;
 | 
			
		||||
use mysql::Pool;
 | 
			
		||||
 | 
			
		||||
/// Database access helper
 | 
			
		||||
///
 | 
			
		||||
/// @author Pierre Hubert
 | 
			
		||||
 | 
			
		||||
// Pool shared across threads
 | 
			
		||||
static mut POOL: Option<Arc<Mutex<mysql::Pool>>> = None;
 | 
			
		||||
 | 
			
		||||
/// Connect to the database
 | 
			
		||||
pub fn connect(conf: &DatabaseConfig) -> Result<(), Box<dyn Error>> {
 | 
			
		||||
    let url = format!(
 | 
			
		||||
        "mysql://{}:{}@{}:3306/{}",
 | 
			
		||||
        conf.username, conf.password, conf.host, conf.name
 | 
			
		||||
    );
 | 
			
		||||
 | 
			
		||||
    let pool = Pool::new(url)?;
 | 
			
		||||
    let pool = Some(Arc::new(Mutex::new(pool)));
 | 
			
		||||
 | 
			
		||||
    unsafe {
 | 
			
		||||
        POOL = pool;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    Ok(())
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										1
									
								
								src/helpers/mod.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								src/helpers/mod.rs
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1 @@
 | 
			
		||||
pub mod database;
 | 
			
		||||
@@ -1 +1,2 @@
 | 
			
		||||
pub mod data;
 | 
			
		||||
pub mod data;
 | 
			
		||||
pub mod helpers;
 | 
			
		||||
@@ -1,11 +1,13 @@
 | 
			
		||||
use comunic_server::data::config::{conf, Config};
 | 
			
		||||
use comunic_server::helpers::database;
 | 
			
		||||
 | 
			
		||||
fn main() {
 | 
			
		||||
 | 
			
		||||
    // Load configuration
 | 
			
		||||
    Config::load("config.yaml").expect("Could not load configuration!");
 | 
			
		||||
 | 
			
		||||
    println!("{:#?}", conf());
 | 
			
		||||
    // Connect to the database
 | 
			
		||||
    database::connect(&conf().database).expect("Could not connect to database!");
 | 
			
		||||
 | 
			
		||||
    println!("Hello, world!");
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user