Skip to content

Instantly share code, notes, and snippets.

@alingse
Created April 11, 2023 03:27
Show Gist options
  • Save alingse/a3187af45d516d591c7a077ed8c739f9 to your computer and use it in GitHub Desktop.
Save alingse/a3187af45d516d591c7a077ed8c739f9 to your computer and use it in GitHub Desktop.
Show Gorm Pluck query on JSONType and JSONSlice
package main
import (
"context"
"database/sql"
"fmt"
"gorm.io/datatypes"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type (
User struct {
Name string `json:"name"`
Age int `json:"age"`
}
TestTable struct {
ID uint64
Info datatypes.JSONType[*User]
Parent datatypes.JSONSlice[*User]
}
)
func (*TestTable) TableName() string {
return "user"
}
func main() {
var ctx = context.Background()
var db = prepareDB()
var err error
db = db.WithContext(ctx)
db.AutoMigrate(&TestTable{})
db.Create(&TestTable{
Info: datatypes.NewJSONType(&User{Name: "name", Age: 18}),
Parent: datatypes.JSONSlice[*User]{&User{Name: "A", Age: 38}, &User{Name: "B", Age: 39}},
})
// ok
row := &TestTable{}
db.Limit(1).Order("id DESC").Find(row)
// find all row &{name 18}
fmt.Println("find all row ", row.Info.Data())
// ok
var field []datatypes.JSONType[*User]
err = db.Model(&TestTable{}).Limit(1).Order("id DESC").Pluck("info", &field).Error
// find field &{name 18} <nil>
fmt.Println("find field ", field[0].Data(), err)
// ok
var fullRow TestTable
err = db.Model(&TestTable{}).Limit(1).Order("id DESC").Pluck("info", &fullRow.Info).Error
// find field in row <nil> &{name 18}
fmt.Println("find field in row ", err, fullRow.Info.Data())
// ok
var parents []datatypes.JSONSlice[*User]
err = db.Model(&TestTable{}).Limit(1).Order("id DESC").Pluck("parent", &parents).Error
fmt.Println("find parents in slice ", err, parents[0], *parents[0][0], *parents[0][1])
}
func prepareDB() *gorm.DB {
var err error
pool, err := sql.Open("mysql", "root:@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=true&loc=Local")
if err != nil {
panic(err)
}
db, err := gorm.Open(mysql.New(mysql.Config{Conn: pool}), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment