Select of a hardcoded value returns Option<T> instead of just T
Bug Description
When including hardcoded values in a SELECT statement, the value that is returned by sqlx is an Option<T> type.
For example;
let record = query!("SELECT true as value").fetch_one(conn).await?;
println!("{:?}", record.value);
results in;
Some(true)
While I would expect that this should not have to be an option, since it is guaranteed that the value is always present.
Minimal Reproduction
Info
- SQLx version: 0.7.3
- SQLx features enabled: postgres, runtime-tokio
- Database server and version: (Running in docker:) PostgreSQL 16.1 (Debian 16.1-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
- Operating system: Pop!_OS 22.04 LTS x86_64
-
rustc --version: 1.80.1
This is a known issue because of how null inference works in the Postgres driver. Null inference takes its seed data from NOT NULL flags on table columns, so any output that doesn't come from a table can't be null-checked.
This is explained in the documentation: https://docs.rs/sqlx/latest/sqlx/macro.query.html#nullability-output-columns
Fixing this would require parsing the query, which is kind of a non-starter. There are crates that exist for this, but I'm not particularly impressed with them. The performance of the query macros depends highly on the amount of code that runs in them since they compile in debug mode by default, so the less we run the better.
The EXPLAIN output does include the expression for each column, so we could limit ourselves to just parsing the expression itself. That's something we could potentially do in-tree.