Browse Source

完成数据库层的基础操作

yjp 11 months ago
parent
commit
b2692c1299

+ 12 - 2
application/application.go

@@ -2,6 +2,7 @@ package application
 
 import (
 	"git.sxidc.com/go-framework/baize/api"
+	"git.sxidc.com/go-framework/baize/infrastructure"
 	"git.sxidc.com/go-framework/baize/infrastructure/logger"
 )
 
@@ -9,14 +10,18 @@ type App struct {
 	// api实例
 	apiInstance *api.Api
 
+	// 基础设施实例
+	infrastructureInstance *infrastructure.Infrastructure
+
 	// 日志
 	loggerInstance *logger.Logger
 }
 
 // New 创建Application
-func New(api *api.Api) *App {
+func New(api *api.Api, i *infrastructure.Infrastructure) *App {
 	return &App{
-		apiInstance: api,
+		apiInstance:            api,
+		infrastructureInstance: i,
 	}
 }
 
@@ -45,6 +50,11 @@ func (app *App) Api() *api.Api {
 	return app.apiInstance
 }
 
+// Infrastructure 获取Infrastructure实例
+func (app *App) Infrastructure() *infrastructure.Infrastructure {
+	return app.infrastructureInstance
+}
+
 // Logger 获取logger实例
 func (app *App) Logger() *logger.Logger {
 	return app.loggerInstance

+ 11 - 1
application/config.go

@@ -2,6 +2,7 @@ package application
 
 import (
 	"encoding/json"
+	"git.sxidc.com/go-framework/baize/infrastructure/database/operations"
 	"git.sxidc.com/go-tools/utils/fileutils"
 	"git.sxidc.com/service-supports/fserr"
 	"gopkg.in/yaml.v3"
@@ -9,7 +10,8 @@ import (
 )
 
 type Config struct {
-	ApiConfig `json:"api" yaml:"api"`
+	ApiConfig            `json:"api" yaml:"api"`
+	InfrastructureConfig `json:"infrastructure" yaml:"infrastructure"`
 }
 
 type ApiConfig struct {
@@ -17,6 +19,14 @@ type ApiConfig struct {
 	Port      string `json:"port" yaml:"port"`
 }
 
+type InfrastructureConfig struct {
+	Database InfrastructureDatabase
+}
+
+type InfrastructureDatabase struct {
+	Operations *operations.Config
+}
+
 func LoadFromJsonFile(jsonFilePath string) (Config, error) {
 	if !fileutils.PathExists(jsonFilePath) {
 		return Config{}, fserr.New("配置文件不存在")

+ 24 - 6
baize.go

@@ -3,13 +3,31 @@ package baize
 import (
 	"git.sxidc.com/go-framework/baize/api"
 	"git.sxidc.com/go-framework/baize/application"
+	"git.sxidc.com/go-framework/baize/infrastructure"
+	"git.sxidc.com/go-framework/baize/infrastructure/database/operations"
 )
 
 func NewApplication(conf application.Config) *application.App {
-	return application.New(
-		api.New(
-			api.WithUrlPrefix(conf.ApiConfig.UrlPrefix),
-			api.WithPort(conf.ApiConfig.Port),
-		),
-	)
+	apiConfig := conf.ApiConfig
+	apiInstance := api.New(api.WithUrlPrefix(apiConfig.UrlPrefix), api.WithPort(apiConfig.Port))
+
+	var infrastructureInstance *infrastructure.Infrastructure
+	if conf.InfrastructureConfig.Database.Operations != nil {
+		operationsConfig := conf.InfrastructureConfig.Database.Operations
+		infrastructureInstance = infrastructure.NewInfrastructure(infrastructure.Config{
+			DatabaseConfig: infrastructure.DatabaseConfig{
+				Operations: &operations.Config{
+					UserName:           operationsConfig.UserName,
+					Password:           operationsConfig.Password,
+					Address:            operationsConfig.Address,
+					Port:               operationsConfig.Port,
+					Database:           operationsConfig.Database,
+					MaxConnections:     operationsConfig.MaxConnections,
+					MaxIdleConnections: operationsConfig.MaxIdleConnections,
+				},
+			},
+		})
+	}
+
+	return application.New(apiInstance, infrastructureInstance)
 }

+ 6 - 2
binding/binding.go

@@ -3,6 +3,7 @@ package binding
 import (
 	"git.sxidc.com/go-framework/baize/api"
 	"git.sxidc.com/go-framework/baize/domain"
+	"git.sxidc.com/go-framework/baize/infrastructure"
 	"git.sxidc.com/go-tools/utils/reflectutils"
 	"git.sxidc.com/go-tools/utils/strutils"
 	"git.sxidc.com/service-supports/fserr"
@@ -41,7 +42,7 @@ func StaticFile(router api.Router, item *StaticFileBindItem) {
 
 type DTOBindFunc func(c *api.Context, dto DTO) error
 type FormDomainObjectsFunc func(c *api.Context, dto DTO) ([]domain.Object, error)
-type ServiceFunc[O any] func(c *api.Context, dto DTO, objects []domain.Object) (O, error)
+type ServiceFunc[O any] func(c *api.Context, dto DTO, objects []domain.Object, i *infrastructure.Infrastructure) (O, error)
 type ResponseFunc[O any] func(c *api.Context, statusCode int, data O, err error)
 
 // SimpleBindItem  路由条目
@@ -70,6 +71,9 @@ type SimpleBindItem[O any] struct {
 	// 与FormObjectsFunc字段二选一使用,如果都指定,会按照FormObjectsFunc字段处理
 	Objects []domain.Object
 
+	// 基础设施实例,可以通过Application取到
+	Infrastructure *infrastructure.Infrastructure
+
 	// 应用服务泛型函数
 	ServiceFunc ServiceFunc[O]
 
@@ -194,7 +198,7 @@ func (item *BindItem[O]) bind(router api.Router, middlewares ...api.Handler) {
 			// 执行业务函数
 			statusCode := http.StatusOK
 
-			outputModel, err := item.ServiceFunc(c, dto, domainObjects)
+			outputModel, err := item.ServiceFunc(c, dto, domainObjects, item.Infrastructure)
 			if err != nil {
 				statusCode = fserr.ParseCode(err).HttpCode
 			}

+ 6 - 5
examples/binding/main.go

@@ -7,6 +7,7 @@ import (
 	"git.sxidc.com/go-framework/baize/application"
 	"git.sxidc.com/go-framework/baize/binding"
 	"git.sxidc.com/go-framework/baize/domain"
+	"git.sxidc.com/go-framework/baize/infrastructure"
 	"git.sxidc.com/go-tools/utils/strutils"
 	DEATH "github.com/vrecan/death"
 	"syscall"
@@ -69,7 +70,7 @@ func main() {
 		ResponseFunc: binding.SendIDResponse[string],
 		DTO:          &CreateClassJsonBody{},
 		Objects:      []domain.Object{&Class{}},
-		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (string, error) {
+		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (string, error) {
 			e := domain.ToConcreteObject[*Class](objects[0])
 			e.ID = strutils.SimpleUUID()
 			classMap[e.ID] = e
@@ -83,7 +84,7 @@ func main() {
 		ResponseFunc: binding.SendMsgResponse,
 		DTO:          &DeleteClassPathParams{},
 		Objects:      []domain.Object{&Class{}},
-		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (any, error) {
+		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (any, error) {
 			id := domain.Field[string](objects[0], "ID")
 			delete(classMap, id)
 			fmt.Println("Deleted Entity:" + id)
@@ -97,7 +98,7 @@ func main() {
 		ResponseFunc: binding.SendMsgResponse,
 		DTO:          &UpdateClassJsonBody{},
 		Objects:      []domain.Object{&Class{}},
-		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (any, error) {
+		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (any, error) {
 			id := domain.Field[string](objects[0], "ID")
 			newName := domain.Field[string](objects[0], "Name")
 
@@ -123,7 +124,7 @@ func main() {
 		ResponseFunc: binding.SendInfosResponse[ClassInfo],
 		DTO:          &QueryClassesQueryParams{},
 		Objects:      []domain.Object{&Class{}},
-		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (binding.InfosData[ClassInfo], error) {
+		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (binding.InfosData[ClassInfo], error) {
 			name := domain.Field[string](objects[0], "Name")
 
 			classInfos := make([]ClassInfo, 0)
@@ -189,7 +190,7 @@ func main() {
 		ResponseFunc: binding.SendInfoResponse[*ClassInfo],
 		DTO:          &GetClassQueryParams{},
 		Objects:      []domain.Object{&Class{}},
-		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (*ClassInfo, error) {
+		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (*ClassInfo, error) {
 			id := domain.Field[string](objects[0], "ID")
 
 			classInfo := new(ClassInfo)

+ 0 - 11
infrastructure/database/operations/config.go

@@ -1,11 +0,0 @@
-package operations
-
-type OperationsConfig struct {
-	UserName           string
-	Password           string
-	Address            string
-	Port               string
-	Database           string
-	MaxConnections     int
-	MaxIdleConnections int
-}

+ 2 - 6
infrastructure/database/operations/db.go

@@ -8,11 +8,7 @@ import (
 	"gorm.io/gorm/logger"
 )
 
-const (
-	databaseTypePostgres = "postgres"
-)
-
-func newGormDB(dbConfig *OperationsConfig) (*gorm.DB, error) {
+func newGormDB(dbConfig *Config) (*gorm.DB, error) {
 	if dbConfig == nil {
 		return nil, errors.New("没有传递数据库配置")
 	}
@@ -25,7 +21,7 @@ func newGormDB(dbConfig *OperationsConfig) (*gorm.DB, error) {
 	return gormDB, nil
 }
 
-func newPostgresGormDB(dbConfig *OperationsConfig) (*gorm.DB, error) {
+func newPostgresGormDB(dbConfig *Config) (*gorm.DB, error) {
 	dsn := "host=%s port=%s user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai"
 	connStr := fmt.Sprintf(dsn, dbConfig.Address, dbConfig.Port, dbConfig.UserName, dbConfig.Password, dbConfig.Database)
 	return gorm.Open(postgres.Open(connStr), &gorm.Config{

+ 14 - 4
infrastructure/database/operations/operations.go

@@ -10,12 +10,22 @@ import (
 	"time"
 )
 
+type Config struct {
+	UserName           string
+	Password           string
+	Address            string
+	Port               string
+	Database           string
+	MaxConnections     int
+	MaxIdleConnections int
+}
+
 type Operations struct {
 	db           *gorm.DB
 	stopPingChan chan any
 }
 
-func NewOperations(dbConfig *OperationsConfig) (*Operations, error) {
+func NewOperations(dbConfig *Config) (*Operations, error) {
 	gormDB, err := newGormDB(dbConfig)
 	if err != nil {
 		return nil, err
@@ -118,8 +128,8 @@ func (op *Operations) AutoMigrate(tables ...Table) error {
 	return nil
 }
 
-func (op *Operations) ExecuteRawSql(sql string, executeParams map[string]any) ([]sql.Result, error) {
-	parsedSql, err := template.ParseTemplateStringToString(sql, executeParams)
+func (op *Operations) ExecuteRawSql(sqlStr string, executeParams map[string]any) ([]sql.Result, error) {
+	parsedSql, err := template.ParseTemplateStringToString(sqlStr, executeParams)
 	if err != nil {
 		return nil, err
 	}
@@ -149,6 +159,6 @@ func (op *Operations) ExecuteRawSql(sql string, executeParams map[string]any) ([
 	return results, nil
 }
 
-func (op *Operations) ExecuteSql(sql string, _ map[string]any) ([]sql.Result, error) {
+func (op *Operations) ExecuteSql(_ string, _ map[string]any) ([]sql.Result, error) {
 	return make([]sql.Result, 0), nil
 }

+ 2 - 10
infrastructure/database/operations/transaction.go

@@ -5,17 +5,9 @@ type TransactionOperations struct {
 }
 
 func (op *TransactionOperations) RollbackTransaction() {
-	defer func() {
-		op.processDB = op.initDB
-	}()
-
-	op.processDB.Rollback()
+	op.db.Rollback()
 }
 
 func (op *TransactionOperations) CommitTransaction() {
-	defer func() {
-		op.processDB = op.initDB
-	}()
-
-	op.processDB.Commit()
+	op.db.Commit()
 }

+ 38 - 0
infrastructure/infrastructure.go

@@ -5,11 +5,49 @@ import (
 	"git.sxidc.com/go-framework/baize/infrastructure/database/operations"
 )
 
+type Config struct {
+	DatabaseConfig
+}
+
+type DatabaseConfig struct {
+	Operations *operations.Config
+}
+
 type Infrastructure struct {
 	dbOperations *operations.Operations
 	dataService  *data_service.DataService
 }
 
+func NewInfrastructure(config Config) *Infrastructure {
+	i := new(Infrastructure)
+
+	if config.DatabaseConfig.Operations != nil {
+		op, err := operations.NewOperations(config.DatabaseConfig.Operations)
+		if err != nil {
+			panic("创建数据库操作失败" + err.Error())
+		}
+
+		i.dbOperations = op
+	}
+
+	return i
+}
+
+func DestroyInfrastructure(i *Infrastructure) error {
+	if i == nil {
+		return nil
+	}
+
+	if i.dbOperations != nil {
+		err := operations.DestroyOperation(i.dbOperations)
+		if err != nil {
+			panic("销毁数据库操作失败" + err.Error())
+		}
+	}
+
+	return nil
+}
+
 func (i Infrastructure) GetDBOperations() *operations.Operations {
 	return i.dbOperations
 }