5 definitions for the one simple struct
/table, is this standard? - Can we have a DRY alternative?
#4329
Replies: 1 comment
-
I think you have a massive misunderstanding on how these types can and should play together. They might look similar in your case, but in practice they are different. The first observation is that you can either generate 2 from 1 or vice versa. So, sure you can count them as two types but you don't need to write both. Any other type is strictly speaking optional. It's up to you and your use-cases how you design and use these types. For complex applications it's advice to have three different types there as the field of these types tend to quickly diverge based on your needs. That is something that you likely observe as soon as your application grows for some while. Anyway let's go through the other variants one by one. Struct 0 might seems like a "model" struct that maps 1:1 to tables, but that's a false assumption. These structs map 1:1 to query results, which can and often do include fields from more than one table. For struct 3 and 4 I personally do not see the point why you keep separate structs there, as nothing is stopping you to put the This leaves us with 3 out of those 5 types that you need to write: Struct 0, the SQL in 2 and struct 4. Now take a step back and look why this is the case:
So in the end it's all about flexibility: Instead of having a strict restrictive 1 table maps to 1 struct model diesel allows you to mix and match structs as required. That gives you the ability to only load/insert what you really need to load and insert, which makes your applications more performant and easier to maintain in the long run. The disadvantage is that you as an author are responsible for describing what you want.
Sure the easy case might seem obvious, but that becomes complicated really quickly. For example: Which type to choose for the timestamp?
This was discussed quite often in the issue tracker, so yes you would have been able to find an answer to that with rather minimal effort, eg by looking at this issue |
Beta Was this translation helpful? Give feedback.
-
Extracting out a little bit of almost real-world code, I find I need 5 representations of the same thing to do the most basic of operations.
Namely:
0
1
2
3
4
So that's 5 representations of the same thing. Sure, I've had some fun in SQL and been able to get very specific. But pretend I didn't, and just wanted some obvious defaults, that a deterministic algorithm could trivially infer (type map).
In Python I wrote a compile to translate SQLalchemy into plain old Python classes (and back again). In Rust I suppose macros is the hacky reflection alternative.
Anyway would be great to get your perspective here, as I'm sure I'm not the first to ask about this, and there must be solutions?
Beta Was this translation helpful? Give feedback.
All reactions