Merge pull request #2137 from peekeri/influx-2050

Refactor Results to Response (#2050)
pull/2168/head
Paul Dix 2015-04-04 11:28:19 -04:00
commit fb52703b13
10 changed files with 71 additions and 71 deletions

View File

@ -148,11 +148,11 @@ func queryDB(con *client.Client, cmd string) (res []client.Result, err error) {
Command: cmd, Command: cmd,
Database: MyDB, Database: MyDB,
} }
if results, err := con.Query(q); err == nil { if response, err := con.Query(q); err == nil {
if results.Error() != nil { if response.Error() != nil {
return res, results.Error() return res, response.Error()
} }
res = results.Results res = response.Results
} }
return return
} }

View File

@ -63,8 +63,8 @@ func ExampleClient_Query() {
Command: "select count(value) from shapes", Command: "select count(value) from shapes",
Database: "square_holes", Database: "square_holes",
} }
if results, err := con.Query(q); err == nil && results.Error() == nil { if response, err := con.Query(q); err == nil && response.Error() == nil {
log.Println(results.Results) log.Println(response.Results)
} }
} }

View File

@ -54,8 +54,8 @@ func NewClient(c Config) (*Client, error) {
return &client, nil return &client, nil
} }
// Query sends a command to the server and returns the Results // Query sends a command to the server and returns the Response
func (c *Client) Query(q Query) (*Results, error) { func (c *Client) Query(q Query) (*Response, error) {
u := c.url u := c.url
u.Path = "query" u.Path = "query"
@ -78,20 +78,20 @@ func (c *Client) Query(q Query) (*Results, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
var results Results var response Response
dec := json.NewDecoder(resp.Body) dec := json.NewDecoder(resp.Body)
dec.UseNumber() dec.UseNumber()
err = dec.Decode(&results) err = dec.Decode(&response)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &results, nil return &response, nil
} }
// Write takes BatchPoints and allows for writing of multiple points with defaults // Write takes BatchPoints and allows for writing of multiple points with defaults
// If successful, error is nil and Results is nil // If successful, error is nil and Response is nil
// If an error occurs, Results may contain additional information if populated. // If an error occurs, Response may contain additional information if populated.
func (c *Client) Write(bp BatchPoints) (*Results, error) { func (c *Client) Write(bp BatchPoints) (*Response, error) {
c.url.Path = "write" c.url.Path = "write"
b, err := json.Marshal(&bp) b, err := json.Marshal(&bp)
@ -111,16 +111,16 @@ func (c *Client) Write(bp BatchPoints) (*Results, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
var results Results var response Response
dec := json.NewDecoder(resp.Body) dec := json.NewDecoder(resp.Body)
dec.UseNumber() dec.UseNumber()
err = dec.Decode(&results) err = dec.Decode(&response)
if err != nil && err.Error() != "EOF" { if err != nil && err.Error() != "EOF" {
return nil, err return nil, err
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return &results, results.Error() return &response, response.Error()
} }
return nil, nil return nil, nil
@ -217,14 +217,14 @@ func (r *Result) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// Results represents a list of statement results. // Response represents a list of statement results.
type Results struct { type Response struct {
Results []Result Results []Result
Err error Err error
} }
// MarshalJSON encodes the result into JSON. // MarshalJSON encodes the response into JSON.
func (r *Results) MarshalJSON() ([]byte, error) { func (r *Response) MarshalJSON() ([]byte, error) {
// Define a struct that outputs "error" as a string. // Define a struct that outputs "error" as a string.
var o struct { var o struct {
Results []Result `json:"results,omitempty"` Results []Result `json:"results,omitempty"`
@ -240,8 +240,8 @@ func (r *Results) MarshalJSON() ([]byte, error) {
return json.Marshal(&o) return json.Marshal(&o)
} }
// UnmarshalJSON decodes the data into the Results struct // UnmarshalJSON decodes the data into the Response struct
func (r *Results) UnmarshalJSON(b []byte) error { func (r *Response) UnmarshalJSON(b []byte) error {
var o struct { var o struct {
Results []Result `json:"results,omitempty"` Results []Result `json:"results,omitempty"`
Err string `json:"error,omitempty"` Err string `json:"error,omitempty"`
@ -262,7 +262,7 @@ func (r *Results) UnmarshalJSON(b []byte) error {
// Error returns the first error from any statement. // Error returns the first error from any statement.
// Returns nil if no errors occurred on any statements. // Returns nil if no errors occurred on any statements.
func (r Results) Error() error { func (r Response) Error() error {
if r.Err != nil { if r.Err != nil {
return r.Err return r.Err
} }

View File

@ -46,7 +46,7 @@ func TestClient_Ping(t *testing.T) {
func TestClient_Query(t *testing.T) { func TestClient_Query(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var data influxdb.Results var data influxdb.Response
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(data) _ = json.NewEncoder(w).Encode(data)
})) }))
@ -99,7 +99,7 @@ func TestClient_BasicAuth(t *testing.T) {
func TestClient_Write(t *testing.T) { func TestClient_Write(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var data influxdb.Results var data influxdb.Response
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(data) _ = json.NewEncoder(w).Encode(data)
})) }))
@ -124,7 +124,7 @@ func TestClient_UserAgent(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedUserAgent = r.UserAgent() receivedUserAgent = r.UserAgent()
var data influxdb.Results var data influxdb.Response
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(data) _ = json.NewEncoder(w).Encode(data)
})) }))

View File

@ -271,14 +271,14 @@ func (c *CommandLine) dump() {
} }
func (c *CommandLine) executeQuery(query string) { func (c *CommandLine) executeQuery(query string) {
results, err := c.Client.Query(client.Query{Command: query, Database: c.Database}) response, err := c.Client.Query(client.Query{Command: query, Database: c.Database})
if err != nil { if err != nil {
fmt.Printf("ERR: %s\n", err) fmt.Printf("ERR: %s\n", err)
return return
} }
c.FormatResults(results, os.Stdout) c.FormatResponse(response, os.Stdout)
if results.Error() != nil { if response.Error() != nil {
fmt.Printf("ERR: %s\n", results.Error()) fmt.Printf("ERR: %s\n", response.Error())
if c.Database == "" { if c.Database == "" {
fmt.Println("Warning: It is possible this error is due to not setting a database.") fmt.Println("Warning: It is possible this error is due to not setting a database.")
fmt.Println(`Please set a database with the command "use <database>".`) fmt.Println(`Please set a database with the command "use <database>".`)
@ -286,26 +286,26 @@ func (c *CommandLine) executeQuery(query string) {
} }
} }
func (c *CommandLine) FormatResults(results *client.Results, w io.Writer) { func (c *CommandLine) FormatResponse(response *client.Response, w io.Writer) {
switch c.Format { switch c.Format {
case "json": case "json":
c.writeJSON(results, w) c.writeJSON(response, w)
case "csv": case "csv":
c.writeCSV(results, w) c.writeCSV(response, w)
case "column": case "column":
c.writeColumns(results, w) c.writeColumns(response, w)
default: default:
fmt.Fprintf(w, "Unknown output format %q.\n", c.Format) fmt.Fprintf(w, "Unknown output format %q.\n", c.Format)
} }
} }
func (c *CommandLine) writeJSON(results *client.Results, w io.Writer) { func (c *CommandLine) writeJSON(response *client.Response, w io.Writer) {
var data []byte var data []byte
var err error var err error
if c.Pretty { if c.Pretty {
data, err = json.MarshalIndent(results, "", " ") data, err = json.MarshalIndent(response, "", " ")
} else { } else {
data, err = json.Marshal(results) data, err = json.Marshal(response)
} }
if err != nil { if err != nil {
fmt.Fprintf(w, "Unable to parse json: %s\n", err) fmt.Fprintf(w, "Unable to parse json: %s\n", err)
@ -314,9 +314,9 @@ func (c *CommandLine) writeJSON(results *client.Results, w io.Writer) {
fmt.Fprintln(w, string(data)) fmt.Fprintln(w, string(data))
} }
func (c *CommandLine) writeCSV(results *client.Results, w io.Writer) { func (c *CommandLine) writeCSV(response *client.Response, w io.Writer) {
csvw := csv.NewWriter(w) csvw := csv.NewWriter(w)
for _, result := range results.Results { for _, result := range response.Results {
// Create a tabbed writer for each result as they won't always line up // Create a tabbed writer for each result as they won't always line up
rows := c.formatResults(result, "\t") rows := c.formatResults(result, "\t")
for _, r := range rows { for _, r := range rows {
@ -326,8 +326,8 @@ func (c *CommandLine) writeCSV(results *client.Results, w io.Writer) {
} }
} }
func (c *CommandLine) writeColumns(results *client.Results, w io.Writer) { func (c *CommandLine) writeColumns(response *client.Response, w io.Writer) {
for _, result := range results.Results { for _, result := range response.Results {
// Create a tabbed writer for each result a they won't always line up // Create a tabbed writer for each result a they won't always line up
w := new(tabwriter.Writer) w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 8, 1, '\t', 0) w.Init(os.Stdout, 0, 8, 1, '\t', 0)

View File

@ -1442,11 +1442,11 @@ func TestClientLibrary(t *testing.T) {
for _, q := range test.queries { for _, q := range test.queries {
if q.query.Command != "" { if q.query.Command != "" {
time.Sleep(500 * time.Millisecond) time.Sleep(500 * time.Millisecond)
queryResult, err := c.Query(q.query) queryResponse, err := c.Query(q.query)
if q.err != errToString(err) { if q.err != errToString(err) {
t.Errorf("unexpected error. expected: %s, got %v", q.err, err) t.Errorf("unexpected error. expected: %s, got %v", q.err, err)
} }
jsonResult := mustMarshalJSON(queryResult) jsonResult := mustMarshalJSON(queryResponse)
if q.expected != jsonResult { if q.expected != jsonResult {
t.Logf("query expected result: %s\n", q.expected) t.Logf("query expected result: %s\n", q.expected)
t.Logf("query got result: %s\n", jsonResult) t.Logf("query got result: %s\n", jsonResult)

View File

@ -202,7 +202,7 @@ func (h *Handler) serveQuery(w http.ResponseWriter, r *http.Request, user *influ
} }
// if we're not chunking, this will be the in memory buffer for all results before sending to client // if we're not chunking, this will be the in memory buffer for all results before sending to client
res := influxdb.Results{Results: make([]*influxdb.Result, 0)} res := influxdb.Response{Results: make([]*influxdb.Result, 0)}
statusWritten := false statusWritten := false
// pull all results from the channel // pull all results from the channel
@ -320,7 +320,7 @@ func (h *Handler) showMeasurements(db string, user *influxdb.User) ([]string, er
if err != nil { if err != nil {
return measurements, err return measurements, err
} }
results := influxdb.Results{} results := influxdb.Response{}
for r := range c { for r := range c {
results.Results = append(results.Results, r) results.Results = append(results.Results, r)
@ -691,12 +691,12 @@ func httpError(w http.ResponseWriter, error string, pretty bool, code int) {
w.Header().Add("content-type", "application/json") w.Header().Add("content-type", "application/json")
w.WriteHeader(code) w.WriteHeader(code)
results := influxdb.Results{Err: errors.New(error)} response := influxdb.Response{Err: errors.New(error)}
var b []byte var b []byte
if pretty { if pretty {
b, _ = json.MarshalIndent(results, "", " ") b, _ = json.MarshalIndent(response, "", " ")
} else { } else {
b, _ = json.Marshal(results) b, _ = json.Marshal(response)
} }
w.Write(b) w.Write(b)
} }

View File

@ -1354,7 +1354,7 @@ func TestHandler_serveWriteSeriesNonZeroTime(t *testing.T) {
t.Errorf("unexpected status: %d", status) t.Errorf("unexpected status: %d", status)
} }
r := &influxdb.Results{} r := &influxdb.Response{}
if err := json.Unmarshal([]byte(body), r); err != nil { if err := json.Unmarshal([]byte(body), r); err != nil {
t.Logf("query : %s\n", query) t.Logf("query : %s\n", query)
t.Log(body) t.Log(body)
@ -1401,7 +1401,7 @@ func TestHandler_serveWriteSeriesZeroTime(t *testing.T) {
t.Errorf("unexpected status: %d", status) t.Errorf("unexpected status: %d", status)
} }
r := &influxdb.Results{} r := &influxdb.Response{}
if err := json.Unmarshal([]byte(body), r); err != nil { if err := json.Unmarshal([]byte(body), r); err != nil {
t.Logf("query : %s\n", query) t.Logf("query : %s\n", query)
t.Log(body) t.Log(body)
@ -1489,7 +1489,7 @@ func TestHandler_serveWriteSeriesBatch(t *testing.T) {
t.Errorf("unexpected status: %d", status) t.Errorf("unexpected status: %d", status)
} }
r := &influxdb.Results{} r := &influxdb.Response{}
if err := json.Unmarshal([]byte(body), r); err != nil { if err := json.Unmarshal([]byte(body), r); err != nil {
t.Logf("query : %s\n", query) t.Logf("query : %s\n", query)
t.Log(body) t.Log(body)
@ -1531,7 +1531,7 @@ func TestHandler_serveWriteSeriesFieldTypeConflict(t *testing.T) {
t.Errorf("unexpected status: %d", status) t.Errorf("unexpected status: %d", status)
} }
r := &influxdb.Results{} r := &influxdb.Response{}
if err := json.Unmarshal([]byte(body), r); err != nil { if err := json.Unmarshal([]byte(body), r); err != nil {
t.Log(body) t.Log(body)
t.Error(err) t.Error(err)
@ -1646,16 +1646,16 @@ func TestHandler_ChunkedResponses(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("error reading response: %s", err.Error()) t.Fatalf("error reading response: %s", err.Error())
} }
results := &influxdb.Results{} response := &influxdb.Response{}
err = json.Unmarshal(chunk[0:n], results) err = json.Unmarshal(chunk[0:n], response)
if err != nil { if err != nil {
t.Fatalf("error unmarshaling resultsz: %s", err.Error()) t.Fatalf("error unmarshaling resultsz: %s", err.Error())
} }
if len(results.Results) != 1 { if len(response.Results) != 1 {
t.Fatalf("didn't get 1 result: %s\n", mustMarshalJSON(results)) t.Fatalf("didn't get 1 result: %s\n", mustMarshalJSON(response))
} }
if len(results.Results[0].Series) != 1 { if len(response.Results[0].Series) != 1 {
t.Fatalf("didn't get 1 series: %s\n", mustMarshalJSON(results)) t.Fatalf("didn't get 1 series: %s\n", mustMarshalJSON(response))
} }
var vals [][]interface{} var vals [][]interface{}
if i == 0 { if i == 0 {
@ -1663,8 +1663,8 @@ func TestHandler_ChunkedResponses(t *testing.T) {
} else { } else {
vals = [][]interface{}{{"2009-11-10T23:30:00Z", 25}} vals = [][]interface{}{{"2009-11-10T23:30:00Z", 25}}
} }
if mustMarshalJSON(vals) != mustMarshalJSON(results.Results[0].Series[0].Values) { if mustMarshalJSON(vals) != mustMarshalJSON(response.Results[0].Series[0].Values) {
t.Fatalf("values weren't what was expected:\n exp: %s\n got: %s", mustMarshalJSON(vals), mustMarshalJSON(results.Results[0].Series[0].Values)) t.Fatalf("values weren't what was expected:\n exp: %s\n got: %s", mustMarshalJSON(vals), mustMarshalJSON(response.Results[0].Series[0].Values))
} }
} }
} }

View File

@ -3318,14 +3318,14 @@ func (r *Result) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// Results represents a list of statement results. // Response represents a list of statement results.
type Results struct { type Response struct {
Results []*Result Results []*Result
Err error Err error
} }
// MarshalJSON encodes a Results struct into JSON. // MarshalJSON encodes a Response struct into JSON.
func (r Results) MarshalJSON() ([]byte, error) { func (r Response) MarshalJSON() ([]byte, error) {
// Define a struct that outputs "error" as a string. // Define a struct that outputs "error" as a string.
var o struct { var o struct {
Results []*Result `json:"results,omitempty"` Results []*Result `json:"results,omitempty"`
@ -3341,8 +3341,8 @@ func (r Results) MarshalJSON() ([]byte, error) {
return json.Marshal(&o) return json.Marshal(&o)
} }
// UnmarshalJSON decodes the data into the Results struct // UnmarshalJSON decodes the data into the Response struct
func (r *Results) UnmarshalJSON(b []byte) error { func (r *Response) UnmarshalJSON(b []byte) error {
var o struct { var o struct {
Results []*Result `json:"results,omitempty"` Results []*Result `json:"results,omitempty"`
Err string `json:"error,omitempty"` Err string `json:"error,omitempty"`
@ -3361,7 +3361,7 @@ func (r *Results) UnmarshalJSON(b []byte) error {
// Error returns the first error from any statement. // Error returns the first error from any statement.
// Returns nil if no errors occurred on any statements. // Returns nil if no errors occurred on any statements.
func (r *Results) Error() error { func (r *Response) Error() error {
if r.Err != nil { if r.Err != nil {
return r.Err return r.Err
} }

View File

@ -1945,12 +1945,12 @@ func (s *Server) MustWriteSeries(database, retentionPolicy string, points []infl
return index return index
} }
func (s *Server) executeQuery(q *influxql.Query, db string, user *influxdb.User) influxdb.Results { func (s *Server) executeQuery(q *influxql.Query, db string, user *influxdb.User) influxdb.Response {
results, err := s.ExecuteQuery(q, db, user, 10000) results, err := s.ExecuteQuery(q, db, user, 10000)
if err != nil { if err != nil {
return influxdb.Results{Err: err} return influxdb.Response{Err: err}
} }
res := influxdb.Results{} res := influxdb.Response{}
for r := range results { for r := range results {
l := len(res.Results) l := len(res.Results)
if l == 0 { if l == 0 {