Skip to content

Commit

Permalink
feat: run query and save in file
Browse files Browse the repository at this point in the history
  • Loading branch information
invm committed Oct 9, 2023
1 parent 90833cd commit 7eb7d86
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 25 deletions.
2 changes: 1 addition & 1 deletion src-tauri/src/database/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ impl ConnectedConnection {
}
}

pub async fn execute_query(&self, q: String) -> Result<Value> {
pub async fn execute_query(&self, q: &str) -> Result<Value> {
match &self.pool {
ConnectionPool::Mysql(pool) => engine::mysql::query::execute_query(pool, q),
// ConnectionPool::Postgres(_pool) => todo!(),
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/database/engine/mysql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ pub fn raw_query(mut conn: PooledConn, query: String) -> Result<serde_json::Valu
return Ok(result);
}

pub fn execute_query(pool: &Pool, query: String) -> Result<serde_json::Value> {
pub fn execute_query(pool: &Pool, query: &str) -> Result<serde_json::Value> {
let mut conn = pool.get_conn()?;
let mut results = conn.query_iter(&query)?;
let mut results = conn.query_iter(query)?;
let mut sets: Vec<ResultSet> = vec![];
while let Some(result_set) = results.iter() {
let affected_rows = result_set.affected_rows();
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/handlers/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub async fn enqueue_query(
if enqueued_ids.contains(&id) {
continue;
}
if auto_limit {
if auto_limit && !statement.to_lowercase().contains("limit") {
statement = format!("{} LIMIT 1000", statement);
}
let task = QueryTask::new(conn.clone(), statement, id, tab_idx, idx);
Expand Down Expand Up @@ -90,7 +90,7 @@ pub async fn execute_query(
_auto_limit: bool,
) -> CommandResult<Value> {
let connection = app_handle.acquire_connection(conn_id);
let result = connection.execute_query(query).await?;
let result = connection.execute_query(&query).await?;
Ok(result)
}

Expand Down
74 changes: 57 additions & 17 deletions src-tauri/src/queues/query.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
use crate::database::connections::ConnectedConnection;
use crate::utils::init::write_query;
use anyhow::Result;
use serde::Deserialize;
use serde::Serialize;
use tauri::Manager;
use tokio::sync::mpsc;
use tracing::info;

pub enum Events {
QueryFinished,
}

impl Events {
fn as_str(&self) -> &'static str {
match self {
Events::QueryFinished => "query_finished",
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum QueryTaskStatus {
Queued,
Expand All @@ -24,9 +37,9 @@ impl Default for QueryTaskStatus {
pub struct QueryTask {
pub conn: ConnectedConnection,
pub query: String,
pub tab_idx: usize,
pub id: String,
pub status: QueryTaskStatus,
pub tab_idx: usize,
pub query_idx: usize,
}

Expand Down Expand Up @@ -59,10 +72,13 @@ pub struct QueryTaskEnqueueResult {

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryTaskResult {
pub success: bool,
pub status: QueryTaskStatus,
pub query: String,
pub id: String,
pub path: Option<String>,
pub error: Option<String>,
pub tab_idx: usize,
pub query_idx: usize,
}

pub async fn async_process_model(
Expand All @@ -71,23 +87,45 @@ pub async fn async_process_model(
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
while let Some(input) = input_rx.recv().await {
let task = input;
match task.conn.execute_query(task.query).await {
Ok(_res) => {
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
output_tx
.send(QueryTaskResult {
success: false,
id: task.id,
path: Some("asd".to_string()),
error: None,
})
.await?;
match task.conn.execute_query(&task.query).await {
Ok(content) => {
match write_query(&task.id, &content.to_string()) {
Ok(path) => {
output_tx
.send(QueryTaskResult {
status: QueryTaskStatus::Completed,
query: task.query,
id: task.id,
query_idx: task.query_idx,
tab_idx: task.tab_idx,
path: Some(path),
error: None,
})
.await?
}
Err(e) => {
output_tx
.send(QueryTaskResult {
status: QueryTaskStatus::Error,
query: task.query,
id: task.id,
query_idx: task.query_idx,
tab_idx: task.tab_idx,
path: None,
error: Some(e.to_string()),
})
.await?
}
}
}
Err(e) => {
output_tx
.send(QueryTaskResult {
success: false,
status: QueryTaskStatus::Error,
query: task.query,
id: task.id,
query_idx: task.query_idx,
tab_idx: task.tab_idx,
path: None,
error: Some(e.to_string()),
})
Expand All @@ -98,7 +136,9 @@ pub async fn async_process_model(
Ok(())
}

pub async fn rs2js<R: tauri::Runtime>(query: QueryTaskResult, manager: &impl Manager<R>) {
info!(?query, "rs2js");
manager.emit_all("rs2js", query).unwrap();
pub async fn rs2js<R: tauri::Runtime>(result: QueryTaskResult, manager: &impl Manager<R>) {
info!(?result, "rs2js");
manager
.emit_all(Events::QueryFinished.as_str(), result)
.unwrap();
}
7 changes: 7 additions & 0 deletions src-tauri/src/utils/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,10 @@ pub fn write_file(path: &PathBuf, content: &str) -> Result<()> {
}
Ok(())
}

pub fn write_query(id: &str, content: &str) -> Result<String> {
let tmp_dir = get_tmp_dir()?;
let path = tmp_dir + "/" + id;
write_file(&PathBuf::from(&path), content)?;
Ok(path)
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
VimIcon,
} from "components/UI/Icons";
import { useAppSelector } from "services/Context";
import { QueryTaskEnqueueResult } from "interfaces";
import { Events, QueryTaskEnqueueResult } from "interfaces";
import { t } from "utils/i18n";
import { Alert } from "components/UI";
import { basicSetup } from "codemirror";
Expand Down Expand Up @@ -101,8 +101,7 @@ export const QueryTextArea = (props: {
};

onMount(async () => {
await listen("rs2js", (event) => {
log("js: rs2js: ");
await listen(Events.QueryFinished, (event) => {
log(event);
});
});
Expand Down
4 changes: 4 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,7 @@ export type Table = {
props: Record<string, any>;
}[];
};

export const Events = {
QueryFinished: "query_finished",
} as const;

0 comments on commit 7eb7d86

Please sign in to comment.