sdk.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package sdk
  2. import (
  3. "git.sxidc.com/go-tools/utils/strutils"
  4. "git.sxidc.com/service-supports/ds-sdk/client"
  5. "git.sxidc.com/service-supports/ds-sdk/grpc_client"
  6. "git.sxidc.com/service-supports/ds-sdk/grpc_client/v1/request"
  7. "github.com/pkg/errors"
  8. "io"
  9. )
  10. type SDK struct {
  11. options *Options
  12. client *client.Client
  13. grpcClient *grpc_client.Client
  14. }
  15. func (s *SDK) ExecuteRawSql(sql string, values ...any) ([]map[string]any, error) {
  16. if strutils.IsStringEmpty(sql) {
  17. return make([]map[string]any, 0), nil
  18. }
  19. options := s.options
  20. tableRows, err := s.client.ExecuteRawSql(options.token, options.baseUrl,
  21. options.namespace, options.dataSource, sql, values...)
  22. if err != nil {
  23. return nil, err
  24. }
  25. results := make([]map[string]any, len(tableRows))
  26. for i, row := range tableRows {
  27. results[i] = row
  28. }
  29. return results, nil
  30. }
  31. func (s *SDK) Transaction(txFunc TxFunc) error {
  32. stream, err := s.grpcClient.Transaction()
  33. if err != nil {
  34. return err
  35. }
  36. defer func() {
  37. innerErr := stream.CloseSend()
  38. if innerErr != nil {
  39. panic(innerErr)
  40. }
  41. }()
  42. err = stream.Send(&request.TransactionOperation{
  43. Request: &request.TransactionOperation_TransactionBeginRequest{
  44. TransactionBeginRequest: &request.TransactionBeginRequest{
  45. Token: s.options.token,
  46. Namespace: s.options.namespace,
  47. DataSource: s.options.dataSource,
  48. },
  49. }})
  50. if err != nil {
  51. return err
  52. }
  53. resp, err := stream.Recv()
  54. if err != nil {
  55. return err
  56. }
  57. if !resp.Success {
  58. return errors.New(resp.Msg)
  59. }
  60. err = txFunc(&Transaction{
  61. stream: stream,
  62. })
  63. if err != nil {
  64. return err
  65. }
  66. err = stream.Send(&request.TransactionOperation{
  67. Request: &request.TransactionOperation_TransactionEndRequest{
  68. TransactionEndRequest: &request.TransactionEndRequest{},
  69. }})
  70. if err != nil {
  71. return err
  72. }
  73. _, err = stream.Recv()
  74. if err != nil && err != io.EOF {
  75. return err
  76. }
  77. return nil
  78. }