package models import ( "fmt" "math/rand" "time" "github.com/oklog/ulid/v2" "gorm.io/gorm" ) type EntityBase struct { ID ULIDWrapper `gorm:"type:bytea;primaryKey"` CreatedAt time.Time `gorm:"index"` UpdatedAt time.Time `gorm:"index"` DeletedAt gorm.DeletedAt `gorm:"index"` } // BeforeCreate is called by GORM before creating a record func (eb *EntityBase) BeforeCreate(tx *gorm.DB) error { if eb.ID.Compare(ULIDWrapper{}) == 0 { // If ID is empty // Generate a new ULID entropy := ulid.Monotonic(rand.New(rand.NewSource(time.Now().UnixNano())), 0) newID := ulid.MustNew(ulid.Timestamp(time.Now()), entropy) eb.ID = ULIDWrapper{ULID: newID} fmt.Println("Generated ID:", eb.ID) } return nil }