Pg: Question: updating only non null values.

Created on 27 Sep 2017  路  3Comments  路  Source: go-pg/pg

I'm sorry if this is being explained somewhere. I checked the docs, wiki, the issues and the source code and couldn't find the solution.

Suppose, we have a book struct:

type Book struct {
  ID string
  Name string
  Description string
}

Now, I want to update the name and the description only if they are not null values.

If I do the following:

  db.Model(&Book{ID: "1", Name: "new name"}).Update() // sets Description to ""
  db.Model(&Book{ID: "1", Description: "new name"}).Update() // sets Name to ""

Is there a way of not updating the values which are null? Something similar to https://stackoverflow.com/questions/13305878/dont-update-column-if-update-value-is-null

The way I do it right now:

var columns []string
if book.Name != "" {
  columns = append(columns, "name")
}
if book.Description != "" {
  columns = append(columns, "description")
}
_, err := rel.db.Model(&book).Column(columns...).Update()

Is it the way to go in this situation?

Thanks in advance!

Most helpful comment

Please upgrade go-pg and try:

db.Model(&book).UpdateNotNull()

All 3 comments

Please upgrade go-pg and try:

db.Model(&book).UpdateNotNull()

Even this is closed, I have this issue too and came with simple solution. When you want to update an object you always update it current state against new state. This means you first step is retrieve original object and then update it as object and only then update it via pg session.
my case was:

# http handler for trip details update action
originalTrip, err := app.tripModel.GetTrip(id)

if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}

err = json.NewDecoder(r.Body).Decode(&originalTrip)

if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}

err = app.tripModel.UpdateTrip(&originalTrip)

Here's a quick update on the following:

Please upgrade go-pg and try:

db.Model(&book).UpdateNotNull()

UpdateNotNull is now UpdateNotZero from the Changelog:

UpdateNotNull is renamed to UpdateNotZero. As previously it omits zero Go values, but it does not take in account if field is nullable or not.

Here's an example:

_, err := db.Model(&book).WherePK().UpdateNotZero()
Was this page helpful?
0 / 5 - 0 ratings