pocket_relay_database/
lib.rs

1use migration::{Migrator, MigratorTrait};
2use sea_orm::Database as SeaDatabase;
3use std::{
4    fs::{create_dir_all, File},
5    path::Path,
6};
7
8mod data;
9mod entities;
10pub mod interfaces;
11mod migration;
12
13// Re-exports of named entities
14pub use data::user::PlayerRole;
15pub use entities::{GalaxyAtWar, Player, PlayerData};
16
17// Re-exports of database types
18pub use sea_orm::DatabaseConnection;
19pub use sea_orm::DbErr;
20
21/// Database error result type
22pub type DbResult<T> = Result<T, DbErr>;
23
24const DATABASE_PATH: &str = "data/app.db";
25const DATABASE_PATH_URL: &str = "sqlite:data/app.db";
26
27/// Connects to the database returning a Database connection
28/// which allows accessing the database without accessing sea_orm
29pub async fn init() -> DatabaseConnection {
30    let path = Path::new(&DATABASE_PATH);
31    if let Some(parent) = path.parent() {
32        if !parent.exists() {
33            create_dir_all(parent).expect("Unable to create parent directory for sqlite database");
34        }
35    }
36
37    if !path.exists() {
38        File::create(path).expect("Unable to create sqlite database file");
39    }
40
41    let connection = SeaDatabase::connect(DATABASE_PATH_URL)
42        .await
43        .expect("Unable to create database connection");
44
45    Migrator::up(&connection, None)
46        .await
47        .expect("Unable to run database migrations");
48
49    connection
50}