Add query cancellation controls (#41)
Co-authored-by: SuLe <sule@SuLedeMacBook-Air.local> Co-authored-by: skyler <77960507+t8y2@users.noreply.github.com>
This commit is contained in:
@@ -3,6 +3,7 @@ use std::sync::Arc;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::commands::query_cancel::RunningQueries;
|
||||
use crate::db;
|
||||
use crate::db::ssh_tunnel::TunnelManager;
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType};
|
||||
@@ -23,6 +24,7 @@ pub enum PoolKind {
|
||||
pub struct AppState {
|
||||
pub connections: Mutex<HashMap<String, PoolKind>>,
|
||||
pub configs: Mutex<HashMap<String, ConnectionConfig>>,
|
||||
pub running_queries: RunningQueries,
|
||||
pub tunnels: TunnelManager,
|
||||
}
|
||||
|
||||
@@ -31,6 +33,7 @@ impl AppState {
|
||||
Self {
|
||||
connections: Mutex::new(HashMap::new()),
|
||||
configs: Mutex::new(HashMap::new()),
|
||||
running_queries: RunningQueries::default(),
|
||||
tunnels: TunnelManager::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod connection;
|
||||
pub mod history;
|
||||
pub mod mongo_cmd;
|
||||
pub mod query;
|
||||
pub mod query_cancel;
|
||||
pub mod redis_cmd;
|
||||
pub mod schema;
|
||||
pub mod transfer;
|
||||
|
||||
+117
-26
@@ -1,13 +1,16 @@
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tauri::State;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::commands::connection::{AppState, PoolKind};
|
||||
use crate::db;
|
||||
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const MAX_ROWS: usize = 10000;
|
||||
const QUERY_CANCELED: &str = "Query canceled";
|
||||
|
||||
fn duckdb_execute(con: &duckdb::Connection, sql: &str) -> Result<db::QueryResult, String> {
|
||||
let start = std::time::Instant::now();
|
||||
@@ -68,10 +71,46 @@ fn is_connection_error(err: &str) -> bool {
|
||||
|| lower.contains("eof")
|
||||
}
|
||||
|
||||
fn timeout_error() -> String {
|
||||
format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs())
|
||||
}
|
||||
|
||||
fn canceled_error() -> String {
|
||||
QUERY_CANCELED.to_string()
|
||||
}
|
||||
|
||||
fn is_canceled(cancel_token: &Option<CancellationToken>) -> bool {
|
||||
cancel_token
|
||||
.as_ref()
|
||||
.map(|token| token.is_cancelled())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
async fn wait_for_query<F>(
|
||||
cancel_token: Option<CancellationToken>,
|
||||
future: F,
|
||||
) -> Result<db::QueryResult, String>
|
||||
where
|
||||
F: Future<Output = Result<db::QueryResult, String>>,
|
||||
{
|
||||
if let Some(token) = cancel_token {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = token.cancelled() => Err(canceled_error()),
|
||||
result = timeout(QUERY_TIMEOUT, future) => result.map_err(|_| timeout_error())?,
|
||||
}
|
||||
} else {
|
||||
timeout(QUERY_TIMEOUT, future)
|
||||
.await
|
||||
.map_err(|_| timeout_error())?
|
||||
}
|
||||
}
|
||||
|
||||
async fn do_execute(
|
||||
state: &AppState,
|
||||
pool_key: &str,
|
||||
sql: &str,
|
||||
cancel_token: Option<CancellationToken>,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(pool_key).ok_or("Connection not found")?;
|
||||
@@ -81,64 +120,72 @@ async fn do_execute(
|
||||
let con = con.clone();
|
||||
let sql = sql.to_string();
|
||||
drop(connections);
|
||||
let task = tokio::task::spawn_blocking(move || {
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
duckdb_execute(&con, &sql)
|
||||
});
|
||||
timeout(QUERY_TIMEOUT, task)
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map_err(|e| e.to_string())?
|
||||
wait_for_query(cancel_token, async move {
|
||||
let task = tokio::task::spawn_blocking(move || {
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
duckdb_execute(&con, &sql)
|
||||
});
|
||||
task.await.map_err(|e| e.to_string())?
|
||||
})
|
||||
.await
|
||||
}
|
||||
PoolKind::Mysql(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
timeout(QUERY_TIMEOUT, db::mysql::execute_query(&p, sql))
|
||||
wait_for_query(cancel_token, db::mysql::execute_query(&p, sql))
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
timeout(QUERY_TIMEOUT, db::postgres::execute_query(&p, sql))
|
||||
wait_for_query(cancel_token, db::postgres::execute_query(&p, sql))
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
timeout(QUERY_TIMEOUT, db::sqlite::execute_query(&p, sql))
|
||||
wait_for_query(cancel_token, db::sqlite::execute_query(&p, sql))
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::ClickHouse(client) => {
|
||||
let client = client.clone();
|
||||
let database = pool_key.split(':').nth(1).unwrap_or("default").to_string();
|
||||
drop(connections);
|
||||
timeout(QUERY_TIMEOUT, db::clickhouse_driver::execute_query(&client, &database, sql))
|
||||
wait_for_query(cancel_token, db::clickhouse_driver::execute_query(&client, &database, sql))
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::SqlServer(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
timeout(QUERY_TIMEOUT, db::sqlserver::execute_query(&mut client, sql))
|
||||
let mut client = match cancel_token.as_ref() {
|
||||
Some(token) => tokio::select! {
|
||||
biased;
|
||||
_ = token.cancelled() => return Err(canceled_error()),
|
||||
guard = client.lock() => guard,
|
||||
},
|
||||
None => client.lock().await,
|
||||
};
|
||||
wait_for_query(cancel_token, db::sqlserver::execute_query(&mut client, sql))
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Oracle(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
timeout(QUERY_TIMEOUT, db::oracle_driver::execute_query(&*client, sql))
|
||||
let client = match cancel_token.as_ref() {
|
||||
Some(token) => tokio::select! {
|
||||
biased;
|
||||
_ = token.cancelled() => return Err(canceled_error()),
|
||||
guard = client.lock() => guard,
|
||||
},
|
||||
None => client.lock().await,
|
||||
};
|
||||
wait_for_query(cancel_token, db::oracle_driver::execute_query(&*client, sql))
|
||||
.await
|
||||
.map_err(|_| format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs()))?
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Elasticsearch(_) => Err("Use document browser for Elasticsearch".to_string()),
|
||||
@@ -153,25 +200,44 @@ pub async fn execute_query(
|
||||
connection_id: String,
|
||||
database: String,
|
||||
sql: String,
|
||||
execution_id: Option<String>,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let registered_query = execution_id
|
||||
.as_ref()
|
||||
.filter(|id| !id.trim().is_empty())
|
||||
.map(|id| state.running_queries.register(id.clone()));
|
||||
let cancel_token = registered_query.as_ref().map(|query| query.token());
|
||||
|
||||
let pool_key = if database.is_empty() {
|
||||
connection_id.clone()
|
||||
} else {
|
||||
state.get_or_create_pool(&connection_id, Some(&database)).await?
|
||||
};
|
||||
|
||||
let result = do_execute(&state, &pool_key, &sql).await;
|
||||
if is_canceled(&cancel_token) {
|
||||
return Err(canceled_error());
|
||||
}
|
||||
|
||||
let result = do_execute(&state, &pool_key, &sql, cancel_token.clone()).await;
|
||||
|
||||
match &result {
|
||||
Err(e) if is_connection_error(e) => {
|
||||
Err(e) if is_connection_error(e) && !is_canceled(&cancel_token) => {
|
||||
let db_opt = if database.is_empty() { None } else { Some(database.as_str()) };
|
||||
let new_key = state.reconnect_pool(&connection_id, db_opt).await?;
|
||||
do_execute(&state, &new_key, &sql).await
|
||||
do_execute(&state, &new_key, &sql, cancel_token).await
|
||||
}
|
||||
_ => result,
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cancel_query(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
execution_id: String,
|
||||
) -> Result<bool, String> {
|
||||
Ok(state.running_queries.cancel(&execution_id))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn execute_batch(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
@@ -189,7 +255,7 @@ pub async fn execute_batch(
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
for (i, sql) in statements.iter().enumerate() {
|
||||
match do_execute(&state, &pool_key, sql).await {
|
||||
match do_execute(&state, &pool_key, sql, None).await {
|
||||
Ok(result) => {
|
||||
total_affected += result.affected_rows;
|
||||
}
|
||||
@@ -214,3 +280,28 @@ pub async fn execute_batch(
|
||||
truncated: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn wait_for_query_returns_cancelled_when_token_is_cancelled() {
|
||||
let token = CancellationToken::new();
|
||||
token.cancel();
|
||||
|
||||
let result = wait_for_query(Some(token), async {
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
Ok(db::QueryResult {
|
||||
columns: vec![],
|
||||
rows: vec![],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(result.unwrap_err(), QUERY_CANCELED);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct RunningQueries {
|
||||
inner: Arc<Mutex<HashMap<String, CancellationToken>>>,
|
||||
}
|
||||
|
||||
impl RunningQueries {
|
||||
pub fn register(&self, execution_id: String) -> RegisteredQuery {
|
||||
let token = CancellationToken::new();
|
||||
self.inner
|
||||
.lock()
|
||||
.expect("running query registry poisoned")
|
||||
.insert(execution_id.clone(), token.clone());
|
||||
|
||||
RegisteredQuery {
|
||||
execution_id,
|
||||
token,
|
||||
running_queries: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancel(&self, execution_id: &str) -> bool {
|
||||
let token = self
|
||||
.inner
|
||||
.lock()
|
||||
.expect("running query registry poisoned")
|
||||
.get(execution_id)
|
||||
.cloned();
|
||||
|
||||
if let Some(token) = token {
|
||||
token.cancel();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has(&self, execution_id: &str) -> bool {
|
||||
self.inner
|
||||
.lock()
|
||||
.expect("running query registry poisoned")
|
||||
.contains_key(execution_id)
|
||||
}
|
||||
|
||||
fn remove(&self, execution_id: &str) {
|
||||
self.inner
|
||||
.lock()
|
||||
.expect("running query registry poisoned")
|
||||
.remove(execution_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RegisteredQuery {
|
||||
execution_id: String,
|
||||
token: CancellationToken,
|
||||
running_queries: RunningQueries,
|
||||
}
|
||||
|
||||
impl RegisteredQuery {
|
||||
pub fn token(&self) -> CancellationToken {
|
||||
self.token.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RegisteredQuery {
|
||||
fn drop(&mut self) {
|
||||
self.running_queries.remove(&self.execution_id);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::RunningQueries;
|
||||
|
||||
#[test]
|
||||
fn cancel_marks_registered_query_as_cancelled() {
|
||||
let running = RunningQueries::default();
|
||||
let registered = running.register("exec-1".to_string());
|
||||
|
||||
assert!(running.cancel("exec-1"));
|
||||
assert!(registered.token().is_cancelled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_registration_removes_running_query() {
|
||||
let running = RunningQueries::default();
|
||||
let registered = running.register("exec-1".to_string());
|
||||
|
||||
assert!(running.has("exec-1"));
|
||||
drop(registered);
|
||||
|
||||
assert!(!running.has("exec-1"));
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,7 @@ pub fn run() {
|
||||
commands::schema::list_triggers,
|
||||
commands::schema::get_table_ddl,
|
||||
commands::query::execute_query,
|
||||
commands::query::cancel_query,
|
||||
commands::query::execute_batch,
|
||||
commands::redis_cmd::redis_list_databases,
|
||||
commands::redis_cmd::redis_scan_keys,
|
||||
|
||||
+39
-6
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { DatabaseZap, FilePlus2, Play, Loader2, X, Globe, Moon, Sun, Upload, Download, Plus, History, Server, Table2, Database, Search, ShieldCheck, Bot, Pin, AlignLeft, CloudDownload } from "lucide-vue-next";
|
||||
import { DatabaseZap, FilePlus2, Play, Loader2, Square, X, Globe, Moon, Sun, Upload, Download, Plus, History, Server, Table2, Database, Search, ShieldCheck, Bot, Pin, AlignLeft, CloudDownload } from "lucide-vue-next";
|
||||
import { Splitpanes, Pane } from "splitpanes";
|
||||
import "splitpanes/dist/splitpanes.css";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -44,6 +44,7 @@ import { setLocale, currentLocale, type Locale } from "@/i18n";
|
||||
import { getCurrentWindow, type Theme } from "@tauri-apps/api/window";
|
||||
import { getCurrentWebview } from "@tauri-apps/api/webview";
|
||||
import * as api from "@/lib/tauri";
|
||||
import { canCancelQueryExecution, queryExecutionLabelKey } from "@/lib/queryExecutionState";
|
||||
import { resolveExecutableSql } from "@/lib/sqlExecutionTarget";
|
||||
import type { SqlFormatDialect } from "@/lib/sqlFormatter";
|
||||
import { isCloseTabShortcut, isExecuteSqlShortcut } from "@/lib/keyboardShortcuts";
|
||||
@@ -345,6 +346,11 @@ async function doExecute(sql = executableSql.value) {
|
||||
});
|
||||
}
|
||||
|
||||
function cancelActiveExecution() {
|
||||
const tab = activeTab.value;
|
||||
if (tab) void queryStore.cancelTabExecution(tab.id);
|
||||
}
|
||||
|
||||
function onDangerConfirm() {
|
||||
const sql = pendingDangerSql.value || executableSql.value;
|
||||
pendingDangerSql.value = "";
|
||||
@@ -809,12 +815,19 @@ async function setupFileDrop() {
|
||||
<div class="flex items-center gap-0.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6" :disabled="activeTab.isExecuting" @click="tryExecute()">
|
||||
<Loader2 v-if="activeTab.isExecuting" class="h-3.5 w-3.5 animate-spin" />
|
||||
<Button
|
||||
:variant="activeTab.isExecuting ? 'destructive' : 'ghost'"
|
||||
size="icon"
|
||||
class="h-6 w-6"
|
||||
:disabled="activeTab.isCancelling || (!activeTab.isExecuting && !executableSql.trim())"
|
||||
@click="activeTab.isExecuting ? cancelActiveExecution() : tryExecute()"
|
||||
>
|
||||
<Loader2 v-if="activeTab.isCancelling" class="h-3.5 w-3.5 animate-spin" />
|
||||
<Square v-else-if="activeTab.isExecuting" class="h-3.5 w-3.5 fill-current" />
|
||||
<Play v-else class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ t('toolbar.executeShortcut') }}</TooltipContent>
|
||||
<TooltipContent>{{ activeTab.isExecuting ? t('toolbar.stopQuery') : t('toolbar.executeShortcut') }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
@@ -908,6 +921,12 @@ async function setupFileDrop() {
|
||||
<Pane :size="60" :min-size="20">
|
||||
<div class="h-full flex flex-col">
|
||||
<DataGrid v-if="activeTab.result" :key="activeTab.id" class="flex-1 min-h-0" :result="activeTab.result" :sql="activeTab.lastExecutedSql || activeTab.sql" />
|
||||
<div v-else-if="activeTab.isExecuting" class="flex-1 min-h-0 flex flex-col items-center justify-center gap-3 text-muted-foreground text-sm">
|
||||
<div class="flex items-center">
|
||||
<Loader2 class="h-5 w-5 animate-spin mr-2" />
|
||||
{{ t(queryExecutionLabelKey(activeTab)) }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="flex-1 min-h-0 flex items-center justify-center text-muted-foreground text-sm">
|
||||
{{ t('editor.pressToExecute') }}
|
||||
</div>
|
||||
@@ -934,8 +953,22 @@ async function setupFileDrop() {
|
||||
@paginate="onPaginate"
|
||||
@sort="onSort"
|
||||
/>
|
||||
<div v-else-if="activeTab.isExecuting" class="h-full flex items-center justify-center text-muted-foreground text-sm">
|
||||
<Loader2 class="h-5 w-5 animate-spin mr-2" /> {{ t('common.loading') }}
|
||||
<div v-else-if="activeTab.isExecuting" class="h-full flex flex-col items-center justify-center gap-3 text-muted-foreground text-sm">
|
||||
<div class="flex items-center">
|
||||
<Loader2 class="h-5 w-5 animate-spin mr-2" />
|
||||
{{ t(queryExecutionLabelKey(activeTab)) }}
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
class="h-7 gap-1.5"
|
||||
:disabled="!canCancelQueryExecution(activeTab)"
|
||||
@click="cancelActiveExecution"
|
||||
>
|
||||
<Loader2 v-if="activeTab.isCancelling" class="h-3.5 w-3.5 animate-spin" />
|
||||
<Square v-else class="h-3.5 w-3.5 fill-current" />
|
||||
{{ t('toolbar.stopQuery') }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -7,6 +7,7 @@ export default {
|
||||
newQuery: "New Query",
|
||||
execute: "Execute",
|
||||
executeShortcut: "Execute selection/query (Cmd+Enter)",
|
||||
stopQuery: "Stop query",
|
||||
formatSql: "Format SQL",
|
||||
formatSqlFailed: "Failed to format SQL",
|
||||
},
|
||||
@@ -123,6 +124,7 @@ export default {
|
||||
common: {
|
||||
language: "Language",
|
||||
loading: "Loading...",
|
||||
stopping: "Stopping...",
|
||||
close: "Close",
|
||||
},
|
||||
ai: {
|
||||
|
||||
@@ -7,6 +7,7 @@ export default {
|
||||
newQuery: "新建查询",
|
||||
execute: "执行",
|
||||
executeShortcut: "执行选中/全部 (Cmd+Enter)",
|
||||
stopQuery: "停止执行",
|
||||
formatSql: "格式化 SQL",
|
||||
formatSqlFailed: "SQL 格式化失败",
|
||||
},
|
||||
@@ -123,6 +124,7 @@ export default {
|
||||
common: {
|
||||
language: "语言",
|
||||
loading: "加载中...",
|
||||
stopping: "正在停止...",
|
||||
close: "关闭",
|
||||
},
|
||||
ai: {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export interface QueryExecutionStateLike {
|
||||
isExecuting: boolean;
|
||||
isCancelling?: boolean;
|
||||
executionId?: string;
|
||||
}
|
||||
|
||||
export function canCancelQueryExecution(state: QueryExecutionStateLike): boolean {
|
||||
return state.isExecuting && !!state.executionId && !state.isCancelling;
|
||||
}
|
||||
|
||||
export function queryExecutionLabelKey(state: Pick<QueryExecutionStateLike, "isCancelling">): "common.loading" | "common.stopping" {
|
||||
return state.isCancelling ? "common.stopping" : "common.loading";
|
||||
}
|
||||
+6
-2
@@ -95,8 +95,12 @@ export async function getColumns(
|
||||
return invoke("get_columns", { connectionId, database, schema, table });
|
||||
}
|
||||
|
||||
export async function executeQuery(connectionId: string, database: string, sql: string): Promise<QueryResult> {
|
||||
return invoke("execute_query", { connectionId, database, sql });
|
||||
export async function executeQuery(connectionId: string, database: string, sql: string, executionId?: string): Promise<QueryResult> {
|
||||
return invoke("execute_query", { connectionId, database, sql, executionId });
|
||||
}
|
||||
|
||||
export async function cancelQuery(executionId: string): Promise<boolean> {
|
||||
return invoke("cancel_query", { executionId });
|
||||
}
|
||||
|
||||
export async function executeBatch(connectionId: string, database: string, statements: string[]): Promise<QueryResult> {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { defineStore } from "pinia";
|
||||
import { ref } from "vue";
|
||||
import type { QueryTab } from "@/types/database";
|
||||
import { orderPinnedFirst } from "@/lib/pinnedItems";
|
||||
import { canCancelQueryExecution } from "@/lib/queryExecutionState";
|
||||
import { closeAllTabsState, closeOtherTabsState } from "@/lib/tabCloseActions";
|
||||
import * as api from "@/lib/tauri";
|
||||
|
||||
@@ -31,6 +32,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
database,
|
||||
sql: "",
|
||||
isExecuting: false,
|
||||
isCancelling: false,
|
||||
mode,
|
||||
};
|
||||
tabs.value.push(tab);
|
||||
@@ -41,6 +43,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
function closeTab(id: string) {
|
||||
const idx = tabs.value.findIndex((t) => t.id === id);
|
||||
if (idx < 0) return;
|
||||
if (tabs.value[idx].isExecuting) void cancelTabExecution(id);
|
||||
tabs.value.splice(idx, 1);
|
||||
if (activeTabId.value === id) {
|
||||
activeTabId.value = tabs.value[Math.min(idx, tabs.value.length - 1)]?.id ?? null;
|
||||
@@ -48,12 +51,18 @@ export const useQueryStore = defineStore("query", () => {
|
||||
}
|
||||
|
||||
function closeOtherTabs(id: string) {
|
||||
tabs.value
|
||||
.filter((tab) => tab.id !== id && tab.isExecuting)
|
||||
.forEach((tab) => void cancelTabExecution(tab.id));
|
||||
const next = closeOtherTabsState(tabs.value, activeTabId.value, id);
|
||||
tabs.value = next.tabs;
|
||||
activeTabId.value = next.activeTabId;
|
||||
}
|
||||
|
||||
function closeAllTabs() {
|
||||
tabs.value
|
||||
.filter((tab) => tab.isExecuting)
|
||||
.forEach((tab) => void cancelTabExecution(tab.id));
|
||||
const next = closeAllTabsState(tabs.value, activeTabId.value);
|
||||
tabs.value = next.tabs;
|
||||
activeTabId.value = next.activeTabId;
|
||||
@@ -97,7 +106,12 @@ export const useQueryStore = defineStore("query", () => {
|
||||
|
||||
function setExecuting(id: string, isExecuting: boolean) {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
if (tab) tab.isExecuting = isExecuting;
|
||||
if (!tab) return;
|
||||
tab.isExecuting = isExecuting;
|
||||
if (!isExecuting) {
|
||||
tab.isCancelling = false;
|
||||
tab.executionId = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function toErrorResult(e: any): NonNullable<QueryTab["result"]> {
|
||||
@@ -114,6 +128,8 @@ export const useQueryStore = defineStore("query", () => {
|
||||
if (!tab) return;
|
||||
tab.result = toErrorResult(e);
|
||||
tab.isExecuting = false;
|
||||
tab.isCancelling = false;
|
||||
tab.executionId = undefined;
|
||||
}
|
||||
|
||||
async function executeCurrentTab() {
|
||||
@@ -132,18 +148,53 @@ export const useQueryStore = defineStore("query", () => {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
if (!tab || !sql.trim()) return;
|
||||
|
||||
const executionId = crypto.randomUUID();
|
||||
tab.isExecuting = true;
|
||||
tab.isCancelling = false;
|
||||
tab.executionId = executionId;
|
||||
tab.lastExecutedSql = sql;
|
||||
try {
|
||||
tab.result = await api.executeQuery(tab.connectionId, tab.database, sql);
|
||||
tab.result = await api.executeQuery(tab.connectionId, tab.database, sql, executionId);
|
||||
} catch (e: any) {
|
||||
tab.result = toErrorResult(e);
|
||||
const current = tabs.value.find((t) => t.id === id);
|
||||
if (current?.executionId === executionId) {
|
||||
current.result = toErrorResult(e);
|
||||
}
|
||||
} finally {
|
||||
tab.isExecuting = false;
|
||||
const current = tabs.value.find((t) => t.id === id);
|
||||
if (current?.executionId === executionId) {
|
||||
current.isExecuting = false;
|
||||
current.isCancelling = false;
|
||||
current.executionId = undefined;
|
||||
}
|
||||
}
|
||||
trimResultCache();
|
||||
}
|
||||
|
||||
async function cancelTabExecution(id: string) {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
if (!tab || !canCancelQueryExecution(tab)) return false;
|
||||
|
||||
const executionId = tab.executionId;
|
||||
if (!executionId) return false;
|
||||
tab.isCancelling = true;
|
||||
try {
|
||||
const canceled = await api.cancelQuery(executionId);
|
||||
if (!canceled) {
|
||||
const current = tabs.value.find((t) => t.id === id);
|
||||
if (current && current.executionId === executionId) current.isCancelling = false;
|
||||
}
|
||||
return canceled;
|
||||
} catch (e: any) {
|
||||
const current = tabs.value.find((t) => t.id === id);
|
||||
if (current && current.executionId === executionId) {
|
||||
current.isCancelling = false;
|
||||
current.result = toErrorResult(e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function trimResultCache() {
|
||||
const inactive = tabs.value.filter((t) => t.id !== activeTabId.value && t.result);
|
||||
if (inactive.length > MAX_CACHED_RESULTS) {
|
||||
@@ -169,5 +220,6 @@ export const useQueryStore = defineStore("query", () => {
|
||||
executeCurrentTab,
|
||||
executeCurrentSql,
|
||||
executeTabSql,
|
||||
cancelTabExecution,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -102,6 +102,8 @@ export interface QueryTab {
|
||||
pinned?: boolean;
|
||||
result?: QueryResult;
|
||||
isExecuting: boolean;
|
||||
isCancelling?: boolean;
|
||||
executionId?: string;
|
||||
mode: "data" | "query" | "redis" | "mongo";
|
||||
tableMeta?: {
|
||||
schema?: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import test from "node:test";
|
||||
import { orderPinnedFirst } from "../src/lib/pinnedItems.js";
|
||||
import { orderPinnedFirst } from "../src/lib/pinnedItems.ts";
|
||||
|
||||
test("orders pinned items before unpinned items without changing relative order", () => {
|
||||
const items = [
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import test from "node:test";
|
||||
import { canCancelQueryExecution, queryExecutionLabelKey } from "../src/lib/queryExecutionState.ts";
|
||||
|
||||
test("only allows cancelling an active execution with an execution id", () => {
|
||||
assert.equal(canCancelQueryExecution({ isExecuting: true, executionId: "exec-1" }), true);
|
||||
assert.equal(canCancelQueryExecution({ isExecuting: true, executionId: "exec-1", isCancelling: true }), false);
|
||||
assert.equal(canCancelQueryExecution({ isExecuting: true }), false);
|
||||
assert.equal(canCancelQueryExecution({ isExecuting: false, executionId: "exec-1" }), false);
|
||||
});
|
||||
|
||||
test("uses a stopping label while cancellation is in progress", () => {
|
||||
assert.equal(queryExecutionLabelKey({ isExecuting: true }), "common.loading");
|
||||
assert.equal(queryExecutionLabelKey({ isExecuting: true, isCancelling: true }), "common.stopping");
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import test from "node:test";
|
||||
import { resolveExecutableSql } from "../src/lib/sqlExecutionTarget.js";
|
||||
import { resolveExecutableSql } from "../src/lib/sqlExecutionTarget.ts";
|
||||
|
||||
test("uses selected SQL when the editor has a non-empty selection", () => {
|
||||
const sql = "SELECT * FROM users;\nSELECT * FROM orders;";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import test from "node:test";
|
||||
import { formatSqlText } from "../src/lib/sqlFormatter.js";
|
||||
import { formatSqlText } from "../src/lib/sqlFormatter.ts";
|
||||
|
||||
test("formats SQL with uppercase keywords and readable line breaks", async () => {
|
||||
const formatted = await formatSqlText("select id, name from users where active = 1 order by name", "postgres");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import test from "node:test";
|
||||
import { closeAllTabsState, closeOtherTabsState } from "../src/lib/tabCloseActions.js";
|
||||
import { closeAllTabsState, closeOtherTabsState } from "../src/lib/tabCloseActions.ts";
|
||||
|
||||
test("close other tabs keeps the target tab and makes it active", () => {
|
||||
const tabs = [{ id: "a" }, { id: "b" }, { id: "c" }];
|
||||
|
||||
Reference in New Issue
Block a user