feat: extract dbx-core crate for web deployment support
Refactor all database drivers, query execution, schema operations, and business logic into a shared `dbx-core` crate. The Tauri desktop app becomes a thin shell delegating to dbx-core, enabling future web and CLI frontends to reuse the same core.
This commit is contained in:
+1
-2
@@ -5,8 +5,7 @@ node_modules/
|
||||
|
||||
# Build output
|
||||
dist/
|
||||
|
||||
# Tauri build output is handled by src-tauri/.gitignore
|
||||
/target/
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
|
||||
Generated
+10062
File diff suppressed because it is too large
Load Diff
+10
@@ -0,0 +1,10 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src-tauri", "crates/dbx-core", "src-web"]
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
strip = true
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
opt-level = "s"
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "dbx-core"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
percent-encoding = "2"
|
||||
log = "0.4"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-util = { version = "0.7", features = ["compat"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
rust_decimal = { version = "1", features = ["serde"] }
|
||||
anyhow = "1"
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
sqlx = { version = "0.8", features = ["runtime-tokio", "tls-native-tls", "mysql", "postgres", "sqlite", "json", "chrono", "uuid", "rust_decimal"] }
|
||||
redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tokio-rustls-comp"] }
|
||||
rustls = { version = "0.23", features = ["aws-lc-rs"] }
|
||||
duckdb = { version = "1.3.2", features = ["bundled"] }
|
||||
tiberius = { version = "0.12.3", features = ["tds73", "chrono", "rust_decimal"] }
|
||||
reqwest = { version = "0.12", features = ["json", "stream"] }
|
||||
futures = "0.3"
|
||||
mongodb = "3.2.5"
|
||||
oracle-rs = "0.1"
|
||||
russh = "0.60"
|
||||
portpicker = "0.1.1"
|
||||
csv = "1"
|
||||
calamine = "0.30.1"
|
||||
@@ -0,0 +1,792 @@
|
||||
use futures::StreamExt;
|
||||
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream cancel registry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static AI_STREAMS: LazyLock<RwLock<HashMap<String, Arc<AtomicBool>>>> =
|
||||
LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
pub async fn register_stream(session_id: &str) -> Arc<AtomicBool> {
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
AI_STREAMS
|
||||
.write()
|
||||
.await
|
||||
.insert(session_id.to_string(), cancelled.clone());
|
||||
cancelled
|
||||
}
|
||||
|
||||
pub async fn cancel_stream(session_id: &str) -> bool {
|
||||
if let Some(flag) = AI_STREAMS.read().await.get(session_id) {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn unregister_stream(session_id: &str) {
|
||||
AI_STREAMS.write().await.remove(session_id);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AiProvider {
|
||||
Claude,
|
||||
Openai,
|
||||
Custom,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AiApiStyle {
|
||||
Completions,
|
||||
Responses,
|
||||
}
|
||||
|
||||
impl Default for AiApiStyle {
|
||||
fn default() -> Self {
|
||||
Self::Completions
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiConfig {
|
||||
pub provider: AiProvider,
|
||||
#[serde(default)]
|
||||
pub api_key: String,
|
||||
#[serde(default)]
|
||||
pub endpoint: String,
|
||||
#[serde(default)]
|
||||
pub model: String,
|
||||
#[serde(default)]
|
||||
pub api_style: AiApiStyle,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiMessage {
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiCompletionRequest {
|
||||
pub config: AiConfig,
|
||||
pub system_prompt: String,
|
||||
pub messages: Vec<AiMessage>,
|
||||
pub max_tokens: Option<u32>,
|
||||
pub temperature: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AiStreamChunk {
|
||||
pub session_id: String,
|
||||
pub delta: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning_delta: Option<String>,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiChatMessage {
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiConversation {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub connection_name: String,
|
||||
pub database: String,
|
||||
pub messages: Vec<AiChatMessage>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn resolve_endpoint(config: &AiConfig) -> String {
|
||||
let ep = config.endpoint.trim().trim_end_matches('/');
|
||||
if ep.ends_with("/chat/completions")
|
||||
|| ep.ends_with("/responses")
|
||||
|| ep.ends_with("/messages")
|
||||
{
|
||||
return ep.to_string();
|
||||
}
|
||||
match config.provider {
|
||||
AiProvider::Claude => format!("{ep}/messages"),
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if config.api_style == AiApiStyle::Responses {
|
||||
format!("{ep}/responses")
|
||||
} else {
|
||||
format!("{ep}/chat/completions")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stream_data_payload(line: &str) -> Option<&str> {
|
||||
let line = line.trim();
|
||||
if line.is_empty()
|
||||
|| line.starts_with(':')
|
||||
|| line.starts_with("event:")
|
||||
|| line.starts_with("id:")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let Some(data) = line.strip_prefix("data:") {
|
||||
return Some(data.trim_start());
|
||||
}
|
||||
if line.starts_with('{') {
|
||||
return Some(line);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn claude_stream_text(event: &serde_json::Value) -> Option<&str> {
|
||||
if event["type"] == "content_block_delta" {
|
||||
return event["delta"]["text"].as_str();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn openai_stream_text(event: &serde_json::Value) -> Option<&str> {
|
||||
event["choices"]
|
||||
.get(0)
|
||||
.and_then(|choice| {
|
||||
choice["delta"]["content"]
|
||||
.as_str()
|
||||
.or_else(|| choice["message"]["content"].as_str())
|
||||
})
|
||||
.or_else(|| event["content"].as_str())
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
pub fn openai_stream_reasoning(event: &serde_json::Value) -> Option<&str> {
|
||||
event["choices"]
|
||||
.get(0)
|
||||
.and_then(|choice| choice["delta"]["reasoning_content"].as_str())
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
pub fn responses_stream_text(event: &serde_json::Value) -> Option<&str> {
|
||||
event["delta"].as_str().filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
pub fn extract_error(data: &serde_json::Value) -> Option<String> {
|
||||
data["error"]["message"]
|
||||
.as_str()
|
||||
.or_else(|| data["error"].as_str())
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
pub fn build_responses_input(system_prompt: &str, messages: &[AiMessage]) -> serde_json::Value {
|
||||
let mut input = Vec::new();
|
||||
if !system_prompt.is_empty() {
|
||||
input.push(json!({
|
||||
"role": "developer",
|
||||
"content": system_prompt,
|
||||
}));
|
||||
}
|
||||
for m in messages {
|
||||
input.push(json!({
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
}));
|
||||
}
|
||||
json!(input)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Validation helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn validate_config(config: &AiConfig) -> Result<(), String> {
|
||||
if config.api_key.trim().is_empty() {
|
||||
return Err("API key is required".to_string());
|
||||
}
|
||||
if config.endpoint.trim().is_empty() {
|
||||
return Err("Endpoint is required".to_string());
|
||||
}
|
||||
if config.model.trim().is_empty() {
|
||||
return Err("Model is required".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Non-streaming calls
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn call_claude(
|
||||
client: &reqwest::Client,
|
||||
request: AiCompletionRequest,
|
||||
) -> Result<String, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
"x-api-key",
|
||||
HeaderValue::from_str(&request.config.api_key).map_err(|e| e.to_string())?,
|
||||
);
|
||||
headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"system": request.system_prompt,
|
||||
"messages": request.messages,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Claude request failed: {e}"))?;
|
||||
|
||||
let status = res.status();
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(extract_error(&data).unwrap_or_else(|| format!("Claude API error: {status}")));
|
||||
}
|
||||
|
||||
Ok(data["content"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find_map(|item| item["text"].as_str()))
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub async fn call_openai_compatible(
|
||||
client: &reqwest::Client,
|
||||
request: AiCompletionRequest,
|
||||
) -> Result<String, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key))
|
||||
.map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let mut messages = vec![json!({ "role": "system", "content": request.system_prompt })];
|
||||
messages.extend(
|
||||
request
|
||||
.messages
|
||||
.iter()
|
||||
.map(|message| json!({ "role": message.role, "content": message.content })),
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"messages": messages,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
let status = res.status();
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(extract_error(&data).unwrap_or_else(|| format!("API error: {status}")));
|
||||
}
|
||||
|
||||
Ok(data["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub async fn call_responses_api(
|
||||
client: &reqwest::Client,
|
||||
request: AiCompletionRequest,
|
||||
) -> Result<String, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key))
|
||||
.map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"input": build_responses_input(&request.system_prompt, &request.messages),
|
||||
"max_output_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
let status = res.status();
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(extract_error(&data).unwrap_or_else(|| format!("API error: {status}")));
|
||||
}
|
||||
|
||||
Ok(data["output"]
|
||||
.as_array()
|
||||
.and_then(|items| {
|
||||
items.iter().find_map(|item| {
|
||||
item["content"]
|
||||
.as_array()
|
||||
.and_then(|parts| parts.iter().find_map(|p| p["text"].as_str()))
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// High-level: test_connection_core / complete
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn test_connection_core(config: &AiConfig) -> Result<String, String> {
|
||||
validate_config(config)?;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let request = AiCompletionRequest {
|
||||
config: config.clone(),
|
||||
system_prompt: String::new(),
|
||||
messages: vec![AiMessage {
|
||||
role: "user".into(),
|
||||
content: "hi".into(),
|
||||
}],
|
||||
max_tokens: Some(1),
|
||||
temperature: Some(0.0),
|
||||
};
|
||||
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => call_claude(&client, request).await,
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if request.config.api_style == AiApiStyle::Responses {
|
||||
call_responses_api(&client, request).await
|
||||
} else {
|
||||
call_openai_compatible(&client, request).await
|
||||
}
|
||||
}
|
||||
}
|
||||
.map(|_| "OK".to_string())
|
||||
}
|
||||
|
||||
pub async fn complete(request: &AiCompletionRequest) -> Result<String, String> {
|
||||
validate_config(&request.config)?;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => call_claude(&client, request.clone()).await,
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if request.config.api_style == AiApiStyle::Responses {
|
||||
call_responses_api(&client, request.clone()).await
|
||||
} else {
|
||||
call_openai_compatible(&client, request.clone()).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Streaming
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn stream(
|
||||
session_id: &str,
|
||||
request: &AiCompletionRequest,
|
||||
cancelled: &AtomicBool,
|
||||
on_chunk: impl Fn(AiStreamChunk),
|
||||
) -> Result<(), String> {
|
||||
validate_config(&request.config)?;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => {
|
||||
stream_claude(&client, session_id, request, cancelled, &on_chunk).await
|
||||
}
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if request.config.api_style == AiApiStyle::Responses {
|
||||
stream_responses_api(&client, session_id, request, cancelled, &on_chunk).await
|
||||
} else {
|
||||
stream_openai(&client, session_id, request, cancelled, &on_chunk).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream_claude(
|
||||
client: &reqwest::Client,
|
||||
session_id: &str,
|
||||
request: &AiCompletionRequest,
|
||||
cancelled: &AtomicBool,
|
||||
on_chunk: &impl Fn(AiStreamChunk),
|
||||
) -> Result<(), String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
"x-api-key",
|
||||
HeaderValue::from_str(&request.config.api_key).map_err(|e| e.to_string())?,
|
||||
);
|
||||
headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"system": request.system_prompt,
|
||||
"messages": request.messages,
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Claude request failed: {e}"))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
return Err(extract_error(&data).unwrap_or_else(|| "Claude API error".to_string()));
|
||||
}
|
||||
|
||||
let mut byte_stream = res.bytes_stream();
|
||||
let mut buf = String::new();
|
||||
|
||||
let mut finished = false;
|
||||
while let Some(chunk) = byte_stream.next().await {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
buf.push_str(&String::from_utf8_lossy(&chunk));
|
||||
|
||||
while let Some(pos) = buf.find('\n') {
|
||||
let line = buf[..pos].to_string();
|
||||
buf = buf[pos + 1..].to_string();
|
||||
|
||||
let Some(data) = stream_data_payload(&line) else {
|
||||
continue;
|
||||
};
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(data) {
|
||||
if let Some(text) = claude_stream_text(&event) {
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: text.to_string(),
|
||||
reasoning_delta: None,
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: None,
|
||||
done: true,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stream_openai(
|
||||
client: &reqwest::Client,
|
||||
session_id: &str,
|
||||
request: &AiCompletionRequest,
|
||||
cancelled: &AtomicBool,
|
||||
on_chunk: &impl Fn(AiStreamChunk),
|
||||
) -> Result<(), String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key))
|
||||
.map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let mut messages = vec![json!({ "role": "system", "content": request.system_prompt })];
|
||||
messages.extend(
|
||||
request
|
||||
.messages
|
||||
.iter()
|
||||
.map(|m| json!({ "role": m.role, "content": m.content })),
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"messages": messages,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
return Err(extract_error(&data).unwrap_or_else(|| "API error".to_string()));
|
||||
}
|
||||
|
||||
let mut byte_stream = res.bytes_stream();
|
||||
let mut buf = String::new();
|
||||
|
||||
let mut finished = false;
|
||||
while let Some(chunk) = byte_stream.next().await {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
buf.push_str(&String::from_utf8_lossy(&chunk));
|
||||
|
||||
while let Some(pos) = buf.find('\n') {
|
||||
let line = buf[..pos].to_string();
|
||||
buf = buf[pos + 1..].to_string();
|
||||
|
||||
let Some(data) = stream_data_payload(&line) else {
|
||||
continue;
|
||||
};
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(data) {
|
||||
if let Some(reasoning) = openai_stream_reasoning(&event) {
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: Some(reasoning.to_string()),
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
if let Some(text) = openai_stream_text(&event) {
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: text.to_string(),
|
||||
reasoning_delta: None,
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: None,
|
||||
done: true,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stream_responses_api(
|
||||
client: &reqwest::Client,
|
||||
session_id: &str,
|
||||
request: &AiCompletionRequest,
|
||||
cancelled: &AtomicBool,
|
||||
on_chunk: &impl Fn(AiStreamChunk),
|
||||
) -> Result<(), String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key))
|
||||
.map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"input": build_responses_input(&request.system_prompt, &request.messages),
|
||||
"max_output_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
return Err(extract_error(&data).unwrap_or_else(|| "API error".to_string()));
|
||||
}
|
||||
|
||||
let mut byte_stream = res.bytes_stream();
|
||||
let mut buf = String::new();
|
||||
|
||||
let mut finished = false;
|
||||
while let Some(chunk) = byte_stream.next().await {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
buf.push_str(&String::from_utf8_lossy(&chunk));
|
||||
|
||||
while let Some(pos) = buf.find('\n') {
|
||||
let line = buf[..pos].to_string();
|
||||
buf = buf[pos + 1..].to_string();
|
||||
|
||||
let Some(data) = stream_data_payload(&line) else {
|
||||
continue;
|
||||
};
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(data) {
|
||||
if let Some(text) = responses_stream_text(&event) {
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: text.to_string(),
|
||||
reasoning_delta: None,
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
on_chunk(AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: None,
|
||||
done: true,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conversation persistence (path-based)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MAX_CONVERSATIONS: usize = 50;
|
||||
|
||||
pub fn read_conversations(path: &Path) -> Result<Vec<AiConversation>, String> {
|
||||
if !path.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn write_conversations(path: &Path, conversations: &[AiConversation]) -> Result<(), String> {
|
||||
let json = serde_json::to_string(conversations).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn save_conversation(path: &Path, conversation: AiConversation) -> Result<(), String> {
|
||||
let mut conversations = read_conversations(path)?;
|
||||
if let Some(pos) = conversations.iter().position(|c| c.id == conversation.id) {
|
||||
conversations[pos] = conversation;
|
||||
} else {
|
||||
conversations.insert(0, conversation);
|
||||
conversations.truncate(MAX_CONVERSATIONS);
|
||||
}
|
||||
write_conversations(path, &conversations)
|
||||
}
|
||||
|
||||
pub fn load_conversations(path: &Path) -> Result<Vec<AiConversation>, String> {
|
||||
read_conversations(path)
|
||||
}
|
||||
|
||||
pub fn delete_conversation(path: &Path, id: &str) -> Result<(), String> {
|
||||
let conversations: Vec<AiConversation> = read_conversations(path)?
|
||||
.into_iter()
|
||||
.filter(|c| c.id != id)
|
||||
.collect();
|
||||
write_conversations(path, &conversations)
|
||||
}
|
||||
|
||||
pub fn save_config(path: &Path, config: &AiConfig) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn load_config(path: &Path) -> Result<Option<AiConfig>, String> {
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map(Some).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::db;
|
||||
use crate::db::ssh_tunnel::TunnelManager;
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType};
|
||||
use crate::query_cancel::RunningQueries;
|
||||
|
||||
pub fn expand_tilde(path: &str) -> String {
|
||||
if path == "~" || path.starts_with("~/") {
|
||||
if let Ok(home) = std::env::var(if cfg!(windows) { "USERPROFILE" } else { "HOME" }) {
|
||||
return format!("{}{}", home, &path[1..]);
|
||||
}
|
||||
}
|
||||
path.to_string()
|
||||
}
|
||||
|
||||
pub enum PoolKind {
|
||||
Mysql(sqlx::mysql::MySqlPool, bool),
|
||||
Postgres(sqlx::postgres::PgPool),
|
||||
Sqlite(sqlx::sqlite::SqlitePool),
|
||||
Redis(tokio::sync::Mutex<redis::aio::MultiplexedConnection>),
|
||||
DuckDb(Arc<std::sync::Mutex<duckdb::Connection>>),
|
||||
MongoDb(mongodb::Client),
|
||||
ClickHouse(db::clickhouse_driver::ChClient),
|
||||
SqlServer(Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>),
|
||||
Oracle(Arc<tokio::sync::Mutex<db::oracle_driver::OracleClient>>),
|
||||
Elasticsearch(db::elasticsearch_driver::EsClient),
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub connections: Mutex<HashMap<String, PoolKind>>,
|
||||
pub configs: Mutex<HashMap<String, ConnectionConfig>>,
|
||||
pub running_queries: RunningQueries,
|
||||
pub tunnels: TunnelManager,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
connections: Mutex::new(HashMap::new()),
|
||||
configs: Mutex::new(HashMap::new()),
|
||||
running_queries: RunningQueries::default(),
|
||||
tunnels: TunnelManager::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_or_create_pool(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
database: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let db_type = {
|
||||
let configs = self.configs.lock().await;
|
||||
configs.get(connection_id).map(|c| c.db_type.clone())
|
||||
};
|
||||
|
||||
let is_embedded = matches!(db_type, Some(DatabaseType::Sqlite) | Some(DatabaseType::DuckDb));
|
||||
if is_embedded {
|
||||
return Ok(connection_id.to_string());
|
||||
}
|
||||
|
||||
let is_single_conn = matches!(db_type, Some(DatabaseType::Oracle));
|
||||
let pool_key = if is_single_conn {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
match database {
|
||||
Some(db) => format!("{connection_id}:{db}"),
|
||||
None => connection_id.to_string(),
|
||||
}
|
||||
};
|
||||
|
||||
let conns = self.connections.lock().await;
|
||||
if conns.contains_key(&pool_key) {
|
||||
return Ok(pool_key);
|
||||
}
|
||||
drop(conns);
|
||||
|
||||
let configs = self.configs.lock().await;
|
||||
let config = configs
|
||||
.get(connection_id)
|
||||
.ok_or("Connection config not found")?
|
||||
.clone();
|
||||
drop(configs);
|
||||
|
||||
let mut db_config = config.clone();
|
||||
if let Some(db) = database {
|
||||
if db_config.db_type != DatabaseType::Oracle {
|
||||
db_config.database = Some(db.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let (host, port) = self.connection_host_port(connection_id, &db_config).await?;
|
||||
let url = connection_url_for_endpoint(&db_config, &host, port);
|
||||
let pool = match db_config.db_type {
|
||||
DatabaseType::Mysql if db_config.needs_bare_mysql() => PoolKind::Mysql(db::mysql::connect_bare(&url).await?, true),
|
||||
DatabaseType::Mysql => PoolKind::Mysql(db::mysql::connect(&url).await?, false),
|
||||
DatabaseType::Doris | DatabaseType::StarRocks => PoolKind::Mysql(db::mysql::connect_bare(&url).await?, true),
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => PoolKind::Postgres(db::postgres::connect(&url).await?),
|
||||
DatabaseType::Sqlite => PoolKind::Sqlite(db::sqlite::connect_path(&expand_tilde(&db_config.host)).await?),
|
||||
DatabaseType::Redis => {
|
||||
let con = db::redis_driver::connect(&url).await?;
|
||||
PoolKind::Redis(tokio::sync::Mutex::new(con))
|
||||
}
|
||||
DatabaseType::DuckDb => {
|
||||
let con = duckdb::Connection::open(&expand_tilde(&db_config.host)).map_err(|e| e.to_string())?;
|
||||
PoolKind::DuckDb(Arc::new(std::sync::Mutex::new(con)))
|
||||
}
|
||||
DatabaseType::MongoDb => {
|
||||
let client = mongodb::Client::with_uri_str(&url).await.map_err(|e| e.to_string())?;
|
||||
PoolKind::MongoDb(client)
|
||||
}
|
||||
DatabaseType::ClickHouse => {
|
||||
let username = if db_config.username.is_empty() { None } else { Some(db_config.username.clone()) };
|
||||
let password = if db_config.password.is_empty() { None } else { Some(db_config.password.clone()) };
|
||||
let client = db::clickhouse_driver::ChClient::new(&url, username, password);
|
||||
db::clickhouse_driver::test_connection(&client).await?;
|
||||
PoolKind::ClickHouse(client)
|
||||
}
|
||||
DatabaseType::SqlServer => {
|
||||
let client = db::sqlserver::connect(
|
||||
&host,
|
||||
port,
|
||||
&db_config.username,
|
||||
&db_config.password,
|
||||
db_config.database.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
PoolKind::SqlServer(Arc::new(tokio::sync::Mutex::new(client)))
|
||||
}
|
||||
DatabaseType::Oracle => {
|
||||
let client = db::oracle_driver::connect(
|
||||
&host,
|
||||
port,
|
||||
db_config.database.as_deref().unwrap_or("ORCL"),
|
||||
&db_config.username, &db_config.password,
|
||||
)
|
||||
.await?;
|
||||
PoolKind::Oracle(Arc::new(tokio::sync::Mutex::new(client)))
|
||||
}
|
||||
DatabaseType::Elasticsearch => {
|
||||
let client = db::elasticsearch_driver::EsClient::new(
|
||||
&url,
|
||||
Some(&db_config.username),
|
||||
Some(&db_config.password),
|
||||
);
|
||||
db::elasticsearch_driver::test_connection(&client).await?;
|
||||
PoolKind::Elasticsearch(client)
|
||||
}
|
||||
};
|
||||
|
||||
self.connections.lock().await.insert(pool_key.clone(), pool);
|
||||
Ok(pool_key)
|
||||
}
|
||||
|
||||
pub async fn connection_host_port(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
config: &ConnectionConfig,
|
||||
) -> Result<(String, u16), String> {
|
||||
if !config.ssh_enabled || config.ssh_host.is_empty() {
|
||||
return Ok((config.host.clone(), config.port));
|
||||
}
|
||||
|
||||
if let Some(local_port) = self.tunnels.local_port(connection_id).await {
|
||||
return Ok(("127.0.0.1".to_string(), local_port));
|
||||
}
|
||||
|
||||
let local_port = self
|
||||
.tunnels
|
||||
.start_tunnel(
|
||||
connection_id,
|
||||
&config.ssh_host,
|
||||
config.ssh_port,
|
||||
&config.ssh_user,
|
||||
&config.ssh_password,
|
||||
&config.ssh_key_path,
|
||||
&config.ssh_key_passphrase,
|
||||
&config.host,
|
||||
config.port,
|
||||
config.ssh_expose_lan,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(("127.0.0.1".to_string(), local_port))
|
||||
}
|
||||
|
||||
pub async fn reconnect_pool(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
database: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let is_single_conn = {
|
||||
let configs = self.configs.lock().await;
|
||||
configs.get(connection_id)
|
||||
.map(|c| c.db_type == DatabaseType::Oracle || c.db_type == DatabaseType::Elasticsearch)
|
||||
.unwrap_or(false)
|
||||
};
|
||||
let pool_key = if is_single_conn {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
match database {
|
||||
Some(db) => format!("{connection_id}:{db}"),
|
||||
None => connection_id.to_string(),
|
||||
}
|
||||
};
|
||||
self.connections.lock().await.remove(&pool_key);
|
||||
self.get_or_create_pool(connection_id, database).await
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connection_url_for_endpoint(config: &ConnectionConfig, host: &str, port: u16) -> String {
|
||||
if host == config.host && port == config.port {
|
||||
config.connection_url()
|
||||
} else {
|
||||
config.connection_url_with_host(host, port)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redacted_connection_url_for_endpoint(
|
||||
config: &ConnectionConfig,
|
||||
host: &str,
|
||||
port: u16,
|
||||
) -> String {
|
||||
if host == config.host && port == config.port {
|
||||
config.redacted_connection_url()
|
||||
} else {
|
||||
config.redacted_connection_url_with_host(host, port)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
use crate::models::connection::ConnectionConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const MAIN_PASSWORD_KEY: &str = "password";
|
||||
pub const SSH_PASSWORD_KEY: &str = "ssh_password";
|
||||
pub const SSH_KEY_PASSPHRASE_KEY: &str = "ssh_key_passphrase";
|
||||
pub const CONNECTION_STRING_KEY: &str = "connection_string";
|
||||
|
||||
pub trait ConnectionSecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String>;
|
||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String>;
|
||||
fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
pub struct FileSecretStore {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl FileSecretStore {
|
||||
pub fn new(path: PathBuf) -> Self {
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn read_store(&self) -> HashMap<String, String> {
|
||||
std::fs::read_to_string(&self.path)
|
||||
.ok()
|
||||
.and_then(|json| serde_json::from_str(&json).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_store(&self, map: &HashMap<String, String>) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(map).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&self.path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionSecretStore for FileSecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String> {
|
||||
let mut map = self.read_store();
|
||||
map.insert(secret_account(connection_id, key), secret.to_string());
|
||||
self.write_store(&map)
|
||||
}
|
||||
|
||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String> {
|
||||
Ok(self.read_store().get(&secret_account(connection_id, key)).cloned())
|
||||
}
|
||||
|
||||
fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String> {
|
||||
let mut map = self.read_store();
|
||||
map.remove(&secret_account(connection_id, key));
|
||||
self.write_store(&map)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_connections_to_file(
|
||||
path: &Path,
|
||||
configs: &[ConnectionConfig],
|
||||
store: &dyn ConnectionSecretStore,
|
||||
) -> Result<(), String> {
|
||||
delete_removed_connection_secrets(path, configs, store)?;
|
||||
for config in configs {
|
||||
persist_secret(store, &config.id, MAIN_PASSWORD_KEY, &config.password)?;
|
||||
persist_secret(store, &config.id, SSH_PASSWORD_KEY, &config.ssh_password)?;
|
||||
persist_secret(store, &config.id, SSH_KEY_PASSPHRASE_KEY, &config.ssh_key_passphrase)?;
|
||||
persist_optional_secret(
|
||||
store,
|
||||
&config.id,
|
||||
CONNECTION_STRING_KEY,
|
||||
config.connection_string.as_deref(),
|
||||
)?;
|
||||
}
|
||||
|
||||
write_sanitized_connections(path, configs)
|
||||
}
|
||||
|
||||
pub fn load_connections_from_file(
|
||||
path: &Path,
|
||||
store: &dyn ConnectionSecretStore,
|
||||
) -> Result<Vec<ConnectionConfig>, String> {
|
||||
if !path.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let mut configs = read_connections(path)?;
|
||||
let mut needs_rewrite = false;
|
||||
for config in &mut configs {
|
||||
if config.password.is_empty() {
|
||||
if let Some(secret) = store.get_secret(&config.id, MAIN_PASSWORD_KEY)? {
|
||||
config.password = secret;
|
||||
}
|
||||
} else {
|
||||
store.set_secret(&config.id, MAIN_PASSWORD_KEY, &config.password)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
|
||||
if config.ssh_password.is_empty() {
|
||||
if let Some(secret) = store.get_secret(&config.id, SSH_PASSWORD_KEY)? {
|
||||
config.ssh_password = secret;
|
||||
}
|
||||
} else {
|
||||
store.set_secret(&config.id, SSH_PASSWORD_KEY, &config.ssh_password)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
|
||||
if config.ssh_key_passphrase.is_empty() {
|
||||
if let Some(secret) = store.get_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)? {
|
||||
config.ssh_key_passphrase = secret;
|
||||
}
|
||||
} else {
|
||||
store.set_secret(&config.id, SSH_KEY_PASSPHRASE_KEY, &config.ssh_key_passphrase)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
|
||||
match config
|
||||
.connection_string
|
||||
.as_deref()
|
||||
.filter(|secret| !secret.is_empty())
|
||||
{
|
||||
Some(secret) => {
|
||||
store.set_secret(&config.id, CONNECTION_STRING_KEY, secret)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
None => {
|
||||
if let Some(secret) = store.get_secret(&config.id, CONNECTION_STRING_KEY)? {
|
||||
config.connection_string = Some(secret);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if needs_rewrite {
|
||||
write_sanitized_connections(path, &configs)?;
|
||||
}
|
||||
|
||||
Ok(configs)
|
||||
}
|
||||
|
||||
fn delete_removed_connection_secrets(
|
||||
path: &Path,
|
||||
configs: &[ConnectionConfig],
|
||||
store: &dyn ConnectionSecretStore,
|
||||
) -> Result<(), String> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let previous = match read_connections(path) {
|
||||
Ok(configs) => configs,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
let current_ids: HashSet<&str> = configs.iter().map(|config| config.id.as_str()).collect();
|
||||
for config in previous {
|
||||
if current_ids.contains(config.id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
store.delete_secret(&config.id, MAIN_PASSWORD_KEY)?;
|
||||
store.delete_secret(&config.id, SSH_PASSWORD_KEY)?;
|
||||
store.delete_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)?;
|
||||
store.delete_secret(&config.id, CONNECTION_STRING_KEY)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_secret(
|
||||
store: &dyn ConnectionSecretStore,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
secret: &str,
|
||||
) -> Result<(), String> {
|
||||
if secret.is_empty() {
|
||||
store.delete_secret(connection_id, key)
|
||||
} else {
|
||||
store.set_secret(connection_id, key, secret)
|
||||
}
|
||||
}
|
||||
|
||||
fn persist_optional_secret(
|
||||
store: &dyn ConnectionSecretStore,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
secret: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
match secret.filter(|secret| !secret.is_empty()) {
|
||||
Some(secret) => store.set_secret(connection_id, key, secret),
|
||||
None => store.delete_secret(connection_id, key),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_connections(path: &Path) -> Result<Vec<ConnectionConfig>, String> {
|
||||
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn write_sanitized_connections(path: &Path, configs: &[ConnectionConfig]) -> Result<(), String> {
|
||||
let sanitized = sanitize_connections(configs);
|
||||
let json = serde_json::to_string_pretty(&sanitized).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn sanitize_connections(configs: &[ConnectionConfig]) -> Vec<ConnectionConfig> {
|
||||
configs
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut config| {
|
||||
config.password.clear();
|
||||
config.ssh_password.clear();
|
||||
config.ssh_key_passphrase.clear();
|
||||
config.connection_string = None;
|
||||
config
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn secret_account(connection_id: &str, key: &str) -> String {
|
||||
format!("connection:{connection_id}:{key}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
load_connections_from_file, save_connections_to_file, ConnectionSecretStore,
|
||||
CONNECTION_STRING_KEY, MAIN_PASSWORD_KEY, SSH_PASSWORD_KEY,
|
||||
};
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Default)]
|
||||
struct MemorySecretStore {
|
||||
values: RefCell<HashMap<String, String>>,
|
||||
deleted: RefCell<Vec<String>>,
|
||||
}
|
||||
|
||||
impl MemorySecretStore {
|
||||
fn set_existing(&self, connection_id: &str, key: &str, value: &str) {
|
||||
self.values
|
||||
.borrow_mut()
|
||||
.insert(secret_key(connection_id, key), value.to_string());
|
||||
}
|
||||
|
||||
fn get_existing(&self, connection_id: &str, key: &str) -> Option<String> {
|
||||
self.values
|
||||
.borrow()
|
||||
.get(&secret_key(connection_id, key))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn was_deleted(&self, connection_id: &str, key: &str) -> bool {
|
||||
self.deleted
|
||||
.borrow()
|
||||
.contains(&secret_key(connection_id, key))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionSecretStore for MemorySecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String> {
|
||||
self.values
|
||||
.borrow_mut()
|
||||
.insert(secret_key(connection_id, key), secret.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String> {
|
||||
Ok(self
|
||||
.values
|
||||
.borrow()
|
||||
.get(&secret_key(connection_id, key))
|
||||
.cloned())
|
||||
}
|
||||
|
||||
fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String> {
|
||||
self.values
|
||||
.borrow_mut()
|
||||
.remove(&secret_key(connection_id, key));
|
||||
self.deleted
|
||||
.borrow_mut()
|
||||
.push(secret_key(connection_id, key));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn secret_key(connection_id: &str, key: &str) -> String {
|
||||
format!("{connection_id}:{key}")
|
||||
}
|
||||
|
||||
fn temp_connections_file(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"dbx-connection-secrets-test-{}-{name}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir.join("connections.json")
|
||||
}
|
||||
|
||||
fn connection(id: &str, password: &str, ssh_password: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
id: id.to_string(),
|
||||
name: format!("{id} connection"),
|
||||
db_type: DatabaseType::Postgres,
|
||||
driver_profile: None,
|
||||
driver_label: None,
|
||||
url_params: None,
|
||||
host: "localhost".to_string(),
|
||||
port: 5432,
|
||||
username: "postgres".to_string(),
|
||||
password: password.to_string(),
|
||||
database: Some("postgres".to_string()),
|
||||
color: None,
|
||||
ssh_enabled: !ssh_password.is_empty(),
|
||||
ssh_host: String::new(),
|
||||
ssh_port: 22,
|
||||
ssh_user: String::new(),
|
||||
ssh_password: ssh_password.to_string(),
|
||||
ssh_key_path: String::new(),
|
||||
ssh_key_passphrase: String::new(),
|
||||
ssh_expose_lan: false,
|
||||
ssl: false,
|
||||
connection_string: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_configs(path: &Path) -> Vec<ConnectionConfig> {
|
||||
let json = std::fs::read_to_string(path).unwrap();
|
||||
serde_json::from_str(&json).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_connections_moves_passwords_to_secret_store_and_redacts_file() {
|
||||
let path = temp_connections_file("save-redacts");
|
||||
let store = MemorySecretStore::default();
|
||||
let configs = vec![connection("main", "db-secret", "ssh-secret")];
|
||||
|
||||
save_connections_to_file(&path, &configs, &store).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.get_existing("main", MAIN_PASSWORD_KEY).as_deref(),
|
||||
Some("db-secret")
|
||||
);
|
||||
assert_eq!(
|
||||
store.get_existing("main", SSH_PASSWORD_KEY).as_deref(),
|
||||
Some("ssh-secret")
|
||||
);
|
||||
let persisted = read_configs(&path);
|
||||
assert_eq!(persisted[0].password, "");
|
||||
assert_eq!(persisted[0].ssh_password, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_connections_restores_passwords_from_secret_store() {
|
||||
let path = temp_connections_file("load-restores");
|
||||
let store = MemorySecretStore::default();
|
||||
store.set_existing("main", MAIN_PASSWORD_KEY, "db-secret");
|
||||
store.set_existing("main", SSH_PASSWORD_KEY, "ssh-secret");
|
||||
let sanitized = vec![connection("main", "", "")];
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&sanitized).unwrap()).unwrap();
|
||||
|
||||
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||
|
||||
assert_eq!(loaded[0].password, "db-secret");
|
||||
assert_eq!(loaded[0].ssh_password, "ssh-secret");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_connections_migrates_plaintext_passwords_and_rewrites_sanitized_file() {
|
||||
let path = temp_connections_file("migrates-plaintext");
|
||||
let store = MemorySecretStore::default();
|
||||
let legacy = vec![connection("legacy", "plain-db", "plain-ssh")];
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&legacy).unwrap()).unwrap();
|
||||
|
||||
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||
|
||||
assert_eq!(loaded[0].password, "plain-db");
|
||||
assert_eq!(loaded[0].ssh_password, "plain-ssh");
|
||||
assert_eq!(
|
||||
store.get_existing("legacy", MAIN_PASSWORD_KEY).as_deref(),
|
||||
Some("plain-db")
|
||||
);
|
||||
assert_eq!(
|
||||
store.get_existing("legacy", SSH_PASSWORD_KEY).as_deref(),
|
||||
Some("plain-ssh")
|
||||
);
|
||||
let persisted = read_configs(&path);
|
||||
assert_eq!(persisted[0].password, "");
|
||||
assert_eq!(persisted[0].ssh_password, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_connections_deletes_secrets_for_removed_connections() {
|
||||
let path = temp_connections_file("deletes-removed");
|
||||
let store = MemorySecretStore::default();
|
||||
let previous = vec![connection("old", "", ""), connection("kept", "", "")];
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&previous).unwrap()).unwrap();
|
||||
store.set_existing("old", MAIN_PASSWORD_KEY, "old-db");
|
||||
store.set_existing("old", SSH_PASSWORD_KEY, "old-ssh");
|
||||
store.set_existing("kept", MAIN_PASSWORD_KEY, "kept-db");
|
||||
|
||||
save_connections_to_file(&path, &[connection("kept", "new-db", "")], &store).unwrap();
|
||||
|
||||
assert!(store.was_deleted("old", MAIN_PASSWORD_KEY));
|
||||
assert!(store.was_deleted("old", SSH_PASSWORD_KEY));
|
||||
assert_eq!(
|
||||
store.get_existing("kept", MAIN_PASSWORD_KEY).as_deref(),
|
||||
Some("new-db")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_connections_moves_connection_string_to_secret_store_and_restores_it() {
|
||||
let path = temp_connections_file("connection-string");
|
||||
let store = MemorySecretStore::default();
|
||||
let mut config = connection("mongo", "", "");
|
||||
config.db_type = DatabaseType::MongoDb;
|
||||
config.connection_string = Some("mongodb://user:secret@localhost/app".to_string());
|
||||
|
||||
save_connections_to_file(&path, &[config], &store).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store
|
||||
.get_existing("mongo", CONNECTION_STRING_KEY)
|
||||
.as_deref(),
|
||||
Some("mongodb://user:secret@localhost/app")
|
||||
);
|
||||
let persisted = read_configs(&path);
|
||||
assert_eq!(persisted[0].connection_string, None);
|
||||
|
||||
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||
assert_eq!(
|
||||
loaded[0].connection_string.as_deref(),
|
||||
Some("mongodb://user:secret@localhost/app")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use reqwest::Client as HttpClient;
|
||||
use serde::Deserialize;
|
||||
use std::time::Instant;
|
||||
|
||||
use super::{ColumnInfo, DatabaseInfo, QueryResult, TableInfo};
|
||||
use crate::types::{ColumnInfo, DatabaseInfo, QueryResult, TableInfo};
|
||||
|
||||
pub struct ChClient {
|
||||
http: HttpClient,
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
use reqwest::Client as HttpClient;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::mongo_driver::MongoDocumentResult;
|
||||
use crate::db::mongo_driver::MongoDocumentResult;
|
||||
|
||||
pub struct EsClient {
|
||||
http: HttpClient,
|
||||
@@ -0,0 +1,13 @@
|
||||
pub mod clickhouse_driver;
|
||||
pub mod elasticsearch_driver;
|
||||
pub mod mongo_driver;
|
||||
pub mod mysql;
|
||||
pub mod oracle_driver;
|
||||
pub mod postgres;
|
||||
pub mod redis_driver;
|
||||
pub mod sqlite;
|
||||
pub mod sqlserver;
|
||||
pub mod ssh_tunnel;
|
||||
|
||||
// Re-export types so that `db::QueryResult` etc. work within dbx-core
|
||||
pub use crate::types::*;
|
||||
@@ -4,7 +4,7 @@ use sqlx::mysql::{MySqlPool, MySqlPoolOptions, MySqlRow};
|
||||
use sqlx::{Column, Executor, Row, TypeInfo, ValueRef};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
use crate::types::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
|
||||
fn quote_value(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'"))
|
||||
@@ -1,7 +1,7 @@
|
||||
use oracle_rs::{Config, Connection};
|
||||
use std::time::Instant;
|
||||
|
||||
use super::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
use crate::types::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
|
||||
pub type OracleClient = Connection;
|
||||
|
||||
@@ -4,7 +4,7 @@ use sqlx::postgres::{PgPool, PgPoolOptions, PgRow};
|
||||
use sqlx::{Column, Executor, Row, TypeInfo, ValueRef};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
use crate::types::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
|
||||
fn pg_temporal_to_json_value(row: &PgRow, idx: usize) -> Option<serde_json::Value> {
|
||||
if let Ok(v) = row.try_get::<DateTime<Utc>, _>(idx) {
|
||||
@@ -2,7 +2,7 @@ use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRo
|
||||
use sqlx::{Column, Executor, Row};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
use crate::types::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
|
||||
pub async fn connect_path(path: &str) -> Result<SqlitePool, String> {
|
||||
let mut options = SqliteConnectOptions::new()
|
||||
@@ -4,7 +4,7 @@ use tokio::net::TcpStream;
|
||||
use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt};
|
||||
use std::time::Instant;
|
||||
|
||||
use super::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
use crate::types::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, QueryResult, TableInfo, TriggerInfo};
|
||||
|
||||
pub type SqlServerClient = Client<Compat<TcpStream>>;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HistoryEntry {
|
||||
pub id: String,
|
||||
pub connection_name: String,
|
||||
pub database: String,
|
||||
pub sql: String,
|
||||
pub executed_at: String,
|
||||
pub execution_time_ms: u128,
|
||||
pub success: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub const MAX_HISTORY: usize = 1000;
|
||||
|
||||
pub fn read_all(path: &Path) -> Result<Vec<HistoryEntry>, String> {
|
||||
if !path.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn write_all(path: &Path, entries: &[HistoryEntry]) -> Result<(), String> {
|
||||
let json = serde_json::to_string(entries).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn save_history_entry(path: &Path, entry: HistoryEntry) -> Result<(), String> {
|
||||
let mut entries = read_all(path)?;
|
||||
entries.insert(0, entry);
|
||||
entries.truncate(MAX_HISTORY);
|
||||
write_all(path, &entries)
|
||||
}
|
||||
|
||||
pub fn load_history_entries(path: &Path, limit: usize, offset: usize) -> Result<Vec<HistoryEntry>, String> {
|
||||
let entries = read_all(path)?;
|
||||
Ok(entries.into_iter().skip(offset).take(limit).collect())
|
||||
}
|
||||
|
||||
pub fn clear_history_entries(path: &Path) -> Result<(), String> {
|
||||
write_all(path, &[])
|
||||
}
|
||||
|
||||
pub fn delete_history_entry_by_id(path: &Path, id: &str) -> Result<(), String> {
|
||||
let entries: Vec<HistoryEntry> = read_all(path)?
|
||||
.into_iter()
|
||||
.filter(|e| e.id != id)
|
||||
.collect();
|
||||
write_all(path, &entries)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub mod ai;
|
||||
pub mod connection;
|
||||
pub mod connection_secrets;
|
||||
pub mod db;
|
||||
pub mod history;
|
||||
pub mod models;
|
||||
pub mod mongo_ops;
|
||||
pub mod query;
|
||||
pub mod query_cancel;
|
||||
pub mod redis_ops;
|
||||
pub mod schema;
|
||||
pub mod sql;
|
||||
pub mod table_import;
|
||||
pub mod transfer;
|
||||
pub mod types;
|
||||
pub mod update;
|
||||
@@ -0,0 +1,353 @@
|
||||
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ConnectionConfig {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub db_type: DatabaseType,
|
||||
#[serde(default)]
|
||||
pub driver_profile: Option<String>,
|
||||
#[serde(default)]
|
||||
pub driver_label: Option<String>,
|
||||
#[serde(default)]
|
||||
pub url_params: Option<String>,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub database: Option<String>,
|
||||
#[serde(default)]
|
||||
pub color: Option<String>,
|
||||
#[serde(default)]
|
||||
pub ssh_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub ssh_host: String,
|
||||
#[serde(default = "default_ssh_port")]
|
||||
pub ssh_port: u16,
|
||||
#[serde(default)]
|
||||
pub ssh_user: String,
|
||||
#[serde(default)]
|
||||
pub ssh_password: String,
|
||||
#[serde(default)]
|
||||
pub ssh_key_path: String,
|
||||
#[serde(default)]
|
||||
pub ssh_key_passphrase: String,
|
||||
#[serde(default)]
|
||||
pub ssh_expose_lan: bool,
|
||||
#[serde(default)]
|
||||
pub ssl: bool,
|
||||
#[serde(default)]
|
||||
pub connection_string: Option<String>,
|
||||
}
|
||||
|
||||
fn default_ssh_port() -> u16 {
|
||||
22
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DatabaseType {
|
||||
Mysql,
|
||||
Postgres,
|
||||
Sqlite,
|
||||
Redis,
|
||||
#[serde(rename = "duckdb")]
|
||||
DuckDb,
|
||||
#[serde(rename = "clickhouse")]
|
||||
ClickHouse,
|
||||
#[serde(rename = "sqlserver")]
|
||||
SqlServer,
|
||||
#[serde(rename = "mongodb")]
|
||||
MongoDb,
|
||||
#[serde(rename = "oracle")]
|
||||
Oracle,
|
||||
#[serde(rename = "elasticsearch")]
|
||||
Elasticsearch,
|
||||
Doris,
|
||||
#[serde(rename = "starrocks")]
|
||||
StarRocks,
|
||||
Redshift,
|
||||
}
|
||||
|
||||
impl ConnectionConfig {
|
||||
pub fn needs_bare_mysql(&self) -> bool {
|
||||
matches!(self.db_type, DatabaseType::Doris | DatabaseType::StarRocks)
|
||||
|| self.driver_profile.as_deref().map(|p| p.to_lowercase())
|
||||
.is_some_and(|p| matches!(p.as_str(), "doris" | "starrocks" | "selectdb" | "tdengine"))
|
||||
}
|
||||
|
||||
pub fn connection_url(&self) -> String {
|
||||
self.connection_url_with_host(&self.host, self.port)
|
||||
}
|
||||
|
||||
pub fn redacted_connection_url(&self) -> String {
|
||||
self.redacted_connection_url_with_host(&self.host, self.port)
|
||||
}
|
||||
|
||||
pub fn redacted_connection_url_with_host(&self, host: &str, port: u16) -> String {
|
||||
let host = bracket_ipv6(host);
|
||||
let db_part = self
|
||||
.database
|
||||
.as_deref()
|
||||
.filter(|d| !d.is_empty())
|
||||
.map(|d| format!("/{}", encode_url_part(d)))
|
||||
.unwrap_or_default();
|
||||
let params = self.normalized_url_params();
|
||||
|
||||
match self.db_type {
|
||||
DatabaseType::Sqlite | DatabaseType::DuckDb => {
|
||||
format!("{}?mode=rwc", self.host)
|
||||
}
|
||||
DatabaseType::Redis => {
|
||||
let scheme = if self.ssl { "rediss" } else { "redis" };
|
||||
format!("{scheme}://{host}:{port}/")
|
||||
}
|
||||
DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks => format!("mysql://{host}:{port}{db_part}?{params}"),
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => {
|
||||
let suffix = if params.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("?{params}")
|
||||
};
|
||||
format!("postgres://{host}:{port}{db_part}{suffix}")
|
||||
}
|
||||
DatabaseType::ClickHouse => format!("http://{host}:{port}"),
|
||||
DatabaseType::SqlServer => format!(
|
||||
"server=tcp:{host},{port};database={}",
|
||||
self.database.as_deref().unwrap_or("master")
|
||||
),
|
||||
DatabaseType::MongoDb => {
|
||||
if let Some(cs) = self.connection_string.as_deref().filter(|s| !s.is_empty()) {
|
||||
return cs.to_string();
|
||||
}
|
||||
format!("mongodb://{host}:{port}{db_part}")
|
||||
}
|
||||
DatabaseType::Oracle => format!("oracle://{host}:{port}{db_part}"),
|
||||
DatabaseType::Elasticsearch => format!("http://{host}:{port}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connection_url_with_host(&self, host: &str, port: u16) -> String {
|
||||
let host = bracket_ipv6(host);
|
||||
let db_part = self
|
||||
.database
|
||||
.as_deref()
|
||||
.filter(|d| !d.is_empty())
|
||||
.map(|d| format!("/{}", encode_url_part(d)))
|
||||
.unwrap_or_default();
|
||||
let username = encode_url_part(&self.username);
|
||||
let password = encode_url_part(&self.password);
|
||||
let params = self.normalized_url_params();
|
||||
|
||||
match self.db_type {
|
||||
DatabaseType::Sqlite | DatabaseType::DuckDb => {
|
||||
format!("{}?mode=rwc", self.host)
|
||||
}
|
||||
DatabaseType::Redis => {
|
||||
let scheme = if self.ssl { "rediss" } else { "redis" };
|
||||
if self.username.is_empty() && self.password.is_empty() {
|
||||
format!("{scheme}://{host}:{port}/")
|
||||
} else if self.username.is_empty() {
|
||||
format!("{scheme}://:{password}@{host}:{port}/")
|
||||
} else {
|
||||
format!("{scheme}://{username}:{password}@{host}:{port}/")
|
||||
}
|
||||
}
|
||||
DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks => format!(
|
||||
"mysql://{}:{}@{host}:{port}{db_part}?{params}",
|
||||
username, password
|
||||
),
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => {
|
||||
let suffix = if params.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("?{params}")
|
||||
};
|
||||
format!(
|
||||
"postgres://{}:{}@{host}:{port}{db_part}{suffix}",
|
||||
username, password
|
||||
)
|
||||
}
|
||||
DatabaseType::ClickHouse => format!("http://{host}:{port}"),
|
||||
DatabaseType::SqlServer => format!(
|
||||
"server=tcp:{host},{port};user={};password={};database={}",
|
||||
self.username,
|
||||
self.password,
|
||||
self.database.as_deref().unwrap_or("master")
|
||||
),
|
||||
DatabaseType::MongoDb => {
|
||||
if let Some(cs) = self.connection_string.as_deref().filter(|s| !s.is_empty()) {
|
||||
return cs.to_string();
|
||||
}
|
||||
if self.username.is_empty() {
|
||||
format!("mongodb://{host}:{port}{db_part}")
|
||||
} else {
|
||||
format!("mongodb://{username}:{password}@{host}:{port}{db_part}")
|
||||
}
|
||||
}
|
||||
DatabaseType::Oracle => {
|
||||
format!("oracle://{}:{}@{host}:{port}{db_part}", username, password)
|
||||
}
|
||||
DatabaseType::Elasticsearch => format!("http://{host}:{port}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_url_params(&self) -> String {
|
||||
let value = self.url_params.as_deref().unwrap_or("").trim();
|
||||
if self.needs_bare_mysql() {
|
||||
let v = value.trim_start_matches('?');
|
||||
let filtered: Vec<&str> = v.split('&')
|
||||
.filter(|p| !p.is_empty() && !p.starts_with("charset=") && !p.starts_with("ssl-mode=preferred"))
|
||||
.collect();
|
||||
return if filtered.is_empty() { "ssl-mode=disabled".to_string() } else { format!("ssl-mode=disabled&{}", filtered.join("&")) };
|
||||
}
|
||||
match self.db_type {
|
||||
DatabaseType::Mysql => {
|
||||
let base = "ssl-mode=preferred&charset=utf8mb4";
|
||||
if value.is_empty() {
|
||||
base.to_string()
|
||||
} else if value.contains("ssl-mode=") {
|
||||
let v = value.trim_start_matches('?');
|
||||
if v.contains("charset=") { v.to_string() } else { format!("{v}&charset=utf8mb4") }
|
||||
} else {
|
||||
let v = value.trim_start_matches('?');
|
||||
if v.contains("charset=") { format!("ssl-mode=preferred&{v}") } else { format!("{base}&{v}") }
|
||||
}
|
||||
}
|
||||
DatabaseType::Doris | DatabaseType::StarRocks => {
|
||||
let v = value.trim_start_matches('?');
|
||||
let filtered: Vec<&str> = v.split('&')
|
||||
.filter(|p| !p.is_empty() && !p.starts_with("charset=") && !p.starts_with("ssl-mode=preferred"))
|
||||
.collect();
|
||||
if filtered.is_empty() { "ssl-mode=disabled".to_string() } else { format!("ssl-mode=disabled&{}", filtered.join("&")) }
|
||||
}
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => value.trim_start_matches('?').to_string(),
|
||||
_ => value.trim_start_matches('?').to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_url_part(value: &str) -> String {
|
||||
utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
|
||||
}
|
||||
|
||||
fn bracket_ipv6(host: &str) -> String {
|
||||
if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{host}]")
|
||||
} else {
|
||||
host.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ConnectionConfig, DatabaseType};
|
||||
|
||||
fn mysql_config(username: &str, password: &str, database: Option<&str>) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
id: "id".to_string(),
|
||||
name: "name".to_string(),
|
||||
db_type: DatabaseType::Mysql,
|
||||
driver_profile: None,
|
||||
driver_label: None,
|
||||
url_params: None,
|
||||
host: "10.1.2.3".to_string(),
|
||||
port: 2883,
|
||||
username: username.to_string(),
|
||||
password: password.to_string(),
|
||||
database: database.map(str::to_string),
|
||||
color: None,
|
||||
ssh_enabled: false,
|
||||
ssh_host: String::new(),
|
||||
ssh_port: 22,
|
||||
ssh_user: String::new(),
|
||||
ssh_password: String::new(),
|
||||
ssh_key_path: String::new(),
|
||||
ssh_key_passphrase: String::new(),
|
||||
ssh_expose_lan: false,
|
||||
ssl: false,
|
||||
connection_string: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_url_encodes_oceanbase_username() {
|
||||
let config = mysql_config("user@tenant#cluster", "secret", None);
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"mysql://user%40tenant%23cluster:secret@10.1.2.3:2883?ssl-mode=preferred&charset=utf8mb4"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_url_encodes_password_and_database() {
|
||||
let config = mysql_config("root", "p@ss:word#1", Some("db/name"));
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"mysql://root:p%40ss%3Aword%231@10.1.2.3:2883/db%2Fname?ssl-mode=preferred&charset=utf8mb4"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_url_appends_custom_params() {
|
||||
let mut config = mysql_config("root", "secret", Some("test"));
|
||||
config.url_params = Some("charset=utf8mb4".to_string());
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"mysql://root:secret@10.1.2.3:2883/test?ssl-mode=preferred&charset=utf8mb4"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_url_appends_custom_params() {
|
||||
let mut config = mysql_config("postgres", "secret", Some("test"));
|
||||
config.db_type = DatabaseType::Postgres;
|
||||
config.url_params = Some("sslmode=disable".to_string());
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"postgres://postgres:secret@10.1.2.3:2883/test?sslmode=disable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_mysql_url_omits_credentials() {
|
||||
let config = mysql_config("user@tenant#cluster", "p@ss:word#1", Some("db/name"));
|
||||
|
||||
let url = config.redacted_connection_url();
|
||||
|
||||
assert_eq!(url, "mysql://10.1.2.3:2883/db%2Fname?ssl-mode=preferred&charset=utf8mb4");
|
||||
assert!(!url.contains("user"));
|
||||
assert!(!url.contains("p%40ss"));
|
||||
assert!(!url.contains("p@ss"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_sqlserver_url_omits_credentials() {
|
||||
let mut config = mysql_config("sa", "super-secret", Some("master"));
|
||||
config.db_type = DatabaseType::SqlServer;
|
||||
|
||||
let url = config.redacted_connection_url();
|
||||
|
||||
assert_eq!(url, "server=tcp:10.1.2.3,2883;database=master");
|
||||
assert!(!url.contains("sa"));
|
||||
assert!(!url.contains("super-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_redis_url_omits_credentials_and_keeps_tls_scheme() {
|
||||
let mut config = mysql_config("default", "redis-secret", None);
|
||||
config.db_type = DatabaseType::Redis;
|
||||
config.ssl = true;
|
||||
|
||||
let url = config.redacted_connection_url();
|
||||
|
||||
assert_eq!(url, "rediss://10.1.2.3:2883/");
|
||||
assert!(!url.contains("default"));
|
||||
assert!(!url.contains("redis-secret"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod connection;
|
||||
@@ -0,0 +1,114 @@
|
||||
use crate::connection::{AppState, PoolKind};
|
||||
use crate::db::mongo_driver::{self, MongoDocumentResult};
|
||||
use crate::db::elasticsearch_driver;
|
||||
|
||||
pub async fn mongo_list_databases_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => mongo_driver::list_databases(client).await,
|
||||
PoolKind::Elasticsearch(_) => Ok(vec!["default".to_string()]),
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mongo_list_collections_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => mongo_driver::list_collections(client, database).await,
|
||||
PoolKind::Elasticsearch(client) => elasticsearch_driver::list_indices(client).await,
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mongo_find_documents_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
collection: &str,
|
||||
skip: u64,
|
||||
limit: i64,
|
||||
) -> Result<MongoDocumentResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::find_documents(client, database, collection, skip, limit).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::find_documents(&client, collection, skip, limit).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mongo_insert_document_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
collection: &str,
|
||||
doc_json: &str,
|
||||
) -> Result<String, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::insert_document(client, database, collection, doc_json).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::insert_document(&client, collection, doc_json).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mongo_update_document_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
collection: &str,
|
||||
id: &str,
|
||||
doc_json: &str,
|
||||
) -> Result<u64, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::update_document(client, database, collection, id, doc_json).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::update_document(&client, collection, id, doc_json).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mongo_delete_document_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
collection: &str,
|
||||
id: &str,
|
||||
) -> Result<u64, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::delete_document(client, database, collection, id).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::delete_document(&client, collection, id).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::connection::{AppState, PoolKind};
|
||||
use crate::db;
|
||||
use crate::sql::split_sql_statements;
|
||||
|
||||
pub const QUERY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub const MAX_ROWS: usize = 10000;
|
||||
pub const QUERY_CANCELED: &str = "Query canceled";
|
||||
|
||||
pub fn duckdb_execute(con: &duckdb::Connection, sql: &str) -> Result<db::QueryResult, String> {
|
||||
let start = std::time::Instant::now();
|
||||
let trimmed = sql.trim().to_uppercase();
|
||||
|
||||
if trimmed.starts_with("SELECT") || trimmed.starts_with("SHOW") || trimmed.starts_with("DESCRIBE")
|
||||
|| trimmed.starts_with("EXPLAIN") || trimmed.starts_with("WITH") || trimmed.starts_with("PRAGMA")
|
||||
{
|
||||
let mut stmt = con.prepare(sql).map_err(|e| e.to_string())?;
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
let stmt_ref = rows.as_ref().ok_or("DuckDB statement unavailable")?;
|
||||
let col_count = stmt_ref.column_count();
|
||||
let columns: Vec<String> = (0..col_count)
|
||||
.map(|i| stmt_ref.column_name(i).map(|s| s.to_string()).unwrap_or_else(|_| "?".to_string()))
|
||||
.collect();
|
||||
|
||||
let mut result_rows = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
if result_rows.len() >= MAX_ROWS { break; }
|
||||
let vals: Vec<serde_json::Value> = (0..col_count).map(|i| {
|
||||
row.get::<_, String>(i)
|
||||
.map(serde_json::Value::String)
|
||||
.or_else(|_| row.get::<_, i64>(i).map(|v| serde_json::Value::Number(v.into())))
|
||||
.or_else(|_| row.get::<_, f64>(i).map(|v| {
|
||||
serde_json::Number::from_f64(v)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}))
|
||||
.or_else(|_| row.get::<_, bool>(i).map(serde_json::Value::Bool))
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}).collect();
|
||||
result_rows.push(vals);
|
||||
}
|
||||
|
||||
let truncated = result_rows.len() >= MAX_ROWS;
|
||||
Ok(db::QueryResult { columns, rows: result_rows, affected_rows: 0, execution_time_ms: start.elapsed().as_millis(), truncated })
|
||||
} else {
|
||||
let affected = con.execute(sql, []).map_err(|e| e.to_string())?;
|
||||
Ok(db::QueryResult { columns: vec![], rows: vec![], affected_rows: affected as u64, execution_time_ms: start.elapsed().as_millis(), truncated: false })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn truncate_result(mut result: db::QueryResult) -> db::QueryResult {
|
||||
if result.rows.len() > MAX_ROWS {
|
||||
result.rows.truncate(MAX_ROWS);
|
||||
result.truncated = true;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn is_connection_error(err: &str) -> bool {
|
||||
let lower = err.to_lowercase();
|
||||
lower.contains("connection")
|
||||
|| lower.contains("broken pipe")
|
||||
|| lower.contains("reset by peer")
|
||||
|| lower.contains("timed out")
|
||||
|| lower.contains("closed")
|
||||
|| lower.contains("eof")
|
||||
}
|
||||
|
||||
pub fn timeout_error() -> String {
|
||||
format!("Query timed out after {} seconds", QUERY_TIMEOUT.as_secs())
|
||||
}
|
||||
|
||||
pub fn canceled_error() -> String {
|
||||
QUERY_CANCELED.to_string()
|
||||
}
|
||||
|
||||
pub fn is_canceled(cancel_token: &Option<CancellationToken>) -> bool {
|
||||
cancel_token
|
||||
.as_ref()
|
||||
.map(|token| token.is_cancelled())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub async fn wait_for_query<F>(
|
||||
cancel_token: Option<CancellationToken>,
|
||||
future: F,
|
||||
) -> Result<db::QueryResult, String>
|
||||
where
|
||||
F: Future<Output = Result<db::QueryResult, String>>,
|
||||
{
|
||||
wait_for_query_with_timeout(cancel_token, QUERY_TIMEOUT, future).await
|
||||
}
|
||||
|
||||
pub async fn wait_for_query_with_timeout<F>(
|
||||
cancel_token: Option<CancellationToken>,
|
||||
timeout_duration: Duration,
|
||||
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(timeout_duration, future) => result.map_err(|_| timeout_error())?,
|
||||
}
|
||||
} else {
|
||||
timeout(timeout_duration, future)
|
||||
.await
|
||||
.map_err(|_| timeout_error())?
|
||||
}
|
||||
}
|
||||
|
||||
pub 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")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::DuckDb(con) => {
|
||||
let con = con.clone();
|
||||
let sql = sql.to_string();
|
||||
drop(connections);
|
||||
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, bare) => {
|
||||
let p = p.clone();
|
||||
let bare = *bare;
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::mysql::execute_query(&p, sql, bare))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::postgres::execute_query(&p, sql))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::sqlite::execute_query(&p, sql))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::ClickHouse(client) => {
|
||||
let client = client.clone();
|
||||
let database = pool_key.split(':').nth(1).unwrap_or("default").to_string();
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::clickhouse_driver::execute_query(&client, &database, sql))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::SqlServer(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
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(truncate_result)
|
||||
}
|
||||
PoolKind::Oracle(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
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(truncate_result)
|
||||
}
|
||||
PoolKind::Elasticsearch(_) => Err("Use document browser for Elasticsearch".to_string()),
|
||||
PoolKind::Redis(_) => Err("Use Redis-specific commands".to_string()),
|
||||
PoolKind::MongoDb(_) => Err("Use MongoDB-specific commands".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn execute_sql_statement(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
sql: &str,
|
||||
cancel_token: Option<CancellationToken>,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let pool_key = if database.is_empty() {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
state.get_or_create_pool(connection_id, Some(database)).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) && !is_canceled(&cancel_token) => {
|
||||
let db_opt = if database.is_empty() { None } else { Some(database) };
|
||||
let new_key = state.reconnect_pool(connection_id, db_opt).await?;
|
||||
do_execute(state, &new_key, sql, cancel_token).await
|
||||
}
|
||||
_ => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn execute_multi_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
sql: &str,
|
||||
cancel_token: Option<CancellationToken>,
|
||||
) -> Result<Vec<db::QueryResult>, String> {
|
||||
let statements = split_sql_statements(sql);
|
||||
if statements.len() <= 1 {
|
||||
let single_sql = statements.into_iter().next().unwrap_or_default();
|
||||
let result = execute_sql_statement(
|
||||
state, connection_id, database, &single_sql, cancel_token,
|
||||
).await?;
|
||||
return Ok(vec![result]);
|
||||
}
|
||||
|
||||
let mut results = Vec::with_capacity(statements.len());
|
||||
for stmt in &statements {
|
||||
if is_canceled(&cancel_token) {
|
||||
results.push(db::QueryResult {
|
||||
columns: vec!["Error".to_string()],
|
||||
rows: vec![vec![serde_json::Value::String(canceled_error())]],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
match execute_sql_statement(
|
||||
state, connection_id, database, stmt, cancel_token.clone(),
|
||||
).await {
|
||||
Ok(r) => results.push(r),
|
||||
Err(e) => {
|
||||
results.push(db::QueryResult {
|
||||
columns: vec!["Error".to_string()],
|
||||
rows: vec![vec![serde_json::Value::String(e)]],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
pub async fn execute_statements(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
statements: &[String],
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let pool_key = if database.is_empty() {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
state.get_or_create_pool(connection_id, Some(database)).await?
|
||||
};
|
||||
|
||||
let mut total_affected: u64 = 0;
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
for (i, sql) in statements.iter().enumerate() {
|
||||
match do_execute(state, &pool_key, sql, None).await {
|
||||
Ok(result) => {
|
||||
total_affected += result.affected_rows;
|
||||
}
|
||||
Err(e) => {
|
||||
if is_connection_error(&e) {
|
||||
let db_opt = if database.is_empty() { None } else { Some(database) };
|
||||
let _ = state.reconnect_pool(connection_id, db_opt).await;
|
||||
}
|
||||
return Err(format!(
|
||||
"Statement {} failed: {}. Previous {} statement(s) may have been committed.",
|
||||
i + 1, e, i
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(db::QueryResult {
|
||||
columns: vec![],
|
||||
rows: vec![],
|
||||
affected_rows: total_affected,
|
||||
execution_time_ms: start.elapsed().as_millis(),
|
||||
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);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wait_for_query_without_token_still_times_out() {
|
||||
let result = wait_for_query_with_timeout(None, Duration::from_millis(10), async {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
Ok(db::QueryResult {
|
||||
columns: vec![],
|
||||
rows: vec![],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(result.unwrap_err(), timeout_error());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use crate::connection::{AppState, PoolKind};
|
||||
use crate::db::redis_driver::{self, RedisScanResult, RedisValue};
|
||||
|
||||
pub async fn redis_list_databases_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
) -> Result<Vec<u32>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::list_databases(&mut con).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_scan_keys_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
db: u32,
|
||||
cursor: u64,
|
||||
pattern: &str,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::scan_keys_page(&mut con, cursor, pattern, count).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_get_value_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
) -> Result<RedisValue, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::get_value(&mut con, key).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_set_string_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
value: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::set_string(&mut con, key, value, ttl).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_delete_key_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::delete_key(&mut con, key).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_hash_set_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
field: &str,
|
||||
value: &str,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::hash_set(&mut *con.lock().await, key, field, value).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_hash_del_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
field: &str,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::hash_del(&mut *con.lock().await, key, field).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_list_push_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
value: &str,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::list_push(&mut *con.lock().await, key, value).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_list_remove_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
index: i64,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::list_remove(&mut *con.lock().await, key, index).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_set_add_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
member: &str,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::set_add(&mut *con.lock().await, key, member).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn redis_set_remove_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
member: &str,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::set_remove(&mut *con.lock().await, key, member).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::connection::{AppState, PoolKind};
|
||||
use crate::db;
|
||||
|
||||
pub fn duckdb_query_tables(con: &duckdb::Connection) -> Result<Vec<db::TableInfo>, String> {
|
||||
let mut stmt = con.prepare(
|
||||
"SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'main' ORDER BY table_name"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok(db::TableInfo {
|
||||
name: row.get::<_, String>(0)?,
|
||||
table_type: row.get::<_, String>(1)?,
|
||||
})
|
||||
}).map_err(|e| e.to_string())?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
pub fn duckdb_query_columns(con: &duckdb::Connection, table: &str) -> Result<Vec<db::ColumnInfo>, String> {
|
||||
let mut pk_stmt = con.prepare(
|
||||
"SELECT kcu.column_name
|
||||
FROM information_schema.table_constraints tc
|
||||
JOIN information_schema.key_column_usage kcu
|
||||
ON tc.constraint_name = kcu.constraint_name
|
||||
AND tc.table_schema = kcu.table_schema
|
||||
AND tc.table_name = kcu.table_name
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY'
|
||||
AND tc.table_schema = 'main'
|
||||
AND tc.table_name = ?
|
||||
ORDER BY kcu.ordinal_position"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let pk_rows = pk_stmt.query_map([table], |row| row.get::<_, String>(0))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let primary_keys: std::collections::HashSet<String> = pk_rows.filter_map(|r| r.ok()).collect();
|
||||
|
||||
let mut stmt = con.prepare(
|
||||
"SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'main' AND table_name = ?
|
||||
ORDER BY ordinal_position"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let rows = stmt.query_map([table], |row| {
|
||||
let name = row.get::<_, String>(0)?;
|
||||
Ok(db::ColumnInfo {
|
||||
is_primary_key: primary_keys.contains(&name),
|
||||
name,
|
||||
data_type: row.get::<_, String>(1)?,
|
||||
is_nullable: row.get::<_, String>(2).unwrap_or_default() == "YES",
|
||||
column_default: row.get::<_, Option<String>>(3)?,
|
||||
extra: None, comment: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
character_maximum_length: None,
|
||||
})
|
||||
}).map_err(|e| e.to_string())?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
pub fn extract_duckdb(connections: &HashMap<String, PoolKind>, key: &str) -> Option<Arc<std::sync::Mutex<duckdb::Connection>>> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::DuckDb(con) => Some(con.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_sqlserver(connections: &HashMap<String, PoolKind>, key: &str) -> Option<Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::SqlServer(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_clickhouse(connections: &HashMap<String, PoolKind>, key: &str) -> Option<db::clickhouse_driver::ChClient> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::ClickHouse(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_oracle(connections: &HashMap<String, PoolKind>, key: &str) -> Option<Arc<tokio::sync::Mutex<db::oracle_driver::OracleClient>>> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::Oracle(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_databases_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_clickhouse(&connections, connection_id) {
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::list_databases(&client).await;
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, connection_id) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_databases(&mut client).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, connection_id) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_databases(&*client).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_databases(p).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_databases(p).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_databases(p).await,
|
||||
PoolKind::DuckDb(_) => Ok(vec![db::DatabaseInfo { name: "main".to_string() }]),
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_schemas_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_schemas(&mut client).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_schemas(&*client).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Postgres(p) => db::postgres::list_schemas(p).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_tables_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
) -> Result<Vec<db::TableInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(con) = extract_duckdb(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
return duckdb_query_tables(&con);
|
||||
}
|
||||
if let Some(client) = extract_clickhouse(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::list_tables(&client, database).await;
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_tables(&mut client, schema).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_tables(&*client, schema).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_tables(p, schema).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_tables(p, schema).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_tables(p, schema).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_columns_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::ColumnInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(con) = extract_duckdb(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
return duckdb_query_columns(&con, table);
|
||||
}
|
||||
if let Some(client) = extract_clickhouse(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::get_columns(&client, database, table).await;
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::get_columns(&mut client, schema, table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::get_columns(&*client, schema, table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::get_columns(p, schema, table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::get_columns(p, schema, table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::get_columns(p, schema, table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_indexes_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::IndexInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_indexes(&mut client, schema, table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_indexes(&*client, schema, table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_indexes(p, schema, table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_indexes(p, schema, table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_indexes(p, schema, table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_foreign_keys_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::ForeignKeyInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_foreign_keys(&mut client, schema, table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_foreign_keys(&*client, schema, table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_foreign_keys(p, schema, table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_foreign_keys(p, schema, table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_foreign_keys(p, schema, table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_triggers_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::TriggerInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_triggers(&mut client, schema, table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_triggers(&*client, schema, table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_triggers(p, schema, table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_triggers(p, schema, table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_triggers(p, schema, table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_table_ddl_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<String, String> {
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(con) = extract_duckdb(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let tbl = table.replace('\'', "''");
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
let mut stmt = con.prepare(&format!("SELECT sql FROM duckdb_tables() WHERE table_name = '{tbl}'"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
if let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
return row.get::<_, String>(0).map_err(|e| e.to_string());
|
||||
}
|
||||
return Err("Table not found".to_string());
|
||||
}
|
||||
if let Some(client) = extract_clickhouse(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let result = db::clickhouse_driver::execute_query(&client, database, &format!("SHOW CREATE TABLE `{table}`")).await?;
|
||||
return result.rows.first()
|
||||
.and_then(|r| r.first())
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.ok_or_else(|| "Table not found".to_string());
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return build_sqlserver_ddl(&mut client, schema, table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return build_oracle_ddl(&*client, schema, table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => mysql_ddl(p, table).await,
|
||||
PoolKind::Postgres(p) => pg_ddl(p, schema, table).await,
|
||||
PoolKind::Sqlite(p) => sqlite_ddl(p, table).await,
|
||||
_ => Err("DDL not supported for this database type".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mysql_ddl(pool: &sqlx::mysql::MySqlPool, table: &str) -> Result<String, String> {
|
||||
use sqlx::Row;
|
||||
let sql = format!("SHOW CREATE TABLE `{}`", table.replace('`', "``"));
|
||||
let row: sqlx::mysql::MySqlRow = sqlx::raw_sql(&sql)
|
||||
.fetch_one(pool).await.map_err(|e| e.to_string())?;
|
||||
row.try_get::<String, _>(1)
|
||||
.or_else(|_| row.try_get::<Vec<u8>, _>(1).map(|b| String::from_utf8_lossy(&b).to_string()))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn sqlite_ddl(pool: &sqlx::sqlite::SqlitePool, table: &str) -> Result<String, String> {
|
||||
use sqlx::Row;
|
||||
let row: sqlx::sqlite::SqliteRow = sqlx::query("SELECT sql FROM sqlite_master WHERE type='table' AND name=?")
|
||||
.bind(table)
|
||||
.fetch_one(pool).await.map_err(|e| e.to_string())?;
|
||||
row.try_get::<String, _>(0).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn pg_ddl(pool: &sqlx::postgres::PgPool, schema: &str, table: &str) -> Result<String, String> {
|
||||
let columns = db::postgres::get_columns(pool, schema, table).await?;
|
||||
let indexes = db::postgres::list_indexes(pool, schema, table).await?;
|
||||
let fkeys = db::postgres::list_foreign_keys(pool, schema, table).await?;
|
||||
|
||||
let mut ddl = format!("CREATE TABLE \"{schema}\".\"{table}\" (\n");
|
||||
let col_lines: Vec<String> = columns.iter().map(|c| {
|
||||
let mut line = format!(" \"{}\" {}", c.name, c.data_type);
|
||||
if !c.is_nullable { line.push_str(" NOT NULL"); }
|
||||
if let Some(ref def) = c.column_default { line.push_str(&format!(" DEFAULT {def}")); }
|
||||
line
|
||||
}).collect();
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
let pks: Vec<&str> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.iter().map(|k| format!("\"{k}\"")).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
for fk in &fkeys {
|
||||
ddl.push_str(&format!(",\n CONSTRAINT \"{}\" FOREIGN KEY (\"{}\") REFERENCES \"{}\"(\"{}\")", fk.name, fk.column, fk.ref_table, fk.ref_column));
|
||||
}
|
||||
ddl.push_str("\n);\n");
|
||||
|
||||
for idx in &indexes {
|
||||
if idx.is_primary { continue; }
|
||||
let unique = if idx.is_unique { "UNIQUE " } else { "" };
|
||||
let cols = idx.columns.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
|
||||
let using = idx.index_type.as_deref().map(|t| format!(" USING {t}")).unwrap_or_default();
|
||||
let include = idx.included_columns.as_deref().filter(|c| !c.is_empty()).map(|cols| format!(" INCLUDE ({})", cols.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", "))).unwrap_or_default();
|
||||
let filter = idx.filter.as_deref().map(|f| format!(" WHERE {f}")).unwrap_or_default();
|
||||
ddl.push_str(&format!("\nCREATE {unique}INDEX \"{}\" ON \"{schema}\".\"{table}\"{using} ({cols}){include}{filter};", idx.name));
|
||||
if let Some(ref c) = idx.comment {
|
||||
ddl.push_str(&format!("\nCOMMENT ON INDEX \"{schema}\".\"{}\" IS '{}';", idx.name, c.replace('\'', "''")));
|
||||
}
|
||||
}
|
||||
Ok(ddl)
|
||||
}
|
||||
|
||||
pub async fn build_sqlserver_ddl(client: &mut db::sqlserver::SqlServerClient, schema: &str, table: &str) -> Result<String, String> {
|
||||
let columns = db::sqlserver::get_columns(client, schema, table).await?;
|
||||
let indexes = db::sqlserver::list_indexes(client, schema, table).await?;
|
||||
let fkeys = db::sqlserver::list_foreign_keys(client, schema, table).await?;
|
||||
|
||||
let mut ddl = format!("CREATE TABLE [{schema}].[{table}] (\n");
|
||||
let col_lines: Vec<String> = columns.iter().map(|c| {
|
||||
let mut line = format!(" [{}] {}", c.name, c.data_type);
|
||||
if !c.is_nullable { line.push_str(" NOT NULL"); }
|
||||
if let Some(ref def) = c.column_default { line.push_str(&format!(" DEFAULT {def}")); }
|
||||
line
|
||||
}).collect();
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
let pks: Vec<&str> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.iter().map(|k| format!("[{k}]")).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
for fk in &fkeys {
|
||||
ddl.push_str(&format!(",\n CONSTRAINT [{}] FOREIGN KEY ([{}]) REFERENCES [{}]([{}])", fk.name, fk.column, fk.ref_table, fk.ref_column));
|
||||
}
|
||||
ddl.push_str("\n);\n");
|
||||
|
||||
for idx in &indexes {
|
||||
if idx.is_primary { continue; }
|
||||
let unique = if idx.is_unique { "UNIQUE " } else { "" };
|
||||
let idx_type = idx.index_type.as_deref().map(|t| format!("{t} ")).unwrap_or_default();
|
||||
let cols = idx.columns.iter().map(|c| format!("[{c}]")).collect::<Vec<_>>().join(", ");
|
||||
let include = idx.included_columns.as_deref().filter(|c| !c.is_empty()).map(|cols| format!(" INCLUDE ({})", cols.iter().map(|c| format!("[{c}]")).collect::<Vec<_>>().join(", "))).unwrap_or_default();
|
||||
let filter = idx.filter.as_deref().map(|f| format!(" WHERE {f}")).unwrap_or_default();
|
||||
ddl.push_str(&format!("\nCREATE {unique}{idx_type}INDEX [{}] ON [{schema}].[{table}] ({cols}){include}{filter};", idx.name));
|
||||
}
|
||||
Ok(ddl)
|
||||
}
|
||||
|
||||
pub async fn build_oracle_ddl(client: &db::oracle_driver::OracleClient, schema: &str, table: &str) -> Result<String, String> {
|
||||
let columns = db::oracle_driver::get_columns(client, schema, table).await?;
|
||||
let indexes = db::oracle_driver::list_indexes(client, schema, table).await?;
|
||||
let fkeys = db::oracle_driver::list_foreign_keys(client, schema, table).await?;
|
||||
|
||||
let mut ddl = format!("CREATE TABLE \"{schema}\".\"{table}\" (\n");
|
||||
let col_lines: Vec<String> = columns.iter().map(|c| {
|
||||
let mut line = format!(" \"{}\" {}", c.name, c.data_type);
|
||||
if !c.is_nullable { line.push_str(" NOT NULL"); }
|
||||
if let Some(ref def) = c.column_default { line.push_str(&format!(" DEFAULT {def}")); }
|
||||
line
|
||||
}).collect();
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
let pks: Vec<&str> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.iter().map(|k| format!("\"{k}\"")).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
for fk in &fkeys {
|
||||
ddl.push_str(&format!(",\n CONSTRAINT \"{}\" FOREIGN KEY (\"{}\") REFERENCES \"{}\"(\"{}\")", fk.name, fk.column, fk.ref_table, fk.ref_column));
|
||||
}
|
||||
ddl.push_str("\n);\n");
|
||||
|
||||
for idx in &indexes {
|
||||
if idx.is_primary { continue; }
|
||||
let unique = if idx.is_unique { "UNIQUE " } else { "" };
|
||||
let cols = idx.columns.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
|
||||
ddl.push_str(&format!("\nCREATE {unique}INDEX \"{}\" ON \"{schema}\".\"{table}\" ({cols});", idx.name));
|
||||
}
|
||||
Ok(ddl)
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SqlFileRequest {
|
||||
pub execution_id: String,
|
||||
pub connection_id: String,
|
||||
pub database: String,
|
||||
pub file_path: String,
|
||||
pub continue_on_error: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SqlFilePreview {
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub size_bytes: u64,
|
||||
pub preview: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SqlFileStatus {
|
||||
Started,
|
||||
Running,
|
||||
StatementDone,
|
||||
StatementFailed,
|
||||
Done,
|
||||
Error,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SqlFileProgress {
|
||||
pub execution_id: String,
|
||||
pub status: SqlFileStatus,
|
||||
pub statement_index: usize,
|
||||
pub success_count: usize,
|
||||
pub failure_count: usize,
|
||||
pub affected_rows: u64,
|
||||
pub elapsed_ms: u128,
|
||||
pub statement_summary: String,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SqlStatementSplitter {
|
||||
buffer: String,
|
||||
in_single_quote: bool,
|
||||
in_double_quote: bool,
|
||||
in_backtick: bool,
|
||||
in_line_comment: bool,
|
||||
in_block_comment: bool,
|
||||
dollar_quote_tag: Option<String>,
|
||||
previous: Option<char>,
|
||||
}
|
||||
|
||||
impl SqlStatementSplitter {
|
||||
pub fn push_chunk(&mut self, chunk: &str) -> Vec<String> {
|
||||
let mut statements = Vec::new();
|
||||
let chars = chunk.chars().collect::<Vec<_>>();
|
||||
let mut i = 0;
|
||||
|
||||
while i < chars.len() {
|
||||
if let Some(tag) = &self.dollar_quote_tag {
|
||||
let tag_chars = tag.chars().collect::<Vec<_>>();
|
||||
if starts_with_chars(&chars, i, &tag_chars) {
|
||||
for tag_ch in &tag_chars {
|
||||
self.buffer.push(*tag_ch);
|
||||
self.previous = Some(*tag_ch);
|
||||
}
|
||||
i += tag_chars.len();
|
||||
self.dollar_quote_tag = None;
|
||||
continue;
|
||||
}
|
||||
|
||||
let ch = chars[i];
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let ch = chars[i];
|
||||
let next = chars.get(i + 1).copied();
|
||||
|
||||
if self.in_line_comment {
|
||||
self.buffer.push(ch);
|
||||
if ch == '\n' {
|
||||
self.in_line_comment = false;
|
||||
}
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.in_block_comment {
|
||||
self.buffer.push(ch);
|
||||
if self.previous == Some('*') && ch == '/' {
|
||||
self.in_block_comment = false;
|
||||
}
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if !self.in_single_quote && !self.in_double_quote && !self.in_backtick {
|
||||
if self.previous == Some('-') && ch == '-' {
|
||||
self.in_line_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if self.previous == Some('/') && ch == '*' {
|
||||
self.in_block_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if ch == '-' && next == Some('-') {
|
||||
self.in_line_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if ch == '/' && next == Some('*') {
|
||||
self.in_block_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(tag) = dollar_quote_tag_at(&chars, i) {
|
||||
for tag_ch in tag.chars() {
|
||||
self.buffer.push(tag_ch);
|
||||
self.previous = Some(tag_ch);
|
||||
}
|
||||
i += tag.chars().count();
|
||||
self.dollar_quote_tag = Some(tag);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
match ch {
|
||||
'\'' if !self.in_double_quote
|
||||
&& !self.in_backtick
|
||||
&& self.previous != Some('\\') =>
|
||||
{
|
||||
self.in_single_quote = !self.in_single_quote;
|
||||
self.buffer.push(ch);
|
||||
}
|
||||
'"' if !self.in_single_quote
|
||||
&& !self.in_backtick
|
||||
&& self.previous != Some('\\') =>
|
||||
{
|
||||
self.in_double_quote = !self.in_double_quote;
|
||||
self.buffer.push(ch);
|
||||
}
|
||||
'`' if !self.in_single_quote && !self.in_double_quote => {
|
||||
self.in_backtick = !self.in_backtick;
|
||||
self.buffer.push(ch);
|
||||
}
|
||||
';' if !self.in_single_quote && !self.in_double_quote && !self.in_backtick => {
|
||||
self.push_current_statement(&mut statements);
|
||||
}
|
||||
_ => self.buffer.push(ch),
|
||||
}
|
||||
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
statements
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Vec<String> {
|
||||
let mut statements = Vec::new();
|
||||
self.push_current_statement(&mut statements);
|
||||
statements
|
||||
}
|
||||
|
||||
fn push_current_statement(&mut self, statements: &mut Vec<String>) {
|
||||
let statement = self.buffer.trim();
|
||||
if has_executable_sql(statement) {
|
||||
statements.push(statement.to_string());
|
||||
}
|
||||
self.buffer.clear();
|
||||
self.previous = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn split_sql_statements(sql: &str) -> Vec<String> {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
let mut statements = splitter.push_chunk(sql);
|
||||
statements.extend(splitter.finish());
|
||||
statements
|
||||
}
|
||||
|
||||
pub fn statement_summary(statement: &str) -> String {
|
||||
const MAX_LEN: usize = 120;
|
||||
|
||||
let collapsed = statement.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if collapsed.chars().count() <= MAX_LEN {
|
||||
return collapsed;
|
||||
}
|
||||
|
||||
collapsed.chars().take(MAX_LEN).collect()
|
||||
}
|
||||
|
||||
fn starts_with_chars(chars: &[char], start: usize, needle: &[char]) -> bool {
|
||||
start + needle.len() <= chars.len() && chars[start..start + needle.len()] == *needle
|
||||
}
|
||||
|
||||
fn dollar_quote_tag_at(chars: &[char], start: usize) -> Option<String> {
|
||||
if chars.get(start) != Some(&'$') {
|
||||
return None;
|
||||
}
|
||||
|
||||
match chars.get(start + 1) {
|
||||
Some('$') => return Some("$$".to_string()),
|
||||
Some(ch) if ch.is_ascii_alphabetic() || *ch == '_' => {}
|
||||
_ => return None,
|
||||
}
|
||||
|
||||
let mut end = start + 2;
|
||||
while let Some(ch) = chars.get(end) {
|
||||
if *ch == '$' {
|
||||
return Some(chars[start..=end].iter().collect());
|
||||
}
|
||||
if !ch.is_ascii_alphanumeric() && *ch != '_' {
|
||||
return None;
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn has_executable_sql(statement: &str) -> bool {
|
||||
let chars = statement.chars().collect::<Vec<_>>();
|
||||
let mut in_line_comment = false;
|
||||
let mut in_block_comment = false;
|
||||
let mut previous = None;
|
||||
let mut i = 0;
|
||||
|
||||
while i < chars.len() {
|
||||
let ch = chars[i];
|
||||
let next = chars.get(i + 1).copied();
|
||||
|
||||
if in_line_comment {
|
||||
if ch == '\n' {
|
||||
in_line_comment = false;
|
||||
}
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_block_comment {
|
||||
if previous == Some('*') && ch == '/' {
|
||||
in_block_comment = false;
|
||||
}
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '-' && next == Some('-') {
|
||||
in_line_comment = true;
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '/' && next == Some('*') {
|
||||
if is_mysql_executable_comment_start(&chars, i) {
|
||||
return true;
|
||||
}
|
||||
in_block_comment = true;
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if !ch.is_whitespace() {
|
||||
return true;
|
||||
}
|
||||
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn is_mysql_executable_comment_start(chars: &[char], start: usize) -> bool {
|
||||
chars.get(start) == Some(&'/')
|
||||
&& chars.get(start + 1) == Some(&'*')
|
||||
&& (chars.get(start + 2) == Some(&'!')
|
||||
|| (chars.get(start + 2) == Some(&'M') && chars.get(start + 3) == Some(&'!')))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn split_sql_script(sql: &str) -> Result<Vec<String>, String> {
|
||||
Ok(split_sql_statements(sql))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{split_sql_script, SqlStatementSplitter};
|
||||
|
||||
#[test]
|
||||
fn splits_semicolon_delimited_statements() {
|
||||
assert_eq!(
|
||||
split_sql_script("CREATE TABLE a(id int); INSERT INTO a VALUES (1);").unwrap(),
|
||||
vec!["CREATE TABLE a(id int)", "INSERT INTO a VALUES (1)"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_semicolons_inside_quotes_and_comments() {
|
||||
let sql = "\
|
||||
INSERT INTO logs VALUES ('a;b', \"c;d\", `weird;name`);\n\
|
||||
-- comment ; ignored\n\
|
||||
/* block ; ignored */\n\
|
||||
SELECT 1;";
|
||||
assert_eq!(
|
||||
split_sql_script(sql).unwrap(),
|
||||
vec![
|
||||
"INSERT INTO logs VALUES ('a;b', \"c;d\", `weird;name`)",
|
||||
"-- comment ; ignored\n/* block ; ignored */\nSELECT 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_trailing_statement_without_semicolon() {
|
||||
assert_eq!(
|
||||
split_sql_script("CREATE TABLE a(id int);\nINSERT INTO a VALUES (1)").unwrap(),
|
||||
vec!["CREATE TABLE a(id int)", "INSERT INTO a VALUES (1)"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_comment_openers_can_span_chunks() {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
|
||||
assert_eq!(splitter.push_chunk("SELECT 1; -"), vec!["SELECT 1"]);
|
||||
assert_eq!(
|
||||
splitter.push_chunk("- comment ; ignored\nSELECT 2;"),
|
||||
vec!["-- comment ; ignored\nSELECT 2"]
|
||||
);
|
||||
assert_eq!(splitter.finish(), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_comment_openers_can_span_chunks() {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
|
||||
assert_eq!(splitter.push_chunk("SELECT 1; /"), vec!["SELECT 1"]);
|
||||
assert_eq!(
|
||||
splitter.push_chunk("* comment ; ignored */\nSELECT 2;"),
|
||||
vec!["/* comment ; ignored */\nSELECT 2"]
|
||||
);
|
||||
assert_eq!(splitter.finish(), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_comment_only_tail_after_statement() {
|
||||
assert_eq!(
|
||||
split_sql_script("CREATE TABLE a(id int); -- done\n/* no more sql */").unwrap(),
|
||||
vec!["CREATE TABLE a(id int)"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_postgres_dollar_quoted_function_body_together() {
|
||||
let sql = "\
|
||||
CREATE FUNCTION bump_counter()\n\
|
||||
RETURNS trigger AS $$\n\
|
||||
BEGIN\n\
|
||||
PERFORM 1;\n\
|
||||
RETURN NEW;\n\
|
||||
END;\n\
|
||||
$$ LANGUAGE plpgsql;\n\
|
||||
SELECT 1;";
|
||||
|
||||
assert_eq!(
|
||||
split_sql_script(sql).unwrap(),
|
||||
vec![
|
||||
"CREATE FUNCTION bump_counter()\nRETURNS trigger AS $$\nBEGIN\nPERFORM 1;\nRETURN NEW;\nEND;\n$$ LANGUAGE plpgsql",
|
||||
"SELECT 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_mysql_executable_comments_as_statements() {
|
||||
assert_eq!(
|
||||
split_sql_script(
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\nSELECT 1;",
|
||||
)
|
||||
.unwrap(),
|
||||
vec![
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */",
|
||||
"SELECT 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
use calamine::{open_workbook_auto, Data, Reader};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::connection::DatabaseType;
|
||||
use crate::transfer::{execute_on_pool, generate_insert, qualified_table};
|
||||
use crate::connection::AppState;
|
||||
|
||||
pub const DEFAULT_PREVIEW_LIMIT: usize = 50;
|
||||
pub const DEFAULT_BATCH_SIZE: usize = 500;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParsedImportFile {
|
||||
pub columns: Vec<String>,
|
||||
pub rows: Vec<Vec<serde_json::Value>>,
|
||||
pub total_rows: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ImportSqlBatch {
|
||||
pub sql: String,
|
||||
pub row_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportColumnMapping {
|
||||
pub source_column: String,
|
||||
pub target_column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TableImportMode {
|
||||
Append,
|
||||
Truncate,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportRequest {
|
||||
pub import_id: String,
|
||||
pub connection_id: String,
|
||||
pub database: String,
|
||||
pub schema: String,
|
||||
pub table: String,
|
||||
pub file_path: String,
|
||||
pub mappings: Vec<TableImportColumnMapping>,
|
||||
pub mode: TableImportMode,
|
||||
pub batch_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportPreview {
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub file_type: String,
|
||||
pub size_bytes: u64,
|
||||
pub columns: Vec<String>,
|
||||
pub rows: Vec<Vec<serde_json::Value>>,
|
||||
pub total_rows: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportSummary {
|
||||
pub import_id: String,
|
||||
pub rows_imported: usize,
|
||||
pub total_rows: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportProgress {
|
||||
pub import_id: String,
|
||||
pub status: TableImportStatus,
|
||||
pub rows_imported: usize,
|
||||
pub total_rows: usize,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TableImportStatus {
|
||||
Running,
|
||||
Done,
|
||||
Error,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ImportFileKind {
|
||||
Csv,
|
||||
Tsv,
|
||||
Json,
|
||||
Xlsx,
|
||||
}
|
||||
|
||||
impl ImportFileKind {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ImportFileKind::Csv => "csv",
|
||||
ImportFileKind::Tsv => "tsv",
|
||||
ImportFileKind::Json => "json",
|
||||
ImportFileKind::Xlsx => "xlsx",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn import_file_kind(path: &str) -> Result<ImportFileKind, String> {
|
||||
let lower = path.to_lowercase();
|
||||
if lower.ends_with(".csv") {
|
||||
Ok(ImportFileKind::Csv)
|
||||
} else if lower.ends_with(".tsv") {
|
||||
Ok(ImportFileKind::Tsv)
|
||||
} else if lower.ends_with(".json") {
|
||||
Ok(ImportFileKind::Json)
|
||||
} else if lower.ends_with(".xlsx") || lower.ends_with(".xlsm") || lower.ends_with(".xls") {
|
||||
Ok(ImportFileKind::Xlsx)
|
||||
} else {
|
||||
Err("Unsupported import file type".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_header(value: &str, index: usize) -> String {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
format!("column_{}", index + 1)
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn csv_value(value: &str) -> serde_json::Value {
|
||||
if value.is_empty() {
|
||||
serde_json::Value::Null
|
||||
} else {
|
||||
serde_json::Value::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_delimited_bytes(
|
||||
bytes: &[u8],
|
||||
delimiter: u8,
|
||||
preview_limit: usize,
|
||||
) -> Result<ParsedImportFile, String> {
|
||||
let mut reader = csv::ReaderBuilder::new()
|
||||
.delimiter(delimiter)
|
||||
.flexible(true)
|
||||
.from_reader(bytes);
|
||||
let columns = reader
|
||||
.headers()
|
||||
.map_err(|e| e.to_string())?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, header)| normalize_header(header, index))
|
||||
.collect::<Vec<_>>();
|
||||
if columns.is_empty() {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let mut total_rows = 0;
|
||||
for record in reader.records() {
|
||||
let record = record.map_err(|e| e.to_string())?;
|
||||
total_rows += 1;
|
||||
if rows.len() >= preview_limit {
|
||||
continue;
|
||||
}
|
||||
let mut row = Vec::with_capacity(columns.len());
|
||||
for index in 0..columns.len() {
|
||||
row.push(
|
||||
record
|
||||
.get(index)
|
||||
.map(csv_value)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_csv_bytes(bytes: &[u8], preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
parse_delimited_bytes(bytes, b',', preview_limit)
|
||||
}
|
||||
|
||||
pub fn parse_json_bytes(bytes: &[u8], preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
|
||||
let items = match value {
|
||||
serde_json::Value::Array(items) => items,
|
||||
serde_json::Value::Object(_) => vec![value],
|
||||
_ => return Err("JSON import must be an object or an array".to_string()),
|
||||
};
|
||||
if items.is_empty() {
|
||||
return Err("Import file has no rows".to_string());
|
||||
}
|
||||
|
||||
if items.iter().all(|item| item.is_object()) {
|
||||
let mut columns = Vec::new();
|
||||
for item in &items {
|
||||
if let Some(obj) = item.as_object() {
|
||||
for key in obj.keys() {
|
||||
if !columns.contains(key) {
|
||||
columns.push(key.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if columns.is_empty() {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
let rows = items
|
||||
.iter()
|
||||
.take(preview_limit)
|
||||
.map(|item| {
|
||||
let obj = item.as_object().expect("checked object JSON row");
|
||||
columns
|
||||
.iter()
|
||||
.map(|column| obj.get(column).cloned().unwrap_or(serde_json::Value::Null))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
return Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows: items.len(),
|
||||
});
|
||||
}
|
||||
|
||||
if items.iter().all(|item| item.is_array()) {
|
||||
let max_cols = items
|
||||
.iter()
|
||||
.filter_map(|item| item.as_array().map(|row| row.len()))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if max_cols == 0 {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
let columns = (0..max_cols)
|
||||
.map(|index| format!("column_{}", index + 1))
|
||||
.collect::<Vec<_>>();
|
||||
let rows = items
|
||||
.iter()
|
||||
.take(preview_limit)
|
||||
.map(|item| {
|
||||
let arr = item.as_array().expect("checked array JSON row");
|
||||
(0..max_cols)
|
||||
.map(|index| arr.get(index).cloned().unwrap_or(serde_json::Value::Null))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
return Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows: items.len(),
|
||||
});
|
||||
}
|
||||
|
||||
Err("JSON rows must all be objects or all be arrays".to_string())
|
||||
}
|
||||
|
||||
pub fn xlsx_cell_value(cell: &Data) -> serde_json::Value {
|
||||
match cell {
|
||||
Data::Empty => serde_json::Value::Null,
|
||||
Data::String(s) => csv_value(s),
|
||||
Data::Float(n) => serde_json::Number::from_f64(*n)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
Data::Int(n) => serde_json::Value::Number((*n).into()),
|
||||
Data::Bool(v) => serde_json::Value::Bool(*v),
|
||||
Data::DateTime(v) => serde_json::Value::String(v.to_string()),
|
||||
Data::DateTimeIso(v) => serde_json::Value::String(v.clone()),
|
||||
Data::DurationIso(v) => serde_json::Value::String(v.clone()),
|
||||
Data::Error(v) => serde_json::Value::String(v.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn xlsx_cell_label(cell: &Data) -> String {
|
||||
match cell {
|
||||
Data::Empty => String::new(),
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Float(n) => n.to_string(),
|
||||
Data::Int(n) => n.to_string(),
|
||||
Data::Bool(v) => v.to_string(),
|
||||
Data::DateTime(v) => v.to_string(),
|
||||
Data::DateTimeIso(v) => v.clone(),
|
||||
Data::DurationIso(v) => v.clone(),
|
||||
Data::Error(v) => v.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_xlsx_file(path: &str, preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
let mut workbook = open_workbook_auto(path).map_err(|e| e.to_string())?;
|
||||
let sheet_name = workbook
|
||||
.sheet_names()
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or_else(|| "Workbook has no sheets".to_string())?;
|
||||
let range = workbook
|
||||
.worksheet_range(&sheet_name)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut rows_iter = range.rows();
|
||||
let header = rows_iter
|
||||
.next()
|
||||
.ok_or_else(|| "Import file has no rows".to_string())?;
|
||||
let columns = header
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, cell)| normalize_header(&xlsx_cell_label(cell), index))
|
||||
.collect::<Vec<_>>();
|
||||
if columns.is_empty() {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let mut total_rows = 0;
|
||||
for source_row in rows_iter {
|
||||
total_rows += 1;
|
||||
if rows.len() >= preview_limit {
|
||||
continue;
|
||||
}
|
||||
let mut row = Vec::with_capacity(columns.len());
|
||||
for index in 0..columns.len() {
|
||||
row.push(
|
||||
source_row
|
||||
.get(index)
|
||||
.map(xlsx_cell_value)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_import_file(path: &str, preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
match import_file_kind(path)? {
|
||||
ImportFileKind::Csv => {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
parse_csv_bytes(&bytes, preview_limit)
|
||||
}
|
||||
ImportFileKind::Tsv => {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
parse_delimited_bytes(&bytes, b'\t', preview_limit)
|
||||
}
|
||||
ImportFileKind::Json => {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
parse_json_bytes(&bytes, preview_limit)
|
||||
}
|
||||
ImportFileKind::Xlsx => parse_xlsx_file(path, preview_limit),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mapping_indexes(
|
||||
data: &ParsedImportFile,
|
||||
mappings: &[TableImportColumnMapping],
|
||||
) -> Result<Vec<(usize, String)>, String> {
|
||||
if mappings.is_empty() {
|
||||
return Err("No columns mapped for import".to_string());
|
||||
}
|
||||
let mut mapped = Vec::new();
|
||||
let mut target_seen = HashSet::new();
|
||||
for mapping in mappings {
|
||||
let source_index = data
|
||||
.columns
|
||||
.iter()
|
||||
.position(|column| column == &mapping.source_column)
|
||||
.ok_or_else(|| format!("Source column not found: {}", mapping.source_column))?;
|
||||
if mapping.target_column.trim().is_empty() {
|
||||
return Err("Target column cannot be empty".to_string());
|
||||
}
|
||||
if !target_seen.insert(mapping.target_column.clone()) {
|
||||
return Err(format!(
|
||||
"Target column mapped more than once: {}",
|
||||
mapping.target_column
|
||||
));
|
||||
}
|
||||
mapped.push((source_index, mapping.target_column.clone()));
|
||||
}
|
||||
Ok(mapped)
|
||||
}
|
||||
|
||||
pub fn build_import_insert_batches(
|
||||
data: &ParsedImportFile,
|
||||
mappings: &[TableImportColumnMapping],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
db_type: &DatabaseType,
|
||||
batch_size: usize,
|
||||
) -> Result<Vec<ImportSqlBatch>, String> {
|
||||
let mapped = mapping_indexes(data, mappings)?;
|
||||
let columns = mapped
|
||||
.iter()
|
||||
.map(|(_, target)| target.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let batch_size = batch_size.max(1);
|
||||
let mut batches = Vec::new();
|
||||
|
||||
for chunk in data.rows.chunks(batch_size) {
|
||||
let rows = chunk
|
||||
.iter()
|
||||
.map(|row| {
|
||||
mapped
|
||||
.iter()
|
||||
.map(|(source_index, _)| {
|
||||
row.get(*source_index)
|
||||
.cloned()
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let sql = generate_insert(&columns, &rows, table, schema, db_type);
|
||||
if !sql.trim().is_empty() {
|
||||
batches.push(ImportSqlBatch {
|
||||
sql,
|
||||
row_count: chunk.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(batches)
|
||||
}
|
||||
|
||||
pub fn truncate_sql(table: &str, schema: &str, db_type: &DatabaseType) -> String {
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
match db_type {
|
||||
DatabaseType::Sqlite => format!("DELETE FROM {full_table}"),
|
||||
_ => format!("TRUNCATE TABLE {full_table}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preview_table_import_file_core(file_path: &str) -> Result<TableImportPreview, String> {
|
||||
let kind = import_file_kind(file_path)?;
|
||||
let parsed = parse_import_file(file_path, DEFAULT_PREVIEW_LIMIT)?;
|
||||
let metadata = std::fs::metadata(file_path).map_err(|e| e.to_string())?;
|
||||
let file_name = Path::new(file_path)
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or(file_path)
|
||||
.to_string();
|
||||
|
||||
Ok(TableImportPreview {
|
||||
file_name,
|
||||
file_path: file_path.to_string(),
|
||||
file_type: kind.label().to_string(),
|
||||
size_bytes: metadata.len(),
|
||||
columns: parsed.columns,
|
||||
rows: parsed.rows,
|
||||
total_rows: parsed.total_rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// Core import logic. Returns (rows_imported, total_rows).
|
||||
/// `progress_callback` is invoked for progress updates.
|
||||
pub async fn import_table_file_core<F>(
|
||||
state: &AppState,
|
||||
request: &TableImportRequest,
|
||||
db_type: &DatabaseType,
|
||||
pool_key: &str,
|
||||
is_cancelled: impl Fn(&str) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + '_>>,
|
||||
mut progress_callback: F,
|
||||
) -> Result<TableImportSummary, String>
|
||||
where
|
||||
F: FnMut(TableImportProgress),
|
||||
{
|
||||
let batch_size = if request.batch_size == 0 {
|
||||
DEFAULT_BATCH_SIZE
|
||||
} else {
|
||||
request.batch_size
|
||||
};
|
||||
|
||||
let parsed = match parse_import_file(&request.file_path, usize::MAX) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported: 0,
|
||||
total_rows: 0,
|
||||
error: Some(error.clone()),
|
||||
});
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
let total_rows = parsed.total_rows;
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Running,
|
||||
rows_imported: 0,
|
||||
total_rows,
|
||||
error: None,
|
||||
});
|
||||
|
||||
let batches = match build_import_insert_batches(
|
||||
&parsed,
|
||||
&request.mappings,
|
||||
&request.table,
|
||||
&request.schema,
|
||||
db_type,
|
||||
batch_size,
|
||||
) {
|
||||
Ok(batches) => batches,
|
||||
Err(error) => {
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported: 0,
|
||||
total_rows,
|
||||
error: Some(error.clone()),
|
||||
});
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
if matches!(request.mode, TableImportMode::Truncate) {
|
||||
let sql = truncate_sql(&request.table, &request.schema, db_type);
|
||||
if let Err(error) = execute_on_pool(state, pool_key, &sql).await {
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported: 0,
|
||||
total_rows,
|
||||
error: Some(error.clone()),
|
||||
});
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows_imported = 0;
|
||||
for batch in batches {
|
||||
if is_cancelled(&request.import_id).await {
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Cancelled,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: None,
|
||||
});
|
||||
return Err("Import cancelled".to_string());
|
||||
}
|
||||
|
||||
if let Err(error) = execute_on_pool(state, pool_key, &batch.sql).await {
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: Some(error.clone()),
|
||||
});
|
||||
return Err(error);
|
||||
}
|
||||
rows_imported = (rows_imported + batch.row_count).min(total_rows);
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Running,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
|
||||
progress_callback(TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Done,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: None,
|
||||
});
|
||||
|
||||
Ok(TableImportSummary {
|
||||
import_id: request.import_id.clone(),
|
||||
rows_imported,
|
||||
total_rows,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::connection::DatabaseType;
|
||||
|
||||
#[test]
|
||||
fn parses_csv_headers_and_preview_rows() {
|
||||
let parsed = parse_csv_bytes(b"id,name,active\n1,Ada,true\n2,,false\n", 10).unwrap();
|
||||
|
||||
assert_eq!(parsed.columns, vec!["id", "name", "active"]);
|
||||
assert_eq!(parsed.total_rows, 2);
|
||||
assert_eq!(
|
||||
parsed.rows[0],
|
||||
vec![
|
||||
serde_json::Value::String("1".to_string()),
|
||||
serde_json::Value::String("Ada".to_string()),
|
||||
serde_json::Value::String("true".to_string()),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.rows[1],
|
||||
vec![
|
||||
serde_json::Value::String("2".to_string()),
|
||||
serde_json::Value::Null,
|
||||
serde_json::Value::String("false".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_tsv_with_tab_delimiter() {
|
||||
let parsed = parse_delimited_bytes(b"id\tname\n1\tAda\n", b'\t', 10).unwrap();
|
||||
|
||||
assert_eq!(parsed.columns, vec!["id", "name"]);
|
||||
assert_eq!(parsed.total_rows, 1);
|
||||
assert_eq!(
|
||||
parsed.rows[0],
|
||||
vec![
|
||||
serde_json::Value::String("1".to_string()),
|
||||
serde_json::Value::String("Ada".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_json_array_objects_with_union_columns() {
|
||||
let parsed =
|
||||
parse_json_bytes(br#"[{"id":1,"name":"Ada"},{"id":2,"active":true}]"#, 10).unwrap();
|
||||
|
||||
assert_eq!(parsed.columns, vec!["id", "name", "active"]);
|
||||
assert_eq!(parsed.total_rows, 2);
|
||||
assert_eq!(
|
||||
parsed.rows[0],
|
||||
vec![
|
||||
serde_json::json!(1),
|
||||
serde_json::json!("Ada"),
|
||||
serde_json::Value::Null,
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.rows[1],
|
||||
vec![
|
||||
serde_json::json!(2),
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!(true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_import_insert_batches_from_mapped_columns() {
|
||||
let mappings = vec![
|
||||
TableImportColumnMapping {
|
||||
source_column: "id".to_string(),
|
||||
target_column: "user_id".to_string(),
|
||||
},
|
||||
TableImportColumnMapping {
|
||||
source_column: "name".to_string(),
|
||||
target_column: "display_name".to_string(),
|
||||
},
|
||||
];
|
||||
let data = ParsedImportFile {
|
||||
columns: vec!["id".to_string(), "name".to_string(), "ignored".to_string()],
|
||||
rows: vec![
|
||||
vec![
|
||||
serde_json::json!(1),
|
||||
serde_json::json!("Ada"),
|
||||
serde_json::json!("x"),
|
||||
],
|
||||
vec![
|
||||
serde_json::json!(2),
|
||||
serde_json::json!("O'Hara"),
|
||||
serde_json::json!("y"),
|
||||
],
|
||||
vec![
|
||||
serde_json::json!(3),
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("z"),
|
||||
],
|
||||
],
|
||||
total_rows: 3,
|
||||
};
|
||||
|
||||
let batches = build_import_insert_batches(
|
||||
&data,
|
||||
&mappings,
|
||||
"users",
|
||||
"public",
|
||||
&DatabaseType::Postgres,
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(batches, vec![
|
||||
ImportSqlBatch {
|
||||
sql: "INSERT INTO \"public\".\"users\" (\"user_id\", \"display_name\") VALUES\n(1, 'Ada'),\n(2, 'O''Hara')".to_string(),
|
||||
row_count: 2,
|
||||
},
|
||||
ImportSqlBatch {
|
||||
sql: "INSERT INTO \"public\".\"users\" (\"user_id\", \"display_name\") VALUES\n(3, NULL)".to_string(),
|
||||
row_count: 1,
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
use std::collections::HashSet;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::connection::{AppState, PoolKind};
|
||||
use crate::db;
|
||||
use crate::models::connection::DatabaseType;
|
||||
|
||||
static CANCELLED: std::sync::LazyLock<RwLock<HashSet<String>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashSet::new()));
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TransferRequest {
|
||||
pub transfer_id: String,
|
||||
pub source_connection_id: String,
|
||||
pub source_database: String,
|
||||
pub source_schema: String,
|
||||
pub target_connection_id: String,
|
||||
pub target_database: String,
|
||||
pub target_schema: String,
|
||||
pub tables: Vec<String>,
|
||||
pub create_table: bool,
|
||||
pub truncate_before: bool,
|
||||
pub batch_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TransferProgress {
|
||||
pub transfer_id: String,
|
||||
pub table: String,
|
||||
pub table_index: usize,
|
||||
pub total_tables: usize,
|
||||
pub rows_transferred: u64,
|
||||
pub total_rows: Option<u64>,
|
||||
pub status: TransferStatus,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TransferStatus {
|
||||
Running,
|
||||
TableDone,
|
||||
Done,
|
||||
Error,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
pub fn quote_identifier(name: &str, db_type: &DatabaseType) -> String {
|
||||
match db_type {
|
||||
DatabaseType::Mysql | DatabaseType::ClickHouse | DatabaseType::Doris | DatabaseType::StarRocks => format!("`{}`", name.replace('`', "``")),
|
||||
DatabaseType::SqlServer => format!("[{}]", name.replace(']', "]]")),
|
||||
_ => format!("\"{}\"", name.replace('"', "\"\"")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn qualified_table(table: &str, schema: &str, db_type: &DatabaseType) -> String {
|
||||
let qt = quote_identifier(table, db_type);
|
||||
if schema.is_empty() {
|
||||
qt
|
||||
} else {
|
||||
format!("{}.{}", quote_identifier(schema, db_type), qt)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn escape_value(val: &serde_json::Value, db_type: &DatabaseType) -> String {
|
||||
match val {
|
||||
serde_json::Value::Null => "NULL".to_string(),
|
||||
serde_json::Value::Bool(b) => match db_type {
|
||||
DatabaseType::Mysql | DatabaseType::Sqlite | DatabaseType::DuckDb | DatabaseType::Doris | DatabaseType::StarRocks => {
|
||||
if *b { "1".to_string() } else { "0".to_string() }
|
||||
}
|
||||
_ => if *b { "TRUE".to_string() } else { "FALSE".to_string() },
|
||||
},
|
||||
serde_json::Value::Number(n) => n.to_string(),
|
||||
serde_json::Value::String(s) => {
|
||||
format!("'{}'", s.replace('\'', "''"))
|
||||
}
|
||||
_ => {
|
||||
let s = val.to_string();
|
||||
format!("'{}'", s.replace('\'', "''"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_column_type(source_type: &str, _source_db: &DatabaseType, target_db: &DatabaseType) -> String {
|
||||
let t = source_type.to_lowercase();
|
||||
let base = t.split('(').next().unwrap_or(&t).trim();
|
||||
|
||||
match base {
|
||||
"int" | "integer" | "int4" | "mediumint" => match target_db {
|
||||
DatabaseType::Postgres => "INTEGER".into(),
|
||||
DatabaseType::Mysql => "INT".into(),
|
||||
DatabaseType::SqlServer => "INT".into(),
|
||||
_ => "INTEGER".into(),
|
||||
},
|
||||
"bigint" | "int8" => "BIGINT".into(),
|
||||
"smallint" | "int2" => "SMALLINT".into(),
|
||||
"tinyint" => match target_db {
|
||||
DatabaseType::Postgres => "SMALLINT".into(),
|
||||
_ => "TINYINT".into(),
|
||||
},
|
||||
"serial" | "bigserial" | "smallserial" => match target_db {
|
||||
DatabaseType::Postgres => source_type.to_uppercase(),
|
||||
DatabaseType::Mysql => "BIGINT AUTO_INCREMENT".into(),
|
||||
_ => "INTEGER".into(),
|
||||
},
|
||||
"float" | "float4" | "real" => match target_db {
|
||||
DatabaseType::Postgres => "REAL".into(),
|
||||
_ => "FLOAT".into(),
|
||||
},
|
||||
"double" | "double precision" | "float8" => match target_db {
|
||||
DatabaseType::Postgres => "DOUBLE PRECISION".into(),
|
||||
_ => "DOUBLE".into(),
|
||||
},
|
||||
"decimal" | "numeric" | "number" => {
|
||||
if t.contains('(') {
|
||||
match target_db {
|
||||
DatabaseType::Mysql | DatabaseType::Postgres | DatabaseType::SqlServer | DatabaseType::Oracle => {
|
||||
format!("DECIMAL{}", &t[t.find('(').unwrap()..])
|
||||
}
|
||||
_ => "NUMERIC".into(),
|
||||
}
|
||||
} else {
|
||||
"NUMERIC".into()
|
||||
}
|
||||
}
|
||||
"varchar" | "nvarchar" | "character varying" | "varchar2" => {
|
||||
if t.contains('(') {
|
||||
let len_part = &t[t.find('(').unwrap()..];
|
||||
match target_db {
|
||||
DatabaseType::Postgres => format!("VARCHAR{len_part}"),
|
||||
DatabaseType::Mysql => format!("VARCHAR{len_part}"),
|
||||
DatabaseType::SqlServer => format!("NVARCHAR{len_part}"),
|
||||
_ => format!("VARCHAR{len_part}"),
|
||||
}
|
||||
} else {
|
||||
"VARCHAR(255)".into()
|
||||
}
|
||||
}
|
||||
"char" | "nchar" | "character" => {
|
||||
if t.contains('(') {
|
||||
let len_part = &t[t.find('(').unwrap()..];
|
||||
format!("CHAR{len_part}")
|
||||
} else {
|
||||
"CHAR(1)".into()
|
||||
}
|
||||
}
|
||||
"text" | "longtext" | "mediumtext" | "tinytext" | "clob" | "ntext" => "TEXT".into(),
|
||||
"bool" | "boolean" => match target_db {
|
||||
DatabaseType::Mysql => "TINYINT(1)".into(),
|
||||
DatabaseType::SqlServer => "BIT".into(),
|
||||
_ => "BOOLEAN".into(),
|
||||
},
|
||||
"date" => "DATE".into(),
|
||||
"time" => "TIME".into(),
|
||||
"datetime" => match target_db {
|
||||
DatabaseType::Postgres => "TIMESTAMP".into(),
|
||||
_ => "DATETIME".into(),
|
||||
},
|
||||
"timestamp" | "timestamptz" | "timestamp with time zone"
|
||||
| "timestamp without time zone" => match target_db {
|
||||
DatabaseType::Mysql => "DATETIME".into(),
|
||||
DatabaseType::SqlServer => "DATETIME2".into(),
|
||||
_ => "TIMESTAMP".into(),
|
||||
},
|
||||
"blob" | "longblob" | "mediumblob" | "tinyblob" | "binary" | "varbinary" | "image" => {
|
||||
match target_db {
|
||||
DatabaseType::Postgres => "BYTEA".into(),
|
||||
DatabaseType::Mysql => "BLOB".into(),
|
||||
DatabaseType::SqlServer => "VARBINARY(MAX)".into(),
|
||||
_ => "BLOB".into(),
|
||||
}
|
||||
}
|
||||
"bytea" => match target_db {
|
||||
DatabaseType::Postgres => "BYTEA".into(),
|
||||
DatabaseType::Mysql => "BLOB".into(),
|
||||
_ => "BLOB".into(),
|
||||
},
|
||||
"json" | "jsonb" => match target_db {
|
||||
DatabaseType::Postgres => "JSONB".into(),
|
||||
DatabaseType::Mysql => "JSON".into(),
|
||||
_ => "TEXT".into(),
|
||||
},
|
||||
"uuid" => match target_db {
|
||||
DatabaseType::Postgres => "UUID".into(),
|
||||
_ => "VARCHAR(36)".into(),
|
||||
},
|
||||
"bit" => match target_db {
|
||||
DatabaseType::Postgres => "BOOLEAN".into(),
|
||||
_ => "BIT".into(),
|
||||
},
|
||||
_ => "TEXT".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_create_table_ddl(
|
||||
columns: &[db::ColumnInfo],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
target_db: &DatabaseType,
|
||||
source_db: &DatabaseType,
|
||||
) -> String {
|
||||
let full_table = qualified_table(table, schema, target_db);
|
||||
|
||||
let col_lines: Vec<String> = columns
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mapped_type = map_column_type(&c.data_type, source_db, target_db);
|
||||
let mut line = format!(" {} {}", quote_identifier(&c.name, target_db), mapped_type);
|
||||
if !c.is_nullable {
|
||||
line.push_str(" NOT NULL");
|
||||
}
|
||||
line
|
||||
})
|
||||
.collect();
|
||||
|
||||
let pks: Vec<String> = columns
|
||||
.iter()
|
||||
.filter(|c| c.is_primary_key)
|
||||
.map(|c| quote_identifier(&c.name, target_db))
|
||||
.collect();
|
||||
|
||||
let mut ddl = match target_db {
|
||||
DatabaseType::SqlServer => format!("IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{table}')\n"),
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
let create_prefix = match target_db {
|
||||
DatabaseType::SqlServer => "CREATE TABLE",
|
||||
_ => "CREATE TABLE IF NOT EXISTS",
|
||||
};
|
||||
|
||||
ddl.push_str(&format!("{create_prefix} {full_table} (\n"));
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.join(", ")));
|
||||
}
|
||||
|
||||
ddl.push_str("\n)");
|
||||
|
||||
if matches!(target_db, DatabaseType::ClickHouse) {
|
||||
ddl.push_str(" ENGINE = MergeTree() ORDER BY tuple()");
|
||||
}
|
||||
|
||||
ddl
|
||||
}
|
||||
|
||||
pub fn generate_insert(
|
||||
columns: &[String],
|
||||
rows: &[Vec<serde_json::Value>],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
db_type: &DatabaseType,
|
||||
) -> String {
|
||||
if rows.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
let col_list = columns
|
||||
.iter()
|
||||
.map(|c| quote_identifier(c, db_type))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
let value_rows: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let vals: Vec<String> = row.iter().map(|v| escape_value(v, db_type)).collect();
|
||||
format!("({})", vals.join(", "))
|
||||
})
|
||||
.collect();
|
||||
|
||||
format!("INSERT INTO {full_table} ({col_list}) VALUES\n{}", value_rows.join(",\n"))
|
||||
}
|
||||
|
||||
pub fn pagination_sql(
|
||||
columns: &[String],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
db_type: &DatabaseType,
|
||||
offset: u64,
|
||||
limit: usize,
|
||||
) -> String {
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
let col_list = columns
|
||||
.iter()
|
||||
.map(|c| quote_identifier(c, db_type))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
match db_type {
|
||||
DatabaseType::SqlServer | DatabaseType::Oracle => {
|
||||
format!(
|
||||
"SELECT {col_list} FROM {full_table} ORDER BY (SELECT NULL) OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
format!("SELECT {col_list} FROM {full_table} LIMIT {limit} OFFSET {offset}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn count_sql(table: &str, schema: &str, db_type: &DatabaseType) -> String {
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
format!("SELECT COUNT(*) FROM {full_table}")
|
||||
}
|
||||
|
||||
pub async fn execute_on_pool(
|
||||
state: &AppState,
|
||||
pool_key: &str,
|
||||
sql: &str,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(pool_key).ok_or("Connection not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, bare) => {
|
||||
let p = p.clone();
|
||||
let bare = *bare;
|
||||
drop(connections);
|
||||
db::mysql::execute_query(&p, sql, bare).await
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::postgres::execute_query(&p, sql).await
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::sqlite::execute_query(&p, sql).await
|
||||
}
|
||||
PoolKind::ClickHouse(client) => {
|
||||
let client = client.clone();
|
||||
let database = pool_key.split(':').nth(1).unwrap_or("default").to_string();
|
||||
drop(connections);
|
||||
db::clickhouse_driver::execute_query(&client, &database, sql).await
|
||||
}
|
||||
PoolKind::SqlServer(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
db::sqlserver::execute_query(&mut client, sql).await
|
||||
}
|
||||
PoolKind::Oracle(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
db::oracle_driver::execute_query(&*client, sql).await
|
||||
}
|
||||
PoolKind::DuckDb(con) => {
|
||||
let con = con.clone();
|
||||
let sql = sql.to_string();
|
||||
drop(connections);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
let start = std::time::Instant::now();
|
||||
let trimmed = sql.trim().to_uppercase();
|
||||
if trimmed.starts_with("SELECT") || trimmed.starts_with("SHOW")
|
||||
|| trimmed.starts_with("DESCRIBE") || trimmed.starts_with("WITH")
|
||||
|| trimmed.starts_with("PRAGMA")
|
||||
{
|
||||
let mut stmt = con.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
let stmt_ref = rows.as_ref().ok_or("DuckDB statement unavailable")?;
|
||||
let col_count = stmt_ref.column_count();
|
||||
let columns: Vec<String> = (0..col_count)
|
||||
.map(|i| stmt_ref.column_name(i).map(|s| s.to_string()).unwrap_or_else(|_| "?".to_string()))
|
||||
.collect();
|
||||
let mut result_rows = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
let vals: Vec<serde_json::Value> = (0..col_count).map(|i| {
|
||||
row.get::<_, String>(i).map(serde_json::Value::String)
|
||||
.or_else(|_| row.get::<_, i64>(i).map(|v| serde_json::Value::Number(v.into())))
|
||||
.or_else(|_| row.get::<_, f64>(i).map(|v| {
|
||||
serde_json::Number::from_f64(v).map(serde_json::Value::Number).unwrap_or(serde_json::Value::Null)
|
||||
}))
|
||||
.or_else(|_| row.get::<_, bool>(i).map(serde_json::Value::Bool))
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}).collect();
|
||||
result_rows.push(vals);
|
||||
}
|
||||
Ok(db::QueryResult { columns, rows: result_rows, affected_rows: 0, execution_time_ms: start.elapsed().as_millis(), truncated: false })
|
||||
} else {
|
||||
let affected = con.execute(&sql, []).map_err(|e| e.to_string())?;
|
||||
Ok(db::QueryResult { columns: vec![], rows: vec![], affected_rows: affected as u64, execution_time_ms: start.elapsed().as_millis(), truncated: false })
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
_ => Err("Unsupported database type for transfer".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_db_type(state: &AppState, connection_id: &str) -> Result<DatabaseType, String> {
|
||||
let configs = state.configs.lock().await;
|
||||
configs
|
||||
.get(connection_id)
|
||||
.map(|c| c.db_type.clone())
|
||||
.ok_or_else(|| format!("Connection config not found: {connection_id}"))
|
||||
}
|
||||
|
||||
pub async fn get_columns_for_transfer(
|
||||
state: &AppState,
|
||||
pool_key: &str,
|
||||
_connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::ColumnInfo>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
|
||||
if let Some(PoolKind::DuckDb(con)) = connections.get(pool_key) {
|
||||
let con = con.clone();
|
||||
drop(connections);
|
||||
let table = table.to_string();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
let mut stmt = con.prepare(
|
||||
"SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'main' AND table_name = ?
|
||||
ORDER BY ordinal_position"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let rows = stmt.query_map([&table], |row| {
|
||||
Ok(db::ColumnInfo {
|
||||
name: row.get::<_, String>(0)?,
|
||||
data_type: row.get::<_, String>(1)?,
|
||||
is_nullable: row.get::<_, String>(2).unwrap_or_default() == "YES",
|
||||
column_default: row.get::<_, Option<String>>(3)?,
|
||||
is_primary_key: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
character_maximum_length: None,
|
||||
})
|
||||
}).map_err(|e| e.to_string())?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}).await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if let Some(PoolKind::ClickHouse(client)) = connections.get(pool_key) {
|
||||
let client = client.clone();
|
||||
let database = database.to_string();
|
||||
let table = table.to_string();
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::get_columns(&client, &database, &table).await;
|
||||
}
|
||||
if let Some(PoolKind::SqlServer(client)) = connections.get(pool_key) {
|
||||
let client = client.clone();
|
||||
let schema = schema.to_string();
|
||||
let table = table.to_string();
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::get_columns(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(PoolKind::Oracle(client)) = connections.get(pool_key) {
|
||||
let client = client.clone();
|
||||
let schema = schema.to_string();
|
||||
let table = table.to_string();
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::get_columns(&*client, &schema, &table).await;
|
||||
}
|
||||
|
||||
let pool = connections.get(pool_key).ok_or("Pool not found")?;
|
||||
let schema = schema.to_string();
|
||||
let table = table.to_string();
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::mysql::get_columns(&p, &schema, &table).await
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::postgres::get_columns(&p, &schema, &table).await
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::sqlite::get_columns(&p, &schema, &table).await
|
||||
}
|
||||
_ => Err("Unsupported database type".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn is_cancelled(transfer_id: &str) -> bool {
|
||||
CANCELLED.read().await.contains(transfer_id)
|
||||
}
|
||||
|
||||
pub async fn set_cancelled(transfer_id: &str) {
|
||||
CANCELLED.write().await.insert(transfer_id.to_string());
|
||||
}
|
||||
|
||||
pub async fn clear_cancelled(transfer_id: &str) {
|
||||
CANCELLED.write().await.remove(transfer_id);
|
||||
}
|
||||
|
||||
/// Transfer a single table. Returns rows transferred.
|
||||
/// `progress_callback` is invoked for progress updates.
|
||||
pub async fn transfer_table<F>(
|
||||
state: &AppState,
|
||||
request: &TransferRequest,
|
||||
table: &str,
|
||||
table_index: usize,
|
||||
source_db_type: &DatabaseType,
|
||||
target_db_type: &DatabaseType,
|
||||
source_pool_key: &str,
|
||||
target_pool_key: &str,
|
||||
mut progress_callback: F,
|
||||
) -> Result<u64, String>
|
||||
where
|
||||
F: FnMut(TransferProgress),
|
||||
{
|
||||
let total_tables = request.tables.len();
|
||||
|
||||
// Get source columns (deduplicate by name)
|
||||
let columns = {
|
||||
let raw = get_columns_for_transfer(
|
||||
state, source_pool_key, &request.source_connection_id,
|
||||
&request.source_database, &request.source_schema, table,
|
||||
).await?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
raw.into_iter().filter(|c| seen.insert(c.name.clone())).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if columns.is_empty() {
|
||||
return Err(format!("No columns found for table {table}"));
|
||||
}
|
||||
|
||||
let col_names: Vec<String> = columns.iter().map(|c| c.name.clone()).collect();
|
||||
log::info!("[transfer] {} has {} columns, counting rows...", table, columns.len());
|
||||
|
||||
// Count source rows
|
||||
let total_rows = {
|
||||
let sql = count_sql(table, &request.source_schema, source_db_type);
|
||||
match execute_on_pool(state, source_pool_key, &sql).await {
|
||||
Ok(result) => result.rows.first()
|
||||
.and_then(|r| r.first())
|
||||
.and_then(|v| match v {
|
||||
serde_json::Value::Number(n) => n.as_u64(),
|
||||
serde_json::Value::String(s) => s.parse::<u64>().ok(),
|
||||
_ => None,
|
||||
}),
|
||||
Err(e) => {
|
||||
log::warn!("[transfer] count failed for {}: {}", table, e);
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
log::info!("[transfer] {} total_rows={:?}", table, total_rows);
|
||||
|
||||
// Create table on target if requested
|
||||
if request.create_table {
|
||||
let ddl = generate_create_table_ddl(&columns, table, &request.target_schema, target_db_type, source_db_type);
|
||||
log::info!("[transfer] creating target table: {}", &ddl[..ddl.len().min(200)]);
|
||||
if let Err(e) = execute_on_pool(state, target_pool_key, &ddl).await {
|
||||
let err_lower = e.to_lowercase();
|
||||
if !err_lower.contains("already exists") && !err_lower.contains("there is already") {
|
||||
return Err(format!("Failed to create table: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Truncate target if requested
|
||||
if request.truncate_before {
|
||||
let full_table = qualified_table(table, &request.target_schema, target_db_type);
|
||||
let truncate_sql = match target_db_type {
|
||||
DatabaseType::Sqlite | DatabaseType::DuckDb => format!("DELETE FROM {full_table}"),
|
||||
_ => format!("TRUNCATE TABLE {full_table}"),
|
||||
};
|
||||
execute_on_pool(state, target_pool_key, &truncate_sql).await
|
||||
.map_err(|e| format!("Failed to truncate: {e}"))?;
|
||||
}
|
||||
|
||||
// Transfer data in batches
|
||||
let batch_size = if request.batch_size == 0 { 1000 } else { request.batch_size };
|
||||
let mut offset: u64 = 0;
|
||||
let mut total_transferred: u64 = 0;
|
||||
|
||||
loop {
|
||||
if is_cancelled(&request.transfer_id).await {
|
||||
return Err("Cancelled".to_string());
|
||||
}
|
||||
|
||||
let sql = pagination_sql(&col_names, table, &request.source_schema, source_db_type, offset, batch_size);
|
||||
let result = execute_on_pool(state, source_pool_key, &sql).await?;
|
||||
let row_count = result.rows.len();
|
||||
|
||||
if row_count == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
let insert_sql = generate_insert(&col_names, &result.rows, table, &request.target_schema, target_db_type);
|
||||
if !insert_sql.is_empty() {
|
||||
execute_on_pool(state, target_pool_key, &insert_sql).await
|
||||
.map_err(|e| format!("Insert failed at offset {offset}: {e}"))?;
|
||||
}
|
||||
|
||||
total_transferred += row_count as u64;
|
||||
log::info!("[transfer] {} batch +{} rows (total {})", table, row_count, total_transferred);
|
||||
offset += row_count as u64;
|
||||
|
||||
progress_callback(TransferProgress {
|
||||
transfer_id: request.transfer_id.clone(),
|
||||
table: table.to_string(),
|
||||
table_index,
|
||||
total_tables,
|
||||
rows_transferred: total_transferred,
|
||||
total_rows,
|
||||
status: TransferStatus::Running,
|
||||
error: None,
|
||||
});
|
||||
|
||||
if row_count < batch_size {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(total_transferred)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DatabaseInfo {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
pub table_type: String, // "TABLE" or "VIEW"
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ColumnInfo {
|
||||
pub name: String,
|
||||
pub data_type: String,
|
||||
pub is_nullable: bool,
|
||||
pub column_default: Option<String>,
|
||||
pub is_primary_key: bool,
|
||||
pub extra: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
pub numeric_precision: Option<i32>,
|
||||
pub numeric_scale: Option<i32>,
|
||||
pub character_maximum_length: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct QueryResult {
|
||||
pub columns: Vec<String>,
|
||||
pub rows: Vec<Vec<serde_json::Value>>,
|
||||
pub affected_rows: u64,
|
||||
pub execution_time_ms: u128,
|
||||
#[serde(default)]
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IndexInfo {
|
||||
pub name: String,
|
||||
pub columns: Vec<String>,
|
||||
pub is_unique: bool,
|
||||
pub is_primary: bool,
|
||||
pub filter: Option<String>,
|
||||
pub index_type: Option<String>,
|
||||
pub included_columns: Option<Vec<String>>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ForeignKeyInfo {
|
||||
pub name: String,
|
||||
pub column: String,
|
||||
pub ref_table: String,
|
||||
pub ref_column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TriggerInfo {
|
||||
pub name: String,
|
||||
pub event: String,
|
||||
pub timing: String,
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/t8y2/dbx/releases/latest";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GithubRelease {
|
||||
pub tag_name: String,
|
||||
pub name: Option<String>,
|
||||
pub html_url: String,
|
||||
pub body: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UpdateInfo {
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub update_available: bool,
|
||||
pub release_name: String,
|
||||
pub release_url: String,
|
||||
pub release_notes: String,
|
||||
}
|
||||
|
||||
pub async fn fetch_latest_release() -> Result<GithubRelease, String> {
|
||||
let client = reqwest::Client::new();
|
||||
client
|
||||
.get(LATEST_RELEASE_URL)
|
||||
.header(reqwest::header::USER_AGENT, "dbx-update-checker")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to check updates: {e}"))?
|
||||
.error_for_status()
|
||||
.map_err(|e| format!("Failed to check updates: {e}"))?
|
||||
.json::<GithubRelease>()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse update response: {e}"))
|
||||
}
|
||||
|
||||
pub fn build_update_info(release: GithubRelease, current_version: &str) -> UpdateInfo {
|
||||
let latest_version = normalize_version(&release.tag_name);
|
||||
|
||||
UpdateInfo {
|
||||
update_available: is_newer_version(&latest_version, current_version),
|
||||
current_version: current_version.to_string(),
|
||||
latest_version,
|
||||
release_name: release.name.unwrap_or_else(|| release.tag_name.clone()),
|
||||
release_url: release.html_url,
|
||||
release_notes: release.body.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_version(version: &str) -> String {
|
||||
version.trim().trim_start_matches('v').to_string()
|
||||
}
|
||||
|
||||
pub fn parse_version(version: &str) -> Vec<u64> {
|
||||
normalize_version(version)
|
||||
.split(['.', '-', '+'])
|
||||
.map(|part| part.parse::<u64>().unwrap_or(0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn is_newer_version(latest: &str, current: &str) -> bool {
|
||||
let latest_parts = parse_version(latest);
|
||||
let current_parts = parse_version(current);
|
||||
let max_len = latest_parts.len().max(current_parts.len());
|
||||
|
||||
for i in 0..max_len {
|
||||
let latest_part = *latest_parts.get(i).unwrap_or(&0);
|
||||
let current_part = *current_parts.get(i).unwrap_or(&0);
|
||||
if latest_part > current_part {
|
||||
return true;
|
||||
}
|
||||
if latest_part < current_part {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{is_newer_version, normalize_version};
|
||||
|
||||
#[test]
|
||||
fn normalizes_tag_versions() {
|
||||
assert_eq!(normalize_version("v1.2.3"), "1.2.3");
|
||||
assert_eq!(normalize_version(" 0.2.0 "), "0.2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compares_semver_like_versions() {
|
||||
assert!(is_newer_version("0.2.1", "0.2.0"));
|
||||
assert!(is_newer_version("1.0.0", "0.9.9"));
|
||||
assert!(!is_newer_version("0.2.0", "0.2.0"));
|
||||
assert!(!is_newer_version("0.1.9", "0.2.0"));
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,6 @@ crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.5.6", features = [] }
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
strip = true
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
opt-level = "s"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
@@ -54,3 +47,4 @@ russh = "0.60"
|
||||
keyring = { version = "3.6.3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }
|
||||
csv = "1.4.0"
|
||||
calamine = "0.30.1"
|
||||
dbx-core = { path = "../crates/dbx-core" }
|
||||
|
||||
+48
-712
@@ -1,64 +1,6 @@
|
||||
use futures::StreamExt;
|
||||
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
static AI_STREAMS: LazyLock<RwLock<HashMap<String, Arc<AtomicBool>>>> =
|
||||
LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AiProvider {
|
||||
Claude,
|
||||
Openai,
|
||||
Custom,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AiApiStyle {
|
||||
Completions,
|
||||
Responses,
|
||||
}
|
||||
|
||||
impl Default for AiApiStyle {
|
||||
fn default() -> Self {
|
||||
Self::Completions
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiConfig {
|
||||
pub provider: AiProvider,
|
||||
pub api_key: String,
|
||||
pub endpoint: String,
|
||||
pub model: String,
|
||||
#[serde(default)]
|
||||
pub api_style: AiApiStyle,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiMessage {
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiCompletionRequest {
|
||||
pub config: AiConfig,
|
||||
pub system_prompt: String,
|
||||
pub messages: Vec<AiMessage>,
|
||||
pub max_tokens: Option<u32>,
|
||||
pub temperature: Option<f32>,
|
||||
}
|
||||
pub use dbx_core::ai::*;
|
||||
|
||||
fn ai_config_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
@@ -66,674 +8,68 @@ fn ai_config_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
Ok(dir.join("ai_config.json"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_test_connection(config: AiConfig) -> Result<String, String> {
|
||||
if config.api_key.trim().is_empty() {
|
||||
return Err("API key is required".to_string());
|
||||
}
|
||||
if config.endpoint.trim().is_empty() {
|
||||
return Err("Endpoint is required".to_string());
|
||||
}
|
||||
if config.model.trim().is_empty() {
|
||||
return Err("Model is required".to_string());
|
||||
}
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let request = AiCompletionRequest {
|
||||
config,
|
||||
system_prompt: String::new(),
|
||||
messages: vec![AiMessage { role: "user".into(), content: "hi".into() }],
|
||||
max_tokens: Some(1),
|
||||
temperature: Some(0.0),
|
||||
};
|
||||
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => call_claude(&client, request).await,
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if request.config.api_style == AiApiStyle::Responses {
|
||||
call_responses_api(&client, request).await
|
||||
} else {
|
||||
call_openai_compatible(&client, request).await
|
||||
}
|
||||
}
|
||||
}.map(|_| "OK".to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_ai_config(app: AppHandle, config: AiConfig) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?;
|
||||
std::fs::write(ai_config_file(&app)?, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn load_ai_config(app: AppHandle) -> Result<Option<AiConfig>, String> {
|
||||
let path = ai_config_file(&app)?;
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map(Some).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_complete(request: AiCompletionRequest) -> Result<String, String> {
|
||||
if request.config.api_key.trim().is_empty() {
|
||||
return Err("API key is required".to_string());
|
||||
}
|
||||
if request.config.endpoint.trim().is_empty() {
|
||||
return Err("Endpoint is required".to_string());
|
||||
}
|
||||
if request.config.model.trim().is_empty() {
|
||||
return Err("Model is required".to_string());
|
||||
}
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => call_claude(&client, request).await,
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if request.config.api_style == AiApiStyle::Responses {
|
||||
call_responses_api(&client, request).await
|
||||
} else {
|
||||
call_openai_compatible(&client, request).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
struct AiStreamChunk {
|
||||
session_id: String,
|
||||
delta: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
reasoning_delta: Option<String>,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_stream(app: AppHandle, session_id: String, request: AiCompletionRequest) -> Result<(), String> {
|
||||
if request.config.api_key.trim().is_empty() {
|
||||
return Err("API key is required".to_string());
|
||||
}
|
||||
if request.config.endpoint.trim().is_empty() {
|
||||
return Err("Endpoint is required".to_string());
|
||||
}
|
||||
if request.config.model.trim().is_empty() {
|
||||
return Err("Model is required".to_string());
|
||||
}
|
||||
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
AI_STREAMS.write().await.insert(session_id.clone(), cancelled.clone());
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let result = match request.config.provider {
|
||||
AiProvider::Claude => stream_claude(&app, &client, &session_id, request, &cancelled).await,
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if request.config.api_style == AiApiStyle::Responses {
|
||||
stream_responses_api(&app, &client, &session_id, request, &cancelled).await
|
||||
} else {
|
||||
stream_openai(&app, &client, &session_id, request, &cancelled).await
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
AI_STREAMS.write().await.remove(&session_id);
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_cancel_stream(session_id: String) -> Result<bool, String> {
|
||||
if let Some(flag) = AI_STREAMS.read().await.get(&session_id) {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream_claude(app: &AppHandle, client: &reqwest::Client, session_id: &str, request: AiCompletionRequest, cancelled: &AtomicBool) -> Result<(), String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
"x-api-key",
|
||||
HeaderValue::from_str(&request.config.api_key).map_err(|e| e.to_string())?,
|
||||
);
|
||||
headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"system": request.system_prompt,
|
||||
"messages": request.messages,
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Claude request failed: {e}"))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
return Err(extract_error(&data).unwrap_or_else(|| "Claude API error".to_string()));
|
||||
}
|
||||
|
||||
let mut stream = res.bytes_stream();
|
||||
let mut buf = String::new();
|
||||
|
||||
let mut finished = false;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
buf.push_str(&String::from_utf8_lossy(&chunk));
|
||||
|
||||
while let Some(pos) = buf.find('\n') {
|
||||
let line = buf[..pos].to_string();
|
||||
buf = buf[pos + 1..].to_string();
|
||||
|
||||
let Some(data) = stream_data_payload(&line) else {
|
||||
continue;
|
||||
};
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(data) {
|
||||
if let Some(text) = claude_stream_text(&event) {
|
||||
emit_stream_delta(app, session_id, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = app.emit("ai-stream-chunk", AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: None,
|
||||
done: true,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stream_openai(app: &AppHandle, client: &reqwest::Client, session_id: &str, request: AiCompletionRequest, cancelled: &AtomicBool) -> Result<(), String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key)).map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let mut messages = vec![json!({ "role": "system", "content": request.system_prompt })];
|
||||
messages.extend(
|
||||
request.messages.iter().map(|m| json!({ "role": m.role, "content": m.content })),
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"messages": messages,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
return Err(extract_error(&data).unwrap_or_else(|| "API error".to_string()));
|
||||
}
|
||||
|
||||
let mut stream = res.bytes_stream();
|
||||
let mut buf = String::new();
|
||||
|
||||
let mut finished = false;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
buf.push_str(&String::from_utf8_lossy(&chunk));
|
||||
|
||||
while let Some(pos) = buf.find('\n') {
|
||||
let line = buf[..pos].to_string();
|
||||
buf = buf[pos + 1..].to_string();
|
||||
|
||||
let Some(data) = stream_data_payload(&line) else {
|
||||
continue;
|
||||
};
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(data) {
|
||||
if let Some(reasoning) = openai_stream_reasoning(&event) {
|
||||
emit_stream_reasoning(app, session_id, reasoning);
|
||||
}
|
||||
if let Some(text) = openai_stream_text(&event) {
|
||||
emit_stream_delta(app, session_id, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = app.emit("ai-stream-chunk", AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: None,
|
||||
done: true,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn call_claude(client: &reqwest::Client, request: AiCompletionRequest) -> Result<String, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
"x-api-key",
|
||||
HeaderValue::from_str(&request.config.api_key).map_err(|e| e.to_string())?,
|
||||
);
|
||||
headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"system": request.system_prompt,
|
||||
"messages": request.messages,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Claude request failed: {e}"))?;
|
||||
|
||||
let status = res.status();
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(extract_error(&data).unwrap_or_else(|| format!("Claude API error: {status}")));
|
||||
}
|
||||
|
||||
Ok(data["content"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find_map(|item| item["text"].as_str()))
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
async fn call_openai_compatible(
|
||||
client: &reqwest::Client,
|
||||
request: AiCompletionRequest,
|
||||
) -> Result<String, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key)).map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let mut messages = vec![json!({ "role": "system", "content": request.system_prompt })];
|
||||
messages.extend(
|
||||
request
|
||||
.messages
|
||||
.iter()
|
||||
.map(|message| json!({ "role": message.role, "content": message.content })),
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"messages": messages,
|
||||
"max_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
let status = res.status();
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(extract_error(&data).unwrap_or_else(|| format!("API error: {status}")));
|
||||
}
|
||||
|
||||
Ok(data["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
fn extract_error(data: &serde_json::Value) -> Option<String> {
|
||||
data["error"]["message"]
|
||||
.as_str()
|
||||
.or_else(|| data["error"].as_str())
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
fn resolve_endpoint(config: &AiConfig) -> String {
|
||||
let ep = config.endpoint.trim().trim_end_matches('/');
|
||||
if ep.ends_with("/chat/completions") || ep.ends_with("/responses") || ep.ends_with("/messages") {
|
||||
return ep.to_string();
|
||||
}
|
||||
match config.provider {
|
||||
AiProvider::Claude => format!("{ep}/messages"),
|
||||
AiProvider::Openai | AiProvider::Custom => {
|
||||
if config.api_style == AiApiStyle::Responses {
|
||||
format!("{ep}/responses")
|
||||
} else {
|
||||
format!("{ep}/chat/completions")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_data_payload(line: &str) -> Option<&str> {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with(':') || line.starts_with("event:") || line.starts_with("id:") {
|
||||
return None;
|
||||
}
|
||||
if let Some(data) = line.strip_prefix("data:") {
|
||||
return Some(data.trim_start());
|
||||
}
|
||||
if line.starts_with('{') {
|
||||
return Some(line);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn claude_stream_text(event: &serde_json::Value) -> Option<&str> {
|
||||
if event["type"] == "content_block_delta" {
|
||||
return event["delta"]["text"].as_str();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn openai_stream_text(event: &serde_json::Value) -> Option<&str> {
|
||||
event["choices"]
|
||||
.get(0)
|
||||
.and_then(|choice| {
|
||||
choice["delta"]["content"]
|
||||
.as_str()
|
||||
.or_else(|| choice["message"]["content"].as_str())
|
||||
})
|
||||
.or_else(|| event["content"].as_str())
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
fn openai_stream_reasoning(event: &serde_json::Value) -> Option<&str> {
|
||||
event["choices"]
|
||||
.get(0)
|
||||
.and_then(|choice| choice["delta"]["reasoning_content"].as_str())
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
fn emit_stream_delta(app: &AppHandle, session_id: &str, delta: &str) {
|
||||
let _ = app.emit("ai-stream-chunk", AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: delta.to_string(),
|
||||
reasoning_delta: None,
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
|
||||
fn emit_stream_reasoning(app: &AppHandle, session_id: &str, reasoning: &str) {
|
||||
let _ = app.emit("ai-stream-chunk", AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: Some(reasoning.to_string()),
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
|
||||
fn build_responses_input(system_prompt: &str, messages: &[AiMessage]) -> serde_json::Value {
|
||||
let mut input = Vec::new();
|
||||
if !system_prompt.is_empty() {
|
||||
input.push(json!({
|
||||
"role": "developer",
|
||||
"content": system_prompt,
|
||||
}));
|
||||
}
|
||||
for m in messages {
|
||||
input.push(json!({
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
}));
|
||||
}
|
||||
json!(input)
|
||||
}
|
||||
|
||||
async fn call_responses_api(
|
||||
client: &reqwest::Client,
|
||||
request: AiCompletionRequest,
|
||||
) -> Result<String, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key)).map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"input": build_responses_input(&request.system_prompt, &request.messages),
|
||||
"max_output_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
let status = res.status();
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(extract_error(&data).unwrap_or_else(|| format!("API error: {status}")));
|
||||
}
|
||||
|
||||
Ok(data["output"]
|
||||
.as_array()
|
||||
.and_then(|items| {
|
||||
items.iter().find_map(|item| {
|
||||
item["content"]
|
||||
.as_array()
|
||||
.and_then(|parts| parts.iter().find_map(|p| p["text"].as_str()))
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
async fn stream_responses_api(app: &AppHandle, client: &reqwest::Client, session_id: &str, request: AiCompletionRequest, cancelled: &AtomicBool) -> Result<(), String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", request.config.api_key)).map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"model": request.config.model,
|
||||
"input": build_responses_input(&request.system_prompt, &request.messages),
|
||||
"max_output_tokens": request.max_tokens.unwrap_or(2048),
|
||||
"temperature": request.temperature.unwrap_or(0.2),
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let res = client
|
||||
.post(&resolve_endpoint(&request.config))
|
||||
.headers(headers)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("AI request failed: {e}"))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||
return Err(extract_error(&data).unwrap_or_else(|| "API error".to_string()));
|
||||
}
|
||||
|
||||
let mut stream = res.bytes_stream();
|
||||
let mut buf = String::new();
|
||||
|
||||
let mut finished = false;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
buf.push_str(&String::from_utf8_lossy(&chunk));
|
||||
|
||||
while let Some(pos) = buf.find('\n') {
|
||||
let line = buf[..pos].to_string();
|
||||
buf = buf[pos + 1..].to_string();
|
||||
|
||||
let Some(data) = stream_data_payload(&line) else {
|
||||
continue;
|
||||
};
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(data) {
|
||||
if let Some(text) = responses_stream_text(&event) {
|
||||
emit_stream_delta(app, session_id, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = app.emit("ai-stream-chunk", AiStreamChunk {
|
||||
session_id: session_id.to_string(),
|
||||
delta: String::new(),
|
||||
reasoning_delta: None,
|
||||
done: true,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn responses_stream_text(event: &serde_json::Value) -> Option<&str> {
|
||||
event["delta"].as_str().filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
// --- AI Conversation Persistence ---
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiChatMessage {
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiConversation {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub connection_name: String,
|
||||
pub database: String,
|
||||
pub messages: Vec<AiChatMessage>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
fn conversations_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
Ok(dir.join("ai_conversations.json"))
|
||||
}
|
||||
|
||||
fn read_conversations(app: &AppHandle) -> Result<Vec<AiConversation>, String> {
|
||||
let path = conversations_file(app)?;
|
||||
if !path.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map_err(|e| e.to_string())
|
||||
#[tauri::command]
|
||||
pub async fn ai_test_connection(config: AiConfig) -> Result<String, String> {
|
||||
dbx_core::ai::test_connection_core(&config).await
|
||||
}
|
||||
|
||||
fn write_conversations(app: &AppHandle, conversations: &[AiConversation]) -> Result<(), String> {
|
||||
let path = conversations_file(app)?;
|
||||
let json = serde_json::to_string(conversations).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
const MAX_CONVERSATIONS: usize = 50;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_ai_conversation(app: AppHandle, conversation: AiConversation) -> Result<(), String> {
|
||||
let mut conversations = read_conversations(&app)?;
|
||||
if let Some(pos) = conversations.iter().position(|c| c.id == conversation.id) {
|
||||
conversations[pos] = conversation;
|
||||
} else {
|
||||
conversations.insert(0, conversation);
|
||||
conversations.truncate(MAX_CONVERSATIONS);
|
||||
}
|
||||
write_conversations(&app, &conversations)
|
||||
pub async fn save_ai_config(app: AppHandle, config: AiConfig) -> Result<(), String> {
|
||||
dbx_core::ai::save_config(&ai_config_file(&app)?, &config)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn load_ai_config(app: AppHandle) -> Result<Option<AiConfig>, String> {
|
||||
dbx_core::ai::load_config(&ai_config_file(&app)?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_complete(request: AiCompletionRequest) -> Result<String, String> {
|
||||
dbx_core::ai::complete(&request).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_stream(
|
||||
app: AppHandle,
|
||||
session_id: String,
|
||||
request: AiCompletionRequest,
|
||||
) -> Result<(), String> {
|
||||
let cancelled = dbx_core::ai::register_stream(&session_id).await;
|
||||
|
||||
let result = dbx_core::ai::stream(&session_id, &request, &cancelled, |chunk| {
|
||||
let _ = app.emit("ai-stream-chunk", &chunk);
|
||||
})
|
||||
.await;
|
||||
|
||||
dbx_core::ai::unregister_stream(&session_id).await;
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn ai_cancel_stream(session_id: String) -> Result<bool, String> {
|
||||
Ok(dbx_core::ai::cancel_stream(&session_id).await)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_ai_conversation(
|
||||
app: AppHandle,
|
||||
conversation: AiConversation,
|
||||
) -> Result<(), String> {
|
||||
dbx_core::ai::save_conversation(&conversations_file(&app)?, conversation)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn load_ai_conversations(app: AppHandle) -> Result<Vec<AiConversation>, String> {
|
||||
read_conversations(&app)
|
||||
dbx_core::ai::load_conversations(&conversations_file(&app)?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn delete_ai_conversation(app: AppHandle, id: String) -> Result<(), String> {
|
||||
let conversations: Vec<AiConversation> = read_conversations(&app)?
|
||||
.into_iter()
|
||||
.filter(|c| c.id != id)
|
||||
.collect();
|
||||
write_conversations(&app, &conversations)
|
||||
dbx_core::ai::delete_conversation(&conversations_file(&app)?, &id)
|
||||
}
|
||||
|
||||
@@ -1,218 +1,16 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::commands::connection_secrets::{
|
||||
create_secret_store, load_connections_from_file, save_connections_to_file,
|
||||
};
|
||||
use crate::commands::query_cancel::RunningQueries;
|
||||
use crate::db;
|
||||
use crate::db::ssh_tunnel::TunnelManager;
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType};
|
||||
|
||||
fn expand_tilde(path: &str) -> String {
|
||||
if path == "~" || path.starts_with("~/") {
|
||||
if let Ok(home) = std::env::var(if cfg!(windows) { "USERPROFILE" } else { "HOME" }) {
|
||||
return format!("{}{}", home, &path[1..]);
|
||||
}
|
||||
}
|
||||
path.to_string()
|
||||
}
|
||||
|
||||
pub enum PoolKind {
|
||||
Mysql(sqlx::mysql::MySqlPool, bool),
|
||||
Postgres(sqlx::postgres::PgPool),
|
||||
Sqlite(sqlx::sqlite::SqlitePool),
|
||||
Redis(tokio::sync::Mutex<redis::aio::MultiplexedConnection>),
|
||||
DuckDb(std::sync::Arc<std::sync::Mutex<duckdb::Connection>>),
|
||||
MongoDb(mongodb::Client),
|
||||
ClickHouse(db::clickhouse_driver::ChClient),
|
||||
SqlServer(std::sync::Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>),
|
||||
Oracle(std::sync::Arc<tokio::sync::Mutex<db::oracle_driver::OracleClient>>),
|
||||
Elasticsearch(db::elasticsearch_driver::EsClient),
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub connections: Mutex<HashMap<String, PoolKind>>,
|
||||
pub configs: Mutex<HashMap<String, ConnectionConfig>>,
|
||||
pub running_queries: RunningQueries,
|
||||
pub tunnels: TunnelManager,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
connections: Mutex::new(HashMap::new()),
|
||||
configs: Mutex::new(HashMap::new()),
|
||||
running_queries: RunningQueries::default(),
|
||||
tunnels: TunnelManager::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_or_create_pool(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
database: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let db_type = {
|
||||
let configs = self.configs.lock().await;
|
||||
configs.get(connection_id).map(|c| c.db_type.clone())
|
||||
};
|
||||
|
||||
let is_embedded = matches!(db_type, Some(DatabaseType::Sqlite) | Some(DatabaseType::DuckDb));
|
||||
if is_embedded {
|
||||
return Ok(connection_id.to_string());
|
||||
}
|
||||
|
||||
let is_single_conn = matches!(db_type, Some(DatabaseType::Oracle));
|
||||
let pool_key = if is_single_conn {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
match database {
|
||||
Some(db) => format!("{connection_id}:{db}"),
|
||||
None => connection_id.to_string(),
|
||||
}
|
||||
};
|
||||
|
||||
let conns = self.connections.lock().await;
|
||||
if conns.contains_key(&pool_key) {
|
||||
return Ok(pool_key);
|
||||
}
|
||||
drop(conns);
|
||||
|
||||
let configs = self.configs.lock().await;
|
||||
let config = configs
|
||||
.get(connection_id)
|
||||
.ok_or("Connection config not found")?
|
||||
.clone();
|
||||
drop(configs);
|
||||
|
||||
let mut db_config = config.clone();
|
||||
if let Some(db) = database {
|
||||
if db_config.db_type != DatabaseType::Oracle {
|
||||
db_config.database = Some(db.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let (host, port) = self.connection_host_port(connection_id, &db_config).await?;
|
||||
let url = connection_url_for_endpoint(&db_config, &host, port);
|
||||
let pool = match db_config.db_type {
|
||||
DatabaseType::Mysql if db_config.needs_bare_mysql() => PoolKind::Mysql(db::mysql::connect_bare(&url).await?, true),
|
||||
DatabaseType::Mysql => PoolKind::Mysql(db::mysql::connect(&url).await?, false),
|
||||
DatabaseType::Doris | DatabaseType::StarRocks => PoolKind::Mysql(db::mysql::connect_bare(&url).await?, true),
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => PoolKind::Postgres(db::postgres::connect(&url).await?),
|
||||
DatabaseType::Sqlite => PoolKind::Sqlite(db::sqlite::connect_path(&expand_tilde(&db_config.host)).await?),
|
||||
DatabaseType::Redis => {
|
||||
let con = db::redis_driver::connect(&url).await?;
|
||||
PoolKind::Redis(tokio::sync::Mutex::new(con))
|
||||
}
|
||||
DatabaseType::DuckDb => {
|
||||
let con = duckdb::Connection::open(&expand_tilde(&db_config.host)).map_err(|e| e.to_string())?;
|
||||
PoolKind::DuckDb(std::sync::Arc::new(std::sync::Mutex::new(con)))
|
||||
}
|
||||
DatabaseType::MongoDb => {
|
||||
let client = mongodb::Client::with_uri_str(&url).await.map_err(|e| e.to_string())?;
|
||||
PoolKind::MongoDb(client)
|
||||
}
|
||||
DatabaseType::ClickHouse => {
|
||||
let username = if db_config.username.is_empty() { None } else { Some(db_config.username.clone()) };
|
||||
let password = if db_config.password.is_empty() { None } else { Some(db_config.password.clone()) };
|
||||
let client = db::clickhouse_driver::ChClient::new(&url, username, password);
|
||||
db::clickhouse_driver::test_connection(&client).await?;
|
||||
PoolKind::ClickHouse(client)
|
||||
}
|
||||
DatabaseType::SqlServer => {
|
||||
let client = db::sqlserver::connect(
|
||||
&host,
|
||||
port,
|
||||
&db_config.username,
|
||||
&db_config.password,
|
||||
db_config.database.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
PoolKind::SqlServer(std::sync::Arc::new(tokio::sync::Mutex::new(client)))
|
||||
}
|
||||
DatabaseType::Oracle => {
|
||||
let client = db::oracle_driver::connect(
|
||||
&host,
|
||||
port,
|
||||
db_config.database.as_deref().unwrap_or("ORCL"),
|
||||
&db_config.username, &db_config.password,
|
||||
)
|
||||
.await?;
|
||||
PoolKind::Oracle(std::sync::Arc::new(tokio::sync::Mutex::new(client)))
|
||||
}
|
||||
DatabaseType::Elasticsearch => {
|
||||
let client = db::elasticsearch_driver::EsClient::new(
|
||||
&url,
|
||||
Some(&db_config.username),
|
||||
Some(&db_config.password),
|
||||
);
|
||||
db::elasticsearch_driver::test_connection(&client).await?;
|
||||
PoolKind::Elasticsearch(client)
|
||||
}
|
||||
};
|
||||
|
||||
self.connections.lock().await.insert(pool_key.clone(), pool);
|
||||
Ok(pool_key)
|
||||
}
|
||||
|
||||
async fn connection_host_port(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
config: &ConnectionConfig,
|
||||
) -> Result<(String, u16), String> {
|
||||
if !config.ssh_enabled || config.ssh_host.is_empty() {
|
||||
return Ok((config.host.clone(), config.port));
|
||||
}
|
||||
|
||||
if let Some(local_port) = self.tunnels.local_port(connection_id).await {
|
||||
return Ok(("127.0.0.1".to_string(), local_port));
|
||||
}
|
||||
|
||||
let local_port = self
|
||||
.tunnels
|
||||
.start_tunnel(
|
||||
connection_id,
|
||||
&config.ssh_host,
|
||||
config.ssh_port,
|
||||
&config.ssh_user,
|
||||
&config.ssh_password,
|
||||
&config.ssh_key_path,
|
||||
&config.ssh_key_passphrase,
|
||||
&config.host,
|
||||
config.port,
|
||||
config.ssh_expose_lan,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(("127.0.0.1".to_string(), local_port))
|
||||
}
|
||||
|
||||
pub async fn reconnect_pool(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
database: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let is_single_conn = {
|
||||
let configs = self.configs.lock().await;
|
||||
configs.get(connection_id)
|
||||
.map(|c| c.db_type == DatabaseType::Oracle || c.db_type == DatabaseType::Elasticsearch)
|
||||
.unwrap_or(false)
|
||||
};
|
||||
let pool_key = if is_single_conn {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
match database {
|
||||
Some(db) => format!("{connection_id}:{db}"),
|
||||
None => connection_id.to_string(),
|
||||
}
|
||||
};
|
||||
self.connections.lock().await.remove(&pool_key);
|
||||
self.get_or_create_pool(connection_id, database).await
|
||||
}
|
||||
}
|
||||
pub use dbx_core::connection::{
|
||||
connection_url_for_endpoint, expand_tilde, redacted_connection_url_for_endpoint, AppState,
|
||||
PoolKind,
|
||||
};
|
||||
use dbx_core::db;
|
||||
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
|
||||
|
||||
fn connections_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
@@ -220,24 +18,10 @@ fn connections_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
Ok(dir.join("connections.json"))
|
||||
}
|
||||
|
||||
fn connection_url_for_endpoint(config: &ConnectionConfig, host: &str, port: u16) -> String {
|
||||
if host == config.host && port == config.port {
|
||||
config.connection_url()
|
||||
} else {
|
||||
config.connection_url_with_host(host, port)
|
||||
}
|
||||
}
|
||||
|
||||
fn redacted_connection_url_for_endpoint(
|
||||
config: &ConnectionConfig,
|
||||
host: &str,
|
||||
port: u16,
|
||||
) -> String {
|
||||
if host == config.host && port == config.port {
|
||||
config.redacted_connection_url()
|
||||
} else {
|
||||
config.redacted_connection_url_with_host(host, port)
|
||||
}
|
||||
fn sidebar_layout_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
Ok(dir.join("sidebar_layout.json"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -257,12 +41,6 @@ pub async fn load_connections(app: AppHandle) -> Result<Vec<ConnectionConfig>, S
|
||||
load_connections_from_file(&path, &*store)
|
||||
}
|
||||
|
||||
fn sidebar_layout_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
Ok(dir.join("sidebar_layout.json"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_sidebar_layout(
|
||||
app: AppHandle,
|
||||
|
||||
@@ -1,22 +1,14 @@
|
||||
use crate::models::connection::ConnectionConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
pub(super) const MAIN_PASSWORD_KEY: &str = "password";
|
||||
pub(super) const SSH_PASSWORD_KEY: &str = "ssh_password";
|
||||
pub(super) const SSH_KEY_PASSPHRASE_KEY: &str = "ssh_key_passphrase";
|
||||
pub(super) const CONNECTION_STRING_KEY: &str = "connection_string";
|
||||
// Re-export core types and functions
|
||||
pub(super) use dbx_core::connection_secrets::{
|
||||
save_connections_to_file, load_connections_from_file,
|
||||
ConnectionSecretStore, FileSecretStore,
|
||||
secret_account,
|
||||
};
|
||||
|
||||
const KEYRING_SERVICE: &str = "dev.dbx.connections";
|
||||
|
||||
pub(super) trait ConnectionSecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String>;
|
||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String>;
|
||||
fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
pub(super) struct KeyringConnectionSecretStore;
|
||||
|
||||
impl ConnectionSecretStore for KeyringConnectionSecretStore {
|
||||
@@ -45,46 +37,6 @@ impl ConnectionSecretStore for KeyringConnectionSecretStore {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct FileSecretStore {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl FileSecretStore {
|
||||
fn new(path: PathBuf) -> Self {
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn read_store(&self) -> HashMap<String, String> {
|
||||
std::fs::read_to_string(&self.path)
|
||||
.ok()
|
||||
.and_then(|json| serde_json::from_str(&json).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_store(&self, map: &HashMap<String, String>) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(map).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&self.path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionSecretStore for FileSecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String> {
|
||||
let mut map = self.read_store();
|
||||
map.insert(secret_account(connection_id, key), secret.to_string());
|
||||
self.write_store(&map)
|
||||
}
|
||||
|
||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String> {
|
||||
Ok(self.read_store().get(&secret_account(connection_id, key)).cloned())
|
||||
}
|
||||
|
||||
fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String> {
|
||||
let mut map = self.read_store();
|
||||
map.remove(&secret_account(connection_id, key));
|
||||
self.write_store(&map)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_secret_store(app: &AppHandle) -> Box<dyn ConnectionSecretStore> {
|
||||
if cfg!(debug_assertions) {
|
||||
let dir = app.path().app_data_dir().expect("failed to resolve app data dir");
|
||||
@@ -95,391 +47,11 @@ pub(super) fn create_secret_store(app: &AppHandle) -> Box<dyn ConnectionSecretSt
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn save_connections_to_file(
|
||||
path: &Path,
|
||||
configs: &[ConnectionConfig],
|
||||
store: &dyn ConnectionSecretStore,
|
||||
) -> Result<(), String> {
|
||||
delete_removed_connection_secrets(path, configs, store)?;
|
||||
for config in configs {
|
||||
persist_secret(store, &config.id, MAIN_PASSWORD_KEY, &config.password)?;
|
||||
persist_secret(store, &config.id, SSH_PASSWORD_KEY, &config.ssh_password)?;
|
||||
persist_secret(store, &config.id, SSH_KEY_PASSPHRASE_KEY, &config.ssh_key_passphrase)?;
|
||||
persist_optional_secret(
|
||||
store,
|
||||
&config.id,
|
||||
CONNECTION_STRING_KEY,
|
||||
config.connection_string.as_deref(),
|
||||
)?;
|
||||
}
|
||||
|
||||
write_sanitized_connections(path, configs)
|
||||
}
|
||||
|
||||
pub(super) fn load_connections_from_file(
|
||||
path: &Path,
|
||||
store: &dyn ConnectionSecretStore,
|
||||
) -> Result<Vec<ConnectionConfig>, String> {
|
||||
if !path.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let mut configs = read_connections(path)?;
|
||||
let mut needs_rewrite = false;
|
||||
for config in &mut configs {
|
||||
if config.password.is_empty() {
|
||||
if let Some(secret) = store.get_secret(&config.id, MAIN_PASSWORD_KEY)? {
|
||||
config.password = secret;
|
||||
}
|
||||
} else {
|
||||
store.set_secret(&config.id, MAIN_PASSWORD_KEY, &config.password)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
|
||||
if config.ssh_password.is_empty() {
|
||||
if let Some(secret) = store.get_secret(&config.id, SSH_PASSWORD_KEY)? {
|
||||
config.ssh_password = secret;
|
||||
}
|
||||
} else {
|
||||
store.set_secret(&config.id, SSH_PASSWORD_KEY, &config.ssh_password)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
|
||||
if config.ssh_key_passphrase.is_empty() {
|
||||
if let Some(secret) = store.get_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)? {
|
||||
config.ssh_key_passphrase = secret;
|
||||
}
|
||||
} else {
|
||||
store.set_secret(&config.id, SSH_KEY_PASSPHRASE_KEY, &config.ssh_key_passphrase)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
|
||||
match config
|
||||
.connection_string
|
||||
.as_deref()
|
||||
.filter(|secret| !secret.is_empty())
|
||||
{
|
||||
Some(secret) => {
|
||||
store.set_secret(&config.id, CONNECTION_STRING_KEY, secret)?;
|
||||
needs_rewrite = true;
|
||||
}
|
||||
None => {
|
||||
if let Some(secret) = store.get_secret(&config.id, CONNECTION_STRING_KEY)? {
|
||||
config.connection_string = Some(secret);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if needs_rewrite {
|
||||
write_sanitized_connections(path, &configs)?;
|
||||
}
|
||||
|
||||
Ok(configs)
|
||||
}
|
||||
|
||||
fn delete_removed_connection_secrets(
|
||||
path: &Path,
|
||||
configs: &[ConnectionConfig],
|
||||
store: &dyn ConnectionSecretStore,
|
||||
) -> Result<(), String> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let previous = match read_connections(path) {
|
||||
Ok(configs) => configs,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
let current_ids: HashSet<&str> = configs.iter().map(|config| config.id.as_str()).collect();
|
||||
for config in previous {
|
||||
if current_ids.contains(config.id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
store.delete_secret(&config.id, MAIN_PASSWORD_KEY)?;
|
||||
store.delete_secret(&config.id, SSH_PASSWORD_KEY)?;
|
||||
store.delete_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)?;
|
||||
store.delete_secret(&config.id, CONNECTION_STRING_KEY)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_secret(
|
||||
store: &dyn ConnectionSecretStore,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
secret: &str,
|
||||
) -> Result<(), String> {
|
||||
if secret.is_empty() {
|
||||
store.delete_secret(connection_id, key)
|
||||
} else {
|
||||
store.set_secret(connection_id, key, secret)
|
||||
}
|
||||
}
|
||||
|
||||
fn persist_optional_secret(
|
||||
store: &dyn ConnectionSecretStore,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
secret: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
match secret.filter(|secret| !secret.is_empty()) {
|
||||
Some(secret) => store.set_secret(connection_id, key, secret),
|
||||
None => store.delete_secret(connection_id, key),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_connections(path: &Path) -> Result<Vec<ConnectionConfig>, String> {
|
||||
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn write_sanitized_connections(path: &Path, configs: &[ConnectionConfig]) -> Result<(), String> {
|
||||
let sanitized = sanitize_connections(configs);
|
||||
let json = serde_json::to_string_pretty(&sanitized).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn sanitize_connections(configs: &[ConnectionConfig]) -> Vec<ConnectionConfig> {
|
||||
configs
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut config| {
|
||||
config.password.clear();
|
||||
config.ssh_password.clear();
|
||||
config.ssh_key_passphrase.clear();
|
||||
config.connection_string = None;
|
||||
config
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn keyring_entry(connection_id: &str, key: &str, action: &str) -> Result<keyring::Entry, String> {
|
||||
keyring::Entry::new(KEYRING_SERVICE, &secret_account(connection_id, key))
|
||||
.map_err(|err| keyring_error(action, connection_id, key, err))
|
||||
}
|
||||
|
||||
fn secret_account(connection_id: &str, key: &str) -> String {
|
||||
format!("connection:{connection_id}:{key}")
|
||||
}
|
||||
|
||||
fn keyring_error(action: &str, connection_id: &str, key: &str, err: keyring::Error) -> String {
|
||||
format!("Failed to {action} saved {key} for connection {connection_id}: {err}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
load_connections_from_file, save_connections_to_file, ConnectionSecretStore,
|
||||
CONNECTION_STRING_KEY, MAIN_PASSWORD_KEY, SSH_PASSWORD_KEY,
|
||||
};
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Default)]
|
||||
struct MemorySecretStore {
|
||||
values: RefCell<HashMap<String, String>>,
|
||||
deleted: RefCell<Vec<String>>,
|
||||
}
|
||||
|
||||
impl MemorySecretStore {
|
||||
fn set_existing(&self, connection_id: &str, key: &str, value: &str) {
|
||||
self.values
|
||||
.borrow_mut()
|
||||
.insert(secret_key(connection_id, key), value.to_string());
|
||||
}
|
||||
|
||||
fn get_existing(&self, connection_id: &str, key: &str) -> Option<String> {
|
||||
self.values
|
||||
.borrow()
|
||||
.get(&secret_key(connection_id, key))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn was_deleted(&self, connection_id: &str, key: &str) -> bool {
|
||||
self.deleted
|
||||
.borrow()
|
||||
.contains(&secret_key(connection_id, key))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionSecretStore for MemorySecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String> {
|
||||
self.values
|
||||
.borrow_mut()
|
||||
.insert(secret_key(connection_id, key), secret.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String> {
|
||||
Ok(self
|
||||
.values
|
||||
.borrow()
|
||||
.get(&secret_key(connection_id, key))
|
||||
.cloned())
|
||||
}
|
||||
|
||||
fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String> {
|
||||
self.values
|
||||
.borrow_mut()
|
||||
.remove(&secret_key(connection_id, key));
|
||||
self.deleted
|
||||
.borrow_mut()
|
||||
.push(secret_key(connection_id, key));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn secret_key(connection_id: &str, key: &str) -> String {
|
||||
format!("{connection_id}:{key}")
|
||||
}
|
||||
|
||||
fn temp_connections_file(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"dbx-connection-secrets-test-{}-{name}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir.join("connections.json")
|
||||
}
|
||||
|
||||
fn connection(id: &str, password: &str, ssh_password: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
id: id.to_string(),
|
||||
name: format!("{id} connection"),
|
||||
db_type: DatabaseType::Postgres,
|
||||
driver_profile: None,
|
||||
driver_label: None,
|
||||
url_params: None,
|
||||
host: "localhost".to_string(),
|
||||
port: 5432,
|
||||
username: "postgres".to_string(),
|
||||
password: password.to_string(),
|
||||
database: Some("postgres".to_string()),
|
||||
color: None,
|
||||
ssh_enabled: !ssh_password.is_empty(),
|
||||
ssh_host: String::new(),
|
||||
ssh_port: 22,
|
||||
ssh_user: String::new(),
|
||||
ssh_password: ssh_password.to_string(),
|
||||
ssh_key_path: String::new(),
|
||||
ssh_key_passphrase: String::new(),
|
||||
ssh_expose_lan: false,
|
||||
ssl: false,
|
||||
connection_string: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_configs(path: &Path) -> Vec<ConnectionConfig> {
|
||||
let json = std::fs::read_to_string(path).unwrap();
|
||||
serde_json::from_str(&json).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_connections_moves_passwords_to_secret_store_and_redacts_file() {
|
||||
let path = temp_connections_file("save-redacts");
|
||||
let store = MemorySecretStore::default();
|
||||
let configs = vec![connection("main", "db-secret", "ssh-secret")];
|
||||
|
||||
save_connections_to_file(&path, &configs, &store).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.get_existing("main", MAIN_PASSWORD_KEY).as_deref(),
|
||||
Some("db-secret")
|
||||
);
|
||||
assert_eq!(
|
||||
store.get_existing("main", SSH_PASSWORD_KEY).as_deref(),
|
||||
Some("ssh-secret")
|
||||
);
|
||||
let persisted = read_configs(&path);
|
||||
assert_eq!(persisted[0].password, "");
|
||||
assert_eq!(persisted[0].ssh_password, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_connections_restores_passwords_from_secret_store() {
|
||||
let path = temp_connections_file("load-restores");
|
||||
let store = MemorySecretStore::default();
|
||||
store.set_existing("main", MAIN_PASSWORD_KEY, "db-secret");
|
||||
store.set_existing("main", SSH_PASSWORD_KEY, "ssh-secret");
|
||||
let sanitized = vec![connection("main", "", "")];
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&sanitized).unwrap()).unwrap();
|
||||
|
||||
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||
|
||||
assert_eq!(loaded[0].password, "db-secret");
|
||||
assert_eq!(loaded[0].ssh_password, "ssh-secret");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_connections_migrates_plaintext_passwords_and_rewrites_sanitized_file() {
|
||||
let path = temp_connections_file("migrates-plaintext");
|
||||
let store = MemorySecretStore::default();
|
||||
let legacy = vec![connection("legacy", "plain-db", "plain-ssh")];
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&legacy).unwrap()).unwrap();
|
||||
|
||||
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||
|
||||
assert_eq!(loaded[0].password, "plain-db");
|
||||
assert_eq!(loaded[0].ssh_password, "plain-ssh");
|
||||
assert_eq!(
|
||||
store.get_existing("legacy", MAIN_PASSWORD_KEY).as_deref(),
|
||||
Some("plain-db")
|
||||
);
|
||||
assert_eq!(
|
||||
store.get_existing("legacy", SSH_PASSWORD_KEY).as_deref(),
|
||||
Some("plain-ssh")
|
||||
);
|
||||
let persisted = read_configs(&path);
|
||||
assert_eq!(persisted[0].password, "");
|
||||
assert_eq!(persisted[0].ssh_password, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_connections_deletes_secrets_for_removed_connections() {
|
||||
let path = temp_connections_file("deletes-removed");
|
||||
let store = MemorySecretStore::default();
|
||||
let previous = vec![connection("old", "", ""), connection("kept", "", "")];
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&previous).unwrap()).unwrap();
|
||||
store.set_existing("old", MAIN_PASSWORD_KEY, "old-db");
|
||||
store.set_existing("old", SSH_PASSWORD_KEY, "old-ssh");
|
||||
store.set_existing("kept", MAIN_PASSWORD_KEY, "kept-db");
|
||||
|
||||
save_connections_to_file(&path, &[connection("kept", "new-db", "")], &store).unwrap();
|
||||
|
||||
assert!(store.was_deleted("old", MAIN_PASSWORD_KEY));
|
||||
assert!(store.was_deleted("old", SSH_PASSWORD_KEY));
|
||||
assert_eq!(
|
||||
store.get_existing("kept", MAIN_PASSWORD_KEY).as_deref(),
|
||||
Some("new-db")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_connections_moves_connection_string_to_secret_store_and_restores_it() {
|
||||
let path = temp_connections_file("connection-string");
|
||||
let store = MemorySecretStore::default();
|
||||
let mut config = connection("mongo", "", "");
|
||||
config.db_type = DatabaseType::MongoDb;
|
||||
config.connection_string = Some("mongodb://user:secret@localhost/app".to_string());
|
||||
|
||||
save_connections_to_file(&path, &[config], &store).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store
|
||||
.get_existing("mongo", CONNECTION_STRING_KEY)
|
||||
.as_deref(),
|
||||
Some("mongodb://user:secret@localhost/app")
|
||||
);
|
||||
let persisted = read_configs(&path);
|
||||
assert_eq!(persisted[0].connection_string, None);
|
||||
|
||||
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||
assert_eq!(
|
||||
loaded[0].connection_string.as_deref(),
|
||||
Some("mongodb://user:secret@localhost/app")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HistoryEntry {
|
||||
pub id: String,
|
||||
pub connection_name: String,
|
||||
pub database: String,
|
||||
pub sql: String,
|
||||
pub executed_at: String,
|
||||
pub execution_time_ms: u128,
|
||||
pub success: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
pub use dbx_core::history::HistoryEntry;
|
||||
|
||||
fn history_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
@@ -19,29 +8,10 @@ fn history_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
Ok(dir.join("query_history.json"))
|
||||
}
|
||||
|
||||
fn read_all(app: &AppHandle) -> Result<Vec<HistoryEntry>, String> {
|
||||
let path = history_file(app)?;
|
||||
if !path.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn write_all(app: &AppHandle, entries: &[HistoryEntry]) -> Result<(), String> {
|
||||
let path = history_file(app)?;
|
||||
let json = serde_json::to_string(entries).map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
const MAX_HISTORY: usize = 1000;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_history(app: AppHandle, entry: HistoryEntry) -> Result<(), String> {
|
||||
let mut entries = read_all(&app)?;
|
||||
entries.insert(0, entry);
|
||||
entries.truncate(MAX_HISTORY);
|
||||
write_all(&app, &entries)
|
||||
let path = history_file(&app)?;
|
||||
dbx_core::history::save_history_entry(&path, entry)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -50,20 +20,18 @@ pub async fn load_history(
|
||||
limit: usize,
|
||||
offset: usize,
|
||||
) -> Result<Vec<HistoryEntry>, String> {
|
||||
let entries = read_all(&app)?;
|
||||
Ok(entries.into_iter().skip(offset).take(limit).collect())
|
||||
let path = history_file(&app)?;
|
||||
dbx_core::history::load_history_entries(&path, limit, offset)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn clear_history(app: AppHandle) -> Result<(), String> {
|
||||
write_all(&app, &[])
|
||||
let path = history_file(&app)?;
|
||||
dbx_core::history::clear_history_entries(&path)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn delete_history_entry(app: AppHandle, id: String) -> Result<(), String> {
|
||||
let entries: Vec<HistoryEntry> = read_all(&app)?
|
||||
.into_iter()
|
||||
.filter(|e| e.id != id)
|
||||
.collect();
|
||||
write_all(&app, &entries)
|
||||
let path = history_file(&app)?;
|
||||
dbx_core::history::delete_history_entry_by_id(&path, &id)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
|
||||
use crate::commands::connection::{AppState, PoolKind};
|
||||
use crate::db::mongo_driver::{self, MongoDocumentResult};
|
||||
use crate::db::elasticsearch_driver;
|
||||
use crate::commands::connection::AppState;
|
||||
use dbx_core::db::mongo_driver::MongoDocumentResult;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mongo_list_databases(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => mongo_driver::list_databases(client).await,
|
||||
PoolKind::Elasticsearch(_) => Ok(vec!["default".to_string()]),
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
dbx_core::mongo_ops::mongo_list_databases_core(&state, &connection_id).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -24,12 +18,7 @@ pub async fn mongo_list_collections(
|
||||
connection_id: String,
|
||||
database: String,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => mongo_driver::list_collections(client, &database).await,
|
||||
PoolKind::Elasticsearch(client) => elasticsearch_driver::list_indices(client).await,
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
dbx_core::mongo_ops::mongo_list_collections_core(&state, &connection_id, &database).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -41,18 +30,7 @@ pub async fn mongo_find_documents(
|
||||
skip: u64,
|
||||
limit: i64,
|
||||
) -> Result<MongoDocumentResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::find_documents(client, &database, &collection, skip, limit).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::find_documents(&client, &collection, skip, limit).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
dbx_core::mongo_ops::mongo_find_documents_core(&state, &connection_id, &database, &collection, skip, limit).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -63,18 +41,7 @@ pub async fn mongo_insert_document(
|
||||
collection: String,
|
||||
doc_json: String,
|
||||
) -> Result<String, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::insert_document(client, &database, &collection, &doc_json).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::insert_document(&client, &collection, &doc_json).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
dbx_core::mongo_ops::mongo_insert_document_core(&state, &connection_id, &database, &collection, &doc_json).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -86,18 +53,7 @@ pub async fn mongo_update_document(
|
||||
id: String,
|
||||
doc_json: String,
|
||||
) -> Result<u64, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::update_document(client, &database, &collection, &id, &doc_json).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::update_document(&client, &collection, &id, &doc_json).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
dbx_core::mongo_ops::mongo_update_document_core(&state, &connection_id, &database, &collection, &id, &doc_json).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -108,16 +64,5 @@ pub async fn mongo_delete_document(
|
||||
collection: String,
|
||||
id: String,
|
||||
) -> Result<u64, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::MongoDb(client) => {
|
||||
mongo_driver::delete_document(client, &database, &collection, &id).await
|
||||
}
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::delete_document(&client, &collection, &id).await
|
||||
}
|
||||
_ => Err("Not a MongoDB/Elasticsearch connection".to_string()),
|
||||
}
|
||||
dbx_core::mongo_ops::mongo_delete_document_core(&state, &connection_id, &database, &collection, &id).await
|
||||
}
|
||||
|
||||
+17
-361
@@ -1,240 +1,12 @@
|
||||
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::commands::sql_file::split_sql_statements;
|
||||
use crate::db;
|
||||
use crate::commands::connection::AppState;
|
||||
use dbx_core::db;
|
||||
use dbx_core::sql::split_sql_statements;
|
||||
|
||||
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();
|
||||
let trimmed = sql.trim().to_uppercase();
|
||||
|
||||
if trimmed.starts_with("SELECT") || trimmed.starts_with("SHOW") || trimmed.starts_with("DESCRIBE")
|
||||
|| trimmed.starts_with("EXPLAIN") || trimmed.starts_with("WITH") || trimmed.starts_with("PRAGMA")
|
||||
{
|
||||
let mut stmt = con.prepare(sql).map_err(|e| e.to_string())?;
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
let stmt_ref = rows.as_ref().ok_or("DuckDB statement unavailable")?;
|
||||
let col_count = stmt_ref.column_count();
|
||||
let columns: Vec<String> = (0..col_count)
|
||||
.map(|i| stmt_ref.column_name(i).map(|s| s.to_string()).unwrap_or_else(|_| "?".to_string()))
|
||||
.collect();
|
||||
|
||||
let mut result_rows = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
if result_rows.len() >= MAX_ROWS { break; }
|
||||
let vals: Vec<serde_json::Value> = (0..col_count).map(|i| {
|
||||
row.get::<_, String>(i)
|
||||
.map(serde_json::Value::String)
|
||||
.or_else(|_| row.get::<_, i64>(i).map(|v| serde_json::Value::Number(v.into())))
|
||||
.or_else(|_| row.get::<_, f64>(i).map(|v| {
|
||||
serde_json::Number::from_f64(v)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}))
|
||||
.or_else(|_| row.get::<_, bool>(i).map(serde_json::Value::Bool))
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}).collect();
|
||||
result_rows.push(vals);
|
||||
}
|
||||
|
||||
let truncated = result_rows.len() >= MAX_ROWS;
|
||||
Ok(db::QueryResult { columns, rows: result_rows, affected_rows: 0, execution_time_ms: start.elapsed().as_millis(), truncated })
|
||||
} else {
|
||||
let affected = con.execute(sql, []).map_err(|e| e.to_string())?;
|
||||
Ok(db::QueryResult { columns: vec![], rows: vec![], affected_rows: affected as u64, execution_time_ms: start.elapsed().as_millis(), truncated: false })
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_result(mut result: db::QueryResult) -> db::QueryResult {
|
||||
if result.rows.len() > MAX_ROWS {
|
||||
result.rows.truncate(MAX_ROWS);
|
||||
result.truncated = true;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn is_connection_error(err: &str) -> bool {
|
||||
let lower = err.to_lowercase();
|
||||
lower.contains("connection")
|
||||
|| lower.contains("broken pipe")
|
||||
|| lower.contains("reset by peer")
|
||||
|| lower.contains("timed out")
|
||||
|| lower.contains("closed")
|
||||
|| 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>>,
|
||||
{
|
||||
wait_for_query_with_timeout(cancel_token, QUERY_TIMEOUT, future).await
|
||||
}
|
||||
|
||||
async fn wait_for_query_with_timeout<F>(
|
||||
cancel_token: Option<CancellationToken>,
|
||||
timeout_duration: Duration,
|
||||
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(timeout_duration, future) => result.map_err(|_| timeout_error())?,
|
||||
}
|
||||
} else {
|
||||
timeout(timeout_duration, 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")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::DuckDb(con) => {
|
||||
let con = con.clone();
|
||||
let sql = sql.to_string();
|
||||
drop(connections);
|
||||
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, bare) => {
|
||||
let p = p.clone();
|
||||
let bare = *bare;
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::mysql::execute_query(&p, sql, bare))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::postgres::execute_query(&p, sql))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::sqlite::execute_query(&p, sql))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::ClickHouse(client) => {
|
||||
let client = client.clone();
|
||||
let database = pool_key.split(':').nth(1).unwrap_or("default").to_string();
|
||||
drop(connections);
|
||||
wait_for_query(cancel_token, db::clickhouse_driver::execute_query(&client, &database, sql))
|
||||
.await
|
||||
.map(truncate_result)
|
||||
}
|
||||
PoolKind::SqlServer(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
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(truncate_result)
|
||||
}
|
||||
PoolKind::Oracle(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
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(truncate_result)
|
||||
}
|
||||
PoolKind::Elasticsearch(_) => Err("Use document browser for Elasticsearch".to_string()),
|
||||
PoolKind::Redis(_) => Err("Use Redis-specific commands".to_string()),
|
||||
PoolKind::MongoDb(_) => Err("Use MongoDB-specific commands".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn execute_sql_statement(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
sql: &str,
|
||||
cancel_token: Option<CancellationToken>,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let pool_key = if database.is_empty() {
|
||||
connection_id.to_string()
|
||||
} else {
|
||||
state.get_or_create_pool(connection_id, Some(database)).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) && !is_canceled(&cancel_token) => {
|
||||
let db_opt = if database.is_empty() { None } else { Some(database) };
|
||||
let new_key = state.reconnect_pool(connection_id, db_opt).await?;
|
||||
do_execute(state, &new_key, sql, cancel_token).await
|
||||
}
|
||||
_ => result,
|
||||
}
|
||||
}
|
||||
// Re-export core functions for use by other modules (e.g., sql_file.rs)
|
||||
pub use dbx_core::query::execute_sql_statement;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn execute_query(
|
||||
@@ -250,16 +22,14 @@ pub async fn execute_query(
|
||||
.map(|id| state.running_queries.register(id.clone()));
|
||||
let cancel_token = registered_query.as_ref().map(|query| query.token());
|
||||
|
||||
let result = execute_sql_statement(
|
||||
dbx_core::query::execute_sql_statement(
|
||||
&state,
|
||||
&connection_id,
|
||||
&database,
|
||||
&sql,
|
||||
cancel_token,
|
||||
)
|
||||
.await;
|
||||
|
||||
result
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -276,44 +46,14 @@ pub async fn execute_multi(
|
||||
.map(|id| state.running_queries.register(id.clone()));
|
||||
let cancel_token = registered_query.as_ref().map(|query| query.token());
|
||||
|
||||
let statements = split_sql_statements(&sql);
|
||||
if statements.len() <= 1 {
|
||||
let single_sql = statements.into_iter().next().unwrap_or_default();
|
||||
let result = execute_sql_statement(
|
||||
&state, &connection_id, &database, &single_sql, cancel_token,
|
||||
).await?;
|
||||
return Ok(vec![result]);
|
||||
}
|
||||
|
||||
let mut results = Vec::with_capacity(statements.len());
|
||||
for stmt in &statements {
|
||||
if is_canceled(&cancel_token) {
|
||||
results.push(db::QueryResult {
|
||||
columns: vec!["Error".to_string()],
|
||||
rows: vec![vec![serde_json::Value::String(canceled_error())]],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
match execute_sql_statement(
|
||||
&state, &connection_id, &database, stmt, cancel_token.clone(),
|
||||
).await {
|
||||
Ok(r) => results.push(r),
|
||||
Err(e) => {
|
||||
results.push(db::QueryResult {
|
||||
columns: vec!["Error".to_string()],
|
||||
rows: vec![vec![serde_json::Value::String(e)]],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
dbx_core::query::execute_multi_core(
|
||||
&state,
|
||||
&connection_id,
|
||||
&database,
|
||||
&sql,
|
||||
cancel_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -324,48 +64,6 @@ pub async fn cancel_query(
|
||||
Ok(state.running_queries.cancel(&execution_id))
|
||||
}
|
||||
|
||||
async fn execute_statements(
|
||||
state: &Arc<AppState>,
|
||||
connection_id: String,
|
||||
database: String,
|
||||
statements: Vec<String>,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let pool_key = if database.is_empty() {
|
||||
connection_id.clone()
|
||||
} else {
|
||||
state.get_or_create_pool(&connection_id, Some(&database)).await?
|
||||
};
|
||||
|
||||
let mut total_affected: u64 = 0;
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
for (i, sql) in statements.iter().enumerate() {
|
||||
match do_execute(&state, &pool_key, sql, None).await {
|
||||
Ok(result) => {
|
||||
total_affected += result.affected_rows;
|
||||
}
|
||||
Err(e) => {
|
||||
if is_connection_error(&e) {
|
||||
let db_opt = if database.is_empty() { None } else { Some(database.as_str()) };
|
||||
let _ = state.reconnect_pool(&connection_id, db_opt).await;
|
||||
}
|
||||
return Err(format!(
|
||||
"Statement {} failed: {}. Previous {} statement(s) may have been committed.",
|
||||
i + 1, e, i
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(db::QueryResult {
|
||||
columns: vec![],
|
||||
rows: vec![],
|
||||
affected_rows: total_affected,
|
||||
execution_time_ms: start.elapsed().as_millis(),
|
||||
truncated: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn execute_batch(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
@@ -373,7 +71,7 @@ pub async fn execute_batch(
|
||||
database: String,
|
||||
statements: Vec<String>,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
execute_statements(&state, connection_id, database, statements).await
|
||||
dbx_core::query::execute_statements(&state, &connection_id, &database, &statements).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -383,47 +81,5 @@ pub async fn execute_script(
|
||||
database: String,
|
||||
sql: String,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
execute_statements(&state, connection_id, database, split_sql_statements(&sql)).await
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wait_for_query_without_token_still_times_out() {
|
||||
let result = wait_for_query_with_timeout(None, Duration::from_millis(10), async {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
Ok(db::QueryResult {
|
||||
columns: vec![],
|
||||
rows: vec![],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(result.unwrap_err(), timeout_error());
|
||||
}
|
||||
dbx_core::query::execute_statements(&state, &connection_id, &database, &split_sql_statements(&sql)).await
|
||||
}
|
||||
|
||||
@@ -1,98 +1,2 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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"));
|
||||
}
|
||||
}
|
||||
#[allow(unused_imports)]
|
||||
pub use dbx_core::query_cancel::*;
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
|
||||
use crate::commands::connection::{AppState, PoolKind};
|
||||
use crate::db::redis_driver::{self, RedisScanResult, RedisValue};
|
||||
use crate::commands::connection::AppState;
|
||||
use dbx_core::db::redis_driver::{RedisScanResult, RedisValue};
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn redis_list_databases(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String,
|
||||
) -> Result<Vec<u32>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::list_databases(&mut con).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_list_databases_core(&state, &connection_id).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -29,16 +21,7 @@ pub async fn redis_scan_keys(
|
||||
pattern: String,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::scan_keys_page(&mut con, cursor, &pattern, count).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_scan_keys_core(&state, &connection_id, db, cursor, &pattern, count).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -47,15 +30,7 @@ pub async fn redis_get_value(
|
||||
connection_id: String,
|
||||
key: String,
|
||||
) -> Result<RedisValue, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::get_value(&mut con, &key).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_get_value_core(&state, &connection_id, &key).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -66,15 +41,7 @@ pub async fn redis_set_string(
|
||||
value: String,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::set_string(&mut con, &key, &value, ttl).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_set_string_core(&state, &connection_id, &key, &value, ttl).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -83,15 +50,7 @@ pub async fn redis_delete_key(
|
||||
connection_id: String,
|
||||
key: String,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::delete_key(&mut con, &key).await
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_delete_key_core(&state, &connection_id, &key).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -99,11 +58,7 @@ pub async fn redis_hash_set(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String, key: String, field: String, value: String,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::hash_set(&mut *con.lock().await, &key, &field, &value).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_hash_set_core(&state, &connection_id, &key, &field, &value).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -111,11 +66,7 @@ pub async fn redis_hash_del(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String, key: String, field: String,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::hash_del(&mut *con.lock().await, &key, &field).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_hash_del_core(&state, &connection_id, &key, &field).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -123,11 +74,7 @@ pub async fn redis_list_push(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String, key: String, value: String,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::list_push(&mut *con.lock().await, &key, &value).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_list_push_core(&state, &connection_id, &key, &value).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -135,11 +82,7 @@ pub async fn redis_list_remove(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String, key: String, index: i64,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::list_remove(&mut *con.lock().await, &key, index).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_list_remove_core(&state, &connection_id, &key, index).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -147,11 +90,7 @@ pub async fn redis_set_add(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String, key: String, member: String,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::set_add(&mut *con.lock().await, &key, &member).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_set_add_core(&state, &connection_id, &key, &member).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -159,9 +98,5 @@ pub async fn redis_set_remove(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String, key: String, member: String,
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.lock().await;
|
||||
match connections.get(&connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => redis_driver::set_remove(&mut *con.lock().await, &key, &member).await,
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
dbx_core::redis_ops::redis_set_remove_core(&state, &connection_id, &key, &member).await
|
||||
}
|
||||
|
||||
@@ -1,123 +1,15 @@
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
|
||||
use crate::commands::connection::{AppState, PoolKind};
|
||||
use crate::db;
|
||||
|
||||
fn duckdb_query_tables(con: &duckdb::Connection) -> Result<Vec<db::TableInfo>, String> {
|
||||
let mut stmt = con.prepare(
|
||||
"SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'main' ORDER BY table_name"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok(db::TableInfo {
|
||||
name: row.get::<_, String>(0)?,
|
||||
table_type: row.get::<_, String>(1)?,
|
||||
})
|
||||
}).map_err(|e| e.to_string())?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
fn duckdb_query_columns(con: &duckdb::Connection, table: &str) -> Result<Vec<db::ColumnInfo>, String> {
|
||||
let mut pk_stmt = con.prepare(
|
||||
"SELECT kcu.column_name
|
||||
FROM information_schema.table_constraints tc
|
||||
JOIN information_schema.key_column_usage kcu
|
||||
ON tc.constraint_name = kcu.constraint_name
|
||||
AND tc.table_schema = kcu.table_schema
|
||||
AND tc.table_name = kcu.table_name
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY'
|
||||
AND tc.table_schema = 'main'
|
||||
AND tc.table_name = ?
|
||||
ORDER BY kcu.ordinal_position"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let pk_rows = pk_stmt.query_map([table], |row| row.get::<_, String>(0))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let primary_keys: std::collections::HashSet<String> = pk_rows.filter_map(|r| r.ok()).collect();
|
||||
|
||||
let mut stmt = con.prepare(
|
||||
"SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'main' AND table_name = ?
|
||||
ORDER BY ordinal_position"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let rows = stmt.query_map([table], |row| {
|
||||
let name = row.get::<_, String>(0)?;
|
||||
Ok(db::ColumnInfo {
|
||||
is_primary_key: primary_keys.contains(&name),
|
||||
name,
|
||||
data_type: row.get::<_, String>(1)?,
|
||||
is_nullable: row.get::<_, String>(2).unwrap_or_default() == "YES",
|
||||
column_default: row.get::<_, Option<String>>(3)?,
|
||||
extra: None, comment: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
character_maximum_length: None,
|
||||
})
|
||||
}).map_err(|e| e.to_string())?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
fn extract_duckdb(connections: &std::collections::HashMap<String, PoolKind>, key: &str) -> Option<std::sync::Arc<std::sync::Mutex<duckdb::Connection>>> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::DuckDb(con) => Some(con.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_sqlserver(connections: &std::collections::HashMap<String, PoolKind>, key: &str) -> Option<std::sync::Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::SqlServer(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_clickhouse(connections: &std::collections::HashMap<String, PoolKind>, key: &str) -> Option<db::clickhouse_driver::ChClient> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::ClickHouse(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_oracle(connections: &std::collections::HashMap<String, PoolKind>, key: &str) -> Option<std::sync::Arc<tokio::sync::Mutex<db::oracle_driver::OracleClient>>> {
|
||||
match connections.get(key)? {
|
||||
PoolKind::Oracle(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
use crate::commands::connection::AppState;
|
||||
use dbx_core::db;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_databases(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String,
|
||||
) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_clickhouse(&connections, &connection_id) {
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::list_databases(&client).await;
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &connection_id) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_databases(&mut client).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &connection_id) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_databases(&*client).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&connection_id).ok_or("Connection not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_databases(p).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_databases(p).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_databases(p).await,
|
||||
PoolKind::DuckDb(_) => Ok(vec![db::DatabaseInfo { name: "main".to_string() }]),
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::list_databases_core(&state, &connection_id).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -126,29 +18,7 @@ pub async fn list_schemas(
|
||||
connection_id: String,
|
||||
database: String,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_schemas(&mut client).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_schemas(&*client).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Postgres(p) => db::postgres::list_schemas(p).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::list_schemas_core(&state, &connection_id, &database).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -158,40 +28,7 @@ pub async fn list_tables(
|
||||
database: String,
|
||||
schema: String,
|
||||
) -> Result<Vec<db::TableInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(con) = extract_duckdb(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
return duckdb_query_tables(&con);
|
||||
}
|
||||
if let Some(client) = extract_clickhouse(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::list_tables(&client, &database).await;
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_tables(&mut client, &schema).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_tables(&*client, &schema).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_tables(p, &schema).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_tables(p, &schema).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_tables(p, &schema).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::list_tables_core(&state, &connection_id, &database, &schema).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -202,40 +39,7 @@ pub async fn get_columns(
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> Result<Vec<db::ColumnInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(con) = extract_duckdb(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
return duckdb_query_columns(&con, &table);
|
||||
}
|
||||
if let Some(client) = extract_clickhouse(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::get_columns(&client, &database, &table).await;
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::get_columns(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::get_columns(&*client, &schema, &table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::get_columns(p, &schema, &table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::get_columns(p, &schema, &table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::get_columns(p, &schema, &table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::get_columns_core(&state, &connection_id, &database, &schema, &table).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -246,31 +50,7 @@ pub async fn list_indexes(
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> Result<Vec<db::IndexInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_indexes(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_indexes(&*client, &schema, &table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_indexes(p, &schema, &table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_indexes(p, &schema, &table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_indexes(p, &schema, &table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::list_indexes_core(&state, &connection_id, &database, &schema, &table).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -281,31 +61,7 @@ pub async fn list_foreign_keys(
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> Result<Vec<db::ForeignKeyInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_foreign_keys(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_foreign_keys(&*client, &schema, &table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_foreign_keys(p, &schema, &table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_foreign_keys(p, &schema, &table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_foreign_keys(p, &schema, &table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::list_foreign_keys_core(&state, &connection_id, &database, &schema, &table).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -316,31 +72,7 @@ pub async fn list_triggers(
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> Result<Vec<db::TriggerInfo>, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_triggers(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::list_triggers(&*client, &schema, &table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => db::mysql::list_triggers(p, &schema, &table).await,
|
||||
PoolKind::Postgres(p) => db::postgres::list_triggers(p, &schema, &table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_triggers(p, &schema, &table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
dbx_core::schema::list_triggers_core(&state, &connection_id, &database, &schema, &table).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -351,173 +83,5 @@ pub async fn get_table_ddl(
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> Result<String, String> {
|
||||
let pool_key = state.get_or_create_pool(&connection_id, Some(&database)).await?;
|
||||
|
||||
{
|
||||
let connections = state.connections.lock().await;
|
||||
if let Some(con) = extract_duckdb(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let tbl = table.replace('\'', "''");
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
let mut stmt = con.prepare(&format!("SELECT sql FROM duckdb_tables() WHERE table_name = '{tbl}'"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
if let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
return row.get::<_, String>(0).map_err(|e| e.to_string());
|
||||
}
|
||||
return Err("Table not found".to_string());
|
||||
}
|
||||
if let Some(client) = extract_clickhouse(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let result = db::clickhouse_driver::execute_query(&client, &database, &format!("SHOW CREATE TABLE `{table}`")).await?;
|
||||
return result.rows.first()
|
||||
.and_then(|r| r.first())
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.ok_or_else(|| "Table not found".to_string());
|
||||
}
|
||||
if let Some(client) = extract_sqlserver(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return build_sqlserver_ddl(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(client) = extract_oracle(&connections, &pool_key) {
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return build_oracle_ddl(&*client, &schema, &table).await;
|
||||
}
|
||||
}
|
||||
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => mysql_ddl(p, &table).await,
|
||||
PoolKind::Postgres(p) => pg_ddl(p, &schema, &table).await,
|
||||
PoolKind::Sqlite(p) => sqlite_ddl(p, &table).await,
|
||||
_ => Err("DDL not supported for this database type".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn mysql_ddl(pool: &sqlx::mysql::MySqlPool, table: &str) -> Result<String, String> {
|
||||
use sqlx::Row;
|
||||
let sql = format!("SHOW CREATE TABLE `{}`", table.replace('`', "``"));
|
||||
let row: sqlx::mysql::MySqlRow = sqlx::raw_sql(&sql)
|
||||
.fetch_one(pool).await.map_err(|e| e.to_string())?;
|
||||
row.try_get::<String, _>(1)
|
||||
.or_else(|_| row.try_get::<Vec<u8>, _>(1).map(|b| String::from_utf8_lossy(&b).to_string()))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
async fn sqlite_ddl(pool: &sqlx::sqlite::SqlitePool, table: &str) -> Result<String, String> {
|
||||
use sqlx::Row;
|
||||
let row: sqlx::sqlite::SqliteRow = sqlx::query("SELECT sql FROM sqlite_master WHERE type='table' AND name=?")
|
||||
.bind(table)
|
||||
.fetch_one(pool).await.map_err(|e| e.to_string())?;
|
||||
row.try_get::<String, _>(0).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
async fn pg_ddl(pool: &sqlx::postgres::PgPool, schema: &str, table: &str) -> Result<String, String> {
|
||||
let columns = db::postgres::get_columns(pool, schema, table).await?;
|
||||
let indexes = db::postgres::list_indexes(pool, schema, table).await?;
|
||||
let fkeys = db::postgres::list_foreign_keys(pool, schema, table).await?;
|
||||
|
||||
let mut ddl = format!("CREATE TABLE \"{schema}\".\"{table}\" (\n");
|
||||
let col_lines: Vec<String> = columns.iter().map(|c| {
|
||||
let mut line = format!(" \"{}\" {}", c.name, c.data_type);
|
||||
if !c.is_nullable { line.push_str(" NOT NULL"); }
|
||||
if let Some(ref def) = c.column_default { line.push_str(&format!(" DEFAULT {def}")); }
|
||||
line
|
||||
}).collect();
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
let pks: Vec<&str> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.iter().map(|k| format!("\"{k}\"")).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
for fk in &fkeys {
|
||||
ddl.push_str(&format!(",\n CONSTRAINT \"{}\" FOREIGN KEY (\"{}\") REFERENCES \"{}\"(\"{}\")", fk.name, fk.column, fk.ref_table, fk.ref_column));
|
||||
}
|
||||
ddl.push_str("\n);\n");
|
||||
|
||||
for idx in &indexes {
|
||||
if idx.is_primary { continue; }
|
||||
let unique = if idx.is_unique { "UNIQUE " } else { "" };
|
||||
let cols = idx.columns.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
|
||||
let using = idx.index_type.as_deref().map(|t| format!(" USING {t}")).unwrap_or_default();
|
||||
let include = idx.included_columns.as_deref().filter(|c| !c.is_empty()).map(|cols| format!(" INCLUDE ({})", cols.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", "))).unwrap_or_default();
|
||||
let filter = idx.filter.as_deref().map(|f| format!(" WHERE {f}")).unwrap_or_default();
|
||||
ddl.push_str(&format!("\nCREATE {unique}INDEX \"{}\" ON \"{schema}\".\"{table}\"{using} ({cols}){include}{filter};", idx.name));
|
||||
if let Some(ref c) = idx.comment {
|
||||
ddl.push_str(&format!("\nCOMMENT ON INDEX \"{schema}\".\"{}\" IS '{}';", idx.name, c.replace('\'', "''")));
|
||||
}
|
||||
}
|
||||
Ok(ddl)
|
||||
}
|
||||
|
||||
async fn build_sqlserver_ddl(client: &mut db::sqlserver::SqlServerClient, schema: &str, table: &str) -> Result<String, String> {
|
||||
let columns = db::sqlserver::get_columns(client, schema, table).await?;
|
||||
let indexes = db::sqlserver::list_indexes(client, schema, table).await?;
|
||||
let fkeys = db::sqlserver::list_foreign_keys(client, schema, table).await?;
|
||||
|
||||
let mut ddl = format!("CREATE TABLE [{schema}].[{table}] (\n");
|
||||
let col_lines: Vec<String> = columns.iter().map(|c| {
|
||||
let mut line = format!(" [{}] {}", c.name, c.data_type);
|
||||
if !c.is_nullable { line.push_str(" NOT NULL"); }
|
||||
if let Some(ref def) = c.column_default { line.push_str(&format!(" DEFAULT {def}")); }
|
||||
line
|
||||
}).collect();
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
let pks: Vec<&str> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.iter().map(|k| format!("[{k}]")).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
for fk in &fkeys {
|
||||
ddl.push_str(&format!(",\n CONSTRAINT [{}] FOREIGN KEY ([{}]) REFERENCES [{}]([{}])", fk.name, fk.column, fk.ref_table, fk.ref_column));
|
||||
}
|
||||
ddl.push_str("\n);\n");
|
||||
|
||||
for idx in &indexes {
|
||||
if idx.is_primary { continue; }
|
||||
let unique = if idx.is_unique { "UNIQUE " } else { "" };
|
||||
let idx_type = idx.index_type.as_deref().map(|t| format!("{t} ")).unwrap_or_default();
|
||||
let cols = idx.columns.iter().map(|c| format!("[{c}]")).collect::<Vec<_>>().join(", ");
|
||||
let include = idx.included_columns.as_deref().filter(|c| !c.is_empty()).map(|cols| format!(" INCLUDE ({})", cols.iter().map(|c| format!("[{c}]")).collect::<Vec<_>>().join(", "))).unwrap_or_default();
|
||||
let filter = idx.filter.as_deref().map(|f| format!(" WHERE {f}")).unwrap_or_default();
|
||||
ddl.push_str(&format!("\nCREATE {unique}{idx_type}INDEX [{}] ON [{schema}].[{table}] ({cols}){include}{filter};", idx.name));
|
||||
}
|
||||
Ok(ddl)
|
||||
}
|
||||
|
||||
async fn build_oracle_ddl(client: &db::oracle_driver::OracleClient, schema: &str, table: &str) -> Result<String, String> {
|
||||
let columns = db::oracle_driver::get_columns(client, schema, table).await?;
|
||||
let indexes = db::oracle_driver::list_indexes(client, schema, table).await?;
|
||||
let fkeys = db::oracle_driver::list_foreign_keys(client, schema, table).await?;
|
||||
|
||||
let mut ddl = format!("CREATE TABLE \"{schema}\".\"{table}\" (\n");
|
||||
let col_lines: Vec<String> = columns.iter().map(|c| {
|
||||
let mut line = format!(" \"{}\" {}", c.name, c.data_type);
|
||||
if !c.is_nullable { line.push_str(" NOT NULL"); }
|
||||
if let Some(ref def) = c.column_default { line.push_str(&format!(" DEFAULT {def}")); }
|
||||
line
|
||||
}).collect();
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
let pks: Vec<&str> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.iter().map(|k| format!("\"{k}\"")).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
for fk in &fkeys {
|
||||
ddl.push_str(&format!(",\n CONSTRAINT \"{}\" FOREIGN KEY (\"{}\") REFERENCES \"{}\"(\"{}\")", fk.name, fk.column, fk.ref_table, fk.ref_column));
|
||||
}
|
||||
ddl.push_str("\n);\n");
|
||||
|
||||
for idx in &indexes {
|
||||
if idx.is_primary { continue; }
|
||||
let unique = if idx.is_unique { "UNIQUE " } else { "" };
|
||||
let cols = idx.columns.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
|
||||
ddl.push_str(&format!("\nCREATE {unique}INDEX \"{}\" ON \"{schema}\".\"{table}\" ({cols});", idx.name));
|
||||
}
|
||||
Ok(ddl)
|
||||
dbx_core::schema::get_table_ddl_core(&state, &connection_id, &database, &schema, &table).await
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::sync::RwLock;
|
||||
@@ -12,6 +11,11 @@ use tokio_util::sync::CancellationToken;
|
||||
use crate::commands::connection::AppState;
|
||||
use crate::commands::query::execute_sql_statement;
|
||||
|
||||
pub use dbx_core::sql::{
|
||||
statement_summary, SqlFilePreview, SqlFileProgress, SqlFileRequest,
|
||||
SqlFileStatus, SqlStatementSplitter,
|
||||
};
|
||||
|
||||
static SQL_FILE_EXECUTIONS: std::sync::LazyLock<RwLock<HashMap<String, CancellationToken>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
@@ -22,51 +26,6 @@ struct StatementErrorDecision {
|
||||
result: Result<bool, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SqlFileRequest {
|
||||
pub execution_id: String,
|
||||
pub connection_id: String,
|
||||
pub database: String,
|
||||
pub file_path: String,
|
||||
pub continue_on_error: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SqlFilePreview {
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub size_bytes: u64,
|
||||
pub preview: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SqlFileStatus {
|
||||
Started,
|
||||
Running,
|
||||
StatementDone,
|
||||
StatementFailed,
|
||||
Done,
|
||||
Error,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SqlFileProgress {
|
||||
pub execution_id: String,
|
||||
pub status: SqlFileStatus,
|
||||
pub statement_index: usize,
|
||||
pub success_count: usize,
|
||||
pub failure_count: usize,
|
||||
pub affected_rows: u64,
|
||||
pub elapsed_ms: u128,
|
||||
pub statement_summary: String,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct SqlFileSummary {
|
||||
@@ -76,255 +35,6 @@ struct SqlFileSummary {
|
||||
failed_statement_index: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SqlStatementSplitter {
|
||||
buffer: String,
|
||||
in_single_quote: bool,
|
||||
in_double_quote: bool,
|
||||
in_backtick: bool,
|
||||
in_line_comment: bool,
|
||||
in_block_comment: bool,
|
||||
dollar_quote_tag: Option<String>,
|
||||
previous: Option<char>,
|
||||
}
|
||||
|
||||
impl SqlStatementSplitter {
|
||||
fn push_chunk(&mut self, chunk: &str) -> Vec<String> {
|
||||
let mut statements = Vec::new();
|
||||
let chars = chunk.chars().collect::<Vec<_>>();
|
||||
let mut i = 0;
|
||||
|
||||
while i < chars.len() {
|
||||
if let Some(tag) = &self.dollar_quote_tag {
|
||||
let tag_chars = tag.chars().collect::<Vec<_>>();
|
||||
if starts_with_chars(&chars, i, &tag_chars) {
|
||||
for tag_ch in &tag_chars {
|
||||
self.buffer.push(*tag_ch);
|
||||
self.previous = Some(*tag_ch);
|
||||
}
|
||||
i += tag_chars.len();
|
||||
self.dollar_quote_tag = None;
|
||||
continue;
|
||||
}
|
||||
|
||||
let ch = chars[i];
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let ch = chars[i];
|
||||
let next = chars.get(i + 1).copied();
|
||||
|
||||
if self.in_line_comment {
|
||||
self.buffer.push(ch);
|
||||
if ch == '\n' {
|
||||
self.in_line_comment = false;
|
||||
}
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.in_block_comment {
|
||||
self.buffer.push(ch);
|
||||
if self.previous == Some('*') && ch == '/' {
|
||||
self.in_block_comment = false;
|
||||
}
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if !self.in_single_quote && !self.in_double_quote && !self.in_backtick {
|
||||
if self.previous == Some('-') && ch == '-' {
|
||||
self.in_line_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if self.previous == Some('/') && ch == '*' {
|
||||
self.in_block_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if ch == '-' && next == Some('-') {
|
||||
self.in_line_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if ch == '/' && next == Some('*') {
|
||||
self.in_block_comment = true;
|
||||
self.buffer.push(ch);
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(tag) = dollar_quote_tag_at(&chars, i) {
|
||||
for tag_ch in tag.chars() {
|
||||
self.buffer.push(tag_ch);
|
||||
self.previous = Some(tag_ch);
|
||||
}
|
||||
i += tag.chars().count();
|
||||
self.dollar_quote_tag = Some(tag);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
match ch {
|
||||
'\'' if !self.in_double_quote
|
||||
&& !self.in_backtick
|
||||
&& self.previous != Some('\\') =>
|
||||
{
|
||||
self.in_single_quote = !self.in_single_quote;
|
||||
self.buffer.push(ch);
|
||||
}
|
||||
'"' if !self.in_single_quote
|
||||
&& !self.in_backtick
|
||||
&& self.previous != Some('\\') =>
|
||||
{
|
||||
self.in_double_quote = !self.in_double_quote;
|
||||
self.buffer.push(ch);
|
||||
}
|
||||
'`' if !self.in_single_quote && !self.in_double_quote => {
|
||||
self.in_backtick = !self.in_backtick;
|
||||
self.buffer.push(ch);
|
||||
}
|
||||
';' if !self.in_single_quote && !self.in_double_quote && !self.in_backtick => {
|
||||
self.push_current_statement(&mut statements);
|
||||
}
|
||||
_ => self.buffer.push(ch),
|
||||
}
|
||||
|
||||
self.previous = Some(ch);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
statements
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<String> {
|
||||
let mut statements = Vec::new();
|
||||
self.push_current_statement(&mut statements);
|
||||
statements
|
||||
}
|
||||
|
||||
fn push_current_statement(&mut self, statements: &mut Vec<String>) {
|
||||
let statement = self.buffer.trim();
|
||||
if has_executable_sql(statement) {
|
||||
statements.push(statement.to_string());
|
||||
}
|
||||
self.buffer.clear();
|
||||
self.previous = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn split_sql_statements(sql: &str) -> Vec<String> {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
let mut statements = splitter.push_chunk(sql);
|
||||
statements.extend(splitter.finish());
|
||||
statements
|
||||
}
|
||||
|
||||
fn starts_with_chars(chars: &[char], start: usize, needle: &[char]) -> bool {
|
||||
start + needle.len() <= chars.len() && chars[start..start + needle.len()] == *needle
|
||||
}
|
||||
|
||||
fn dollar_quote_tag_at(chars: &[char], start: usize) -> Option<String> {
|
||||
if chars.get(start) != Some(&'$') {
|
||||
return None;
|
||||
}
|
||||
|
||||
match chars.get(start + 1) {
|
||||
Some('$') => return Some("$$".to_string()),
|
||||
Some(ch) if ch.is_ascii_alphabetic() || *ch == '_' => {}
|
||||
_ => return None,
|
||||
}
|
||||
|
||||
let mut end = start + 2;
|
||||
while let Some(ch) = chars.get(end) {
|
||||
if *ch == '$' {
|
||||
return Some(chars[start..=end].iter().collect());
|
||||
}
|
||||
if !ch.is_ascii_alphanumeric() && *ch != '_' {
|
||||
return None;
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn has_executable_sql(statement: &str) -> bool {
|
||||
let chars = statement.chars().collect::<Vec<_>>();
|
||||
let mut in_line_comment = false;
|
||||
let mut in_block_comment = false;
|
||||
let mut previous = None;
|
||||
let mut i = 0;
|
||||
|
||||
while i < chars.len() {
|
||||
let ch = chars[i];
|
||||
let next = chars.get(i + 1).copied();
|
||||
|
||||
if in_line_comment {
|
||||
if ch == '\n' {
|
||||
in_line_comment = false;
|
||||
}
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_block_comment {
|
||||
if previous == Some('*') && ch == '/' {
|
||||
in_block_comment = false;
|
||||
}
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '-' && next == Some('-') {
|
||||
in_line_comment = true;
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '/' && next == Some('*') {
|
||||
if is_mysql_executable_comment_start(&chars, i) {
|
||||
return true;
|
||||
}
|
||||
in_block_comment = true;
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if !ch.is_whitespace() {
|
||||
return true;
|
||||
}
|
||||
|
||||
previous = Some(ch);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn is_mysql_executable_comment_start(chars: &[char], start: usize) -> bool {
|
||||
chars.get(start) == Some(&'/')
|
||||
&& chars.get(start + 1) == Some(&'*')
|
||||
&& (chars.get(start + 2) == Some(&'!')
|
||||
|| (chars.get(start + 2) == Some(&'M') && chars.get(start + 3) == Some(&'!')))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn preview_sql_file(file_path: String) -> Result<SqlFilePreview, String> {
|
||||
let path = PathBuf::from(&file_path);
|
||||
@@ -808,17 +518,6 @@ fn sql_file_progress(
|
||||
}
|
||||
}
|
||||
|
||||
fn statement_summary(statement: &str) -> String {
|
||||
const MAX_LEN: usize = 120;
|
||||
|
||||
let collapsed = statement.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if collapsed.chars().count() <= MAX_LEN {
|
||||
return collapsed;
|
||||
}
|
||||
|
||||
collapsed.chars().take(MAX_LEN).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn run_statements_for_test(
|
||||
statements: Vec<String>,
|
||||
@@ -871,118 +570,6 @@ async fn run_statements_for_test(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn split_sql_script(sql: &str) -> Result<Vec<String>, String> {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
let mut statements = splitter.push_chunk(sql);
|
||||
statements.extend(splitter.finish());
|
||||
Ok(statements)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{split_sql_script, SqlStatementSplitter};
|
||||
|
||||
#[test]
|
||||
fn splits_semicolon_delimited_statements() {
|
||||
assert_eq!(
|
||||
split_sql_script("CREATE TABLE a(id int); INSERT INTO a VALUES (1);").unwrap(),
|
||||
vec!["CREATE TABLE a(id int)", "INSERT INTO a VALUES (1)"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_semicolons_inside_quotes_and_comments() {
|
||||
let sql = "\
|
||||
INSERT INTO logs VALUES ('a;b', \"c;d\", `weird;name`);\n\
|
||||
-- comment ; ignored\n\
|
||||
/* block ; ignored */\n\
|
||||
SELECT 1;";
|
||||
assert_eq!(
|
||||
split_sql_script(sql).unwrap(),
|
||||
vec![
|
||||
"INSERT INTO logs VALUES ('a;b', \"c;d\", `weird;name`)",
|
||||
"-- comment ; ignored\n/* block ; ignored */\nSELECT 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_trailing_statement_without_semicolon() {
|
||||
assert_eq!(
|
||||
split_sql_script("CREATE TABLE a(id int);\nINSERT INTO a VALUES (1)").unwrap(),
|
||||
vec!["CREATE TABLE a(id int)", "INSERT INTO a VALUES (1)"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_comment_openers_can_span_chunks() {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
|
||||
assert_eq!(splitter.push_chunk("SELECT 1; -"), vec!["SELECT 1"]);
|
||||
assert_eq!(
|
||||
splitter.push_chunk("- comment ; ignored\nSELECT 2;"),
|
||||
vec!["-- comment ; ignored\nSELECT 2"]
|
||||
);
|
||||
assert_eq!(splitter.finish(), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_comment_openers_can_span_chunks() {
|
||||
let mut splitter = SqlStatementSplitter::default();
|
||||
|
||||
assert_eq!(splitter.push_chunk("SELECT 1; /"), vec!["SELECT 1"]);
|
||||
assert_eq!(
|
||||
splitter.push_chunk("* comment ; ignored */\nSELECT 2;"),
|
||||
vec!["/* comment ; ignored */\nSELECT 2"]
|
||||
);
|
||||
assert_eq!(splitter.finish(), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_comment_only_tail_after_statement() {
|
||||
assert_eq!(
|
||||
split_sql_script("CREATE TABLE a(id int); -- done\n/* no more sql */").unwrap(),
|
||||
vec!["CREATE TABLE a(id int)"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_postgres_dollar_quoted_function_body_together() {
|
||||
let sql = "\
|
||||
CREATE FUNCTION bump_counter()\n\
|
||||
RETURNS trigger AS $$\n\
|
||||
BEGIN\n\
|
||||
PERFORM 1;\n\
|
||||
RETURN NEW;\n\
|
||||
END;\n\
|
||||
$$ LANGUAGE plpgsql;\n\
|
||||
SELECT 1;";
|
||||
|
||||
assert_eq!(
|
||||
split_sql_script(sql).unwrap(),
|
||||
vec![
|
||||
"CREATE FUNCTION bump_counter()\nRETURNS trigger AS $$\nBEGIN\nPERFORM 1;\nRETURN NEW;\nEND;\n$$ LANGUAGE plpgsql",
|
||||
"SELECT 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_mysql_executable_comments_as_statements() {
|
||||
assert_eq!(
|
||||
split_sql_script(
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\nSELECT 1;",
|
||||
)
|
||||
.unwrap(),
|
||||
vec![
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */",
|
||||
"SELECT 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod execution_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,455 +1,21 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use calamine::{open_workbook_auto, Data, Reader};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::commands::connection::AppState;
|
||||
use crate::commands::transfer::{execute_on_pool, generate_insert, get_db_type, qualified_table};
|
||||
use crate::models::connection::DatabaseType;
|
||||
use crate::commands::transfer::get_db_type;
|
||||
|
||||
const DEFAULT_PREVIEW_LIMIT: usize = 50;
|
||||
const DEFAULT_BATCH_SIZE: usize = 500;
|
||||
// Re-export types for backward compatibility
|
||||
pub use dbx_core::table_import::{
|
||||
TableImportPreview, TableImportProgress,
|
||||
TableImportRequest, TableImportSummary,
|
||||
};
|
||||
|
||||
static CANCELLED_IMPORTS: std::sync::LazyLock<RwLock<HashSet<String>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashSet::new()));
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ParsedImportFile {
|
||||
columns: Vec<String>,
|
||||
rows: Vec<Vec<serde_json::Value>>,
|
||||
total_rows: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct ImportSqlBatch {
|
||||
sql: String,
|
||||
row_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportColumnMapping {
|
||||
pub source_column: String,
|
||||
pub target_column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TableImportMode {
|
||||
Append,
|
||||
Truncate,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportRequest {
|
||||
pub import_id: String,
|
||||
pub connection_id: String,
|
||||
pub database: String,
|
||||
pub schema: String,
|
||||
pub table: String,
|
||||
pub file_path: String,
|
||||
pub mappings: Vec<TableImportColumnMapping>,
|
||||
pub mode: TableImportMode,
|
||||
pub batch_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportPreview {
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub file_type: String,
|
||||
pub size_bytes: u64,
|
||||
pub columns: Vec<String>,
|
||||
pub rows: Vec<Vec<serde_json::Value>>,
|
||||
pub total_rows: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportSummary {
|
||||
pub import_id: String,
|
||||
pub rows_imported: usize,
|
||||
pub total_rows: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableImportProgress {
|
||||
pub import_id: String,
|
||||
pub status: TableImportStatus,
|
||||
pub rows_imported: usize,
|
||||
pub total_rows: usize,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TableImportStatus {
|
||||
Running,
|
||||
Done,
|
||||
Error,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum ImportFileKind {
|
||||
Csv,
|
||||
Tsv,
|
||||
Json,
|
||||
Xlsx,
|
||||
}
|
||||
|
||||
impl ImportFileKind {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
ImportFileKind::Csv => "csv",
|
||||
ImportFileKind::Tsv => "tsv",
|
||||
ImportFileKind::Json => "json",
|
||||
ImportFileKind::Xlsx => "xlsx",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn import_file_kind(path: &str) -> Result<ImportFileKind, String> {
|
||||
let lower = path.to_lowercase();
|
||||
if lower.ends_with(".csv") {
|
||||
Ok(ImportFileKind::Csv)
|
||||
} else if lower.ends_with(".tsv") {
|
||||
Ok(ImportFileKind::Tsv)
|
||||
} else if lower.ends_with(".json") {
|
||||
Ok(ImportFileKind::Json)
|
||||
} else if lower.ends_with(".xlsx") || lower.ends_with(".xlsm") || lower.ends_with(".xls") {
|
||||
Ok(ImportFileKind::Xlsx)
|
||||
} else {
|
||||
Err("Unsupported import file type".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_header(value: &str, index: usize) -> String {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
format!("column_{}", index + 1)
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn csv_value(value: &str) -> serde_json::Value {
|
||||
if value.is_empty() {
|
||||
serde_json::Value::Null
|
||||
} else {
|
||||
serde_json::Value::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_delimited_bytes(
|
||||
bytes: &[u8],
|
||||
delimiter: u8,
|
||||
preview_limit: usize,
|
||||
) -> Result<ParsedImportFile, String> {
|
||||
let mut reader = csv::ReaderBuilder::new()
|
||||
.delimiter(delimiter)
|
||||
.flexible(true)
|
||||
.from_reader(bytes);
|
||||
let columns = reader
|
||||
.headers()
|
||||
.map_err(|e| e.to_string())?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, header)| normalize_header(header, index))
|
||||
.collect::<Vec<_>>();
|
||||
if columns.is_empty() {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let mut total_rows = 0;
|
||||
for record in reader.records() {
|
||||
let record = record.map_err(|e| e.to_string())?;
|
||||
total_rows += 1;
|
||||
if rows.len() >= preview_limit {
|
||||
continue;
|
||||
}
|
||||
let mut row = Vec::with_capacity(columns.len());
|
||||
for index in 0..columns.len() {
|
||||
row.push(
|
||||
record
|
||||
.get(index)
|
||||
.map(csv_value)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_csv_bytes(bytes: &[u8], preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
parse_delimited_bytes(bytes, b',', preview_limit)
|
||||
}
|
||||
|
||||
fn parse_json_bytes(bytes: &[u8], preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
|
||||
let items = match value {
|
||||
serde_json::Value::Array(items) => items,
|
||||
serde_json::Value::Object(_) => vec![value],
|
||||
_ => return Err("JSON import must be an object or an array".to_string()),
|
||||
};
|
||||
if items.is_empty() {
|
||||
return Err("Import file has no rows".to_string());
|
||||
}
|
||||
|
||||
if items.iter().all(|item| item.is_object()) {
|
||||
let mut columns = Vec::new();
|
||||
for item in &items {
|
||||
if let Some(obj) = item.as_object() {
|
||||
for key in obj.keys() {
|
||||
if !columns.contains(key) {
|
||||
columns.push(key.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if columns.is_empty() {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
let rows = items
|
||||
.iter()
|
||||
.take(preview_limit)
|
||||
.map(|item| {
|
||||
let obj = item.as_object().expect("checked object JSON row");
|
||||
columns
|
||||
.iter()
|
||||
.map(|column| obj.get(column).cloned().unwrap_or(serde_json::Value::Null))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
return Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows: items.len(),
|
||||
});
|
||||
}
|
||||
|
||||
if items.iter().all(|item| item.is_array()) {
|
||||
let max_cols = items
|
||||
.iter()
|
||||
.filter_map(|item| item.as_array().map(|row| row.len()))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if max_cols == 0 {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
let columns = (0..max_cols)
|
||||
.map(|index| format!("column_{}", index + 1))
|
||||
.collect::<Vec<_>>();
|
||||
let rows = items
|
||||
.iter()
|
||||
.take(preview_limit)
|
||||
.map(|item| {
|
||||
let arr = item.as_array().expect("checked array JSON row");
|
||||
(0..max_cols)
|
||||
.map(|index| arr.get(index).cloned().unwrap_or(serde_json::Value::Null))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
return Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows: items.len(),
|
||||
});
|
||||
}
|
||||
|
||||
Err("JSON rows must all be objects or all be arrays".to_string())
|
||||
}
|
||||
|
||||
fn xlsx_cell_value(cell: &Data) -> serde_json::Value {
|
||||
match cell {
|
||||
Data::Empty => serde_json::Value::Null,
|
||||
Data::String(s) => csv_value(s),
|
||||
Data::Float(n) => serde_json::Number::from_f64(*n)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
Data::Int(n) => serde_json::Value::Number((*n).into()),
|
||||
Data::Bool(v) => serde_json::Value::Bool(*v),
|
||||
Data::DateTime(v) => serde_json::Value::String(v.to_string()),
|
||||
Data::DateTimeIso(v) => serde_json::Value::String(v.clone()),
|
||||
Data::DurationIso(v) => serde_json::Value::String(v.clone()),
|
||||
Data::Error(v) => serde_json::Value::String(v.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn xlsx_cell_label(cell: &Data) -> String {
|
||||
match cell {
|
||||
Data::Empty => String::new(),
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Float(n) => n.to_string(),
|
||||
Data::Int(n) => n.to_string(),
|
||||
Data::Bool(v) => v.to_string(),
|
||||
Data::DateTime(v) => v.to_string(),
|
||||
Data::DateTimeIso(v) => v.clone(),
|
||||
Data::DurationIso(v) => v.clone(),
|
||||
Data::Error(v) => v.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_xlsx_file(path: &str, preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
let mut workbook = open_workbook_auto(path).map_err(|e| e.to_string())?;
|
||||
let sheet_name = workbook
|
||||
.sheet_names()
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or_else(|| "Workbook has no sheets".to_string())?;
|
||||
let range = workbook
|
||||
.worksheet_range(&sheet_name)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut rows_iter = range.rows();
|
||||
let header = rows_iter
|
||||
.next()
|
||||
.ok_or_else(|| "Import file has no rows".to_string())?;
|
||||
let columns = header
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, cell)| normalize_header(&xlsx_cell_label(cell), index))
|
||||
.collect::<Vec<_>>();
|
||||
if columns.is_empty() {
|
||||
return Err("Import file has no columns".to_string());
|
||||
}
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let mut total_rows = 0;
|
||||
for source_row in rows_iter {
|
||||
total_rows += 1;
|
||||
if rows.len() >= preview_limit {
|
||||
continue;
|
||||
}
|
||||
let mut row = Vec::with_capacity(columns.len());
|
||||
for index in 0..columns.len() {
|
||||
row.push(
|
||||
source_row
|
||||
.get(index)
|
||||
.map(xlsx_cell_value)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
Ok(ParsedImportFile {
|
||||
columns,
|
||||
rows,
|
||||
total_rows,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_import_file(path: &str, preview_limit: usize) -> Result<ParsedImportFile, String> {
|
||||
match import_file_kind(path)? {
|
||||
ImportFileKind::Csv => {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
parse_csv_bytes(&bytes, preview_limit)
|
||||
}
|
||||
ImportFileKind::Tsv => {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
parse_delimited_bytes(&bytes, b'\t', preview_limit)
|
||||
}
|
||||
ImportFileKind::Json => {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
parse_json_bytes(&bytes, preview_limit)
|
||||
}
|
||||
ImportFileKind::Xlsx => parse_xlsx_file(path, preview_limit),
|
||||
}
|
||||
}
|
||||
|
||||
fn mapping_indexes(
|
||||
data: &ParsedImportFile,
|
||||
mappings: &[TableImportColumnMapping],
|
||||
) -> Result<Vec<(usize, String)>, String> {
|
||||
if mappings.is_empty() {
|
||||
return Err("No columns mapped for import".to_string());
|
||||
}
|
||||
let mut mapped = Vec::new();
|
||||
let mut target_seen = HashSet::new();
|
||||
for mapping in mappings {
|
||||
let source_index = data
|
||||
.columns
|
||||
.iter()
|
||||
.position(|column| column == &mapping.source_column)
|
||||
.ok_or_else(|| format!("Source column not found: {}", mapping.source_column))?;
|
||||
if mapping.target_column.trim().is_empty() {
|
||||
return Err("Target column cannot be empty".to_string());
|
||||
}
|
||||
if !target_seen.insert(mapping.target_column.clone()) {
|
||||
return Err(format!(
|
||||
"Target column mapped more than once: {}",
|
||||
mapping.target_column
|
||||
));
|
||||
}
|
||||
mapped.push((source_index, mapping.target_column.clone()));
|
||||
}
|
||||
Ok(mapped)
|
||||
}
|
||||
|
||||
fn build_import_insert_batches(
|
||||
data: &ParsedImportFile,
|
||||
mappings: &[TableImportColumnMapping],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
db_type: &DatabaseType,
|
||||
batch_size: usize,
|
||||
) -> Result<Vec<ImportSqlBatch>, String> {
|
||||
let mapped = mapping_indexes(data, mappings)?;
|
||||
let columns = mapped
|
||||
.iter()
|
||||
.map(|(_, target)| target.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let batch_size = batch_size.max(1);
|
||||
let mut batches = Vec::new();
|
||||
|
||||
for chunk in data.rows.chunks(batch_size) {
|
||||
let rows = chunk
|
||||
.iter()
|
||||
.map(|row| {
|
||||
mapped
|
||||
.iter()
|
||||
.map(|(source_index, _)| {
|
||||
row.get(*source_index)
|
||||
.cloned()
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let sql = generate_insert(&columns, &rows, table, schema, db_type);
|
||||
if !sql.trim().is_empty() {
|
||||
batches.push(ImportSqlBatch {
|
||||
sql,
|
||||
row_count: chunk.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(batches)
|
||||
}
|
||||
|
||||
fn truncate_sql(table: &str, schema: &str, db_type: &DatabaseType) -> String {
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
match db_type {
|
||||
DatabaseType::Sqlite => format!("DELETE FROM {full_table}"),
|
||||
_ => format!("TRUNCATE TABLE {full_table}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_progress(app: &AppHandle, progress: TableImportProgress) {
|
||||
let _ = app.emit("table-import-progress", progress);
|
||||
}
|
||||
@@ -464,24 +30,7 @@ async fn clear_cancelled(import_id: &str) {
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn preview_table_import_file(file_path: String) -> Result<TableImportPreview, String> {
|
||||
let kind = import_file_kind(&file_path)?;
|
||||
let parsed = parse_import_file(&file_path, DEFAULT_PREVIEW_LIMIT)?;
|
||||
let metadata = std::fs::metadata(&file_path).map_err(|e| e.to_string())?;
|
||||
let file_name = Path::new(&file_path)
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or(&file_path)
|
||||
.to_string();
|
||||
|
||||
Ok(TableImportPreview {
|
||||
file_name,
|
||||
file_path,
|
||||
file_type: kind.label().to_string(),
|
||||
size_bytes: metadata.len(),
|
||||
columns: parsed.columns,
|
||||
rows: parsed.rows,
|
||||
total_rows: parsed.total_rows,
|
||||
})
|
||||
dbx_core::table_import::preview_table_import_file_core(&file_path)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -499,142 +48,19 @@ pub async fn import_table_file(
|
||||
.get_or_create_pool(&request.connection_id, Some(&request.database))
|
||||
.await?
|
||||
};
|
||||
let batch_size = if request.batch_size == 0 {
|
||||
DEFAULT_BATCH_SIZE
|
||||
} else {
|
||||
request.batch_size
|
||||
};
|
||||
|
||||
let parsed = match parse_import_file(&request.file_path, usize::MAX) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported: 0,
|
||||
total_rows: 0,
|
||||
error: Some(error.clone()),
|
||||
},
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
let total_rows = parsed.total_rows;
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Running,
|
||||
rows_imported: 0,
|
||||
total_rows,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
|
||||
let batches = match build_import_insert_batches(
|
||||
&parsed,
|
||||
&request.mappings,
|
||||
&request.table,
|
||||
&request.schema,
|
||||
let result = dbx_core::table_import::import_table_file_core(
|
||||
&state,
|
||||
&request,
|
||||
&db_type,
|
||||
batch_size,
|
||||
) {
|
||||
Ok(batches) => batches,
|
||||
Err(error) => {
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported: 0,
|
||||
total_rows,
|
||||
error: Some(error.clone()),
|
||||
},
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
&pool_key,
|
||||
|import_id| Box::pin(is_cancelled(import_id)),
|
||||
|progress| emit_progress(&app, progress),
|
||||
)
|
||||
.await;
|
||||
|
||||
if matches!(request.mode, TableImportMode::Truncate) {
|
||||
let sql = truncate_sql(&request.table, &request.schema, &db_type);
|
||||
if let Err(error) = execute_on_pool(&state, &pool_key, &sql).await {
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported: 0,
|
||||
total_rows,
|
||||
error: Some(error.clone()),
|
||||
},
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows_imported = 0;
|
||||
for batch in batches {
|
||||
if is_cancelled(&request.import_id).await {
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Cancelled,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
clear_cancelled(&request.import_id).await;
|
||||
return Err("Import cancelled".to_string());
|
||||
}
|
||||
|
||||
if let Err(error) = execute_on_pool(&state, &pool_key, &batch.sql).await {
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Error,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: Some(error.clone()),
|
||||
},
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
rows_imported = (rows_imported + batch.row_count).min(total_rows);
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Running,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
emit_progress(
|
||||
&app,
|
||||
TableImportProgress {
|
||||
import_id: request.import_id.clone(),
|
||||
status: TableImportStatus::Done,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
clear_cancelled(&request.import_id).await;
|
||||
|
||||
Ok(TableImportSummary {
|
||||
import_id: request.import_id,
|
||||
rows_imported,
|
||||
total_rows,
|
||||
})
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -642,129 +68,3 @@ pub async fn cancel_table_import(import_id: String) -> Result<bool, String> {
|
||||
CANCELLED_IMPORTS.write().await.insert(import_id);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::connection::DatabaseType;
|
||||
|
||||
#[test]
|
||||
fn parses_csv_headers_and_preview_rows() {
|
||||
let parsed = parse_csv_bytes(b"id,name,active\n1,Ada,true\n2,,false\n", 10).unwrap();
|
||||
|
||||
assert_eq!(parsed.columns, vec!["id", "name", "active"]);
|
||||
assert_eq!(parsed.total_rows, 2);
|
||||
assert_eq!(
|
||||
parsed.rows[0],
|
||||
vec![
|
||||
serde_json::Value::String("1".to_string()),
|
||||
serde_json::Value::String("Ada".to_string()),
|
||||
serde_json::Value::String("true".to_string()),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.rows[1],
|
||||
vec![
|
||||
serde_json::Value::String("2".to_string()),
|
||||
serde_json::Value::Null,
|
||||
serde_json::Value::String("false".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_tsv_with_tab_delimiter() {
|
||||
let parsed = parse_delimited_bytes(b"id\tname\n1\tAda\n", b'\t', 10).unwrap();
|
||||
|
||||
assert_eq!(parsed.columns, vec!["id", "name"]);
|
||||
assert_eq!(parsed.total_rows, 1);
|
||||
assert_eq!(
|
||||
parsed.rows[0],
|
||||
vec![
|
||||
serde_json::Value::String("1".to_string()),
|
||||
serde_json::Value::String("Ada".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_json_array_objects_with_union_columns() {
|
||||
let parsed =
|
||||
parse_json_bytes(br#"[{"id":1,"name":"Ada"},{"id":2,"active":true}]"#, 10).unwrap();
|
||||
|
||||
assert_eq!(parsed.columns, vec!["id", "name", "active"]);
|
||||
assert_eq!(parsed.total_rows, 2);
|
||||
assert_eq!(
|
||||
parsed.rows[0],
|
||||
vec![
|
||||
serde_json::json!(1),
|
||||
serde_json::json!("Ada"),
|
||||
serde_json::Value::Null,
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.rows[1],
|
||||
vec![
|
||||
serde_json::json!(2),
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!(true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_import_insert_batches_from_mapped_columns() {
|
||||
let mappings = vec![
|
||||
TableImportColumnMapping {
|
||||
source_column: "id".to_string(),
|
||||
target_column: "user_id".to_string(),
|
||||
},
|
||||
TableImportColumnMapping {
|
||||
source_column: "name".to_string(),
|
||||
target_column: "display_name".to_string(),
|
||||
},
|
||||
];
|
||||
let data = ParsedImportFile {
|
||||
columns: vec!["id".to_string(), "name".to_string(), "ignored".to_string()],
|
||||
rows: vec![
|
||||
vec![
|
||||
serde_json::json!(1),
|
||||
serde_json::json!("Ada"),
|
||||
serde_json::json!("x"),
|
||||
],
|
||||
vec![
|
||||
serde_json::json!(2),
|
||||
serde_json::json!("O'Hara"),
|
||||
serde_json::json!("y"),
|
||||
],
|
||||
vec![
|
||||
serde_json::json!(3),
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("z"),
|
||||
],
|
||||
],
|
||||
total_rows: 3,
|
||||
};
|
||||
|
||||
let batches = build_import_insert_batches(
|
||||
&data,
|
||||
&mappings,
|
||||
"users",
|
||||
"public",
|
||||
&DatabaseType::Postgres,
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(batches, vec![
|
||||
ImportSqlBatch {
|
||||
sql: "INSERT INTO \"public\".\"users\" (\"user_id\", \"display_name\") VALUES\n(1, 'Ada'),\n(2, 'O''Hara')".to_string(),
|
||||
row_count: 2,
|
||||
},
|
||||
ImportSqlBatch {
|
||||
sql: "INSERT INTO \"public\".\"users\" (\"user_id\", \"display_name\") VALUES\n(3, NULL)".to_string(),
|
||||
row_count: 1,
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,628 +1,18 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::commands::connection::{AppState, PoolKind};
|
||||
use crate::db;
|
||||
use crate::models::connection::DatabaseType;
|
||||
use crate::commands::connection::AppState;
|
||||
|
||||
static CANCELLED: std::sync::LazyLock<RwLock<HashSet<String>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashSet::new()));
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TransferRequest {
|
||||
pub transfer_id: String,
|
||||
pub source_connection_id: String,
|
||||
pub source_database: String,
|
||||
pub source_schema: String,
|
||||
pub target_connection_id: String,
|
||||
pub target_database: String,
|
||||
pub target_schema: String,
|
||||
pub tables: Vec<String>,
|
||||
pub create_table: bool,
|
||||
pub truncate_before: bool,
|
||||
pub batch_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TransferProgress {
|
||||
pub transfer_id: String,
|
||||
pub table: String,
|
||||
pub table_index: usize,
|
||||
pub total_tables: usize,
|
||||
pub rows_transferred: u64,
|
||||
pub total_rows: Option<u64>,
|
||||
pub status: TransferStatus,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TransferStatus {
|
||||
Running,
|
||||
TableDone,
|
||||
Done,
|
||||
Error,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
pub(crate) fn quote_identifier(name: &str, db_type: &DatabaseType) -> String {
|
||||
match db_type {
|
||||
DatabaseType::Mysql | DatabaseType::ClickHouse | DatabaseType::Doris | DatabaseType::StarRocks => format!("`{}`", name.replace('`', "``")),
|
||||
DatabaseType::SqlServer => format!("[{}]", name.replace(']', "]]")),
|
||||
_ => format!("\"{}\"", name.replace('"', "\"\"")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn qualified_table(table: &str, schema: &str, db_type: &DatabaseType) -> String {
|
||||
let qt = quote_identifier(table, db_type);
|
||||
if schema.is_empty() {
|
||||
qt
|
||||
} else {
|
||||
format!("{}.{}", quote_identifier(schema, db_type), qt)
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_value(val: &serde_json::Value, db_type: &DatabaseType) -> String {
|
||||
match val {
|
||||
serde_json::Value::Null => "NULL".to_string(),
|
||||
serde_json::Value::Bool(b) => match db_type {
|
||||
DatabaseType::Mysql | DatabaseType::Sqlite | DatabaseType::DuckDb | DatabaseType::Doris | DatabaseType::StarRocks => {
|
||||
if *b { "1".to_string() } else { "0".to_string() }
|
||||
}
|
||||
_ => if *b { "TRUE".to_string() } else { "FALSE".to_string() },
|
||||
},
|
||||
serde_json::Value::Number(n) => n.to_string(),
|
||||
serde_json::Value::String(s) => {
|
||||
format!("'{}'", s.replace('\'', "''"))
|
||||
}
|
||||
_ => {
|
||||
let s = val.to_string();
|
||||
format!("'{}'", s.replace('\'', "''"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_column_type(source_type: &str, _source_db: &DatabaseType, target_db: &DatabaseType) -> String {
|
||||
let t = source_type.to_lowercase();
|
||||
let base = t.split('(').next().unwrap_or(&t).trim();
|
||||
|
||||
match base {
|
||||
"int" | "integer" | "int4" | "mediumint" => match target_db {
|
||||
DatabaseType::Postgres => "INTEGER".into(),
|
||||
DatabaseType::Mysql => "INT".into(),
|
||||
DatabaseType::SqlServer => "INT".into(),
|
||||
_ => "INTEGER".into(),
|
||||
},
|
||||
"bigint" | "int8" => "BIGINT".into(),
|
||||
"smallint" | "int2" => "SMALLINT".into(),
|
||||
"tinyint" => match target_db {
|
||||
DatabaseType::Postgres => "SMALLINT".into(),
|
||||
_ => "TINYINT".into(),
|
||||
},
|
||||
"serial" | "bigserial" | "smallserial" => match target_db {
|
||||
DatabaseType::Postgres => source_type.to_uppercase(),
|
||||
DatabaseType::Mysql => "BIGINT AUTO_INCREMENT".into(),
|
||||
_ => "INTEGER".into(),
|
||||
},
|
||||
"float" | "float4" | "real" => match target_db {
|
||||
DatabaseType::Postgres => "REAL".into(),
|
||||
_ => "FLOAT".into(),
|
||||
},
|
||||
"double" | "double precision" | "float8" => match target_db {
|
||||
DatabaseType::Postgres => "DOUBLE PRECISION".into(),
|
||||
_ => "DOUBLE".into(),
|
||||
},
|
||||
"decimal" | "numeric" | "number" => {
|
||||
if t.contains('(') {
|
||||
match target_db {
|
||||
DatabaseType::Mysql | DatabaseType::Postgres | DatabaseType::SqlServer | DatabaseType::Oracle => {
|
||||
format!("DECIMAL{}", &t[t.find('(').unwrap()..])
|
||||
}
|
||||
_ => "NUMERIC".into(),
|
||||
}
|
||||
} else {
|
||||
"NUMERIC".into()
|
||||
}
|
||||
}
|
||||
"varchar" | "nvarchar" | "character varying" | "varchar2" => {
|
||||
if t.contains('(') {
|
||||
let len_part = &t[t.find('(').unwrap()..];
|
||||
match target_db {
|
||||
DatabaseType::Postgres => format!("VARCHAR{len_part}"),
|
||||
DatabaseType::Mysql => format!("VARCHAR{len_part}"),
|
||||
DatabaseType::SqlServer => format!("NVARCHAR{len_part}"),
|
||||
_ => format!("VARCHAR{len_part}"),
|
||||
}
|
||||
} else {
|
||||
"VARCHAR(255)".into()
|
||||
}
|
||||
}
|
||||
"char" | "nchar" | "character" => {
|
||||
if t.contains('(') {
|
||||
let len_part = &t[t.find('(').unwrap()..];
|
||||
format!("CHAR{len_part}")
|
||||
} else {
|
||||
"CHAR(1)".into()
|
||||
}
|
||||
}
|
||||
"text" | "longtext" | "mediumtext" | "tinytext" | "clob" | "ntext" => "TEXT".into(),
|
||||
"bool" | "boolean" => match target_db {
|
||||
DatabaseType::Mysql => "TINYINT(1)".into(),
|
||||
DatabaseType::SqlServer => "BIT".into(),
|
||||
_ => "BOOLEAN".into(),
|
||||
},
|
||||
"date" => "DATE".into(),
|
||||
"time" => "TIME".into(),
|
||||
"datetime" => match target_db {
|
||||
DatabaseType::Postgres => "TIMESTAMP".into(),
|
||||
_ => "DATETIME".into(),
|
||||
},
|
||||
"timestamp" | "timestamptz" | "timestamp with time zone"
|
||||
| "timestamp without time zone" => match target_db {
|
||||
DatabaseType::Mysql => "DATETIME".into(),
|
||||
DatabaseType::SqlServer => "DATETIME2".into(),
|
||||
_ => "TIMESTAMP".into(),
|
||||
},
|
||||
"blob" | "longblob" | "mediumblob" | "tinyblob" | "binary" | "varbinary" | "image" => {
|
||||
match target_db {
|
||||
DatabaseType::Postgres => "BYTEA".into(),
|
||||
DatabaseType::Mysql => "BLOB".into(),
|
||||
DatabaseType::SqlServer => "VARBINARY(MAX)".into(),
|
||||
_ => "BLOB".into(),
|
||||
}
|
||||
}
|
||||
"bytea" => match target_db {
|
||||
DatabaseType::Postgres => "BYTEA".into(),
|
||||
DatabaseType::Mysql => "BLOB".into(),
|
||||
_ => "BLOB".into(),
|
||||
},
|
||||
"json" | "jsonb" => match target_db {
|
||||
DatabaseType::Postgres => "JSONB".into(),
|
||||
DatabaseType::Mysql => "JSON".into(),
|
||||
_ => "TEXT".into(),
|
||||
},
|
||||
"uuid" => match target_db {
|
||||
DatabaseType::Postgres => "UUID".into(),
|
||||
_ => "VARCHAR(36)".into(),
|
||||
},
|
||||
"bit" => match target_db {
|
||||
DatabaseType::Postgres => "BOOLEAN".into(),
|
||||
_ => "BIT".into(),
|
||||
},
|
||||
_ => "TEXT".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_create_table_ddl(
|
||||
columns: &[db::ColumnInfo],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
target_db: &DatabaseType,
|
||||
source_db: &DatabaseType,
|
||||
) -> String {
|
||||
let full_table = qualified_table(table, schema, target_db);
|
||||
|
||||
let col_lines: Vec<String> = columns
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mapped_type = map_column_type(&c.data_type, source_db, target_db);
|
||||
let mut line = format!(" {} {}", quote_identifier(&c.name, target_db), mapped_type);
|
||||
if !c.is_nullable {
|
||||
line.push_str(" NOT NULL");
|
||||
}
|
||||
line
|
||||
})
|
||||
.collect();
|
||||
|
||||
let pks: Vec<String> = columns
|
||||
.iter()
|
||||
.filter(|c| c.is_primary_key)
|
||||
.map(|c| quote_identifier(&c.name, target_db))
|
||||
.collect();
|
||||
|
||||
let mut ddl = match target_db {
|
||||
DatabaseType::SqlServer => format!("IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{table}')\n"),
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
let create_prefix = match target_db {
|
||||
DatabaseType::SqlServer => "CREATE TABLE",
|
||||
_ => "CREATE TABLE IF NOT EXISTS",
|
||||
};
|
||||
|
||||
ddl.push_str(&format!("{create_prefix} {full_table} (\n"));
|
||||
ddl.push_str(&col_lines.join(",\n"));
|
||||
|
||||
if !pks.is_empty() {
|
||||
ddl.push_str(&format!(",\n PRIMARY KEY ({})", pks.join(", ")));
|
||||
}
|
||||
|
||||
ddl.push_str("\n)");
|
||||
|
||||
if matches!(target_db, DatabaseType::ClickHouse) {
|
||||
ddl.push_str(" ENGINE = MergeTree() ORDER BY tuple()");
|
||||
}
|
||||
|
||||
ddl
|
||||
}
|
||||
|
||||
pub(crate) fn generate_insert(
|
||||
columns: &[String],
|
||||
rows: &[Vec<serde_json::Value>],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
db_type: &DatabaseType,
|
||||
) -> String {
|
||||
if rows.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
let col_list = columns
|
||||
.iter()
|
||||
.map(|c| quote_identifier(c, db_type))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
let value_rows: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let vals: Vec<String> = row.iter().map(|v| escape_value(v, db_type)).collect();
|
||||
format!("({})", vals.join(", "))
|
||||
})
|
||||
.collect();
|
||||
|
||||
format!("INSERT INTO {full_table} ({col_list}) VALUES\n{}", value_rows.join(",\n"))
|
||||
}
|
||||
|
||||
fn pagination_sql(
|
||||
columns: &[String],
|
||||
table: &str,
|
||||
schema: &str,
|
||||
db_type: &DatabaseType,
|
||||
offset: u64,
|
||||
limit: usize,
|
||||
) -> String {
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
let col_list = columns
|
||||
.iter()
|
||||
.map(|c| quote_identifier(c, db_type))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
match db_type {
|
||||
DatabaseType::SqlServer | DatabaseType::Oracle => {
|
||||
format!(
|
||||
"SELECT {col_list} FROM {full_table} ORDER BY (SELECT NULL) OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
format!("SELECT {col_list} FROM {full_table} LIMIT {limit} OFFSET {offset}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn count_sql(table: &str, schema: &str, db_type: &DatabaseType) -> String {
|
||||
let full_table = qualified_table(table, schema, db_type);
|
||||
format!("SELECT COUNT(*) FROM {full_table}")
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_on_pool(
|
||||
state: &AppState,
|
||||
pool_key: &str,
|
||||
sql: &str,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
let pool = connections.get(pool_key).ok_or("Connection not found")?;
|
||||
|
||||
match pool {
|
||||
PoolKind::Mysql(p, bare) => {
|
||||
let p = p.clone();
|
||||
let bare = *bare;
|
||||
drop(connections);
|
||||
db::mysql::execute_query(&p, sql, bare).await
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::postgres::execute_query(&p, sql).await
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::sqlite::execute_query(&p, sql).await
|
||||
}
|
||||
PoolKind::ClickHouse(client) => {
|
||||
let client = client.clone();
|
||||
let database = pool_key.split(':').nth(1).unwrap_or("default").to_string();
|
||||
drop(connections);
|
||||
db::clickhouse_driver::execute_query(&client, &database, sql).await
|
||||
}
|
||||
PoolKind::SqlServer(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
db::sqlserver::execute_query(&mut client, sql).await
|
||||
}
|
||||
PoolKind::Oracle(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
db::oracle_driver::execute_query(&*client, sql).await
|
||||
}
|
||||
PoolKind::DuckDb(con) => {
|
||||
let con = con.clone();
|
||||
let sql = sql.to_string();
|
||||
drop(connections);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
let start = std::time::Instant::now();
|
||||
let trimmed = sql.trim().to_uppercase();
|
||||
if trimmed.starts_with("SELECT") || trimmed.starts_with("SHOW")
|
||||
|| trimmed.starts_with("DESCRIBE") || trimmed.starts_with("WITH")
|
||||
|| trimmed.starts_with("PRAGMA")
|
||||
{
|
||||
let mut stmt = con.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
let stmt_ref = rows.as_ref().ok_or("DuckDB statement unavailable")?;
|
||||
let col_count = stmt_ref.column_count();
|
||||
let columns: Vec<String> = (0..col_count)
|
||||
.map(|i| stmt_ref.column_name(i).map(|s| s.to_string()).unwrap_or_else(|_| "?".to_string()))
|
||||
.collect();
|
||||
let mut result_rows = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
let vals: Vec<serde_json::Value> = (0..col_count).map(|i| {
|
||||
row.get::<_, String>(i).map(serde_json::Value::String)
|
||||
.or_else(|_| row.get::<_, i64>(i).map(|v| serde_json::Value::Number(v.into())))
|
||||
.or_else(|_| row.get::<_, f64>(i).map(|v| {
|
||||
serde_json::Number::from_f64(v).map(serde_json::Value::Number).unwrap_or(serde_json::Value::Null)
|
||||
}))
|
||||
.or_else(|_| row.get::<_, bool>(i).map(serde_json::Value::Bool))
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}).collect();
|
||||
result_rows.push(vals);
|
||||
}
|
||||
Ok(db::QueryResult { columns, rows: result_rows, affected_rows: 0, execution_time_ms: start.elapsed().as_millis(), truncated: false })
|
||||
} else {
|
||||
let affected = con.execute(&sql, []).map_err(|e| e.to_string())?;
|
||||
Ok(db::QueryResult { columns: vec![], rows: vec![], affected_rows: affected as u64, execution_time_ms: start.elapsed().as_millis(), truncated: false })
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
_ => Err("Unsupported database type for transfer".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_db_type(state: &AppState, connection_id: &str) -> Result<DatabaseType, String> {
|
||||
let configs = state.configs.lock().await;
|
||||
configs
|
||||
.get(connection_id)
|
||||
.map(|c| c.db_type.clone())
|
||||
.ok_or_else(|| format!("Connection config not found: {connection_id}"))
|
||||
}
|
||||
|
||||
async fn get_columns_for_transfer(
|
||||
state: &AppState,
|
||||
pool_key: &str,
|
||||
_connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::ColumnInfo>, String> {
|
||||
let connections = state.connections.lock().await;
|
||||
|
||||
if let Some(PoolKind::DuckDb(con)) = connections.get(pool_key) {
|
||||
let con = con.clone();
|
||||
drop(connections);
|
||||
let table = table.to_string();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
let con = con.lock().map_err(|e| e.to_string())?;
|
||||
// Inline DuckDB column query
|
||||
let mut stmt = con.prepare(
|
||||
"SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'main' AND table_name = ?
|
||||
ORDER BY ordinal_position"
|
||||
).map_err(|e| e.to_string())?;
|
||||
let rows = stmt.query_map([&table], |row| {
|
||||
Ok(db::ColumnInfo {
|
||||
name: row.get::<_, String>(0)?,
|
||||
data_type: row.get::<_, String>(1)?,
|
||||
is_nullable: row.get::<_, String>(2).unwrap_or_default() == "YES",
|
||||
column_default: row.get::<_, Option<String>>(3)?,
|
||||
is_primary_key: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
character_maximum_length: None,
|
||||
})
|
||||
}).map_err(|e| e.to_string())?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}).await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if let Some(PoolKind::ClickHouse(client)) = connections.get(pool_key) {
|
||||
let client = client.clone();
|
||||
let database = database.to_string();
|
||||
let table = table.to_string();
|
||||
drop(connections);
|
||||
return db::clickhouse_driver::get_columns(&client, &database, &table).await;
|
||||
}
|
||||
if let Some(PoolKind::SqlServer(client)) = connections.get(pool_key) {
|
||||
let client = client.clone();
|
||||
let schema = schema.to_string();
|
||||
let table = table.to_string();
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::get_columns(&mut client, &schema, &table).await;
|
||||
}
|
||||
if let Some(PoolKind::Oracle(client)) = connections.get(pool_key) {
|
||||
let client = client.clone();
|
||||
let schema = schema.to_string();
|
||||
let table = table.to_string();
|
||||
drop(connections);
|
||||
let client = client.lock().await;
|
||||
return db::oracle_driver::get_columns(&*client, &schema, &table).await;
|
||||
}
|
||||
|
||||
let pool = connections.get(pool_key).ok_or("Pool not found")?;
|
||||
let schema = schema.to_string();
|
||||
let table = table.to_string();
|
||||
match pool {
|
||||
PoolKind::Mysql(p, _) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::mysql::get_columns(&p, &schema, &table).await
|
||||
}
|
||||
PoolKind::Postgres(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::postgres::get_columns(&p, &schema, &table).await
|
||||
}
|
||||
PoolKind::Sqlite(p) => {
|
||||
let p = p.clone();
|
||||
drop(connections);
|
||||
db::sqlite::get_columns(&p, &schema, &table).await
|
||||
}
|
||||
_ => Err("Unsupported database type".to_string()),
|
||||
}
|
||||
}
|
||||
// Re-export types and functions used by other modules
|
||||
pub use dbx_core::transfer::{
|
||||
get_db_type,
|
||||
TransferProgress, TransferRequest, TransferStatus,
|
||||
};
|
||||
|
||||
fn emit_progress(app: &AppHandle, progress: TransferProgress) {
|
||||
let _ = app.emit("transfer-progress", progress);
|
||||
}
|
||||
|
||||
async fn is_cancelled(transfer_id: &str) -> bool {
|
||||
CANCELLED.read().await.contains(transfer_id)
|
||||
}
|
||||
|
||||
async fn transfer_table(
|
||||
app: &AppHandle,
|
||||
state: &AppState,
|
||||
request: &TransferRequest,
|
||||
table: &str,
|
||||
table_index: usize,
|
||||
source_db_type: &DatabaseType,
|
||||
target_db_type: &DatabaseType,
|
||||
source_pool_key: &str,
|
||||
target_pool_key: &str,
|
||||
) -> Result<u64, String> {
|
||||
let total_tables = request.tables.len();
|
||||
|
||||
// Get source columns (deduplicate by name)
|
||||
let columns = {
|
||||
let raw = get_columns_for_transfer(
|
||||
state, source_pool_key, &request.source_connection_id,
|
||||
&request.source_database, &request.source_schema, table,
|
||||
).await?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
raw.into_iter().filter(|c| seen.insert(c.name.clone())).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if columns.is_empty() {
|
||||
return Err(format!("No columns found for table {table}"));
|
||||
}
|
||||
|
||||
let col_names: Vec<String> = columns.iter().map(|c| c.name.clone()).collect();
|
||||
log::info!("[transfer] {} has {} columns, counting rows...", table, columns.len());
|
||||
|
||||
// Count source rows
|
||||
let total_rows = {
|
||||
let sql = count_sql(table, &request.source_schema, source_db_type);
|
||||
match execute_on_pool(state, source_pool_key, &sql).await {
|
||||
Ok(result) => result.rows.first()
|
||||
.and_then(|r| r.first())
|
||||
.and_then(|v| match v {
|
||||
serde_json::Value::Number(n) => n.as_u64(),
|
||||
serde_json::Value::String(s) => s.parse::<u64>().ok(),
|
||||
_ => None,
|
||||
}),
|
||||
Err(e) => {
|
||||
log::warn!("[transfer] count failed for {}: {}", table, e);
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
log::info!("[transfer] {} total_rows={:?}", table, total_rows);
|
||||
|
||||
// Create table on target if requested
|
||||
if request.create_table {
|
||||
let ddl = generate_create_table_ddl(&columns, table, &request.target_schema, target_db_type, source_db_type);
|
||||
log::info!("[transfer] creating target table: {}", &ddl[..ddl.len().min(200)]);
|
||||
if let Err(e) = execute_on_pool(state, target_pool_key, &ddl).await {
|
||||
let err_lower = e.to_lowercase();
|
||||
if !err_lower.contains("already exists") && !err_lower.contains("there is already") {
|
||||
return Err(format!("Failed to create table: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Truncate target if requested
|
||||
if request.truncate_before {
|
||||
let full_table = qualified_table(table, &request.target_schema, target_db_type);
|
||||
let truncate_sql = match target_db_type {
|
||||
DatabaseType::Sqlite | DatabaseType::DuckDb => format!("DELETE FROM {full_table}"),
|
||||
_ => format!("TRUNCATE TABLE {full_table}"),
|
||||
};
|
||||
execute_on_pool(state, target_pool_key, &truncate_sql).await
|
||||
.map_err(|e| format!("Failed to truncate: {e}"))?;
|
||||
}
|
||||
|
||||
// Transfer data in batches
|
||||
let batch_size = if request.batch_size == 0 { 1000 } else { request.batch_size };
|
||||
let mut offset: u64 = 0;
|
||||
let mut total_transferred: u64 = 0;
|
||||
|
||||
loop {
|
||||
if is_cancelled(&request.transfer_id).await {
|
||||
return Err("Cancelled".to_string());
|
||||
}
|
||||
|
||||
let sql = pagination_sql(&col_names, table, &request.source_schema, source_db_type, offset, batch_size);
|
||||
let result = execute_on_pool(state, source_pool_key, &sql).await?;
|
||||
let row_count = result.rows.len();
|
||||
|
||||
if row_count == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
let insert_sql = generate_insert(&col_names, &result.rows, table, &request.target_schema, target_db_type);
|
||||
if !insert_sql.is_empty() {
|
||||
execute_on_pool(state, target_pool_key, &insert_sql).await
|
||||
.map_err(|e| format!("Insert failed at offset {offset}: {e}"))?;
|
||||
}
|
||||
|
||||
total_transferred += row_count as u64;
|
||||
log::info!("[transfer] {} batch +{} rows (total {})", table, row_count, total_transferred);
|
||||
offset += row_count as u64;
|
||||
|
||||
emit_progress(app, TransferProgress {
|
||||
transfer_id: request.transfer_id.clone(),
|
||||
table: table.to_string(),
|
||||
table_index,
|
||||
total_tables,
|
||||
rows_transferred: total_transferred,
|
||||
total_rows,
|
||||
status: TransferStatus::Running,
|
||||
error: None,
|
||||
});
|
||||
|
||||
if row_count < batch_size {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(total_transferred)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn start_transfer(
|
||||
app: AppHandle,
|
||||
@@ -649,7 +39,7 @@ pub async fn start_transfer(
|
||||
log::info!("[transfer] starting transfer_id={} tables={}", transfer_id, total_tables);
|
||||
|
||||
for (i, table) in request.tables.iter().enumerate() {
|
||||
if is_cancelled(&transfer_id).await {
|
||||
if dbx_core::transfer::is_cancelled(&transfer_id).await {
|
||||
emit_progress(&app, TransferProgress {
|
||||
transfer_id: transfer_id.clone(),
|
||||
table: table.clone(),
|
||||
@@ -660,16 +50,17 @@ pub async fn start_transfer(
|
||||
status: TransferStatus::Cancelled,
|
||||
error: None,
|
||||
});
|
||||
CANCELLED.write().await.remove(&transfer_id);
|
||||
dbx_core::transfer::clear_cancelled(&transfer_id).await;
|
||||
return;
|
||||
}
|
||||
|
||||
log::info!("[transfer] table {}/{}: {}", i + 1, total_tables, table);
|
||||
|
||||
match transfer_table(
|
||||
&app, &state, &request, table, i,
|
||||
match dbx_core::transfer::transfer_table(
|
||||
&state, &request, table, i,
|
||||
&source_db_type, &target_db_type,
|
||||
&source_pool_key, &target_pool_key,
|
||||
|progress| emit_progress(&app, progress),
|
||||
).await {
|
||||
Ok(rows) => {
|
||||
emit_progress(&app, TransferProgress {
|
||||
@@ -695,7 +86,7 @@ pub async fn start_transfer(
|
||||
status: TransferStatus::Cancelled,
|
||||
error: None,
|
||||
});
|
||||
CANCELLED.write().await.remove(&transfer_id);
|
||||
dbx_core::transfer::clear_cancelled(&transfer_id).await;
|
||||
return;
|
||||
}
|
||||
emit_progress(&app, TransferProgress {
|
||||
@@ -708,13 +99,13 @@ pub async fn start_transfer(
|
||||
status: TransferStatus::Error,
|
||||
error: Some(e),
|
||||
});
|
||||
CANCELLED.write().await.remove(&transfer_id);
|
||||
dbx_core::transfer::clear_cancelled(&transfer_id).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CANCELLED.write().await.remove(&transfer_id);
|
||||
dbx_core::transfer::clear_cancelled(&transfer_id).await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
@@ -722,6 +113,6 @@ pub async fn start_transfer(
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cancel_transfer(transfer_id: String) -> Result<(), String> {
|
||||
CANCELLED.write().await.insert(transfer_id);
|
||||
dbx_core::transfer::set_cancelled(&transfer_id).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,98 +1,8 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/t8y2/dbx/releases/latest";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct GithubRelease {
|
||||
tag_name: String,
|
||||
name: Option<String>,
|
||||
html_url: String,
|
||||
body: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UpdateInfo {
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub update_available: bool,
|
||||
pub release_name: String,
|
||||
pub release_url: String,
|
||||
pub release_notes: String,
|
||||
}
|
||||
pub use dbx_core::update::UpdateInfo;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn check_for_updates() -> Result<UpdateInfo, String> {
|
||||
let client = reqwest::Client::new();
|
||||
let release = client
|
||||
.get(LATEST_RELEASE_URL)
|
||||
.header(reqwest::header::USER_AGENT, "dbx-update-checker")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to check updates: {e}"))?
|
||||
.error_for_status()
|
||||
.map_err(|e| format!("Failed to check updates: {e}"))?
|
||||
.json::<GithubRelease>()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse update response: {e}"))?;
|
||||
|
||||
let current_version = env!("CARGO_PKG_VERSION").to_string();
|
||||
let latest_version = normalize_version(&release.tag_name);
|
||||
|
||||
Ok(UpdateInfo {
|
||||
update_available: is_newer_version(&latest_version, ¤t_version),
|
||||
current_version,
|
||||
latest_version,
|
||||
release_name: release.name.unwrap_or_else(|| release.tag_name.clone()),
|
||||
release_url: release.html_url,
|
||||
release_notes: release.body.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_version(version: &str) -> String {
|
||||
version.trim().trim_start_matches('v').to_string()
|
||||
}
|
||||
|
||||
fn parse_version(version: &str) -> Vec<u64> {
|
||||
normalize_version(version)
|
||||
.split(['.', '-', '+'])
|
||||
.map(|part| part.parse::<u64>().unwrap_or(0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_newer_version(latest: &str, current: &str) -> bool {
|
||||
let latest_parts = parse_version(latest);
|
||||
let current_parts = parse_version(current);
|
||||
let max_len = latest_parts.len().max(current_parts.len());
|
||||
|
||||
for i in 0..max_len {
|
||||
let latest_part = *latest_parts.get(i).unwrap_or(&0);
|
||||
let current_part = *current_parts.get(i).unwrap_or(&0);
|
||||
if latest_part > current_part {
|
||||
return true;
|
||||
}
|
||||
if latest_part < current_part {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{is_newer_version, normalize_version};
|
||||
|
||||
#[test]
|
||||
fn normalizes_tag_versions() {
|
||||
assert_eq!(normalize_version("v1.2.3"), "1.2.3");
|
||||
assert_eq!(normalize_version(" 0.2.0 "), "0.2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compares_semver_like_versions() {
|
||||
assert!(is_newer_version("0.2.1", "0.2.0"));
|
||||
assert!(is_newer_version("1.0.0", "0.9.9"));
|
||||
assert!(!is_newer_version("0.2.0", "0.2.0"));
|
||||
assert!(!is_newer_version("0.1.9", "0.2.0"));
|
||||
}
|
||||
let release = dbx_core::update::fetch_latest_release().await?;
|
||||
let current_version = env!("CARGO_PKG_VERSION");
|
||||
Ok(dbx_core::update::build_update_info(release, current_version))
|
||||
}
|
||||
|
||||
+4
-74
@@ -1,74 +1,4 @@
|
||||
pub mod clickhouse_driver;
|
||||
pub mod elasticsearch_driver;
|
||||
pub mod mongo_driver;
|
||||
pub mod mysql;
|
||||
pub mod oracle_driver;
|
||||
pub mod postgres;
|
||||
pub mod redis_driver;
|
||||
pub mod sqlite;
|
||||
pub mod sqlserver;
|
||||
pub mod ssh_tunnel;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DatabaseInfo {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
pub table_type: String, // "TABLE" or "VIEW"
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ColumnInfo {
|
||||
pub name: String,
|
||||
pub data_type: String,
|
||||
pub is_nullable: bool,
|
||||
pub column_default: Option<String>,
|
||||
pub is_primary_key: bool,
|
||||
pub extra: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
pub numeric_precision: Option<i32>,
|
||||
pub numeric_scale: Option<i32>,
|
||||
pub character_maximum_length: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct QueryResult {
|
||||
pub columns: Vec<String>,
|
||||
pub rows: Vec<Vec<serde_json::Value>>,
|
||||
pub affected_rows: u64,
|
||||
pub execution_time_ms: u128,
|
||||
#[serde(default)]
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IndexInfo {
|
||||
pub name: String,
|
||||
pub columns: Vec<String>,
|
||||
pub is_unique: bool,
|
||||
pub is_primary: bool,
|
||||
pub filter: Option<String>,
|
||||
pub index_type: Option<String>,
|
||||
pub included_columns: Option<Vec<String>>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ForeignKeyInfo {
|
||||
pub name: String,
|
||||
pub column: String,
|
||||
pub ref_table: String,
|
||||
pub ref_column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TriggerInfo {
|
||||
pub name: String,
|
||||
pub event: String,
|
||||
pub timing: String,
|
||||
}
|
||||
#[allow(unused_imports)]
|
||||
pub use dbx_core::db::*;
|
||||
#[allow(unused_imports)]
|
||||
pub use dbx_core::types::*;
|
||||
|
||||
@@ -1,352 +1 @@
|
||||
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ConnectionConfig {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub db_type: DatabaseType,
|
||||
#[serde(default)]
|
||||
pub driver_profile: Option<String>,
|
||||
#[serde(default)]
|
||||
pub driver_label: Option<String>,
|
||||
#[serde(default)]
|
||||
pub url_params: Option<String>,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub database: Option<String>,
|
||||
#[serde(default)]
|
||||
pub color: Option<String>,
|
||||
#[serde(default)]
|
||||
pub ssh_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub ssh_host: String,
|
||||
#[serde(default = "default_ssh_port")]
|
||||
pub ssh_port: u16,
|
||||
#[serde(default)]
|
||||
pub ssh_user: String,
|
||||
#[serde(default)]
|
||||
pub ssh_password: String,
|
||||
#[serde(default)]
|
||||
pub ssh_key_path: String,
|
||||
#[serde(default)]
|
||||
pub ssh_key_passphrase: String,
|
||||
#[serde(default)]
|
||||
pub ssh_expose_lan: bool,
|
||||
#[serde(default)]
|
||||
pub ssl: bool,
|
||||
#[serde(default)]
|
||||
pub connection_string: Option<String>,
|
||||
}
|
||||
|
||||
fn default_ssh_port() -> u16 {
|
||||
22
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DatabaseType {
|
||||
Mysql,
|
||||
Postgres,
|
||||
Sqlite,
|
||||
Redis,
|
||||
#[serde(rename = "duckdb")]
|
||||
DuckDb,
|
||||
#[serde(rename = "clickhouse")]
|
||||
ClickHouse,
|
||||
#[serde(rename = "sqlserver")]
|
||||
SqlServer,
|
||||
#[serde(rename = "mongodb")]
|
||||
MongoDb,
|
||||
#[serde(rename = "oracle")]
|
||||
Oracle,
|
||||
#[serde(rename = "elasticsearch")]
|
||||
Elasticsearch,
|
||||
Doris,
|
||||
#[serde(rename = "starrocks")]
|
||||
StarRocks,
|
||||
Redshift,
|
||||
}
|
||||
|
||||
impl ConnectionConfig {
|
||||
pub fn needs_bare_mysql(&self) -> bool {
|
||||
matches!(self.db_type, DatabaseType::Doris | DatabaseType::StarRocks)
|
||||
|| self.driver_profile.as_deref().map(|p| p.to_lowercase())
|
||||
.is_some_and(|p| matches!(p.as_str(), "doris" | "starrocks" | "selectdb" | "tdengine"))
|
||||
}
|
||||
|
||||
pub fn connection_url(&self) -> String {
|
||||
self.connection_url_with_host(&self.host, self.port)
|
||||
}
|
||||
|
||||
pub fn redacted_connection_url(&self) -> String {
|
||||
self.redacted_connection_url_with_host(&self.host, self.port)
|
||||
}
|
||||
|
||||
pub fn redacted_connection_url_with_host(&self, host: &str, port: u16) -> String {
|
||||
let host = bracket_ipv6(host);
|
||||
let db_part = self
|
||||
.database
|
||||
.as_deref()
|
||||
.filter(|d| !d.is_empty())
|
||||
.map(|d| format!("/{}", encode_url_part(d)))
|
||||
.unwrap_or_default();
|
||||
let params = self.normalized_url_params();
|
||||
|
||||
match self.db_type {
|
||||
DatabaseType::Sqlite | DatabaseType::DuckDb => {
|
||||
format!("{}?mode=rwc", self.host)
|
||||
}
|
||||
DatabaseType::Redis => {
|
||||
let scheme = if self.ssl { "rediss" } else { "redis" };
|
||||
format!("{scheme}://{host}:{port}/")
|
||||
}
|
||||
DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks => format!("mysql://{host}:{port}{db_part}?{params}"),
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => {
|
||||
let suffix = if params.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("?{params}")
|
||||
};
|
||||
format!("postgres://{host}:{port}{db_part}{suffix}")
|
||||
}
|
||||
DatabaseType::ClickHouse => format!("http://{host}:{port}"),
|
||||
DatabaseType::SqlServer => format!(
|
||||
"server=tcp:{host},{port};database={}",
|
||||
self.database.as_deref().unwrap_or("master")
|
||||
),
|
||||
DatabaseType::MongoDb => {
|
||||
if let Some(cs) = self.connection_string.as_deref().filter(|s| !s.is_empty()) {
|
||||
return cs.to_string();
|
||||
}
|
||||
format!("mongodb://{host}:{port}{db_part}")
|
||||
}
|
||||
DatabaseType::Oracle => format!("oracle://{host}:{port}{db_part}"),
|
||||
DatabaseType::Elasticsearch => format!("http://{host}:{port}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connection_url_with_host(&self, host: &str, port: u16) -> String {
|
||||
let host = bracket_ipv6(host);
|
||||
let db_part = self
|
||||
.database
|
||||
.as_deref()
|
||||
.filter(|d| !d.is_empty())
|
||||
.map(|d| format!("/{}", encode_url_part(d)))
|
||||
.unwrap_or_default();
|
||||
let username = encode_url_part(&self.username);
|
||||
let password = encode_url_part(&self.password);
|
||||
let params = self.normalized_url_params();
|
||||
|
||||
match self.db_type {
|
||||
DatabaseType::Sqlite | DatabaseType::DuckDb => {
|
||||
format!("{}?mode=rwc", self.host)
|
||||
}
|
||||
DatabaseType::Redis => {
|
||||
let scheme = if self.ssl { "rediss" } else { "redis" };
|
||||
if self.username.is_empty() && self.password.is_empty() {
|
||||
format!("{scheme}://{host}:{port}/")
|
||||
} else if self.username.is_empty() {
|
||||
format!("{scheme}://:{password}@{host}:{port}/")
|
||||
} else {
|
||||
format!("{scheme}://{username}:{password}@{host}:{port}/")
|
||||
}
|
||||
}
|
||||
DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks => format!(
|
||||
"mysql://{}:{}@{host}:{port}{db_part}?{params}",
|
||||
username, password
|
||||
),
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => {
|
||||
let suffix = if params.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("?{params}")
|
||||
};
|
||||
format!(
|
||||
"postgres://{}:{}@{host}:{port}{db_part}{suffix}",
|
||||
username, password
|
||||
)
|
||||
}
|
||||
DatabaseType::ClickHouse => format!("http://{host}:{port}"),
|
||||
DatabaseType::SqlServer => format!(
|
||||
"server=tcp:{host},{port};user={};password={};database={}",
|
||||
self.username,
|
||||
self.password,
|
||||
self.database.as_deref().unwrap_or("master")
|
||||
),
|
||||
DatabaseType::MongoDb => {
|
||||
if let Some(cs) = self.connection_string.as_deref().filter(|s| !s.is_empty()) {
|
||||
return cs.to_string();
|
||||
}
|
||||
if self.username.is_empty() {
|
||||
format!("mongodb://{host}:{port}{db_part}")
|
||||
} else {
|
||||
format!("mongodb://{username}:{password}@{host}:{port}{db_part}")
|
||||
}
|
||||
}
|
||||
DatabaseType::Oracle => {
|
||||
format!("oracle://{}:{}@{host}:{port}{db_part}", username, password)
|
||||
}
|
||||
DatabaseType::Elasticsearch => format!("http://{host}:{port}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_url_params(&self) -> String {
|
||||
let value = self.url_params.as_deref().unwrap_or("").trim();
|
||||
if self.needs_bare_mysql() {
|
||||
let v = value.trim_start_matches('?');
|
||||
let filtered: Vec<&str> = v.split('&')
|
||||
.filter(|p| !p.is_empty() && !p.starts_with("charset=") && !p.starts_with("ssl-mode=preferred"))
|
||||
.collect();
|
||||
return if filtered.is_empty() { "ssl-mode=disabled".to_string() } else { format!("ssl-mode=disabled&{}", filtered.join("&")) };
|
||||
}
|
||||
match self.db_type {
|
||||
DatabaseType::Mysql => {
|
||||
let base = "ssl-mode=preferred&charset=utf8mb4";
|
||||
if value.is_empty() {
|
||||
base.to_string()
|
||||
} else if value.contains("ssl-mode=") {
|
||||
let v = value.trim_start_matches('?');
|
||||
if v.contains("charset=") { v.to_string() } else { format!("{v}&charset=utf8mb4") }
|
||||
} else {
|
||||
let v = value.trim_start_matches('?');
|
||||
if v.contains("charset=") { format!("ssl-mode=preferred&{v}") } else { format!("{base}&{v}") }
|
||||
}
|
||||
}
|
||||
DatabaseType::Doris | DatabaseType::StarRocks => {
|
||||
let v = value.trim_start_matches('?');
|
||||
let filtered: Vec<&str> = v.split('&')
|
||||
.filter(|p| !p.is_empty() && !p.starts_with("charset=") && !p.starts_with("ssl-mode=preferred"))
|
||||
.collect();
|
||||
if filtered.is_empty() { "ssl-mode=disabled".to_string() } else { format!("ssl-mode=disabled&{}", filtered.join("&")) }
|
||||
}
|
||||
DatabaseType::Postgres | DatabaseType::Redshift => value.trim_start_matches('?').to_string(),
|
||||
_ => value.trim_start_matches('?').to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_url_part(value: &str) -> String {
|
||||
utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
|
||||
}
|
||||
|
||||
fn bracket_ipv6(host: &str) -> String {
|
||||
if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{host}]")
|
||||
} else {
|
||||
host.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ConnectionConfig, DatabaseType};
|
||||
|
||||
fn mysql_config(username: &str, password: &str, database: Option<&str>) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
id: "id".to_string(),
|
||||
name: "name".to_string(),
|
||||
db_type: DatabaseType::Mysql,
|
||||
driver_profile: None,
|
||||
driver_label: None,
|
||||
url_params: None,
|
||||
host: "10.1.2.3".to_string(),
|
||||
port: 2883,
|
||||
username: username.to_string(),
|
||||
password: password.to_string(),
|
||||
database: database.map(str::to_string),
|
||||
color: None,
|
||||
ssh_enabled: false,
|
||||
ssh_host: String::new(),
|
||||
ssh_port: 22,
|
||||
ssh_user: String::new(),
|
||||
ssh_password: String::new(),
|
||||
ssh_key_path: String::new(),
|
||||
ssh_expose_lan: false,
|
||||
ssl: false,
|
||||
connection_string: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_url_encodes_oceanbase_username() {
|
||||
let config = mysql_config("user@tenant#cluster", "secret", None);
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"mysql://user%40tenant%23cluster:secret@10.1.2.3:2883?ssl-mode=preferred&charset=utf8mb4"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_url_encodes_password_and_database() {
|
||||
let config = mysql_config("root", "p@ss:word#1", Some("db/name"));
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"mysql://root:p%40ss%3Aword%231@10.1.2.3:2883/db%2Fname?ssl-mode=preferred&charset=utf8mb4"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_url_appends_custom_params() {
|
||||
let mut config = mysql_config("root", "secret", Some("test"));
|
||||
config.url_params = Some("charset=utf8mb4".to_string());
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"mysql://root:secret@10.1.2.3:2883/test?ssl-mode=preferred&charset=utf8mb4"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_url_appends_custom_params() {
|
||||
let mut config = mysql_config("postgres", "secret", Some("test"));
|
||||
config.db_type = DatabaseType::Postgres;
|
||||
config.url_params = Some("sslmode=disable".to_string());
|
||||
|
||||
assert_eq!(
|
||||
config.connection_url(),
|
||||
"postgres://postgres:secret@10.1.2.3:2883/test?sslmode=disable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_mysql_url_omits_credentials() {
|
||||
let config = mysql_config("user@tenant#cluster", "p@ss:word#1", Some("db/name"));
|
||||
|
||||
let url = config.redacted_connection_url();
|
||||
|
||||
assert_eq!(url, "mysql://10.1.2.3:2883/db%2Fname?ssl-mode=preferred&charset=utf8mb4");
|
||||
assert!(!url.contains("user"));
|
||||
assert!(!url.contains("p%40ss"));
|
||||
assert!(!url.contains("p@ss"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_sqlserver_url_omits_credentials() {
|
||||
let mut config = mysql_config("sa", "super-secret", Some("master"));
|
||||
config.db_type = DatabaseType::SqlServer;
|
||||
|
||||
let url = config.redacted_connection_url();
|
||||
|
||||
assert_eq!(url, "server=tcp:10.1.2.3,2883;database=master");
|
||||
assert!(!url.contains("sa"));
|
||||
assert!(!url.contains("super-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_redis_url_omits_credentials_and_keeps_tls_scheme() {
|
||||
let mut config = mysql_config("default", "redis-secret", None);
|
||||
config.db_type = DatabaseType::Redis;
|
||||
config.ssl = true;
|
||||
|
||||
let url = config.redacted_connection_url();
|
||||
|
||||
assert_eq!(url, "rediss://10.1.2.3:2883/");
|
||||
assert!(!url.contains("default"));
|
||||
assert!(!url.contains("redis-secret"));
|
||||
}
|
||||
}
|
||||
pub use dbx_core::models::connection::*;
|
||||
|
||||
Reference in New Issue
Block a user