Skip to content

Commit

Permalink
refactor(back): separate sqlite specific queries
Browse files Browse the repository at this point in the history
  • Loading branch information
kareemmahlees committed Dec 17, 2023
1 parent 202037e commit d8c7e3b
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 32 deletions.
1 change: 1 addition & 0 deletions src-tauri/src/drivers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod sqlite;
14 changes: 14 additions & 0 deletions src-tauri/src/drivers/sqlite.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
pub fn get_tables_sqlite() -> &'static str {
"SELECT name
FROM sqlite_schema
WHERE type ='table'
AND name NOT LIKE 'sqlite_%';" as _
}

pub fn get_columns_definition_sqlite(table_name: String) -> String {
format!(
"select name,type,\"notnull\",dflt_value,pk from pragma_table_info('{}');",
table_name
)
.to_string()
}
5 changes: 3 additions & 2 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod connection;
mod drivers;
mod row;
mod table;
mod utils;
Expand All @@ -10,7 +11,7 @@ use connection::{
connections_exist, create_connection_record, establish_connection, get_connection_details,
get_connections, test_connection,
};
use row::{create_row, delete_row, get_rows, update_row};
use row::{create_row, delete_rows, get_rows, update_row};
use sqlx::Pool;
use table::{get_columns_definition, get_tables};
use tokio::sync::Mutex;
Expand All @@ -37,7 +38,7 @@ fn main() {
get_connection_details,
get_tables,
get_rows,
delete_row,
delete_rows,
get_columns_definition,
create_row,
update_row,
Expand Down
18 changes: 11 additions & 7 deletions src-tauri/src/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub async fn get_rows(
}

#[tauri::command]
pub async fn delete_row(
pub async fn delete_rows(
connection: State<'_, DbInstance>,
pk_col_name: String,
row_pk_values: Vec<JsonValue>,
Expand All @@ -44,18 +44,22 @@ pub async fn delete_row(
let long_lived = connection.pool.lock().await;
let conn = long_lived.as_ref().unwrap();

let params = format!("?{}", ",?".repeat(row_pk_values.len() - 1));
let query_str = format!("DELETE FROM {table_name} WHERE {pk_col_name} in ({params});",);
let mut query = sqlx::query(&query_str);
let mut params: String = Default::default();
for val in row_pk_values.iter() {
// this should cover most cases of primary keys
if val.is_number() {
query = query.bind(val.as_i64().unwrap());
params.push_str(format!("{},", val.as_i64().unwrap()).as_str());
} else {
query = query.bind(val.as_str().unwrap());
params.push_str(format!("{},", val.as_str().unwrap()).as_str());
}
}
let result = query.execute(conn).await.unwrap();
params.pop(); // to remove the last trailing comma

let query_str = format!("DELETE FROM {table_name} WHERE {pk_col_name} in ({params});",);
let result = sqlx::query(&query_str)
.execute(conn)
.await
.map_err(|_| "Failed to delete rows".to_string())?;
Ok(result.rows_affected())
}

Expand Down
49 changes: 27 additions & 22 deletions src-tauri/src/table.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::drivers::sqlite::{get_columns_definition_sqlite, get_tables_sqlite};
use crate::utils;
use crate::utils::Drivers;
use crate::DbInstance;
use serde_json::Value as JsonValue;
use serde_json::Value::{Bool as JsonBool, String as JsonString};
Expand All @@ -8,17 +10,17 @@ use tauri::State;

#[tauri::command]
pub async fn get_tables(connection: State<'_, DbInstance>) -> Result<Option<Vec<String>>, ()> {
let long_lived = connection.pool.lock().await;
let conn = long_lived.as_ref().unwrap();
let rows = sqlx::query(
"SELECT name
FROM sqlite_schema
WHERE type ='table'
AND name NOT LIKE 'sqlite_%';",
)
.fetch_all(conn)
.await
.unwrap();
let conn_long_lived = connection.pool.lock().await;
let conn = conn_long_lived.as_ref().unwrap();
let driver_long_lived = connection.driver.lock().await;
let driver = driver_long_lived.as_ref().unwrap();

let query_string = match driver {
Drivers::SQLite => get_tables_sqlite(),
Drivers::PostgreSQL => todo!(),
Drivers::MySQL => todo!(),
};
let rows = sqlx::query(query_string).fetch_all(conn).await.unwrap();
if rows.is_empty() {
return Ok(None);
}
Expand All @@ -34,18 +36,21 @@ pub async fn get_columns_definition(
connection: State<'_, DbInstance>,
table_name: String,
) -> Result<HashMap<String, HashMap<String, JsonValue>>, String> {
let long_lived = connection.pool.lock().await;
let conn = long_lived.as_ref().unwrap();
let conn_long_lived = connection.pool.lock().await;
let conn = conn_long_lived.as_ref().unwrap();

let driver_long_lived = connection.driver.lock().await;
let driver = driver_long_lived.as_ref().unwrap();

let rows = sqlx::query(
format!(
"select name,type,\"notnull\",dflt_value,pk from pragma_table_info('{table_name}');"
)
.as_str(),
)
.fetch_all(conn)
.await
.map_err(|err| err.to_string())?;
let query_string = match driver {
Drivers::SQLite => get_columns_definition_sqlite(table_name),
Drivers::PostgreSQL => todo!(),
Drivers::MySQL => todo!(),
};
let rows = sqlx::query(query_string.as_str())
.fetch_all(conn)
.await
.map_err(|err| err.to_string())?;

let mut result = HashMap::<String, HashMap<String, JsonValue>>::new();

Expand Down
2 changes: 1 addition & 1 deletion src/app/dashboard/details/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const deleteRows = async (

if (rows.length <= 0) return

const command = invoke<number>("delete_row", {
const command = invoke<number>("delete_rows", {
pkColName: column.columnDef.meta?.name,
rowPkValues: rows,
tableName
Expand Down

0 comments on commit d8c7e3b

Please sign in to comment.