Generate struct from query statement #2729
oOBoomberOo
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
While
FromRow
andquery!()
have been a huge improvement for ensuring the type-correctness with the database. I started noticing a pattern emerging in my code that works in the opposite direction ofFromRow
, so I'd like to see what you think of this.sqlx::data_source
is a macro that generates a named struct that contains fields of what the specified query statement returns. You can think of it as the opposite of anonymous structs generated by thequery!()
macro.While
FromRow
defines a way to map the database values into an existing struct, this macro defines a new struct that maps into the database values.Here's some code example to express my idea:
I think this makes it easy to keep the structs consistent with the table, allows you to reuse queries, and unlike anonymous structs, the type can be used in function parameters and return types.
You could even store the query in a trait and make the struct 'executable', e.g.
Beta Was this translation helpful? Give feedback.
All reactions