Shyamin Ayesh
Shyamin Ayesh

Reputation: 102

Use a unix timestamp for UpdatedAt field in gorm

I'm writing an application that communicates with sqlite3 database using GORM ORM. Now the thing is I need to make UpdatedAt column a unix timestamp because another legacy application is using the same database and they should be compatible.

So I tried to update the UpdatedAt field with unix timestamp on BeforeUpdate hook using the following code block.

func (c *CartItems) BeforeUpdate() (err error) {
    fmt.Println("----------------------------------------")
    fmt.Println("BeforeUpdate")
    fmt.Println( c )
    c.UpdatedAt = time.Now().Unix()
    fmt.Println("----------------------------------------")
    return
}

but when I run the code query remains same and didn't add the timestamp into the database.

gorm log

----------------------------------------
BeforeUpdate
&{55 21 4 7 1585607114 1585607114 {0 [] [] [] {0 0 } 0 0} {0  0 0 0}}
----------------------------------------

[2020-03-31 04:30:02]  [0.46ms]  UPDATE "cart_items" SET "quantity" = 7, "updated_at" = '2020-03-31 04:30:02'  WHERE "cart_items"."id" = 55  
[1 rows affected or returned ] 
[GIN] 2020/03/31 - 04:30:02 | 200 |   97.963597ms |       127.0.0.1 | POST     "/cache/cart/21/item"

Upvotes: 0

Views: 2757

Answers (1)

ifnotak
ifnotak

Reputation: 4662

Use the following if you want to have UpdatedAt() and CreatedAt() as unix timestamps.

type CartItems struct {
    CreatedAt int64
    UpdatedAt int64
}

func (m *CartItems) BeforeUpdate(scope *gorm.Scope) error {
    scope.SetColumn("UpdatedAt", time.Now().Unix())
    return nil
}

func (m *CartItems) BeforeCreate(scope *gorm.Scope) error {
    if m.UpdatedAt == 0 {
        scope.SetColumn("UpdatedAt", time.Now().Unix())
    }

    scope.SetColumn("CreatedAt", time.Now().Unix())
    return nil
}

Unfortunately, gorm is not well documented so you would have to read the code to understand how this works, namely this line calls the above BeforeUpdate() function.

As you can see in the callMethod() function, it checks the signature of the function in the switch to decide on how to call the function.

Upvotes: 4

Related Questions