Repository navigation
Description
Problem
A bound None::<String> is declared as nvarchar(1) for MSSQL. This makes T-SQL expressions that take their result type from that parameter silently truncate fallback values:
ISNULL(@p1, N'hello')returnsh, with length 1.COALESCE(@p1, N'hello')returnshello.
Minimal repro (SQLx only)
Cargo.toml:
[dependencies]
sqlx-oldapi = { version = "0.6.56", features = ["runtime-tokio-rustls", "mssql"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }src/main.rs:
use sqlx_oldapi::{mssql::MssqlPoolOptions, Row};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = std::env::var("DATABASE_URL")?;
let pool = MssqlPoolOptions::new().connect(&url).await?;
let row = sqlx_oldapi::query(
r#"
SELECT
ISNULL(@p1, N'hello') AS isnull_value,
COALESCE(@p1, N'hello') AS coalesce_value,
LEN(ISNULL(@p1, N'hello')) AS isnull_len
"#,
)
.bind(None::<String>)
.fetch_one(&pool)
.await?;
let isnull_value: String = row.try_get("isnull_value")?;
let coalesce_value: String = row.try_get("coalesce_value")?;
let isnull_len: i32 = row.try_get("isnull_len")?;
println!("ISNULL=[{isnull_value}], COALESCE=[{coalesce_value}], len={isnull_len}");
Ok(())
}Run against a reachable SQL Server with DATABASE_URL set. With the current driver, output is ISNULL=[h], COALESCE=[hello], len=1. Expected output is ISNULL=[hello], COALESCE=[hello], len=5.
Diagnosis / references
Encode<Mssql> for Option<T>::produces returns the special DataType::Null for None (source). DataType::Null formats as nvarchar(1) (source). MssqlArguments::add uses this same type both to build the sp_executesql parameter declaration and to encode the TDS value (source).
SQL Server requires each sp_executesql parameter definition to name a data type, and ISNULL returns the type of its first expression, truncating a longer replacement to that type's length (sp_executesql docs, ISNULL docs). The TDS spec permits clients to send NULLTYPE in an RPC request (MS-TDS product behavior).
A possible fix is to keep the null wire encoding but derive the SQL parameter declaration from T::type_info() for None. In particular, Option<String> should be declared as nvarchar(max) (the static MSSQL type for str), not nvarchar(1).
Related SQLPage report: sqlpage/SQLPage#1481
Activity
test(mssql): replace null declaration test with ISNULL query covering #…
test(mssql): e2e test for ISNULL with null parameter (issue #58)
MSSQL: preserve bound type for NULL parameter declarations (#59)