Convers query results to CSV with format flag

This commit is contained in:
Dan Sosedoff
2014-10-10 18:56:02 -05:00
parent 2e766af361
commit 38cef071e8
2 changed files with 42 additions and 0 deletions

View File

@@ -1,6 +1,9 @@
package main
import (
"bytes"
"encoding/csv"
"fmt"
"github.com/jmoiron/sqlx"
"reflect"
)
@@ -107,3 +110,30 @@ func (res *Result) Format() []map[string]interface{} {
return items
}
func (res *Result) CSV() string {
buff := &bytes.Buffer{}
writer := csv.NewWriter(buff)
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.String()
}