package main
import (
"encoding/json"
"fmt"
"github.com/jinzhu/gorm"
"github.com/pborman/uuid"
"os"
"reflect"
"strings"
_ "github.com/mattn/go-sqlite3"
)
type User struct {
Id string `gorm:"primary_key;uuid"`
Age int64
Name string `sql:"size:255"`
UserPhone string `gorm:"column(user_phone); size(32)"`
UserQQ string `gorm:"column(user_qq); size(32);"`
UserCity string `gorm:"column(user_city); size(32)"`
}
// create UUID
func beforeCreate(scope *gorm.Scope) {
reflectValue := reflect.Indirect(reflect.ValueOf(scope.Value))
if strings.Contains(string(reflectValue.Type().Field(0).Tag), "uuid") {
uuid.SetClockSequence(-1)
scope.SetColumn("id", uuid.NewUUID().String())
}
}
func main() {
err := os.Remove("D:\\huawei-oj\\test\\work\\gwx.db")
if err != nil {
fmt.Println(err)
}
db, err := gorm.Open("sqlite3", "D:\\huawei-oj\\test\\work\\gwx.db")
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.Callback().Create().Before("gorm:create").Register("my_plugin:before_create", beforeCreate)
db.AutoMigrate(&User{})
user := User{
Name: "jinzhu",
UserPhone: "11111",
UserQQ: "11111",
UserCity: "11111",
}
db.Create(&user)
var u User
db.First(&u)
js, err := json.MarshalIndent(u.Name, "", " ")
if err != nil {
fmt.Println(err)
}
fmt.Println(string(js))
}