Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[]string to jsonb with Gorm and postgres

I have a Go struct which contains a slice of strings which I'd like to save as a jsonB object in Postgres with GORM.

I've come accross a solution which requires to use the GORM specific type (postgres.Jsonb) which I'd like to avoid.

When I try to run the AutoMigrate with a slice in my model, it panics and won't start although when I wrap this slice in a struct (which I'm okay doing) it will run without error but won't create the column in postgres.

type User struct {
        gorm.Model
        Data []string `sql:"type:"jsonb"; json:"data"`
} //Panics

type User struct {
        gorm.Model
        Data struct {
            NestedData []string
        } `sql:"type:"jsonb"; json:"data"`
} //Doesn't crash but doesn't create my column

Has anyone been able to manipulate jsonb with GORM without using the postgres.Jsonb type in models ?

like image 211
Le G Avatar asked Sep 03 '25 10:09

Le G


1 Answers

The simplest way to use JSONB in Gorm is to use pgtype.JSONB.

Gorm uses pgx as it driver, and pgx has package called pgtype, which has type named pgtype.JSONB.

If you have already install pgx as Gorm instructed, you don't need install any other package.

This method should be the best practice since it using underlying driver and no custom code is needed. It can also be used for any JSONB type beyond []string.

type User struct {
    gorm.Model
    Data pgtype.JSONB `gorm:"type:jsonb;default:'[]';not null"`
}

Get value from DB

u := User{}
db.find(&u)

var data []string

err := u.Data.AssignTo(&data)
if err != nil {
    t.Fatal(err)
}

Set value to DB

u := User{}

err := u.Data.Set([]string{"abc","def"})
if err != nil {
    return
}

db.Updates(&u)
like image 199
Yari Avatar answered Sep 05 '25 03:09

Yari