gorp PreUpdate method update involuntary columns

181 Views Asked by At

see below.

type User struct {
    Id         int64  `db:"id" json:"id"`
    Name  string `db:"name" json:"name"`
    DateCreate int64  `db:"date_create"`
    DateUpdate int64  `db:"date_update"`
}

func (u *User) PreInsert(s gorp.SqlExecutor) error {
    u.DateCreate = time.Now().UnixNano()
    u.DateUpdate = u.DateCreate
    return nil
}

func (u *User) PreUpdate(s gorp.SqlExecutor) error {
    u.DateUpdate = time.Now().UnixNano()
    return nil
}

I executed INSERT.

user := model.User{
    Name:      "John",
}

err := dbMap.Insert(&user)

Result of INSERT. no problem

1,John,1444918337049394761,1444918337049394761

continue, I executed UPDATE.

user := model.User{
    Id:        1,
    Name:      "John",
}

_, err := dbMap.Update(&user)

Result of UPDATE

1,John,0,1444918337049394900

Column DateCreate updated.

Of course, my expectation values are

1,John,1444918337049394761,1444918337049394900
1

There are 1 best solutions below

1
HectorJ On

That's because when initializing your user struct, you did not explicitely set user.DateCreate, which effectively sets it to 0.

gorp cannot guess which fields you mean to update or not, so it updates them all.

To do what you want, you have to choose between trade-offs

  1. Get the struct from the ORM, with the field already set to the good value. That's one additional select query that will be executed.
  2. Execute a custom query, losing the convenience of the ORM
  3. I'm guessing you could have another struct type without this field. That seems messy, I do not recommend that.