github.com/influxdata/influxdb/v2@v2.7.6/influxql/query/response.go (about)

     1  package query
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  )
     7  
     8  // Response represents a list of statement results.
     9  type Response struct {
    10  	Results []*Result
    11  	Err     error
    12  }
    13  
    14  // MarshalJSON encodes a Response struct into JSON.
    15  func (r Response) MarshalJSON() ([]byte, error) {
    16  	// Define a struct that outputs "error" as a string.
    17  	var o struct {
    18  		Results []*Result `json:"results,omitempty"`
    19  		Err     string    `json:"error,omitempty"`
    20  	}
    21  
    22  	// Copy fields to output struct.
    23  	o.Results = r.Results
    24  	if r.Err != nil {
    25  		o.Err = r.Err.Error()
    26  	}
    27  
    28  	return json.Marshal(&o)
    29  }
    30  
    31  // UnmarshalJSON decodes the data into the Response struct.
    32  func (r *Response) UnmarshalJSON(b []byte) error {
    33  	var o struct {
    34  		Results []*Result `json:"results,omitempty"`
    35  		Err     string    `json:"error,omitempty"`
    36  	}
    37  
    38  	err := json.Unmarshal(b, &o)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	r.Results = o.Results
    43  	if o.Err != "" {
    44  		r.Err = errors.New(o.Err)
    45  	}
    46  	return nil
    47  }
    48  
    49  // Error returns the first error from any statement.
    50  // Returns nil if no errors occurred on any statements.
    51  func (r *Response) Error() error {
    52  	if r.Err != nil {
    53  		return r.Err
    54  	}
    55  	for _, rr := range r.Results {
    56  		if rr.Err != nil {
    57  			return rr.Err
    58  		}
    59  	}
    60  	return nil
    61  }