Skip to content

Commit

Permalink
Mostro database automatic creation (#411)
Browse files Browse the repository at this point in the history
* New way to create automatically db of mostro - config template copied automatically

* Update src/db.rs

rabbit suggestion

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update src/db.rs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Fix Keys::parse() call

* feat: create mostro.db automatically at first mostro run

* chore: remove patch file

* fix: added check to migrations folder existence

* Fix: remove a lot o bloat code - discovered cargo can do migration with migrate! macro

* Update src/db.rs

LGTM

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Rabbit improvements

* Fix: possible typo in db query

* Create directory and files without asking

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>
  • Loading branch information
3 people authored Jan 3, 2025
1 parent bdc77d3 commit 98a6b4d
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 104 deletions.
57 changes: 0 additions & 57 deletions epa.patch

This file was deleted.

49 changes: 14 additions & 35 deletions src/cli/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ 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};
use std::io::Write;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
#[cfg(windows)]
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::process;

#[cfg(windows)]
fn has_trailing_slash(p: &Path) -> bool {
Expand Down Expand Up @@ -198,39 +196,20 @@ 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 {}",
if std::fs::create_dir(settings_dir_default.clone()).is_ok() {
tracing::info!("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()?;
}
tracing::info!(
"Created settings file based on template and copied to {} directory",
settings_dir_default.display()
);
print!("Are you sure? (Y/n) > ");

// Ask user confirm for default folder
let mut user_input = String::new();
let _input = stdin();

stdout().flush()?;

let mut answer = stdin().lock();
answer.read_line(&mut user_input)?;

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());
process::exit(0);
}
"n" => {
println!("Try again with another folder...");
process::exit(0);
}
&_ => {
println!("Can't get what you're saying!");
process::exit(0);
}
};
} else {
// Set path
Ok(settings_dir_default)
return Ok(settings_dir_default);
}
// Set path
Ok(settings_dir_default)
}
74 changes: 65 additions & 9 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,85 @@
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 uuid::Uuid;

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

pub async fn connect() -> Result<Pool<Sqlite>, sqlx::Error> {
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).map_err(|e| {
anyhow::anyhow!(
"Failed to create database file at {}: {}",
db_path.display(),
e
)
})?;
match SqlitePool::connect(&db_url).await {
Ok(pool) => {
tracing::info!(
"Successfully created Mostro database file at {}",
db_path.display(),
);
match sqlx::migrate!().run(&pool).await {
Ok(_) => (),
Err(e) => {
// Clean up the created file on migration failure
if let Err(cleanup_err) = std::fs::remove_file(db_path) {
tracing::error!(
error = %cleanup_err,
path = %db_path.display(),
"Failed to create database connection"
);
}
return Err(anyhow::anyhow!(
"Failed to create database connection at {}: {}",
db_path.display(),
e
));
}
}
pool
}
Err(e) => {
tracing::error!(
error = %e,
path = %db_path.display(),
"Failed to create database connection"
);
return Err(anyhow::anyhow!(
"Failed to create database connection at {}: {}",
db_path.display(),
e
));
}
}
} else {
SqlitePool::connect(&db_url).await.map_err(|e| {
anyhow::anyhow!(
"Failed to connect to existing database at {}: {}",
db_path.display(),
e
)
})?
};
Ok(conn)
}

pub async fn edit_buyer_pubkey_order(
Expand Down Expand Up @@ -273,7 +329,7 @@ pub async fn find_held_invoices(pool: &SqlitePool) -> anyhow::Result<Vec<Order>>
r#"
SELECT *
FROM orders
WHERE invoice_held_at !=0 true AND status == 'active'
WHERE invoice_held_at !=0 AND status == 'active'
"#,
)
.fetch_all(pool)
Expand Down
10 changes: 7 additions & 3 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,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

0 comments on commit 98a6b4d

Please sign in to comment.