Skip to content

Instantly share code, notes, and snippets.

@turgayozgur
Created March 20, 2021 10:25
Show Gist options
  • Save turgayozgur/e8e7f3568d5ded9fbad0aeadf2ac4ab5 to your computer and use it in GitHub Desktop.
Save turgayozgur/e8e7f3568d5ded9fbad0aeadf2ac4ab5 to your computer and use it in GitHub Desktop.
golang, scan nullable sql columns
func Scan(rows *sql.Rows, dest ...interface{}) error {
proxy := make([]interface{}, len(dest))
for k, v := range dest {
switch v.(type) {
case *string:
proxy[k] = &sql.NullString{String: "", Valid: true}
case *bool:
proxy[k] = &sql.NullBool{Bool: false, Valid: true}
case *int:
proxy[k] = &sql.NullInt32{Int32: 0, Valid: true}
case *int32:
proxy[k] = &sql.NullInt32{Int32: 0, Valid: true}
case *int64:
proxy[k] = &sql.NullInt64{Int64: 0, Valid: true}
case *float32:
return errors.New("unable to map float32. use float64 instead")
case *float64:
proxy[k] = &sql.NullFloat64{Float64: 0, Valid: true}
case *time.Time:
proxy[k] = &sql.NullTime{Time: time.Time{}, Valid: true}
default:
return errors.New("unable to map. unknown field type")
}
}
if err := rows.Scan(proxy...); err != nil {
return err
}
for k, v := range dest {
switch d := v.(type) {
case *string:
*d = (proxy[k].(*sql.NullString)).String
case *bool:
*d = (proxy[k].(*sql.NullBool)).Bool
case *int:
*d = int((proxy[k].(*sql.NullInt32)).Int32)
case *int32:
*d = (proxy[k].(*sql.NullInt32)).Int32
case *int64:
*d = (proxy[k].(*sql.NullInt64)).Int64
case *float64:
*d = (proxy[k].(*sql.NullFloat64)).Float64
case *time.Time:
*d = (proxy[k].(*sql.NullTime)).Time
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment