-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
177 lines (143 loc) · 3.6 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"database/sql"
"encoding/csv"
"errors"
"fmt"
"os"
"strconv"
"github.com/Jeffail/gabs/v2"
_ "github.com/denisenkom/go-mssqldb"
flags "github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
)
const version string = "1.1.2"
var opts struct {
Query string `short:"q" long:"query" required:"true" description:"Query to run to extract data"`
Format string `short:"f" long:"format" required:"false" description:"Output format (default: TSV)"`
ColumnNames bool `short:"c" long:"column-names" required:"false" description:"Whether to include column names as first line of the output file"`
}
func main() {
setupLogging()
_, err := flags.Parse(&opts)
handleError(err)
log.Debugf("options: %v", opts)
if opts.Query == "v" || opts.Query == "version" {
fmt.Println(version)
os.Exit(0)
}
c := getConnection()
log.Debugf("connection: %s", c)
rows := query(c, opts.Query)
output(rows, opts.Format, opts.ColumnNames)
}
// Creates a new writer, defaulting to tabs
// as separator.
func newTsvWriter() *csv.Writer {
w := csv.NewWriter(os.Stdout)
w.Comma = '\t'
return w
}
// Utility function to setup logging.
// If no log level is specified from
// the environment, we default to ERROR,
// so that the resulting TSV doesn't get mixed
// up with logging statements unless an error
// occurred.
func setupLogging() {
l := os.Getenv("LOG_LEVEL")
if l == "" {
l = "ERROR"
}
level, err := log.ParseLevel(l)
handleError(err)
log.SetLevel(level)
}
// Receives a list of rows and iterates through them,
// while printing them to the stdout
func output(rows *sql.Rows, format string, includeColumns bool) {
defer rows.Close()
if format == "json" {
outputJSON(rows)
} else {
outputTsv(rows, includeColumns)
}
log.Debug("done")
}
func outputTsv(rows *sql.Rows, includeColumns bool) {
w := newTsvWriter()
cols, err := rows.Columns()
handleError(err)
log.Debug("columns: %v", cols)
values := make([]string, len(cols))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
if includeColumns == true {
w.Write(cols)
}
for rows.Next() {
err = rows.Scan(scanArgs...)
handleError(err)
if err := w.Write(values); err != nil {
log.Fatalln("error writing record to csv:", err)
}
w.Flush()
if err := w.Error(); err != nil {
log.Fatal(err)
}
}
handleError(rows.Err())
}
func outputJSON(rows *sql.Rows) {
cols, err := rows.ColumnTypes()
handleError(err)
for rows.Next() {
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i := range columns {
columnPointers[i] = &columns[i]
}
if err := rows.Scan(columnPointers...); err != nil {
return
}
m := make(map[string]interface{})
for i, col := range cols {
m[col.Name()] = *columnPointers[i].(*interface{})
switch t := col.DatabaseTypeName(); t {
case "DECIMAL":
dec, err := strconv.ParseFloat(string(m[col.Name()].([]uint8)), 64)
if err == nil {
m[col.Name()] = dec
}
}
}
jsonObj := gabs.Wrap(m)
fmt.Println(jsonObj.String())
}
}
func query(c string, q string) *sql.Rows {
conn, err := sql.Open("mssql", c)
handleError(err)
defer conn.Close()
stmt, err := conn.Prepare(opts.Query)
handleError(err)
defer stmt.Close()
rows, err := stmt.Query()
handleError(err)
return rows
}
func getConnection() string {
c := os.Getenv("MSSQL_CONN")
if c == "" {
handleError(errors.New("Environment variable MSSQL_CONN must be passed to connect to the DB"))
}
return c
}
// How can I live without you?
func handleError(err error) {
if err != nil {
log.Fatalf("%v", err)
}
}