Make a note of the part that I investigated a little around, such as model definition with struct
and migration with ʻAutoMigrate`.
While leaving the automatic generation of UUID to the library, I wanted to be able to specify a fixed UUID when inputting test and seed data, so I corresponded as follows.
First, define the model in the struct
package model
import (
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
)
type User struct {
ID string `validate:"is_valid_uuid" gorm:"primaryKey;size:255;default:uuid_generate_v4()" json:"id"`
...
}
//If the ID does not come, do not validate it, and if it does, check if it is a UUID
validate := validator.New()
validate.RegisterValidation("is_valid_uuid", isValidUUID)
func isValidUUID(fl v.FieldLevel) bool {
id := fl.Field().String()
if len(id) == 0 {
return true
}
_, err := uuid.Parse(id)
return err == nil
}
Install the extension ʻuuid-ossp in postgres before ʻAutoMigrate (& User {})
to use ʻuuid_generate_v4 ()` above
db, err = gorm.Open("postgres", fmt.Sprintf(
"host=%s port=%s user=%s password=%s dbname=%s", host, port, user, password, dbname,
))
if err != nil {
panic(err)
}
db.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`)
result := db.AutoMigrate(&model.User{})
...
Specify type with struct tag
type User struct {
Role string `validate:"is_valid_role" gorm:"type:role_enum;default:'user'" json:"role"`
...
}
ʻAdd type definition to postgres before AutoMigrate`
db.Exec(`
DO
$$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'role_enum') THEN
create type role_enum AS ENUM ('admin', 'editor', 'user');
END IF;
END
$$;
`)
result := db.AutoMigrate(&model.User{})
...
It was a memo about the migration of GORM. If there are others, I will add them.
Recommended Posts