-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
output_yaml.go
73 lines (65 loc) · 1.54 KB
/
output_yaml.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
package trdsql
import (
"encoding/hex"
"unicode/utf8"
"github.com/goccy/go-yaml"
)
// YAMLWriter provides methods of the Writer interface.
type YAMLWriter struct {
writer *yaml.Encoder
outNULL string
results []yaml.MapSlice
needNULL bool
}
// NewYAMLWriter returns YAMLWriter.
func NewYAMLWriter(writeOpts *WriteOpts) *YAMLWriter {
w := &YAMLWriter{}
w.writer = yaml.NewEncoder(writeOpts.OutStream)
w.needNULL = writeOpts.OutNeedNULL
w.outNULL = writeOpts.OutNULL
return w
}
// PreWrite is area preparation.
func (w *YAMLWriter) PreWrite(columns []string, types []string) error {
w.results = make([]yaml.MapSlice, 0)
return nil
}
// WriteRow is Addition to array.
func (w *YAMLWriter) WriteRow(values []any, columns []string) error {
m := make(yaml.MapSlice, len(values))
for i, col := range values {
m[i].Key = columns[i]
m[i].Value = compatibleYAML(col, w.needNULL, w.outNULL)
}
w.results = append(w.results, m)
return nil
}
// CompatibleYAML converts the value to a YAML-compatible value.
func compatibleYAML(v any, needNULL bool, outNULL string) any {
var yl any
switch t := v.(type) {
case []byte:
if err := yaml.Unmarshal(t, &yl); err == nil {
return yl
}
if ok := utf8.Valid(t); ok {
return string(t)
}
return `\x` + hex.EncodeToString(t)
case string:
y := []byte(t)
if err := yaml.Unmarshal(y, &yl); err == nil {
return yl
}
return v
default:
if needNULL {
return outNULL
}
return v
}
}
// PostWrite is actual output.
func (w *YAMLWriter) PostWrite() error {
return w.writer.Encode(w.results)
}