tblfmt

package module
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2025 License: MIT Imports: 26 Imported by: 13

README

About tblfmt

Package tblfmt provides streaming table encoders for result sets (ie, from a database), creating tables like the following:

 author_id | name                  | z
-----------+-----------------------+---
        14 | a	b	c	d  |
        15 | aoeu                 +|
           | test                 +|
           |                       |
        16 | foo\bbar              |
        17 | a	b	\r        +|
           | 	a                  |
        18 | 袈	袈		袈 |
        19 | 袈	袈		袈+| a+
           |                       |
(6 rows)

Additionally, there are standard encoders for JSON, CSV, HTML, unaligned and other display variants supported by usql.

Unit Tests Go Reference Discord Discussion

Installing

Install in the usual Go fashion:

$ go get -u github.com/xo/tblfmt

Using

tblfmt was designed for use by usql and Go's native database/sql types, but will handle any type with the following interface:

// ResultSet is the shared interface for a result set.
type ResultSet interface {
	Next() bool
	Scan(...interface{}) error
	Columns() ([]string, error)
	Close() error
	Err() error
	NextResultSet() bool
}

tblfmt can be used similar to the following:

// _example/example.go
package main

import (
	"log"
	"os"

	_ "github.com/lib/pq"
	"github.com/xo/dburl"
	"github.com/xo/tblfmt"
)

func main() {
	db, err := dburl.Open("postgres://booktest:booktest@localhost")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	res, err := db.Query("select * from authors")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Close()
	enc, err := tblfmt.NewTableEncoder(
		res,
		// force minimum column widths
		tblfmt.WithWidths(20, 20),
	)
	if err = enc.EncodeAll(os.Stdout); err != nil {
		log.Fatal(err)
	}
}

Which can produce output like the following:

╔══════════════════════╦═══════════════════════════╦═══╗
║ author_id            ║ name                      ║ z ║
╠══════════════════════╬═══════════════════════════╬═══╣
║                   14 ║ a	b	c	d  ║   ║
║                   15 ║ aoeu                     ↵║   ║
║                      ║ test                     ↵║   ║
║                      ║                           ║   ║
║                    2 ║ 袈	袈		袈 ║   ║
╚══════════════════════╩═══════════════════════════╩═══╝
(3 rows)

Please see the Go Reference for the full API.

Testing

Run using standard go test:

$ go test -v

Documentation

Overview

Package tblfmt provides streaming table encoders for result sets (ie, from a database).

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Encode

func Encode(w io.Writer, resultSet ResultSet, params map[string]string, options ...Option) error

Encode encodes the result set to the writer using the supplied map params and any additional options.

func EncodeAll

func EncodeAll(w io.Writer, resultSet ResultSet, params map[string]string, options ...Option) error

EncodeAll encodes all result sets to the writer using the supplied map params and any additional options.

Example
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/xo/tblfmt"
)

// result is a simple type providing a tblfmt.ResultSet.
type result struct {
	pos  int
	cols []string
	vals [][]interface{}
}

// 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 ...interface{}) error {
	for i := range vals {
		x, ok := vals[i].(*interface{})
		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
}

// getDatabaseResults returns a tblfmt.ResultSet, which is an interface that is
// compatible with Go's standard
func getDatabaseResults() tblfmt.ResultSet {
	return &result{
		cols: []string{"author_id", "name", "z"},
		vals: [][]interface{}{
			{14, "a\tb\tc\td", nil},
			{15, "aoeu\ntest\n", nil},
			{2, "袈\t袈\t\t袈", nil},
		},
	}
}

func main() {
	res := getDatabaseResults()
	if err := tblfmt.EncodeAll(os.Stdout, res, map[string]string{
		"format":   "csv",
		"fieldsep": "|",
		"null":     "<nil>",
	}); err != nil {
		log.Fatal(err)
	}
}
Output:

author_id,name,z
14,"a	b	c	d",<nil>
15,"aoeu
test
",<nil>
2,"袈	袈		袈",<nil>

func EncodeAsciiDoc added in v0.6.2

func EncodeAsciiDoc(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeAsciiDoc encodes the result set to the writer using the asciidoc template and the supplied encoding options.

func EncodeAsciiDocAll added in v0.6.2

func EncodeAsciiDocAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeAsciiDoc encodes the result set to the writer using the asciidoc template and the supplied encoding options.

func EncodeCSV

func EncodeCSV(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeCSV encodes the result set to the writer unaligned using the supplied encoding options.

func EncodeCSVAll

func EncodeCSVAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeCSVAll encodes all result sets to the writer unaligned using the supplied encoding options.

func EncodeExpanded

func EncodeExpanded(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeExpanded encodes result set to the writer as a table using the supplied encoding options.

func EncodeExpandedAll

func EncodeExpandedAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeExpandedAll encodes all result sets to the writer as a table using the supplied encoding options.

func EncodeHTML added in v0.6.2

func EncodeHTML(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeHTML encodes the result set to the writer using the html template and the supplied encoding options.

func EncodeHTMLAll added in v0.6.2

func EncodeHTMLAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeHTML encodes the result set to the writer using the html template and the supplied encoding options.

func EncodeJSON

func EncodeJSON(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeJSON encodes the result set to the writer as JSON using the supplied encoding options.

func EncodeJSONAll

func EncodeJSONAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeJSONAll encodes all result sets to the writer as JSON using the supplied encoding options.

func EncodeTable

func EncodeTable(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeTable encodes result set to the writer as a table using the supplied encoding options.

func EncodeTableAll

func EncodeTableAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeTableAll encodes all result sets to the writer as a table using the supplied encoding options.

func EncodeTemplate

func EncodeTemplate(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeTemplate encodes the result set to the writer using a template from the supplied encoding options.

func EncodeTemplateAll

func EncodeTemplateAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeTemplateAll encodes all result sets to the writer using a template from the supplied encoding options.

Example
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/xo/tblfmt"
)

// result is a simple type providing a tblfmt.ResultSet.
type result struct {
	pos  int
	cols []string
	vals [][]interface{}
}

// 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 ...interface{}) error {
	for i := range vals {
		x, ok := vals[i].(*interface{})
		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
}

// getDatabaseResults returns a tblfmt.ResultSet, which is an interface that is
// compatible with Go's standard
func getDatabaseResults() tblfmt.ResultSet {
	return &result{
		cols: []string{"author_id", "name", "z"},
		vals: [][]interface{}{
			{14, "a\tb\tc\td", nil},
			{15, "aoeu\ntest\n", nil},
			{2, "袈\t袈\t\t袈", nil},
		},
	}
}

func main() {
	res := getDatabaseResults()
	if err := tblfmt.EncodeTemplateAll(os.Stdout, res, tblfmt.WithTemplate("html")); err != nil {
		log.Fatal(err)
	}
}
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

func EncodeUnaligned(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeUnaligned encodes the result set to the writer unaligned using the supplied encoding options.

func EncodeUnalignedAll added in v0.5.0

func EncodeUnalignedAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeUnalignedAll encodes all result sets to the writer unaligned using the supplied encoding options.

func EncodeVertical added in v0.6.2

func EncodeVertical(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeVertical encodes the result set to the writer using the vertical template and the supplied encoding options.

func EncodeVerticalAll added in v0.6.2

func EncodeVerticalAll(w io.Writer, resultSet ResultSet, opts ...Option) error

EncodeVertical encodes the result set to the writer using the vertical template and the supplied encoding options.

func FromMap

func FromMap(opts map[string]string) (Builder, []Option)

FromMap creates an encoder for the provided result set, applying the named options.

Note: this func is primarily a helper func to accommodate psql-like format option names.

Types

type Align

type Align int

Align indicates an alignment direction for a value.

const (
	AlignLeft Align = iota
	AlignRight
	AlignCenter
)

Align values.

func (Align) String

func (a Align) String() string

String satisfies the fmt.Stringer interface.

type Builder

type Builder = func(ResultSet, ...Option) (Encoder, error)

Builder is the shared builder interface.

type CrosstabView added in v0.5.0

type CrosstabView struct {
	// contains filtered or unexported fields
}

CrosstabView is a crosstab view for result sets.

CAUTION:

A design decision was made to not support multiple result sets, and to force the user to create a new crosstab view for each result set. As such, NextResultSet always returns false, and any use of this view should take care when using inside a loop or passing to other code that calls NextResultSet.

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 ...interface{}) error

Scan satisfies the ResultSet interface.

type Encoder

type Encoder interface {
	Encode(io.Writer) error
	EncodeAll(io.Writer) error
}

Encoder is the shared interface for encoders.

func NewAsciiDocEncoder added in v0.5.0

func NewAsciiDocEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewAsciiDocEncoder creates a new asciidoc template encoder using the provided options.

func NewCSVEncoder

func NewCSVEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewCSVEncoder creates a new csv encoder using the provided options.

Creates an unaligned encoder using the default field separator ',' and field quote of '"'.

func NewExpandedEncoder

func NewExpandedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewExpandedEncoder creates a new expanded table encoder using the provided options.

func NewHTMLEncoder added in v0.5.0

func NewHTMLEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewHTMLEncoder creates a new html template encoder using the provided options.

func NewJSONEncoder

func NewJSONEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewJSONEncoder creates a new JSON encoder using the provided options.

func NewTableEncoder

func NewTableEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

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.

Example
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/xo/tblfmt"
)

// result is a simple type providing a tblfmt.ResultSet.
type result struct {
	pos  int
	cols []string
	vals [][]interface{}
}

// 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 ...interface{}) error {
	for i := range vals {
		x, ok := vals[i].(*interface{})
		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
}

// getDatabaseResults returns a tblfmt.ResultSet, which is an interface that is
// compatible with Go's standard
func getDatabaseResults() tblfmt.ResultSet {
	return &result{
		cols: []string{"author_id", "name", "z"},
		vals: [][]interface{}{
			{14, "a\tb\tc\td", nil},
			{15, "aoeu\ntest\n", nil},
			{2, "袈\t袈\t\t袈", nil},
		},
	}
}

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)
	}
}
Output:

╔══════════════════════╦═══════════════════════════╦═══╗
║      author_id       ║           name            ║ z ║
╠══════════════════════╬═══════════════════════════╬═══╣
║                   14 ║ a	b	c	d  ║   ║
║                   15 ║ aoeu                     ↵║   ║
║                      ║ test                     ↵║   ║
║                      ║                           ║   ║
║                    2 ║ 袈	袈		袈 ║   ║
╚══════════════════════╩═══════════════════════════╩═══╝
(3 rows)

func NewTemplateEncoder

func NewTemplateEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewTemplateEncoder creates a new template encoder using the provided options.

func NewUnalignedEncoder added in v0.5.0

func NewUnalignedEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewUnalignedEncoder creates a new unaligned encoder using the provided options.

func NewVerticalEncoder added in v0.6.2

func NewVerticalEncoder(resultSet ResultSet, opts ...Option) (Encoder, error)

NewVerticalEncoder creates a new vertical template encoder using the provided 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"
	// ErrResultSetHasNoColumns is the result set has no columns error.
	ErrResultSetHasNoColumns Error = "result set has no columns"
	// 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"
	// ErrCrosstabDataColumnMustBeSpecifiedWhenQueryReturnsMoreThanThreeColumnsA
	// 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.

func (Error) Error

func (err Error) Error() string

Error satisfies the error interface.

type EscapeFormatter

type EscapeFormatter struct {
	// contains filtered or unexported fields
}

EscapeFormatter is an escaping formatter, that handles formatting the standard Go types.

When the encoder is not nil, then it will be passed any map[string]interface{} and []interface{} values encountered, otherwise the stdlib's encoding/json.Encoder will be used.

func NewEscapeFormatter

func NewEscapeFormatter(opts ...EscapeFormatterOption) *EscapeFormatter

NewEscapeFormatter creates a escape formatter to handle basic Go values, such as []byte, string, time.Time, and sql.Null*. Formatting for map[string]interface{} and []interface{} will be passed to a marshaler provided by WithEncoder, otherwise the standard encoding/json.Encoder will be used to marshal those values.

func (*EscapeFormatter) Format

func (f *EscapeFormatter) Format(vals []interface{}) ([]*Value, error)

Format satisfies the Formatter interface.

func (*EscapeFormatter) Header

func (f *EscapeFormatter) Header(headers []string) ([]*Value, error)

Header satisfies the Formatter interface.

type EscapeFormatterOption

type EscapeFormatterOption func(*EscapeFormatter)

EscapeFormatterOption is an escape formatter option.

func WithEncoder added in v0.10.0

func WithEncoder(encoder func(interface{}) ([]byte, error)) EscapeFormatterOption

WithEncoder is an escape formatter option to set a standard Go encoder to use for encoding the value.

func WithHeaderAlign added in v0.2.0

func WithHeaderAlign(a Align) EscapeFormatterOption

WithHeaderAlign sets the alignment of header values.

func WithInvalid

func WithInvalid(invalid string) EscapeFormatterOption

WithInvalid is an escape formatter option to set the invalid value used when an invalid rune is encountered during escaping.

func WithIsJSON added in v0.5.0

func WithIsJSON(isJSON bool) EscapeFormatterOption

WithIsJSON is an escape formatter option to enable special escaping for JSON characters in non-complex values.

func WithIsRaw added in v0.5.0

func WithIsRaw(isRaw bool, sep, quote rune) EscapeFormatterOption

WithIsRaw is an escape formatter option to enable special escaping for raw characters in values.

func WithJSONConfig

func WithJSONConfig(prefix, indent string, escapeHTML bool) EscapeFormatterOption

WithJSONConfig is an escape formatter option to set the JSON encoding prefix, indent value, and whether or not to escape HTML. Passed to the standard encoding/json.Encoder when a marshaler has not been set on the escape formatter.

func WithMask

func WithMask(mask string) EscapeFormatterOption

WithMask is an escape formatter option to set the mask used for empty headers.

func WithNumericLocale added in v0.10.0

func WithNumericLocale(enable bool, locale string) EscapeFormatterOption

WithNumericLocale sets the numeric locale printer.

func WithTimeFormat

func WithTimeFormat(timeFormat string) EscapeFormatterOption

WithTimeFormat is an escape formatter option to set the time format used for time values.

func WithTimeLocation added in v0.13.1

func WithTimeLocation(timeLocation *time.Location) EscapeFormatterOption

WithTimeLocation is an escape formatter option to set the time location used for time values.

type ExpandedEncoder

type ExpandedEncoder struct {
	TableEncoder
}

ExpandedEncoder is a buffered, lookahead expanded table encoder for result sets.

func (*ExpandedEncoder) Encode

func (enc *ExpandedEncoder) Encode(w io.Writer) error

Encode encodes a single result set to the writer using the formatting options specified in the encoder.

func (*ExpandedEncoder) EncodeAll

func (enc *ExpandedEncoder) EncodeAll(w io.Writer) error

EncodeAll encodes all result sets to the writer using the encoder settings.

type Formatter

type Formatter interface {
	// Header returns a slice of formatted values for the provided headers.
	Header([]string) ([]*Value, error)
	// Format returns a slice of formatted value the provided row values.
	Format([]interface{}) ([]*Value, error)
}

Formatter is the common interface for formatting values.

type JSONEncoder

type JSONEncoder struct {
	// contains filtered or unexported fields
}

JSONEncoder is an unbuffered JSON encoder for result sets.

func (*JSONEncoder) Encode

func (enc *JSONEncoder) Encode(w io.Writer) error

Encode encodes a single result set to the writer using the formatting options specified in the encoder.

func (*JSONEncoder) EncodeAll

func (enc *JSONEncoder) EncodeAll(w io.Writer) error

EncodeAll encodes all result sets to the writer using the encoder settings.

type LineStyle

type LineStyle struct {
	Top  [4]rune
	Mid  [4]rune
	Row  [4]rune
	Wrap [4]rune
	End  [4]rune
}

LineStyle is a table line style.

See the ASCII, OldASCII, and Unicode styles below for predefined table styles.

Tables generally look like the following:

+-----------+---------------------------+---+
| author_id |           name            | z |
+-----------+---------------------------+---+
|        14 | a       b       c       d |   |
|        15 | aoeu                     +|   |
|           | test                     +|   |
|           |                           |   |
+-----------+---------------------------+---+

When border is 0, then no surrounding borders will be shown:

author_id           name            z
--------- ------------------------- -
       14 a       b       c       d
       15 aoeu                     +
          test                     +

When border is 1, then a border between columns will be shown:

 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.

Tables using this style will look like the following:

+-----------+---------------------------+---+
| 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.

Tables using this style will look like the following:

+-----------+---------------------------+---+
| 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.

Tables using this style will look like the following:

╔═══════════╦═══════════════════════════╦═══╗
║ 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.

Tables using this style will look like the following:

┌───────────┬───────────────────────────┬───┐
│ author_id │           name            │ z │
├───────────┼───────────────────────────┼───┤
│        14 │ a       b       c       d │   │
│        15 │ aoeu                     ↵│   │
│           │ test                     ↵│   │
│           │                           │   │
└───────────┴───────────────────────────┴───┘

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a Encoder option.

func FormatterOptionFromMap added in v0.11.1

func FormatterOptionFromMap(opts map[string]string) Option

FormatterOptionFromMap builds formatter encoding options from the named options.

func WithBorder

func WithBorder(border int) Option

WithBorder is a encoder option to set the border size.

func WithColumnTypes added in v0.12.0

func WithColumnTypes(columnTypes func(ResultSet, []interface{}, int) error) Option

WithColumnTypes is a encoder option to set a func to use for building column types.

func WithColumnTypesFunc added in v0.12.0

func WithColumnTypesFunc(f func(*sql.ColumnType) (interface{}, error)) Option

WithColumnTypesFunc is a encoder option to set a func to build each column's type.

func WithCount

func WithCount(count int) Option

WithCount is a encoder option to set the buffered line count.

func WithEmpty

func WithEmpty(empty string) Option

WithEmpty is a encoder option to set the value used in empty (nil) cells.

func WithExecutor added in v0.5.0

func WithExecutor(executor func(io.Writer, interface{}) error) Option

WithExecutor is a encoder option to set the executor.

func WithFormatter

func WithFormatter(formatter Formatter) Option

WithFormatter is a encoder option to set a formatter for formatting values.

func WithFormatterOptions added in v0.7.1

func WithFormatterOptions(opts ...EscapeFormatterOption) Option

WithFormatterOptions is a encoder option to add additional formatter options.

func WithInline

func WithInline(inline bool) Option

WithInline is a encoder option to set the column headers as inline to the top line.

func WithLineStyle

func WithLineStyle(lineStyle LineStyle) Option

WithLineStyle is a encoder option to set the table line style.

func WithLowerColumnNames added in v0.7.5

func WithLowerColumnNames(lowerColumnNames bool) Option

WithLowerColumnNames is a encoder option to lower case column names when column names are all caps.

func WithMinExpandWidth added in v0.3.0

func WithMinExpandWidth(w int) Option

WithMinExpandWidth is a encoder option to set maximum width before switching to expanded format.

func WithMinPagerHeight added in v0.3.0

func WithMinPagerHeight(h int) Option

WithMinPagerHeight is a encoder option to set maximum height before redirecting output to pager.

func WithMinPagerWidth added in v0.3.0

func WithMinPagerWidth(w int) Option

WithMinPagerWidth is a encoder option to set maximum width before redirecting output to pager.

func WithNewline

func WithNewline(newline string) Option

WithNewline is a encoder option to set the newline.

func WithPager added in v0.3.0

func WithPager(p string) Option

WithPager is a encoder option to set the pager command.

func WithParams added in v0.5.0

func WithParams(params ...string) Option

WithParams is a view option to set the column parameters.

func WithQuote added in v0.5.0

func WithQuote(quote rune) Option

WithQuote is a encoder option to set the field quote.

func WithRawTemplate added in v0.5.0

func WithRawTemplate(text, typ string) Option

WithRawTemplate is a encoder option to set a raw template of either "text" or "html" type.

func WithSeparator added in v0.5.0

func WithSeparator(sep rune) Option

WithSeparator is a encoder option to set the field separator.

func WithSkipHeader added in v0.4.0

func WithSkipHeader(s bool) Option

WithSkipHeader is a encoder option to disable writing a header.

func WithSummary

func WithSummary(summary Summary) Option

WithSummary is a encoder option to set a table summary.

func WithTableAttributes added in v0.2.0

func WithTableAttributes(a string) Option

WithTableAttributes is a encoder option to set the table attributes.

func WithTemplate

func WithTemplate(name string) Option

WithTemplate is a encoder option to set a named template.

func WithTitle

func WithTitle(title string) Option

WithTitle is a encoder option to set the table title.

func WithUseColumnTypes added in v0.7.0

func WithUseColumnTypes(useColumnTypes bool) Option

WithUseColumnTypes is a encoder option to use the result set's column types.

func WithWidths

func WithWidths(widths ...int) Option

WithWidths is a encoder option to set (minimum) widths for a column.

type ResultSet

type ResultSet interface {
	Next() bool
	Scan(...interface{}) error
	Columns() ([]string, error)
	Close() error
	Err() error
	NextResultSet() bool
}

ResultSet is the shared interface for a result set.

func NewCrosstabView added in v0.5.0

func NewCrosstabView(resultSet ResultSet, opts ...Option) (ResultSet, error)

NewCrosstabView creates a new crosstab view.

type Summary added in v0.13.0

type Summary = map[int]func(io.Writer, int) (int, error)

Summary is the interface for a summary map.

func DefaultTableSummary

func DefaultTableSummary() Summary

DefaultTableSummary is the default table summary.

Default table summaries look like the following:

(3 rows)

type TableEncoder

type TableEncoder struct {
	// contains filtered or unexported fields
}

TableEncoder is a buffered, lookahead table encoder for result sets.

func (*TableEncoder) Encode

func (enc *TableEncoder) Encode(w io.Writer) error

Encode encodes a single result set to the writer using the formatting options specified in the encoder.

func (*TableEncoder) EncodeAll

func (enc *TableEncoder) EncodeAll(w io.Writer) error

EncodeAll encodes all result sets to the writer using the encoder settings.

type TemplateEncoder

type TemplateEncoder struct {
	// contains filtered or unexported fields
}

TemplateEncoder is an unbuffered template encoder for result sets.

func (*TemplateEncoder) Encode

func (enc *TemplateEncoder) Encode(w io.Writer) error

Encode encodes a single result set to the writer using the formatting options specified in the encoder.

func (*TemplateEncoder) EncodeAll

func (enc *TemplateEncoder) EncodeAll(w io.Writer) error

EncodeAll encodes all result sets to the writer using the encoder settings.

type UnalignedEncoder added in v0.5.0

type UnalignedEncoder struct {
	// contains filtered or unexported fields
}

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).

func (*UnalignedEncoder) Encode added in v0.5.0

func (enc *UnalignedEncoder) Encode(w io.Writer) error

Encode encodes a single result set to the writer using the formatting options specified in the encoder.

func (*UnalignedEncoder) EncodeAll added in v0.5.0

func (enc *UnalignedEncoder) EncodeAll(w io.Writer) error

EncodeAll encodes all result sets to the writer using the encoder settings.

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 indicates value alignment.
	Align Align
	// Raw tracks whether or not the value should be encoded or not.
	Raw bool
	// Quoted tracks whether or not a raw value should be quoted or not (ie,
	// contains a space or non printable character).
	Quoted bool
}

Value contains information pertaining to a formatted value.

func FormatBytes

func FormatBytes(src []byte, invalid []byte, invalidWidth int, isJSON, isRaw bool, sep, quote rune) *Value

FormatBytes parses src, saving escaped (encoded) and unescaped runes to a Value, along with tab and newline positions in the generated buf.

func (*Value) LineWidth

func (v *Value) LineWidth(l, offset, tab int) int

LineWidth returns the line width (in runes) of line l.

func (*Value) MaxWidth

func (v *Value) MaxWidth(offset, tab int) int

MaxWidth calculates the maximum width (in runes) of the longest line contained in Buf, relative to starting offset and the tab width.

func (Value) String added in v0.2.0

func (v Value) String() string

Directories

Path Synopsis
_example/example.go
_example/example.go
Package templates contains embedded templates for the tblfmt package.
Package templates contains embedded templates for the tblfmt package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL