Structure to set the default character type, but the actual field type is an integer. Query and creation errors are reported.

如果结构体的某个字段中 tag 设置了 默认值 字符类型,而字段是 整型。则在查询和创建,均会报错解析错误。

I think the query should not report errors, and the data in the database should prevail. And it would be better to indicate in the creation exactly which field is set wrong. This is not reported in the sql statement.

我觉得查询中应该不进行报错,以数据库中数据为准。而创建中最好能够指明具体是哪个字段设置错误。因为 sql 语句中,这一现象没有进行报错。

Description

package main

import (
    "testing"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

type TestModle struct {
    ID     uint64 `gorm:"coulmn:id"`
    UserID uint64 `gorm:"coulmn:user_id;default:'1'"`
}

func (t *TestModle) TableName() string {
    return "test_user_tab"
}

func TestQueryModel(t *testing.T) {
    db, err := gorm.Open(mysql.Open("root:my-secret-pw@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    data := &TestModle{}
    err = db.Table("test_user_tab").Where("id = ?", 1).First(data).Error

    if err != nil {
        t.Errorf("err :%+v", err)
    }
}

print err:


2022/08/14 13:57:00 /com.docker.devenvironments.code/gormv2-test/query_model_test.go:17
[error] failed to parse '1' as default value for uint, got error: strconv.ParseUint: parsing "'1'": invalid syntax
--- FAIL: TestQueryModel (0.01s)
    /com.docker.devenvironments.code/gormv2-test/query_model_test.go:20: err :failed to parse '1' as default value for uint, got error: strconv.ParseUint: parsing "'1'": invalid syntax
FAIL
FAIL    gormv2-test 0.030s
FAIL
package main

import (
    "testing"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func TestCreateModel(t *testing.T) {
    db, err := gorm.Open(mysql.Open("root:my-secret-pw@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    err = db.Create(&TestModle{ID: 1, UserID: 1}).Error

    if err != nil {
        t.Errorf("err :%+v", err)
    }
}

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: jinzhu

Need to change

UserID uint64 `gorm:"coulmn:user_id;default:'1'"`

to

UserID uint64 `gorm:"coulmn:user_id;default:1"`

We would like to be strict to parsing the struct to make sure user won't be surprised in some cases and cache the parsing result for performance.