-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathencode.go
1354 lines (1302 loc) · 33.6 KB
/
encode.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tblfmt
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os/exec"
"strings"
"sync/atomic"
"syscall"
"unicode"
runewidth "github.com/mattn/go-runewidth"
)
// TableEncoder is a buffered, lookahead table encoder for result sets.
type TableEncoder struct {
// ResultSet is the result set to encode.
resultSet ResultSet
// count is the number of rows to scan ahead by (buffer), up to count, in
// order to determine maximum column widths returned by the encoder's
// formatter.
//
// Note: when 0 all rows will be scanned (buffered) prior to encoding the
// table.
count int
// tab is the tab width.
tab int
// newline is the record separator to use.
newline []byte
// border is the display border size.
border int
// inline toggles writing the column header names inline with the top line.
inline bool
// lineStyle is the table line style.
lineStyle LineStyle
// formatter handles formatting values prior to output.
formatter Formatter
// skipHeader disables writing header.
skipHeader bool
// summary is the summary map.
summary Summary
// isCustomSummary when summary has been set via options
isCustomSummary bool
// title is the title value.
title *Value
// empty is the empty value.
empty *Value
// headers contains formatted column names.
headers []*Value
// offsets are the column offsets.
offsets []int
// widths are the user-supplied column widths.
widths []int
// maxWidths are calculated max column widths. Max widths are at least as
// wide as user-supplied widths
maxWidths []int
// minExpandWidth of the table required to switch to the ExpandedEncoder
// zero disables switching
minExpandWidth int
// minPagerWidth of the table required to redirect output to the pager,
// zero disables pager
minPagerWidth int
// minPagerHeight of the table required to redirect output to the pager,
// zero disables pager
minPagerHeight int
// pagerCmd is the pager command to run and redirect output to
// if height or width is greater than minPagerHeight and minPagerWidth,
pagerCmd string
// scanCount is the number of scanned results in the result set.
scanCount int64
// lowerColumnNames indicates lower casing the column names when column
// names are all caps.
lowerColumnNames bool
// columnTypes is used to build column types for a result set.
columnTypes func(ResultSet, []interface{}, int) error
// w is the undelying writer
w *bufio.Writer
}
// NewTableEncoder creates a new table encoder using the provided options.
//
// The table encoder has a default value of border 1, and a tab width of 8.
func NewTableEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) {
enc := &TableEncoder{
resultSet: resultSet,
newline: newline,
border: 1,
tab: 8,
lineStyle: ASCIILineStyle(),
formatter: NewEscapeFormatter(WithHeaderAlign(AlignCenter)),
summary: DefaultTableSummary(),
empty: &Value{
Tabs: make([][][2]int, 1),
},
}
// apply options
for _, o := range opts {
if err := o.apply(enc); err != nil {
return nil, err
}
}
// check linestyle runes
// TODO: this check should be removed
for _, l := range [][4]rune{
enc.lineStyle.Top,
enc.lineStyle.Mid,
enc.lineStyle.Row,
enc.lineStyle.Wrap,
enc.lineStyle.End,
} {
for _, r := range l {
if r != 0 && runewidth.RuneWidth(r) != 1 {
return nil, ErrInvalidLineStyle
}
}
}
return enc, nil
}
// Encode encodes a single result set to the writer using the formatting
// options specified in the encoder.
func (enc *TableEncoder) Encode(w io.Writer) error {
// reset scan count
enc.scanCount = 0
enc.w = bufio.NewWriterSize(w, 2048)
if enc.resultSet == nil {
return ErrResultSetIsNil
}
// get and check columns
clen, cols, err := buildColNames(enc.resultSet, enc.lowerColumnNames)
switch {
case err != nil:
return err
case clen == 0:
return ErrResultSetHasNoColumns
}
// setup offsets, widths
enc.offsets = make([]int, clen)
wroteHeader := enc.skipHeader
// default to user-supplied widths
enc.maxWidths = make([]int, clen)
copy(enc.maxWidths, enc.widths)
enc.headers, err = enc.formatter.Header(cols)
if err != nil {
return err
}
var cmd *exec.Cmd
var cmdBuf io.WriteCloser
for {
var vals [][]*Value
// buffer
vals, err = enc.nextResults()
if err != nil {
return err
}
// no more values
if len(vals) == 0 {
break
}
enc.calcWidth(vals)
if enc.minExpandWidth != 0 && enc.tableWidth() >= enc.minExpandWidth {
t := *enc
t.formatter = NewEscapeFormatter()
exp := ExpandedEncoder{
TableEncoder: t,
}
exp.offsets = make([]int, 2)
exp.maxWidths = make([]int, 2)
exp.headers, err = exp.formatter.Header(cols)
if err != nil {
return err
}
exp.calcWidth(vals)
if exp.pagerCmd != "" && cmd == nil &&
((exp.minPagerHeight != 0 && exp.tableHeight(vals) >= exp.minPagerHeight) ||
(exp.minPagerWidth != 0 && exp.tableWidth() >= exp.minPagerWidth)) {
cmd, cmdBuf, err = startPager(exp.pagerCmd, w)
if err != nil {
return err
}
exp.w = bufio.NewWriterSize(cmdBuf, 2048)
}
if err := exp.encodeVals(vals); err != nil {
return checkErr(err, cmd)
}
continue
}
if enc.pagerCmd != "" && cmd == nil &&
((enc.minPagerHeight != 0 && enc.tableHeight(vals) >= enc.minPagerHeight) ||
(enc.minPagerWidth != 0 && enc.tableWidth() >= enc.minPagerWidth)) {
cmd, cmdBuf, err = startPager(enc.pagerCmd, w)
if err != nil {
return err
}
enc.w = bufio.NewWriterSize(cmdBuf, 2048)
}
// print header if not already done
if !wroteHeader {
wroteHeader = true
enc.header()
}
if err := enc.encodeVals(vals); err != nil {
return checkErr(err, cmd)
}
// draw end border
if enc.border >= 2 {
enc.divider(enc.rowStyle(enc.lineStyle.End))
}
}
// add summary
if err := summarize(enc.w, enc.summary, enc.scanCount); err != nil {
return err
}
if err := enc.w.Flush(); err != nil {
return checkErr(err, cmd)
}
if cmd != nil {
cmdBuf.Close()
return cmd.Wait()
}
return nil
}
func startPager(pagerCmd string, w io.Writer) (*exec.Cmd, io.WriteCloser, error) {
cmd := exec.Command(pagerCmd)
cmd.Stdout = w
cmd.Stderr = w
cmdBuf, err := cmd.StdinPipe()
if err != nil {
return nil, nil, err
}
return cmd, cmdBuf, cmd.Start()
}
func checkErr(err error, cmd *exec.Cmd) error {
if cmd != nil && errors.Is(err, syscall.EPIPE) {
// broken pipe means pager quit before consuming all data, which might be expected
return nil
}
return err
}
func (enc *TableEncoder) encodeVals(vals [][]*Value) error {
rs := enc.rowStyle(enc.lineStyle.Row)
// print buffered vals
for i := 0; i < len(vals); i++ {
enc.row(vals[i], rs)
if i+1%1000 == 0 {
// check error every 1k rows
if err := enc.w.Flush(); err != nil {
return err
}
}
}
return nil
}
// EncodeAll encodes all result sets to the writer using the encoder settings.
func (enc *TableEncoder) EncodeAll(w io.Writer) error {
if err := enc.Encode(w); err != nil {
return err
}
for enc.resultSet.NextResultSet() {
if _, err := w.Write(enc.newline); err != nil {
return err
}
if err := enc.Encode(w); err != nil {
return err
}
}
return nil
}
// nextResults reads the next enc.count values,
// or all values if enc.count = 0
func (enc *TableEncoder) nextResults() ([][]*Value, error) {
var vals [][]*Value
if enc.count != 0 {
vals = make([][]*Value, 0, enc.count)
}
// read to count (or all)
var i int
var r []interface{}
for enc.resultSet.Next() {
if i == 0 {
// set up storage for results
var err error
r, err = buildColumnTypes(enc.resultSet, len(enc.headers), enc.columnTypes)
if err != nil {
return nil, err
}
}
v, err := scanAndFormat(enc.resultSet, r, enc.formatter, &enc.scanCount)
if err != nil {
return vals, err
}
vals, i = append(vals, v), i+1
// read by batches of enc.count rows
if enc.count != 0 && i%enc.count == 0 {
break
}
}
return vals, enc.resultSet.Err()
}
func (enc *TableEncoder) calcWidth(vals [][]*Value) {
// calc offsets and widths for this batch of rows
var offset int
rs := enc.rowStyle(enc.lineStyle.Row)
offset += runewidth.StringWidth(string(rs.left))
for i, h := range enc.headers {
if i != 0 {
offset += runewidth.StringWidth(string(rs.middle))
}
// store offset
enc.offsets[i] = offset
// header's widths are the minimum
enc.maxWidths[i] = max(enc.maxWidths[i], h.MaxWidth(offset, enc.tab))
// from top to bottom, find max column width
for j := 0; j < len(vals); j++ {
cell := vals[j][i]
if cell == nil {
cell = enc.empty
}
enc.maxWidths[i] = max(enc.maxWidths[i], cell.MaxWidth(offset, enc.tab))
}
// add column width, and one space for newline indicator
offset += enc.maxWidths[i]
if rs.hasWrapping && enc.border != 0 {
offset++
}
}
}
func (enc *TableEncoder) header() {
rs := enc.rowStyle(enc.lineStyle.Row)
if enc.title != nil && enc.title.Width != 0 {
maxWidth := ((enc.tableWidth() - enc.title.Width) / 2) + enc.title.Width
enc.writeAligned(enc.title.Buf, rs.filler, AlignRight, maxWidth-enc.title.Width)
enc.w.Write(enc.newline)
}
// draw top border
if enc.border >= 2 && !enc.inline {
enc.divider(enc.rowStyle(enc.lineStyle.Top))
}
// draw the header row with top border style
if enc.inline {
rs = enc.rowStyle(enc.lineStyle.Top)
}
// write header
enc.row(enc.headers, rs)
if !enc.inline {
// draw mid divider
enc.divider(enc.rowStyle(enc.lineStyle.Mid))
}
}
// rowStyle returns the left, right and midle borders.
// It also profides the filler string, and indicates
// if this style uses a wrapping indicator.
func (enc TableEncoder) rowStyle(r [4]rune) rowStyle {
var left, right, middle, spacer, filler string
spacer = strings.Repeat(string(r[1]), runewidth.RuneWidth(enc.lineStyle.Row[1]))
filler = string(r[1])
// compact output, r[1] is set to \0
if r[1] == 0 {
filler = " "
}
// outside borders
if enc.border > 1 {
left = string(r[0])
right = string(r[3])
}
// initial spacer when borders are set
if enc.border > 0 {
left += spacer
}
middle = " "
if enc.border >= 1 { // inside border
middle = string(r[2]) + spacer
}
return rowStyle{
left: []byte(left),
wrapper: []byte(string(enc.lineStyle.Wrap[1])),
middle: []byte(middle),
right: []byte(right + string(enc.newline)),
filler: []byte(filler),
hasWrapping: runewidth.RuneWidth(enc.lineStyle.Row[1]) > 0,
}
}
// divider draws a divider.
func (enc *TableEncoder) divider(rs rowStyle) {
// left
enc.w.Write(rs.left)
for i, width := range enc.maxWidths {
// column
enc.w.Write(bytes.Repeat(rs.filler, width))
// line feed indicator
if rs.hasWrapping && enc.border >= 1 {
enc.w.Write(rs.filler)
}
// middle separator
if i != len(enc.maxWidths)-1 {
enc.w.Write(rs.middle)
}
}
// right
enc.w.Write(rs.right)
}
// tableWidth calculates total table width.
func (enc *TableEncoder) tableWidth() int {
rs := enc.rowStyle(enc.lineStyle.Mid)
width := runewidth.StringWidth(string(rs.left)) + runewidth.StringWidth(string(rs.right))
for i, w := range enc.maxWidths {
width += w
if rs.hasWrapping && enc.border >= 1 {
width += 1
}
if i != len(enc.maxWidths)-1 {
width += runewidth.StringWidth(string(rs.middle))
}
}
return width
}
// tableHeight calculates total table height.
func (enc *TableEncoder) tableHeight(rows [][]*Value) int {
height := 0
if enc.title != nil && enc.title.Width != 0 {
height += strings.Count(string(enc.title.Buf), "\n")
}
// top border
if enc.border >= 2 && !enc.inline {
height++
}
// header
height++
// mid divider
if enc.inline {
height++
}
for _, row := range rows {
largest := 1
for _, cell := range row {
if cell == nil {
cell = enc.empty
}
if len(cell.Newlines) > largest {
largest = len(cell.Newlines)
}
}
height += largest
}
// end border
if enc.border >= 2 {
height++
}
// scanCount at this point is not the final value but this is better than nothing
if enc.summary != nil && enc.summary[-1] != nil || enc.summary[int(enc.scanCount)] != nil {
height++
}
return height
}
// row draws the a table row.
func (enc *TableEncoder) row(vals []*Value, rs rowStyle) {
var l int
for {
// left
enc.w.Write(rs.left)
var remaining bool
for i, v := range vals {
if v == nil {
v = enc.empty
}
// write value
if l <= len(v.Newlines) {
// determine start, end, width
start, end, width := 0, len(v.Buf), 0
if l > 0 {
start = v.Newlines[l-1][0] + 1
}
if l < len(v.Newlines) {
end = v.Newlines[l][0]
width += v.Newlines[l][1]
}
if len(v.Tabs) != 0 && len(v.Tabs[l]) != 0 {
width += tabwidth(v.Tabs[l], enc.offsets[i], enc.tab)
}
if l == len(v.Newlines) {
width += v.Width
}
padding := enc.maxWidths[i] - width
// no padding for last cell if no border and aligned left
if enc.border <= 1 && v.Align == AlignLeft && i == len(vals)-1 && (!rs.hasWrapping || l >= len(v.Newlines)) {
padding = 0
}
enc.writeAligned(v.Buf[start:end], rs.filler, v.Align, padding)
} else {
if enc.border > 1 || i != len(vals)-1 {
enc.w.Write(bytes.Repeat(rs.filler, enc.maxWidths[i]))
}
}
// write newline wrap value
if rs.hasWrapping {
if l < len(v.Newlines) {
enc.w.Write(rs.wrapper)
} else {
enc.w.Write(rs.filler)
}
}
remaining = remaining || l < len(v.Newlines)
// middle separator. If border == 0, the new line indicator
// acts as the middle separator
if i != len(enc.maxWidths)-1 && enc.border >= 1 {
enc.w.Write(rs.middle)
}
}
// right
enc.w.Write(rs.right)
if !remaining {
break
}
l++
}
}
func (enc *TableEncoder) writeAligned(b, filler []byte, a Align, padding int) {
// calc padding
paddingLeft := 0
paddingRight := 0
switch a {
case AlignRight:
paddingLeft = padding
paddingRight = 0
case AlignCenter:
paddingLeft = padding / 2
paddingRight = padding/2 + padding%2
case AlignLeft:
paddingLeft = 0
paddingRight = padding
}
// add padding left
if paddingLeft > 0 {
enc.w.Write(bytes.Repeat(filler, paddingLeft))
}
// write
enc.w.Write(b)
// add padding right
if paddingRight > 0 {
enc.w.Write(bytes.Repeat(filler, paddingRight))
}
}
// rowStyle is the row style for a row, as arrays of bytes to print.
type rowStyle struct {
left, right, middle, filler, wrapper []byte
hasWrapping bool
}
// ExpandedEncoder is a buffered, lookahead expanded table encoder for result sets.
type ExpandedEncoder struct {
TableEncoder
}
// NewExpandedEncoder creates a new expanded table encoder using the provided options.
func NewExpandedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) {
tableEnc, err := NewTableEncoder(resultSet, opts...)
if err != nil {
return nil, err
}
t := tableEnc.(*TableEncoder)
t.formatter = NewEscapeFormatter()
if !t.isCustomSummary {
t.summary = nil
}
enc := &ExpandedEncoder{
TableEncoder: *t,
}
return enc, nil
}
// Encode encodes a single result set to the writer using the formatting
// options specified in the encoder.
func (enc *ExpandedEncoder) Encode(w io.Writer) error {
// reset scan count
enc.scanCount = 0
enc.w = bufio.NewWriterSize(w, 2048)
if enc.resultSet == nil {
return ErrResultSetIsNil
}
// get and check columns
clen, cols, err := buildColNames(enc.resultSet, enc.lowerColumnNames)
switch {
case err != nil:
return err
case clen == 0:
return ErrResultSetHasNoColumns
}
// setup offsets, widths
enc.offsets = make([]int, 2)
enc.maxWidths = make([]int, 2)
enc.headers, err = enc.formatter.Header(cols)
if err != nil {
return err
}
var cmd *exec.Cmd
var cmdBuf io.WriteCloser
wroteTitle := enc.skipHeader
for {
var vals [][]*Value
// buffer
vals, err = enc.nextResults()
if err != nil {
return err
}
// no more values
if len(vals) == 0 {
break
}
enc.calcWidth(vals)
if enc.pagerCmd != "" && cmd == nil &&
((enc.minPagerHeight != 0 && enc.tableHeight(vals) >= enc.minPagerHeight) ||
(enc.minPagerWidth != 0 && enc.tableWidth() >= enc.minPagerWidth)) {
cmd, cmdBuf, err = startPager(enc.pagerCmd, w)
if err != nil {
return err
}
enc.w = bufio.NewWriterSize(cmdBuf, 2048)
}
// print title if not already done
if !wroteTitle {
wroteTitle = true
if enc.title != nil && enc.title.Width != 0 {
enc.w.Write(enc.title.Buf)
enc.w.Write(enc.newline)
}
}
if err := enc.encodeVals(vals); err != nil {
return checkErr(err, cmd)
}
}
// add summary
if err := summarize(w, enc.summary, enc.scanCount); err != nil {
return err
}
if err := enc.w.Flush(); err != nil {
return checkErr(err, cmd)
}
if cmd != nil {
cmdBuf.Close()
return cmd.Wait()
}
return nil
}
func (enc *ExpandedEncoder) encodeVals(vals [][]*Value) error {
rs := enc.rowStyle(enc.lineStyle.Row)
// print buffered vals
for i := 0; i < len(vals); i++ {
enc.record(i, vals[i], rs)
if i+1%1000 == 0 {
// check error every 1k rows
if err := enc.w.Flush(); err != nil {
return err
}
}
}
// draw end border
if enc.border >= 2 && enc.scanCount != 0 {
enc.divider(enc.rowStyle(enc.lineStyle.End))
}
return nil
}
// EncodeAll encodes all result sets to the writer using the encoder settings.
func (enc *ExpandedEncoder) EncodeAll(w io.Writer) error {
if err := enc.Encode(w); err != nil {
return err
}
for enc.resultSet.NextResultSet() {
if _, err := w.Write(enc.newline); err != nil {
return err
}
if err := enc.Encode(w); err != nil {
return err
}
}
return nil
}
func (enc *ExpandedEncoder) calcWidth(vals [][]*Value) {
rs := enc.rowStyle(enc.lineStyle.Row)
offset := runewidth.StringWidth(string(rs.left))
enc.offsets[0] = offset
// first column is always the column name
for _, h := range enc.headers {
enc.maxWidths[0] = max(enc.maxWidths[0], h.MaxWidth(offset, enc.tab))
}
offset += enc.maxWidths[0]
if rs.hasWrapping && enc.border != 0 {
offset++
}
mw := runewidth.StringWidth(string(rs.middle))
offset += mw
enc.offsets[1] = offset
// second column is any value from any row but no less than the record header
enc.maxWidths[1] = max(0, len(enc.recordHeader(len(vals)-1))-enc.maxWidths[0]-mw-1)
for _, row := range vals {
for _, cell := range row {
if cell == nil {
cell = enc.empty
}
enc.maxWidths[1] = max(enc.maxWidths[1], cell.MaxWidth(offset, enc.tab))
}
}
}
// tableHeight calculates total table height.
func (enc *ExpandedEncoder) tableHeight(rows [][]*Value) int {
height := 0
if enc.title != nil && enc.title.Width != 0 {
height += strings.Count(string(enc.title.Buf), "\n")
}
for _, row := range rows {
// header
height++
for _, cell := range row {
if cell == nil {
cell = enc.empty
}
height += 1 + len(cell.Newlines)
}
}
// end border
if enc.border >= 2 {
height++
}
// scanCount at this point is not the final value but this is better than nothing
if enc.summary != nil && enc.summary[-1] != nil || enc.summary[int(enc.scanCount)] != nil {
height++
}
return height
}
func (enc *ExpandedEncoder) record(i int, vals []*Value, rs rowStyle) {
if !enc.skipHeader {
// write record header as a single record
headerRS := rs
header := enc.recordHeader(i)
if enc.border != 0 {
headerRS = enc.rowStyle(enc.lineStyle.Top)
if i != 0 {
headerRS = enc.rowStyle(enc.lineStyle.Mid)
}
}
enc.w.Write(headerRS.left)
enc.w.WriteString(header)
padding := enc.maxWidths[0] + enc.maxWidths[1] + runewidth.StringWidth(string(headerRS.middle))*2 - len(header) - 1
if padding > 0 {
enc.w.Write(bytes.Repeat(headerRS.filler, padding))
}
// write newline wrap value
enc.w.Write(headerRS.filler)
enc.w.Write(headerRS.right)
}
// write each value with column name in first col
for j, v := range vals {
if v != nil {
v.Align = AlignLeft
}
enc.row([]*Value{enc.headers[j], v}, rs)
}
}
func (enc *ExpandedEncoder) recordHeader(i int) string {
header := fmt.Sprintf("* Record %d", i+1)
if enc.border != 0 {
header = fmt.Sprintf("[ RECORD %d ]", i+1)
}
return header
}
// JSONEncoder is an unbuffered JSON encoder for result sets.
type JSONEncoder struct {
resultSet ResultSet
// newline is the record separator to use.
newline []byte
// formatter handles formatting values prior to output.
formatter Formatter
// empty is the empty value.
empty *Value
// lowerColumnNames indicates lower casing the column names when column
// names are all caps.
lowerColumnNames bool
// columnTypes is used to build column types for a result set.
columnTypes func(ResultSet, []interface{}, int) error
}
// NewJSONEncoder creates a new JSON encoder using the provided options.
func NewJSONEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) {
enc := &JSONEncoder{
resultSet: resultSet,
newline: newline,
formatter: NewEscapeFormatter(WithIsJSON(true)),
empty: &Value{
Buf: []byte("null"),
Tabs: make([][][2]int, 1),
Raw: true,
},
}
for _, o := range opts {
if err := o.apply(enc); err != nil {
return nil, err
}
}
return enc, nil
}
// Encode encodes a single result set to the writer using the formatting
// options specified in the encoder.
func (enc *JSONEncoder) Encode(w io.Writer) error {
if enc.resultSet == nil {
return ErrResultSetIsNil
}
var i int
var (
start = []byte{'['}
end = []byte{']'}
open = []byte{'{'}
cls = []byte{'}'}
q = []byte{'"'}
cma = []byte{','}
)
// get and check columns
clen, cols, err := buildColNames(enc.resultSet, enc.lowerColumnNames)
switch {
case err != nil:
return err
case clen == 0:
return ErrResultSetHasNoColumns
}
cb := make([][]byte, clen)
for i = 0; i < clen; i++ {
if cb[i], err = json.Marshal(cols[i]); err != nil {
return err
}
cb[i] = append(cb[i], ':')
}
// set up storage for results
r, err := buildColumnTypes(enc.resultSet, clen, enc.columnTypes)
if err != nil {
return err
}
// start
if _, err = w.Write(start); err != nil {
return err
}
// process
var v *Value
var vals []*Value
var count int64
for enc.resultSet.Next() {
if count != 0 {
if _, err = w.Write(cma); err != nil {
return err
}
}
vals, err = scanAndFormat(enc.resultSet, r, enc.formatter, &count)
if err != nil {
return err
}
if _, err = w.Write(open); err != nil {
return err
}
for i = 0; i < clen; i++ {
v = vals[i]
if v == nil {
v = enc.empty
}
// write "column":
if _, err = w.Write(cb[i]); err != nil {
return err
}
// if raw, write the exact value
if v.Raw {
if _, err = w.Write(v.Buf); err != nil {
return err
}
} else {
if _, err = w.Write(q); err != nil {
return err
}
if _, err = w.Write(v.Buf); err != nil {
return err
}
if _, err = w.Write(q); err != nil {
return err
}
}
if i != clen-1 {
if _, err = w.Write(cma); err != nil {
return err
}
}
}
if _, err = w.Write(cls); err != nil {
return err
}
}
err = enc.resultSet.Err()
if err != nil {
return err
}
// end
_, err = w.Write(end)
return err
}
// EncodeAll encodes all result sets to the writer using the encoder settings.
func (enc *JSONEncoder) EncodeAll(w io.Writer) error {
if err := enc.Encode(w); err != nil {
return err
}
for enc.resultSet.NextResultSet() {
if _, err := w.Write([]byte{','}); err != nil {
return err
}
if _, err := w.Write(enc.newline); err != nil {
return err
}
if err := enc.Encode(w); err != nil {
return err
}
}
if _, err := w.Write(enc.newline); err != nil {
return err
}
return nil
}
// UnalignedEncoder is an unbuffered, unaligned encoder for result sets.
//
// Provides a way of encoding unaligned result sets in formats such as
// comma-separated value (CSV) or tab-separated value (TSV) files.
//
// By default uses a field separator of '|', no quote separator, and record
// separator using the default newline for the platfom ("\r\n" on Windows, "\n"
// otherwise).
type UnalignedEncoder struct {
// resultSet is the result set to encode.
resultSet ResultSet
// sep is the separator to use.
sep rune
// quote is the quote to use.
quote rune
// newline is the record separator to use.
newline []byte
// formatter handles formatting values prior to output.
formatter Formatter
// skipHeader disables writing header.
skipHeader bool
// summary is the summary map.
summary map[int]func(io.Writer, int) (int, error)
// empty is the empty value.
empty *Value
// lowerColumnNames indicates lower casing the column names when column
// names are all caps.
lowerColumnNames bool
// columnTypes is used to build column types for a result set.
columnTypes func(ResultSet, []interface{}, int) error
}
// NewUnalignedEncoder creates a new unaligned encoder using the provided
// options.
func NewUnalignedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) {
sep, quote := rune('|'), rune(0)
enc := &UnalignedEncoder{
resultSet: resultSet,
sep: sep,
quote: quote,
newline: newline,
formatter: NewEscapeFormatter(WithIsRaw(true, sep, quote)),
summary: DefaultTableSummary(),
empty: &Value{
Tabs: make([][][2]int, 1),
},
}
for _, o := range opts {
if err := o.apply(enc); err != nil {
return nil, err
}
}
return enc, nil