diff --git a/app/provider/database_connect/contract.go b/app/provider/database_connect/contract.go new file mode 100644 index 0000000..457a516 --- /dev/null +++ b/app/provider/database_connect/contract.go @@ -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 +} diff --git a/app/provider/database_connect/provider.go b/app/provider/database_connect/provider.go new file mode 100644 index 0000000..8fa13ad --- /dev/null +++ b/app/provider/database_connect/provider.go @@ -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 +} diff --git a/app/provider/database_connect/service.go b/app/provider/database_connect/service.go new file mode 100644 index 0000000..133d212 --- /dev/null +++ b/app/provider/database_connect/service.go @@ -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 +}