-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexecutor.go
87 lines (73 loc) · 1.43 KB
/
executor.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
package main
import (
"context"
"database/sql"
"fmt"
"os"
"os/signal"
"strings"
"github.com/jmoiron/sqlx"
)
type executor struct {
db *sqlx.DB
renderer *renderer
history *history
}
func newExecutor(db *sqlx.DB, renderer *renderer, history *history) *executor {
return &executor{
db: db,
renderer: renderer,
history: history,
}
}
func (e *executor) execute(in string) {
ctx, ctxCancel := context.WithCancel(context.Background())
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
ctxCancel()
}
}()
in = strings.TrimSpace(in)
if in == "" {
return
}
if in == "exit" {
os.Exit(0)
}
if in[len(in)-1] != ';' {
fmt.Println("missing trailing ';'")
return
}
e.history.add(in)
rows, err := e.db.QueryContext(ctx, in)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
columns, err := rows.Columns()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
types, err := rows.ColumnTypes()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
var resultRows [][]interface{}
for rows.Next() {
arr := buildScanArray(types)
rows.Scan(arr...)
resultRows = append(resultRows, arr)
}
e.renderer.renderResults(columns, resultRows)
}
func buildScanArray(types []*sql.ColumnType) []interface{} {
res := make([]interface{}, len(types))
for i, t := range types {
res[i] = sqlTypeToGo(t)
}
return res
}