I'm trying to save a nested struct into postgres using gorm, but I'm hitting some issues with my map[string]*InnerStruct type.
I want to store my map type as JSONB in postgres, so I've defined a Scanner/Valuer like so as suggested in similar questions:
type SomeMapType map[string]*InnerStruct
type StoreStruct struct {
gorm.Model
Id string `gorm:"type:uuid;primary_key"`
AccountID string
SomeMapType SomeMapType `gorm:"column:cache,type:jsonb"`
}
var _ driver.Valuer = SomeMapType{}
var _ sql.Scanner = &SomeMapType{}
func (smt SomeMapType) Value() (driver.Value, error) {
return json.Marshal(smt)
}
func (smt *SomeMapType) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(b, &smt)
}
but when I try to create a table like so:
err := db.
CreateTable(StoreStruct{}).
Table(tableName).Error)
A panic occurs:
panic: invalid sql type SomeMapType (map) for postgres [recovered]
It looks like this happens even before my Valuer/Scanner implementations are called.
Is it just not possible to store a map field on a struct you want to save to a DB with gorm?
I believe I've seen examples that seem to be working with map[string]interface{} so I'm not sure why my scenario is different?
"to your struct tags for SomeMapType.map[string]SomeType, I'm able to implement Scanner/Valuer for other types fine.