1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package initialize
- import (
- "gorm.io/driver/mysql"
- "gorm.io/gorm/logger"
- "gorm.io/gorm/schema"
- "log"
- "os"
- "time"
- "lcfns/global"
- "gorm.io/gorm"
- )
- func Gorm() *gorm.DB {
- m := global.Config.Mysql
- 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
- }
- }
- 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
- }
|