/internal/app/model/gormx/gorm.go
https://github.com/LyricTian/gin-admin · Go · 79 lines · 63 code · 12 blank · 4 comment · 9 complexity · 84b378be95783bc6813c5330021159b7 MD5 · raw file
- package gormx
- import (
- "strings"
- "time"
- "github.com/LyricTian/gin-admin/v7/internal/app/config"
- "github.com/LyricTian/gin-admin/v7/internal/app/model/gormx/entity"
- "github.com/LyricTian/gin-admin/v7/pkg/logger"
- "github.com/jinzhu/gorm"
- // gorm存储注入
- _ "github.com/jinzhu/gorm/dialects/mysql"
- _ "github.com/jinzhu/gorm/dialects/postgres"
- _ "github.com/jinzhu/gorm/dialects/sqlite"
- )
- // Config 配置参数
- type Config struct {
- Debug bool
- DBType string
- DSN string
- MaxLifetime int
- MaxOpenConns int
- MaxIdleConns int
- TablePrefix string
- }
- // NewDB 创建DB实例
- func NewDB(c *Config) (*gorm.DB, func(), error) {
- gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
- return c.TablePrefix + defaultTableName
- }
- db, err := gorm.Open(c.DBType, c.DSN)
- if err != nil {
- return nil, nil, err
- }
- if c.Debug {
- db = db.Debug()
- }
- cleanFunc := func() {
- err := db.Close()
- if err != nil {
- logger.Errorf("Gorm db close error: %s", err.Error())
- }
- }
- err = db.DB().Ping()
- if err != nil {
- return nil, cleanFunc, err
- }
- db.SingularTable(true)
- db.DB().SetMaxIdleConns(c.MaxIdleConns)
- db.DB().SetMaxOpenConns(c.MaxOpenConns)
- db.DB().SetConnMaxLifetime(time.Duration(c.MaxLifetime) * time.Second)
- return db, cleanFunc, nil
- }
- // AutoMigrate 自动映射数据表
- func AutoMigrate(db *gorm.DB) error {
- if dbType := config.C.Gorm.DBType; strings.ToLower(dbType) == "mysql" {
- db = db.Set("gorm:table_options", "ENGINE=InnoDB")
- }
- return db.AutoMigrate(
- new(entity.Demo),
- new(entity.MenuAction),
- new(entity.MenuActionResource),
- new(entity.Menu),
- new(entity.RoleMenu),
- new(entity.Role),
- new(entity.UserRole),
- new(entity.User),
- ).Error
- }