Skip to content

Commit

Permalink
feat: add project and and rework data storing
Browse files Browse the repository at this point in the history
  • Loading branch information
dancixx committed May 21, 2024
1 parent bcca2ca commit d8a807a
Show file tree
Hide file tree
Showing 17 changed files with 185 additions and 127 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"editor.semanticHighlighting.enabled": false
},
"rust-analyzer.rustfmt.overrideCommand": ["leptosfmt", "--stdin", "--rustfmt"],
"rust-analyzer.procMacro.attributes.enable": true,
"editor.tokenColorCustomizations": {
"[LaserWave High Contrast]": {
"textMateRules": [
Expand Down
5 changes: 5 additions & 0 deletions common/src/types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
use std::collections::BTreeMap;

pub mod pgsql;

pub type BTreeStore = BTreeMap<String, String>;
pub type BTreeVecStore = BTreeMap<String, Vec<String>>;

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ anyhow = "1.0.83"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
ahash = { version = "0.8.11", features = ["serde"] }
bincode = "1.3.3"



Expand Down
9 changes: 6 additions & 3 deletions src-tauri/src/dbs/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ use std::collections::BTreeMap;
use tauri::{Result, State};

use crate::AppState;
use common::types::BTreeVecStore;

#[tauri::command(rename_all = "snake_case")]
pub async fn project_db_select(app_state: State<'_, AppState>) -> Result<BTreeMap<String, String>> {
pub async fn project_db_select(app_state: State<'_, AppState>) -> Result<BTreeVecStore> {
let project_db = app_state.project_db.lock().await;
let db = project_db.clone().unwrap();
let mut projects = BTreeMap::new();
Expand All @@ -20,7 +21,7 @@ pub async fn project_db_select(app_state: State<'_, AppState>) -> Result<BTreeMa

let project = (
String::from_utf8(project.0.to_vec()).unwrap(),
String::from_utf8(project.1.to_vec()).unwrap(),
bincode::deserialize(&project.1).unwrap(),
);
projects.insert(project.0, project.1);
}
Expand All @@ -30,11 +31,13 @@ pub async fn project_db_select(app_state: State<'_, AppState>) -> Result<BTreeMa
#[tauri::command(rename_all = "snake_case")]
pub async fn project_db_insert(
project_id: &str,
project_details: &str,
project_details: Vec<String>,
app_state: State<'_, AppState>,
) -> Result<()> {
let project_db = app_state.project_db.lock().await;
let db = project_db.clone().unwrap();
let project_details = bincode::serialize(&project_details).unwrap();
// project_id - [driver, user, password, host, port]
db.insert(project_id, project_details).unwrap();
Ok(())
}
Expand Down
25 changes: 11 additions & 14 deletions src-tauri/src/drivers/pgsql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{utils::reflective_get, AppState};
#[tauri::command(rename_all = "snake_case")]
pub async fn pgsql_connector(
project_id: &str,
key: Option<&str>,
key: Option<[&str; 4]>,
app: AppHandle,
) -> Result<ProjectConnectionStatus> {
let app_state = app.state::<AppState>();
Expand All @@ -26,24 +26,21 @@ pub async fn pgsql_connector(
}

let key = match key {
Some(key) => key.to_string(),
Some(key) => format!(
"user={} password={} host={} port={}",
key[0], key[1], key[2], key[3]
),
None => {
let projects_db = app_state.project_db.lock().await;
let projects_db = projects_db.as_ref().unwrap();
let project_details = projects_db.get(project_id).unwrap().unwrap().to_vec();
let project_details = String::from_utf8(project_details).unwrap();
let project_details = project_details.split(":").collect::<Vec<&str>>();
let project_details = project_details
.into_iter()
.skip(1)
.map(|s| {
let kv = s.split('=').collect::<Vec<&str>>();
kv[1].to_owned()
})
.collect::<Vec<String>>();
let project_details = projects_db.get(project_id).unwrap();
let project_details = match project_details {
Some(bytes) => bincode::deserialize::<Vec<String>>(&bytes).unwrap(),
_ => Vec::new(),
};
let project_details = format!(
"user={} password={} host={} port={}",
project_details[0], project_details[1], project_details[2], project_details[3]
project_details[1], project_details[2], project_details[3], project_details[4]
);
project_details
}
Expand Down
8 changes: 7 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use crate::{
performane::Performance,
sidebar::index::Sidebar,
store::{
atoms::{QueryPerformanceAtom, QueryPerformanceContext, RunQueryAtom, RunQueryContext},
atoms::{
PgsqlConnectionDetailsAtom, PgsqlConnectionDetailsContext, QueryPerformanceAtom,
QueryPerformanceContext, RunQueryAtom, RunQueryContext,
},
projects::ProjectsStore,
queries::QueriesStore,
tabs::TabsStore,
Expand All @@ -29,6 +32,9 @@ pub fn App() -> impl IntoView {
RwSignal::new(VecDeque::<QueryPerformanceAtom>::new()),
);
provide_context::<RunQueryContext>(RwSignal::new(RunQueryAtom::default()));
provide_context::<PgsqlConnectionDetailsContext>(RwSignal::new(
PgsqlConnectionDetailsAtom::default(),
));
provide_context(TabsStore::default());

view! {
Expand Down
5 changes: 1 addition & 4 deletions src/dashboard/query_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ pub const MODE_ID: &str = "pgsql";
#[component]
pub fn QueryEditor(index: usize) -> impl IntoView {
let tabs_store = expect_context::<TabsStore>();
let active_project = move || match tabs_store.selected_projects.get().get(index) {
Some(project) => Some(project.clone()),
_ => None,
};
let active_project = move || tabs_store.selected_projects.get().get(index).cloned();
let projects_store = expect_context::<ProjectsStore>();
let project_driver = projects_store.select_driver_by_project(active_project().as_deref());
let tabs_store_rc = Rc::new(RefCell::new(tabs_store));
Expand Down
31 changes: 19 additions & 12 deletions src/databases/pgsql/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ use crate::{
InvokePgsqlRunQueryArgs,
},
store::{
atoms::{QueryPerformanceAtom, QueryPerformanceContext, RunQueryAtom, RunQueryContext},
atoms::{
PgsqlConnectionDetailsContext, QueryPerformanceAtom, QueryPerformanceContext, RunQueryAtom,
RunQueryContext,
},
tabs::TabsStore,
},
};
Expand Down Expand Up @@ -48,12 +51,16 @@ impl<'a> Pgsql<'a> {
self
.status
.update(|prev| *prev = ProjectConnectionStatus::Connecting);
let connection_string = self.generate_connection_string();
let status = invoke::<_, ProjectConnectionStatus>(
Invoke::PgsqlConnector.as_ref(),
&InvokePgsqlConnectorArgs {
project_id: &self.project_id.get(),
key: Some(&connection_string),
key: Some([
self.user.unwrap(),
self.password.unwrap(),
self.host.unwrap(),
self.port.unwrap(),
]),
},
)
.await
Expand Down Expand Up @@ -158,15 +165,15 @@ impl<'a> Pgsql<'a> {
self.port = Some(port);
}

fn generate_connection_string(&self) -> String {
let connection_string = format!(
"user={} password={} host={} port={}",
self.user.as_ref().unwrap(),
self.password.as_ref().unwrap(),
self.host.as_ref().unwrap(),
self.port.as_ref().unwrap(),
);
connection_string
pub fn edit_connection_details(&self) {
let atom = expect_context::<PgsqlConnectionDetailsContext>();
atom.update(|prev| {
prev.project_id = self.project_id.get().clone();
prev.user = self.user.unwrap().to_string();
prev.password = self.password.unwrap().to_string();
prev.host = self.host.unwrap().to_string();
prev.port = self.port.unwrap().to_string();
});
}
}

39 changes: 21 additions & 18 deletions src/databases/pgsql/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use leptos_icons::*;
use leptos_toaster::{Toast, ToastId, ToastVariant, Toasts};

use super::{driver::Pgsql, schema::Schema};
use crate::store::{projects::ProjectsStore, tabs::TabsStore};
use crate::{
modals::add_pgsql_connection::AddPgsqlConnection,
store::{projects::ProjectsStore, tabs::TabsStore},
};
use common::enums::ProjectConnectionStatus;

#[component]
Expand All @@ -14,29 +17,18 @@ pub fn Pgsql(project_id: String) -> impl IntoView {
let tabs_store = expect_context::<TabsStore>();
let projects_store = expect_context::<ProjectsStore>();
let project_details = projects_store.select_project_by_name(&project_id).unwrap();
let connection_params = project_details
.split(':')
.map(String::from)
.collect::<Vec<String>>();
let connection_params = connection_params
.into_iter()
.skip(1)
.map(|s| {
let kv = s.split('=').collect::<Vec<&str>>();
kv[1].to_owned()
})
.collect::<Vec<String>>();
let connection_params = Box::leak(connection_params.into_boxed_slice());
let project_details = Box::leak(Box::new(project_details));
// [user, password, host, port]
let mut pgsql = Pgsql::new(project_id.clone().to_string());
{
pgsql.load_connection_details(
&connection_params[0],
&connection_params[1],
&connection_params[2],
&connection_params[3],
&project_details[1],
&project_details[2],
&project_details[3],
&project_details[4],
);
}
let show = create_rw_signal(false);
let toast_context = expect_context::<Toasts>();
let create_toast = move |variant: ToastVariant, title: String| {
let toast_id = ToastId::new();
Expand Down Expand Up @@ -80,6 +72,7 @@ pub fn Pgsql(project_id: String) -> impl IntoView {

view! {
<Provider value=pgsql>
<AddPgsqlConnection show=show/>
<div class="pl-1 text-xs">
<div class="flex flex-row justify-between items-center">
<button
Expand Down Expand Up @@ -131,6 +124,16 @@ pub fn Pgsql(project_id: String) -> impl IntoView {

<Icon icon=icondata::HiCircleStackOutlineLg width="12" height="12"/>
</button>
<button
class="p-1 rounded-full hover:bg-gray-200"
on:click=move |_| {
pgsql.edit_connection_details();
show.set(true);
}
>

<Icon icon=icondata::HiPencilSquareOutlineLg width="12" height="12"/>
</button>
<button
class="p-1 rounded-full hover:bg-gray-200"
on:click={
Expand Down
4 changes: 2 additions & 2 deletions src/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl AsRef<str> for Invoke {
#[derive(Serialize, Deserialize)]
pub struct InvokePgsqlConnectorArgs<'a> {
pub project_id: &'a str,
pub key: Option<&'a str>,
pub key: Option<[&'a str; 4]>,
}

#[derive(Serialize, Deserialize)]
Expand All @@ -85,7 +85,7 @@ pub struct InvokePgsqlRunQueryArgs<'a> {
#[derive(Serialize, Deserialize)]
pub struct InvokeProjectDbInsertArgs<'a> {
pub project_id: &'a str,
pub project_details: &'a str,
pub project_details: Vec<String>,
}

#[derive(Serialize, Deserialize)]
Expand Down
49 changes: 48 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
use syn::{parse_macro_input, Data, DeriveInput, Fields, ItemFn};

#[proc_macro_attribute]
pub fn set_running_query(_attr: TokenStream, item: TokenStream) -> TokenStream {
Expand Down Expand Up @@ -30,3 +30,50 @@ pub fn set_running_query(_attr: TokenStream, item: TokenStream) -> TokenStream {
TokenStream::from(gen)
}

#[proc_macro_derive(StructIntoIterator)]
pub fn into_iterator_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);

let name = &input.ident;

let fields = match input.data {
Data::Struct(data_struct) => match data_struct.fields {
Fields::Named(fields_named) => fields_named.named,
_ => panic!("IntoIterator can only be derived for structs with named fields."),
},
_ => panic!("IntoIterator can only be derived for structs."),
};

let field_names = fields.iter().filter_map(|f| {
let field_type = &f.ty;
if let syn::Type::Path(type_path) = field_type {
if type_path
.path
.segments
.iter()
.any(|segment| segment.ident == "String")
{
return f.ident.as_ref();
}
}
None
});

let gen = quote! {
impl IntoIterator for #name {
type Item = String;
type IntoIter = std::vec::IntoIter<String>;

fn into_iter(self) -> Self::IntoIter {
let mut vec = Vec::new();
#(
vec.push(self.#field_names.to_owned());
)*
vec.into_iter()
}
}
};

gen.into()
}

Loading

0 comments on commit d8a807a

Please sign in to comment.