sqlx
sqlx copied to clipboard
Document how to use `Json<T>` with the query macros
Bug Description
The Json support for postgresql only works through the usage of the Value type. The Json type when used as show in the documentation doesn't work : https://docs.rs/sqlx/latest/sqlx/types/struct.Json.html
I've checked the source and I have the feeling that the Json module is not covered by tests, it may have been broken in one refactoring.
Minimal Reproduction
I've made a minimal repo that repro the compiler error.
https://github.com/ElysaSrc/repro-sqlx-json-bug
Info
- SQLx version: 0.7.4
- SQLx features enabled:
["runtime-tokio","tls-rustls","postgres","chrono","migrate","uuid","json"]
- Database server and version: Postgres 14
- Operating system: Nixos unstable - Linux 6.7.9
-
rustc --version
: rustc 1.77.0 (aedd173a2 2024-03-17)
Not a bug. The query macros map JSON columns to serde_json::Value
by default. You have to tell the macro to use the Json
adapter using the type override syntax: https://docs.rs/sqlx/latest/sqlx/macro.query.html#force-a-differentcustom-type
See this example (uses query!()
but the concept is the same): https://github.com/launchbadge/sqlx/blob/main/examples/postgres/json/src/main.rs#L80
Note also that query_as!()
does not currently use FromRow
as stated in the docs: https://docs.rs/sqlx/latest/sqlx/macro.query_as.html
Leaving this open as a documentation issue.
It is indeed working as intended when the types are set in the request. Sorry for the false bug.
Hey there, would be open to take this on. @ElysaSrc, where would you have wished to find the hint regarding the need to use the Json
adapter?
I just ran into this myself. It would be nice if the docs for the Json<>
type mentioned that you need to do the type override thing, with an example. From the examples on that page, I assumed it would work with the macros, and was surprised when it didn't.
@dyc3 I took a shot at writing down what you recommended. Is it helpful?
Yes! That's exactly what I was looking for.
#3447 would have been what I was looking for too! Thanks, sorry for the delay to respond.
Thanks for the Feedback! I will fix the doctests when I get home today so that the PR is mergeable.