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
//! Functions to prepare database connection for node.

use std::{fmt, io};

use log::debug;

use koibumi_node::db;

use crate::{config::create_data_dir, param::Params};

/// An error which can be returned when operating on the node database.
#[derive(Debug)]
pub enum Error {
    /// A standard I/O error was caught during operation on the node database.
    /// The actual error caught is returned as a payload of this variant.
    IoError(io::Error),
    /// A SQLx error was caught during operation on the node database.
    /// The actual error caught is returned as a payload of this variant.
    SqlxError(sqlx::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IoError(err) => err.fmt(f),
            Self::SqlxError(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for Error {}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Self::IoError(err)
    }
}

impl From<sqlx::Error> for Error {
    fn from(err: sqlx::Error) -> Self {
        Self::SqlxError(err)
    }
}

/// Connects the database and returns a connection pool object.
pub async fn prepare(params: &Params) -> Result<db::SqlitePool, Error> {
    let mut path = create_data_dir(params)?;
    path.push("node.db");
    debug!("db: {:?}", path);
    Ok(db::SqlitePool::connect_with(
        sqlx::sqlite::SqliteConnectOptions::new()
            .filename(path)
            .create_if_missing(true),
    )
    .await?)
}