data_service.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package data_service
  2. import (
  3. "git.sxidc.com/go-framework/baize/framework/core/infrastructure/database/sql"
  4. "git.sxidc.com/go-tools/utils/template"
  5. "git.sxidc.com/service-supports/ds-sdk/sdk"
  6. "github.com/pkg/errors"
  7. "time"
  8. )
  9. type Config struct {
  10. Token string `json:"token" yaml:"token"`
  11. Address string `json:"address" yaml:"address"`
  12. HttpPort string `json:"http_port" yaml:"http_port"`
  13. GrpcPort string `json:"grpc_port" yaml:"grpc_port"`
  14. Namespace string `json:"namespace" yaml:"namespace"`
  15. DataSource string `json:"data_source" yaml:"data_source"`
  16. HttpTimeoutSec int `json:"http_timeout_sec" yaml:"http_timeout_sec"`
  17. }
  18. type Executor struct{}
  19. func NewExecutor(conf *Config) (*Executor, error) {
  20. if conf.HttpTimeoutSec == 0 {
  21. conf.HttpTimeoutSec = 30
  22. }
  23. err := sdk.InitInstance(conf.Token, conf.Address, conf.HttpPort, conf.GrpcPort, conf.Namespace, conf.DataSource,
  24. sdk.WithTimeout(time.Duration(conf.HttpTimeoutSec)*time.Second))
  25. if err != nil {
  26. return nil, errors.New(err.Error())
  27. }
  28. return &Executor{}, nil
  29. }
  30. func DestroyExecutor(executor *Executor) error {
  31. if executor == nil {
  32. return nil
  33. }
  34. err := sdk.DestroyInstance()
  35. if err != nil {
  36. return errors.New(err.Error())
  37. }
  38. return nil
  39. }
  40. func (executor *Executor) ExecuteRawSql(sqlStr string, args ...any) ([]sql.Result, error) {
  41. return executor.ExecuteRawSqlTemplate(sqlStr, nil, args...)
  42. }
  43. func (executor *Executor) ExecuteRawSqlTemplate(sqlStr string, executeParams map[string]any, args ...any) ([]sql.Result, error) {
  44. parsedSql, err := template.ParseTemplateStringToString(sqlStr, executeParams)
  45. if err != nil {
  46. return nil, errors.New(err.Error())
  47. }
  48. tableRows, err := sdk.GetInstance().ExecuteRawSql(parsedSql, args...)
  49. if err != nil {
  50. return nil, errors.New(err.Error())
  51. }
  52. results := make([]sql.Result, len(tableRows))
  53. for i, row := range tableRows {
  54. results[i] = row
  55. }
  56. return results, nil
  57. }