123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- package initialize
- import (
- "fmt"
- "github.com/flipped-aurora/gin-vue-admin/server/model/system"
- "go.uber.org/zap"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- "gorm.io/gorm/schema"
- "lc-fangdaosha/global"
- "lc-fangdaosha/model/app"
- "log"
- "os"
- "time"
- )
- func Gorm() *gorm.DB {
- m := global.Config.Mysql
- fmt.Println("mysql配置:", m)
- if m.Dbname == "" {
- return nil
- }
- mysqlConfig := mysql.Config{
- DSN: m.Dsn(), // DSN data source name
- DefaultStringSize: 191, // string 类型字段的默认长度
- SkipInitializeWithVersion: false, // 根据版本自动配置
- }
- if db, err := gorm.Open(mysql.New(mysqlConfig), config(m.Prefix, m.Singular)); err != nil {
- log.Fatalln("29:", err)
- return nil
- } else {
- db.InstanceSet("gorm:table_options", "ENGINE="+m.Engine)
- sqlDB, _ := db.DB()
- sqlDB.SetMaxIdleConns(m.MaxIdleConns)
- sqlDB.SetMaxOpenConns(m.MaxOpenConns)
- return db
- }
- }
- func RegisterTables() {
- db := global.Db
- err := db.AutoMigrate(
- system.SysApi{},
- system.SysUser{},
- system.SysBaseMenu{},
- system.JwtBlacklist{},
- system.SysAuthority{},
- //system.SysDictionary{},
- system.SysOperationRecord{},
- //system.SysAutoCodeHistory{},
- system.SysDictionaryDetail{},
- //system.SysBaseMenuParameter{},
- system.SysBaseMenuBtn{},
- system.SysAuthorityBtn{},
- //system.SysAutoCode{},
- //system.SysChatGptOption{},
- //example.ExaFile{},
- //example.ExaCustomer{},
- //example.ExaFileChunk{},
- //example.ExaFileUploadAndDownload{},
- app.Camera{}, app.Picture{}, app.PictureData{}, app.Gateway{}, app.Event{},
- )
- if err != nil {
- global.GVA_LOG.Error("register table failed", zap.Error(err))
- os.Exit(0)
- }
- global.GVA_LOG.Info("register table success")
- }
- type DBBASE interface {
- GetLogMode() string
- }
- func config(prefix string, singular bool) *gorm.Config {
- config := &gorm.Config{
- NamingStrategy: schema.NamingStrategy{
- TablePrefix: prefix,
- SingularTable: singular,
- },
- DisableForeignKeyConstraintWhenMigrating: true,
- }
- _default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
- SlowThreshold: 200 * time.Millisecond,
- LogLevel: logger.Warn,
- Colorful: true,
- })
- var logMode DBBASE
- logMode = &global.Config.Mysql
- switch logMode.GetLogMode() {
- case "silent", "Silent":
- config.Logger = _default.LogMode(logger.Silent)
- case "error", "Error":
- config.Logger = _default.LogMode(logger.Error)
- case "warn", "Warn":
- config.Logger = _default.LogMode(logger.Warn)
- case "info", "Info":
- config.Logger = _default.LogMode(logger.Info)
- default:
- config.Logger = _default.LogMode(logger.Info)
- }
- return config
- }
|