sqlx
sqlx copied to clipboard
Update reflectx to allow for optional nested structs
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:
select house.id, owner.*,
from house
left join owner on owner.id = house.owner
Before
type House struct {
ID int
Owner *Person // if left join gives nulls, Owner is set
}
type Owner struct {
ID sql.NullInt64 // make nullable columns even tho if table doesn't have those columns nullable
}
After
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
Hello, @ardan-bkennedy, and I recently stepped in to help maintain this project. We are sorting the opened issues and pull requests and would like to know if you still NEED this merged. I think that #900 might solve some issues with this PR and so I'm tempted to close this in favor of that PR. Thank you for your contribution.