transaction.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package sdk
  2. import (
  3. "encoding/json"
  4. "git.sxidc.com/go-tools/utils/reflectutils"
  5. "git.sxidc.com/service-supports/ds-sdk/grpc_client/v1"
  6. "git.sxidc.com/service-supports/ds-sdk/grpc_client/v1/request"
  7. "github.com/pkg/errors"
  8. "reflect"
  9. )
  10. type TxFunc func(tx *Transaction) error
  11. type Transaction struct {
  12. stream v1.SqlService_TransactionClient
  13. }
  14. func (tx *Transaction) ExecuteRawSql(sql string, values ...any) ([]map[string]any, error) {
  15. var retErr error
  16. defer func() {
  17. if retErr != nil {
  18. innerErr := tx.stream.CloseSend()
  19. if innerErr != nil {
  20. panic(innerErr)
  21. }
  22. }
  23. }()
  24. rawSqlValues := make([]map[string]any, 0)
  25. for _, value := range values {
  26. typedValueReflectValue := reflect.ValueOf(value)
  27. if !typedValueReflectValue.IsValid() {
  28. return nil, errors.New("无效值")
  29. }
  30. typedValueReflectValueElem := reflectutils.PointerValueElem(typedValueReflectValue)
  31. values = append(values, map[string]any{
  32. "kind": typedValueReflectValueElem.Kind(),
  33. "value": typedValueReflectValueElem.Interface(),
  34. })
  35. }
  36. requestMap := map[string]any{
  37. "sql": sql,
  38. "values": rawSqlValues,
  39. }
  40. requestJsonBytes, err := json.Marshal(requestMap)
  41. if err != nil {
  42. retErr = err
  43. return nil, retErr
  44. }
  45. err = tx.stream.SendMsg(&request.TransactionOperation{
  46. Request: &request.TransactionOperation_ExecuteRawSqlJsonRequest{
  47. ExecuteRawSqlJsonRequest: string(requestJsonBytes),
  48. },
  49. })
  50. if err != nil {
  51. retErr = err
  52. return nil, retErr
  53. }
  54. resp, err := tx.stream.Recv()
  55. if err != nil {
  56. retErr = err
  57. return nil, retErr
  58. }
  59. if !resp.Success {
  60. retErr = errors.New(resp.Msg)
  61. return nil, retErr
  62. }
  63. tableRows := make([]map[string]any, 0)
  64. err = json.Unmarshal([]byte(resp.Results), &tableRows)
  65. if err != nil {
  66. retErr = err
  67. return nil, retErr
  68. }
  69. results := make([]map[string]any, len(tableRows))
  70. for i, row := range tableRows {
  71. results[i] = row
  72. }
  73. return results, nil
  74. }