about summary refs log tree commit diff stats
path: root/crates/rocie-server/src/app.rs
blob: 0467ef7672687b2e6abd8840cf3e2bfe0803da7f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// rocie - An enterprise grocery management system
//
// Copyright (C) 2026 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Rocie.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::{cell::OnceCell, path::PathBuf, sync::OnceLock};

use sqlx::{SqlitePool, sqlite::SqliteConnectOptions};

use crate::storage::migrate::{DbVersion, migrate_db};

#[derive(Clone)]
pub(crate) struct App {
    pub(crate) db: SqlitePool,
    pub(crate) db_version_at_start: OnceLock<DbVersion>,
}

impl App {
    pub(crate) async fn new(db_path: PathBuf) -> Result<Self, app_create::Error> {
        let db = {
            let options = SqliteConnectOptions::new()
                .filename(&db_path)
                .optimize_on_close(true, None)
                .create_if_missing(true);

            SqlitePool::connect_with(options).await.map_err(|err| {
                app_create::Error::DbConnectionFailed {
                    inner: err,
                    db_path,
                }
            })?
        };

        let me = Self {
            db,
            db_version_at_start: OnceLock::new(),
        };

        migrate_db(&me).await?;

        Ok(me)
    }
}

pub(crate) mod app_create {
    use std::path::PathBuf;

    use crate::storage::migrate::migrate_db;

    #[derive(thiserror::Error, Debug)]
    pub(crate) enum Error {
        #[error("Failed to connect to the sqlite database at `{db_path}`, because: {inner}")]
        DbConnectionFailed {
            inner: sqlx::Error,
            db_path: PathBuf,
        },

        #[error("Failed to migrate db to the current version")]
        MigrateDb(#[from] migrate_db::Error),
    }
}