Documentation
¶
Overview ¶
Package tblfmt provides streaming table encoders for result sets (that is, result sets from a database).
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/xo/tblfmt"
)
func main() {
res := getDatabaseResults()
if err := tblfmt.EncodeAll(os.Stdout, res, map[string]string{
"format": "aligned",
"border": "2",
}); err != nil {
log.Fatal(err)
}
}
// getDatabaseResults returns a tblfmt.ResultSet. A *sql.Rows from the
// database/sql package also implements that interface.
func getDatabaseResults() tblfmt.ResultSet {
return &result{
cols: []string{"author_id", "name", "z"},
vals: [][]any{
{14, "a\tb\tc\td", nil},
{15, "aoeu\ntest\n", nil},
{2, "袈\t袈\t\t袈", nil},
},
}
}
// result is a type that implements the tblfmt.ResultSet interface.
type result struct {
pos int
cols []string
vals [][]any
}
// Columns satisfies the tblfmt.ResultSet interface.
func (res *result) Columns() ([]string, error) {
return res.cols, nil
}
// Next satisfies the tblfmt.ResultSet interface.
func (res *result) Next() bool {
return res.pos < len(res.vals)
}
// Scan satisfies the tblfmt.ResultSet interface.
func (res *result) Scan(vals ...any) error {
for i := range vals {
x, ok := vals[i].(*any)
if !ok {
return fmt.Errorf("scan for col %d expected *interface{}, got: %T", i, vals[i])
}
*x = res.vals[res.pos][i]
}
res.pos++
return nil
}
// Err satisfies the tblfmt.ResultSet interface.
func (res *result) Err() error {
return nil
}
// Close satisfies the tblfmt.ResultSet interface.
func (res *result) Close() error {
return nil
}
// NextResultSet satisfies the tblfmt.ResultSet interface.
func (res *result) NextResultSet() bool {
return false
}
Output:
Index ¶
- func Encode(w io.Writer, resultSet ResultSet, params map[string]string, options ...Option) error
- func EncodeAll(w io.Writer, resultSet ResultSet, params map[string]string, options ...Option) error
- func EncodeAsciiDoc(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeAsciiDocAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeCSV(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeCSVAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeExpanded(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeExpandedAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeHTML(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeHTMLAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeJSON(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeJSONAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeTable(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeTableAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeTemplate(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeTemplateAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeUnaligned(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeUnalignedAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeVertical(w io.Writer, resultSet ResultSet, opts ...Option) error
- func EncodeVerticalAll(w io.Writer, resultSet ResultSet, opts ...Option) error
- func FromMap(opts map[string]string) (Builder, []Option)
- func WriteAsciidocTo(w io.Writer, tpl *Template) error
- func WriteHTMLTo(w io.Writer, tpl *Template) error
- func WriteVerticalTo(w io.Writer, tpl *Template) error
- type Align
- type Builder
- type CrosstabView
- type Encoder
- func NewAsciiDocEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewCSVEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewExpandedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewHTMLEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewJSONEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewTableEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewTemplateEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewUnalignedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- func NewVerticalEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)
- type Error
- type EscapeFormatter
- type EscapeFormatterOption
- func WithAlign(a Align) EscapeFormatterOption
- func WithEncoder(encoder func(any) ([]byte, error)) EscapeFormatterOption
- func WithHeaderAlign(a Align) EscapeFormatterOption
- func WithInvalid(invalid string) EscapeFormatterOption
- func WithIsJSON(isJSON bool) EscapeFormatterOption
- func WithIsRaw(isRaw bool, sep, quote rune) EscapeFormatterOption
- func WithJSONConfig(prefix, indent string, escapeHTML bool) EscapeFormatterOption
- func WithMask(mask string) EscapeFormatterOption
- func WithNumericLocale(enable bool, locale string) EscapeFormatterOption
- func WithTimeFormat(timeFormat string) EscapeFormatterOption
- func WithTimeLocation(timeLocation *time.Location) EscapeFormatterOption
- type ExpandedEncoder
- type Formatter
- type JSONEncoder
- type LineStyle
- type Option
- func FormatterOptionFromMap(opts map[string]string) Option
- func WithBorder(border int) Option
- func WithColumnTypes(columnTypes func(ResultSet, []any, int) error) Option
- func WithColumnTypesFunc(f func(*sql.ColumnType) (any, error)) Option
- func WithCount(count int) Option
- func WithEmpty(empty string) Option
- func WithExecutor(executor func(io.Writer, *Template) error) Option
- func WithForceUpperColumnNames(forceUpper bool) Option
- func WithFormatter(formatter Formatter) Option
- func WithFormatterOptions(opts ...EscapeFormatterOption) Option
- func WithHeaderTransformer(headerTransformer Transformer) Option
- func WithInline(inline bool) Option
- func WithLineStyle(lineStyle LineStyle) Option
- func WithLowerColumnNames(lowerColumnNames bool) Option
- func WithMinExpandWidth(w int) Option
- func WithMinPagerHeight(h int) Option
- func WithMinPagerWidth(w int) Option
- func WithNewline(newline string) Option
- func WithPager(p string) Option
- func WithParams(params ...string) Option
- func WithQuote(quote rune) Option
- func WithSeparator(sep rune) Option
- func WithSkipHeader(s bool) Option
- func WithSummary(summary Summary) Option
- func WithTableAttributes(a string) Option
- func WithTemplate(name string) Option
- func WithTitle(title string) Option
- func WithUseColumnTypes(useColumnTypes bool) Option
- func WithWidths(widths ...int) Option
- type ResultSet
- type Summary
- type TableEncoder
- type Template
- type TemplateEncoder
- type TransformStyle
- type Transformer
- type UnalignedEncoder
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Encode ¶
Encode encodes the result set to the writer. It uses the parameters in the map and any other options that you supply.
func EncodeAll ¶
EncodeAll encodes all result sets to the writer. It uses the parameters in the map and any other options that you supply.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/xo/tblfmt"
)
func main() {
res := getDatabaseResults()
if err := tblfmt.EncodeAll(os.Stdout, res, map[string]string{
"format": "csv",
"fieldsep": "|",
"null": "<nil>",
}); err != nil {
log.Fatal(err)
}
}
// getDatabaseResults returns a tblfmt.ResultSet. A *sql.Rows from the
// database/sql package also implements that interface.
func getDatabaseResults() tblfmt.ResultSet {
return &result{
cols: []string{"author_id", "name", "z"},
vals: [][]any{
{14, "a\tb\tc\td", nil},
{15, "aoeu\ntest\n", nil},
{2, "袈\t袈\t\t袈", nil},
},
}
}
// result is a type that implements the tblfmt.ResultSet interface.
type result struct {
pos int
cols []string
vals [][]any
}
// Columns satisfies the tblfmt.ResultSet interface.
func (res *result) Columns() ([]string, error) {
return res.cols, nil
}
// Next satisfies the tblfmt.ResultSet interface.
func (res *result) Next() bool {
return res.pos < len(res.vals)
}
// Scan satisfies the tblfmt.ResultSet interface.
func (res *result) Scan(vals ...any) error {
for i := range vals {
x, ok := vals[i].(*any)
if !ok {
return fmt.Errorf("scan for col %d expected *interface{}, got: %T", i, vals[i])
}
*x = res.vals[res.pos][i]
}
res.pos++
return nil
}
// Err satisfies the tblfmt.ResultSet interface.
func (res *result) Err() error {
return nil
}
// Close satisfies the tblfmt.ResultSet interface.
func (res *result) Close() error {
return nil
}
// NextResultSet satisfies the tblfmt.ResultSet interface.
func (res *result) NextResultSet() bool {
return false
}
Output: author_id,name,z 14,"a b c d",<nil> 15,"aoeu test ",<nil> 2,"袈 袈 袈",<nil>
func EncodeAsciiDoc ¶ added in v0.6.2
EncodeAsciiDoc encodes the result set to the writer with the asciidoc template and the options that you supply.
func EncodeAsciiDocAll ¶ added in v0.6.2
EncodeAsciiDocAll encodes all result sets to the writer with the asciidoc template and the options that you supply.
func EncodeCSV ¶
EncodeCSV encodes the result set to the writer as unaligned CSV, with the options that you supply.
func EncodeCSVAll ¶
EncodeCSVAll encodes all result sets to the writer as unaligned CSV, with the options that you supply.
func EncodeExpanded ¶
EncodeExpanded encodes the result set to the writer as an expanded table, with the options that you supply.
func EncodeExpandedAll ¶
EncodeExpandedAll encodes all result sets to the writer as an expanded table, with the options that you supply.
func EncodeHTML ¶ added in v0.6.2
EncodeHTML encodes the result set to the writer with the html template and the options that you supply.
func EncodeHTMLAll ¶ added in v0.6.2
EncodeHTMLAll encodes all result sets to the writer with the html template and the options that you supply.
func EncodeJSON ¶
EncodeJSON encodes the result set to the writer as JSON, with the options that you supply.
func EncodeJSONAll ¶
EncodeJSONAll encodes all result sets to the writer as JSON, with the options that you supply.
func EncodeTable ¶
EncodeTable encodes the result set to the writer as a table, with the options that you supply.
func EncodeTableAll ¶
EncodeTableAll encodes all result sets to the writer as a table, with the options that you supply.
func EncodeTemplate ¶
EncodeTemplate encodes the result set to the writer with a template. The options that you supply set the template.
func EncodeTemplateAll ¶
EncodeTemplateAll encodes all result sets to the writer with a template. The options that you supply set the template.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/xo/tblfmt"
)
func main() {
res := getDatabaseResults()
if err := tblfmt.EncodeTemplateAll(os.Stdout, res, tblfmt.WithTemplate("html")); err != nil {
log.Fatal(err)
}
}
// getDatabaseResults returns a tblfmt.ResultSet. A *sql.Rows from the
// database/sql package also implements that interface.
func getDatabaseResults() tblfmt.ResultSet {
return &result{
cols: []string{"author_id", "name", "z"},
vals: [][]any{
{14, "a\tb\tc\td", nil},
{15, "aoeu\ntest\n", nil},
{2, "袈\t袈\t\t袈", nil},
},
}
}
// result is a type that implements the tblfmt.ResultSet interface.
type result struct {
pos int
cols []string
vals [][]any
}
// Columns satisfies the tblfmt.ResultSet interface.
func (res *result) Columns() ([]string, error) {
return res.cols, nil
}
// Next satisfies the tblfmt.ResultSet interface.
func (res *result) Next() bool {
return res.pos < len(res.vals)
}
// Scan satisfies the tblfmt.ResultSet interface.
func (res *result) Scan(vals ...any) error {
for i := range vals {
x, ok := vals[i].(*any)
if !ok {
return fmt.Errorf("scan for col %d expected *interface{}, got: %T", i, vals[i])
}
*x = res.vals[res.pos][i]
}
res.pos++
return nil
}
// Err satisfies the tblfmt.ResultSet interface.
func (res *result) Err() error {
return nil
}
// Close satisfies the tblfmt.ResultSet interface.
func (res *result) Close() error {
return nil
}
// NextResultSet satisfies the tblfmt.ResultSet interface.
func (res *result) NextResultSet() bool {
return false
}
Output: <table> <caption></caption> <thead> <tr> <th align="left">author_id</th> <th align="left">name</th> <th align="left">z</th> </tr> </thead> <tbody> <tr> <td align="right">14</td> <td align="left">a b c d</td> <td align="left"></td> </tr> <tr> <td align="right">15</td> <td align="left">aoeu test </td> <td align="left"></td> </tr> <tr> <td align="right">2</td> <td align="left">袈 袈 袈</td> <td align="left"></td> </tr> </tbody> </table>
func EncodeUnaligned ¶ added in v0.5.0
EncodeUnaligned encodes the result set to the writer as unaligned text, with the options that you supply.
func EncodeUnalignedAll ¶ added in v0.5.0
EncodeUnalignedAll encodes all result sets to the writer as unaligned text, with the options that you supply.
func EncodeVertical ¶ added in v0.6.2
EncodeVertical encodes the result set to the writer with the vertical template and the options that you supply.
func EncodeVerticalAll ¶ added in v0.6.2
EncodeVerticalAll encodes all result sets to the writer with the vertical template and the options that you supply.
func FromMap ¶
FromMap returns the Builder and the options for the format and the other parameters in the map.
Note: this func is mainly a helper for parameter names that are like the format option names of psql.
func WriteAsciidocTo ¶ added in v0.17.0
WriteAsciidocTo writes simple asciidoc output to the writer.
func WriteHTMLTo ¶ added in v0.17.0
WriteHTMLTo writes simple HTML output to the writer.
Types ¶
type CrosstabView ¶ added in v0.5.0
type CrosstabView struct {
// contains filtered or unexported fields
}
CrosstabView is a crosstab view for result sets.
CAUTION:
By design, a crosstab view does not support multiple result sets. You must create a new crosstab view for each result set. Thus, NextResultSet always returns false. If you use this view inside a loop, or give it to other code that calls NextResultSet, be careful.
func (*CrosstabView) Close ¶ added in v0.5.0
func (view *CrosstabView) Close() error
Close satisfies the ResultSet interface.
func (*CrosstabView) Columns ¶ added in v0.5.0
func (view *CrosstabView) Columns() ([]string, error)
Columns satisfies the ResultSet interface.
func (*CrosstabView) Err ¶ added in v0.5.0
func (view *CrosstabView) Err() error
Err satisfies the ResultSet interface.
func (*CrosstabView) Next ¶ added in v0.5.0
func (view *CrosstabView) Next() bool
Next satisfies the ResultSet interface.
func (*CrosstabView) NextResultSet ¶ added in v0.5.0
func (view *CrosstabView) NextResultSet() bool
NextResultSet satisfies the ResultSet interface.
func (*CrosstabView) Scan ¶ added in v0.5.0
func (view *CrosstabView) Scan(v ...any) error
Scan satisfies the ResultSet interface.
type Encoder ¶
Encoder is the shared interface for encoders.
func NewAsciiDocEncoder ¶ added in v0.5.0
NewAsciiDocEncoder creates a template encoder for AsciiDoc with the options.
func NewCSVEncoder ¶
NewCSVEncoder creates a CSV encoder with the options.
It creates an unaligned encoder. By default, the field separator is ',' and the field quote is '"'.
func NewExpandedEncoder ¶
NewExpandedEncoder creates an expanded table encoder with the options.
func NewHTMLEncoder ¶ added in v0.5.0
NewHTMLEncoder creates a template encoder for HTML with the options.
func NewJSONEncoder ¶
NewJSONEncoder creates a JSON encoder with the options.
func NewTableEncoder ¶
NewTableEncoder creates a table encoder with the options.
By default, the table encoder has a border of 1 and a tab width of 8.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/xo/tblfmt"
)
func main() {
res := getDatabaseResults()
enc, err := tblfmt.NewTableEncoder(
res,
tblfmt.WithBorder(2),
tblfmt.WithLineStyle(tblfmt.UnicodeDoubleLineStyle()),
tblfmt.WithWidths(20, 20),
tblfmt.WithSummary(tblfmt.DefaultTableSummary()),
)
if err != nil {
log.Fatal(err)
}
if err := enc.EncodeAll(os.Stdout); err != nil {
log.Fatal(err)
}
}
// getDatabaseResults returns a tblfmt.ResultSet. A *sql.Rows from the
// database/sql package also implements that interface.
func getDatabaseResults() tblfmt.ResultSet {
return &result{
cols: []string{"author_id", "name", "z"},
vals: [][]any{
{14, "a\tb\tc\td", nil},
{15, "aoeu\ntest\n", nil},
{2, "袈\t袈\t\t袈", nil},
},
}
}
// result is a type that implements the tblfmt.ResultSet interface.
type result struct {
pos int
cols []string
vals [][]any
}
// Columns satisfies the tblfmt.ResultSet interface.
func (res *result) Columns() ([]string, error) {
return res.cols, nil
}
// Next satisfies the tblfmt.ResultSet interface.
func (res *result) Next() bool {
return res.pos < len(res.vals)
}
// Scan satisfies the tblfmt.ResultSet interface.
func (res *result) Scan(vals ...any) error {
for i := range vals {
x, ok := vals[i].(*any)
if !ok {
return fmt.Errorf("scan for col %d expected *interface{}, got: %T", i, vals[i])
}
*x = res.vals[res.pos][i]
}
res.pos++
return nil
}
// Err satisfies the tblfmt.ResultSet interface.
func (res *result) Err() error {
return nil
}
// Close satisfies the tblfmt.ResultSet interface.
func (res *result) Close() error {
return nil
}
// NextResultSet satisfies the tblfmt.ResultSet interface.
func (res *result) NextResultSet() bool {
return false
}
Output: ╔══════════════════════╦═══════════════════════════╦═══╗ ║ author_id ║ name ║ z ║ ╠══════════════════════╬═══════════════════════════╬═══╣ ║ 14 ║ a b c d ║ ║ ║ 15 ║ aoeu ↵║ ║ ║ ║ test ↵║ ║ ║ ║ ║ ║ ║ 2 ║ 袈 袈 袈 ║ ║ ╚══════════════════════╩═══════════════════════════╩═══╝ (3 rows)
func NewTemplateEncoder ¶
NewTemplateEncoder creates a template encoder with the options.
func NewUnalignedEncoder ¶ added in v0.5.0
NewUnalignedEncoder creates an unaligned encoder with the options.
type Error ¶
type Error string
Error is an error.
const ( // ErrResultSetIsNil is the result set is nil error. ErrResultSetIsNil Error = "result set is nil" // ErrResultSetHasNoColumnTypes is the result set has no column types error. ErrResultSetHasNoColumnTypes Error = "result set has no column types" // ErrResultSetReturnedInvalidColumnTypes is the result set returned invalid column types error. ErrResultSetReturnedInvalidColumnTypes Error = "result set returned invalid column types" // ErrInvalidFormat is the invalid format error. ErrInvalidFormat Error = "invalid format" // ErrInvalidLineStyle is the invalid line style error. ErrInvalidLineStyle Error = "invalid line style" // ErrInvalidTemplate is the invalid template error. ErrInvalidTemplate Error = "invalid template" // ErrInvalidFieldSeparator is the invalid field separator error. ErrInvalidFieldSeparator Error = "invalid field separator" // ErrInvalidCSVFieldSeparator is the invalid csv field separator error. ErrInvalidCSVFieldSeparator Error = "invalid csv field separator" // ErrInvalidColumnParams is the invalid column params error. ErrInvalidColumnParams Error = "invalid column params" // ErrCrosstabResultMustHaveAtLeast3Columns is the crosstab result must // have at least 3 columns error. ErrCrosstabResultMustHaveAtLeast3Columns Error = "crosstab result must have at least 3 columns" // ErrCrosstabDataColumnMustBeSpecifiedWhenQueryReturnsMoreThanThreeColumns // is the data column must be specified when query returns more than three // columns error. ErrCrosstabDataColumnMustBeSpecifiedWhenQueryReturnsMoreThanThreeColumns Error = "data column must be specified when query returns more than three columns" // ErrCrosstabVerticalAndHorizontalColumnsMustNotBeSame is the crosstab // vertical and horizontal columns must not be same error. ErrCrosstabVerticalAndHorizontalColumnsMustNotBeSame Error = "crosstab vertical and horizontal columns must not be same" // ErrCrosstabVerticalColumnNotInResult is the crosstab vertical column not // in result error. ErrCrosstabVerticalColumnNotInResult Error = "crosstab vertical column not in result" // ErrCrosstabHorizontalColumnNotInResult is the crosstab horizontal column // not in result error. ErrCrosstabHorizontalColumnNotInResult Error = "crosstab horizontal column not in result" // ErrCrosstabDataColumnNotInResult is the crosstab data column not in // result error. ErrCrosstabDataColumnNotInResult Error = "crosstab data column not in result" // ErrCrosstabHorizontalSortColumnNotInResult is the crosstab horizontal // sort column not in result error. ErrCrosstabHorizontalSortColumnNotInResult Error = "crosstab horizontal sort column not in result" // ErrCrosstabDuplicateVerticalAndHorizontalValue is the crosstab duplicate // vertical and horizontal value error. ErrCrosstabDuplicateVerticalAndHorizontalValue Error = "crosstab duplicate vertical and horizontal value" // ErrCrosstabHorizontalSortColumnIsNotANumber is the crosstab horizontal // sort column is not a number error. ErrCrosstabHorizontalSortColumnIsNotANumber Error = "crosstab horizontal sort column is not a number" )
Error values.
type EscapeFormatter ¶
type EscapeFormatter struct {
// contains filtered or unexported fields
}
EscapeFormatter is a formatter that escapes values. It formats the standard Go types.
If a marshal func is set with WithEncoder, the formatter passes it each map[string]interface{} and []interface{} value. Otherwise, the formatter uses encoding/json/v2 from the standard library.
func NewEscapeFormatter ¶
func NewEscapeFormatter(opts ...EscapeFormatterOption) *EscapeFormatter
NewEscapeFormatter creates an escape formatter for basic Go values, such as []byte, string, time.Time, sql.Null*, and any database/sql/driver.Valuer. The formatter passes map[string]interface{} and []interface{} values to the marshal func set with WithEncoder. Otherwise, it uses the standard encoding/json/v2 to marshal those values.
type EscapeFormatterOption ¶
type EscapeFormatterOption func(*EscapeFormatter)
EscapeFormatterOption is an escape formatter option.
func WithAlign ¶ added in v0.18.0
func WithAlign(a Align) EscapeFormatterOption
WithAlign sets the forced alignment for values.
func WithEncoder ¶ added in v0.10.0
func WithEncoder(encoder func(any) ([]byte, error)) EscapeFormatterOption
WithEncoder is an escape formatter option that sets a standard Go marshal func to encode the value.
func WithHeaderAlign ¶ added in v0.2.0
func WithHeaderAlign(a Align) EscapeFormatterOption
WithHeaderAlign sets the alignment of the column names in the header.
func WithInvalid ¶
func WithInvalid(invalid string) EscapeFormatterOption
WithInvalid is an escape formatter option that sets the text that replaces an invalid rune in the escape.
func WithIsJSON ¶ added in v0.5.0
func WithIsJSON(isJSON bool) EscapeFormatterOption
WithIsJSON is an escape formatter option that turns on a special escape for JSON characters in values that are not complex.
func WithIsRaw ¶ added in v0.5.0
func WithIsRaw(isRaw bool, sep, quote rune) EscapeFormatterOption
WithIsRaw is an escape formatter option that turns on a special escape for raw characters in values.
func WithJSONConfig ¶
func WithJSONConfig(prefix, indent string, escapeHTML bool) EscapeFormatterOption
WithJSONConfig is an escape formatter option that sets the JSON prefix, the JSON indent, and whether to escape HTML. The formatter passes them to encoding/json/v2 if no marshal func is set on the escape formatter.
The prefix and indent must contain only spaces and tabs, and are ignored otherwise. Output is compact when both are empty.
func WithMask ¶
func WithMask(mask string) EscapeFormatterOption
WithMask is an escape formatter option that sets the mask for an empty column name in the header.
func WithNumericLocale ¶ added in v0.10.0
func WithNumericLocale(enable bool, locale string) EscapeFormatterOption
WithNumericLocale sets the numeric locale printer. The printer groups the digits of a number as the locale does, the same as \pset numericlocale in psql.
It has no effect on JSON output. A grouped number is not a JSON number. A JSON string for it makes the JSON type of a column depend on a display option. Every other format applies it. The csv output quotes each field that needs it, exactly as psql does.
func WithTimeFormat ¶
func WithTimeFormat(timeFormat string) EscapeFormatterOption
WithTimeFormat is an escape formatter option that sets the time format for time values.
func WithTimeLocation ¶ added in v0.13.1
func WithTimeLocation(timeLocation *time.Location) EscapeFormatterOption
WithTimeLocation is an escape formatter option that sets the time location for time values.
type ExpandedEncoder ¶
type ExpandedEncoder struct {
TableEncoder
}
ExpandedEncoder is an encoder that writes a result set as an expanded table. It writes each row as a record, with one line for each column. It buffers a batch of rows ahead, as TableEncoder does.
type Formatter ¶
type Formatter interface {
// Header returns a slice of formatted values for the column names of a
// header.
Header([]string) ([]*Value, error)
// Format returns a slice of formatted values for the values of a row.
Format([]any) ([]*Value, error)
}
Formatter is the common interface that formats values.
type JSONEncoder ¶
type JSONEncoder struct {
// contains filtered or unexported fields
}
JSONEncoder is an encoder that writes a result set as JSON. It does not buffer rows.
type LineStyle ¶
LineStyle is a line style for tables.
The ASCII, OldASCII, and Unicode line styles below are predefined line styles.
A table usually looks like this:
+-----------+---------------------------+---+ | author_id | name | z | +-----------+---------------------------+---+ | 14 | a b c d | | | 15 | aoeu +| | | | test +| | | | | | +-----------+---------------------------+---+
If the border is 0, the encoder does not write a border around the table:
author_id name z
--------- ------------------------- -
14 a b c d
15 aoeu +
test +
If the border is 1, the encoder writes a border between the columns:
author_id | name | z
-----------+---------------------------+---
14 | a b c d |
15 | aoeu +|
| test +|
| |
func ASCIILineStyle ¶
func ASCIILineStyle() LineStyle
ASCIILineStyle is the ASCII line style for tables.
A table with this line style looks like this:
+-----------+---------------------------+---+ | author_id | name | z | +-----------+---------------------------+---+ | 14 | a b c d | | | 15 | aoeu +| | | | test +| | | | | | +-----------+---------------------------+---+
func OldASCIILineStyle ¶
func OldASCIILineStyle() LineStyle
OldASCIILineStyle is the old ASCII line style for tables.
A table with this line style looks like this:
+-----------+---------------------------+---+ | author_id | name | z | +-----------+---------------------------+---+ | 14 | a b c d | | | 15 | aoeu | | | : test | | : | +-----------+---------------------------+---+
func TableLineStyle ¶ added in v0.18.0
func TableLineStyle() LineStyle
TableLineStyle is the table line style.
A table with this line style looks like this:
AUTHOR_ID NAME Z
14 a b c d
15 aoeu
test
func UnicodeDoubleLineStyle ¶
func UnicodeDoubleLineStyle() LineStyle
UnicodeDoubleLineStyle is the Unicode double line style for tables.
A table with this line style looks like this:
╔═══════════╦═══════════════════════════╦═══╗ ║ author_id ║ name ║ z ║ ╠═══════════╬═══════════════════════════╬═══╣ ║ 14 ║ a b c d ║ ║ ║ 15 ║ aoeu ↵║ ║ ║ ║ test ↵║ ║ ║ ║ ║ ║ ╚═══════════╩═══════════════════════════╩═══╝
func UnicodeLineStyle ¶
func UnicodeLineStyle() LineStyle
UnicodeLineStyle is the Unicode line style for tables.
A table with this line style looks like this:
┌───────────┬───────────────────────────┬───┐ │ author_id │ name │ z │ ├───────────┼───────────────────────────┼───┤ │ 14 │ a b c d │ │ │ 15 │ aoeu ↵│ │ │ │ test ↵│ │ │ │ │ │ └───────────┴───────────────────────────┴───┘
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option is an encoder option.
func FormatterOptionFromMap ¶ added in v0.11.1
FormatterOptionFromMap builds an option that sets the formatter options from the parameters in the map.
func WithBorder ¶
WithBorder is an encoder option that sets the border size.
func WithColumnTypes ¶ added in v0.12.0
WithColumnTypes is an encoder option that sets the func that builds the column types.
func WithColumnTypesFunc ¶ added in v0.12.0
func WithColumnTypesFunc(f func(*sql.ColumnType) (any, error)) Option
WithColumnTypesFunc is an encoder option that sets a func that builds the type of each column.
func WithExecutor ¶ added in v0.5.0
WithExecutor is an encoder option that sets the executor.
func WithForceUpperColumnNames ¶ added in v0.18.0
WithForceUpperColumnNames is an encoder option that changes all column names to upper case. See TransformForceUpper.
func WithFormatter ¶
WithFormatter is an encoder option that sets the formatter for values.
func WithFormatterOptions ¶ added in v0.7.1
func WithFormatterOptions(opts ...EscapeFormatterOption) Option
WithFormatterOptions is an encoder option that adds more formatter options.
func WithHeaderTransformer ¶ added in v0.18.0
func WithHeaderTransformer(headerTransformer Transformer) Option
WithHeaderTransformer is an encoder option that sets the transform style for the header.
func WithInline ¶
WithInline is an encoder option that writes the header inline with the top line.
func WithLineStyle ¶
WithLineStyle is an encoder option that sets the line style of the table.
func WithLowerColumnNames ¶ added in v0.7.5
WithLowerColumnNames is an encoder option that changes the column names to lower case when they are all upper case. See TransformUpperToLower.
func WithMinExpandWidth ¶ added in v0.3.0
WithMinExpandWidth is an encoder option that sets the maximum width before the encoder switches to the expanded format.
func WithMinPagerHeight ¶ added in v0.3.0
WithMinPagerHeight is an encoder option that sets the maximum height before the encoder sends the output to the pager.
func WithMinPagerWidth ¶ added in v0.3.0
WithMinPagerWidth is an encoder option that sets the maximum width before the encoder sends the output to the pager.
func WithNewline ¶
WithNewline is an encoder option that sets the newline.
func WithParams ¶ added in v0.5.0
WithParams is a view option that sets the column parameters.
func WithQuote ¶ added in v0.5.0
WithQuote is an encoder option that sets the quote character for fields.
func WithSeparator ¶ added in v0.5.0
WithSeparator is an encoder option that sets the field separator.
func WithSkipHeader ¶ added in v0.4.0
WithSkipHeader is an encoder option that stops the encoder from writing the header.
func WithSummary ¶
WithSummary is an encoder option that sets the summary of the table.
func WithTableAttributes ¶ added in v0.2.0
WithTableAttributes is an encoder option that sets the table attributes.
func WithTemplate ¶
WithTemplate is an encoder option that sets the template by its name.
func WithUseColumnTypes ¶ added in v0.7.0
WithUseColumnTypes is an encoder option that makes the encoder use the column types of the result set.
func WithWidths ¶
WithWidths is an encoder option that sets the (minimum) width of each column.
type ResultSet ¶
type ResultSet interface {
Next() bool
Scan(...any) error
Columns() ([]string, error)
Close() error
Err() error
NextResultSet() bool
}
ResultSet is the shared interface for a result set.
type Summary ¶ added in v0.13.0
Summary maps a row count to the func that writes the summary for that count. The key -1 holds the func for any other count.
func DefaultTableSummary ¶
func DefaultTableSummary() Summary
DefaultTableSummary is the default summary for tables.
The default summary looks like this:
(3 rows)
type TableEncoder ¶
type TableEncoder struct {
// contains filtered or unexported fields
}
TableEncoder is an encoder that writes a result set as a table. It buffers a batch of rows ahead to find the widths of the columns.
type Template ¶ added in v0.17.0
type Template struct {
Attributes string
Headers []*Value
Rows [][]*Value
SkipHeader bool
Title *Value
}
Template holds the data for a template.
type TemplateEncoder ¶
type TemplateEncoder struct {
// contains filtered or unexported fields
}
TemplateEncoder is a template encoder for result sets.
Note: the encoder reads every row of a result set into memory before it runs the template, because the template receives all the rows at once.
type TransformStyle ¶ added in v0.18.0
type TransformStyle int
TransformStyle is a transform style for column names in the header.
const ( TransformNone TransformStyle = iota TransformForceLower TransformForceUpper TransformUpperToLower TransformLowerToUpper )
Transform styles.
func (TransformStyle) Transform ¶ added in v0.18.0
func (style TransformStyle) Transform(s string) string
Transform transforms s with the style. It satisfies the Transformer interface.
type Transformer ¶ added in v0.18.0
Transformer is the interface for column transformers.
type UnalignedEncoder ¶ added in v0.5.0
type UnalignedEncoder struct {
// contains filtered or unexported fields
}
UnalignedEncoder is an encoder that writes a result set with no alignment. It does not buffer rows.
You can use it to encode a result set in formats such as comma-separated values (CSV) or tab-separated values (TSV).
By default, the field separator is '|', there is no quote character, and the record separator is the default newline for the platform ("\r\n" on Windows, "\n" otherwise).
type Value ¶
type Value struct {
// Buf is the formatted value.
Buf []byte
// Newlines are the positions of newline characters in Buf.
Newlines [][2]int
// Tabs are the positions of tab characters in Buf, split per line.
Tabs [][][2]int
// Width is the remaining width.
Width int
// Align is the alignment of the value.
Align Align
// Raw is true when the JSON encoder writes Buf exactly, with no quotes.
Raw bool
// Quoted tracks whether a raw value must be quoted, that is, whether it
// contains a space or a non printable character.
Quoted bool
}
Value holds a formatted value and data about it.
func FormatBytes ¶
func FormatBytes(src []byte, invalid []byte, invalidWidth int, isJSON, isRaw bool, sep, quote rune) *Value
FormatBytes escapes src to a Value. The Value holds the escaped (encoded) and unescaped runes, and the positions of the tabs and newlines in its Buf.