0

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?

3
  • Make sure to add a closing " to your struct tags for SomeMapType. Commented Aug 6, 2020 at 19:01
  • Yep, sorry lost the quote while anonymizing the code Commented Aug 6, 2020 at 20:31
  • @User-Upvotedon'tsayThanks that link isn't that relevant because it's not dealing with a map[string]SomeType, I'm able to implement Scanner/Valuer for other types fine. Commented Aug 6, 2020 at 22:17

1 Answer 1

1

My problem was not including the SQL type tag annotation.

Making the changes below fixed my issue:

type StoreStruct struct {
    gorm.Model
    Id               string `gorm:"type:uuid;primary_key"`
    AccountID        string
    SomeMapType      SomeMapType `gorm:"column:cache" sql:"type:jsonb"`
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.