2020-08-06 20:58:47 +03:00
|
|
|
package tablew
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/cli/output"
|
|
|
|
"github.com/neilotoole/sq/libsq/sqlz"
|
|
|
|
)
|
|
|
|
|
2020-08-09 16:46:46 +03:00
|
|
|
type recordWriter struct {
|
2020-08-06 20:58:47 +03:00
|
|
|
tbl *table
|
|
|
|
recMeta sqlz.RecordMeta
|
|
|
|
rowCount int
|
|
|
|
}
|
|
|
|
|
2020-08-09 16:46:46 +03:00
|
|
|
// NewRecordWriter returns a RecordWriter for text table output.
|
|
|
|
func NewRecordWriter(out io.Writer, fm *output.Formatting, header bool) output.RecordWriter {
|
2020-08-06 20:58:47 +03:00
|
|
|
tbl := &table{out: out, fm: fm, header: header}
|
2020-08-09 16:46:46 +03:00
|
|
|
w := &recordWriter{tbl: tbl}
|
2020-08-06 20:58:47 +03:00
|
|
|
w.tbl.reset()
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2020-08-09 16:46:46 +03:00
|
|
|
// Open implements output.RecordWriter.
|
|
|
|
func (w *recordWriter) Open(recMeta sqlz.RecordMeta) error {
|
2020-08-06 20:58:47 +03:00
|
|
|
w.recMeta = recMeta
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-09 16:46:46 +03:00
|
|
|
// Flush implements output.RecordWriter.
|
|
|
|
func (w *recordWriter) Flush() error {
|
2020-08-06 20:58:47 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-09 16:46:46 +03:00
|
|
|
// 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.Names()
|
|
|
|
w.tbl.tblImpl.SetHeader(header)
|
|
|
|
|
|
|
|
w.tbl.renderAll()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-09 16:46:46 +03:00
|
|
|
// WriteRecords implements output.RecordWriter.
|
|
|
|
func (w *recordWriter) WriteRecords(recs []sqlz.Record) error {
|
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
|
|
|
|
}
|