sqlite icon indicating copy to clipboard operation
sqlite copied to clipboard

time zone will be lost when using `db.Exec()` to create columns containing time

Open cyberxnomad opened this issue 1 year ago • 0 comments

When using db.Create() to create a column containing the time, it will contain the time zone

type Example struct {
	Id        int `gorm:"primaryKey;autoIncrement;"`
	CreatedAt time.Time
	UpdatedAt time.Time
	Name      string
}

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

	db.AutoMigrate(new(Example))

	example := Example{Name: "Tome"}

	db.Debug().Create(&example)
}
[37.259ms] [rows:1] INSERT INTO `examples` (`created_at`,`updated_at`,`name`) VALUES ("2024-10-23 10:53:07.42","2024-10-23 10:53:07.42","Tome") RETURNING `id`

image

using db.Exec()

type Example struct {
	Id        int `gorm:"primaryKey;autoIncrement;"`
	CreatedAt time.Time
	UpdatedAt time.Time
	Name      string
}

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

	db.AutoMigrate(new(Example))

	now := time.Now()
	example := Example{Name: "Tome", Id: 1, CreatedAt: now, UpdatedAt: now}

	sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
		return tx.Create(&example)
	})

	fmt.Println("sql:", sql)

	db.Exec(sql)
}
sql: INSERT INTO `examples` (`created_at`,`updated_at`,`name`,`id`) VALUES ("2024-10-23 10:58:19.003","2024-10-23 10:58:19.003","Tome",1) RETURNING `id`

image

cyberxnomad avatar Oct 23 '24 03:10 cyberxnomad