登录
首页 >  Golang >  Go问答

Gorm 返回不同的时间戳格式,然后用于创建记录

来源:stackoverflow

时间:2024-03-17 11:39:27 138浏览 收藏

使用 Gorm 框架创建和获取记录时,时间戳格式不一致。创建记录时,使用 nowfunc 指定的格式返回时间戳。然而,检索同一记录时,时间戳格式却发生了变化。这种差异是由 Go 和 Postgres SQL 的时间精度差异造成的,前者为纳秒,后者为微秒。使用 sqltime 库可以解决此问题,该库调整了 Go 中的时间精度,使其与 Postgres SQL 兼容。

问题内容

我正在使用 gorm 从使用 gin 的 go 应用程序中创建记录。我已在 gorm.config 文件中指定了 nowfunc,如 gorm 文档中所指定。

这是一个使用 gin 和 gorm 的完整封装示例应用程序,它演示了我试图解决的问题:

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")
}

当我运行此应用程序并发送以下请求来创建记录时,如下所示:

curl --location --request post 'localhost:8080/post/' \
--header 'content-type: application/json' \
--data-raw '{
    "code": "aaa"
}'

我收到以下回复:

{
    "id": 1,
    "createdat": "2021-04-16t15:48:59.749294z",
    "updatedat": "2021-04-16t15:48:59.749294z",
    "deletedat": null,
    "code": "aaa",
    "price": 0
}

请注意,时间戳的格式为 nowfunc 指定的格式。但是,如果我按如下方式检索此记录:

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

我收到以下记录:

{
    "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
}

所以问题是为什么我没有收到具有与 post 响应中相同时间戳格式的 get 请求的记录?

更新: 使用 sql-lite 数据库时不会发生这种情况。


正确答案


经过大量研究,问题是Go的默认时间精度是纳秒,但Postgres SQL是微秒精度。以下库解决了我的问题:

https://github.com/SamuelTissot/sqltime

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Gorm 返回不同的时间戳格式,然后用于创建记录》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>