| 1 |
package tblfmt |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
"encoding/json/jsontext" |
| 7 |
json "encoding/json/v2" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"io" |
| 11 |
"os/exec" |
| 12 |
"strings" |
| 13 |
"syscall" |
| 14 |
|
| 15 |
runewidth "github.com/mattn/go-runewidth" |
| 16 |
) |
| 17 |
|
| 18 |
// TableEncoder is a buffered, lookahead table encoder for result sets. |
| 19 |
type TableEncoder struct { |
| 20 |
// ResultSet is the result set to encode. |
| 21 |
resultSet ResultSet |
| 22 |
// count is the number of rows to scan ahead by (buffer), up to count, in |
| 23 |
// order to determine maximum column widths returned by the encoder's |
| 24 |
// formatter. |
| 25 |
// |
| 26 |
// Note: when 0 all rows will be scanned (buffered) prior to encoding the |
| 27 |
// table. |
| 28 |
count int |
| 29 |
// tab is the tab width. |
| 30 |
tab int |
| 31 |
// newline is the record separator to use. |
| 32 |
newline []byte |
| 33 |
// border is the display border size. |
| 34 |
border int |
| 35 |
// inline toggles writing the column header names inline with the top line. |
| 36 |
inline bool |
| 37 |
// lineStyle is the table line style. |
| 38 |
lineStyle LineStyle |
| 39 |
// formatter handles formatting values prior to output. |
| 40 |
formatter Formatter |
| 41 |
// skipHeader disables writing header. |
| 42 |
skipHeader bool |
| 43 |
// summary is the summary map. |
| 44 |
summary Summary |
| 45 |
// isCustomSummary when summary has been set via options |
| 46 |
isCustomSummary bool |
| 47 |
// title is the title value. |
| 48 |
title *Value |
| 49 |
// empty is the empty value. |
| 50 |
empty *Value |
| 51 |
// headers contains formatted column names. |
| 52 |
headers []*Value |
| 53 |
// offsets are the column offsets. |
| 54 |
offsets []int |
| 55 |
// widths are the user-supplied column widths. |
| 56 |
widths []int |
| 57 |
// maxWidths are calculated max column widths. Max widths are at least as |
| 58 |
// wide as user-supplied widths |
| 59 |
maxWidths []int |
| 60 |
// aligns are the calculated column alignments, followed by a column's null |
| 61 |
// values, which have no type of their own to align by. |
| 62 |
aligns []Align |
| 63 |
// minExpandWidth of the table required to switch to the ExpandedEncoder |
| 64 |
// zero disables switching |
| 65 |
minExpandWidth int |
| 66 |
// minPagerWidth of the table required to redirect output to the pager, |
| 67 |
// zero disables pager |
| 68 |
minPagerWidth int |
| 69 |
// minPagerHeight of the table required to redirect output to the pager, |
| 70 |
// zero disables pager |
| 71 |
minPagerHeight int |
| 72 |
// pagerCmd is the pager command to run and redirect output to |
| 73 |
// if height or width is greater than minPagerHeight and minPagerWidth, |
| 74 |
pagerCmd string |
| 75 |
// scanCount is the number of scanned results in the result set. |
| 76 |
scanCount int |
| 77 |
// headerTransformer is the column header transformer. |
| 78 |
headerTransformer Transformer |
| 79 |
// columnTypes is used to build column types for a result set. |
| 80 |
columnTypes func(ResultSet, []any, int) error |
| 81 |
// w is the undelying writer |
| 82 |
w *bufio.Writer |
| 83 |
} |
| 84 |
|
| 85 |
// NewTableEncoder creates a new table encoder using the provided options. |
| 86 |
// |
| 87 |
// The table encoder has a default value of border 1, and a tab width of 8. |
| 88 |
func NewTableEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 89 |
enc := &TableEncoder{ |
| 90 |
resultSet: resultSet, |
| 91 |
newline: newline, |
| 92 |
border: 1, |
| 93 |
tab: 8, |
| 94 |
lineStyle: ASCIILineStyle(), |
| 95 |
formatter: NewEscapeFormatter(WithHeaderAlign(AlignCenter)), |
| 96 |
summary: DefaultTableSummary(), |
| 97 |
empty: &Value{ |
| 98 |
Tabs: make([][][2]int, 1), |
| 99 |
}, |
| 100 |
} |
| 101 |
// apply options |
| 102 |
for _, o := range opts { |
| 103 |
if err := o.apply(enc); err != nil { |
| 104 |
return nil, err |
| 105 |
} |
| 106 |
} |
| 107 |
// check linestyle runes |
| 108 |
// TODO: this check should be removed |
| 109 |
for _, l := range [][4]rune{ |
| 110 |
enc.lineStyle.Top, |
| 111 |
enc.lineStyle.Mid, |
| 112 |
enc.lineStyle.Row, |
| 113 |
enc.lineStyle.Wrap, |
| 114 |
enc.lineStyle.End, |
| 115 |
} { |
| 116 |
for _, r := range l { |
| 117 |
if r != 0 && runewidth.RuneWidth(r) != 1 { |
| 118 |
return nil, ErrInvalidLineStyle |
| 119 |
} |
| 120 |
} |
| 121 |
} |
| 122 |
return enc, nil |
| 123 |
} |
| 124 |
|
| 125 |
// Encode encodes a single result set to the writer using the formatting |
| 126 |
// options specified in the encoder. |
| 127 |
func (enc *TableEncoder) Encode(w io.Writer) error { |
| 128 |
// reset scan count |
| 129 |
enc.scanCount = 0 |
| 130 |
enc.w = bufio.NewWriterSize(w, 2048) |
| 131 |
if enc.resultSet == nil { |
| 132 |
return ErrResultSetIsNil |
| 133 |
} |
| 134 |
// get and check columns |
| 135 |
clen, cols, err := buildColNames(enc.resultSet, enc.headerTransformer) |
| 136 |
switch { |
| 137 |
case err != nil: |
| 138 |
return err |
| 139 |
case clen == 0: |
| 140 |
return ErrResultSetHasNoColumns |
| 141 |
} |
| 142 |
// setup offsets, widths |
| 143 |
enc.offsets = make([]int, clen) |
| 144 |
wroteHeader := enc.skipHeader |
| 145 |
// default to user-supplied widths |
| 146 |
enc.maxWidths = make([]int, clen) |
| 147 |
enc.aligns = make([]Align, clen) |
| 148 |
copy(enc.maxWidths, enc.widths) |
| 149 |
enc.headers, err = enc.formatter.Header(cols) |
| 150 |
if err != nil { |
| 151 |
return err |
| 152 |
} |
| 153 |
var cmd *exec.Cmd |
| 154 |
var cmdBuf io.WriteCloser |
| 155 |
for { |
| 156 |
var vals [][]*Value |
| 157 |
// buffer |
| 158 |
vals, err = enc.nextResults() |
| 159 |
if err != nil { |
| 160 |
return err |
| 161 |
} |
| 162 |
// no more values |
| 163 |
if len(vals) == 0 { |
| 164 |
break |
| 165 |
} |
| 166 |
enc.calcWidth(vals) |
| 167 |
if enc.minExpandWidth != 0 && enc.tableWidth() >= enc.minExpandWidth { |
| 168 |
t := *enc |
| 169 |
t.formatter = NewEscapeFormatter() |
| 170 |
exp := ExpandedEncoder{ |
| 171 |
TableEncoder: t, |
| 172 |
} |
| 173 |
exp.offsets = make([]int, 2) |
| 174 |
exp.maxWidths = make([]int, 2) |
| 175 |
exp.aligns = make([]Align, 2) |
| 176 |
exp.headers, err = exp.formatter.Header(cols) |
| 177 |
if err != nil { |
| 178 |
return err |
| 179 |
} |
| 180 |
exp.calcWidth(vals) |
| 181 |
if exp.pagerCmd != "" && cmd == nil && |
| 182 |
((exp.minPagerHeight != 0 && exp.tableHeight(vals) >= exp.minPagerHeight) || |
| 183 |
(exp.minPagerWidth != 0 && exp.tableWidth() >= exp.minPagerWidth)) { |
| 184 |
cmd, cmdBuf, err = startPager(exp.pagerCmd, w) |
| 185 |
if err != nil { |
| 186 |
return err |
| 187 |
} |
| 188 |
exp.w = bufio.NewWriterSize(cmdBuf, 2048) |
| 189 |
} |
| 190 |
if err := exp.encodeVals(vals); err != nil { |
| 191 |
return checkErr(err, cmd) |
| 192 |
} |
| 193 |
continue |
| 194 |
} |
| 195 |
if enc.pagerCmd != "" && cmd == nil && |
| 196 |
((enc.minPagerHeight != 0 && enc.tableHeight(vals) >= enc.minPagerHeight) || |
| 197 |
(enc.minPagerWidth != 0 && enc.tableWidth() >= enc.minPagerWidth)) { |
| 198 |
cmd, cmdBuf, err = startPager(enc.pagerCmd, w) |
| 199 |
if err != nil { |
| 200 |
return err |
| 201 |
} |
| 202 |
enc.w = bufio.NewWriterSize(cmdBuf, 2048) |
| 203 |
} |
| 204 |
// print header if not already done |
| 205 |
if !wroteHeader { |
| 206 |
wroteHeader = true |
| 207 |
enc.header() |
| 208 |
} |
| 209 |
if err := enc.encodeVals(vals); err != nil { |
| 210 |
return checkErr(err, cmd) |
| 211 |
} |
| 212 |
// draw end border |
| 213 |
if enc.border >= 2 { |
| 214 |
enc.divider(enc.rowStyle(enc.lineStyle.End)) |
| 215 |
} |
| 216 |
} |
| 217 |
// add summary |
| 218 |
if err := summarize(enc.w, enc.summary, enc.scanCount); err != nil { |
| 219 |
return err |
| 220 |
} |
| 221 |
if err := enc.w.Flush(); err != nil { |
| 222 |
return checkErr(err, cmd) |
| 223 |
} |
| 224 |
if cmd != nil { |
| 225 |
_ = cmdBuf.Close() |
| 226 |
return cmd.Wait() |
| 227 |
} |
| 228 |
return nil |
| 229 |
} |
| 230 |
|
| 231 |
func (enc *TableEncoder) encodeVals(vals [][]*Value) error { |
| 232 |
rs := enc.rowStyle(enc.lineStyle.Row) |
| 233 |
// print buffered vals |
| 234 |
for i := range vals { |
| 235 |
enc.row(vals[i], rs) |
| 236 |
if i+1%1000 == 0 { |
| 237 |
// check error every 1k rows |
| 238 |
if err := enc.w.Flush(); err != nil { |
| 239 |
return err |
| 240 |
} |
| 241 |
} |
| 242 |
} |
| 243 |
return nil |
| 244 |
} |
| 245 |
|
| 246 |
// EncodeAll encodes all result sets to the writer using the encoder settings. |
| 247 |
func (enc *TableEncoder) EncodeAll(w io.Writer) error { |
| 248 |
if err := enc.Encode(w); err != nil { |
| 249 |
return err |
| 250 |
} |
| 251 |
for enc.resultSet.NextResultSet() { |
| 252 |
if _, err := w.Write(enc.newline); err != nil { |
| 253 |
return err |
| 254 |
} |
| 255 |
if err := enc.Encode(w); err != nil { |
| 256 |
return err |
| 257 |
} |
| 258 |
} |
| 259 |
return nil |
| 260 |
} |
| 261 |
|
| 262 |
// nextResults reads the next enc.count values, or all values if enc.count = 0. |
| 263 |
func (enc *TableEncoder) nextResults() ([][]*Value, error) { |
| 264 |
var vals [][]*Value |
| 265 |
if enc.count != 0 { |
| 266 |
vals = make([][]*Value, 0, enc.count) |
| 267 |
} |
| 268 |
// read to count (or all) |
| 269 |
var i int |
| 270 |
var r []any |
| 271 |
for enc.resultSet.Next() { |
| 272 |
if i == 0 { |
| 273 |
// set up storage for results |
| 274 |
var err error |
| 275 |
r, err = buildColumnTypes(enc.resultSet, len(enc.headers), enc.columnTypes) |
| 276 |
if err != nil { |
| 277 |
return nil, err |
| 278 |
} |
| 279 |
} |
| 280 |
v, err := scanAndFormat(enc.resultSet, r, enc.formatter, &enc.scanCount) |
| 281 |
if err != nil { |
| 282 |
return vals, err |
| 283 |
} |
| 284 |
vals, i = append(vals, v), i+1 |
| 285 |
// read by batches of enc.count rows |
| 286 |
if enc.count != 0 && i%enc.count == 0 { |
| 287 |
break |
| 288 |
} |
| 289 |
} |
| 290 |
return vals, enc.resultSet.Err() |
| 291 |
} |
| 292 |
|
| 293 |
func (enc *TableEncoder) calcWidth(vals [][]*Value) { |
| 294 |
// calc offsets and widths for this batch of rows |
| 295 |
var offset int |
| 296 |
rs := enc.rowStyle(enc.lineStyle.Row) |
| 297 |
offset += runewidth.StringWidth(string(rs.left)) |
| 298 |
for i, h := range enc.headers { |
| 299 |
if i != 0 { |
| 300 |
offset += runewidth.StringWidth(string(rs.middle)) |
| 301 |
} |
| 302 |
// store offset |
| 303 |
enc.offsets[i] = offset |
| 304 |
// header's widths are the minimum |
| 305 |
enc.maxWidths[i] = max(enc.maxWidths[i], h.MaxWidth(offset, enc.tab)) |
| 306 |
// from top to bottom, find max column width |
| 307 |
for j := range vals { |
| 308 |
cell := vals[j][i] |
| 309 |
if cell == nil { |
| 310 |
cell = enc.empty |
| 311 |
} |
| 312 |
enc.maxWidths[i] = max(enc.maxWidths[i], cell.MaxWidth(offset, enc.tab)) |
| 313 |
} |
| 314 |
// a null cell has no type of its own to align by, so it follows the |
| 315 |
// column, the way psql aligns the null string by the column's type. A |
| 316 |
// batch with nothing to learn from keeps what an earlier one found. |
| 317 |
if align, ok := columnAlign(vals, i); ok { |
| 318 |
enc.aligns[i] = align |
| 319 |
} |
| 320 |
// add column width, and one space for newline indicator |
| 321 |
offset += enc.maxWidths[i] |
| 322 |
if rs.hasWrapping && enc.border != 0 { |
| 323 |
offset++ |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
func (enc *TableEncoder) header() { |
| 329 |
rs := enc.rowStyle(enc.lineStyle.Row) |
| 330 |
if enc.title != nil && enc.title.Width != 0 { |
| 331 |
maxWidth := ((enc.tableWidth() - enc.title.Width) / 2) + enc.title.Width |
| 332 |
enc.writeAligned(enc.title.Buf, rs.filler, AlignRight, maxWidth-enc.title.Width) |
| 333 |
_, _ = enc.w.Write(enc.newline) |
| 334 |
} |
| 335 |
// draw top border |
| 336 |
if enc.border >= 2 && !enc.inline { |
| 337 |
enc.divider(enc.rowStyle(enc.lineStyle.Top)) |
| 338 |
} |
| 339 |
// draw the header row with top border style |
| 340 |
if enc.inline { |
| 341 |
rs = enc.rowStyle(enc.lineStyle.Top) |
| 342 |
} |
| 343 |
// write header |
| 344 |
enc.row(enc.headers, rs) |
| 345 |
if !enc.inline { |
| 346 |
// draw mid divider |
| 347 |
enc.divider(enc.rowStyle(enc.lineStyle.Mid)) |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
// rowStyle returns the left, right and middle borders. It also provides the |
| 352 |
// filler string, and indicates if this style uses a wrapping indicator. |
| 353 |
func (enc *TableEncoder) rowStyle(r [4]rune) rowStyle { |
| 354 |
var left, right, middle, spacer, filler string |
| 355 |
spacer = strings.Repeat(string(r[1]), runewidth.RuneWidth(enc.lineStyle.Row[1])) |
| 356 |
filler = string(r[1]) |
| 357 |
// compact output, r[1] is set to \0 |
| 358 |
if r[1] == 0 { |
| 359 |
filler = " " |
| 360 |
} |
| 361 |
// outside borders |
| 362 |
if enc.border > 1 { |
| 363 |
left = string(r[0]) |
| 364 |
right = string(r[3]) |
| 365 |
} |
| 366 |
// initial spacer when borders are set |
| 367 |
if enc.border > 0 { |
| 368 |
left += spacer |
| 369 |
} |
| 370 |
middle = " " |
| 371 |
if enc.border >= 1 { // inside border |
| 372 |
middle = string(r[2]) + spacer |
| 373 |
} |
| 374 |
return rowStyle{ |
| 375 |
left: []byte(left), |
| 376 |
wrapper: []byte(string(enc.lineStyle.Wrap[1])), |
| 377 |
middle: []byte(middle), |
| 378 |
right: []byte(right + string(enc.newline)), |
| 379 |
filler: []byte(filler), |
| 380 |
hasWrapping: runewidth.RuneWidth(enc.lineStyle.Row[1]) > 0, |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
// divider draws a divider. |
| 385 |
func (enc *TableEncoder) divider(rs rowStyle) { |
| 386 |
// left |
| 387 |
_, _ = enc.w.Write(rs.left) |
| 388 |
for i, width := range enc.maxWidths { |
| 389 |
// column |
| 390 |
_, _ = enc.w.Write(bytes.Repeat(rs.filler, width)) |
| 391 |
// line feed indicator |
| 392 |
if rs.hasWrapping && enc.border >= 1 { |
| 393 |
_, _ = enc.w.Write(rs.filler) |
| 394 |
} |
| 395 |
// middle separator |
| 396 |
if i != len(enc.maxWidths)-1 { |
| 397 |
_, _ = enc.w.Write(rs.middle) |
| 398 |
} |
| 399 |
} |
| 400 |
// right |
| 401 |
_, _ = enc.w.Write(rs.right) |
| 402 |
} |
| 403 |
|
| 404 |
// tableWidth calculates total table width. |
| 405 |
func (enc *TableEncoder) tableWidth() int { |
| 406 |
rs := enc.rowStyle(enc.lineStyle.Mid) |
| 407 |
width := runewidth.StringWidth(string(rs.left)) + runewidth.StringWidth(string(rs.right)) |
| 408 |
for i, w := range enc.maxWidths { |
| 409 |
width += w |
| 410 |
if rs.hasWrapping && enc.border >= 1 { |
| 411 |
width++ |
| 412 |
} |
| 413 |
if i != len(enc.maxWidths)-1 { |
| 414 |
width += runewidth.StringWidth(string(rs.middle)) |
| 415 |
} |
| 416 |
} |
| 417 |
return width |
| 418 |
} |
| 419 |
|
| 420 |
// tableHeight calculates total table height. |
| 421 |
func (enc *TableEncoder) tableHeight(rows [][]*Value) int { |
| 422 |
height := 0 |
| 423 |
if enc.title != nil && enc.title.Width != 0 { |
| 424 |
height += strings.Count(string(enc.title.Buf), "\n") |
| 425 |
} |
| 426 |
// top border |
| 427 |
if enc.border >= 2 && !enc.inline { |
| 428 |
height++ |
| 429 |
} |
| 430 |
// header |
| 431 |
height++ |
| 432 |
// mid divider |
| 433 |
if enc.inline { |
| 434 |
height++ |
| 435 |
} |
| 436 |
for _, row := range rows { |
| 437 |
largest := 1 |
| 438 |
for _, cell := range row { |
| 439 |
if cell == nil { |
| 440 |
cell = enc.empty |
| 441 |
} |
| 442 |
if len(cell.Newlines) > largest { |
| 443 |
largest = len(cell.Newlines) |
| 444 |
} |
| 445 |
} |
| 446 |
height += largest |
| 447 |
} |
| 448 |
// end border |
| 449 |
if enc.border >= 2 { |
| 450 |
height++ |
| 451 |
} |
| 452 |
// scanCount at this point is not the final value but this is better than nothing |
| 453 |
if enc.summary != nil && enc.summary[-1] != nil || enc.summary[enc.scanCount] != nil { |
| 454 |
height++ |
| 455 |
} |
| 456 |
return height |
| 457 |
} |
| 458 |
|
| 459 |
// row draws the a table row. |
| 460 |
func (enc *TableEncoder) row(vals []*Value, rs rowStyle) { |
| 461 |
var l int |
| 462 |
for { |
| 463 |
// left |
| 464 |
_, _ = enc.w.Write(rs.left) |
| 465 |
var remaining bool |
| 466 |
for i, v := range vals { |
| 467 |
align := enc.aligns[i] |
| 468 |
if v == nil { |
| 469 |
v = enc.empty |
| 470 |
} else { |
| 471 |
align = v.Align |
| 472 |
} |
| 473 |
// write value |
| 474 |
if l <= len(v.Newlines) { |
| 475 |
// determine start, end, width |
| 476 |
start, end, width := 0, len(v.Buf), 0 |
| 477 |
if l > 0 { |
| 478 |
start = v.Newlines[l-1][0] + 1 |
| 479 |
} |
| 480 |
if l < len(v.Newlines) { |
| 481 |
end = v.Newlines[l][0] |
| 482 |
width += v.Newlines[l][1] |
| 483 |
} |
| 484 |
if len(v.Tabs) != 0 && len(v.Tabs[l]) != 0 { |
| 485 |
width += tabwidth(v.Tabs[l], enc.offsets[i], enc.tab) |
| 486 |
} |
| 487 |
if l == len(v.Newlines) { |
| 488 |
width += v.Width |
| 489 |
} |
| 490 |
padding := enc.maxWidths[i] - width |
| 491 |
// no padding for last cell if no border and aligned left |
| 492 |
if enc.border <= 1 && align == AlignLeft && i == len(vals)-1 && (!rs.hasWrapping || l >= len(v.Newlines)) { |
| 493 |
padding = 0 |
| 494 |
} |
| 495 |
enc.writeAligned(v.Buf[start:end], rs.filler, align, padding) |
| 496 |
} else if enc.border > 1 || i != len(vals)-1 { |
| 497 |
_, _ = enc.w.Write(bytes.Repeat(rs.filler, enc.maxWidths[i])) |
| 498 |
} |
| 499 |
// write newline wrap value |
| 500 |
if rs.hasWrapping { |
| 501 |
if l < len(v.Newlines) { |
| 502 |
_, _ = enc.w.Write(rs.wrapper) |
| 503 |
} else { |
| 504 |
_, _ = enc.w.Write(rs.filler) |
| 505 |
} |
| 506 |
} |
| 507 |
remaining = remaining || l < len(v.Newlines) |
| 508 |
// middle separator. If border == 0, the new line indicator |
| 509 |
// acts as the middle separator |
| 510 |
if i != len(enc.maxWidths)-1 && enc.border >= 1 { |
| 511 |
_, _ = enc.w.Write(rs.middle) |
| 512 |
} |
| 513 |
} |
| 514 |
// right |
| 515 |
_, _ = enc.w.Write(rs.right) |
| 516 |
if !remaining { |
| 517 |
break |
| 518 |
} |
| 519 |
l++ |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
func (enc *TableEncoder) writeAligned(b, filler []byte, a Align, padding int) { |
| 524 |
// calc padding |
| 525 |
paddingLeft := 0 |
| 526 |
paddingRight := 0 |
| 527 |
switch a { |
| 528 |
case AlignRight: |
| 529 |
paddingLeft = padding |
| 530 |
paddingRight = 0 |
| 531 |
case AlignCenter: |
| 532 |
paddingLeft = padding / 2 |
| 533 |
paddingRight = padding/2 + padding%2 |
| 534 |
case AlignLeft: |
| 535 |
paddingLeft = 0 |
| 536 |
paddingRight = padding |
| 537 |
} |
| 538 |
// add padding left |
| 539 |
if paddingLeft > 0 { |
| 540 |
_, _ = enc.w.Write(bytes.Repeat(filler, paddingLeft)) |
| 541 |
} |
| 542 |
// write |
| 543 |
_, _ = enc.w.Write(b) |
| 544 |
// add padding right |
| 545 |
if paddingRight > 0 { |
| 546 |
_, _ = enc.w.Write(bytes.Repeat(filler, paddingRight)) |
| 547 |
} |
| 548 |
} |
| 549 |
|
| 550 |
// rowStyle is the row style for a row, as arrays of bytes to print. |
| 551 |
type rowStyle struct { |
| 552 |
left, right, middle, filler, wrapper []byte |
| 553 |
hasWrapping bool |
| 554 |
} |
| 555 |
|
| 556 |
// ExpandedEncoder is a buffered, lookahead expanded table encoder for result sets. |
| 557 |
type ExpandedEncoder struct { |
| 558 |
TableEncoder |
| 559 |
} |
| 560 |
|
| 561 |
// NewExpandedEncoder creates a new expanded table encoder using the provided options. |
| 562 |
func NewExpandedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 563 |
tableEnc, err := NewTableEncoder(resultSet, opts...) |
| 564 |
if err != nil { |
| 565 |
return nil, err |
| 566 |
} |
| 567 |
t := tableEnc.(*TableEncoder) |
| 568 |
t.formatter = NewEscapeFormatter() |
| 569 |
if !t.isCustomSummary { |
| 570 |
t.summary = nil |
| 571 |
} |
| 572 |
enc := &ExpandedEncoder{ |
| 573 |
TableEncoder: *t, |
| 574 |
} |
| 575 |
return enc, nil |
| 576 |
} |
| 577 |
|
| 578 |
// Encode encodes a single result set to the writer using the formatting |
| 579 |
// options specified in the encoder. |
| 580 |
func (enc *ExpandedEncoder) Encode(w io.Writer) error { |
| 581 |
// reset scan count |
| 582 |
enc.scanCount = 0 |
| 583 |
enc.w = bufio.NewWriterSize(w, 2048) |
| 584 |
if enc.resultSet == nil { |
| 585 |
return ErrResultSetIsNil |
| 586 |
} |
| 587 |
// get and check columns |
| 588 |
clen, cols, err := buildColNames(enc.resultSet, enc.headerTransformer) |
| 589 |
switch { |
| 590 |
case err != nil: |
| 591 |
return err |
| 592 |
case clen == 0: |
| 593 |
return ErrResultSetHasNoColumns |
| 594 |
} |
| 595 |
// setup offsets, widths |
| 596 |
enc.offsets = make([]int, 2) |
| 597 |
enc.maxWidths = make([]int, 2) |
| 598 |
enc.aligns = make([]Align, 2) |
| 599 |
enc.headers, err = enc.formatter.Header(cols) |
| 600 |
if err != nil { |
| 601 |
return err |
| 602 |
} |
| 603 |
var cmd *exec.Cmd |
| 604 |
var cmdBuf io.WriteCloser |
| 605 |
wroteTitle := enc.skipHeader |
| 606 |
for { |
| 607 |
var vals [][]*Value |
| 608 |
// buffer |
| 609 |
vals, err = enc.nextResults() |
| 610 |
if err != nil { |
| 611 |
return err |
| 612 |
} |
| 613 |
// no more values |
| 614 |
if len(vals) == 0 { |
| 615 |
break |
| 616 |
} |
| 617 |
enc.calcWidth(vals) |
| 618 |
if enc.pagerCmd != "" && cmd == nil && |
| 619 |
((enc.minPagerHeight != 0 && enc.tableHeight(vals) >= enc.minPagerHeight) || |
| 620 |
(enc.minPagerWidth != 0 && enc.tableWidth() >= enc.minPagerWidth)) { |
| 621 |
cmd, cmdBuf, err = startPager(enc.pagerCmd, w) |
| 622 |
if err != nil { |
| 623 |
return err |
| 624 |
} |
| 625 |
enc.w = bufio.NewWriterSize(cmdBuf, 2048) |
| 626 |
} |
| 627 |
// print title if not already done |
| 628 |
if !wroteTitle { |
| 629 |
wroteTitle = true |
| 630 |
if enc.title != nil && enc.title.Width != 0 { |
| 631 |
_, _ = enc.w.Write(enc.title.Buf) |
| 632 |
_, _ = enc.w.Write(enc.newline) |
| 633 |
} |
| 634 |
} |
| 635 |
if err := enc.encodeVals(vals); err != nil { |
| 636 |
return checkErr(err, cmd) |
| 637 |
} |
| 638 |
} |
| 639 |
// add summary |
| 640 |
if err := summarize(w, enc.summary, enc.scanCount); err != nil { |
| 641 |
return err |
| 642 |
} |
| 643 |
if err := enc.w.Flush(); err != nil { |
| 644 |
return checkErr(err, cmd) |
| 645 |
} |
| 646 |
if cmd != nil { |
| 647 |
_ = cmdBuf.Close() |
| 648 |
return cmd.Wait() |
| 649 |
} |
| 650 |
return nil |
| 651 |
} |
| 652 |
|
| 653 |
func (enc *ExpandedEncoder) encodeVals(vals [][]*Value) error { |
| 654 |
rs := enc.rowStyle(enc.lineStyle.Row) |
| 655 |
// print buffered vals |
| 656 |
for i := range vals { |
| 657 |
enc.record(i, vals[i], rs) |
| 658 |
if i+1%1000 == 0 { |
| 659 |
// check error every 1k rows |
| 660 |
if err := enc.w.Flush(); err != nil { |
| 661 |
return err |
| 662 |
} |
| 663 |
} |
| 664 |
} |
| 665 |
// draw end border |
| 666 |
if enc.border >= 2 && enc.scanCount != 0 { |
| 667 |
enc.divider(enc.rowStyle(enc.lineStyle.End)) |
| 668 |
} |
| 669 |
return nil |
| 670 |
} |
| 671 |
|
| 672 |
// EncodeAll encodes all result sets to the writer using the encoder settings. |
| 673 |
func (enc *ExpandedEncoder) EncodeAll(w io.Writer) error { |
| 674 |
if err := enc.Encode(w); err != nil { |
| 675 |
return err |
| 676 |
} |
| 677 |
for enc.resultSet.NextResultSet() { |
| 678 |
if _, err := w.Write(enc.newline); err != nil { |
| 679 |
return err |
| 680 |
} |
| 681 |
if err := enc.Encode(w); err != nil { |
| 682 |
return err |
| 683 |
} |
| 684 |
} |
| 685 |
return nil |
| 686 |
} |
| 687 |
|
| 688 |
func (enc *ExpandedEncoder) calcWidth(vals [][]*Value) { |
| 689 |
rs := enc.rowStyle(enc.lineStyle.Row) |
| 690 |
offset := runewidth.StringWidth(string(rs.left)) |
| 691 |
enc.offsets[0] = offset |
| 692 |
// first column is always the column name |
| 693 |
for _, h := range enc.headers { |
| 694 |
enc.maxWidths[0] = max(enc.maxWidths[0], h.MaxWidth(offset, enc.tab)) |
| 695 |
} |
| 696 |
offset += enc.maxWidths[0] |
| 697 |
if rs.hasWrapping && enc.border != 0 { |
| 698 |
offset++ |
| 699 |
} |
| 700 |
mw := runewidth.StringWidth(string(rs.middle)) |
| 701 |
offset += mw |
| 702 |
enc.offsets[1] = offset |
| 703 |
// second column is any value from any row but no less than the record header |
| 704 |
enc.maxWidths[1] = max(0, len(enc.recordHeader(len(vals)-1))-enc.maxWidths[0]-mw-1) |
| 705 |
for _, row := range vals { |
| 706 |
for _, cell := range row { |
| 707 |
if cell == nil { |
| 708 |
cell = enc.empty |
| 709 |
} |
| 710 |
enc.maxWidths[1] = max(enc.maxWidths[1], cell.MaxWidth(offset, enc.tab)) |
| 711 |
} |
| 712 |
} |
| 713 |
} |
| 714 |
|
| 715 |
// tableHeight calculates total table height. |
| 716 |
func (enc *ExpandedEncoder) tableHeight(rows [][]*Value) int { |
| 717 |
height := 0 |
| 718 |
if enc.title != nil && enc.title.Width != 0 { |
| 719 |
height += strings.Count(string(enc.title.Buf), "\n") |
| 720 |
} |
| 721 |
for _, row := range rows { |
| 722 |
// header |
| 723 |
height++ |
| 724 |
for _, cell := range row { |
| 725 |
if cell == nil { |
| 726 |
cell = enc.empty |
| 727 |
} |
| 728 |
height += 1 + len(cell.Newlines) |
| 729 |
} |
| 730 |
} |
| 731 |
// end border |
| 732 |
if enc.border >= 2 { |
| 733 |
height++ |
| 734 |
} |
| 735 |
// scanCount at this point is not the final value but this is better than nothing |
| 736 |
if enc.summary != nil && enc.summary[-1] != nil || enc.summary[enc.scanCount] != nil { |
| 737 |
height++ |
| 738 |
} |
| 739 |
return height |
| 740 |
} |
| 741 |
|
| 742 |
func (enc *ExpandedEncoder) record(i int, vals []*Value, rs rowStyle) { |
| 743 |
if !enc.skipHeader { |
| 744 |
// write record header as a single record |
| 745 |
headerRS := rs |
| 746 |
header := enc.recordHeader(i) |
| 747 |
if enc.border != 0 { |
| 748 |
headerRS = enc.rowStyle(enc.lineStyle.Top) |
| 749 |
if i != 0 { |
| 750 |
headerRS = enc.rowStyle(enc.lineStyle.Mid) |
| 751 |
} |
| 752 |
} |
| 753 |
_, _ = enc.w.Write(headerRS.left) |
| 754 |
_, _ = enc.w.WriteString(header) |
| 755 |
padding := enc.maxWidths[0] + enc.maxWidths[1] + runewidth.StringWidth(string(headerRS.middle))*2 - len(header) - 1 |
| 756 |
if padding > 0 { |
| 757 |
_, _ = enc.w.Write(bytes.Repeat(headerRS.filler, padding)) |
| 758 |
} |
| 759 |
// write newline wrap value |
| 760 |
_, _ = enc.w.Write(headerRS.filler) |
| 761 |
_, _ = enc.w.Write(headerRS.right) |
| 762 |
} |
| 763 |
// write each value with column name in first col |
| 764 |
for j, v := range vals { |
| 765 |
if v != nil { |
| 766 |
v.Align = AlignLeft |
| 767 |
} |
| 768 |
enc.row([]*Value{enc.headers[j], v}, rs) |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
func (enc *ExpandedEncoder) recordHeader(i int) string { |
| 773 |
header := fmt.Sprintf("* Record %d", i+1) |
| 774 |
if enc.border != 0 { |
| 775 |
header = fmt.Sprintf("[ RECORD %d ]", i+1) |
| 776 |
} |
| 777 |
return header |
| 778 |
} |
| 779 |
|
| 780 |
// columnAlign returns the alignment shared by column i's non-null values, and |
| 781 |
// whether the column had any to share. |
| 782 |
// |
| 783 |
// Note: a column whose values do not agree on an alignment has none to pass |
| 784 |
// on, and is left aligned. |
| 785 |
func columnAlign(vals [][]*Value, i int) (Align, bool) { |
| 786 |
var align Align |
| 787 |
var found bool |
| 788 |
for j := range vals { |
| 789 |
switch cell := vals[j][i]; { |
| 790 |
case cell == nil: |
| 791 |
case !found: |
| 792 |
align, found = cell.Align, true |
| 793 |
case cell.Align != align: |
| 794 |
return AlignLeft, true |
| 795 |
} |
| 796 |
} |
| 797 |
return align, found |
| 798 |
} |
| 799 |
|
| 800 |
// JSONEncoder is an unbuffered JSON encoder for result sets. |
| 801 |
type JSONEncoder struct { |
| 802 |
resultSet ResultSet |
| 803 |
// newline is the record separator to use. |
| 804 |
newline []byte |
| 805 |
// formatter handles formatting values prior to output. |
| 806 |
formatter Formatter |
| 807 |
// empty is the empty value. |
| 808 |
empty *Value |
| 809 |
// headerTransformer is the column header transformer. |
| 810 |
headerTransformer Transformer |
| 811 |
// columnTypes is used to build column types for a result set. |
| 812 |
columnTypes func(ResultSet, []any, int) error |
| 813 |
} |
| 814 |
|
| 815 |
// NewJSONEncoder creates a new JSON encoder using the provided options. |
| 816 |
func NewJSONEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 817 |
enc := &JSONEncoder{ |
| 818 |
resultSet: resultSet, |
| 819 |
newline: newline, |
| 820 |
// note: the prefix is the indent of the column a value sits on, so |
| 821 |
// that the lines of a nested object or array line up under it. |
| 822 |
formatter: NewEscapeFormatter(WithIsJSON(true), WithJSONConfig(jsonValueIndent, jsonIndent, false)), |
| 823 |
empty: &Value{ |
| 824 |
Buf: []byte("null"), |
| 825 |
Tabs: make([][][2]int, 1), |
| 826 |
Raw: true, |
| 827 |
}, |
| 828 |
} |
| 829 |
for _, o := range opts { |
| 830 |
if err := o.apply(enc); err != nil { |
| 831 |
return nil, err |
| 832 |
} |
| 833 |
} |
| 834 |
return enc, nil |
| 835 |
} |
| 836 |
|
| 837 |
// jsonIndent is the indent of one level of the JSON encoder's output, and |
| 838 |
// jsonRowIndent and jsonValueIndent the indents of a row and of a value. |
| 839 |
const ( |
| 840 |
jsonIndent = " " |
| 841 |
jsonRowIndent = jsonIndent |
| 842 |
jsonValueIndent = jsonIndent + jsonIndent |
| 843 |
) |
| 844 |
|
| 845 |
// Encode encodes a single result set to the writer using the formatting |
| 846 |
// options specified in the encoder. |
| 847 |
func (enc *JSONEncoder) Encode(w io.Writer) error { |
| 848 |
if enc.resultSet == nil { |
| 849 |
return ErrResultSetIsNil |
| 850 |
} |
| 851 |
var ( |
| 852 |
start = []byte{'['} |
| 853 |
end = []byte{']'} |
| 854 |
open = []byte{'{'} |
| 855 |
cls = []byte{'}'} |
| 856 |
q = []byte{'"'} |
| 857 |
cma = []byte{','} |
| 858 |
rowNL = append(append([]byte{}, enc.newline...), jsonRowIndent...) |
| 859 |
valNL = append(append([]byte{}, enc.newline...), jsonValueIndent...) |
| 860 |
) |
| 861 |
// get and check columns |
| 862 |
clen, cols, err := buildColNames(enc.resultSet, enc.headerTransformer) |
| 863 |
switch { |
| 864 |
case err != nil: |
| 865 |
return err |
| 866 |
case clen == 0: |
| 867 |
return ErrResultSetHasNoColumns |
| 868 |
} |
| 869 |
cb := make([][]byte, clen) |
| 870 |
for i := range clen { |
| 871 |
// note: matches the v1 encoding/json defaults, which escaped HTML and |
| 872 |
// replaced invalid UTF-8 rather than rejecting it. |
| 873 |
if cb[i], err = json.Marshal(cols[i], jsontext.AllowInvalidUTF8(true), jsontext.EscapeForHTML(true)); err != nil { |
| 874 |
return err |
| 875 |
} |
| 876 |
cb[i] = append(cb[i], ':', ' ') |
| 877 |
} |
| 878 |
// set up storage for results |
| 879 |
r, err := buildColumnTypes(enc.resultSet, clen, enc.columnTypes) |
| 880 |
if err != nil { |
| 881 |
return err |
| 882 |
} |
| 883 |
// start |
| 884 |
if _, err = w.Write(start); err != nil { |
| 885 |
return err |
| 886 |
} |
| 887 |
// process |
| 888 |
var v *Value |
| 889 |
var vals []*Value |
| 890 |
var count int |
| 891 |
for enc.resultSet.Next() { |
| 892 |
if count != 0 { |
| 893 |
if _, err = w.Write(cma); err != nil { |
| 894 |
return err |
| 895 |
} |
| 896 |
} |
| 897 |
vals, err = scanAndFormat(enc.resultSet, r, enc.formatter, &count) |
| 898 |
if err != nil { |
| 899 |
return err |
| 900 |
} |
| 901 |
if _, err = w.Write(rowNL); err != nil { |
| 902 |
return err |
| 903 |
} |
| 904 |
if _, err = w.Write(open); err != nil { |
| 905 |
return err |
| 906 |
} |
| 907 |
for i := range clen { |
| 908 |
v = vals[i] |
| 909 |
if v == nil { |
| 910 |
v = enc.empty |
| 911 |
} |
| 912 |
// write "column": |
| 913 |
if _, err = w.Write(valNL); err != nil { |
| 914 |
return err |
| 915 |
} |
| 916 |
if _, err = w.Write(cb[i]); err != nil { |
| 917 |
return err |
| 918 |
} |
| 919 |
// if raw, write the exact value |
| 920 |
if v.Raw { |
| 921 |
if _, err = w.Write(v.Buf); err != nil { |
| 922 |
return err |
| 923 |
} |
| 924 |
} else { |
| 925 |
if _, err = w.Write(q); err != nil { |
| 926 |
return err |
| 927 |
} |
| 928 |
if _, err = w.Write(v.Buf); err != nil { |
| 929 |
return err |
| 930 |
} |
| 931 |
if _, err = w.Write(q); err != nil { |
| 932 |
return err |
| 933 |
} |
| 934 |
} |
| 935 |
if i != clen-1 { |
| 936 |
if _, err = w.Write(cma); err != nil { |
| 937 |
return err |
| 938 |
} |
| 939 |
} |
| 940 |
} |
| 941 |
if _, err = w.Write(rowNL); err != nil { |
| 942 |
return err |
| 943 |
} |
| 944 |
if _, err = w.Write(cls); err != nil { |
| 945 |
return err |
| 946 |
} |
| 947 |
} |
| 948 |
err = enc.resultSet.Err() |
| 949 |
if err != nil { |
| 950 |
return err |
| 951 |
} |
| 952 |
// end -- an empty result set stays [] rather than opening a line for |
| 953 |
// nothing |
| 954 |
if count != 0 { |
| 955 |
if _, err = w.Write(enc.newline); err != nil { |
| 956 |
return err |
| 957 |
} |
| 958 |
} |
| 959 |
_, err = w.Write(end) |
| 960 |
return err |
| 961 |
} |
| 962 |
|
| 963 |
// EncodeAll encodes all result sets to the writer using the encoder settings. |
| 964 |
func (enc *JSONEncoder) EncodeAll(w io.Writer) error { |
| 965 |
if err := enc.Encode(w); err != nil { |
| 966 |
return err |
| 967 |
} |
| 968 |
for enc.resultSet.NextResultSet() { |
| 969 |
if _, err := w.Write([]byte{','}); err != nil { |
| 970 |
return err |
| 971 |
} |
| 972 |
if _, err := w.Write(enc.newline); err != nil { |
| 973 |
return err |
| 974 |
} |
| 975 |
if err := enc.Encode(w); err != nil { |
| 976 |
return err |
| 977 |
} |
| 978 |
} |
| 979 |
if _, err := w.Write(enc.newline); err != nil { |
| 980 |
return err |
| 981 |
} |
| 982 |
return nil |
| 983 |
} |
| 984 |
|
| 985 |
// UnalignedEncoder is an unbuffered, unaligned encoder for result sets. |
| 986 |
// |
| 987 |
// Provides a way of encoding unaligned result sets in formats such as |
| 988 |
// comma-separated value (CSV) or tab-separated value (TSV) files. |
| 989 |
// |
| 990 |
// By default uses a field separator of '|', no quote separator, and record |
| 991 |
// separator using the default newline for the platfom ("\r\n" on Windows, "\n" |
| 992 |
// otherwise). |
| 993 |
type UnalignedEncoder struct { |
| 994 |
// resultSet is the result set to encode. |
| 995 |
resultSet ResultSet |
| 996 |
// sep is the separator to use. |
| 997 |
sep rune |
| 998 |
// quote is the quote to use. |
| 999 |
quote rune |
| 1000 |
// newline is the record separator to use. |
| 1001 |
newline []byte |
| 1002 |
// formatter handles formatting values prior to output. |
| 1003 |
formatter Formatter |
| 1004 |
// skipHeader disables writing header. |
| 1005 |
skipHeader bool |
| 1006 |
// summary is the summary map. |
| 1007 |
summary map[int]func(io.Writer, int) (int, error) |
| 1008 |
// empty is the empty value. |
| 1009 |
empty *Value |
| 1010 |
// headerTransformer is the column header transformer. |
| 1011 |
headerTransformer Transformer |
| 1012 |
// columnTypes is used to build column types for a result set. |
| 1013 |
columnTypes func(ResultSet, []any, int) error |
| 1014 |
} |
| 1015 |
|
| 1016 |
// NewUnalignedEncoder creates a new unaligned encoder using the provided |
| 1017 |
// options. |
| 1018 |
func NewUnalignedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 1019 |
sep, quote := rune('|'), rune(0) |
| 1020 |
enc := &UnalignedEncoder{ |
| 1021 |
resultSet: resultSet, |
| 1022 |
sep: sep, |
| 1023 |
quote: quote, |
| 1024 |
newline: newline, |
| 1025 |
formatter: NewEscapeFormatter(WithIsRaw(true, sep, quote)), |
| 1026 |
summary: DefaultTableSummary(), |
| 1027 |
empty: &Value{ |
| 1028 |
Tabs: make([][][2]int, 1), |
| 1029 |
}, |
| 1030 |
} |
| 1031 |
for _, o := range opts { |
| 1032 |
if err := o.apply(enc); err != nil { |
| 1033 |
return nil, err |
| 1034 |
} |
| 1035 |
} |
| 1036 |
return enc, nil |
| 1037 |
} |
| 1038 |
|
| 1039 |
// NewCSVEncoder creates a new csv encoder using the provided options. |
| 1040 |
// |
| 1041 |
// Creates an unaligned encoder using the default field separator ',' and field |
| 1042 |
// quote of '"'. |
| 1043 |
func NewCSVEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 1044 |
sep, quote := rune(','), rune('"') |
| 1045 |
enc := &UnalignedEncoder{ |
| 1046 |
resultSet: resultSet, |
| 1047 |
sep: sep, |
| 1048 |
quote: quote, |
| 1049 |
newline: newline, |
| 1050 |
formatter: NewEscapeFormatter(WithIsRaw(true, sep, quote)), |
| 1051 |
summary: Summary{}, |
| 1052 |
empty: &Value{ |
| 1053 |
Tabs: make([][][2]int, 1), |
| 1054 |
}, |
| 1055 |
} |
| 1056 |
for _, o := range opts { |
| 1057 |
if err := o.apply(enc); err != nil { |
| 1058 |
return nil, err |
| 1059 |
} |
| 1060 |
} |
| 1061 |
return enc, nil |
| 1062 |
} |
| 1063 |
|
| 1064 |
// Encode encodes a single result set to the writer using the formatting |
| 1065 |
// options specified in the encoder. |
| 1066 |
func (enc *UnalignedEncoder) Encode(w io.Writer) error { |
| 1067 |
if enc.resultSet == nil { |
| 1068 |
return ErrResultSetIsNil |
| 1069 |
} |
| 1070 |
// get and check columns |
| 1071 |
clen, cols, err := buildColNames(enc.resultSet, enc.headerTransformer) |
| 1072 |
switch { |
| 1073 |
case err != nil: |
| 1074 |
return err |
| 1075 |
case clen == 0: |
| 1076 |
return ErrResultSetHasNoColumns |
| 1077 |
} |
| 1078 |
sep, quote := []byte(string(enc.sep)), []byte(string(enc.quote)) |
| 1079 |
// write header |
| 1080 |
if !enc.skipHeader { |
| 1081 |
headers, err := enc.formatter.Header(cols) |
| 1082 |
if err != nil { |
| 1083 |
return err |
| 1084 |
} |
| 1085 |
for i := range clen { |
| 1086 |
if i != 0 { |
| 1087 |
if _, err := w.Write(sep); err != nil { |
| 1088 |
return err |
| 1089 |
} |
| 1090 |
} |
| 1091 |
buf := headers[i].Buf |
| 1092 |
if enc.quote != 0 && headers[i].Quoted { |
| 1093 |
buf = append(quote, append(buf, quote...)...) |
| 1094 |
} |
| 1095 |
if _, err := w.Write(buf); err != nil { |
| 1096 |
return err |
| 1097 |
} |
| 1098 |
} |
| 1099 |
if _, err := w.Write(enc.newline); err != nil { |
| 1100 |
return err |
| 1101 |
} |
| 1102 |
} |
| 1103 |
// set up storage for results |
| 1104 |
r, err := buildColumnTypes(enc.resultSet, clen, enc.columnTypes) |
| 1105 |
if err != nil { |
| 1106 |
return err |
| 1107 |
} |
| 1108 |
// process |
| 1109 |
var count int |
| 1110 |
for enc.resultSet.Next() { |
| 1111 |
vals, err := scanAndFormat(enc.resultSet, r, enc.formatter, &count) |
| 1112 |
if err != nil { |
| 1113 |
return err |
| 1114 |
} |
| 1115 |
for i := range clen { |
| 1116 |
if i != 0 { |
| 1117 |
if _, err := w.Write(sep); err != nil { |
| 1118 |
return err |
| 1119 |
} |
| 1120 |
} |
| 1121 |
v := vals[i] |
| 1122 |
if v == nil { |
| 1123 |
v = enc.empty |
| 1124 |
} |
| 1125 |
buf := v.Buf |
| 1126 |
if enc.quote != 0 && v.Quoted { |
| 1127 |
buf = append(quote, append(buf, quote...)...) |
| 1128 |
} |
| 1129 |
if _, err := w.Write(buf); err != nil { |
| 1130 |
return err |
| 1131 |
} |
| 1132 |
} |
| 1133 |
if _, err := w.Write(enc.newline); err != nil { |
| 1134 |
return err |
| 1135 |
} |
| 1136 |
} |
| 1137 |
if err := summarize(w, enc.summary, count); err != nil { |
| 1138 |
return err |
| 1139 |
} |
| 1140 |
return enc.resultSet.Err() |
| 1141 |
} |
| 1142 |
|
| 1143 |
// EncodeAll encodes all result sets to the writer using the encoder settings. |
| 1144 |
func (enc *UnalignedEncoder) EncodeAll(w io.Writer) error { |
| 1145 |
if err := enc.Encode(w); err != nil { |
| 1146 |
return err |
| 1147 |
} |
| 1148 |
for enc.resultSet.NextResultSet() { |
| 1149 |
if _, err := w.Write(enc.newline); err != nil { |
| 1150 |
return err |
| 1151 |
} |
| 1152 |
if err := enc.Encode(w); err != nil { |
| 1153 |
return err |
| 1154 |
} |
| 1155 |
} |
| 1156 |
return nil |
| 1157 |
} |
| 1158 |
|
| 1159 |
// TemplateEncoder is an unbuffered template encoder for result sets. |
| 1160 |
type TemplateEncoder struct { |
| 1161 |
// ResultSet is the result set to encode. |
| 1162 |
resultSet ResultSet |
| 1163 |
// executor is the template executor function. |
| 1164 |
executor func(io.Writer, *Template) error |
| 1165 |
// newline is the record separator to use. |
| 1166 |
newline []byte |
| 1167 |
// formatter handles formatting values prior to output. |
| 1168 |
formatter Formatter |
| 1169 |
// title is the title value. |
| 1170 |
title *Value |
| 1171 |
// empty is the empty value. |
| 1172 |
empty *Value |
| 1173 |
// skipHeader disables writing header. |
| 1174 |
skipHeader bool |
| 1175 |
// attributes are extra table attributes. |
| 1176 |
attributes string |
| 1177 |
// headerTransformer is the column header transformer. |
| 1178 |
headerTransformer Transformer |
| 1179 |
// columnTypes is used to build column types for a result set. |
| 1180 |
columnTypes func(ResultSet, []any, int) error |
| 1181 |
} |
| 1182 |
|
| 1183 |
// NewTemplateEncoder creates a new template encoder using the provided options. |
| 1184 |
func NewTemplateEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 1185 |
enc := &TemplateEncoder{ |
| 1186 |
resultSet: resultSet, |
| 1187 |
executor: func(io.Writer, *Template) error { return ErrInvalidTemplate }, |
| 1188 |
newline: newline, |
| 1189 |
formatter: NewEscapeFormatter(), |
| 1190 |
empty: &Value{ |
| 1191 |
Buf: []byte(""), |
| 1192 |
}, |
| 1193 |
} |
| 1194 |
for _, o := range opts { |
| 1195 |
if err := o.apply(enc); err != nil { |
| 1196 |
return nil, err |
| 1197 |
} |
| 1198 |
} |
| 1199 |
return enc, nil |
| 1200 |
} |
| 1201 |
|
| 1202 |
// NewHTMLEncoder creates a new html template encoder using the provided |
| 1203 |
// options. |
| 1204 |
func NewHTMLEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 1205 |
return NewTemplateEncoder(resultSet, append([]Option{WithTemplate("html")}, opts...)...) |
| 1206 |
} |
| 1207 |
|
| 1208 |
// NewAsciiDocEncoder creates a new asciidoc template encoder using the |
| 1209 |
// provided options. |
| 1210 |
func NewAsciiDocEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 1211 |
return NewTemplateEncoder(resultSet, append([]Option{WithTemplate("asciidoc")}, opts...)...) |
| 1212 |
} |
| 1213 |
|
| 1214 |
// NewVerticalEncoder creates a new vertical template encoder using the |
| 1215 |
// provided options. |
| 1216 |
func NewVerticalEncoder(resultSet ResultSet, opts ...Option) (Encoder, error) { |
| 1217 |
return NewTemplateEncoder(resultSet, append([]Option{WithTemplate("vertical")}, opts...)...) |
| 1218 |
} |
| 1219 |
|
| 1220 |
// Encode encodes a single result set to the writer using the formatting |
| 1221 |
// options specified in the encoder. |
| 1222 |
func (enc *TemplateEncoder) Encode(w io.Writer) error { |
| 1223 |
if enc.resultSet == nil { |
| 1224 |
return ErrResultSetIsNil |
| 1225 |
} |
| 1226 |
// get and check columns |
| 1227 |
clen, cols, err := buildColNames(enc.resultSet, enc.headerTransformer) |
| 1228 |
switch { |
| 1229 |
case err != nil: |
| 1230 |
return err |
| 1231 |
case clen == 0: |
| 1232 |
return ErrResultSetHasNoColumns |
| 1233 |
} |
| 1234 |
headers, err := enc.formatter.Header(cols) |
| 1235 |
if err != nil { |
| 1236 |
return err |
| 1237 |
} |
| 1238 |
for i := range clen { |
| 1239 |
if headers[i] == nil { |
| 1240 |
headers[i] = enc.empty |
| 1241 |
} |
| 1242 |
} |
| 1243 |
// set up storage for results |
| 1244 |
r, err := buildColumnTypes(enc.resultSet, clen, enc.columnTypes) |
| 1245 |
if err != nil { |
| 1246 |
return err |
| 1247 |
} |
| 1248 |
// process |
| 1249 |
var rows [][]*Value |
| 1250 |
var count int |
| 1251 |
for enc.resultSet.Next() { |
| 1252 |
vals, err := scanAndFormat(enc.resultSet, r, enc.formatter, &count) |
| 1253 |
if err != nil { |
| 1254 |
return err |
| 1255 |
} |
| 1256 |
rows = append(rows, vals) |
| 1257 |
} |
| 1258 |
if err := enc.resultSet.Err(); err != nil { |
| 1259 |
return err |
| 1260 |
} |
| 1261 |
// a null cell has no type of its own to align by, so it follows the |
| 1262 |
// column, the way psql aligns the null string by the column's type |
| 1263 |
for i := range clen { |
| 1264 |
empty := enc.empty |
| 1265 |
if align, ok := columnAlign(rows, i); ok && align != empty.Align { |
| 1266 |
v := *empty |
| 1267 |
v.Align = align |
| 1268 |
empty = &v |
| 1269 |
} |
| 1270 |
for _, vals := range rows { |
| 1271 |
if vals[i] == nil { |
| 1272 |
vals[i] = empty |
| 1273 |
} |
| 1274 |
} |
| 1275 |
} |
| 1276 |
title := enc.title |
| 1277 |
if title == nil { |
| 1278 |
title = enc.empty |
| 1279 |
} |
| 1280 |
return enc.executor(w, &Template{ |
| 1281 |
Attributes: enc.attributes, |
| 1282 |
Headers: headers, |
| 1283 |
Rows: rows, |
| 1284 |
SkipHeader: enc.skipHeader, |
| 1285 |
Title: title, |
| 1286 |
}) |
| 1287 |
} |
| 1288 |
|
| 1289 |
// EncodeAll encodes all result sets to the writer using the encoder settings. |
| 1290 |
func (enc *TemplateEncoder) EncodeAll(w io.Writer) error { |
| 1291 |
if err := enc.Encode(w); err != nil { |
| 1292 |
return err |
| 1293 |
} |
| 1294 |
for enc.resultSet.NextResultSet() { |
| 1295 |
if _, err := w.Write(enc.newline); err != nil { |
| 1296 |
return err |
| 1297 |
} |
| 1298 |
if err := enc.Encode(w); err != nil { |
| 1299 |
return err |
| 1300 |
} |
| 1301 |
} |
| 1302 |
return nil |
| 1303 |
} |
| 1304 |
|
| 1305 |
// errEncoder provides a no-op encoder that always returns the wrapped error. |
| 1306 |
type errEncoder struct { |
| 1307 |
err error |
| 1308 |
} |
| 1309 |
|
| 1310 |
// Encode satisfies the Encoder interface. |
| 1311 |
func (err *errEncoder) Encode(io.Writer) error { |
| 1312 |
return err.err |
| 1313 |
} |
| 1314 |
|
| 1315 |
// EncodeAll satisfies the Encoder interface. |
| 1316 |
func (err *errEncoder) EncodeAll(io.Writer) error { |
| 1317 |
return err.err |
| 1318 |
} |
| 1319 |
|
| 1320 |
// newErrEncoder creates a no-op error encoder. |
| 1321 |
func newErrEncoder(_ ResultSet, opts ...Option) (Encoder, error) { |
| 1322 |
enc := &errEncoder{} |
| 1323 |
for _, o := range opts { |
| 1324 |
if err := o.apply(enc); err != nil { |
| 1325 |
return nil, err |
| 1326 |
} |
| 1327 |
} |
| 1328 |
return enc, enc.err |
| 1329 |
} |
| 1330 |
|
| 1331 |
// scanAndFormat scans and formats values from the result set. |
| 1332 |
func scanAndFormat(resultSet ResultSet, vals []any, formatter Formatter, count *int) ([]*Value, error) { |
| 1333 |
if err := resultSet.Err(); err != nil { |
| 1334 |
return nil, err |
| 1335 |
} |
| 1336 |
if err := resultSet.Scan(vals...); err != nil { |
| 1337 |
return nil, err |
| 1338 |
} |
| 1339 |
*count++ |
| 1340 |
return formatter.Format(vals) |
| 1341 |
} |
| 1342 |
|
| 1343 |
// buildColNames builds the column names for the result set. |
| 1344 |
func buildColNames(resultSet ResultSet, transformer Transformer) (int, []string, error) { |
| 1345 |
cols, err := resultSet.Columns() |
| 1346 |
if err != nil { |
| 1347 |
return 0, nil, err |
| 1348 |
} |
| 1349 |
clen := len(cols) |
| 1350 |
if transformer != nil { |
| 1351 |
for i := range clen { |
| 1352 |
cols[i] = transformer.Transform(cols[i]) |
| 1353 |
} |
| 1354 |
} |
| 1355 |
return clen, cols, nil |
| 1356 |
} |
| 1357 |
|
| 1358 |
// buildColumnTypes builds a []interface{} for storing scan results. |
| 1359 |
func buildColumnTypes(resultSet ResultSet, n int, columnTypes func(ResultSet, []any, int) error) ([]any, error) { |
| 1360 |
r := make([]any, n) |
| 1361 |
if columnTypes != nil { |
| 1362 |
if err := columnTypes(resultSet, r, n); err != nil { |
| 1363 |
return nil, err |
| 1364 |
} |
| 1365 |
return r, nil |
| 1366 |
} |
| 1367 |
for i := range n { |
| 1368 |
r[i] = new(any) |
| 1369 |
} |
| 1370 |
return r, nil |
| 1371 |
} |
| 1372 |
|
| 1373 |
// summarize writes the table scan count summary. |
| 1374 |
func summarize(w io.Writer, summary Summary, count int) error { |
| 1375 |
// do summary |
| 1376 |
if summary == nil { |
| 1377 |
return nil |
| 1378 |
} |
| 1379 |
var f func(io.Writer, int) (int, error) |
| 1380 |
if z, ok := summary[-1]; ok { |
| 1381 |
f = z |
| 1382 |
} |
| 1383 |
if z, ok := summary[count]; ok { |
| 1384 |
f = z |
| 1385 |
} |
| 1386 |
if f != nil { |
| 1387 |
if _, err := f(w, count); err != nil { |
| 1388 |
return err |
| 1389 |
} |
| 1390 |
if _, err := w.Write(newline); err != nil { |
| 1391 |
return err |
| 1392 |
} |
| 1393 |
} |
| 1394 |
return nil |
| 1395 |
} |
| 1396 |
|
| 1397 |
func startPager(pagerCmd string, w io.Writer) (*exec.Cmd, io.WriteCloser, error) { |
| 1398 |
cmd := exec.Command(pagerCmd) |
| 1399 |
cmd.Stdout = w |
| 1400 |
cmd.Stderr = w |
| 1401 |
cmdBuf, err := cmd.StdinPipe() |
| 1402 |
if err != nil { |
| 1403 |
return nil, nil, err |
| 1404 |
} |
| 1405 |
return cmd, cmdBuf, cmd.Start() |
| 1406 |
} |
| 1407 |
|
| 1408 |
func checkErr(err error, cmd *exec.Cmd) error { |
| 1409 |
if cmd != nil && errors.Is(err, syscall.EPIPE) { |
| 1410 |
// broken pipe means pager quit before consuming all data, which might be expected |
| 1411 |
return nil |
| 1412 |
} |
| 1413 |
return err |
| 1414 |
} |