Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mostro database automatic creation #411

Merged
merged 13 commits into from
Jan 3, 2025
18 changes: 12 additions & 6 deletions src/cli/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use anyhow::{Error, Result};
use config::{Config, ConfigError, Environment, File};
use serde::Deserialize;
use std::ffi::OsString;
use std::fs;
use std::io::{stdin, stdout, BufRead, Write};
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
Expand Down Expand Up @@ -198,8 +197,8 @@ pub fn init_default_dir(config_path: Option<String>) -> Result<PathBuf> {

// If settings dir is not existing
if !folder_default {
println!(
"Creating .mostro default directory {}",
tracing::info!(
"Creating mostro default directory with path: {}",
settings_dir_default.display()
);
print!("Are you sure? (Y/n) > ");
Expand All @@ -215,9 +214,16 @@ pub fn init_default_dir(config_path: Option<String>) -> Result<PathBuf> {

match user_input.to_lowercase().as_str().trim_end() {
"y" | "" => {
fs::create_dir(settings_dir_default.clone())?;
println!("You have created mostro default directory!");
println!("Please, copy settings.tpl.toml and mostro.db too files in {} folder then edit settings file fields with right values (see README.md)", settings_dir_default.display());
if std::fs::create_dir(settings_dir_default.clone()).is_ok() {
tracing::info!("You have created mostro default directory!");
let mut config_file =
std::fs::File::create_new(settings_dir_default.join("settings.toml"))?;
let buf = include_bytes!("../../settings.tpl.toml");
config_file.write_all(buf)?;
config_file.flush()?;
}
println!("Copied template settings file to {} folder, please edit settings file fields with your values (see README.md)", settings_dir_default.display());
println!("Mostro database will be created automatically, but before complete correctly settings toml file");
process::exit(0);
}
"n" => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should create the default directory without asking, later we can add an option for the user to declare that directory on first start

Expand Down
60 changes: 52 additions & 8 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,73 @@
use crate::app::rate_user::{MAX_RATING, MIN_RATING};
use anyhow::Result;
use mostro_core::dispute::Dispute;
use mostro_core::order::Order;
use mostro_core::order::Status;
use mostro_core::user::User;
use nostr_sdk::prelude::*;
use sqlx::migrate::MigrateDatabase;
use sqlx::pool::Pool;
use sqlx::sqlite::SqliteRow;
use sqlx::Row;
use sqlx::Sqlite;
use sqlx::SqlitePool;
use std::path::Path;
use std::path::PathBuf;
use uuid::Uuid;

use crate::cli::settings::Settings;

pub async fn connect() -> Result<Pool<Sqlite>, sqlx::Error> {
fn migrations_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("migrations")
.to_path_buf()
}

// Get all migrations files
fn create_mostro_db() -> Result<Vec<String>> {
let mut tables = Vec::new();
if let Ok(files) = std::fs::read_dir(migrations_root()) {
for file in files.flatten() {
if let Some(file_name) = file.file_name().to_str() {
if file_name.ends_with(".sql") {
let table_content = std::fs::read_to_string(migrations_root().join(file_name))
.expect("Failed to read file");
tables.push(table_content);
}
}
}
}
Ok(tables)
}
arkanoider marked this conversation as resolved.
Show resolved Hide resolved

pub async fn connect() -> Result<Pool<Sqlite>> {
// Get mostro settings
let db_settings = Settings::get_db();
let mut db_url = db_settings.url;
db_url.push_str("mostro.db");
if !Sqlite::database_exists(&db_url).await.unwrap_or(false) {
panic!("Not database found, please create a new one first!");
}
let pool = SqlitePool::connect(&db_url).await?;

Ok(pool)
// Remove sqlite:// from db_url
let tmp = db_url.replace("sqlite://", "");
let db_path = Path::new(&tmp);
let conn = if !db_path.exists() {
let _file = std::fs::File::create_new(db_path).unwrap();
match SqlitePool::connect(&db_url).await {
Ok(pool) => {
tracing::info!("created mostro db file: {}", db_url);
if let Ok(tables) = create_mostro_db() {
for table in tables {
sqlx::query(&table).execute(&pool).await.unwrap();
}
}
pool
}
Err(e) => {
tracing::error!("Error creating mostro db file: {}", e);
return Err(anyhow::anyhow!("Error creating mostro db file: {}", e));
}
}
} else {
SqlitePool::connect(&db_url).await?
};
Ok(conn)
arkanoider marked this conversation as resolved.
Show resolved Hide resolved
}

pub async fn edit_buyer_pubkey_order(
Expand Down
10 changes: 7 additions & 3 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,13 @@ pub async fn send_dm(
pub fn get_keys() -> Result<Keys> {
let nostr_settings = Settings::get_nostr();
// nostr private key
let my_keys = Keys::parse(nostr_settings.nsec_privkey)?;

Ok(my_keys)
match Keys::parse(nostr_settings.nsec_privkey) {
Ok(my_keys) => Ok(my_keys),
Err(e) => {
tracing::error!("Failed to parse nostr private key: {}", e);
std::process::exit(1);
}
}
}

#[allow(clippy::too_many_arguments)]
Expand Down
Loading