gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Object created and fetched do not match

Open ozkansen opened this issue 1 year ago • 1 comments

GORM Playground Link

https://github.com/go-gorm/playground/pull/533

Description

I created user object and then called it from database but fields like CreatedAt, UpdatedAt and Delete do not match local region.

My console output:

[0.225ms] [rows:1] SELECT * FROM `users` WHERE `users`.`id` = 1 AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1
    main_test.go:23: Failed, object not match:
        create: {Model:{ID:1 CreatedAt:2022-10-22 01:27:30.456916 +0300 +03 UpdatedAt:2022-10-22 01:27:30.456916 +0300 +03 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Name:jinzhu Age:0 Birthday:<nil> Account:{Model:{ID:0 CreatedAt:0001-01-01 00:00:00 +0000 UTC UpdatedAt:0001-01-01 00:00:00 +0000 UTC DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} UserID:{Int64:0 Valid:false} Number:} Pets:[] Toys:[] CompanyID:<nil> Company:{ID:0 Name:} ManagerID:<nil> Manager:<nil> Team:[] Languages:[] Friends:[] Active:false}
        get: {Model:{ID:1 CreatedAt:2022-10-22 01:27:30.456916 +0300 +0300 UpdatedAt:2022-10-22 01:27:30.456916 +0300 +0300 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Name:jinzhu Age:0 Birthday:<nil> Account:{Model:{ID:0 CreatedAt:0001-01-01 00:00:00 +0000 UTC UpdatedAt:0001-01-01 00:00:00 +0000 UTC DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} UserID:{Int64:0 Valid:false} Number:} Pets:[] Toys:[] CompanyID:<nil> Company:{ID:0 Name:} ManagerID:<nil> Manager:<nil> Team:[] Languages:[] Friends:[] Active:false}
--- FAIL: TestGORM (0.00s)
FAIL
FAIL	gorm.io/playground	0.435s
FAIL

! attention timezone

ozkansen avatar Oct 21 '22 22:10 ozkansen

I can temporarily bypass the local zone problem when we set the time zone to UTC:

func main() {
	db, err := gorm.Open(sqlite.Open(":memory:"), getGormConfig())
	if err != nil {
		panic(err)
	}

	...
}

func getGormConfig() *gorm.Config {
	return &gorm.Config{NowFunc: useDefaultUTCTimeZone()}
}

func useDefaultUTCTimeZone() func() time.Time {
	var (
		loc *time.Location
		err error
	)

	if loc, err = time.LoadLocation("UTC"); err != nil {
		panic(err)
	}

	time.Local = loc

	return time.Now().Local
}

ozkansen avatar Oct 30 '22 20:10 ozkansen

Yes, you need to specify NowFunc. The database allows different time rules for each table. We cannot help users decide what type of time to use.

a631807682 avatar Nov 27 '22 17:11 a631807682