Skip to content

MSSQL: NULL Option<T> parameters are declared as nvarchar(1) #58

Closed

Description

@lovasoa

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') returns h, with length 1.
  • COALESCE(@p1, N'hello') returns hello.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions