Add MySQL initialization and user model size constraint

This commit is contained in:
koh 2025-04-12 15:54:30 +07:00
parent d83f6c1145
commit 82e7fd1d01
3 changed files with 19 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import (
"time"
"github.com/dungnt11/todoms_golang/global"
"github.com/dungnt11/todoms_golang/internal/models"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
@ -45,3 +46,18 @@ func setPool(db *gorm.DB) {
sqlDb.SetMaxOpenConns(m.MaxOpenConns)
sqlDb.SetConnMaxLifetime(time.Duration(m.ConnMaxLifetime) * time.Second)
}
func defaultInitMysql() {
isInitUser := global.Mdb.Migrator().HasTable(&models.User{})
isInitProduct := global.Mdb.Migrator().HasTable(&models.Product{})
if !isInitUser {
global.Mdb.AutoMigrate(&models.User{})
global.Logger.Info("Initialized User table")
}
if !isInitProduct {
global.Mdb.AutoMigrate(&models.Product{})
global.Logger.Info("Initialized Product table")
}
}

View File

@ -38,6 +38,8 @@ func Run() {
return
}
defaultInitMysql()
// Khởi tạo router
r := provideRouter()

View File

@ -9,7 +9,7 @@ import (
// User đại diện cho người dùng trong hệ thống
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
Username string `json:"username" gorm:"uniqueIndex;not null"`
Username string `json:"username" gorm:"uniqueIndex;not null;size:255"`
Password string `json:"-" gorm:"not null"` // Không trả về password trong JSON
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`