mgutz / dat

Go Postgres Data Access Toolkit

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Serializing custom types

pyrossh opened this issue · comments

I have a struct like this

type JSON map[string]interface{}
type Data struct {
    ID   string `db:"id" json:"id,omitempty"`
    meta JSON   `db:"meta" json:"meta,omitempty"`
}

But When I try to insert it it gives this error sql: converting Exec argument #7's type: unsupported type common.JSONO, a map
Is there some way to overcome this because I want this meta to be serialized to a string and then stored?

You'll need to implement Scan and Value on your JSON type to provide to and from transformers.

If you can adapt to using []byte instead, this implementation by @ansel1 is handy: https://github.com/jinzhu/gorm/issues/516#issuecomment-109055198

@Gurpartap Thanks. @atrniv solved this problem for me the same way. I forgot this issue since we moved away from dat.

type JSONO map[string]interface{}
type JSONA []interface{}

func (jo JSONO) String() string {
    data, err := json.Marshal(jo)
    if err != nil {
        panic(err.Error())
    }
    return string(data)
}

func (jo JSONO) Value() (driver.Value, error) {
    return json.Marshal(jo)
}

func (jo JSONO) Scan(data []byte) error {
    return json.Unmarshal(data, jo)
}

Using this approach I'm getting (JSONMap is same as JSONO):

<*errors.errorString | 0xc420165810>: {
          s: "sql: converting Exec argument #2's type: unsupported type map[interface {}]interface {}, a map",
      }

My model is:

type Game struct {
	ID        string       `db:"id"`
	Name      string       `db:"name"`
	Metadata  JSONMap      `db:"metadata"`
	CreatedAt dat.NullTime `db:"created_at"`
	UpdatedAt dat.NullTime `db:"updated_at"`
}

The dat code is:

                        //Metadata defaults to {}
			game := models.Game{
				Name: uuid.NewV4().String(),
			}
			err := db.
				InsertInto("games").
				Record(&game).
				Returning("id", "created_at", "updated_at").
				QueryStruct(&game)

Any ideas?

What is metadata postgres type, jsonb? I would recommend dat.JSON for jsonb.

I'm not familiar with JSONO type? Please provide gist of DDL for game and type definition of JSONMap.

Sorry man. Was actually a problem with fixtures. I just found out, like a minute ago, lol. Thanks for the fast response. Awesome lib.