guregu / null

reasonable handling of nullable values
BSD 2-Clause "Simplified" License
1.84k stars 238 forks source link

MySQL time scan #37

Closed ecarter202 closed 6 years ago

ecarter202 commented 6 years ago

type JsonUser struct { ID null.Intjson:"id" db:"id" Email null.Stringjson:"email" db:"email" Password null.Stringjson:"-" db:"password" FirstName null.Stringjson:"first_name" db:"first_name" LastName null.Stringjson:"last_name" db:"last_name" CreatedAt null.Timejson:"created_at" db:"created_at" UpdatedAt null.Timejson:"updated_at" db:"updated_at"` }

func UserByID(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) if userID, err := strconv.Atoi(vars["id"]); err != nil { fmt.Fprint(w, response.Success("No record found.", http.StatusNotFound, nil).JSON()) return } else { jsonUser := &JsonUser{} err = DB.QueryRow("SELECT id, email, first_name, last_name, created_at, updated_at FROM users WHERE id = ? LIMIT 1;", userID).Scan(&jsonUser.ID, &jsonUser.Email, &jsonUser.FirstName, &jsonUser.LastName, &jsonUser.CreatedAt, &jsonUser.UpdatedAt) if err != nil { fmt.Fprint(w, response.Error(err.Error(), http.StatusInternalServerError).JSON()) return } fmt.Fprint(w, response.Success("Request successful!", http.StatusOK, jsonUser).JSON()) }

return

}`

CreatedAt is not null, but UpdatedAt is for the particular record I'm retrieving.

The error that is being thrown is: "sql: Scan error on column index 4: null: cannot scan type []uint8 into null.Time: [50 48 49 56 45 48 56 45 50 50 32 48 48 58 53 54 58 50 50]"

It doesn't seem that this package's Time is not handling []uint8 but I'm not sure how to get this working. Thanks!

ecarter202 commented 6 years ago

// Scan implements the Scanner interface. func (t *Time) Scan(value interface{}) error { var err error switch x := value.(type) { case time.Time: t.Time = x case nil: t.Valid = false return nil case []uint8: t.Time, err = time.Parse("2006-01-02 15:04:05", string(value.([]uint8))) if err != nil { err = fmt.Errorf("null: cannot scan type %T into null.Time: %v", value, value) } default: err = fmt.Errorf("null: cannot scan type %T into null.Time: %v", value, value) } t.Valid = err == nil return err }

This seemed to work for my specific case. Would this be a viable solution?

Thanks again.

guregu commented 6 years ago

Do you have parseTime set to true? https://github.com/go-sql-driver/mysql#parsetime

ecarter202 commented 6 years ago

I did not. That seemed to do the trick! Thanks.