go-sqlmock icon indicating copy to clipboard operation
go-sqlmock copied to clipboard

GORM model with time.Time type error

Open reyhansofian opened this issue 5 years ago • 2 comments
trafficstars

Hi, I have an issue with mocking for GORM that uses timestamp on the model. For example, I have this model

type SomeModel struct {
	CreatedAt time.Time      `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at;default:CURRENT_TIMESTAMP" json:"updated_at"`
	DeletedAt *time.Time     `gorm:"column:deleted_at" json:"deleted_at"`
}

I know that we can use sqlmock.NewWithDSN for this case and this is how I initiate the database mock connection

	db, mock, err := sqlmock.NewWithDSN("mysql://user:password@(localhost)/dbname?charset=utf8&parseTime=true&loc=Local")
	if err != nil {
		Expect(err).ShouldNot(HaveOccurred())
	}

	grm, err = gorm.Open("sqlmock", db)
	if err != nil {
		Expect(err).ShouldNot(HaveOccurred())
	}

then this error happens

...
sql: Scan error on column index 5, name \"created_at\": unsupported Scan, storing driver.Value type string into type *time.Time
...

after looking at GORM issues, this should be solved if we're using the parseTime=True on the dsn. Ref: this issue and this issue.

Apparently, GORM didn't parse the dsn correctly. I'm not sure how to fix this issue. I would gladly make a fix for this issue if you can lead me on how to fix this issue properly. Thanks!

reyhansofian avatar May 24 '20 15:05 reyhansofian

Sqlmock is a mock database, it does not know that you use gorm or any other thing underneath. If you use non standard arguments to sql value converter. You need to register it for mock database via options

l3pp4rd avatar May 26 '20 17:05 l3pp4rd

Sqlmock is a mock database, it does not know that you use gorm or any other thing underneath. If you use non standard arguments to sql value converter. You need to register it for mock database via options

Is there a sqlmock options configuration with gorm example showing how to achieve the time conversion?

hielfx avatar Oct 19 '20 19:10 hielfx