koibumi_common/
node.rs

1//! Functions to prepare database connection for node.
2
3use std::{fmt, io};
4
5use log::debug;
6
7use koibumi_node::db;
8
9use crate::{config::create_data_dir, param::Params};
10
11/// An error which can be returned when operating on the node database.
12#[derive(Debug)]
13pub enum Error {
14    /// A standard I/O error was caught during operation on the node database.
15    /// The actual error caught is returned as a payload of this variant.
16    IoError(io::Error),
17    /// A SQLx error was caught during operation on the node database.
18    /// The actual error caught is returned as a payload of this variant.
19    SqlxError(sqlx::Error),
20}
21
22impl fmt::Display for Error {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::IoError(err) => err.fmt(f),
26            Self::SqlxError(err) => err.fmt(f),
27        }
28    }
29}
30
31impl std::error::Error for Error {}
32
33impl From<io::Error> for Error {
34    fn from(err: io::Error) -> Self {
35        Self::IoError(err)
36    }
37}
38
39impl From<sqlx::Error> for Error {
40    fn from(err: sqlx::Error) -> Self {
41        Self::SqlxError(err)
42    }
43}
44
45/// Connects the database and returns a connection pool object.
46pub async fn prepare(params: &Params) -> Result<db::SqlitePool, Error> {
47    let mut path = create_data_dir(params)?;
48    path.push("node.db");
49    debug!("db: {:?}", path);
50    Ok(db::SqlitePool::connect_with(
51        sqlx::sqlite::SqliteConnectOptions::new()
52            .filename(path)
53            .create_if_missing(true),
54    )
55    .await?)
56}