-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
output_vertical.go
81 lines (73 loc) · 1.6 KB
/
output_vertical.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
package trdsql
import (
"bufio"
"fmt"
"strings"
runewidth "github.com/mattn/go-runewidth"
"golang.org/x/term"
)
// VFWriter is Vertical Format output.
type VFWriter struct {
writer *bufio.Writer
outNULL string
header []string
termWidth int
hSize int
count int
needNULL bool
}
// NewVFWriter returns VFWriter.
func NewVFWriter(writeOpts *WriteOpts) *VFWriter {
var err error
w := &VFWriter{}
w.writer = bufio.NewWriter(writeOpts.OutStream)
w.termWidth, _, err = term.GetSize(0)
if err != nil {
w.termWidth = 40
}
w.needNULL = writeOpts.OutNeedNULL
w.outNULL = writeOpts.OutNULL
return w
}
// PreWrite is preparation.
func (w *VFWriter) PreWrite(columns []string, types []string) error {
w.count = 0
w.header = make([]string, len(columns))
w.hSize = 0
for i, col := range columns {
if w.hSize < runewidth.StringWidth(col) {
w.hSize = runewidth.StringWidth(col)
}
w.header[i] = col
}
return nil
}
// WriteRow is actual output.
func (w *VFWriter) WriteRow(values []any, columns []string) error {
w.count++
_, err := fmt.Fprintf(w.writer,
"---[ %d]%s\n", w.count, strings.Repeat("-", (w.termWidth-16)))
if err != nil {
debug.Printf("%s\n", err)
}
for i, col := range w.header {
v := w.hSize - runewidth.StringWidth(col)
str := ValString(values[i])
if values[i] == nil && w.needNULL {
str = w.outNULL
}
_, err := fmt.Fprintf(w.writer,
"%s%s | %-s\n",
strings.Repeat(" ", v+2),
col,
str)
if err != nil {
debug.Printf("%s\n", err)
}
}
return nil
}
// PostWrite is flush.
func (w *VFWriter) PostWrite() error {
return w.writer.Flush()
}