feat: initialize rust backend with axum server, seaorm models, and project scaffolding
This commit is contained in:
42
backend/src/db.rs
Normal file
42
backend/src/db.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
//! Database connection and migrations.
|
||||
|
||||
use sea_orm::{ConnectionTrait, Database, DatabaseConnection, DbBackend, DbErr, Schema, Statement};
|
||||
use sea_orm::sea_query::SqliteQueryBuilder;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::models::bio::{biomarker_entry, biomarker_type};
|
||||
use crate::models::user::{session, user};
|
||||
|
||||
/// Connect to the SQLite database.
|
||||
pub async fn connect(config: &Config) -> Result<DatabaseConnection, DbErr> {
|
||||
let db_path = &config.paths.database;
|
||||
|
||||
// Ensure the data directory exists
|
||||
if let Some(parent) = std::path::Path::new(db_path).parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
|
||||
let db_url = format!("sqlite:{}?mode=rwc", db_path);
|
||||
Database::connect(&db_url).await
|
||||
}
|
||||
|
||||
/// Run migrations to create tables if they don't exist.
|
||||
pub async fn run_migrations(db: &DatabaseConnection) -> Result<(), DbErr> {
|
||||
let schema = Schema::new(DbBackend::Sqlite);
|
||||
|
||||
// Create table statements
|
||||
let statements = vec![
|
||||
schema.create_table_from_entity(user::Entity),
|
||||
schema.create_table_from_entity(session::Entity),
|
||||
schema.create_table_from_entity(biomarker_type::Entity),
|
||||
schema.create_table_from_entity(biomarker_entry::Entity),
|
||||
];
|
||||
|
||||
for mut stmt in statements {
|
||||
let sql = stmt.if_not_exists().to_string(SqliteQueryBuilder);
|
||||
db.execute(Statement::from_string(DbBackend::Sqlite, sql))
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user