Update reflectx to allow for optional nested structs#847
Update reflectx to allow for optional nested structs#847ntbosscher wants to merge 2 commits intojmoiron:masterfrom
Conversation
Nested structs are now only instantiated when one of the database columns in that nested struct is not nil. This allows objects scanned in left/outer joins to keep their natural types (instead of setting everything to NullableX).
Example:
```sql
select house.id, owner.*,
from house
left join owner on owner.id = house.owner
```
``` golang
type House struct {
ID int
Owner *Person // if left join gives nulls, Owner will be nil
}
type Owner struct {
ID int // no need to set this to sql.NullInt
}
```
|
A possible solution for #162 |
|
One trade off is that for nested structs, we end up doing most of the work in sql.convertAssignRows twice This also further complicates reflectx. However, I think the functionality is more natural. With our modeling we typically do things like the following. type User struct {
ID int
Name string
}
type Plan struct {
ID int
CreditsPerMonth int64
}
type UserPlan struct {
User User
Plan *Plan
}This maps directly to database tables. Doing things like setting Plan's properties to nullable fields feels weird and out of place. |
|
Happy to make any adjustments if you see a better way to do this. |
|
This makes a lot of sense, I ran into issues with the existing behaviour recently. I don't like that I have to make a bunch of fields Nullable on existing structs just so they can be properly scanned when performing a left join. Any updates from the team if this can get merged? @jmoiron? Thanks! |
|
@jmoiron, Could you check and merge it? Thanks. 🙏 |
|
Another vote for this |
geeeeeeeeek
left a comment
There was a problem hiding this comment.
Tested locally and it works with multi outer joins. Vote to merge this PR.
geeeeeeeeek
left a comment
There was a problem hiding this comment.
Wait it doesn't work with pointer types: don't know how to parse type int64 -> **uint64
type AccountRow struct {
Account `db:"account"`
OptionOrder `db:"option_order"`
}
type OptionOrder struct {
ID uuid.UUID `db:"id"`
AccountID *uint64 `db:"account_id"`
}
|
Hello, @ardan-bkennedy, and I recently stepped in to help maintain this project. |
Update with latest changes from origin/master
Nested structs are now only instantiated when one of the database columns in that nested struct is not nil. This allows objects scanned in left/outer joins to keep their natural types (instead of setting everything to NullableX).
Example:
Before
After