Search code examples
goupdatesgo-gorm

gorm does not update timestamp field


This is my model:

type User struct {
    ID          uuid.UUID   `gorm:"primarykey;column:id;type:uuid;default:gen_random_uuid()"`
    FullName    string      `gorm:"column:full_name"`
    PhoneNumber string      `gorm:"column:phone_number"`
    JoinDate    pq.NullTime `gorm:"column:join_date"`
}

And I have created my database using this SQL:

CREATE TABLE IF NOT EXISTS "fellowship"."users" (
    "id"           uuid      NOT NULL DEFAULT uuid_generate_v4(),
    "full_name"    text      NOT NULL,
    "phone_number" text      NOT NULL,
    "join_date"    timestamp,
    "created_at"   timestamp NOT NULL DEFAULT NOW(),
    "updated_at"   timestamp NULL     DEFAULT NOW(),

    PRIMARY KEY ("id")
);

If I update the join_date field, the value remains null in the database; even though no errors return:

func UpdateUser(user *models.User) error {
    fmt.Println("repo: user id: ", user.ID)
    fmt.Println("repo: user join date: ", user.JoinDate)

    result := tx.Save(user)

    fmt.Println("result.RowsAffected:", result.RowsAffected)
    fmt.Println("result.Error:", result.Error)

    if result.Error != nil {
        return ParseError(result.Error)
    }

    if result.RowsAffected == 0 {
        return ErrRecordNotFound
    }

    return nil
}

The logs are:

repo: user id:  2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102
repo: user join date:  {2023-09-25 00:00:00 +0000 UTC false}
result.RowsAffected: 1
result.Error: <nil>

And the database join_date column remains null:

postgres=# select id, join_date, created_at from fellowship.users where id = '2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102';
                  id                  | join_date |         created_at         
--------------------------------------+-----------+----------------------------
 2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102 |           | 2023-08-08 15:12:37.001919
(1 row)

This issue only affects the date fields and other columns update successfully.

Edit 1:

I have also checked type sql.NullTime. Result was the same.


Solution

  • The log gives you a big hint. A pq.NullTime is

    type NullTime struct {
        Time  time.Time
        Valid bool // Valid is true if Time is not NULL
    }
    

    and in your log it says

    user join date:  {2023-09-25 00:00:00 +0000 UTC false}
    

    which means you have (essentially):

    JoinTime := pq.NullTime{
        Time: "2023-09-25 00:00:00 +0000 UTC",
        Valid: false,
    }
    

    where Valid: false means "this field is null"