Skip to main content

ohlcv_ctl/cli/command/
init.rs

1use std::path::PathBuf;
2
3use ohlcv::Database;
4use tracing::instrument;
5
6use crate::{
7    config::{CoinConfig, Config},
8    Error,
9};
10
11use super::root_credentials;
12
13/// Initialize the database
14///
15/// # Arguments
16///
17/// * `config` - Optional path to the configuration file. If not provided, the
18///   default configuration file will be used. This file is expected to be in
19///   TOML format. The default file is `ohlcv.toml` and is expected to be in the
20///   current working directory or in `/etc/ohlcv`.
21///
22/// # Errors
23///
24/// Returns an error if the database cannot be initialized or if the
25/// configuration file cannot be loaded.
26#[instrument]
27pub async fn init(config: Option<&PathBuf>) -> Result<(), Error> {
28    let mut config = Config::load(config)?;
29    let creds = root_credentials(&config.database)?;
30    let coins = config
31        .coins
32        .iter()
33        .map(CoinConfig::as_coin)
34        .collect::<Vec<_>>();
35
36    config
37        .database
38        .init_schema(creds, coins.as_slice())
39        .await
40        .map_err(Error::Ohlcv)
41}