sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Document how to use `Json<T>` with the query macros

Open ElysaSrc opened this issue 11 months ago • 2 comments

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)

ElysaSrc avatar Mar 25 '24 07:03 ElysaSrc

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.

abonander avatar Mar 25 '24 08:03 abonander

It is indeed working as intended when the types are set in the request. Sorry for the false bug.

ElysaSrc avatar Mar 25 '24 08:03 ElysaSrc

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?

Lachstec avatar Aug 16 '24 13:08 Lachstec

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 avatar Aug 20 '24 16:08 dyc3

@dyc3 I took a shot at writing down what you recommended. Is it helpful?

Lachstec avatar Aug 20 '24 18:08 Lachstec

Yes! That's exactly what I was looking for.

dyc3 avatar Aug 20 '24 19:08 dyc3

#3447 would have been what I was looking for too! Thanks, sorry for the delay to respond.

ElysaSrc avatar Aug 20 '24 19:08 ElysaSrc

Thanks for the Feedback! I will fix the doctests when I get home today so that the PR is mergeable.

Lachstec avatar Aug 21 '24 07:08 Lachstec