Using gorm
and go-sqlite3
. Opening my db using gorm.Open("sqlite3", "/dev.db?charset=utf8&parseTime=true")
.
Trying to execute
db.Raw("SELECT * from users;").Scan(&users)
// models.User has a deleted_at column that is of the type *time.Time
// I am getting Scan error on column index 1: unsupported driver -> Scan pair: []uint8 -> *time.Time
How do I parse sql into *time.Time?
User struct
type User struct {
ID uint64 `gorm:"primary_key"`
Name sql.NullString
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
lib/pq implements a NullTime type for that. It defines a scanner interface for a time.Time type that may be null. You can use it in exchange to *time.Time
.
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}