Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(sqlserver): support port in SQL Server host (#12813)

lxk955b993e7a6f117
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index d213047dbf..a3a80040e5 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -136,6 +136,7 @@ import { pluginFieldIsRequired, pluginFieldIsVisible } from "@/lib/plugins/plugi
import { detectMqUiAuthKind, isMqAuthKindAllowedForSystem, type MqUiAuthKind } from "@/lib/connection/mqAuth";
import { driverInstallProgressChannel, driverInstallProgressPercent, isDriverInstallProgressForOperation, requestAgentInstallCancellation, resolveAgentInstallOutcome, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";
import { requiresSqlServerLegacyCompatibilityComponent, setSqlServerLegacyCompatibilityConfig, sqlServerUsesLegacyCompatibility, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility";
+import { parseSqlServerHostPort } from "@/lib/sqlserver/sqlServerHostPort";
import { normalizeNacosConsoleUrl, normalizeNacosEndpoint, normalizeNacosMetricsUrl, parseNacosManagedNamespaces } from "@/lib/nacos/nacosAdmin";
import { loadReadableNacosNamespaces, nacosNamespaceIdentity, normalizeNacosNamespaceSelection } from "@/lib/nacos/nacosNamespaceVisibility";
import {
@@ -807,6 +808,34 @@ function markSqlServerPortExplicit() {
setSqlServerPortExplicit(form.value, true);
}
+function handleHostBlur() {
+ if (form.value.db_type === "sqlserver") {
+ const parsed = parseSqlServerHostPort(form.value.host, form.value.port);
+ form.value.host = parsed.host;
+ if (parsed.portExplicit && parsed.port !== undefined) {
+ form.value.port = parsed.port;
+ markSqlServerPortExplicit();
+ resetTestState();
+ }
+ }
+}
+
+function handleHostPaste(event: ClipboardEvent) {
+ if (form.value.db_type === "sqlserver") {
+ const text = event.clipboardData?.getData("text") || "";
+ if (text.includes(",") || text.toLowerCase().startsWith("tcp:") || text.includes(":")) {
+ const parsed = parseSqlServerHostPort(text, form.value.port);
+ if (parsed.portExplicit) {
+ event.preventDefault();
+ form.value.host = parsed.host;
+ form.value.port = parsed.port!;
+ markSqlServerPortExplicit();
+ resetTestState();
+ }
+ }
+ }
+}
+
const keepaliveEnabled = computed({
get: () => Number(form.value.keepalive_interval_secs) > 0,
set: (enabled: boolean) => {
@@ -3144,8 +3173,8 @@ watch(
driver_label: config.driver_label || oceanbasePatch?.driver_label || driverProfiles[profile]?.label || config.db_type,
...savedMysqlTlsFormFields(config),
agent_java_options: config.agent_java_options || [],
- host: config.db_type === "h2" && h2FilePathFromJdbcUrl(config.connection_string) ? h2FilePathFromJdbcUrl(config.connection_string) : config.host,
- port: profile === "tdengine" && (config.port === 0 || config.port === 6030) ? 6041 : config.port,
+ host: config.db_type === "sqlserver" ? parseSqlServerHostPort(config.host, config.port).host : config.db_type === "h2" && h2FilePathFromJdbcUrl(config.connection_string) ? h2FilePathFromJdbcUrl(config.connection_string) : config.host,
+ port: config.db_type === "sqlserver" ? (parseSqlServerHostPort(config.host, config.port).port ?? config.port) : profile === "tdengine" && (config.port === 0 || config.port === 6030) ? 6041 : config.port,
username: config.username,
password: config.password,
// Show the index the backend actually connects with; legacy dirty values
@@ -3201,6 +3230,9 @@ watch(
visible_schemas: config.visible_schemas,
save_password: config.save_password !== false,
};
+ if (config.db_type === "sqlserver" && parseSqlServerHostPort(config.host, config.port).portExplicit) {
+ markSqlServerPortExplicit();
+ }
redisKeyTemplatesText.value = redisKeyTemplatesToTextarea(form.value.redis_key_templates);
oracleTnsAdminPath.value = parseOracleTnsConnectionString(config.connection_string)?.tnsAdmin || "";
productionProtectionEnabled.value = !!config.is_production || (config.production_databases?.length ?? 0) > 0;
@@ -5173,6 +5205,14 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
config.password = config.password.trim();
config.database = undefined;
} else if (config.db_type === "sqlserver") {
+ const parsed = parseSqlServerHostPort(config.host, config.port);
+ config.host = parsed.host;
+ if (parsed.portExplicit && parsed.port !== undefined) {
+ config.port = parsed.port;
+ setSqlServerPortExplicit(config, true);
+ form.value.host = parsed.host;
+ form.value.port = parsed.port;
+ }
if (!connectionUpdateExternalConfigPreserved(config)) config.external_config = sqlServerPortExplicitFromConfig(config) ? { portExplicit: true } : undefined;
} else if (supportsGaussdbIdentifierQuoteStyle(config)) {
const style = gaussdbIdentifierQuoteStyle(config);
@@ -6372,6 +6412,14 @@ function applyConnectionDraftToForm(draft: ConnectionDeepLinkDraft) {
selectedType.value = "gbase";
}
customDriverName.value = isCustomCompatibleProfile() ? draft.driverLabel : "";
+ if (form.value.db_type === "sqlserver") {
+ const parsed = parseSqlServerHostPort(form.value.host, form.value.port);
+ form.value.host = parsed.host;
+ if (parsed.portExplicit && parsed.port !== undefined) {
+ form.value.port = parsed.port;
+ markSqlServerPortExplicit();
+ }
+ }
mongoUseUrl.value = !!draft.useMongoUrl;
if (draft.name?.trim()) {
form.value.name = draft.name.trim();
@@ -9286,7 +9334,7 @@ function openExternalUrl(url: string) {
</div>
<div v-else-if="form.db_type !== 'oracle' || form.oracle_connection_type !== 'tns'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ form.db_type === "elasticsearch" && elasticsearchConnectionMode === "kibana" ? t("connection.elasticsearchKibanaHost") : t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
+ <Input v-model="form.host" class="col-span-2" @blur="handleHostBlur" @paste="handleHostPaste" />
<Input v-model.number="form.port" type="number" class="col-span-1" @input="markSqlServerPortExplicit" />
</div>
diff --git a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts
index 1ecc0265c3..a86cd982e3 100644
--- a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts
+++ b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts
@@ -428,4 +428,46 @@ describe("ConnectionDialog deep-link edit confirmation", () => {
expect(store.updateConnection).toHaveBeenCalledWith(expect.objectContaining({ id: "saved-production", port: 1445, external_config: { portExplicit: true } }));
expect(store.addConnection).not.toHaveBeenCalled();
});
+
+ it("normalizes SQL Server host with comma port and marks explicit port on save", async () => {
+ await mountDialog(savedConnection({ db_type: "sqlserver", driver_profile: "sqlserver", driver_label: "SQL Server", host: "127.0.0.1", port: 1433 }), "dbx://connection/new?id=saved-production&host=gg.test.com,9005");
+ const save = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Save");
+ expect(save).toBeTruthy();
+ save!.click();
+ await settle();
+
+ expect(store.updateConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "saved-production",
+ host: "gg.test.com",
+ port: 9005,
+ external_config: { portExplicit: true },
+ }),
+ );
+ expect(store.addConnection).not.toHaveBeenCalled();
+ });
+
+ it("normalizes SQL Server host with tcp prefix and comma port on blur", async () => {
+ await mountDialog(savedConnection({ db_type: "sqlserver", driver_profile: "sqlserver", driver_label: "SQL Server", host: "127.0.0.1", port: 1433 }));
+ const hostInput = [...document.querySelectorAll("input")].find((input) => input.value === "127.0.0.1");
+ expect(hostInput).toBeTruthy();
+ hostInput!.value = "tcp:sql.example.com,1444";
+ hostInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ hostInput!.dispatchEvent(new Event("blur", { bubbles: true }));
+ await settle();
+
+ const save = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Save");
+ expect(save).toBeTruthy();
+ save!.click();
+ await settle();
+
+ expect(store.updateConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "saved-production",
+ host: "sql.example.com",
+ port: 1444,
+ external_config: { portExplicit: true },
+ }),
+ );
+ });
});
diff --git a/apps/desktop/src/lib/sqlserver/__tests__/sqlServerHostPort.spec.ts b/apps/desktop/src/lib/sqlserver/__tests__/sqlServerHostPort.spec.ts
new file mode 100644
index 0000000000..d29ec34071
--- /dev/null
+++ b/apps/desktop/src/lib/sqlserver/__tests__/sqlServerHostPort.spec.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+import { parseSqlServerHostPort } from "../sqlServerHostPort";
+
+describe("parseSqlServerHostPort", () => {
+ it("parses comma-separated port", () => {
+ expect(parseSqlServerHostPort("gg.test.com,9005")).toEqual({
+ host: "gg.test.com",
+ port: 9005,
+ portExplicit: true,
+ });
+ });
+
+ it("parses comma-separated port with whitespace", () => {
+ expect(parseSqlServerHostPort(" 192.168.1.100, 14333 ")).toEqual({
+ host: "192.168.1.100",
+ port: 14333,
+ portExplicit: true,
+ });
+ });
+
+ it("strips tcp: prefix and extracts comma-separated port", () => {
+ expect(parseSqlServerHostPort("tcp:gg.test.com,9005")).toEqual({
+ host: "gg.test.com",
+ port: 9005,
+ portExplicit: true,
+ });
+ });
+
+ it("strips tcp: prefix without port", () => {
+ expect(parseSqlServerHostPort("tcp:gg.test.com", 1433)).toEqual({
+ host: "gg.test.com",
+ port: 1433,
+ portExplicit: false,
+ });
+ });
+
+ it("parses colon-separated port", () => {
+ expect(parseSqlServerHostPort("gg.test.com:9005")).toEqual({
+ host: "gg.test.com",
+ port: 9005,
+ portExplicit: true,
+ });
+ });
+
+ it("parses named instance with comma port", () => {
+ expect(parseSqlServerHostPort("192.168.1.10\\SQL2022,14333")).toEqual({
+ host: "192.168.1.10\\SQL2022",
+ port: 14333,
+ portExplicit: true,
+ });
+ });
+
+ it("parses named instance with tcp prefix", () => {
+ expect(parseSqlServerHostPort("tcp:192.168.1.10\\SQL2022", 1433)).toEqual({
+ host: "192.168.1.10\\SQL2022",
+ port: 1433,
+ portExplicit: false,
+ });
+ });
+
+ it("parses bracketed IPv6 with comma or colon port", () => {
+ expect(parseSqlServerHostPort("[::1],9005")).toEqual({
+ host: "[::1]",
+ port: 9005,
+ portExplicit: true,
+ });
+ expect(parseSqlServerHostPort("[::1]:9005")).toEqual({
+ host: "[::1]",
+ port: 9005,
+ portExplicit: true,
+ });
+ });
+
+ it("keeps regular host without port", () => {
+ expect(parseSqlServerHostPort("localhost", 1433)).toEqual({
+ host: "localhost",
+ port: 1433,
+ portExplicit: false,
+ });
+ expect(parseSqlServerHostPort("", 1433)).toEqual({
+ host: "",
+ port: 1433,
+ portExplicit: false,
+ });
+ });
+
+ it.each(["[::1],70000", "[::1]:oops", "[::1]:0", "[::1]unexpected", "server:1e3", "server,0x599"])("preserves invalid endpoint text instead of selecting a different port: %s", (host) => {
+ expect(parseSqlServerHostPort(host, 1433)).toEqual({ host, port: 1433, portExplicit: false });
+ });
+});
diff --git a/apps/desktop/src/lib/sqlserver/sqlServerHostPort.ts b/apps/desktop/src/lib/sqlserver/sqlServerHostPort.ts
new file mode 100644
index 0000000000..9c8beff263
--- /dev/null
+++ b/apps/desktop/src/lib/sqlserver/sqlServerHostPort.ts
@@ -0,0 +1,59 @@
+export interface SqlServerHostPortResult {
+ host: string;
+ port?: number;
+ portExplicit: boolean;
+}
+
+export function parseSqlServerHostPort(rawHost: string, currentPort?: number): SqlServerHostPortResult {
+ let host = (rawHost ?? "").trim();
+ if (!host) {
+ return { host: "", port: currentPort, portExplicit: false };
+ }
+
+ // Strip case-insensitive tcp: prefix
+ if (host.toLowerCase().startsWith("tcp:")) {
+ host = host.slice(4).trim();
+ }
+
+ // Bracketed IPv6: [fe80::1],9005 or [::1]:9005 or [::1]
+ if (host.startsWith("[")) {
+ const close = host.indexOf("]");
+ if (close !== -1) {
+ const bracketed = host.slice(0, close + 1);
+ const remainder = host.slice(close + 1).trim();
+ if (remainder.startsWith(",") || remainder.startsWith(":")) {
+ const portStr = remainder.slice(1).trim();
+ const parsed = Number(portStr);
+ if (/^[0-9]+$/.test(portStr) && Number.isInteger(parsed) && parsed > 0 && parsed <= 65535) {
+ return { host: bracketed, port: parsed, portExplicit: true };
+ }
+ }
+ return { host: remainder ? host : bracketed, port: currentPort, portExplicit: false };
+ }
+ }
+
+ // Comma-separated port: host,port or host\instance,port
+ const commaIdx = host.lastIndexOf(",");
+ if (commaIdx !== -1) {
+ const candidateHost = host.slice(0, commaIdx).trim();
+ const portStr = host.slice(commaIdx + 1).trim();
+ const parsed = Number(portStr);
+ if (/^[0-9]+$/.test(portStr) && Number.isInteger(parsed) && parsed > 0 && parsed <= 65535) {
+ return { host: candidateHost, port: parsed, portExplicit: true };
+ }
+ }
+
+ // Colon-separated port: host:port (single colon only to avoid unbracketed IPv6)
+ const colonCount = (host.match(/:/g) || []).length;
+ if (colonCount === 1) {
+ const colonIdx = host.lastIndexOf(":");
+ const candidateHost = host.slice(0, colonIdx).trim();
+ const portStr = host.slice(colonIdx + 1).trim();
+ const parsed = Number(portStr);
+ if (/^[0-9]+$/.test(portStr) && Number.isInteger(parsed) && parsed > 0 && parsed <= 65535) {
+ return { host: candidateHost, port: parsed, portExplicit: true };
+ }
+ }
+
+ return { host, port: currentPort, portExplicit: false };
+}
diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs
index 3683548e12..544a7ec83b 100644
--- a/crates/dbx-core/src/connection/mod.rs
+++ b/crates/dbx-core/src/connection/mod.rs
@@ -6774,7 +6774,9 @@ impl ConnectionEndpoint {
}
fn connection_remote_endpoint(config: &ConnectionConfig) -> (String, u16) {
- if config.db_type == DatabaseType::MongoDb {
+ if config.db_type == DatabaseType::SqlServer {
+ sqlserver_tcp_endpoint(&config.host, config.port)
+ } else if config.db_type == DatabaseType::MongoDb {
config
.connection_string
.as_deref()
@@ -7543,7 +7545,11 @@ pub async fn probe_connection_endpoint(config: &ConnectionConfig, host: &str, po
}
let timeout = std::time::Duration::from_secs(config.effective_connect_timeout_secs());
- let entries = connection_probe_endpoints(host, port);
+ let entries = if config.db_type == DatabaseType::SqlServer {
+ vec![sqlserver_tcp_endpoint(host, port)]
+ } else {
+ connection_probe_endpoints(host, port)
+ };
if entries.is_empty() {
return Err("no host entries to probe".to_string());
@@ -7561,6 +7567,14 @@ pub async fn probe_connection_endpoint(config: &ConnectionConfig, host: &str, po
Err(last_error)
}
+fn sqlserver_tcp_endpoint(host: &str, port: u16) -> (String, u16) {
+ let (host, parsed_port) = dbx_types::models::connection::normalize_sqlserver_host_port(host);
+ // TCP probes and transport layers expect a raw IPv6 address, unlike
+ // Tiberius' combined "[host]:port" string.
+ let probe_host = host.strip_prefix('[').and_then(|value| value.strip_suffix(']')).unwrap_or(&host);
+ (probe_host.to_string(), parsed_port.unwrap_or(port))
+}
+
fn connection_probe_endpoints(host: &str, default_port: u16) -> Vec<(String, u16)> {
host.split(',').filter_map(|part| parse_connection_probe_endpoint(part.trim(), default_port)).collect()
}
@@ -12293,6 +12307,35 @@ for line in sys.stdin:
assert_eq!(connection_remote_endpoint(&config), ("broker.internal".to_string(), 8443));
}
+ #[test]
+ fn sqlserver_connection_remote_endpoint_parses_comma_and_colon_port() {
+ let mut config = mysql_config(None);
+ config.db_type = DatabaseType::SqlServer;
+ config.host = "gg.test.com,9005".to_string();
+ config.port = 1433;
+ assert_eq!(connection_remote_endpoint(&config), ("gg.test.com".to_string(), 9005));
+
+ config.host = "tcp:sql.example.com,1444".to_string();
+ assert_eq!(connection_remote_endpoint(&config), ("sql.example.com".to_string(), 1444));
+
+ config.host = "sql.example.com".to_string();
+ assert_eq!(connection_remote_endpoint(&config), ("sql.example.com".to_string(), 1433));
+
+ config.host = "[::1],9005".to_string();
+ assert_eq!(connection_remote_endpoint(&config), ("::1".to_string(), 9005));
+ }
+
+ #[test]
+ fn sqlserver_probe_resolves_bracketed_ipv6_without_retargeting_invalid_ports() {
+ use std::net::ToSocketAddrs;
+ for host in ["[::1],9005", "[::1]:9005", "tcp:[::1],9005"] {
+ let endpoint = super::sqlserver_tcp_endpoint(host, 1433);
+ let address = (endpoint.0.as_str(), endpoint.1).to_socket_addrs().unwrap().next().unwrap();
+ assert_eq!(address, "[::1]:9005".parse::<std::net::SocketAddr>().unwrap());
+ }
+ assert_eq!(super::sqlserver_tcp_endpoint("[::1],70000", 1433), ("[::1],70000".to_string(), 1433));
+ }
+
#[test]
fn kafka_loopback_bootstrap_endpoint_requires_one_ipv4_loopback_server() {
assert_eq!(
diff --git a/crates/dbx-driver-sqlserver/src/sqlserver.rs b/crates/dbx-driver-sqlserver/src/sqlserver.rs
index f9eb449769..827d7efc01 100644
--- a/crates/dbx-driver-sqlserver/src/sqlserver.rs
+++ b/crates/dbx-driver-sqlserver/src/sqlserver.rs
@@ -303,13 +303,15 @@ struct SqlServerEndpoint<'a> {
}
fn sqlserver_endpoint(host: &str) -> SqlServerEndpoint<'_> {
- if let Some((server, instance)) = host.split_once('\\') {
+ let trimmed = host.trim();
+ let without_tcp = if trimmed.to_ascii_lowercase().starts_with("tcp:") { trimmed[4..].trim() } else { trimmed };
+ if let Some((server, instance)) = without_tcp.split_once('\\') {
if !server.trim().is_empty() && !instance.trim().is_empty() {
return SqlServerEndpoint { host: server.trim(), instance_name: Some(instance.trim()) };
}
}
- SqlServerEndpoint { host: host.trim(), instance_name: None }
+ SqlServerEndpoint { host: without_tcp, instance_name: None }
}
fn sqlserver_uses_named_instance_resolution(endpoint: &SqlServerEndpoint<'_>, port: u16, port_explicit: bool) -> bool {
@@ -498,9 +500,9 @@ async fn try_connect(
timeout: Duration,
) -> Result<SqlServerClient, String> {
let deadline = tokio::time::Instant::now() + timeout;
- let mut current_host = host.to_string();
- let mut current_port = port;
- let mut current_port_explicit = port_explicit;
+ let (mut current_host, parsed_port) = dbx_types::models::connection::normalize_sqlserver_host_port(host);
+ let mut current_port = parsed_port.unwrap_or(port);
+ let mut current_port_explicit = port_explicit || parsed_port.is_some();
let mut redirects = 0;
loop {
@@ -4804,6 +4806,18 @@ mod tests {
);
}
+ #[test]
+ fn sqlserver_endpoint_strips_tcp_prefix() {
+ assert_eq!(
+ super::sqlserver_endpoint(r"tcp:192.168.1.10\SQL2022"),
+ super::SqlServerEndpoint { host: "192.168.1.10", instance_name: Some("SQL2022") }
+ );
+ assert_eq!(
+ super::sqlserver_endpoint("tcp:db.example.com"),
+ super::SqlServerEndpoint { host: "db.example.com", instance_name: None }
+ );
+ }
+
#[test]
fn sqlserver_named_instance_resolution_yields_to_explicit_port() {
let endpoint = super::sqlserver_endpoint(r"db.example.com\SQLEXPRESS");
diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rs
index 6006f718cb..01bb8bd200 100644
--- a/crates/dbx-types/src/models/connection.rs
+++ b/crates/dbx-types/src/models/connection.rs
@@ -1180,12 +1180,20 @@ impl ConnectionConfig {
config.driver_profile = Some("mongodb".to_string());
config.driver_label = Some("MongoDB".to_string());
}
- if config.db_type == DatabaseType::SqlServer
- && sqlserver_legacy_compatibility_param(config.url_params.as_deref())
- {
- config.driver_profile = Some("sqlserver-legacy".to_string());
- config.driver_label = Some("SQL Server legacy compatibility component".to_string());
- config.url_params = without_sqlserver_legacy_compatibility_param(config.url_params.as_deref());
+ if config.db_type == DatabaseType::SqlServer {
+ let (normalized_host, parsed_port) = normalize_sqlserver_host_port(&config.host);
+ config.host = normalized_host;
+ if let Some(port) = parsed_port {
+ config.port = port;
+ let mut ext = config.external_config.as_ref().and_then(|v| v.as_object()).cloned().unwrap_or_default();
+ ext.insert("portExplicit".to_string(), serde_json::Value::Bool(true));
+ config.external_config = Some(serde_json::Value::Object(ext));
+ }
+ if sqlserver_legacy_compatibility_param(config.url_params.as_deref()) {
+ config.driver_profile = Some("sqlserver-legacy".to_string());
+ config.driver_label = Some("SQL Server legacy compatibility component".to_string());
+ config.url_params = without_sqlserver_legacy_compatibility_param(config.url_params.as_deref());
+ }
}
if config.db_type == DatabaseType::Mysql
&& config.driver_profile.as_deref().is_some_and(|profile| profile.eq_ignore_ascii_case("tdengine"))
@@ -3084,6 +3092,58 @@ fn gaussdb_single_host_port(host: &str, default_port: u16) -> (String, u16) {
(bracket_ipv6(host), default_port)
}
+pub fn normalize_sqlserver_host_port(raw_host: &str) -> (String, Option<u16>) {
+ let parse_port = |value: &str| {
+ let value = value.trim();
+ if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
+ return None;
+ }
+ value.parse::<u16>().ok().filter(|port| *port > 0)
+ };
+ let trimmed = raw_host.trim();
+ if trimmed.is_empty() {
+ return (String::new(), None);
+ }
+
+ let without_tcp = if trimmed.to_ascii_lowercase().starts_with("tcp:") { trimmed[4..].trim() } else { trimmed };
+
+ // Bracketed IPv6: [fe80::1],9005 or [::1]:9005 or [::1]
+ if without_tcp.starts_with('[') {
+ if let Some(close) = without_tcp.find(']') {
+ let bracketed = &without_tcp[..=close];
+ let remainder = without_tcp[close + 1..].trim();
+ if let Some(port_str) = remainder.strip_prefix(',').or_else(|| remainder.strip_prefix(':')) {
+ if let Some(port) = parse_port(port_str) {
+ return (bracketed.to_string(), Some(port));
+ }
+ }
+ return (if remainder.is_empty() { bracketed } else { without_tcp }.to_string(), None);
+ }
+ }
+
+ // Comma-separated port: host,port or host\instance,port
+ if let Some((server_part, port_part)) = without_tcp.rsplit_once(',') {
+ let candidate_host = server_part.trim();
+ let candidate_port = port_part.trim();
+ if let Some(port) = parse_port(candidate_port) {
+ return (candidate_host.to_string(), Some(port));
+ }
+ }
+
+ // Colon-separated port: host:port (single colon only to avoid unbracketed IPv6)
+ if without_tcp.matches(':').count() == 1 {
+ if let Some((server_part, port_part)) = without_tcp.rsplit_once(':') {
+ let candidate_host = server_part.trim();
+ let candidate_port = port_part.trim();
+ if let Some(port) = parse_port(candidate_port) {
+ return (candidate_host.to_string(), Some(port));
+ }
+ }
+ }
+
+ (without_tcp.to_string(), None)
+}
+
#[cfg(test)]
mod tests {
#[test]
@@ -4169,6 +4229,64 @@ mod tests {
assert_eq!(canonical.url_params.as_deref(), Some("applicationName=dbx&encrypt=false"));
}
+ #[test]
+ fn normalize_sqlserver_host_port_handles_commas_colons_and_tcp_prefix() {
+ assert_eq!(super::normalize_sqlserver_host_port("gg.test.com,9005"), ("gg.test.com".to_string(), Some(9005)));
+ assert_eq!(
+ super::normalize_sqlserver_host_port("tcp:gg.test.com,9005"),
+ ("gg.test.com".to_string(), Some(9005))
+ );
+ assert_eq!(super::normalize_sqlserver_host_port("tcp:gg.test.com"), ("gg.test.com".to_string(), None));
+ assert_eq!(super::normalize_sqlserver_host_port("gg.test.com:9005"), ("gg.test.com".to_string(), Some(9005)));
+ assert_eq!(
+ super::normalize_sqlserver_host_port(" 192.168.1.100, 14333 "),
+ ("192.168.1.100".to_string(), Some(14333))
+ );
+ assert_eq!(
+ super::normalize_sqlserver_host_port(r"192.168.1.10\SQL2022,14333"),
+ (r"192.168.1.10\SQL2022".to_string(), Some(14333))
+ );
+ assert_eq!(
+ super::normalize_sqlserver_host_port(r"tcp:192.168.1.10\SQL2022"),
+ (r"192.168.1.10\SQL2022".to_string(), None)
+ );
+ assert_eq!(super::normalize_sqlserver_host_port("[::1],9005"), ("[::1]".to_string(), Some(9005)));
+ assert_eq!(super::normalize_sqlserver_host_port("[::1]:9005"), ("[::1]".to_string(), Some(9005)));
+ assert_eq!(super::normalize_sqlserver_host_port("[fe80::1]"), ("[fe80::1]".to_string(), None));
+ assert_eq!(super::normalize_sqlserver_host_port("localhost"), ("localhost".to_string(), None));
+ assert_eq!(super::normalize_sqlserver_host_port(""), ("".to_string(), None));
+ }
+
+ #[test]
+ fn sqlserver_canonicalized_normalizes_host_with_port_and_sets_explicit_flag() {
+ let mut config = mysql_config("sa", "secret", Some("master"));
+ config.db_type = DatabaseType::SqlServer;
+ config.host = "gg.test.com,9005".to_string();
+ config.port = 1433;
+
+ let canonical = config.canonicalized();
+ assert_eq!(canonical.host, "gg.test.com");
+ assert_eq!(canonical.port, 9005);
+ assert!(canonical.sqlserver_port_explicit());
+
+ let mut tcp_config = mysql_config("sa", "secret", Some("master"));
+ tcp_config.db_type = DatabaseType::SqlServer;
+ tcp_config.host = "tcp:sql.example.com,1444".to_string();
+ tcp_config.port = 1433;
+
+ let canonical_tcp = tcp_config.canonicalized();
+ assert_eq!(canonical_tcp.host, "sql.example.com");
+ assert_eq!(canonical_tcp.port, 1444);
+ assert!(canonical_tcp.sqlserver_port_explicit());
+ }
+
+ #[test]
+ fn sqlserver_invalid_endpoint_text_is_not_silently_retargeted() {
+ for host in ["[::1],70000", "[::1]:oops", "[::1]:0", "[::1]unexpected", "server:1e3", "server,0x599"] {
+ assert_eq!(super::normalize_sqlserver_host_port(host), (host.to_string(), None));
+ }
+ }
+
#[test]
fn informix_empty_database_uses_sysmaster_for_connection() {
let mut config = mysql_config("informix", "in4mix", None);
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index d832b6bd45..5f44ea28bf 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -1457,7 +1457,11 @@ async fn test_connection_with_info_impl(
state: &Arc<AppState>,
config: ConnectionConfig,
) -> Result<ConnectionTestResult, String> {
- let config = if config.uses_mongodb_oidc() { config.canonicalized() } else { config };
+ let config = if config.uses_mongodb_oidc() || config.db_type == DatabaseType::SqlServer {
+ config.canonicalized()
+ } else {
+ config
+ };
let tunnel_id = format!("{}:test", config.id);
let has_transport_layers = config.has_effective_transport_layers();
let connection_id = if has_transport_layers { tunnel_id.as_str() } else { config.id.as_str() };