-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add JSON support to FromRow
derive
#2121
Conversation
Would love to see this happen! |
@95ulisse Why is wrapping I'm wary of having more than one thing to do something, cause that's just more to teach. |
@abonander It's not unacceptable, it's just a bit inconvenient in some situations. I think of this Just to keep the example of a generic metadata field, I often find myself writing a model like this one that I keep passing around in my application: pub struct SomeModel {
pub id: Uuid,
pub metadata: HashMap<string, string>,
} As it is right now, I can't just
And that's why I'm not a huge fan of each of them:
Having an As I said at the beginning, these are all just annoyances, not real blocking problems. If we could find a way to make it work with the existing |
6cf15b0
to
eade49c
Compare
After thinking about this more, I will accept this as I want to land something similar for converting to/from types using their @95ulisse do you mind rebasing and fixing the merge conflicts? |
@abonander I've rebased the PR and fixed the conflicts. I've also added a bit of docs to the |
Hello 👋
This PR is a proposal to discuss JSON support for the
FromRow
derive. The proposal is to add a newjson
attribute to indicate that a field should be decoded usingsqlx::types::Json
instead of the field type.Motivation
The currently existing derive for
FromRow
allows quick and easy type conversions usingTryFrom
. This saves us a lot of boilerplate code just for the sake of converting types. UnfortunatelyTryFrom
-based conversions are not enough for json values:Due to Rust's rules, we can't just add an
impl<T> From<Json<T>> for T
as that would violate the orphan rules, so at the moment, we are stuck with one of two solutions:metadata
field fromMetadata
toJson<Metadata>
.FromRow
.Neither of these two solutions are ideal IMHO, hence this proposal of adding a new
json
attribute that will take care of the JSON deserialization and all the necessary type conversions. Using this new attribute, the previous example would become:Example generated code
The example above would (roughly) expand to:
Interactions with the already existing attributes
rename
anddefault
. They work as before, no interference withjson
.flatten
. I don't think it makes sense to use bothflatten
andjson
on the same field, so this combination is rejected.try_from
. If we have a field#[sqlx(json, try_from = "X")] field: Y
, the value will be first deserialized toX
and then converted usingstd::convert::TryFrom
toY
.