添加一些新指令

This commit is contained in:
dandan 2024-10-27 17:55:28 +08:00
parent 6613151288
commit 0d054c46fe
3 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package database_connect
import "gorm.io/gorm"
const DatabaseConnectKey = "hade:database_connect"
type Service interface {
LocalDatabaseConnect() *gorm.DB
AliDataBaseConnect() *gorm.DB
}

View File

@ -0,0 +1,31 @@
package database_connect
import (
"github.com/Superdanda/hade/framework"
)
type DatabaseConnectProvider struct {
framework.ServiceProvider
c framework.Container
}
func (sp *DatabaseConnectProvider) Name() string {
return DatabaseConnectKey
}
func (sp *DatabaseConnectProvider) Register(c framework.Container) framework.NewInstance {
return NewDatabaseConnectService
}
func (sp *DatabaseConnectProvider) IsDefer() bool {
return false
}
func (sp *DatabaseConnectProvider) Params(c framework.Container) []interface{} {
return []interface{}{c}
}
func (sp *DatabaseConnectProvider) Boot(c framework.Container) error {
return nil
}

View File

@ -0,0 +1,36 @@
package database_connect
import (
"fmt"
"github.com/Superdanda/hade/framework"
"github.com/Superdanda/hade/framework/contract"
"github.com/Superdanda/hade/framework/provider/orm"
"gorm.io/gorm"
)
type DatabaseConnectService struct {
container framework.Container
}
func (d DatabaseConnectService) LocalDatabaseConnect() *gorm.DB {
return getDatabaseConnectByYaml("database.local", d)
}
func (d DatabaseConnectService) AliDataBaseConnect() *gorm.DB {
return getDatabaseConnectByYaml("database.ali", d)
}
func NewDatabaseConnectService(params ...interface{}) (interface{}, error) {
container := params[0].(framework.Container)
return &DatabaseConnectService{container: container}, nil
}
func getDatabaseConnectByYaml(yamlPath string, d DatabaseConnectService) *gorm.DB {
ormService := d.container.MustMake(contract.ORMKey).(contract.ORMService)
db, err := ormService.GetDB(orm.WithConfigPath(yamlPath))
if err != nil {
fmt.Println(yamlPath + "数据库连接失败,请检查配置")
return nil
}
return db
}