Move result struct into its own file

This commit is contained in:
Dan Sosedoff 2016-01-04 18:19:16 -06:00
parent 5a92c5508c
commit 91d8d3ee83
2 changed files with 75 additions and 70 deletions

View File

@ -1,9 +1,6 @@
package client
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"reflect"
@ -22,13 +19,6 @@ type Client struct {
ConnectionString string
}
type Row []interface{}
type Result struct {
Columns []string `json:"columns"`
Rows []Row `json:"rows"`
}
// Struct to hold table rows browsing options
type RowsOptions struct {
Limit int // Number of rows to fetch
@ -206,66 +196,6 @@ func (client *Client) query(query string, args ...interface{}) (*Result, error)
return &result, nil
}
func (res *Result) Format() []map[string]interface{} {
var items []map[string]interface{}
for _, row := range res.Rows {
item := make(map[string]interface{})
for i, c := range res.Columns {
item[c] = row[i]
}
items = append(items, item)
}
return items
}
func (res *Result) CSV() []byte {
buff := &bytes.Buffer{}
writer := csv.NewWriter(buff)
writer.Write(res.Columns)
for _, row := range res.Rows {
record := make([]string, len(res.Columns))
for i, item := range row {
if item != nil {
record[i] = fmt.Sprintf("%v", item)
} else {
record[i] = ""
}
}
err := writer.Write(record)
if err != nil {
fmt.Println(err)
break
}
}
writer.Flush()
return buff.Bytes()
}
func (res *Result) JSON() []byte {
records := []map[string]interface{}{}
for _, row := range res.Rows {
record := map[string]interface{}{}
for i, col := range res.Columns {
record[col] = row[i]
}
records = append(records, record)
}
data, _ := json.Marshal(records)
return data
}
// Close database connection
func (client *Client) Close() error {
if client.db != nil {

75
pkg/client/result.go Normal file
View File

@ -0,0 +1,75 @@
package client
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
)
type Row []interface{}
type Result struct {
Columns []string `json:"columns"`
Rows []Row `json:"rows"`
}
func (res *Result) Format() []map[string]interface{} {
var items []map[string]interface{}
for _, row := range res.Rows {
item := make(map[string]interface{})
for i, c := range res.Columns {
item[c] = row[i]
}
items = append(items, item)
}
return items
}
func (res *Result) CSV() []byte {
buff := &bytes.Buffer{}
writer := csv.NewWriter(buff)
writer.Write(res.Columns)
for _, row := range res.Rows {
record := make([]string, len(res.Columns))
for i, item := range row {
if item != nil {
record[i] = fmt.Sprintf("%v", item)
} else {
record[i] = ""
}
}
err := writer.Write(record)
if err != nil {
fmt.Println(err)
break
}
}
writer.Flush()
return buff.Bytes()
}
func (res *Result) JSON() []byte {
records := []map[string]interface{}{}
for _, row := range res.Rows {
record := map[string]interface{}{}
for i, col := range res.Columns {
record[col] = row[i]
}
records = append(records, record)
}
data, _ := json.Marshal(records)
return data
}