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
fix(scan): update setupValuerAndSetter to use default values when pointer t… #6938
base: master
Are you sure you want to change the base?
Conversation
c1afb54
to
88330cb
Compare
@jinzhu any concerns with this PR? |
@a631807682 am I missing something for this to be reviewed? |
fieldIsEmbeddedPointerTypeStruct := len(field.BindNames) > 1 && len(field.StructField.Index) > 0 && field.StructField.Index[0] < 0 | ||
fieldValue := reflect.ValueOf(values[idx]).Elem() | ||
if !fieldIsEmbeddedPointerTypeStruct && fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() { | ||
db.AddError(field.Set(db.Statement.Context, reflectValue, field.DefaultValueInterface)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why use field.DefaultValueInterface? I don't think it is an expected behavior for most users.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
field.DefaultValueInterface
ensures that I return the struct back with default/zero values for each field. i.e. nil for pointers and 0 for ints. It helps to reset the struct.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jinzhu any concerns with that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jinzhu
I think it is expected usage based on your docs: https://gorm.io/docs/sql_builder.html#Scan-sql-Rows-into-struct
var user User
for rows.Next() {
// ScanRows scan a row into user
db.ScanRows(rows, &user)
// do something
}
What did this pull request do?
Addresses #6819
Adding the else condition to use the base type when data is nil ensures that the struct field is always set by the scanIntoStructMethod
User Case Description
It fixes the example from the docs where you initialize the var once: