diff --git a/apps/desktop/src/lib/__tests__/connection/sqlServerLegacyCompatibility.spec.ts b/apps/desktop/src/lib/__tests__/connection/sqlServerLegacyCompatibility.spec.ts index 28f75a7dd1..aaf59d626f 100644 --- a/apps/desktop/src/lib/__tests__/connection/sqlServerLegacyCompatibility.spec.ts +++ b/apps/desktop/src/lib/__tests__/connection/sqlServerLegacyCompatibility.spec.ts @@ -1,5 +1,12 @@ import { describe, expect, it } from "vitest"; -import { isSqlServerNativeEncryptionDisabled, requiresSqlServerLegacyCompatibilityComponent, setSqlServerLegacyCompatibilityConfig, setSqlServerNativeEncryptionDisabled, sqlServerUsesLegacyCompatibility } from "@/lib/connection/sqlServerLegacyCompatibility"; +import { + isSqlServerNativeEncryptionDisabled, + migrateSqlServerLegacyCompatibilityConfig, + requiresSqlServerLegacyCompatibilityComponent, + setSqlServerLegacyCompatibilityConfig, + setSqlServerNativeEncryptionDisabled, + sqlServerUsesLegacyCompatibility, +} from "@/lib/connection/sqlServerLegacyCompatibility"; import type { ConnectionConfig } from "@/types/database"; function connectionConfig(urlParams?: string): ConnectionConfig { @@ -37,11 +44,14 @@ describe("SQL Server legacy compatibility", () => { expect(setSqlServerNativeEncryptionDisabled("applicationName=dbx;sqlserverEncryption=disabled", false)).toBe("applicationName=dbx"); }); - it("keeps historical disabled-encryption connections on the native driver", () => { + it("migrates historical disabled-encryption connections to the legacy driver profile", () => { const config = connectionConfig("sqlserverEncryption=disabled"); + migrateSqlServerLegacyCompatibilityConfig(config); - expect(sqlServerUsesLegacyCompatibility(config)).toBe(false); - expect(requiresSqlServerLegacyCompatibilityComponent(config)).toBe(false); + expect(sqlServerUsesLegacyCompatibility(config)).toBe(true); + expect(requiresSqlServerLegacyCompatibilityComponent(config)).toBe(true); + expect(config.driver_label).toBe("SQL Server legacy compatibility component"); + expect(config.url_params).toBe(""); expect( requiresSqlServerLegacyCompatibilityComponent({ ...config, @@ -51,6 +61,41 @@ describe("SQL Server legacy compatibility", () => { ).toBe(false); }); + it("preserves unrelated params while migrating the historical compatibility flag", () => { + const config = connectionConfig("applicationName=dbx;sqlserverEncryption=off;encrypt=false"); + + migrateSqlServerLegacyCompatibilityConfig(config); + + expect(config.driver_profile).toBe("sqlserver-legacy"); + expect(config.url_params).toBe("applicationName=dbx;encrypt=false"); + }); + + it("preserves semicolons and special characters inside braced values during migration", () => { + const config = connectionConfig("applicationName={DBX; Client};password=50%;sqlserverEncryption=disabled;encrypt=false"); + + migrateSqlServerLegacyCompatibilityConfig(config); + + expect(config.driver_profile).toBe("sqlserver-legacy"); + expect(config.url_params).toBe("applicationName={DBX; Client};password=50%;encrypt=false"); + }); + + it("keeps escaped closing braces from exposing separators inside braced values", () => { + const config = connectionConfig("applicationName={DBX}}; Client};sqlserverEncryption=disabled;encrypt=false"); + + migrateSqlServerLegacyCompatibilityConfig(config); + + expect(config.url_params).toBe("applicationName={DBX}}; Client};encrypt=false"); + }); + + it("keeps generic JDBC encrypt=false on the native driver", () => { + const config = connectionConfig("applicationName=dbx;encrypt=false"); + + migrateSqlServerLegacyCompatibilityConfig(config); + + expect(config.driver_profile).toBe("sqlserver"); + expect(config.url_params).toBe("applicationName=dbx;encrypt=false"); + }); + it("treats a persisted legacy driver profile as compatibility mode", () => { const config = connectionConfig(""); config.driver_profile = "sqlserver-legacy"; diff --git a/apps/desktop/src/lib/connection/sqlServerLegacyCompatibility.ts b/apps/desktop/src/lib/connection/sqlServerLegacyCompatibility.ts index a8349ce6ab..58787a8184 100644 --- a/apps/desktop/src/lib/connection/sqlServerLegacyCompatibility.ts +++ b/apps/desktop/src/lib/connection/sqlServerLegacyCompatibility.ts @@ -31,6 +31,62 @@ export function setSqlServerNativeEncryptionDisabled(params: string | undefined, return parsed.toString(); } +interface SqlServerJdbcParamPart { + separator: "" | "&" | ";"; + value: string; +} + +function splitSqlServerJdbcParams(params: string | undefined): SqlServerJdbcParamPart[] { + const source = (params || "").trim().replace(/^\?/, ""); + const parts: SqlServerJdbcParamPart[] = []; + let separator: SqlServerJdbcParamPart["separator"] = ""; + let start = 0; + let inBraces = false; + + // SQL Server JDBC values use braces to contain separators and `}}` to escape a closing brace. + for (let index = 0; index < source.length; index += 1) { + const char = source[index]; + if (inBraces) { + if (char === "}" && source[index + 1] === "}") { + index += 1; + } else if (char === "}") { + inBraces = false; + } + } else if (char === "{") { + inBraces = true; + } else if (char === "&" || char === ";") { + parts.push({ separator, value: source.slice(start, index) }); + separator = char; + start = index + 1; + } + } + + parts.push({ separator, value: source.slice(start) }); + return parts; +} + +function isSqlServerLegacyCompatibilityPart(part: string): boolean { + const separatorIndex = part.indexOf("="); + if (separatorIndex < 0) return false; + const key = part.slice(0, separatorIndex).trim().toLowerCase(); + const value = part + .slice(separatorIndex + 1) + .trim() + .toLowerCase(); + return key === "sqlserverencryption" && SQLSERVER_ENCRYPTION_DISABLED_VALUES.has(value); +} + +function isSqlServerLegacyCompatibilitySetting(params: string | undefined): boolean { + return splitSqlServerJdbcParams(params).some((part) => isSqlServerLegacyCompatibilityPart(part.value)); +} + +function removeSqlServerLegacyCompatibilitySetting(params: string | undefined): string { + return splitSqlServerJdbcParams(params) + .filter((part) => part.value.trim() && !isSqlServerLegacyCompatibilityPart(part.value)) + .map((part, index) => `${index === 0 ? "" : part.separator}${part.value}`) + .join(""); +} + export function sqlServerUsesLegacyCompatibility(config: Pick): boolean { return config.db_type === "sqlserver" && config.driver_profile === SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY; } @@ -40,6 +96,12 @@ export function setSqlServerLegacyCompatibilityConfig(config: Pick): void { + if (config.db_type !== "sqlserver" || !isSqlServerLegacyCompatibilitySetting(config.url_params)) return; + setSqlServerLegacyCompatibilityConfig(config, true); + config.url_params = removeSqlServerLegacyCompatibilitySetting(config.url_params); +} + export function requiresSqlServerLegacyCompatibilityComponent(config: ConnectionConfig): boolean { return sqlServerUsesLegacyCompatibility(config); } diff --git a/apps/desktop/src/stores/__tests__/connectionStore.sqlserverLegacy.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.sqlserverLegacy.spec.ts index 4c5375a7a0..51b127e338 100644 --- a/apps/desktop/src/stores/__tests__/connectionStore.sqlserverLegacy.spec.ts +++ b/apps/desktop/src/stores/__tests__/connectionStore.sqlserverLegacy.spec.ts @@ -41,11 +41,11 @@ describe("connectionStore SQL Server legacy compatibility", () => { setActivePinia(createPinia()); }); - it("does not preinstall the legacy component for historical disabled-encryption configs", async () => { + it("migrates historical disabled-encryption configs and installs the legacy component", async () => { const connectDb = vi.fn().mockResolvedValue("sqlserver-1"); const installAgent = vi.fn().mockResolvedValue(undefined); - vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false })); + vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true })); vi.doMock("@/lib/backend/api", () => ({ connectDb, installAgent, @@ -56,8 +56,16 @@ describe("connectionStore SQL Server legacy compatibility", () => { const store = useConnectionStore(); await store.connect(sqlServerNativeConnectionWithDisabledEncryption()); - expect(installAgent).not.toHaveBeenCalled(); + expect(installAgent).toHaveBeenCalledWith("sqlserver-legacy"); expect(connectDb).toHaveBeenCalledTimes(1); + expect(connectDb).toHaveBeenCalledWith( + expect.objectContaining({ + driver_profile: "sqlserver-legacy", + driver_label: "SQL Server legacy compatibility component", + url_params: "", + }), + expect.any(Number), + ); }); it("reconnects persisted legacy profiles without reinstalling an installed component", async () => { @@ -66,6 +74,7 @@ describe("connectionStore SQL Server legacy compatibility", () => { const config = sqlServerNativeConnectionWithDisabledEncryption(); config.driver_profile = "sqlserver-legacy"; config.driver_label = "SQL Server legacy compatibility component"; + config.url_params = ""; vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true })); vi.doMock("@/lib/backend/api", () => ({ @@ -87,6 +96,7 @@ describe("connectionStore SQL Server legacy compatibility", () => { const connectDb = vi.fn().mockRejectedValue(new Error("TLS negotiation failed\nSQL Server error 18456: Login failed")); const installAgent = vi.fn().mockResolvedValue(undefined); const config = sqlServerNativeConnectionWithDisabledEncryption(); + config.url_params = ""; vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true })); vi.doMock("@/lib/backend/api", () => ({ diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts index b1d1602bc7..b19bf84e2c 100644 --- a/apps/desktop/src/stores/connectionStore.ts +++ b/apps/desktop/src/stores/connectionStore.ts @@ -54,7 +54,7 @@ import { collapseExpandedTreeNodes } from "@/lib/sidebar/sidebarTreeCollapse"; import { findDatabaseTreeNode } from "@/lib/sidebar/treeRefreshTarget"; import { shouldMarkDisconnected } from "@/lib/connection/connectionHealth"; import { connectionAttemptOriginalErrorMessage, connectionAttemptTimeoutMessage, connectionAttemptTimeoutMs } from "@/lib/connection/connectionAttemptTimeout"; -import { requiresSqlServerLegacyCompatibilityComponent, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility"; +import { migrateSqlServerLegacyCompatibilityConfig, requiresSqlServerLegacyCompatibilityComponent, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility"; import { deleteTabResultSnapshotsForOwner } from "@/lib/tabs/tabResultCache"; import { connectionUsesVisibleSchemaFilter, filterDatabaseNamesForConnection, filterSchemaNamesForConnection, filterVisibleDatabaseNames, normalizeVisibleDatabaseSelection } from "@/lib/database/visibleDatabases"; import { @@ -910,6 +910,8 @@ export const useConnectionStore = defineStore("connection", () => { } function normalizeConnection(config: ConnectionConfig): ConnectionConfig { + config = { ...config }; + migrateSqlServerLegacyCompatibilityConfig(config); const labelMap: Record = { mysql: "MySQL", postgres: "PostgreSQL", diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs index 2a1e4cbf11..4f53f140df 100644 --- a/crates/dbx-core/src/connection.rs +++ b/crates/dbx-core/src/connection.rs @@ -3965,12 +3965,13 @@ mod tests { } #[test] - fn sqlserver_legacy_url_param_does_not_force_agent_driver() { + fn sqlserver_legacy_url_param_requires_canonicalization_before_agent_driver_selection() { let mut config = mysql_config(Some("master")); config.db_type = DatabaseType::SqlServer; - config.url_params = Some("applicationName=dbx;encrypt=false".to_string()); + config.url_params = Some("applicationName=dbx;sqlserverEncryption=disabled".to_string()); assert!(!sqlserver_uses_legacy_driver(&config)); + assert!(sqlserver_uses_legacy_driver(&config.canonicalized())); } #[test] diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs index eabf053c92..a1db687881 100644 --- a/crates/dbx-core/src/models/connection.rs +++ b/crates/dbx-core/src/models/connection.rs @@ -892,6 +892,13 @@ impl ConnectionConfig { pub fn canonicalized(&self) -> Self { let mut config = self.clone(); + 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::Mysql && config.driver_profile.as_deref().is_some_and(|profile| profile.eq_ignore_ascii_case("tdengine")) { @@ -1384,6 +1391,68 @@ fn redis_url_params_enable_insecure(params: Option<&str>) -> bool { }) } +fn sqlserver_url_param_parts(params: Option<&str>) -> Vec<(Option, &str)> { + let source = params.unwrap_or("").trim().trim_start_matches('?'); + let mut parts = Vec::new(); + let mut separator = None; + let mut start = 0; + let mut in_braces = false; + let mut chars = source.char_indices().peekable(); + + // SQL Server JDBC values use braces to contain separators and `}}` to escape a closing brace. + while let Some((index, char)) = chars.next() { + if in_braces { + if char == '}' && chars.peek().is_some_and(|(_, next)| *next == '}') { + chars.next(); + } else if char == '}' { + in_braces = false; + } + } else if char == '{' { + in_braces = true; + } else if matches!(char, '&' | ';') { + parts.push((separator, &source[start..index])); + separator = Some(char); + start = index + char.len_utf8(); + } + } + + parts.push((separator, &source[start..])); + parts +} + +fn sqlserver_legacy_compatibility_part(part: &str) -> bool { + let Some((key, value)) = part.split_once('=') else { + return false; + }; + let disabled = + matches!(value.trim().to_ascii_lowercase().as_str(), "disabled" | "disable" | "false" | "0" | "off" | "no"); + key.trim().eq_ignore_ascii_case("sqlserverEncryption") && disabled +} + +fn sqlserver_legacy_compatibility_param(params: Option<&str>) -> bool { + sqlserver_url_param_parts(params).into_iter().any(|(_, part)| sqlserver_legacy_compatibility_part(part)) +} + +fn without_sqlserver_legacy_compatibility_param(params: Option<&str>) -> Option { + let retained = sqlserver_url_param_parts(params) + .into_iter() + .filter(|(_, part)| !part.trim().is_empty()) + .filter(|(_, part)| !sqlserver_legacy_compatibility_part(part)) + .collect::>(); + if retained.is_empty() { + return None; + } + + let mut output = String::new(); + for (index, (separator, part)) in retained.into_iter().enumerate() { + if index > 0 { + output.extend(separator); + } + output.push_str(part); + } + Some(output) +} + fn url_params_contains_flag(params: Option<&str>, key: &str, expected: &str) -> bool { params.unwrap_or("").trim().trim_start_matches('?').split(['&', ';']).filter_map(|part| part.split_once('=')).any( |(part_key, value)| part_key.trim().eq_ignore_ascii_case(key) && value.trim().eq_ignore_ascii_case(expected), @@ -2003,8 +2072,9 @@ fn bracket_ipv6(host: &str) -> String { mod tests { use super::{ database_info_from_protocol_value, default_query_timeout_secs, default_redis_key_separator, - default_ssh_connect_timeout_secs, ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType, - IdentifierCase, ProxyTunnelConfig, ProxyType, TransportLayerConfig, + default_ssh_connect_timeout_secs, sqlserver_legacy_compatibility_param, + without_sqlserver_legacy_compatibility_param, ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo, + DatabaseType, IdentifierCase, ProxyTunnelConfig, ProxyType, TransportLayerConfig, }; use std::str::FromStr; @@ -2491,6 +2561,49 @@ mod tests { assert!(!canonical.needs_bare_mysql()); } + #[test] + fn historical_sqlserver_legacy_setting_is_canonicalized_to_driver_profile() { + let mut config = mysql_config("sa", "secret", Some("master")); + config.db_type = DatabaseType::SqlServer; + config.driver_profile = Some("sqlserver".to_string()); + config.driver_label = Some("SQL Server".to_string()); + config.url_params = + Some("applicationName={DBX; Client};password=50%;sqlserverEncryption=disabled;encrypt=false".to_string()); + + let canonical = config.canonicalized(); + + assert_eq!(canonical.driver_profile.as_deref(), Some("sqlserver-legacy")); + assert_eq!(canonical.driver_label.as_deref(), Some("SQL Server legacy compatibility component")); + assert_eq!(canonical.url_params.as_deref(), Some("applicationName={DBX; Client};password=50%;encrypt=false")); + assert_eq!(without_sqlserver_legacy_compatibility_param(Some("sqlserverEncryption=disabled")), None); + } + + #[test] + fn sqlserver_legacy_migration_respects_escaped_braces() { + let params = "applicationName={DBX}}; Client};sqlserverEncryption=disabled;encrypt=false"; + + assert!(sqlserver_legacy_compatibility_param(Some(params))); + assert_eq!( + without_sqlserver_legacy_compatibility_param(Some(params)).as_deref(), + Some("applicationName={DBX}}; Client};encrypt=false") + ); + } + + #[test] + fn sqlserver_auto_profile_without_historical_setting_stays_native() { + let mut config = mysql_config("sa", "secret", Some("master")); + config.db_type = DatabaseType::SqlServer; + config.driver_profile = Some("sqlserver".to_string()); + config.driver_label = Some("SQL Server".to_string()); + config.url_params = Some("applicationName=dbx&encrypt=false".to_string()); + + let canonical = config.canonicalized(); + + assert_eq!(canonical.driver_profile.as_deref(), Some("sqlserver")); + assert_eq!(canonical.driver_label.as_deref(), Some("SQL Server")); + assert_eq!(canonical.url_params.as_deref(), Some("applicationName=dbx&encrypt=false")); + } + #[test] fn informix_empty_database_uses_sysmaster_for_connection() { let mut config = mysql_config("informix", "in4mix", None);