feat: rebuild pet app and backend around core care flows
This commit is contained in:
@@ -4,7 +4,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
"gorm.io/gorm/schema"
|
||||
@@ -13,40 +13,31 @@ import (
|
||||
"github.com/sundynix/pets-be/internal/model"
|
||||
)
|
||||
|
||||
// New 建立 GORM 连接,所有表名统一加 sundynix_ 前缀
|
||||
func New(cfg *config.Config) (*gorm.DB, error) {
|
||||
func Open(cfg config.PostgresConfig, release bool) (*gorm.DB, error) {
|
||||
logLevel := logger.Info
|
||||
if cfg.Server.Mode == "release" {
|
||||
if release {
|
||||
logLevel = logger.Warn
|
||||
}
|
||||
|
||||
db, err := gorm.Open(mysql.Open(cfg.MySQL.DSN()), &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
TablePrefix: "sundynix_",
|
||||
SingularTable: false,
|
||||
},
|
||||
// 关联在 Go 层管,不靠库级外键。迁移期建外键时 MySQL 会为外键列自动
|
||||
// 补一个索引,和字段上的 `index` tag 撞成同名索引,父子表同迁时第二次
|
||||
// 建索引报 1061 duplicate。关掉外键约束创建,索引就只由 index tag 建一次
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
Logger: logger.Default.LogMode(logLevel),
|
||||
db, err := gorm.Open(postgres.Open(cfg.DSN()), &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{TablePrefix: "sundynix_", SingularTable: true},
|
||||
Logger: logger.Default.LogMode(logLevel),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gorm open: %w", err)
|
||||
return nil, fmt.Errorf("open postgres: %w", err)
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(50)
|
||||
sqlDB.SetMaxOpenConns(25)
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// Migrate 自动建表
|
||||
func Migrate(db *gorm.DB) error {
|
||||
return db.AutoMigrate(model.AllModels()...)
|
||||
if err := db.AutoMigrate(model.All()...); err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_sundynix_walk_one_active_per_user ON sundynix_walk (user_id) WHERE status IN ('active', 'paused')").Error
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user