Skip to content

Commit

Permalink
Merge pull request #17 from opeolluwa/dev
Browse files Browse the repository at this point in the history
refactor
  • Loading branch information
opeolluwa authored Sep 6, 2023
2 parents 1a924e6 + 1f7fa5f commit 83204a1
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 891 deletions.
722 changes: 8 additions & 714 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 0 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ include_dir = "0.7.3"
indicatif = "0.17.6"
lazy_static = "1.4.0"
lettre = "0.10.4"
# migration = {path = "migration"}# depends on your needs
serde = {versio = "1.0.185", features = ["derive"]}
sqlx = {version = "0.6.2", features = ["runtime-tokio-native-tls", "sqlite"]}
tokio = {version = "1.20.0", features = ["macros"]}
uuid = {version = "1.4.1", features = ["v4", "fast-rng", "macro-diagnostics"]}

[workspace]
members = ["migration"]
22 changes: 0 additions & 22 deletions migration/Cargo.toml

This file was deleted.

41 changes: 0 additions & 41 deletions migration/README.md

This file was deleted.

6 changes: 2 additions & 4 deletions src/commands/gitignore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,8 @@ impl GitIgnoreCommands {
if let Some(file_content) = file_path {
let mut file = File::create(path).unwrap();
file.write_all(file_content.contents()).unwrap();
} else {
}
} else {
}
}
}
}
}

Expand Down
1 change: 0 additions & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ pub mod email;
pub mod gitignore;
pub mod readme;
pub mod sms;
pub mod store;
55 changes: 0 additions & 55 deletions src/commands/store.rs

This file was deleted.

97 changes: 57 additions & 40 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Display};

use chrono::Local;
use serde::{Deserialize, Serialize};
use sqlx::{migrate::MigrateDatabase, FromRow, Pool, Row, Sqlite, SqlitePool};
use sqlx::{
migrate::MigrateDatabase, sqlite::SqliteQueryResult, FromRow, Pool, Row, Sqlite, SqlitePool,
};
use uuid::Uuid;

use crate::{style::PrintColoredText, DB_URL};
pub struct Database;
pub struct Database(pub Vec<Store>);
impl std::fmt::Display for Database {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.iter().try_fold((), |_, data| write!(f, "{}", data))
}
}
#[allow(unused)]

impl Database {
/*
initialize the database connection
this will create a new sqlite database in the OS home directory
*/
pub async fn init() {
if !Sqlite::database_exists(&DB_URL).await.unwrap_or(false) {
match Sqlite::create_database(&DB_URL).await {
Expand All @@ -28,33 +39,17 @@ impl Database {
let db = SqlitePool::connect(&DB_URL).await.unwrap();
let _ = sqlx::query(store_create_table).execute(&db).await.unwrap();
let _ = sqlx::query(email_create_table).execute(&db).await.unwrap();

/* let result = sqlx::query("INSERT INTO store (id, key, value, date) VALUES (?,?,?,?)")
.bind("bobby")
.execute(&db)
.await
.unwrap();
println!("Query result: {:?}", result);
let user_results = sqlx::query_as::<_, User>("SELECT id, name FROM users")
.fetch_all(&db)
.await
.unwrap();
for user in user_results {
println!("[{}] name: {}", user.id, &user.name);
} */
}

// return connection to the database;
pub async fn conn() -> Pool<Sqlite> {
SqlitePool::connect(&DB_URL).await.unwrap()
}

// get the tables in the database
pub async fn tables() -> HashMap<usize, String> {
let db = Self::conn().await;
// tell us the available tables
let result = sqlx::query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(250) NOT NULL);").execute(&db).await.unwrap();
println!("Create user table result: {:?}", result);
let result = sqlx::query(
let result: Vec<sqlx::sqlite::SqliteRow> = sqlx::query(
"SELECT name
FROM sqlite_schema
WHERE type ='table'
Expand All @@ -69,22 +64,15 @@ impl Database {
let key = idx;
let value = row.get::<String, &str>("name");
tables.insert(key, value.to_owned());
// println!("[{}]: {:?}", idx, row.get::<String, &str>("name"));
}

tables
}
}

#[derive(Clone, FromRow, Debug)]
pub struct User {
pub id: i64,
pub name: String,
}

/// for deserializing data from the database
#[derive(Clone, FromRow, Debug, Serialize, Deserialize)]
pub struct StoreModel {
pub struct Store {
pub id: String,
pub key: String,
pub value: String,
Expand All @@ -93,7 +81,7 @@ pub struct StoreModel {
}

/// auto generate the date and Id
impl Default for StoreModel {
impl Default for Store {
fn default() -> Self {
Self {
id: Uuid::new_v4().to_string(), //6971184f-7ae0-4bbf-ab3c-5ff6712eb8f9
Expand All @@ -104,8 +92,17 @@ impl Default for StoreModel {
}
}
}
impl Display for Store {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"\nKEY: {:30}\nVALUE: {}\nDATE ADDED: {}\nLAST UPDATED: {}\n",
self.key, self.value, self.date_added, self.last_updated
)
}
}

impl StoreModel {
impl Store {
/// create a new key-value pair
pub fn new(key: &str, value: &str) -> Self {
let data = Self {
Expand Down Expand Up @@ -162,23 +159,43 @@ impl StoreModel {
Ok(Self { ..self.clone() })
}

///TODO: update the key
pub fn set(key: &str, value: &str) -> Self {
let data = Self {
key: key.to_string(),
value: value.to_string(),
..Default::default()
};
Self { ..data }
/// update the key value pair
pub async fn update(key: &str, value: &str) -> Result<SqliteQueryResult, ()> {
// see if the data exist
let exist = Self::try_exist(key).await;
if !exist {
PrintColoredText::error("the provided key does not exist or has been removed");
return Err(());
}

let db = Database::conn().await;
let last_updated = Local::now().to_rfc2822();
let data =
sqlx::query("UPDATE store SET value =?, last_updated =? WHERE key = ? RETURNING *")
.bind(value.clone())
.bind(last_updated.clone())
.bind(key.clone())
.execute(&db)
.await
.unwrap();

Ok(data)
}

/// remove
pub async fn remove(key: &str) {
let key_exists = Self::try_exist(key).await;
if !key_exists {
PrintColoredText::error("the provided key does not exist or has been removed");
return;
}
let db = Database::conn().await;
let _ = sqlx::query_as::<_, Self>("DELETE * FROM store WHERE key = ?")
let _ = sqlx::query_as::<_, Self>("DELETE FROM store WHERE key = ?")
.bind(key)
.fetch_all(&db)
.await
.unwrap();
let message = format!("{key} removed successfully");
PrintColoredText::success(&message);
}
}
1 change: 0 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use include_dir::{include_dir, Dir};
pub const SOURCE_DIR: Dir = include_dir!("src/templates");
lazy_static! {
pub static ref DB_URL: std::string::String = {
// create the database in the home directory of the system
//create "utils" directory in the home dir and / save files to $HOME/utils;
let os_default_home_dir = dirs::home_dir().unwrap();
let db_path = format!(
Expand Down
Loading

0 comments on commit 83204a1

Please sign in to comment.