github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/extend/orm/orm.go (about) 1 package orm 2 3 import ( 4 "fmt" 5 "github.com/isyscore/isc-gobase/config" 6 "github.com/isyscore/isc-gobase/isc" 7 "github.com/isyscore/isc-gobase/listener" 8 "github.com/isyscore/isc-gobase/logger" 9 "github.com/sirupsen/logrus" 10 "strings" 11 ) 12 13 func getDbDsnWithName(datasourceName string) (string, error) { 14 datasourceConfig := config.DatasourceConfig{} 15 targetDatasourceName := "base.datasource" 16 if datasourceName != "" { 17 targetDatasourceName = "base.datasource." + datasourceName 18 } 19 err := config.GetValueObject(targetDatasourceName, &datasourceConfig) 20 if err != nil { 21 logger.Warn("读取读取配置【datasource】异常") 22 return "", err 23 } 24 25 return getDbDsn(datasourceConfig.DriverName, datasourceConfig), nil 26 } 27 28 func getDbDsn(dbType string, datasourceConfig config.DatasourceConfig) string { 29 sqlConfigMap := map[string]string{} 30 err := config.GetValueObject("base.datasource.url-config", &sqlConfigMap) 31 if err != nil { 32 logger.Warn("读取配置【base.datasource.url-config】异常", err) 33 } 34 35 switch dbType { 36 case "mysql": 37 // 格式:user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" 38 dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", datasourceConfig.Username, datasourceConfig.Password, datasourceConfig.Host, datasourceConfig.Port, datasourceConfig.DbName) 39 if len(sqlConfigMap) != 0 { 40 var kvList []string 41 for key, value := range sqlConfigMap { 42 kvList = append(kvList, fmt.Sprintf("%s=%s", key, specialCharChange(value))) 43 } 44 dsn += fmt.Sprintf("?%s", strings.Join(kvList, "&")) 45 } 46 return dsn 47 case "postgresql": 48 // 格式:host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai 49 dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d", datasourceConfig.Host, datasourceConfig.Username, datasourceConfig.Password, datasourceConfig.DbName, datasourceConfig.Port) 50 if len(sqlConfigMap) != 0 { 51 var kvList []string 52 for key, value := range sqlConfigMap { 53 kvList = append(kvList, fmt.Sprintf("%s=%s", key, value)) 54 } 55 dsn += fmt.Sprintf(" %s", strings.Join(kvList, " ")) 56 } 57 return dsn 58 case "sqlite": 59 // 格式: gorm.db 60 return datasourceConfig.SqlitePath 61 case "sqlserver": 62 // 格式:sqlserver://user:password@localhost:9930?database=gorm 63 dsn := fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s", datasourceConfig.Username, datasourceConfig.Password, datasourceConfig.Host, datasourceConfig.Port, datasourceConfig.DbName) 64 return dsn 65 } 66 return "" 67 } 68 69 func ConfigChangeListenerOfOrm(event listener.BaseEvent) { 70 ev := event.(listener.ConfigChangeEvent) 71 if ev.Key == "base.orm.show-sql" { 72 if isc.ToBool(ev.Value) { 73 logger.Group("orm").SetLevel(logrus.DebugLevel) 74 } else { 75 logger.Group("orm").SetLevel(logrus.InfoLevel) 76 } 77 } 78 }