sq/cli/output/tablew/recordwriter.go

74 lines
1.4 KiB
Go
Raw Normal View History

2020-08-06 20:58:47 +03:00
package tablew
import (
"io"
2023-05-11 05:03:45 +03:00
"sync"
2020-08-06 20:58:47 +03:00
"github.com/neilotoole/sq/libsq/core/record"
2020-08-06 20:58:47 +03:00
"github.com/neilotoole/sq/cli/output"
)
type recordWriter struct {
2023-05-11 05:03:45 +03:00
mu sync.Mutex
2020-08-06 20:58:47 +03:00
tbl *table
recMeta record.Meta
2020-08-06 20:58:47 +03:00
rowCount int
}
// NewRecordWriter returns a RecordWriter for text table output.
func NewRecordWriter(out io.Writer, pr *output.Printing) output.RecordWriter {
tbl := &table{out: out, pr: pr, header: pr.ShowHeader}
w := &recordWriter{tbl: tbl}
2020-08-06 20:58:47 +03:00
w.tbl.reset()
return w
}
// Open implements output.RecordWriter.
func (w *recordWriter) Open(recMeta record.Meta) error {
2020-08-06 20:58:47 +03:00
w.recMeta = recMeta
return nil
}
// Flush implements output.RecordWriter.
func (w *recordWriter) Flush() error {
2020-08-06 20:58:47 +03:00
return nil
}
// Close implements output.RecordWriter.
func (w *recordWriter) Close() error {
2020-08-06 20:58:47 +03:00
if w.rowCount == 0 {
// no data to write
return nil
}
w.tbl.tblImpl.SetAutoWrapText(false)
header := w.recMeta.MungedNames()
2020-08-06 20:58:47 +03:00
w.tbl.tblImpl.SetHeader(header)
w.tbl.renderAll()
return nil
}
// WriteRecords implements output.RecordWriter.
func (w *recordWriter) WriteRecords(recs []record.Record) error {
2023-05-11 05:03:45 +03:00
w.mu.Lock()
defer w.mu.Unlock()
2020-08-06 20:58:47 +03:00
kinds := w.recMeta.Kinds()
var tblRows [][]string
for _, rec := range recs {
tblRow := make([]string, len(rec))
for i, val := range rec {
tblRow[i] = w.tbl.renderResultCell(kinds[i], val)
}
tblRows = append(tblRows, tblRow)
w.rowCount++
}
w.tbl.appendRows(tblRows)
return nil
}