-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrunner.go
79 lines (62 loc) · 1.38 KB
/
runner.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
package sqlexec
import (
"fmt"
"io"
"github.com/jmoiron/sqlx"
"github.com/olekukonko/tablewriter"
)
// Runner runs a SQL statement for given command name and parameters.
type Runner struct {
// FileSystem represents the project directory file system.
FileSystem FileSystem
// DB is a client to underlying database.
DB *sqlx.DB
}
// Run runs a given command with provided parameters.
func (r *Runner) Run(name string, args ...Param) (*Rows, error) {
provider := &Provider{
dialect: r.DB.DriverName(),
}
if err := provider.ReadDir(r.FileSystem); err != nil {
return nil, err
}
query, err := provider.Query(name)
if err != nil {
return nil, err
}
stmt, err := r.DB.Preparex(query)
if err != nil {
return nil, err
}
defer func() {
if stmtErr := stmt.Close(); err == nil {
err = stmtErr
}
}()
return stmt.Queryx(args...)
}
// Print prints the rows
func (r *Runner) Print(writer io.Writer, rows *sqlx.Rows) error {
table := tablewriter.NewWriter(writer)
columns, err := rows.Columns()
if err != nil {
return err
}
table.SetHeader(columns)
for rows.Next() {
record, err := rows.SliceScan()
if err != nil {
return err
}
row := []string{}
for _, column := range record {
if data, ok := column.([]byte); ok {
column = string(data)
}
row = append(row, fmt.Sprintf("%v", column))
}
table.Append(row)
}
table.Render()
return nil
}