Merge branch 't8y2:main' into main

This commit is contained in:
Alexandr
2026-05-11 17:11:12 +04:00
committed by GitHub
45 changed files with 1573 additions and 207 deletions
Generated
+11 -11
View File
@@ -1880,7 +1880,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2214,7 +2214,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3212,7 +3212,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.61.2",
"windows-core 0.62.2",
]
[[package]]
@@ -4196,7 +4196,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.18",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -4287,7 +4287,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6235,7 +6235,7 @@ dependencies = [
[[package]]
name = "rust-oracle"
version = "0.1.6"
source = "git+https://github.com/t8y2/rust-oracle?branch=main#aa5a936c7bfe566123302e885a6965f279c041d9"
source = "git+https://github.com/t8y2/rust-oracle?branch=main#dddc2565d3e7f8c8275f6afc3ba3bc531ed5a2d2"
dependencies = [
"aes 0.8.4",
"async-trait",
@@ -6351,7 +6351,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6452,7 +6452,7 @@ dependencies = [
"security-framework 3.7.0",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7114,7 +7114,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -8054,7 +8054,7 @@ dependencies = [
"getrandom 0.4.2",
"once_cell",
"rustix 1.1.4",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -8553,7 +8553,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.18",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
+1 -1
View File
@@ -23,7 +23,7 @@ redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tokio-rus
rustls = { version = "0.23", features = ["aws-lc-rs"] }
duckdb = "1.3.2"
tiberius = { version = "0.12.3", default-features = false, features = ["tds73", "chrono", "rust_decimal", "rustls"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "socks"] }
futures = "0.3"
mongodb = "3.2.5"
rust-oracle = { git = "https://github.com/t8y2/rust-oracle", branch = "main" }
+53 -6
View File
@@ -70,6 +70,10 @@ pub struct AiConfig {
pub model: String,
#[serde(default)]
pub api_style: AiApiStyle,
#[serde(default)]
pub proxy_enabled: bool,
#[serde(default)]
pub proxy_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -218,6 +222,15 @@ fn validate_config(config: &AiConfig) -> Result<(), String> {
Ok(())
}
pub fn build_ai_http_client(config: &AiConfig, timeout_secs: u64) -> Result<reqwest::Client, String> {
let mut builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(timeout_secs));
if config.proxy_enabled && !config.proxy_url.trim().is_empty() {
let proxy = reqwest::Proxy::all(config.proxy_url.trim()).map_err(|e| format!("Invalid AI proxy URL: {e}"))?;
builder = builder.proxy(proxy);
}
builder.build().map_err(|e| e.to_string())
}
// ---------------------------------------------------------------------------
// Non-streaming calls
// ---------------------------------------------------------------------------
@@ -339,8 +352,7 @@ pub async fn call_responses_api(client: &reqwest::Client, request: AiCompletionR
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 client = build_ai_http_client(config, 15)?;
let request = AiCompletionRequest {
config: config.clone(),
@@ -366,8 +378,7 @@ pub async fn test_connection_core(config: &AiConfig) -> Result<String, 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())?;
let client = build_ai_http_client(&request.config, 60)?;
match request.config.provider {
AiProvider::Claude => call_claude(&client, request.clone()).await,
@@ -393,8 +404,7 @@ pub async fn stream(
) -> 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())?;
let client = build_ai_http_client(&request.config, 120)?;
match request.config.provider {
AiProvider::Claude => stream_claude(&client, session_id, request, cancelled, &on_chunk).await,
@@ -724,3 +734,40 @@ pub fn load_config(path: &Path) -> Result<Option<AiConfig>, String> {
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())
}
#[cfg(test)]
mod tests {
use super::{build_ai_http_client, AiApiStyle, AiConfig, AiProvider};
#[test]
fn ai_config_proxy_fields_default_for_legacy_config() {
let config: AiConfig = serde_json::from_value(serde_json::json!({
"provider": "openai",
"apiKey": "key",
"endpoint": "https://api.openai.com/v1/chat/completions",
"model": "gpt-4o",
"apiStyle": "completions"
}))
.unwrap();
assert_eq!(config.proxy_enabled, false);
assert_eq!(config.proxy_url, "");
}
#[test]
fn ai_http_client_rejects_invalid_proxy_url() {
let config = AiConfig {
provider: AiProvider::Openai,
api_key: "key".to_string(),
endpoint: "https://api.openai.com/v1/chat/completions".to_string(),
model: "gpt-4o".to_string(),
api_style: AiApiStyle::Completions,
proxy_enabled: true,
proxy_url: "not a proxy url".to_string(),
};
let err = build_ai_http_client(&config, 1).unwrap_err();
assert!(err.contains("Invalid AI proxy URL"));
}
}
+57 -1
View File
@@ -5,6 +5,7 @@ use std::sync::Arc;
use tokio::sync::RwLock;
use crate::db;
use crate::db::proxy_tunnel::ProxyTunnelManager;
use crate::db::ssh_tunnel::TunnelManager;
use crate::external;
use crate::models::connection::{parse_mongo_first_host, ConnectionConfig, DatabaseType};
@@ -93,6 +94,7 @@ pub struct AppState {
pub configs: RwLock<HashMap<String, ConnectionConfig>>,
pub running_queries: RunningQueries,
pub tunnels: TunnelManager,
pub proxy_tunnels: ProxyTunnelManager,
pub storage: Storage,
pub plugins: PluginRegistry,
}
@@ -126,6 +128,7 @@ impl AppState {
configs: RwLock::new(HashMap::new()),
running_queries: RunningQueries::default(),
tunnels: TunnelManager::new(),
proxy_tunnels: ProxyTunnelManager::new(),
storage,
plugins: PluginRegistry::new(plugin_dir),
}
@@ -302,6 +305,37 @@ impl AppState {
config: &ConnectionConfig,
) -> Result<(String, u16), String> {
if !config.ssh_enabled || config.ssh_host.is_empty() {
if config.proxy_enabled && !config.proxy_host.is_empty() {
if let Some(local_port) = self.proxy_tunnels.local_port(connection_id).await {
return Ok(("127.0.0.1".to_string(), local_port));
}
let (remote_host, remote_port) = if config.db_type == DatabaseType::MongoDb {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_mongo_first_host)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else {
(config.host.clone(), config.port)
};
let local_port = self
.proxy_tunnels
.start_tunnel(
connection_id,
config.proxy_type,
&config.proxy_host,
config.proxy_port,
&config.proxy_username,
&config.proxy_password,
&remote_host,
remote_port,
)
.await?;
return Ok(("127.0.0.1".to_string(), local_port));
}
return Ok((config.host.clone(), config.port));
}
@@ -412,7 +446,7 @@ async fn detect_ob_oracle_mode(config: &ConnectionConfig, pool: &sqlx::mysql::My
#[cfg(test)]
mod tests {
use super::{database_connection_config, metadata_connection_config, AppState};
use crate::models::connection::{ConnectionConfig, DatabaseType};
use crate::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use crate::schema;
use crate::storage::Storage;
@@ -439,6 +473,12 @@ mod tests {
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: crate::models::connection::default_ssh_connect_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
sysdba: false,
connection_string: None,
@@ -517,4 +557,20 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn proxy_connection_uses_local_forward_endpoint() {
let (state, dir) = test_app_state().await;
let mut config = mysql_config(Some("app"));
config.proxy_enabled = true;
config.proxy_host = "127.0.0.1".to_string();
config.proxy_port = 65000;
let (host, port) = state.connection_host_port("proxied", &config).await.unwrap();
assert_eq!(host, "127.0.0.1");
assert_ne!(port, config.port);
state.proxy_tunnels.stop_tunnel("proxied").await;
let _ = std::fs::remove_dir_all(dir);
}
}
+19 -1
View File
@@ -6,6 +6,7 @@ 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 PROXY_PASSWORD_KEY: &str = "proxy_password";
pub const CONNECTION_STRING_KEY: &str = "connection_string";
pub trait ConnectionSecretStore {
@@ -61,6 +62,7 @@ pub fn save_connections_to_file(
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_secret(store, &config.id, PROXY_PASSWORD_KEY, &config.proxy_password)?;
persist_optional_secret(store, &config.id, CONNECTION_STRING_KEY, config.connection_string.as_deref())?;
}
@@ -105,6 +107,15 @@ pub fn load_connections_from_file(
needs_rewrite = true;
}
if config.proxy_password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, PROXY_PASSWORD_KEY)? {
config.proxy_password = secret;
}
} else {
store.set_secret(&config.id, PROXY_PASSWORD_KEY, &config.proxy_password)?;
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)?;
@@ -195,6 +206,7 @@ fn sanitize_connections(configs: &[ConnectionConfig]) -> Vec<ConnectionConfig> {
config.password.clear();
config.ssh_password.clear();
config.ssh_key_passphrase.clear();
config.proxy_password.clear();
config.connection_string = None;
config
})
@@ -211,7 +223,7 @@ mod tests {
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 crate::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
@@ -286,6 +298,12 @@ mod tests {
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: crate::models::connection::default_ssh_connect_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
sysdba: false,
connection_string: None,
+1
View File
@@ -9,6 +9,7 @@ pub mod mysql;
pub mod ob_oracle;
pub mod oracle_driver;
pub mod postgres;
pub mod proxy_tunnel;
pub mod redis_driver;
pub mod sqlite;
pub mod sqlserver;
+31 -1
View File
@@ -332,10 +332,12 @@ pub async fn list_triggers(conn: &OracleClient, schema: &str, table: &str) -> Re
pub async fn execute_query_with_schema(conn: &OracleClient, schema: &str, sql: &str) -> Result<QueryResult, String> {
let set_schema = format!("ALTER SESSION SET CURRENT_SCHEMA = \"{}\"", schema);
log::info!("[oracle][set-schema:start] schema={schema}");
conn.execute(&set_schema, &[]).await.map_err(|e| {
log::error!("[oracle] set current_schema failed: {e}");
e.to_string()
})?;
log::info!("[oracle][set-schema:done] schema={schema}");
execute_query(conn, sql).await
}
@@ -343,17 +345,31 @@ pub async fn execute_query(conn: &OracleClient, sql: &str) -> Result<QueryResult
let start = Instant::now();
let sql = sql.trim().trim_end_matches(';');
let explicit_limit = explicit_select_row_limit(sql);
log::info!("[oracle][execute:start] explicit_limit={:?} sql={}", explicit_limit, sql);
// Rewrite FETCH FIRST N ROWS ONLY → ROWNUM for Oracle 11g compatibility.
let sql = rewrite_fetch_first(sql);
log::info!("[oracle][execute:rewritten] sql={}", sql.as_ref());
if starts_with_executable_sql_keyword(sql.as_ref(), &["SELECT", "WITH", "SHOW", "DESCRIBE", "EXPLAIN"]) {
let capped_sql = cap_select_rows(sql.as_ref());
let query_limit = explicit_limit.unwrap_or(ORACLE_QUERY_LIMIT).min(ORACLE_QUERY_LIMIT);
log::info!(
"[oracle][query_with_limit:start] query_limit={} fetch_size=500 sql={}",
query_limit,
capped_sql.as_ref()
);
let result = conn.query_with_limit(capped_sql.as_ref(), &[], query_limit, 500).await.map_err(|e| {
log::error!("[oracle] execute_query SELECT failed: {e}");
e.to_string()
})?;
log::info!(
"[oracle][query_with_limit:done] column_count={} row_count={} has_more_rows={} elapsed_ms={}",
result.columns.len(),
result.rows.len(),
result.has_more_rows,
start.elapsed().as_millis()
);
let columns: Vec<String> = result.columns.iter().map(|c| c.name.clone()).collect();
let mut rows: Vec<Vec<serde_json::Value>> = result
.rows
@@ -369,11 +385,24 @@ pub async fn execute_query(conn: &OracleClient, sql: &str) -> Result<QueryResult
rows.truncate(crate::query::MAX_ROWS);
}
log::info!(
"[oracle][execute:done] column_count={} row_count={} truncated={} elapsed_ms={}",
columns.len(),
rows.len(),
truncated,
start.elapsed().as_millis()
);
Ok(QueryResult { columns, rows, affected_rows: 0, execution_time_ms: start.elapsed().as_millis(), truncated })
} else {
log::info!("[oracle][execute-non-select:start] sql={}", sql.as_ref());
match conn.execute(sql.as_ref(), &[]).await {
Ok(result) => {
let _ = conn.commit().await;
log::info!(
"[oracle][execute-non-select:done] affected_rows={} elapsed_ms={}",
result.rows_affected,
start.elapsed().as_millis()
);
Ok(QueryResult {
columns: vec![],
rows: vec![],
@@ -384,8 +413,9 @@ pub async fn execute_query(conn: &OracleClient, sql: &str) -> Result<QueryResult
}
Err(e) => {
let msg = e.to_string();
log::error!("[oracle][execute-non-select:error] {msg}");
if msg.contains("Server rejected") || msg.contains("closed the connection") {
Err("Operation failed (connection closed) — possibly a constraint violation (foreign key, unique, or check constraint).".to_string())
Err(format!("Operation failed (connection closed). Original driver error: {msg}"))
} else {
Err(msg)
}
+212
View File
@@ -0,0 +1,212 @@
use crate::models::connection::ProxyType;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use std::collections::HashMap;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
use tokio::time::{timeout, Duration};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Default)]
pub struct ProxyTunnelManager {
tunnels: tokio::sync::Mutex<HashMap<String, (JoinHandle<()>, u16)>>,
}
impl ProxyTunnelManager {
pub fn new() -> Self {
Self { tunnels: tokio::sync::Mutex::new(HashMap::new()) }
}
pub async fn start_tunnel(
&self,
connection_id: &str,
proxy_type: ProxyType,
proxy_host: &str,
proxy_port: u16,
proxy_username: &str,
proxy_password: &str,
remote_host: &str,
remote_port: u16,
) -> Result<u16, String> {
let local_port = portpicker::pick_unused_port().ok_or("No available port")?;
let listener = TcpListener::bind(("127.0.0.1", local_port))
.await
.map_err(|e| format!("Failed to bind proxy tunnel local port: {e}"))?;
let proxy = ProxyEndpoint {
proxy_type,
host: proxy_host.to_string(),
port: proxy_port,
username: proxy_username.to_string(),
password: proxy_password.to_string(),
};
let remote = RemoteEndpoint { host: remote_host.to_string(), port: remote_port };
let handle = tokio::spawn(proxy_forward_loop(listener, proxy, remote));
self.tunnels.lock().await.insert(connection_id.to_string(), (handle, local_port));
Ok(local_port)
}
pub async fn local_port(&self, connection_id: &str) -> Option<u16> {
self.tunnels.lock().await.get(connection_id).map(|(_, port)| *port)
}
pub async fn stop_tunnel(&self, connection_id: &str) {
if let Some((handle, _)) = self.tunnels.lock().await.remove(connection_id) {
handle.abort();
}
}
}
#[derive(Clone)]
struct ProxyEndpoint {
proxy_type: ProxyType,
host: String,
port: u16,
username: String,
password: String,
}
#[derive(Clone)]
struct RemoteEndpoint {
host: String,
port: u16,
}
async fn proxy_forward_loop(listener: TcpListener, proxy: ProxyEndpoint, remote: RemoteEndpoint) {
loop {
let (mut inbound, _) = match listener.accept().await {
Ok(pair) => pair,
Err(_) => break,
};
let proxy = proxy.clone();
let remote = remote.clone();
tokio::spawn(async move {
let Ok(mut outbound) = connect_via_proxy(&proxy, &remote).await else {
return;
};
let _ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound).await;
});
}
}
async fn connect_via_proxy(proxy: &ProxyEndpoint, remote: &RemoteEndpoint) -> Result<TcpStream, String> {
let stream = timeout(CONNECT_TIMEOUT, TcpStream::connect((proxy.host.as_str(), proxy.port)))
.await
.map_err(|_| "Proxy connection timed out".to_string())?
.map_err(|e| format!("Failed to connect proxy: {e}"))?;
match proxy.proxy_type {
ProxyType::Http => http_connect(stream, proxy, remote).await,
ProxyType::Socks5 => socks5_connect(stream, proxy, remote).await,
}
}
async fn http_connect(
mut stream: TcpStream,
proxy: &ProxyEndpoint,
remote: &RemoteEndpoint,
) -> Result<TcpStream, String> {
let target = format!("{}:{}", remote.host, remote.port);
let mut request = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n");
if !proxy.username.is_empty() || !proxy.password.is_empty() {
let token = BASE64.encode(format!("{}:{}", proxy.username, proxy.password));
request.push_str(&format!("Proxy-Authorization: Basic {token}\r\n"));
}
request.push_str("\r\n");
stream.write_all(request.as_bytes()).await.map_err(|e| format!("Failed to send CONNECT request: {e}"))?;
let mut response = Vec::new();
let mut buf = [0_u8; 1];
while !response.ends_with(b"\r\n\r\n") && response.len() < 8192 {
let n = stream.read(&mut buf).await.map_err(|e| format!("Failed to read CONNECT response: {e}"))?;
if n == 0 {
break;
}
response.push(buf[0]);
}
let text = String::from_utf8_lossy(&response);
if text.starts_with("HTTP/1.1 200") || text.starts_with("HTTP/1.0 200") {
Ok(stream)
} else {
let status = text.lines().next().unwrap_or("invalid proxy response");
Err(format!("HTTP proxy CONNECT failed: {status}"))
}
}
async fn socks5_connect(
mut stream: TcpStream,
proxy: &ProxyEndpoint,
remote: &RemoteEndpoint,
) -> Result<TcpStream, String> {
let wants_auth = !proxy.username.is_empty() || !proxy.password.is_empty();
let methods: &[u8] = if wants_auth { &[0x00, 0x02] } else { &[0x00] };
let mut hello = vec![0x05, methods.len() as u8];
hello.extend_from_slice(methods);
stream.write_all(&hello).await.map_err(|e| format!("Failed to send SOCKS greeting: {e}"))?;
let mut method = [0_u8; 2];
stream.read_exact(&mut method).await.map_err(|e| format!("Failed to read SOCKS greeting: {e}"))?;
if method[0] != 0x05 {
return Err("Invalid SOCKS proxy version".to_string());
}
match method[1] {
0x00 => {}
0x02 => socks5_authenticate(&mut stream, proxy).await?,
0xff => return Err("SOCKS proxy rejected supported authentication methods".to_string()),
other => return Err(format!("SOCKS proxy selected unsupported auth method: {other}")),
}
let host = remote.host.as_bytes();
if host.len() > u8::MAX as usize {
return Err("Remote host is too long for SOCKS5 domain address".to_string());
}
let mut req = vec![0x05, 0x01, 0x00, 0x03, host.len() as u8];
req.extend_from_slice(host);
req.extend_from_slice(&remote.port.to_be_bytes());
stream.write_all(&req).await.map_err(|e| format!("Failed to send SOCKS connect request: {e}"))?;
let mut head = [0_u8; 4];
stream.read_exact(&mut head).await.map_err(|e| format!("Failed to read SOCKS connect response: {e}"))?;
if head[0] != 0x05 {
return Err("Invalid SOCKS connect response version".to_string());
}
if head[1] != 0x00 {
return Err(format!("SOCKS proxy connect failed with code {}", head[1]));
}
let addr_len = match head[3] {
0x01 => 4,
0x03 => {
let mut len = [0_u8; 1];
stream.read_exact(&mut len).await.map_err(|e| format!("Failed to read SOCKS bound address length: {e}"))?;
len[0] as usize
}
0x04 => 16,
other => return Err(format!("Unsupported SOCKS bound address type: {other}")),
};
let mut discard = vec![0_u8; addr_len + 2];
stream.read_exact(&mut discard).await.map_err(|e| format!("Failed to read SOCKS bound address: {e}"))?;
Ok(stream)
}
async fn socks5_authenticate(stream: &mut TcpStream, proxy: &ProxyEndpoint) -> Result<(), String> {
let username = proxy.username.as_bytes();
let password = proxy.password.as_bytes();
if username.len() > u8::MAX as usize || password.len() > u8::MAX as usize {
return Err("SOCKS username or password is too long".to_string());
}
let mut req = vec![0x01, username.len() as u8];
req.extend_from_slice(username);
req.push(password.len() as u8);
req.extend_from_slice(password);
stream.write_all(&req).await.map_err(|e| format!("Failed to send SOCKS authentication: {e}"))?;
let mut res = [0_u8; 2];
stream.read_exact(&mut res).await.map_err(|e| format!("Failed to read SOCKS authentication response: {e}"))?;
if res == [0x01, 0x00] {
Ok(())
} else {
Err("SOCKS proxy authentication failed".to_string())
}
}
+58 -1
View File
@@ -38,6 +38,18 @@ pub struct ConnectionConfig {
#[serde(default = "default_ssh_connect_timeout_secs")]
pub ssh_connect_timeout_secs: u64,
#[serde(default)]
pub proxy_enabled: bool,
#[serde(default)]
pub proxy_type: ProxyType,
#[serde(default)]
pub proxy_host: String,
#[serde(default = "default_proxy_port")]
pub proxy_port: u16,
#[serde(default)]
pub proxy_username: String,
#[serde(default)]
pub proxy_password: String,
#[serde(default)]
pub ssl: bool,
#[serde(default)]
pub sysdba: bool,
@@ -60,6 +72,23 @@ pub fn default_ssh_connect_timeout_secs() -> u64 {
5
}
fn default_proxy_port() -> u16 {
1080
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ProxyType {
Socks5,
Http,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Socks5
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DatabaseType {
@@ -372,7 +401,7 @@ fn bracket_ipv6(host: &str) -> String {
#[cfg(test)]
mod tests {
use super::{default_ssh_connect_timeout_secs, ConnectionConfig, DatabaseType};
use super::{default_ssh_connect_timeout_secs, ConnectionConfig, DatabaseType, ProxyType};
fn mysql_config(username: &str, password: &str, database: Option<&str>) -> ConnectionConfig {
ConnectionConfig {
@@ -397,6 +426,12 @@ mod tests {
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: default_ssh_connect_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
sysdba: false,
connection_string: None,
@@ -431,6 +466,28 @@ mod tests {
assert_eq!(config.effective_ssh_connect_timeout_secs(), default_ssh_connect_timeout_secs());
}
#[test]
fn proxy_fields_default_for_legacy_config() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
"db_type": "mysql",
"host": "10.1.2.3",
"port": 3306,
"username": "root",
"password": "",
"database": null
}))
.unwrap();
assert_eq!(config.proxy_enabled, false);
assert_eq!(config.proxy_type, ProxyType::Socks5);
assert_eq!(config.proxy_host, "");
assert_eq!(config.proxy_port, 1080);
assert_eq!(config.proxy_username, "");
assert_eq!(config.proxy_password, "");
}
#[test]
fn ssh_connect_timeout_zero_uses_default() {
let mut config = mysql_config("root", "", None);
+4
View File
@@ -205,6 +205,7 @@ pub async fn do_execute(
let client = pool.client();
let schema = schema.map(|s| s.to_string());
drop(connections);
log::info!("[query][oracle:lock:start] schema={:?} sql={}", schema, sql);
let client = match cancel_token.as_ref() {
Some(token) => tokio::select! {
biased;
@@ -213,6 +214,7 @@ pub async fn do_execute(
},
None => client.lock().await,
};
log::info!("[query][oracle:lock:done] schema={:?}", schema);
if let Some(schema) = schema {
wait_for_query(cancel_token, db::oracle_driver::execute_query_with_schema(&*client, &schema, sql))
.await
@@ -635,9 +637,11 @@ async fn exec_tx_none_inner(
) -> Result<db::QueryResult, String> {
let mut total_affected: u64 = 0;
for (i, sql) in statements.iter().enumerate() {
log::info!("[query][tx-none:statement:start] index={} sql={}", i + 1, sql);
match do_execute(state, pool_key, sql, schema, None).await {
Ok(result) => {
total_affected += result.affected_rows;
log::info!("[query][tx-none:statement:done] index={} affected_rows={}", i + 1, result.affected_rows);
}
Err(e) => {
log::warn!("Statement {} failed (no transaction support): {}", i + 1, e);
+3
View File
@@ -397,6 +397,7 @@ impl Storage {
sanitized.password = String::new();
sanitized.ssh_password = String::new();
sanitized.ssh_key_passphrase = String::new();
sanitized.proxy_password = String::new();
sanitized.connection_string = None;
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
@@ -411,6 +412,7 @@ impl Storage {
persist_secret_in_tx(&mut tx, &config.id, "password", &config.password).await?;
persist_secret_in_tx(&mut tx, &config.id, "ssh_password", &config.ssh_password).await?;
persist_secret_in_tx(&mut tx, &config.id, "ssh_key_passphrase", &config.ssh_key_passphrase).await?;
persist_secret_in_tx(&mut tx, &config.id, "proxy_password", &config.proxy_password).await?;
if let Some(cs) = &config.connection_string {
persist_secret_in_tx(&mut tx, &config.id, "connection_string", cs).await?;
} else {
@@ -452,6 +454,7 @@ impl Storage {
config.password = self.get_secret(&id, "password").await?.unwrap_or_default();
config.ssh_password = self.get_secret(&id, "ssh_password").await?.unwrap_or_default();
config.ssh_key_passphrase = self.get_secret(&id, "ssh_key_passphrase").await?.unwrap_or_default();
config.proxy_password = self.get_secret(&id, "proxy_password").await?.unwrap_or_default();
config.connection_string = self.get_secret(&id, "connection_string").await?;
configs.push(config);
}
+16
View File
@@ -15,6 +15,12 @@ export interface ConnectionConfig {
database?: string;
url_params?: string;
ssh_enabled: boolean;
proxy_enabled?: boolean;
proxy_type?: "socks5" | "http";
proxy_host?: string;
proxy_port?: number;
proxy_username?: string;
proxy_password?: string;
ssl: boolean;
}
@@ -50,6 +56,7 @@ export async function loadConnections(): Promise<ConnectionConfig[]> {
const config: ConnectionConfig = JSON.parse(row.config_json);
config.id = row.id;
if (!config.password) config.password = getSecret(db, row.id, "password");
if (!config.proxy_password) config.proxy_password = getSecret(db, row.id, "proxy_password");
configs.push(config);
}
@@ -90,6 +97,12 @@ export async function addConnection(config: Omit<ConnectionConfig, "id">): Promi
ssh_key_path: "",
ssh_key_passphrase: "",
ssh_expose_lan: false,
proxy_enabled: config.proxy_enabled ?? false,
proxy_type: config.proxy_type ?? "socks5",
proxy_host: config.proxy_host ?? "",
proxy_port: config.proxy_port ?? 1080,
proxy_username: config.proxy_username ?? "",
proxy_password: "",
ssl: config.ssl ?? false,
sysdba: false,
connection_string: null,
@@ -101,6 +114,9 @@ export async function addConnection(config: Omit<ConnectionConfig, "id">): Promi
if (config.password) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, "password", config.password);
}
if (config.proxy_password) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, "proxy_password", config.proxy_password);
}
});
insert();
db.close();
+123 -5
View File
@@ -1,4 +1,5 @@
import type { ConnectionConfig } from "./connections.js";
import { createServer, connect as netConnect, type Server, type Socket } from "node:net";
export interface TableInfo {
name: string;
@@ -31,6 +32,7 @@ interface PoolEntry {
}
const pools = new Map<string, PoolEntry>();
const proxyTunnels = new Map<string, { server: Server; port: number }>();
function poolKey(config: ConnectionConfig): string {
return `${config.id}:${config.database || ""}`;
@@ -59,8 +61,9 @@ async function getPgPool(config: ConnectionConfig): Promise<import("pg").Pool> {
}
const pg = await import("pg");
const endpoint = await connectionEndpoint(config);
const pool = new pg.default.Pool({
connectionString: buildConnectionUrl(config),
connectionString: buildConnectionUrl(config, endpoint),
max: 3,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 10_000,
@@ -81,8 +84,9 @@ async function getMysqlPool(config: ConnectionConfig): Promise<import("mysql2/pr
}
const mysql = await import("mysql2/promise");
const endpoint = await connectionEndpoint(config);
const pool = mysql.default.createPool({
uri: buildConnectionUrl(config),
uri: buildConnectionUrl(config, endpoint),
connectionLimit: 3,
idleTimeout: 30_000,
connectTimeout: 10_000,
@@ -93,14 +97,128 @@ async function getMysqlPool(config: ConnectionConfig): Promise<import("mysql2/pr
return pool;
}
function buildConnectionUrl(config: ConnectionConfig): string {
async function connectionEndpoint(config: ConnectionConfig): Promise<{ host: string; port: number }> {
if (!config.proxy_enabled || !config.proxy_host) return { host: config.host, port: config.port };
const existing = proxyTunnels.get(config.id);
if (existing) return { host: "127.0.0.1", port: existing.port };
const server = createServer((inbound) => {
connectViaProxy(config)
.then((outbound) => {
inbound.pipe(outbound);
outbound.pipe(inbound);
})
.catch(() => inbound.destroy());
});
const port = await new Promise<number>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (address && typeof address === "object") resolve(address.port);
else reject(new Error("Failed to bind proxy tunnel"));
});
});
proxyTunnels.set(config.id, { server, port });
return { host: "127.0.0.1", port };
}
function buildConnectionUrl(config: ConnectionConfig, endpoint: { host: string; port: number }): string {
const db = config.database || "";
const params = config.url_params || "";
const suffix = params ? `?${params}` : "";
if (isMysqlType(config.db_type)) {
return `mysql://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${config.host}:${config.port}/${db}${suffix}`;
return `mysql://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${endpoint.host}:${endpoint.port}/${db}${suffix}`;
}
return `postgres://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${config.host}:${config.port}/${db}${suffix}`;
return `postgres://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${endpoint.host}:${endpoint.port}/${db}${suffix}`;
}
function connectViaProxy(config: ConnectionConfig): Promise<Socket> {
return new Promise((resolve, reject) => {
const socket = netConnect(config.proxy_port || 1080, config.proxy_host || "127.0.0.1");
socket.once("error", reject);
socket.once("connect", () => {
if ((config.proxy_type || "socks5") === "http") {
httpConnect(socket, config, resolve, reject);
} else {
socks5Connect(socket, config, resolve, reject);
}
});
});
}
function httpConnect(socket: Socket, config: ConnectionConfig, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
const target = `${config.host}:${config.port}`;
const lines = [`CONNECT ${target} HTTP/1.1`, `Host: ${target}`];
if (config.proxy_username || config.proxy_password) {
const token = Buffer.from(`${config.proxy_username || ""}:${config.proxy_password || ""}`).toString("base64");
lines.push(`Proxy-Authorization: Basic ${token}`);
}
socket.write(`${lines.join("\r\n")}\r\n\r\n`);
let buffer = Buffer.alloc(0);
socket.on("data", function onData(chunk: Buffer) {
buffer = Buffer.concat([buffer, chunk]);
const end = buffer.indexOf("\r\n\r\n");
if (end < 0) return;
socket.off("data", onData);
const head = buffer.subarray(0, end).toString("utf8");
if (!/^HTTP\/1\.[01] 200\b/.test(head)) {
reject(new Error(`HTTP proxy CONNECT failed: ${head.split("\r\n")[0] || "invalid response"}`));
socket.destroy();
return;
}
const rest = buffer.subarray(end + 4);
if (rest.length) socket.unshift(rest);
resolve(socket);
});
}
function socks5Connect(socket: Socket, config: ConnectionConfig, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
const wantsAuth = !!(config.proxy_username || config.proxy_password);
socket.write(Buffer.from(wantsAuth ? [0x05, 0x02, 0x00, 0x02] : [0x05, 0x01, 0x00]));
socket.once("data", (method) => {
if (method.length < 2 || method[0] !== 0x05) {
reject(new Error("Invalid SOCKS greeting"));
socket.destroy();
return;
}
if (method[1] === 0x02) {
const user = Buffer.from(config.proxy_username || "");
const pass = Buffer.from(config.proxy_password || "");
socket.write(Buffer.concat([Buffer.from([0x01, user.length]), user, Buffer.from([pass.length]), pass]));
socket.once("data", (auth) => {
if (auth.length < 2 || auth[1] !== 0x00) {
reject(new Error("SOCKS proxy authentication failed"));
socket.destroy();
return;
}
sendSocksConnect(socket, config, resolve, reject);
});
} else if (method[1] === 0x00) {
sendSocksConnect(socket, config, resolve, reject);
} else {
reject(new Error("SOCKS proxy rejected authentication methods"));
socket.destroy();
}
});
}
function sendSocksConnect(socket: Socket, config: ConnectionConfig, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
const host = Buffer.from(config.host);
socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00, 0x03, host.length]), host, portBytes(config.port)]));
socket.once("data", (res) => {
if (res.length < 4 || res[0] !== 0x05 || res[1] !== 0x00) {
reject(new Error(`SOCKS proxy connect failed with code ${res[1] ?? "unknown"}`));
socket.destroy();
return;
}
resolve(socket);
});
}
function portBytes(port: number): Buffer {
const buf = Buffer.alloc(2);
buf.writeUInt16BE(port);
return buf;
}
function isMysqlType(dbType: string): boolean {
+4
View File
@@ -137,6 +137,9 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
if config.ssh_enabled && !config.ssh_host.is_empty() {
state.tunnels.stop_tunnel(&tunnel_id).await;
}
if config.proxy_enabled && !config.proxy_host.is_empty() {
state.proxy_tunnels.stop_tunnel(&tunnel_id).await;
}
result
}
@@ -268,5 +271,6 @@ pub async fn disconnect_db(state: State<'_, Arc<AppState>>, connection_id: Strin
drop(conns);
state.configs.write().await.remove(&connection_id);
state.tunnels.stop_tunnel(&connection_id).await;
state.proxy_tunnels.stop_tunnel(&connection_id).await;
Ok(())
}
+22 -1
View File
@@ -37,8 +37,29 @@ pub async fn execute_multi(
let registered_query =
execution_id.as_ref().filter(|id| !id.trim().is_empty()).map(|id| state.running_queries.register(id.clone()));
let cancel_token = registered_query.as_ref().map(|query| query.token());
let trace_id = execution_id.as_deref().unwrap_or("no-execution-id");
log::info!(
"[query][execute_multi:start] trace_id={} connection_id={} database={} schema={:?} sql={}",
trace_id,
connection_id,
database,
schema,
sql
);
dbx_core::query::execute_multi_core(&state, &connection_id, &database, &sql, schema.as_deref(), cancel_token).await
let result =
dbx_core::query::execute_multi_core(&state, &connection_id, &database, &sql, schema.as_deref(), cancel_token)
.await;
match &result {
Ok(results) => log::info!(
"[query][execute_multi:done] trace_id={} result_count={} row_counts={:?}",
trace_id,
results.len(),
results.iter().map(|result| result.rows.len()).collect::<Vec<_>>()
),
Err(error) => log::error!("[query][execute_multi:error] trace_id={} error={}", trace_id, error),
}
result
}
#[tauri::command]
+8 -1
View File
@@ -88,6 +88,7 @@ pub async fn disconnect_db(
app.configs.write().await.remove(&body.connection_id);
app.tunnels.stop_tunnel(&body.connection_id).await;
app.proxy_tunnels.stop_tunnel(&body.connection_id).await;
Ok(Json(()))
}
@@ -121,7 +122,7 @@ mod tests {
use axum::extract::State;
use axum::Json;
use dbx_core::connection::{AppState, PoolKind};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use dbx_core::storage::Storage;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -150,6 +151,12 @@ mod tests {
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: dbx_core::models::connection::default_ssh_connect_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
sysdba: false,
connection_string: None,
+89 -3
View File
@@ -22,7 +22,7 @@ type DbOption = { value: string; label: string };
type DbCategory = { key: string; title: string; options: DbOption[] };
type DialogStep = "select" | "config";
type DbPickerView = "icon" | "list";
type ConfigTab = "connection" | "ssh";
type ConfigTab = "connection" | "ssh" | "proxy";
const { t } = useI18n();
const { toast } = useToast();
@@ -67,6 +67,12 @@ const defaultForm = (): Omit<ConnectionConfig, "id"> => ({
ssh_key_passphrase: "",
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
proxy_enabled: false,
proxy_type: "socks5",
proxy_host: "",
proxy_port: 1080,
proxy_username: "",
proxy_password: "",
ssl: false,
connection_string: undefined,
jdbc_driver_class: undefined,
@@ -264,6 +270,12 @@ watch(
ssh_key_passphrase: config.ssh_key_passphrase || "",
ssh_expose_lan: config.ssh_expose_lan || false,
ssh_connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
proxy_enabled: config.proxy_enabled || false,
proxy_type: config.proxy_type || "socks5",
proxy_host: config.proxy_host || "",
proxy_port: config.proxy_port || 1080,
proxy_username: config.proxy_username || "",
proxy_password: config.proxy_password || "",
ssl: config.ssl || false,
connection_string: config.connection_string,
jdbc_driver_class: config.jdbc_driver_class,
@@ -408,6 +420,9 @@ const hasDbPickerResults = computed(() => filteredDbCategories.value.some((categ
const selectedDbIcon = computed(() => iconTypeMap[selectedType.value] || selectedProfile().icon || selectedType.value);
const isJdbcConnection = computed(() => form.value.db_type === "jdbc");
const canUseSsh = computed(() => form.value.db_type !== "sqlite" && form.value.db_type !== "jdbc");
const canUseProxy = computed(
() => form.value.db_type !== "sqlite" && form.value.db_type !== "duckdb" && form.value.db_type !== "jdbc",
);
const testResultMessage = computed(() => {
if (!testResult.value) return "";
return testResult.value.ok ? t("connection.testSuccess") : testResult.value.message;
@@ -456,6 +471,8 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
const config: ConnectionConfig = { ...form.value, id };
const sshTimeout = Number(config.ssh_connect_timeout_secs);
config.ssh_connect_timeout_secs = Number.isFinite(sshTimeout) && sshTimeout > 0 ? sshTimeout : 5;
const proxyPort = Number(config.proxy_port);
config.proxy_port = Number.isFinite(proxyPort) && proxyPort > 0 ? proxyPort : 1080;
if (config.db_type === "mongodb" && !mongoUseUrl.value) {
config.connection_string = undefined;
}
@@ -534,6 +551,12 @@ watch(canUseSsh, (value) => {
}
});
watch(canUseProxy, (value) => {
if (!value && configTab.value === "proxy") {
configTab.value = "connection";
}
});
async function save() {
if (isSaving.value) return;
isSaving.value = true;
@@ -778,10 +801,11 @@ function openExternalUrl(url: string) {
<template v-else>
<div class="space-y-3">
<Tabs v-model="configTab" class="min-h-0">
<div v-if="canUseSsh" class="flex items-center justify-between border-b pb-2">
<div v-if="canUseSsh || canUseProxy" class="flex items-center justify-between border-b pb-2">
<TabsList>
<TabsTrigger value="connection">{{ t("connection.basicTab") }}</TabsTrigger>
<TabsTrigger value="ssh">{{ t("connection.sshTunnel") }}</TabsTrigger>
<TabsTrigger v-if="canUseSsh" value="ssh">{{ t("connection.sshTunnel") }}</TabsTrigger>
<TabsTrigger v-if="canUseProxy" value="proxy">{{ t("connection.proxy") }}</TabsTrigger>
</TabsList>
</div>
@@ -1202,6 +1226,68 @@ function openExternalUrl(url: string) {
</div>
</div>
</TabsContent>
<TabsContent v-if="canUseProxy" value="proxy" class="m-0">
<div class="grid gap-4 py-4 pr-2 max-h-[65vh] overflow-y-auto">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxy") }}</Label>
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="form.proxy_enabled" class="mr-0" />
<span class="text-xs text-muted-foreground">{{ t("connection.proxyEnable") }}</span>
</label>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyType") }}</Label>
<Select
:model-value="form.proxy_type || 'socks5'"
:disabled="!form.proxy_enabled"
@update:model-value="(value: any) => (form.proxy_type = value)"
>
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="socks5">SOCKS5</SelectItem>
<SelectItem value="http">HTTP CONNECT</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyHost") }}</Label>
<Input
v-model="form.proxy_host"
class="col-span-2"
placeholder="127.0.0.1"
:disabled="!form.proxy_enabled"
/>
<Input
v-model.number="form.proxy_port"
type="number"
class="col-span-1"
:disabled="!form.proxy_enabled"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyUsername") }}</Label>
<Input
v-model="form.proxy_username"
class="col-span-3"
:placeholder="t('connection.proxyUsernamePlaceholder')"
:disabled="!form.proxy_enabled"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyPassword") }}</Label>
<Input
v-model="form.proxy_password"
type="password"
class="col-span-3"
:placeholder="t('connection.proxyPasswordPlaceholder')"
:disabled="!form.proxy_enabled"
/>
</div>
</div>
</TabsContent>
</Tabs>
</div>
+25
View File
@@ -173,6 +173,8 @@ const tempApiKey = ref(settings.aiConfig.apiKey);
const tempEndpoint = ref(settings.aiConfig.endpoint);
const tempModel = ref(settings.aiConfig.model);
const tempApiStyle = ref<AiApiStyle>(settings.aiConfig.apiStyle || "completions");
const tempProxyEnabled = ref(!!settings.aiConfig.proxyEnabled);
const tempProxyUrl = ref(settings.aiConfig.proxyUrl || "");
const providerDefaults: Record<AiProvider, { endpoint: string; model: string }> = {
claude: { endpoint: "https://api.anthropic.com/v1/messages", model: "claude-sonnet-4-20250514" },
@@ -213,6 +215,8 @@ function openSettings() {
tempEndpoint.value = settings.aiConfig.endpoint;
tempModel.value = settings.aiConfig.model;
tempApiStyle.value = settings.aiConfig.apiStyle || "completions";
tempProxyEnabled.value = !!settings.aiConfig.proxyEnabled;
tempProxyUrl.value = settings.aiConfig.proxyUrl || "";
showSettings.value = true;
}
@@ -223,6 +227,8 @@ function saveSettings() {
endpoint: tempEndpoint.value,
model: tempModel.value,
apiStyle: tempApiStyle.value,
proxyEnabled: tempProxyEnabled.value,
proxyUrl: tempProxyUrl.value,
});
showSettings.value = false;
}
@@ -242,6 +248,8 @@ async function testAiConnection() {
endpoint: tempEndpoint.value,
model: tempModel.value,
apiStyle: tempApiStyle.value,
proxyEnabled: tempProxyEnabled.value,
proxyUrl: tempProxyUrl.value,
});
testResult.value = "success";
} catch (e: any) {
@@ -799,6 +807,23 @@ function formatInlineText(text: string): string {
>
</div>
</div>
<div class="grid grid-cols-3 items-center gap-3">
<Label class="text-right text-xs">{{ t("ai.proxy") }}</Label>
<label class="col-span-2 flex items-center gap-2 text-xs text-muted-foreground">
<input v-model="tempProxyEnabled" type="checkbox" class="h-4 w-4 shrink-0 accent-primary" />
{{ t("ai.proxyEnable") }}
</label>
</div>
<div class="grid grid-cols-3 items-center gap-3">
<Label class="text-right text-xs">{{ t("ai.proxyUrl") }}</Label>
<Input
v-model="tempProxyUrl"
autocomplete="off"
class="col-span-2 h-8 text-xs"
placeholder="socks5://127.0.0.1:7890"
:disabled="!tempProxyEnabled"
/>
</div>
</div>
<DialogFooter class="flex items-center gap-2">
<div class="flex-1 flex items-center gap-2">
+119 -56
View File
@@ -60,8 +60,10 @@ import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import type { QueryResult, ColumnInfo, DatabaseType } from "@/types/database";
import * as api from "@/lib/api";
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/tableSelectSql";
import { isHiddenGridColumn, usesSyntheticRowIdKey } from "@/lib/tableEditing";
import { formatGridSqlLiteral } from "@/lib/dataGridSql";
import { matchesRowStatusFilter, type RowStatus, type RowStatusFilter } from "@/lib/gridRowStatus";
import { displayCellValue, type CellValue } from "@/lib/cellValue";
import { useToast } from "@/composables/useToast";
import { useDataGridExport } from "@/composables/useDataGridExport";
@@ -726,11 +728,25 @@ const isApplyingWhere = ref(false);
const rowStatusFilter = ref<RowStatusFilter>("all");
const gridRef = ref<HTMLDivElement>();
const headerRef = ref<HTMLDivElement>();
const visibleColumnIndexes = computed(() =>
props.result.columns
.map((column, index) => ({ column, index }))
.filter(({ column }) => !isHiddenGridColumn(props.databaseType, column, props.tableMeta?.primaryKeys ?? []))
.map(({ index }) => index),
);
const visibleColumns = computed(() => visibleColumnIndexes.value.map((index) => props.result.columns[index]));
const visibleRows = computed(() =>
props.result.rows.map((row) => visibleColumnIndexes.value.map((index) => row[index])),
);
const firstVisibleColumnIndex = computed(() => visibleColumnIndexes.value[0] ?? 0);
function actualColumnIndex(visibleColumnIndex: number): number {
return visibleColumnIndexes.value[visibleColumnIndex] ?? visibleColumnIndex;
}
// --- Column resize composable ---
const { initColumnWidths, onResizeStart, autoFitColumn, columnVars, getIsResizing } = useDataGridColumnResize({
columns: computed(() => props.result.columns),
rows: computed(() => props.result.rows),
columns: visibleColumns,
rows: visibleRows,
gridRef,
});
function syncHeaderScroll(e: Event) {
@@ -740,7 +756,7 @@ function syncHeaderScroll(e: Event) {
}
initColumnWidths();
watch(() => props.result.columns.length, initColumnWidths);
watch(() => visibleColumns.value.length, initColumnWidths);
watch(
() => props.result,
() => {
@@ -755,6 +771,9 @@ const currentPage = ref(1);
const isFullPage = computed(() => props.result.rows.length >= pageSize.value);
const isResultsContext = computed(() => props.context === "results");
const canUseWhereSearch = computed(() => !!props.tableMeta && !!props.onExecuteSql && !isResultsContext.value);
const tableUsesSyntheticRowId = computed(() =>
usesSyntheticRowIdKey(props.databaseType, props.tableMeta?.primaryKeys ?? []),
);
const clientSearchText = computed(() => (searchText.value.trim() ? searchText.value : ""));
watch(clientSearchText, (value) => {
clearTimeout(_searchTimer);
@@ -799,7 +818,6 @@ function changePageSize(size: number) {
}
// --- Editing (composable) ---
type CellValue = string | number | boolean | null;
interface RowItem {
id: number;
@@ -826,6 +844,7 @@ const editor = useDataGridEditor({
whereFilterInput,
orderByInput,
rowStatusFilter,
initialEditColumn: firstVisibleColumnIndex,
getRowItem,
emit,
});
@@ -936,6 +955,27 @@ function getRowItem(rowId: number): RowItem | undefined {
return displayItems.value.find((item) => item.id === rowId);
}
function visibleRowData(row: CellValue[]): CellValue[] {
return visibleColumnIndexes.value.map((index) => row[index]);
}
function visibleDirtyColumns(row: boolean[]): boolean[] {
return visibleColumnIndexes.value.map((index) => row[index] ?? false);
}
const visibleDisplayItems = computed<RowItem[]>(() =>
displayItems.value.map((item) => ({
...item,
data: visibleRowData(item.data),
isDirtyCol: visibleDirtyColumns(item.isDirtyCol),
})),
);
const exportContextCell = computed(() => {
if (!contextCell.value) return null;
const visibleCol = visibleColumnIndexes.value.indexOf(contextCell.value.col);
return { ...contextCell.value, col: visibleCol };
});
const deleteRowDetails = computed(() =>
props.tableMeta?.tableName
? t("dangerDialog.deleteRowDetails", { table: props.tableMeta.tableName })
@@ -961,8 +1001,8 @@ const isErrorResult = computed(
const errorMessage = computed(() => (isErrorResult.value ? String(props.result.rows[0]?.[0] ?? "") : ""));
// --- Selection composable ---
const selection = useDataGridSelection({
columns: computed(() => props.result.columns),
displayItems,
columns: visibleColumns,
displayItems: visibleDisplayItems,
editingCell,
showTranspose,
transposeRowIndex,
@@ -1001,7 +1041,7 @@ const activeCellDetail = computed(() => {
const column = props.result.columns[cell.col];
if (!item || !column) return null;
const value = item.data[cell.col] ?? null;
const rawValue = formatCell(value);
const rawValue = displayCellValue(value);
const valueText = value === null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
const trimmed = valueText.trim();
const maybeJson = typeof value === "string" && (trimmed.startsWith("{") || trimmed.startsWith("["));
@@ -1197,6 +1237,7 @@ async function applyOrderBySearch() {
orderBy: orderByClause,
limit: pageSize.value,
whereInput: whereFilterInput.value.trim() || undefined,
includeRowId: tableUsesSyntheticRowId.value,
});
await props.onExecuteSql(sql);
} catch (e: any) {
@@ -1222,6 +1263,7 @@ async function applyWhereFilter() {
(sortCol.value ? `${quoteIdent(sortCol.value)} ${sortDir.value.toUpperCase()}` : undefined),
limit: pageSize.value,
whereInput: whereFilterInput.value.trim() || undefined,
includeRowId: tableUsesSyntheticRowId.value,
});
await props.onExecuteSql(sql);
} catch (e: any) {
@@ -1286,8 +1328,8 @@ const {
exportXlsx,
copySql,
} = useDataGridExport({
columns: computed(() => props.result.columns),
displayItems,
columns: visibleColumns,
displayItems: visibleDisplayItems,
sql: computed(() => props.sql),
tableMeta: computed(() =>
props.tableMeta ? { schema: props.tableMeta.schema, tableName: props.tableMeta.tableName } : undefined,
@@ -1295,9 +1337,8 @@ const {
databaseType: computed(() => props.databaseType),
hasCellSelection,
selectedCells,
contextCell,
getRowItem,
formatCell,
contextCell: exportContextCell,
getRowItem: (rowId: number) => visibleDisplayItems.value.find((item) => item.id === rowId),
quoteIdent,
escapeVal,
});
@@ -1334,9 +1375,9 @@ async function pasteClipboardIntoSelection() {
const item = displayItems.value[start.rowIndex + rowOffset];
if (!item) return;
row.forEach((value, colOffset) => {
const col = start.colIndex + colOffset;
if (col >= props.result.columns.length) return;
applyCellValue(item.id, col, value);
const visibleCol = start.colIndex + colOffset;
if (visibleCol >= visibleColumns.value.length) return;
applyCellValue(item.id, actualColumnIndex(visibleCol), value);
});
});
toast(t("grid.pasted"));
@@ -1349,8 +1390,8 @@ function cutSelection() {
for (let rowIndex = range.startRow; rowIndex <= range.endRow; rowIndex++) {
const item = displayItems.value[rowIndex];
if (!item) continue;
for (let col = range.startCol; col <= range.endCol; col++) {
applyCellValue(item.id, col, null);
for (let visibleCol = range.startCol; visibleCol <= range.endCol; visibleCol++) {
applyCellValue(item.id, actualColumnIndex(visibleCol), null);
}
}
}
@@ -1377,8 +1418,10 @@ async function onGridKeydown(event: KeyboardEvent) {
}
function copyDetailValue() {
if (!activeCellDetail.value) return;
copyText(activeCellDetail.value.rawValue);
const detail = activeCellDetail.value;
if (!detail) return;
const text = detail.value === null ? "" : displayCellValue(detail.value);
copyText(text);
}
function copyDetailColumnName() {
@@ -1398,13 +1441,16 @@ const transposeData = computed(() => {
if (transposeRowIndex.value === null) return null;
const item = displayItems.value[transposeRowIndex.value];
if (!item) return null;
return props.result.columns.map((col, i) => ({
column: col,
type: columnTypeMap.value.get(col) || "",
value: item.data[i],
display: formatCell(item.data[i]),
isNull: item.data[i] === null,
}));
return visibleColumnIndexes.value.map((columnIndex) => {
const col = props.result.columns[columnIndex];
return {
column: col,
type: columnTypeMap.value.get(col) || "",
value: item.data[columnIndex],
display: formatCell(item.data[columnIndex]),
isNull: item.data[columnIndex] === null,
};
});
});
function openTranspose(rowIndex: number) {
@@ -1438,10 +1484,10 @@ watch(
);
// --- Context menu handlers ---
function onCellContext(rowId: number, rowIndex: number, colIdx: number) {
function onCellContext(rowId: number, rowIndex: number, colIdx: number, visibleColIdx: number) {
contextCell.value = { rowId, rowIndex, col: colIdx };
if (!cellIsSelected(rowIndex, colIdx)) {
selectSingleCell(rowIndex, colIdx);
if (!cellIsSelected(rowIndex, visibleColIdx)) {
selectSingleCell(rowIndex, visibleColIdx);
}
}
@@ -1855,44 +1901,58 @@ defineExpose({
>
#
</div>
<Tooltip v-for="(col, colIdx) in result.columns" :key="`${col}-${colIdx}`">
<Tooltip v-for="(col, colIdx) in visibleColumns" :key="`${col}-${actualColumnIndex(colIdx)}`">
<TooltipTrigger as-child>
<div
class="shrink-0 px-2 py-1.5 border-r border-border whitespace-nowrap hover:bg-accent/60 select-none relative overflow-hidden"
:style="{ width: `var(--col-w-${colIdx})` }"
>
<span class="flex min-w-0 items-center gap-1 overflow-hidden">
<span class="min-w-0 flex-1 truncate cursor-pointer" @click="toggleSort(col, colIdx)">{{
col
}}</span>
<span
class="min-w-0 flex-1 truncate cursor-pointer"
@click="toggleSort(col, actualColumnIndex(colIdx))"
>
{{ col }}
</span>
<button
type="button"
class="flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
:class="
sortCol === col && sortColIndex === colIdx ? 'text-primary opacity-100' : 'opacity-80'
sortCol === col && sortColIndex === actualColumnIndex(colIdx)
? 'text-primary opacity-100'
: 'opacity-80'
"
:title="t('grid.sort')"
@click.stop="toggleSort(col, colIdx)"
@click.stop="toggleSort(col, actualColumnIndex(colIdx))"
>
<ArrowUp
v-if="sortCol === col && sortColIndex === colIdx && sortDir === 'asc'"
v-if="sortCol === col && sortColIndex === actualColumnIndex(colIdx) && sortDir === 'asc'"
class="h-3 w-3 shrink-0"
/>
<ArrowDown
v-else-if="sortCol === col && sortColIndex === colIdx && sortDir === 'desc'"
v-else-if="
sortCol === col && sortColIndex === actualColumnIndex(colIdx) && sortDir === 'desc'
"
class="h-3 w-3 shrink-0"
/>
<ArrowUpDown v-else class="h-3 w-3 shrink-0" />
</button>
<Popover
:open="localFilterOpenColumn === colIdx"
@update:open="(value: boolean) => (value ? openLocalFilter(colIdx) : closeLocalFilter())"
:open="localFilterOpenColumn === actualColumnIndex(colIdx)"
@update:open="
(value: boolean) =>
value ? openLocalFilter(actualColumnIndex(colIdx)) : closeLocalFilter()
"
>
<PopoverTrigger as-child>
<button
type="button"
class="flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
:class="localFilterActive(colIdx) ? 'text-primary opacity-100' : 'opacity-80'"
:class="
localFilterActive(actualColumnIndex(colIdx))
? 'text-primary opacity-100'
: 'opacity-80'
"
:title="t('grid.localFilter')"
@click.stop
>
@@ -1993,7 +2053,7 @@ defineExpose({
variant="ghost"
size="sm"
class="h-7 px-2 text-xs text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-700 dark:hover:bg-slate-100 dark:hover:text-slate-900"
@click="clearLocalFilter(colIdx)"
@click="clearLocalFilter(actualColumnIndex(colIdx))"
>
{{ t("grid.clearFilter") }}
</Button>
@@ -2099,24 +2159,24 @@ defineExpose({
{{ index + 1 }}
</div>
<div
v-for="(cell, colIdx) in item.data"
:key="colIdx"
v-for="(actualColIdx, visibleColIdx) in visibleColumnIndexes"
:key="actualColIdx"
class="group/cell shrink-0 px-3 py-1 border-r border-border whitespace-nowrap overflow-hidden text-ellipsis relative select-none"
:style="{ width: `var(--col-w-${colIdx})` }"
:style="{ width: `var(--col-w-${visibleColIdx})` }"
:class="{
'text-muted-foreground italic': isNull(cell),
'bg-yellow-500/10': item.isDirtyCol[colIdx],
'cell-selected': cellIsSelected(index, colIdx),
'tabular-nums': typeof cell === 'number',
'text-muted-foreground italic': isNull(item.data[actualColIdx]),
'bg-yellow-500/10': item.isDirtyCol[actualColIdx],
'cell-selected': cellIsSelected(index, visibleColIdx),
'tabular-nums': typeof item.data[actualColIdx] === 'number',
'cursor-text hover:bg-accent/50': editable && !item.isDeleted,
'line-through': item.isDeleted,
}"
@mousedown="beginCellSelection(index, colIdx, $event)"
@mouseenter="extendCellSelection(index, colIdx)"
@dblclick="editable && !item.isDeleted && startEdit(item.id, colIdx)"
@contextmenu="onCellContext(item.id, index, colIdx)"
@mousedown="beginCellSelection(index, visibleColIdx, $event)"
@mouseenter="extendCellSelection(index, visibleColIdx)"
@dblclick="editable && !item.isDeleted && startEdit(item.id, actualColIdx)"
@contextmenu="onCellContext(item.id, index, actualColIdx, visibleColIdx)"
>
<template v-if="editingCell?.rowId === item.id && editingCell?.col === colIdx">
<template v-if="editingCell?.rowId === item.id && editingCell?.col === actualColIdx">
<input
v-model="editValue"
autocapitalize="off"
@@ -2129,12 +2189,12 @@ defineExpose({
/>
</template>
<template v-else>
{{ formatCell(cell) }}
{{ formatCell(item.data[actualColIdx]) }}
<button
class="absolute right-0.5 top-0.5 hidden h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground group-hover/cell:flex"
:title="t('grid.cellDetails')"
@mousedown.stop
@click.stop="showCellDetails(index, colIdx)"
@click.stop="showCellDetails(index, actualColIdx)"
>
<Info class="h-3 w-3" />
</button>
@@ -2267,7 +2327,8 @@ defineExpose({
<div class="text-muted-foreground">{{ t("grid.formattedJson") }}</div>
<pre
class="max-h-72 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words"
>{{ activeCellDetail.formattedJson }}</pre
>
{{ activeCellDetail.formattedJson }}</pre
>
</div>
</div>
@@ -2559,9 +2620,11 @@ defineExpose({
color: oklch(0.6 0.15 250);
font-weight: 600;
}
.ddl-code :deep(.ddl-ident) {
color: oklch(0.65 0.15 150);
}
.ddl-code :deep(.ddl-str) {
color: oklch(0.65 0.15 50);
}
+11 -2
View File
@@ -5,7 +5,14 @@ import { Search, X, ListFilter, Check, FolderPlus } from "lucide-vue-next";
import { useConnectionStore } from "@/stores/connectionStore";
import type { TreeNode } from "@/types/database";
import { matchSidebarLabel } from "@/lib/sidebarSearch";
import { flattenTree, shouldVirtualizeFlatTree, type FlatTreeNode } from "@/composables/useFlatTree";
import {
SIDEBAR_TREE_ROW_HEIGHT,
SIDEBAR_TREE_PRERENDER_COUNT,
SIDEBAR_TREE_SCROLL_BUFFER,
flattenTree,
shouldVirtualizeFlatTree,
type FlatTreeNode,
} from "@/composables/useFlatTree";
import TreeItem from "./TreeItem.vue";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import { RecycleScroller } from "vue-virtual-scroller";
@@ -242,7 +249,9 @@ function onSearchToggle(node: TreeNode) {
v-if="flatNodes.length > 0 && useVirtualTree"
class="min-h-0 flex-1 overflow-y-auto"
:items="flatNodes"
:item-size="28"
:item-size="SIDEBAR_TREE_ROW_HEIGHT"
:buffer="SIDEBAR_TREE_SCROLL_BUFFER"
:prerender="SIDEBAR_TREE_PRERENDER_COUNT"
key-field="id"
type-field="type"
flow-mode
+52 -16
View File
@@ -66,7 +66,12 @@ import {
buildExportPageSql,
type ExportedTableSql,
} from "@/lib/databaseExport";
import { qualifiedTableName as buildQualifiedTableName, quoteTableIdentifier } from "@/lib/tableSelectSql";
import {
buildTableSelectSql,
qualifiedTableName as buildQualifiedTableName,
quoteTableIdentifier,
} from "@/lib/tableSelectSql";
import { editablePrimaryKeys, usesSyntheticRowIdKey } from "@/lib/tableEditing";
import {
SQL_FILE_UNSUPPORTED_TYPES,
DIAGRAM_SUPPORTED_TYPES,
@@ -346,30 +351,58 @@ async function openData() {
const node = props.node;
if (!(node.type === "table" || node.type === "view") || !node.connectionId || !node.database) return;
const config = connectionStore.getConfig(node.connectionId);
const traceId = uuid().slice(0, 8);
const startedAt = performance.now();
const elapsed = () => `${Math.round(performance.now() - startedAt)}ms`;
console.info("[DBX][openData:start]", {
traceId,
type: node.type,
connectionId: node.connectionId,
database: node.database,
schema: node.schema,
table: node.label,
dbType: config?.db_type,
});
const tabId = queryStore.createTab(node.connectionId, node.database, node.label, "data");
console.info("[DBX][openData:tab-created]", { traceId, tabId, elapsed: elapsed() });
queryStore.setExecuting(tabId, true);
try {
console.info("[DBX][openData:ensure-connected:start]", { traceId, elapsed: elapsed() });
await connectionStore.ensureConnected(node.connectionId);
console.info("[DBX][openData:ensure-connected:done]", { traceId, elapsed: elapsed() });
if (!config) throw new Error("Connection config not found");
const qualifiedName =
isSchemaAware(config.db_type) && node.schema
? `${quoteIdent(node.schema)}.${quoteIdent(node.label)}`
: quoteIdent(node.label);
const querySchema = node.schema || node.database;
console.info("[DBX][openData:get-columns:start]", {
traceId,
database: node.database,
schema: querySchema,
table: node.label,
elapsed: elapsed(),
});
const columns = await api.getColumns(node.connectionId, node.database, querySchema, node.label);
const pks = columns.filter((c) => c.is_primary_key).map((c) => c.name);
const order = pks.length ? ` ORDER BY ${pks.map((pk) => `${quoteIdent(pk)} ASC`).join(", ")}` : "";
let sql: string;
if (usesFetchFirst(config.db_type)) {
sql = `SELECT * FROM ${qualifiedName}${order} FETCH FIRST 100 ROWS ONLY`;
} else if (config.db_type === "sqlserver") {
sql = `SELECT TOP 100 * FROM ${qualifiedName}${order}`;
} else {
sql = `SELECT * FROM ${qualifiedName}${order} LIMIT 100;`;
}
console.info("[DBX][openData:get-columns:done]", {
traceId,
columnCount: columns.length,
primaryKeys: columns.filter((column) => column.is_primary_key).map((column) => column.name),
elapsed: elapsed(),
});
const pks = editablePrimaryKeys(config.db_type, columns);
const sql = buildTableSelectSql({
databaseType: config.db_type,
schema: node.schema,
tableName: node.label,
primaryKeys: pks,
includeRowId: usesSyntheticRowIdKey(config.db_type, pks),
});
console.info("[DBX][openData:sql-built]", {
traceId,
primaryKeys: pks,
includeRowId: usesSyntheticRowIdKey(config.db_type, pks),
sql,
elapsed: elapsed(),
});
queryStore.updateSql(tabId, sql);
queryStore.setTableMeta(tabId, {
schema: node.schema,
@@ -378,8 +411,11 @@ async function openData() {
primaryKeys: pks,
});
console.info("[DBX][openData:execute:start]", { traceId, tabId, elapsed: elapsed() });
await queryStore.executeTabSql(tabId, sql);
console.info("[DBX][openData:execute:done]", { traceId, tabId, elapsed: elapsed() });
} catch (e: any) {
console.error("[DBX][openData:error]", { traceId, elapsed: elapsed(), error: e });
queryStore.setErrorResult(tabId, e);
}
}
+9 -2
View File
@@ -3,6 +3,7 @@ import { useI18n } from "vue-i18n";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/tableSelectSql";
import { editablePrimaryKeys, usesSyntheticRowIdKey } from "@/lib/tableEditing";
import { buildSortedQuerySql } from "@/lib/queryResultSort";
import type { QueryTab } from "@/types/database";
import { useToast } from "@/composables/useToast";
@@ -23,16 +24,22 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
options: { orderBy?: string; limit?: number; offset?: number; whereInput?: string } = {},
): string {
const config = connectionStore.getConfig(tab.connectionId);
const primaryKeys = tab.tableMeta ? editablePrimaryKeys(config?.db_type, tab.tableMeta.columns) : [];
if (tab.tableMeta && primaryKeys.join("\0") !== tab.tableMeta.primaryKeys.join("\0")) {
tab.tableMeta.primaryKeys = primaryKeys;
}
const fallbackOrderColumns =
config?.db_type === "sqlserver" && !tab.tableMeta?.primaryKeys?.length
config?.db_type === "sqlserver" && !primaryKeys.length
? tab.tableMeta?.columns.slice(0, 1).map((column) => column.name)
: undefined;
const useRowId = usesSyntheticRowIdKey(config?.db_type, primaryKeys);
return buildTableSelectSql({
databaseType: config?.db_type,
schema: tab.tableMeta?.schema,
tableName: tab.tableMeta?.tableName ?? "",
primaryKeys: tab.tableMeta?.primaryKeys,
primaryKeys,
fallbackOrderColumns,
includeRowId: useRowId,
...options,
});
}
+38 -3
View File
@@ -1,6 +1,11 @@
import { ref, computed, nextTick, type ComputedRef, type Ref } from "vue";
import * as api from "@/lib/api";
import { buildDataGridRollbackStatements, buildDataGridSaveStatements } from "@/lib/dataGridSql";
import {
buildDataGridRollbackStatements,
buildDataGridSaveStatements,
dataGridSaveExecutionSchema,
validateDataGridSave,
} from "@/lib/dataGridSql";
import { rowStatusFilterAfterAddingRow, type RowStatusFilter } from "@/lib/gridRowStatus";
import { useConnectionStore } from "@/stores/connectionStore";
import { useHistoryStore } from "@/stores/historyStore";
@@ -59,6 +64,7 @@ export interface UseDataGridEditorOptions {
whereFilterInput: Ref<string>;
orderByInput: Ref<string>;
rowStatusFilter: Ref<RowStatusFilter>;
initialEditColumn?: ComputedRef<number>;
getRowItem: (rowId: number) => RowItem | undefined;
emit: {
(event: "reload", sql?: string, searchText?: string, whereInput?: string, orderBy?: string): void;
@@ -83,6 +89,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
whereFilterInput,
orderByInput,
rowStatusFilter,
initialEditColumn,
getRowItem,
emit,
} = options;
@@ -342,7 +349,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
nextTick(() => {
const el = getScrollerElement();
if (el) el.scrollTop = el.scrollHeight;
startEdit(rowId, 0);
startEdit(rowId, initialEditColumn?.value ?? 0);
});
}
@@ -484,6 +491,21 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
const stmtOptions = saveStatementOptions();
const validationError = stmtOptions
? validateDataGridSave({
databaseType: databaseType.value,
columns: stmtOptions.columns,
columnInfo: tableMeta.value?.columns,
dirtyRows: stmtOptions.dirtyRows,
newRows: stmtOptions.newRows,
})
: undefined;
if (validationError) {
saveError.value = validationError;
isSaving.value = false;
return;
}
const stmts = stmtOptions ? buildDataGridSaveStatements(stmtOptions) : [];
if (stmts.length === 0) {
isSaving.value = false;
@@ -492,10 +514,23 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const rollbackStmts = stmtOptions ? buildDataGridRollbackStatements(stmtOptions) : [];
const start = Date.now();
let apiResult: { affected_rows?: number } | undefined;
console.info("[DBX][dataGrid:save-statements]", {
databaseType: databaseType.value,
table: tableMeta.value
? [tableMeta.value.schema, tableMeta.value.tableName].filter(Boolean).join(".")
: undefined,
statements: stmts,
rollbackStatements: rollbackStmts,
});
if (useTransaction.value && connectionId.value && database.value) {
try {
apiResult = await api.executeInTransaction(connectionId.value, database.value, stmts, tableMeta.value?.schema);
apiResult = await api.executeInTransaction(
connectionId.value,
database.value,
stmts,
dataGridSaveExecutionSchema(databaseType.value, tableMeta.value),
);
} catch (e: any) {
saveError.value = String(e.message || e);
isSaving.value = false;
+7 -8
View File
@@ -10,8 +10,7 @@ import {
type SelectionData,
} from "@/lib/gridSelection";
import { useToast } from "@/composables/useToast";
type CellValue = string | number | boolean | null;
import { displayCellValue, type CellValue } from "@/lib/cellValue";
interface RowItem {
id: number;
@@ -32,9 +31,10 @@ export interface UseDataGridExportOptions {
databaseType: ComputedRef<string | undefined>;
hasCellSelection: ComputedRef<boolean>;
selectedCells: ComputedRef<SelectionData>;
contextCell: Ref<{ rowId: number; rowIndex: number; col: number } | null>;
contextCell:
| Ref<{ rowId: number; rowIndex: number; col: number } | null>
| ComputedRef<{ rowId: number; rowIndex: number; col: number } | null>;
getRowItem: (rowId: number) => RowItem | undefined;
formatCell: (value: CellValue) => string;
quoteIdent: (name: string) => string;
escapeVal: (value: CellValue) => string;
}
@@ -52,7 +52,6 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
selectedCells,
contextCell,
getRowItem,
formatCell,
quoteIdent,
escapeVal,
} = options;
@@ -88,7 +87,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
if (!contextCell.value || contextCell.value.col < 0) return;
const item = getRowItem(contextCell.value.rowId);
const val = item?.data[contextCell.value.col] ?? null;
copyText(formatCell(val));
copyText(displayCellValue(val));
}
function copyRow() {
@@ -116,7 +115,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
function copyAll() {
const header = columns.value.join("\t");
const body = displayItems.value.map((item) => item.data.map((c) => formatCell(c)).join("\t")).join("\n");
const body = displayItems.value.map((item) => item.data.map((c) => displayCellValue(c)).join("\t")).join("\n");
copyText(`${header}\n${body}`);
}
@@ -182,7 +181,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
// --- Export functions ---
async function exportCsv() {
try {
const rows = displayItems.value.map((item) => item.data.map((c) => formatCell(c)));
const rows = displayItems.value.map((item) => item.data.map((c) => displayCellValue(c)));
if (await saveFileContent(formatCsv(columns.value, rows), "export.csv", "CSV", "csv")) {
toast(t("grid.exported"));
}
+4
View File
@@ -1,5 +1,9 @@
import type { TreeNode, TreeNodeType } from "@/types/database";
export const SIDEBAR_TREE_ROW_HEIGHT = 28;
export const SIDEBAR_TREE_SCROLL_BUFFER = SIDEBAR_TREE_ROW_HEIGHT * 48;
export const SIDEBAR_TREE_PRERENDER_COUNT = 48;
export interface FlatTreeNode {
node: TreeNode;
depth: number;
+17 -2
View File
@@ -1,5 +1,6 @@
import * as api from "@/lib/api";
import { buildTableSelectSql } from "@/lib/tableSelectSql";
import { editablePrimaryKeys, usesSyntheticRowIdKey } from "@/lib/tableEditing";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
@@ -44,12 +45,26 @@ async function openTableTarget(target: NavigationTarget) {
const [columnsResult, dataResult] = await Promise.allSettled([columnsPromise, dataPromise]);
if (columnsResult.status === "fulfilled") {
const columns = columnsResult.value;
const primaryKeys = editablePrimaryKeys(config.db_type, columns);
const useRowId = usesSyntheticRowIdKey(config.db_type, primaryKeys);
queryStore.setTableMeta(tabId, {
schema: target.schema,
tableName: target.tableName,
columns,
primaryKeys: columns.filter((c) => c.is_primary_key).map((c) => c.name),
primaryKeys,
});
if (useRowId) {
const newSql = buildTableSelectSql({
databaseType: config.db_type,
schema: target.schema,
tableName: target.tableName,
whereInput: target.whereInput,
primaryKeys,
includeRowId: true,
});
queryStore.updateSql(tabId, newSql);
await queryStore.executeTabSql(tabId, newSql);
}
}
if (dataResult.status === "rejected") throw dataResult.reason;
if (columnsResult.status === "rejected")
@@ -107,7 +122,7 @@ export function useNavigationTargets(dialogs: {
queryStore.setTableMeta(activeTab.id, {
...activeTab.tableMeta,
columns,
primaryKeys: columns.filter((c) => c.is_primary_key).map((c) => c.name),
primaryKeys: editablePrimaryKeys(connectionStore.getConfig(activeTab.connectionId)?.db_type, columns),
});
await reloadData();
} catch (e: any) {
+11
View File
@@ -143,6 +143,14 @@ export default {
sshKeyPathBrowse: "Browse",
sshExposeLan: "Expose tunnel to LAN",
sshConnectTimeout: "SSH Timeout (seconds)",
proxy: "Proxy",
proxyEnable: "Connect database through proxy",
proxyType: "Proxy Type",
proxyHost: "Proxy Host",
proxyUsername: "Proxy User",
proxyUsernamePlaceholder: "Optional",
proxyPassword: "Proxy Password",
proxyPasswordPlaceholder: "Optional",
jdbcUrl: "JDBC URL",
jdbcUrlPlaceholder: "jdbc:postgresql://localhost:5432/database",
jdbcDriverClass: "Driver Class (optional)",
@@ -467,6 +475,9 @@ export default {
truncated: "Context truncated",
contextSummary: "{database} · {tables} tables",
autoSqlBlocked: "The AI-generated SQL looked too risky to auto-execute. Review it manually before running.",
proxy: "Proxy",
proxyEnable: "Send AI requests through proxy",
proxyUrl: "Proxy URL",
settingsHint:
"The config is stored in the local app data directory. Requests are sent by the Tauri backend instead of directly from the frontend.",
actions: {
+11
View File
@@ -143,6 +143,14 @@ export default {
sshKeyPathBrowse: "Examinar",
sshExposeLan: "Exponer túnel a la red local",
sshConnectTimeout: "Tiempo de espera SSH (segundos)",
proxy: "Proxy",
proxyEnable: "Conectar la base de datos mediante proxy",
proxyType: "Tipo de proxy",
proxyHost: "Host del proxy",
proxyUsername: "Usuario del proxy",
proxyUsernamePlaceholder: "Opcional",
proxyPassword: "Contraseña del proxy",
proxyPasswordPlaceholder: "Opcional",
jdbcUrl: "URL JDBC",
jdbcUrlPlaceholder: "jdbc:postgresql://localhost:5432/base_de_datos",
jdbcDriverClass: "Clase del driver (opcional)",
@@ -474,6 +482,9 @@ export default {
contextSummary: "{database} · {tables} tablas",
autoSqlBlocked:
"El SQL generado por la IA parecía demasiado riesgoso para ejecutarse automáticamente. Revísalo manualmente antes de ejecutar.",
proxy: "Proxy",
proxyEnable: "Enviar solicitudes de IA mediante proxy",
proxyUrl: "URL del proxy",
settingsHint:
"La configuración se almacena en el directorio de datos local de la aplicación. Las solicitudes son enviadas por el backend de Tauri en lugar de directamente desde el frontend.",
actions: {
+11
View File
@@ -142,6 +142,14 @@ export default {
sshKeyPathBrowse: "浏览",
sshExposeLan: "允许局域网访问隧道",
sshConnectTimeout: "SSH 超时时间(秒)",
proxy: "代理",
proxyEnable: "通过代理连接数据库",
proxyType: "代理类型",
proxyHost: "代理主机",
proxyUsername: "代理用户",
proxyUsernamePlaceholder: "可选",
proxyPassword: "代理密码",
proxyPasswordPlaceholder: "可选",
jdbcUrl: "JDBC URL",
jdbcUrlPlaceholder: "jdbc:postgresql://localhost:5432/database",
jdbcDriverClass: "驱动类(可选)",
@@ -458,6 +466,9 @@ export default {
truncated: "上下文已截断",
contextSummary: "{database} · {tables} 张表",
autoSqlBlocked: "AI 生成的 SQL 风险较高,已阻止自动执行,请手动检查后再运行。",
proxy: "代理",
proxyEnable: "AI 请求通过代理发送",
proxyUrl: "代理地址",
settingsHint: "配置会保存在本机应用数据目录中。请求由 Tauri 后端发出,避免在前端直接暴露给模型服务。",
actions: {
generate: "生成 SQL",
+8
View File
@@ -0,0 +1,8 @@
export type CellValue = string | number | boolean | null;
export function displayCellValue(value: CellValue): string {
if (value === null) return "NULL";
if (typeof value === "boolean") return value ? "true" : "false";
if (typeof value === "object") return JSON.stringify(value);
return String(value);
}
+102 -9
View File
@@ -1,4 +1,5 @@
import type { DatabaseType } from "@/types/database";
import { DBX_ROWID_COLUMN } from "./tableEditing.ts";
import { qualifiedTableName, quoteTableIdentifier } from "./tableSelectSql.ts";
export type GridCellValue = string | number | boolean | null;
@@ -9,6 +10,11 @@ export interface DataGridTableMeta {
primaryKeys: string[];
}
export interface DataGridColumnInfo {
name: string;
is_nullable: boolean;
}
export interface DataGridSaveStatementOptions {
databaseType?: DatabaseType;
tableMeta: DataGridTableMeta;
@@ -19,6 +25,42 @@ export interface DataGridSaveStatementOptions {
newRows: GridCellValue[][];
}
export interface DataGridSaveValidationOptions {
databaseType?: DatabaseType;
columns: string[];
columnInfo?: DataGridColumnInfo[];
dirtyRows: Array<[number, Array<[number, GridCellValue]>]>;
newRows: GridCellValue[][];
}
export function validateDataGridSave(options: DataGridSaveValidationOptions): string | undefined {
const notNullColumns = new Set(
(options.columnInfo ?? [])
.filter((column) => !column.is_nullable && !isOracleRowId(options.databaseType, column.name))
.map((column) => normalizeColumnName(column.name)),
);
if (notNullColumns.size === 0) return undefined;
for (const [, changes] of options.dirtyRows) {
for (const [columnIndex, value] of changes) {
const column = options.columns[columnIndex];
if (isNullWriteToNotNullColumn(options.databaseType, notNullColumns, column, value)) {
return nullWriteError(column);
}
}
}
for (const row of options.newRows) {
for (const [columnIndex, column] of options.columns.entries()) {
if (isNullWriteToNotNullColumn(options.databaseType, notNullColumns, column, row[columnIndex])) {
return nullWriteError(column);
}
}
}
return undefined;
}
export function buildDataGridSaveStatements(options: DataGridSaveStatementOptions): string[] {
const table = qualifiedTableName({
databaseType: options.databaseType,
@@ -31,11 +73,13 @@ export function buildDataGridSaveStatements(options: DataGridSaveStatementOption
const row = options.rows[rowIndex];
if (!row) continue;
const sets = changes
.filter(([columnIndex]) => !isOracleRowId(options.databaseType, options.columns[columnIndex]))
.map(
([columnIndex, value]) =>
`${quoteIdent(options.databaseType, options.columns[columnIndex])} = ${formatGridSqlLiteral(value, options.databaseType)}`,
)
.join(", ");
if (!sets) continue;
const where = buildPrimaryKeyWhere(options.databaseType, options.tableMeta.primaryKeys, options.columns, row);
statements.push(`UPDATE ${table} SET ${sets} WHERE ${where};`);
}
@@ -48,8 +92,11 @@ export function buildDataGridSaveStatements(options: DataGridSaveStatementOption
}
for (const row of options.newRows) {
const columns = options.columns.map((column) => quoteIdent(options.databaseType, column)).join(", ");
const values = row.map((v) => formatGridSqlLiteral(v, options.databaseType)).join(", ");
const insertPairs = options.columns
.map((column, index) => ({ column, value: row[index] }))
.filter((pair) => !isOracleRowId(options.databaseType, pair.column));
const columns = insertPairs.map((pair) => quoteIdent(options.databaseType, pair.column)).join(", ");
const values = insertPairs.map((pair) => formatGridSqlLiteral(pair.value, options.databaseType)).join(", ");
statements.push(`INSERT INTO ${table} (${columns}) VALUES (${values});`);
}
@@ -72,8 +119,11 @@ export function buildDataGridRollbackStatements(options: DataGridSaveStatementOp
for (const rowIndex of options.deletedRows) {
const row = options.rows[rowIndex];
if (!row) continue;
const columns = options.columns.map((column) => quoteIdent(options.databaseType, column)).join(", ");
const values = row.map((v) => formatGridSqlLiteral(v, options.databaseType)).join(", ");
const insertPairs = options.columns
.map((column, index) => ({ column, value: row[index] }))
.filter((pair) => !isOracleRowId(options.databaseType, pair.column));
const columns = insertPairs.map((pair) => quoteIdent(options.databaseType, pair.column)).join(", ");
const values = insertPairs.map((pair) => formatGridSqlLiteral(pair.value, options.databaseType)).join(", ");
statements.push(`INSERT INTO ${table} (${columns}) VALUES (${values});`);
}
@@ -84,15 +134,19 @@ export function buildDataGridRollbackStatements(options: DataGridSaveStatementOp
for (const [columnIndex, value] of changes) {
afterRow[columnIndex] = value;
}
const sets = changes
const writableChanges = changes.filter(
([columnIndex]) => !isOracleRowId(options.databaseType, options.columns[columnIndex]),
);
const sets = writableChanges
.map(
([columnIndex]) =>
`${quoteIdent(options.databaseType, options.columns[columnIndex])} = ${formatGridSqlLiteral(row[columnIndex], options.databaseType)}`,
)
.join(", ");
if (!sets) continue;
const where = [
buildPrimaryKeyWhere(options.databaseType, options.tableMeta.primaryKeys, options.columns, afterRow),
...changes.map(([columnIndex, value]) =>
...writableChanges.map(([columnIndex, value]) =>
buildColumnPredicate(options.databaseType, options.columns[columnIndex], value),
),
]
@@ -104,6 +158,14 @@ export function buildDataGridRollbackStatements(options: DataGridSaveStatementOp
return statements;
}
export function dataGridSaveExecutionSchema(
databaseType: DatabaseType | undefined,
tableMeta: DataGridTableMeta | undefined,
): string | undefined {
if (databaseType === "oracle") return undefined;
return tableMeta?.schema;
}
export function formatGridSqlLiteral(value: GridCellValue, databaseType?: DatabaseType): string {
if (value === null || value === undefined) return "NULL";
if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -123,21 +185,52 @@ function buildPrimaryKeyWhere(
return primaryKeys
.map((primaryKey) => {
const value = row[columns.indexOf(primaryKey)];
return `${quoteIdent(databaseType, primaryKey)} = ${formatGridSqlLiteral(value, databaseType)}`;
return `${predicateIdent(databaseType, primaryKey)} = ${formatGridSqlLiteral(value, databaseType)}`;
})
.join(" AND ");
}
function buildRowWhere(databaseType: DatabaseType | undefined, columns: string[], row: GridCellValue[]): string {
return columns.map((column, index) => buildColumnPredicate(databaseType, column, row[index])).join(" AND ");
return columns
.map((column, index) =>
isOracleRowId(databaseType, column) ? "" : buildColumnPredicate(databaseType, column, row[index]),
)
.filter(Boolean)
.join(" AND ");
}
function buildColumnPredicate(databaseType: DatabaseType | undefined, column: string, value: GridCellValue): string {
const ident = quoteIdent(databaseType, column);
const ident = predicateIdent(databaseType, column);
if (value === null || value === undefined) return `${ident} IS NULL`;
return `${ident} = ${formatGridSqlLiteral(value, databaseType)}`;
}
function isOracleRowId(databaseType: DatabaseType | undefined, name: string | undefined): boolean {
return databaseType === "oracle" && name?.toUpperCase() === DBX_ROWID_COLUMN;
}
function isNullWriteToNotNullColumn(
databaseType: DatabaseType | undefined,
notNullColumns: Set<string>,
column: string | undefined,
value: GridCellValue,
): boolean {
if (!column || isOracleRowId(databaseType, column)) return false;
return value === null && notNullColumns.has(normalizeColumnName(column));
}
function normalizeColumnName(name: string): string {
return name.toUpperCase();
}
function nullWriteError(column: string): string {
return `Column "${column}" does not allow NULL.`;
}
function predicateIdent(databaseType: DatabaseType | undefined, name: string): string {
return isOracleRowId(databaseType, name) ? "ROWIDTOCHAR(ROWID)" : quoteIdent(databaseType, name);
}
function quoteIdent(databaseType: DatabaseType | undefined, name: string): string {
return quoteTableIdentifier(databaseType, name);
}
+21
View File
@@ -0,0 +1,21 @@
import type { ColumnInfo, DatabaseType } from "@/types/database";
export const DBX_ROWID_COLUMN = "__DBX_ROWID";
export function editablePrimaryKeys(databaseType: DatabaseType | undefined, columns: ColumnInfo[]): string[] {
const primaryKeys = columns.filter((column) => column.is_primary_key).map((column) => column.name);
if (databaseType === "oracle" && primaryKeys.length === 0) return [DBX_ROWID_COLUMN];
return primaryKeys;
}
export function usesSyntheticRowIdKey(databaseType: DatabaseType | undefined, primaryKeys: string[]): boolean {
return databaseType === "oracle" && primaryKeys.length === 1 && primaryKeys[0].toUpperCase() === DBX_ROWID_COLUMN;
}
export function isHiddenGridColumn(
databaseType: DatabaseType | undefined,
column: string,
primaryKeys: string[],
): boolean {
return usesSyntheticRowIdKey(databaseType, primaryKeys) && column.toUpperCase() === DBX_ROWID_COLUMN;
}
+18 -2
View File
@@ -1,5 +1,6 @@
import type { DatabaseType } from "../types/database.ts";
import { isSchemaAware, usesFetchFirst } from "./databaseCapabilities.ts";
import { DBX_ROWID_COLUMN } from "./tableEditing.ts";
export interface BuildTableSelectSqlOptions {
databaseType?: DatabaseType;
@@ -11,6 +12,7 @@ export interface BuildTableSelectSqlOptions {
limit?: number;
offset?: number;
whereInput?: string;
includeRowId?: boolean;
}
export function quoteTableIdentifier(databaseType: DatabaseType | undefined, name: string): string {
@@ -19,6 +21,15 @@ export function quoteTableIdentifier(databaseType: DatabaseType | undefined, nam
return `"${name.replace(/"/g, '""')}"`;
}
function isOracleRowId(databaseType: DatabaseType | undefined, name: string): boolean {
return databaseType === "oracle" && name.toUpperCase() === DBX_ROWID_COLUMN;
}
function quoteOrderIdentifier(databaseType: DatabaseType | undefined, name: string, tableAlias?: string): string {
if (isOracleRowId(databaseType, name)) return tableAlias ? `${tableAlias}.ROWID` : "ROWID";
return quoteTableIdentifier(databaseType, name);
}
export function qualifiedTableName(
options: Pick<BuildTableSelectSqlOptions, "databaseType" | "schema" | "tableName">,
): string {
@@ -40,17 +51,22 @@ export function buildTableSelectSql(options: BuildTableSelectSqlOptions): string
const table = qualifiedTableName(options);
const predicate = normalizeWhereInput(options.whereInput);
const where = predicate ? ` WHERE (${predicate})` : "";
const rowIdAlias = options.includeRowId && databaseType === "oracle" ? "t" : undefined;
const defaultOrderBy = options.primaryKeys?.length
? options.primaryKeys.map((pk) => `${quoteTableIdentifier(databaseType, pk)} ASC`).join(", ")
? options.primaryKeys.map((pk) => `${quoteOrderIdentifier(databaseType, pk, rowIdAlias)} ASC`).join(", ")
: options.fallbackOrderColumns?.length
? options.fallbackOrderColumns.map((column) => `${quoteTableIdentifier(databaseType, column)} ASC`).join(", ")
: undefined;
const orderBy = options.orderBy ?? defaultOrderBy;
const order = orderBy ? ` ORDER BY ${orderBy}` : "";
const selectColumns =
options.includeRowId && databaseType === "oracle" ? `ROWIDTOCHAR(t.ROWID) AS "${DBX_ROWID_COLUMN}", t.*` : "*";
const tableAlias = options.includeRowId && usesFetchFirst(databaseType) ? `${table} t` : table;
if (usesFetchFirst(databaseType)) {
const offset = options.offset ? ` OFFSET ${options.offset} ROWS` : "";
return `SELECT * FROM ${table}${where}${order}${offset} FETCH FIRST ${limit} ROWS ONLY`;
return `SELECT ${selectColumns} FROM ${tableAlias}${where}${order}${offset} FETCH FIRST ${limit} ROWS ONLY`;
}
if (databaseType === "sqlserver") {
+41
View File
@@ -0,0 +1,41 @@
import type { TableInfo, TreeNode } from "@/types/database";
export function buildTableTreeNodes({
nodeId,
connectionId,
database,
schema,
tables,
}: {
nodeId: string;
connectionId: string;
database: string;
schema?: string;
tables: TableInfo[];
}): TreeNode[] {
return tables.map((table) => ({
id: `${nodeId}:${table.name}`,
label: table.name,
type: table.table_type === "VIEW" ? "view" : "table",
connectionId,
database,
schema,
isExpanded: false,
children: [],
}));
}
export function expandCachedObjectBrowserNodes(nodes: TreeNode[]): TreeNode[] {
return nodes.flatMap((node) => {
if (node.type === "object-browser") return node.hiddenChildren ?? [];
if (!node.children) return [node];
return [
{
...node,
children: expandCachedObjectBrowserNodes(node.children),
},
];
});
}
+12 -71
View File
@@ -23,10 +23,10 @@ import { isTauriRuntime } from "@/lib/tauriRuntime";
import { isSchemaAware, TREE_SCHEMA_TYPES } from "@/lib/databaseCapabilities";
import { buildDatabaseTreeNodes } from "@/lib/databaseTree";
import { buildSqlServerDatabaseTreeNodes, SQLSERVER_DEFAULT_SCHEMA } from "@/lib/sqlServerTree";
import { buildTableTreeNodes, expandCachedObjectBrowserNodes } from "@/lib/tableTree";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
const PINNED_TREE_NODES_STORAGE_KEY = "dbx-pinned-tree-nodes";
const SIDEBAR_TABLE_NODE_LIMIT = 15;
type ImportSource = "dbx" | "navicat" | "dbeaver";
interface LoadTreeOptions {
@@ -171,6 +171,8 @@ export const useConnectionStore = defineStore("connection", () => {
driver_label: config.driver_label || labelMap[profile] || config.db_type,
url_params: config.url_params || "",
ssh_connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
proxy_type: config.proxy_type || "socks5",
proxy_port: config.proxy_port || 1080,
};
}
@@ -278,9 +280,12 @@ export const useConnectionStore = defineStore("connection", () => {
async function loadPersistedTreeChildren(node: TreeNode, cacheKey: string): Promise<boolean> {
const children = await api.loadSchemaCache<TreeNode[]>(cacheKey).catch(() => null);
if (!children) return false;
const normalizedChildren = expandCachedObjectBrowserNodes(children);
setChildren(
node,
node.type === "connection" && node.connectionId ? withSavedSqlRoot(node.connectionId, children, node) : children,
node.type === "connection" && node.connectionId
? withSavedSqlRoot(node.connectionId, normalizedChildren, node)
: normalizedChildren,
);
node.isExpanded = true;
return true;
@@ -290,24 +295,6 @@ export const useConnectionStore = defineStore("connection", () => {
await api.saveSchemaCache(cacheKey, children).catch(() => undefined);
}
function buildObjectBrowserNode(
nodeId: string,
connectionId: string,
database: string,
schema: string | undefined,
objectCount: number,
): TreeNode {
return {
id: `${nodeId}:__object_browser`,
label: "tree.objectBrowser",
type: "object-browser",
connectionId,
database,
schema,
objectCount,
};
}
function useCachedChildren(node: TreeNode, options?: LoadTreeOptions): boolean {
if (options?.force || !loadedTreeNodeChildrenIds.value.has(node.id)) return false;
node.isExpanded = true;
@@ -681,34 +668,7 @@ export const useConnectionStore = defineStore("connection", () => {
api.listSchemas(connectionId, database),
api.listTables(connectionId, database, SQLSERVER_DEFAULT_SCHEMA),
]);
let children = buildSqlServerDatabaseTreeNodes(connectionId, database, schemas, defaultSchemaTables);
if (defaultSchemaTables.length > SIDEBAR_TABLE_NODE_LIMIT) {
const previewTables = buildSqlServerDatabaseTreeNodes(
connectionId,
database,
[],
defaultSchemaTables.slice(0, SIDEBAR_TABLE_NODE_LIMIT),
);
const browserNode = buildObjectBrowserNode(
`${nodeId}:${SQLSERVER_DEFAULT_SCHEMA}`,
connectionId,
database,
SQLSERVER_DEFAULT_SCHEMA,
defaultSchemaTables.length,
);
const hiddenTables = defaultSchemaTables.slice(SIDEBAR_TABLE_NODE_LIMIT);
browserNode.hiddenChildren = hiddenTables.map((t) => ({
id: `${nodeId}:${SQLSERVER_DEFAULT_SCHEMA}:${t.name}`,
label: t.name,
type: (t.table_type === "VIEW" ? "view" : "table") as "view" | "table",
connectionId,
database,
schema: SQLSERVER_DEFAULT_SCHEMA,
isExpanded: false,
children: [],
}));
children = [...previewTables, browserNode, ...children.filter((child) => child.type === "schema")];
}
const children = buildSqlServerDatabaseTreeNodes(connectionId, database, schemas, defaultSchemaTables);
setChildren(node, children);
await savePersistedTreeChildren(cacheKey, children);
node.isExpanded = true;
@@ -732,32 +692,13 @@ export const useConnectionStore = defineStore("connection", () => {
const tables = await api.listTables(connectionId, database, querySchema);
const config = getConfig(connectionId);
const effectiveSchema = schema || (config?.db_type && isSchemaAware(config.db_type) ? database : undefined);
const visibleTables = tables.slice(0, SIDEBAR_TABLE_NODE_LIMIT);
const children: TreeNode[] = visibleTables.map((t) => ({
id: `${nodeId}:${t.name}`,
label: t.name,
type: (t.table_type === "VIEW" ? "view" : "table") as "view" | "table",
const children = buildTableTreeNodes({
nodeId,
connectionId,
database,
schema: effectiveSchema,
isExpanded: false,
children: [],
}));
if (tables.length > SIDEBAR_TABLE_NODE_LIMIT) {
const hiddenTables = tables.slice(SIDEBAR_TABLE_NODE_LIMIT);
const browserNode = buildObjectBrowserNode(nodeId, connectionId, database, effectiveSchema, tables.length);
browserNode.hiddenChildren = hiddenTables.map((t) => ({
id: `${nodeId}:${t.name}`,
label: t.name,
type: (t.table_type === "VIEW" ? "view" : "table") as "view" | "table",
connectionId,
database,
schema: effectiveSchema,
isExpanded: false,
children: [],
}));
children.push(browserNode);
}
tables,
});
setChildren(node, children);
await savePersistedTreeChildren(cacheKey, children);
node.isExpanded = true;
+36
View File
@@ -368,12 +368,32 @@ export const useQueryStore = defineStore("query", () => {
if (!tab || !sql.trim()) return;
const executionId = uuid();
const traceId = executionId.slice(0, 8);
const startedAt = performance.now();
const elapsed = () => `${Math.round(performance.now() - startedAt)}ms`;
tab.isExecuting = true;
tab.isCancelling = false;
tab.executionId = executionId;
tab.lastExecutedSql = sql;
console.info("[DBX][executeTabSql:start]", {
traceId,
tabId: id,
mode: tab.mode,
connectionId: tab.connectionId,
database: tab.database,
schema: tab.schema,
sql,
});
try {
console.info("[DBX][executeTabSql:execute-multi:start]", { traceId, elapsed: elapsed() });
const results = await api.executeMulti(tab.connectionId, tab.database, sql, tab.schema, executionId);
console.info("[DBX][executeTabSql:execute-multi:done]", {
traceId,
resultCount: results.length,
rowCounts: results.map((result) => result.rows.length),
columnCounts: results.map((result) => result.columns.length),
elapsed: elapsed(),
});
const current = tabs.value.find((t) => t.id === id);
if (current?.executionId === executionId) {
if (results.length > 1) {
@@ -387,9 +407,18 @@ export const useQueryStore = defineStore("query", () => {
}
current.resultBaseSql = options?.resultBaseSql ?? sql;
current.resultSortedSql = options?.resultSortedSql;
console.info("[DBX][executeTabSql:metadata:start]", { traceId, elapsed: elapsed() });
await analyzeQueryMetadata(current, current.resultBaseSql);
console.info("[DBX][executeTabSql:metadata:done]", { traceId, elapsed: elapsed() });
} else {
console.warn("[DBX][executeTabSql:stale-result]", {
traceId,
currentExecutionId: current?.executionId,
elapsed: elapsed(),
});
}
} catch (e: any) {
console.error("[DBX][executeTabSql:error]", { traceId, elapsed: elapsed(), error: e });
const current = tabs.value.find((t) => t.id === id);
if (current?.executionId === executionId) {
current.result = toErrorResult(e);
@@ -406,6 +435,13 @@ export const useQueryStore = defineStore("query", () => {
current.isExecuting = false;
current.isCancelling = false;
current.executionId = undefined;
console.info("[DBX][executeTabSql:finish]", { traceId, elapsed: elapsed() });
} else {
console.warn("[DBX][executeTabSql:finish-stale]", {
traceId,
currentExecutionId: current?.executionId,
elapsed: elapsed(),
});
}
}
trimResultCache();
+2
View File
@@ -11,6 +11,8 @@ export interface AiConfig {
endpoint: string;
model: string;
apiStyle: AiApiStyle;
proxyEnabled?: boolean;
proxyUrl?: string;
}
const defaultConfigs: Record<AiProvider, Omit<AiConfig, "apiKey">> = {
+6
View File
@@ -38,6 +38,12 @@ export interface ConnectionConfig {
ssh_key_passphrase?: string;
ssh_expose_lan?: boolean;
ssh_connect_timeout_secs?: number;
proxy_enabled?: boolean;
proxy_type?: "socks5" | "http";
proxy_host?: string;
proxy_port?: number;
proxy_username?: string;
proxy_password?: string;
ssl?: boolean;
sysdba?: boolean;
connection_string?: string;
+52
View File
@@ -0,0 +1,52 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { displayCellValue } from "../src/lib/cellValue.ts";
test("displayCellValue returns NULL for null", () => {
assert.equal(displayCellValue(null), "NULL");
});
test("displayCellValue returns string representation for booleans", () => {
assert.equal(displayCellValue(true), "true");
assert.equal(displayCellValue(false), "false");
});
test("displayCellValue returns String for numbers", () => {
assert.equal(displayCellValue(42), "42");
assert.equal(displayCellValue(-3.14), "-3.14");
assert.equal(displayCellValue(0), "0");
});
test("displayCellValue returns String for strings", () => {
assert.equal(displayCellValue("hello"), "hello");
assert.equal(displayCellValue(""), "");
});
test("displayCellValue does not truncate long strings", () => {
const long = "a".repeat(1000);
assert.equal(displayCellValue(long), long);
});
test("displayCellValue serializes JSON strings containing complex nested objects", () => {
const payload = '{"metadata":{"version":"2.1.0","tags":["alpha","beta"],"flags":{"enabled":true,"nested":{"depth":3,"items":[{"id":1,"label":"a"},{"id":2,"label":"b"}]}}},"data":{"records":[{"key":"k-001","value":42},{"key":"k-002","value":-999}],"summary":{"total":3,"valid":2}}}';
assert.equal(displayCellValue(payload), payload);
});
test("displayCellValue handles strings with unicode and special characters", () => {
const unicodeStr = "你好世界 🚀🎉 <div>test</div> Line1\nLine2\tTabbed";
assert.equal(displayCellValue(unicodeStr), unicodeStr);
});
test("displayCellValue handles large integer and scientific notation as strings", () => {
const bigIntStr = "9007199254740991";
const sciStr = "1e-10";
assert.equal(displayCellValue(bigIntStr), bigIntStr);
assert.equal(displayCellValue(sciStr), sciStr);
});
test("displayCellValue handles empty JSON-like strings without alteration", () => {
assert.equal(displayCellValue("{}"), "{}");
assert.equal(displayCellValue("[]"), "[]");
assert.equal(displayCellValue('{"key":"value"}'), '{"key":"value"}');
assert.equal(displayCellValue("[1,2,3]"), "[1,2,3]");
});
+62 -2
View File
@@ -1,6 +1,10 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { buildDataGridSaveStatements } from "../src/lib/dataGridSql.ts";
import {
buildDataGridSaveStatements,
dataGridSaveExecutionSchema,
validateDataGridSave,
} from "../src/lib/dataGridSql.ts";
test("builds SQL Server grid save statements with schema and bracket quoting", () => {
const statements = buildDataGridSaveStatements({
@@ -12,7 +16,15 @@ test("builds SQL Server grid save statements with schema and bracket quoting", (
},
columns: ["role id", "state", "updated at"],
rows: [[42, "old", "2026-05-03"]],
dirtyRows: [[0, [[1, "ready"], [2, "2026-05-04"]]]],
dirtyRows: [
[
0,
[
[1, "ready"],
[2, "2026-05-04"],
],
],
],
deletedRows: [0],
newRows: [[43, "new", "2026-05-05"]],
});
@@ -23,3 +35,51 @@ test("builds SQL Server grid save statements with schema and bracket quoting", (
"INSERT INTO [game].[player states] ([role id], [state], [updated at]) VALUES (43, N'new', N'2026-05-05');",
]);
});
test("uses Oracle ROWID as a synthetic key without writing it as a normal column", () => {
const statements = buildDataGridSaveStatements({
databaseType: "oracle",
tableMeta: {
schema: "DBXTEST",
tableName: "DBX_LOAD_TABLE_006",
primaryKeys: ["__DBX_ROWID"],
},
columns: ["__DBX_ROWID", "ID", "CITY", "NOTE"],
rows: [["AAATiBAABAAABrXAAA", 1, "上海", "old"]],
dirtyRows: [[0, [[2, "北京"]]]],
deletedRows: [0],
newRows: [[null, 2, "广州", "new"]],
});
assert.deepEqual(statements, [
`UPDATE "DBXTEST"."DBX_LOAD_TABLE_006" SET "CITY" = '北京' WHERE ROWIDTOCHAR(ROWID) = 'AAATiBAABAAABrXAAA';`,
`DELETE FROM "DBXTEST"."DBX_LOAD_TABLE_006" WHERE ROWIDTOCHAR(ROWID) = 'AAATiBAABAAABrXAAA';`,
`INSERT INTO "DBXTEST"."DBX_LOAD_TABLE_006" ("ID", "CITY", "NOTE") VALUES (2, '广州', 'new');`,
]);
});
test("skips current_schema setup for Oracle data grid saves", () => {
assert.equal(
dataGridSaveExecutionSchema("oracle", { schema: "DBXTEST", tableName: "T", primaryKeys: [] }),
undefined,
);
assert.equal(
dataGridSaveExecutionSchema("postgres", { schema: "public", tableName: "T", primaryKeys: [] }),
"public",
);
});
test("rejects NULL writes to non-null table columns", () => {
const error = validateDataGridSave({
columns: ["ID", "CREATED_AT", "CITY"],
columnInfo: [
{ name: "ID", is_nullable: false, is_primary_key: true },
{ name: "CREATED_AT", is_nullable: false, is_primary_key: false },
{ name: "CITY", is_nullable: true, is_primary_key: false },
],
dirtyRows: [[0, [[1, null]]]],
newRows: [[2, null, "上海"]],
});
assert.equal(error, 'Column "CREATED_AT" does not allow NULL.');
});
+20
View File
@@ -0,0 +1,20 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { createPinia, setActivePinia } from "pinia";
import { useQueryStore } from "../src/stores/queryStore.ts";
test("setErrorResult stops loading and shows the error result", () => {
setActivePinia(createPinia());
const store = useQueryStore();
const tabId = store.createTab("conn-1", "db", "users", "data");
store.setExecuting(tabId, true);
store.setErrorResult(tabId, new Error("metadata failed"));
const tab = store.tabs.find((item) => item.id === tabId);
assert.equal(tab?.isExecuting, false);
assert.equal(tab?.isCancelling, false);
assert.equal(tab?.executionId, undefined);
assert.deepEqual(tab?.result?.columns, ["Error"]);
assert.deepEqual(tab?.result?.rows, [["Error: metadata failed"]]);
});
+45
View File
@@ -0,0 +1,45 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import {
DBX_ROWID_COLUMN,
editablePrimaryKeys,
isHiddenGridColumn,
usesSyntheticRowIdKey,
} from "../src/lib/tableEditing.ts";
import type { ColumnInfo } from "../src/types/database.ts";
function column(name: string, isPrimaryKey = false): ColumnInfo {
return {
name,
data_type: "VARCHAR2",
is_nullable: true,
column_default: null,
is_primary_key: isPrimaryKey,
extra: null,
};
}
test("uses ROWID as Oracle editable key when a table has no primary key", () => {
assert.deepEqual(editablePrimaryKeys("oracle", [column("ID"), column("CITY")]), [DBX_ROWID_COLUMN]);
});
test("keeps declared primary keys ahead of Oracle ROWID fallback", () => {
assert.deepEqual(editablePrimaryKeys("oracle", [column("ID", true), column("CITY")]), ["ID"]);
});
test("does not synthesize ROWID for non-Oracle keyless tables", () => {
assert.deepEqual(editablePrimaryKeys("mysql", [column("ID"), column("CITY")]), []);
});
test("detects the synthetic Oracle ROWID key case", () => {
assert.equal(usesSyntheticRowIdKey("oracle", [DBX_ROWID_COLUMN]), true);
assert.equal(usesSyntheticRowIdKey("oracle", [DBX_ROWID_COLUMN.toLowerCase()]), true);
assert.equal(usesSyntheticRowIdKey("postgres", [DBX_ROWID_COLUMN]), false);
assert.equal(usesSyntheticRowIdKey("oracle", ["ID"]), false);
});
test("hides only the synthetic Oracle ROWID grid column", () => {
assert.equal(isHiddenGridColumn("oracle", DBX_ROWID_COLUMN, [DBX_ROWID_COLUMN]), true);
assert.equal(isHiddenGridColumn("oracle", "ROWID", [DBX_ROWID_COLUMN]), false);
assert.equal(isHiddenGridColumn("mysql", DBX_ROWID_COLUMN, [DBX_ROWID_COLUMN]), false);
});
+21 -1
View File
@@ -1,5 +1,6 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { DBX_ROWID_COLUMN } from "../src/lib/tableEditing.ts";
import { buildTableSelectSql } from "../src/lib/tableSelectSql.ts";
test("builds a MySQL table WHERE query from search input", () => {
@@ -37,7 +38,10 @@ test("builds SQL Server first page query with schema-aware brackets", () => {
primaryKeys: ["id"],
});
assert.equal(sql, "SELECT * FROM [dbo].[accounts] WHERE (id = 1) ORDER BY [id] ASC OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY");
assert.equal(
sql,
"SELECT * FROM [dbo].[accounts] WHERE (id = 1) ORDER BY [id] ASC OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY",
);
});
test("builds SQL Server later pages with OFFSET and FETCH", () => {
@@ -65,3 +69,19 @@ test("builds SQL Server pages with fallback order columns when there is no prima
assert.equal(sql, "SELECT * FROM [dbo].[logs] ORDER BY [created_at] ASC OFFSET 50 ROWS FETCH NEXT 50 ROWS ONLY");
});
test("builds Oracle table data queries with ROWID for keyless editing", () => {
const sql = buildTableSelectSql({
databaseType: "oracle",
schema: "DBXTEST",
tableName: "DBX_LOAD_TABLE_006",
primaryKeys: [DBX_ROWID_COLUMN],
includeRowId: true,
limit: 100,
});
assert.equal(
sql,
`SELECT ROWIDTOCHAR(t.ROWID) AS "__DBX_ROWID", t.* FROM "DBXTEST"."DBX_LOAD_TABLE_006" t ORDER BY t.ROWID ASC FETCH FIRST 100 ROWS ONLY`,
);
});
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildTableTreeNodes, expandCachedObjectBrowserNodes } from "../src/lib/tableTree.ts";
import type { TableInfo } from "../src/types/database.ts";
function table(name: string, tableType: "TABLE" | "VIEW" = "TABLE"): TableInfo {
return { name, table_type: tableType };
}
test("keeps every table as a sidebar node instead of truncating to object browser", () => {
const tables: TableInfo[] = Array.from({ length: 16 }, (_, index) => table(`table_${index + 1}`));
const nodes = buildTableTreeNodes({
nodeId: "conn:db",
connectionId: "conn",
database: "db",
tables,
});
assert.equal(nodes.length, 16);
assert.equal(nodes.at(-1)?.label, "table_16");
assert.equal(
nodes.some((node) => node.type === "object-browser"),
false,
);
});
test("preserves table and view node types", () => {
const nodes = buildTableTreeNodes({
nodeId: "conn:db:public",
connectionId: "conn",
database: "db",
schema: "public",
tables: [table("users"), table("user_view", "VIEW")],
});
assert.deepEqual(
nodes.map((node) => [node.label, node.type, node.schema]),
[
["users", "table", "public"],
["user_view", "view", "public"],
],
);
});
test("expands cached object-browser nodes back into regular table nodes", () => {
const nodes = expandCachedObjectBrowserNodes([
{
id: "conn:db:table_1",
label: "table_1",
type: "table",
connectionId: "conn",
database: "db",
isExpanded: false,
children: [],
},
{
id: "conn:db:__object_browser",
label: "tree.objectBrowser",
type: "object-browser",
connectionId: "conn",
database: "db",
hiddenChildren: [
{
id: "conn:db:table_16",
label: "table_16",
type: "table",
connectionId: "conn",
database: "db",
isExpanded: false,
children: [],
},
],
},
]);
assert.deepEqual(
nodes.map((node) => [node.label, node.type]),
[
["table_1", "table"],
["table_16", "table"],
],
);
});
+16 -1
View File
@@ -1,6 +1,12 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { flattenTree, shouldVirtualizeFlatTree } from "../src/composables/useFlatTree.ts";
import {
SIDEBAR_TREE_ROW_HEIGHT,
SIDEBAR_TREE_PRERENDER_COUNT,
SIDEBAR_TREE_SCROLL_BUFFER,
flattenTree,
shouldVirtualizeFlatTree,
} from "../src/composables/useFlatTree.ts";
import type { TreeNode } from "../src/types/database.ts";
test("flattenTree preserves depth and node type for virtualized sidebar rows", () => {
@@ -40,3 +46,12 @@ test("shouldVirtualizeFlatTree only virtualizes very large sidebar trees", () =>
assert.equal(shouldVirtualizeFlatTree(99), false);
assert.equal(shouldVirtualizeFlatTree(100), true);
});
test("sidebar virtual tree keeps enough buffered rows for fast scrolling", () => {
assert.equal(SIDEBAR_TREE_ROW_HEIGHT, 28);
assert.ok(SIDEBAR_TREE_SCROLL_BUFFER >= SIDEBAR_TREE_ROW_HEIGHT * 40);
});
test("sidebar virtual tree prerenders enough rows for the first frame", () => {
assert.ok(SIDEBAR_TREE_PRERENDER_COUNT >= 40);
});