fix(sqlserver): preserve explicit instance ports

This commit is contained in:
zipg authored and GitHub committed 2026-07-14 01:27:40 +08:00
1 parent 8e87ab2e39
commit 8020fe5886
12 files changed
+237 -26

No files matched your search

+46 -13
View File
@@ -18,6 +18,7 @@ pub type SqlServerClient = Client<Compat<TcpStream>>;
pub const SQLSERVER_DRIVER_PANIC_ERROR_PREFIX: &str = "SQL Server driver panic:";
pub const SQLSERVER_LEGACY_DRIVER_PROFILE: &str = "sqlserver-legacy";
pub const SQLSERVER_LEGACY_DRIVER_LABEL: &str = "SQL Server legacy compatibility component";
const SQLSERVER_DEFAULT_PORT: u16 = 1433;
const SIMPLE_QUERY_MODULE_KEYWORDS: &[&str] = &["FUNCTION", "PROC", "PROCEDURE", "TRIGGER", "VIEW"];
// Match JDBC/tiberius `encrypt=false`: encrypt only login, then drop back to raw TDS.
const SQLSERVER_LEGACY_ENCRYPTION_LEVEL: tiberius::EncryptionLevel = tiberius::EncryptionLevel::Off;
@@ -45,6 +46,10 @@ fn sqlserver_endpoint(host: &str) -> SqlServerEndpoint<'_> {
SqlServerEndpoint { host: host.trim(), instance_name: None }
}
fn sqlserver_uses_named_instance_resolution(endpoint: &SqlServerEndpoint<'_>, port: u16, port_explicit: bool) -> bool {
endpoint.instance_name.is_some() && (port == 0 || (port == SQLSERVER_DEFAULT_PORT && !port_explicit))
}
fn query_result_row_limit(max_rows: Option<usize>) -> usize {
max_rows.unwrap_or(MAX_ROWS).max(1)
}
@@ -58,13 +63,28 @@ pub async fn connect(
_url_params: Option<&str>,
timeout: Duration,
) -> Result<SqlServerClient, String> {
match try_connect(host, port, user, pass, database, tiberius::EncryptionLevel::Required, timeout).await {
connect_with_port_explicit(host, port, false, user, pass, database, timeout).await
}
pub async fn connect_with_port_explicit(
host: &str,
port: u16,
port_explicit: bool,
user: &str,
pass: &str,
database: Option<&str>,
timeout: Duration,
) -> Result<SqlServerClient, String> {
match try_connect(host, port, port_explicit, user, pass, database, tiberius::EncryptionLevel::Required, timeout)
.await
{
Ok(client) => Ok(client),
Err(encrypted_error) => try_connect_legacy_sqlserver_encryption(host, port, user, pass, database, timeout)
.await
.map_err(|plain_error| {
if is_sqlserver_tls_handshake_error(&encrypted_error) {
format!(
Err(encrypted_error) => {
try_connect_legacy_sqlserver_encryption(host, port, port_explicit, user, pass, database, timeout)
.await
.map_err(|plain_error| {
if is_sqlserver_tls_handshake_error(&encrypted_error) {
format!(
"{encrypted_error}\n\nThis may be caused by an old SQL Server TLS/encryption configuration. \
If you are connecting to SQL Server 2008/2008 R2/2012 or another legacy instance, \
try SQL Server legacy compatibility mode. It first behaves like encrypt=false and, \
@@ -73,16 +93,18 @@ pub async fn connect(
or SSH tunnels.\n\n\
Automatic native legacy fallback also failed: {plain_error}"
)
} else {
plain_error
}
}),
} else {
plain_error
}
})
}
}
}
async fn try_connect_legacy_sqlserver_encryption(
host: &str,
port: u16,
port_explicit: bool,
user: &str,
pass: &str,
database: Option<&str>,
@@ -90,7 +112,7 @@ async fn try_connect_legacy_sqlserver_encryption(
) -> Result<SqlServerClient, String> {
let mut errors = Vec::new();
for (label, encryption) in SQLSERVER_LEGACY_ENCRYPTION_FALLBACKS {
match try_connect(host, port, user, pass, database, encryption, timeout).await {
match try_connect(host, port, port_explicit, user, pass, database, encryption, timeout).await {
Ok(client) => return Ok(client),
Err(error) => errors.push(format!("{label} failed: {error}")),
}
@@ -120,6 +142,7 @@ fn is_sqlserver_tls_handshake_error(error: &str) -> bool {
async fn try_connect(
host: &str,
port: u16,
port_explicit: bool,
user: &str,
pass: &str,
database: Option<&str>,
@@ -128,8 +151,9 @@ async fn try_connect(
) -> Result<SqlServerClient, String> {
let mut config = Config::new();
let endpoint = sqlserver_endpoint(host);
let uses_named_instance_resolution = sqlserver_uses_named_instance_resolution(&endpoint, port, port_explicit);
config.host(endpoint.host);
if let Some(instance_name) = endpoint.instance_name {
if let Some(instance_name) = endpoint.instance_name.filter(|_| uses_named_instance_resolution) {
config.instance_name(instance_name);
} else {
config.port(port);
@@ -141,7 +165,7 @@ async fn try_connect(
config.trust_cert();
config.encryption(encryption);
let tcp = if endpoint.instance_name.is_some() {
let tcp = if uses_named_instance_resolution {
tokio::time::timeout(timeout, TcpStream::connect_named(&config))
.await
.map_err(|_| format!("SQL Server connection timed out ({}s)", timeout.as_secs()))?
@@ -1893,6 +1917,15 @@ mod tests {
);
}
#[test]
fn sqlserver_named_instance_resolution_yields_to_explicit_port() {
let endpoint = super::sqlserver_endpoint(r"db.example.com\SQLEXPRESS");
assert!(super::sqlserver_uses_named_instance_resolution(&endpoint, 0, false));
assert!(super::sqlserver_uses_named_instance_resolution(&endpoint, 1433, false));
assert!(!super::sqlserver_uses_named_instance_resolution(&endpoint, 1433, true));
assert!(!super::sqlserver_uses_named_instance_resolution(&endpoint, 40030, false));
}
#[test]
fn sqlserver_connect_uses_named_instance_resolution() {
let source = include_str!("sqlserver.rs");