Skip to content

Commit

Permalink
feat: impl store with sea orm
Browse files Browse the repository at this point in the history
  • Loading branch information
opeolluwa committed Mar 21, 2024
1 parent 98688f7 commit 0c1a147
Show file tree
Hide file tree
Showing 15 changed files with 462 additions and 356 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ENV=development
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ENV=development
26 changes: 13 additions & 13 deletions entity/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
// //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15

use sea_orm::entity::prelude::*;
// use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "config")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Option<i32>,
pub smtp_username: Option<String>,
pub smtp_password: Option<String>,
}
// #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
// #[sea_orm(table_name = "config")]
// pub struct Model {
// #[sea_orm(primary_key, auto_increment = false)]
// pub id: Option<i32>,
// pub smtp_username: Option<String>,
// pub smtp_password: Option<String>,
// }

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
// #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
// pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
// impl ActiveModelBehavior for ActiveModel {}
30 changes: 15 additions & 15 deletions entity/src/emails.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
// //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15

use sea_orm::entity::prelude::*;
// use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "emails")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Option<String>,
pub name: Option<String>,
pub email: Option<String>,
#[sea_orm(column_type = "Binary(BlobSize::Blob(None))", nullable)]
pub message: Option<Vec<u8>>,
}
// #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
// #[sea_orm(table_name = "emails")]
// pub struct Model {
// #[sea_orm(primary_key, auto_increment = false)]
// pub id: Option<String>,
// pub name: Option<String>,
// pub email: Option<String>,
// #[sea_orm(column_type = "Binary(BlobSize::Blob(None))", nullable)]
// pub message: Option<Vec<u8>>,
// }

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
// #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
// pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
// impl ActiveModelBehavior for ActiveModel {}
17 changes: 5 additions & 12 deletions entity/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
}
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
#[cfg(test)]
mod tests {
use super::*;
pub mod prelude;

#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
pub mod config;
pub mod emails;
pub mod store;
4 changes: 2 additions & 2 deletions entity/src/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
pub use super::config::Entity as Config;
pub use super::emails::Entity as Emails;
// pub use super::config::Entity as Config;
// pub use super::emails::Entity as Emails;
pub use super::store::Entity as Store;
4 changes: 1 addition & 3 deletions migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20240321_172635_create_store_table::Migration),
]
vec![Box::new(m20240321_172635_create_store_table::Migration)]
}
}
188 changes: 117 additions & 71 deletions src/commands/store.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,124 @@
// use crate::{database::Store, style::PrintColoredText};
// use bcrypt::{hash, verify, DEFAULT_COST};
// use clap::{Args, Subcommand};
// use serde::{Deserialize, Serialize};
use std::time::Duration;

// #[derive(Args, Debug, Serialize, Deserialize)]
// pub struct StoreCommands {
// #[clap(short, long, value_parser)]
// pub key: Option<String>,
// #[clap(short, long, value_parser)]
// pub value: Option<String>,
// #[command(subcommand)]
// pub subcommands: Option<SubCommands>,
// }
use crate::{style::PrintColoredText, DB_URL};
use anyhow::{Ok, Result};
use bcrypt::{hash, verify, DEFAULT_COST};
use chrono::Local;
use clap::{Args, Subcommand};
use entity::store::{self, Entity as Store};
use sea_orm::{ActiveValue::Set, ConnectOptions, Database, DatabaseConnection, EntityTrait};
use serde::{Deserialize, Serialize};
#[derive(Args, Debug, Serialize, Deserialize)]
pub struct StoreCommands {
#[clap(short, long, value_parser)]
pub key: Option<String>,
#[clap(short, long, value_parser)]
pub value: Option<String>,
#[command(subcommand)]
pub subcommands: Option<SubCommands>,
}

// #[derive(Debug, Subcommand, Serialize, Deserialize)]
// pub enum SubCommands {
// /// list the stored data
// List,
// /// delete a key
// Delete { key: String },
// /// clear all stored data
// Clear,
// /// update the value of a key
// Update { key: String, value: String },
// // secure the stored data
// // Secure,
// }
#[derive(Debug, Subcommand, Serialize, Deserialize)]
pub enum SubCommands {
/// list the stored data
List,
/// delete a key
Delete { key: String },
/// clear all stored data
Clear,
/// update the value of a key
Update { key: String, value: String },
// secure the stored data
// Secure,
}

// impl StoreCommands {
// pub async fn parse(&self) {
// if let Some(command) = &self.subcommands {
// match command {
// SubCommands::List => Self::list().await,
// SubCommands::Delete { key } => Self::delete(key).await,
// SubCommands::Clear => Self::clear().await,
// SubCommands::Update { key, value } => Self::update(key, value).await,
// // SubCommands::Secure => Self::secure().await,
// }
// } else {
// let Some(key) = &self.key else {
// PrintColoredText::error("Invalid key");
// return;
// };
// let Some(value) = &self.value else {
// PrintColoredText::error("Invalid value");
// return;
// };
// Store::new(key, value).save().await.unwrap();
// let message = format!("{key} successfully stored");
// PrintColoredText::success(&message);
// }
// }
// async fn list() {
// let data = crate::database::Store::find().await;
// if data.is_empty() {
// PrintColoredText::error("no data found");
// return;
// }
// let data = crate::database::Database(data);
// println!("{}", data);
// }
impl StoreCommands {
pub async fn parse(&self) -> Result<()> {
if let Some(command) = &self.subcommands {
match command {
SubCommands::List => Self::list().await,
SubCommands::Delete { key } => Self::delete(key).await,
SubCommands::Clear => Self::clear().await,
SubCommands::Update { key, value } => Self::update(key, value).await,
// SubCommands::Secure => Self::secure().await,
}
} else {
let Some(key) = &self.key else {
PrintColoredText::error("Invalid key");
std::process::exit(0);
};
let Some(value) = &self.value else {
PrintColoredText::error("Invalid value");
std::process::exit(0);
};
let date_added = Local::now().to_rfc2822();
let last_updated = Local::now().to_rfc2822();
let record = entity::store::ActiveModel {
key: Set(key.to_string()),
value: Set(value.to_string()),
last_updated: Set(date_added),
date_added: Set(last_updated),
..Default::default()
};

// async fn delete(key: &str) {
// crate::database::Store::remove(key).await;
// }
let _ = store::Entity::insert(record)
.exec(&Self::db_connection().await?)
.await?;

// async fn update(key: &str, value: &str) {
// let _ = crate::database::Store::update(key, value).await.ok();
// Store::new(key, value).save().await.unwrap();
let message = format!("{key} successfully stored");
PrintColoredText::success(&message);
Ok(())
}
}
/// find all
async fn list() -> Result<()> {
let data: Vec<entity::store::Model> =
Store::find().all(&Self::db_connection().await?).await?;

// let message = format!("{key} successfully updated");
// PrintColoredText::success(&message);
// }
if data.is_empty() {
PrintColoredText::error("no data found");
std::process::exit(0)
}
// TODO: impl display
println!("{:?}", data);
Ok(())
}

// async fn clear() {
// crate::database::Store::clear().await;
// }
// }
/// remove record from the store
async fn delete(key: &str) -> Result<()> {

Ok(())
}

/// update recoird n the store
async fn update(key: &str, value: &str) -> Result<()> {
// let _ = crate::database::Store::update(key, value).await.ok();

let message = format!("{key} successfully updated");
PrintColoredText::success(&message);
Ok(())
}

async fn clear() -> Result<()> {
// crate::database::Store::clear().await;
Ok(())
}

/// the databse connections
async fn db_connection() -> Result<DatabaseConnection> {
// the databse connection options/configuration
let mut opt = ConnectOptions::new(DB_URL.as_str());
opt.max_connections(100)
.min_connections(5)
.connect_timeout(Duration::from_secs(8))
.acquire_timeout(Duration::from_secs(8))
.idle_timeout(Duration::from_secs(8))
.max_lifetime(Duration::from_secs(8))
.sqlx_logging(true);

// the database instance
let db = Database::connect(opt).await?;
Ok(db)
}
}
65 changes: 65 additions & 0 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// use entity::store::Entity as StoreEntity;
// use anyhow::Result;
// use std::collections::HashMap;
// use uuid::Uuid;

// /// the table trait allows the operation of curd endpoint on tables
// pub trait Store {
// /// create an instance of the store
// fn new(key:&str, value:&str ) -> Self;
// /// find one by id
// fn find_one(&self,id:&str) -> Result<Self, ()> where Self: Sized;
// /// find all records in the table
// fn find_all() -> Result<Vec<Self>, ()> where Self: Sized;
// ///delete one record in the table
// fn delete_one(&self,id:&str) -> Result<(), ()> where Self: Sized;
// /// delete all records in the table
// fn delete_all() -> Result<(), ()> where Self: Sized;
// /// update a record in the table
// fn update(&self, fields: HashMap<String, String>) -> Result<(), ()> where Self: Sized;

// }

// impl Default for StoreEntity {
// fn default() -> Self {
// StoreEntity::
// }
// }
// impl Store for StoreEntity {
// fn new(key:&str, value:&str) -> Self{
// Self {
// id:
// }
// }

// fn find_one(&self, id: &str) -> Result<Self, ()> where Self: Sized {
// // implementation goes here
// todo!()

// }

// fn find_all() -> Result<Vec<Self>, ()> where Self: Sized {
// // implementation goes here
// todo!()

// }

// fn delete_one(&self, id: &str) -> Result<(), ()> where Self: Sized {
// // implementation goes here
// todo!()

// }

// fn delete_all() -> Result<(), ()> where Self: Sized {
// // implementation goes here
// todo!()

// }

// fn update(&self, fields: HashMap<String, String>) -> Result<(), ()> where Self: Sized {
// // implementation goes here
// todo!()

// }

// }
Loading

0 comments on commit 0c1a147

Please sign in to comment.