A.A.
A.A.

Reputation: 442

Gorm Returns Different Timestamp Format Then Used on Record Creation

I'm using GORM to create records from within a Go application that uses gin. I've specified in the gorm.Config file a NowFunc as specified in GORM documentation here.

Here is a full, encapsulated sample application using gin and gorm that demonstrates the problem I am trying to solve:

package main

import (
    "github.com/gin-gonic/gin"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "net/http"
    "strconv"
    "time"
)
var db *gorm.DB

type Product struct {
    gorm.Model
    Code  string
    Price uint
}

func handlePost(c *gin.Context, db *gorm.DB) {
    var product Product
    if err := c.ShouldBind(&product); err != nil {
        c.JSON(http.StatusBadRequest, err)
        return
    }
    db.Debug().Create(&product).Debug()
    c.JSON(http.StatusCreated, product)
}

func handleGet(c *gin.Context, db *gorm.DB) {
    id, err := strconv.ParseInt(c.Param("id"), 10, 64)
    if err != nil {
        _ = c.Error(err)
    }
    var product Product
    product.ID = uint(id)
    db.Debug().Find(&product)
    c.JSON(http.StatusOK, product)
}

func timeformat() time.Time {
    return time.Now().UTC().Truncate(time.Microsecond)
}

func main() {
    dsn := "host=localhost port=5432 dbname=gorm sslmode=disable connect_timeout=5 application_name='gorm test'"
    config := &gorm.Config{NowFunc: timeformat}
    // PROBLEM DOESN'T OCCUR WHEN USING SQL-LITE DB
    //  database, err := gorm.Open(sqlite.Open("test.db"), config)
    // PROBLEM OCCURs WHEN USING POSTGRES DB
    database, err := gorm.Open(postgres.Open(dsn), config)
    if err != nil {
        panic("failed to connect database")
    }
    // Migrate the schema
    database.AutoMigrate(&Product{})
    db = database

    router := gin.Default()

    router.GET("/get/:id", func(c *gin.Context) { handleGet(c, db) })
    router.POST("/post", func(c *gin.Context) { handlePost(c, db) })
    router.Run(":8080")
}

When I run this application and send the following request to create a record as follows:

curl --location --request POST 'localhost:8080/post/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "Code": "AAA"
}'

I receive the following response:

{
    "ID": 1,
    "CreatedAt": "2021-04-16T15:48:59.749294Z",
    "UpdatedAt": "2021-04-16T15:48:59.749294Z",
    "DeletedAt": null,
    "Code": "AAA",
    "Price": 0
}

Note the timestamp is formatted as the NowFunc specified. However, if I retrieve this record as follows:

curl --location --request GET 'localhost:8080/get/1'

I receive the following record:

{
    "ID": 1,
    "CreatedAt": "2021-04-16T11:48:59.749294-04:00",
    "UpdatedAt": "2021-04-16T11:48:59.749294-04:00",
    "DeletedAt": null,
    "Code": "AAA",
    "Price": 0
}

So the question is why do I not receive the records with the GET request with the same timestamp format as in the POST response?

UPDATE: This does not happen when using anSQL-LITE database.

Upvotes: 1

Views: 1867

Answers (1)

A.A.
A.A.

Reputation: 442

After much research, the problem is that Go's default time precision is nanoseconds, but Postgres SQL is microsecond precision. The following library resolved my problem:

https://github.com/SamuelTissot/sqltime

Upvotes: 4

Related Questions