format

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateWidth

func CalculateWidth(columnNames []string, verboseHeaders []string, wc *widthCalculator, screenWidth int, rows []Row) []int

CalculateWidth calculates optimal column widths for table rendering using the default GreedyFrequencyStrategy. columnNames are the plain column names, verboseHeaders are optionally the verbose header strings (with type info, may contain newlines).

func CalculateWidthWithStrategy added in v0.29.0

func CalculateWidthWithStrategy(ws enums.WidthStrategy, columnNames []string, verboseHeaders []string, wc *widthCalculator, screenWidth int, rows []Row) []int

CalculateWidthWithStrategy calculates optimal column widths using the specified strategy. verboseHeaders are passed as the headers parameter so that strategies count them exactly once.

func ExecuteWithFormatter

func ExecuteWithFormatter(formatter StreamingFormatter, rows []Row, columnNames []string, config FormatConfig) error

ExecuteWithFormatter executes buffered formatting using a streaming formatter. Rows are passed as previewRows to InitFormat, enabling formatters like table to calculate optimal column widths from all rows before rendering. Non-table formatters ignore previewRows.

func Formatters added in v0.28.0

func Formatters(row Row) []any

Formatters converts a Row to []any for tablewriter per-cell formatting. Each Cell implements tw.Formatter, so tablewriter calls Format() per cell.

func IsNoWrap added in v0.29.0

func IsNoWrap(c Cell) bool

IsNoWrap reports whether c is a NoWrapCell.

func MaxByWithIdx

func MaxByWithIdx[O cmp.Ordered, E any](fallback E, f func(E) O, seq iter.Seq[E]) (int, E)

MaxByWithIdx returns the index and value of the element with the maximum key.

func MaxWithIdx

func MaxWithIdx[E cmp.Ordered](fallback E, seq iter.Seq[E]) (int, E)

MaxWithIdx returns the index and value of the maximum element in seq.

func RegisterFormatFunc added in v0.28.0

func RegisterFormatFunc(factory FormatFuncFactory, modes ...Mode)

RegisterFormatFunc registers a FormatFuncFactory for the given modes. This allows external packages to add custom output formats (e.g., SQL export) without the format package depending on their implementation.

func RegisterStreamingFormatter added in v0.28.0

func RegisterStreamingFormatter(factory StreamingFormatterFactory, modes ...Mode)

RegisterStreamingFormatter registers a StreamingFormatterFactory for the given modes. This allows external packages to add custom streaming output formats without the format package depending on their implementation.

func RegisterValueFormatMode added in v0.28.0

func RegisterValueFormatMode(vfm ValueFormatMode, modes ...Mode)

RegisterValueFormatMode declares the ValueFormatMode required by the given modes. Formatters call this during init() to declare their value formatting requirements. Modes that don't register default to DisplayValues.

func Texts added in v0.28.0

func Texts(row Row) []string

Texts extracts the raw text from each Cell, returning a plain string slice. Used when a formatter needs to pass values to APIs that only accept []string.

func WriteTable

func WriteTable(w io.Writer, rows []Row, columnNames []string, config FormatConfig, screenWidth int, mode Mode) error

WriteTable writes the table to the provided writer.

func WriteTableWithParams

func WriteTableWithParams(w io.Writer, rows []Row, columnNames []string, config FormatConfig, screenWidth int, mode Mode, params TableParams) error

WriteTableWithParams writes the table with additional table-specific parameters. This delegates to TableStreamingFormatter (non-streaming mode) as the single table rendering engine, eliminating duplicate table rendering code.

Types

type CSVFormatter

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

CSVFormatter provides shared CSV formatting logic for both buffered and streaming modes.

func NewCSVFormatter

func NewCSVFormatter(out io.Writer, skipHeaders bool) *CSVFormatter

NewCSVFormatter creates a new CSV formatter.

func (*CSVFormatter) FinishFormat

func (f *CSVFormatter) FinishFormat() error

FinishFormat completes CSV output.

func (*CSVFormatter) InitFormat

func (f *CSVFormatter) InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

InitFormat writes CSV headers if needed.

func (*CSVFormatter) WriteRow

func (f *CSVFormatter) WriteRow(row Row) error

WriteRow writes a single CSV row.

type Cell added in v0.28.0

type Cell interface {
	// Format returns styled text for display (may include ANSI codes).
	// Called by tablewriter via tw.Formatter interface when FormatConfig.Styled is true.
	// When Styled is false, callers should use RawText() instead.
	Format() string

	// RawText returns plain text without styling.
	// Used by non-table formatters (CSV, XML, etc.) that must not contain ANSI codes.
	RawText() string

	// WithText creates a new Cell with replaced text but preserved styling behavior.
	// Used by table formatters after width-wrapping to carry styling through.
	WithText(text string) Cell
}

Cell is the interface for a single formatted cell. The format package is agnostic to the concrete type — it only calls these methods. Concrete adapters (PlainCell, StyledCell) implement styling logic.

Cell also satisfies tw.Formatter (via Format()), enabling per-cell styling when passed to tablewriter.

type ColumnHint added in v0.29.0

type ColumnHint struct {
	// PreferredMinWidth is the width needed to avoid wrapping all NoWrap cells
	// in this column. Strategies should try to satisfy this but may go below
	// if space is tight.
	PreferredMinWidth int
}

ColumnHint carries per-column metadata that strategies can use for allocation.

type FormatConfig

type FormatConfig struct {
	TabWidth        int
	Verbose         bool
	SkipColumnNames bool
	SQLTableName    string
	SQLBatchSize    int64
	PreviewRows     int64
	Styled          bool                // When true, table output uses Cell.Format() (may include ANSI codes). When false, uses RawText().
	WidthStrategy   enums.WidthStrategy // Column width allocation algorithm. Zero value = GreedyFrequency (default).
	TabVisualize    bool                // When true, visualize tab characters with → symbol in table output.
}

FormatConfig holds configuration values needed by formatters. This replaces the dependency on *systemVariables, exposing only the fields that formatters actually use.

type FormatFunc

type FormatFunc func(out io.Writer, rows []Row, columnNames []string, config FormatConfig, screenWidth int) error

FormatFunc is a function type that formats and writes result data. It takes an output writer, rows, column names, config, and screen width.

func NewFormatter

func NewFormatter(mode Mode) (FormatFunc, error)

NewFormatter creates a new formatter function based on the display mode. Built-in modes (TABLE, CSV, etc.) are handled directly. Custom modes are looked up in the registry (see RegisterFormatFunc).

type FormatFuncFactory added in v0.28.0

type FormatFuncFactory func(mode Mode) (FormatFunc, error)

FormatFuncFactory creates a buffered FormatFunc for the given mode. The mode parameter allows a single factory to handle multiple related modes.

type GreedyFrequencyStrategy added in v0.29.0

type GreedyFrequencyStrategy struct{}

GreedyFrequencyStrategy implements the original frequency-based greedy expansion algorithm. It starts with header-proportional widths, then greedily expands columns that would benefit the most cells (highest frequency count).

func (GreedyFrequencyStrategy) CalculateWidths added in v0.29.0

func (GreedyFrequencyStrategy) CalculateWidths(wc *widthCalculator, availableWidth int,
	headers []string, rows []Row, hints []ColumnHint,
) []int

type HTMLFormatter

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

HTMLFormatter provides streaming HTML table output.

func NewHTMLFormatter

func NewHTMLFormatter(out io.Writer, skipHeaders bool) *HTMLFormatter

NewHTMLFormatter creates a new HTML streaming formatter.

func (*HTMLFormatter) FinishFormat

func (f *HTMLFormatter) FinishFormat() error

FinishFormat completes the HTML table.

func (*HTMLFormatter) InitFormat

func (f *HTMLFormatter) InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

InitFormat writes the HTML table opening and headers.

func (*HTMLFormatter) WriteRow

func (f *HTMLFormatter) WriteRow(row Row) error

WriteRow writes a single HTML table row.

type MarginalCostStrategy added in v0.29.0

type MarginalCostStrategy struct{}

MarginalCostStrategy minimizes total wrap-lines across all cells using a greedy max-heap approach. At each step, it allocates one extra character to the column that yields the largest reduction in total wrap-lines.

Complexity: O(availableWidth * log(numCols)).

func (MarginalCostStrategy) CalculateWidths added in v0.29.0

func (MarginalCostStrategy) CalculateWidths(wc *widthCalculator, availableWidth int,
	headers []string, rows []Row, hints []ColumnHint,
) []int

type Mode added in v0.28.0

type Mode string

Mode represents the output format mode as a string. Built-in modes are defined as constants below. Custom modes can be registered via RegisterFormatFunc and RegisterStreamingFormatter.

Mode values use UPPER_SNAKE_CASE to match the enumer-generated strings of enums.DisplayMode, enabling conversion via format.Mode(dm.String()).

const (
	ModeUnspecified        Mode = "UNSPECIFIED"
	ModeTable              Mode = "TABLE"
	ModeTableComment       Mode = "TABLE_COMMENT"
	ModeTableDetailComment Mode = "TABLE_DETAIL_COMMENT"
	ModeVertical           Mode = "VERTICAL"
	ModeTab                Mode = "TAB"
	ModeHTML               Mode = "HTML"
	ModeXML                Mode = "XML"
	ModeCSV                Mode = "CSV"
)

func (Mode) IsTableMode added in v0.28.0

func (m Mode) IsTableMode() bool

IsTableMode returns true if the mode is one of the table display modes.

type NoWrapCell added in v0.29.0

type NoWrapCell struct {
	Cell
}

NoWrapCell wraps any Cell to indicate its content should preferably not be wrapped. Strategies use this to compute PreferredMinWidth per column so that short values like NULL, true, false are kept intact when space allows.

func (NoWrapCell) WithText added in v0.29.0

func (c NoWrapCell) WithText(s string) Cell

type PlainCell added in v0.28.0

type PlainCell struct {
	Text string
}

PlainCell is the simplest Cell implementation — no styling. Used by client-side statements (SHOW, DESCRIBE, DUMP) and tests.

func (PlainCell) Format added in v0.28.0

func (c PlainCell) Format() string

func (PlainCell) RawText added in v0.28.0

func (c PlainCell) RawText() string

func (PlainCell) WithText added in v0.28.0

func (c PlainCell) WithText(s string) Cell

type ProportionalStrategy added in v0.29.0

type ProportionalStrategy struct{}

ProportionalStrategy allocates column widths proportionally to each column's natural width (the maximum width across header and all rows). It starts with header-proportional + minColumnWidth floor, then distributes remaining space proportionally to each column's deficit.

func (ProportionalStrategy) CalculateWidths added in v0.29.0

func (ProportionalStrategy) CalculateWidths(wc *widthCalculator, availableWidth int,
	headers []string, rows []Row, hints []ColumnHint,
) []int

type Row

type Row = []Cell

Row is a slice of Cell representing one row of formatted data.

func StringsToRow added in v0.28.0

func StringsToRow(ss ...string) Row

StringsToRow converts a slice of strings to a Row of PlainCell. Used by client-side statements and tests that construct rows from plain strings.

type StreamingFormatter

type StreamingFormatter interface {
	// InitFormat is called once with column names and configuration.
	// For table formats, previewRows contains the first N rows for width calculation.
	// For other formats, previewRows may be empty as they don't need preview.
	InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

	// WriteRow outputs a single row.
	WriteRow(row Row) error

	// FinishFormat completes the output (e.g., closing tags, final flush).
	FinishFormat() error
}

StreamingFormatter defines the interface for format-specific streaming output. Each format (CSV, TAB, etc.) implements this interface to handle streaming output.

func NewStreamingFormatter

func NewStreamingFormatter(mode Mode, out io.Writer, config FormatConfig) (StreamingFormatter, error)

NewStreamingFormatter creates a streaming formatter for the given display mode. Note: Table formats (Table, TableComment, TableDetailComment) require screenWidth and should be created with NewTableStreamingFormatter directly by the caller. Built-in modes are handled directly. Custom modes are looked up in the registry.

type StreamingFormatterFactory added in v0.28.0

type StreamingFormatterFactory func(mode Mode, out io.Writer, config FormatConfig) (StreamingFormatter, error)

StreamingFormatterFactory creates a StreamingFormatter for the given mode. The mode parameter allows a single factory to handle multiple related modes.

type StyledCell added in v0.28.0

type StyledCell struct {
	Text  string
	Style string // ANSI SGR sequence, e.g. "\033[32m" for green, "\033[1m" for bold
}

StyledCell renders values with a configurable ANSI SGR sequence. Used for type-based styling (e.g., STRING → green, INT64 → bold, NULL → dim). The Style field holds an ANSI SGR sequence (e.g., "\033[32m" for green). In the styled path, wrapRowStyled handles SGR carry-over across line breaks, so Format() only needs to wrap the entire text — no per-line logic needed.

func (StyledCell) Format added in v0.28.0

func (c StyledCell) Format() string

func (StyledCell) RawText added in v0.28.0

func (c StyledCell) RawText() string

func (StyledCell) WithText added in v0.28.0

func (c StyledCell) WithText(s string) Cell

type TabFormatter

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

TabFormatter provides shared tab-separated formatting logic.

func NewTabFormatter

func NewTabFormatter(out io.Writer, skipHeaders bool) *TabFormatter

NewTabFormatter creates a new tab-separated formatter.

func (*TabFormatter) FinishFormat

func (f *TabFormatter) FinishFormat() error

FinishFormat completes tab-separated output.

func (*TabFormatter) InitFormat

func (f *TabFormatter) InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

InitFormat writes tab-separated headers if needed.

func (*TabFormatter) WriteRow

func (f *TabFormatter) WriteRow(row Row) error

WriteRow writes a single tab-separated row.

type TableParams

type TableParams struct {
	// VerboseHeaders contains header strings rendered with type information.
	// These may include newlines (e.g., "Name\nSTRING") and are used for display
	// when Verbose mode is enabled.
	VerboseHeaders []string
	ColumnAlign    []tw.Align
}

TableParams holds additional parameters for table formatting that are not part of the standard FormatConfig (used only by table format).

type TableStreamingFormatter

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

TableStreamingFormatter provides table output using tablewriter. It supports both streaming mode (output as rows arrive) and buffered mode (collect all rows, then render). This is the single table rendering engine used by both the streaming and buffered code paths.

func NewTableFormatterForBuffered added in v0.28.0

func NewTableFormatterForBuffered(out io.Writer, config FormatConfig, screenWidth int, mode Mode, params TableParams) *TableStreamingFormatter

NewTableFormatterForBuffered creates a table formatter for buffered rendering. Used by the buffered code path where all rows are available before formatting. Supports TableParams (verbose headers, column alignment) and all table modes (TABLE, TABLE_COMMENT, TABLE_DETAIL_COMMENT).

func NewTableStreamingFormatter

func NewTableStreamingFormatter(out io.Writer, config FormatConfig, screenWidth int, previewSize int, mode Mode) *TableStreamingFormatter

NewTableStreamingFormatter creates a streaming table formatter. Used by the streaming pipeline where rows are output as they arrive. previewSize determines how many rows to buffer for width calculation (0 = headers-only). mode specifies the table mode (ModeTable, ModeTableComment, ModeTableDetailComment).

func (*TableStreamingFormatter) FinishFormat

func (f *TableStreamingFormatter) FinishFormat() error

FinishFormat completes the table output.

func (*TableStreamingFormatter) InitFormat

func (f *TableStreamingFormatter) InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

InitFormat initializes the table with column information and preview rows for width calculation.

func (*TableStreamingFormatter) WriteRow

func (f *TableStreamingFormatter) WriteRow(row Row) error

WriteRow writes a single table row.

type ValueFormatMode added in v0.28.0

type ValueFormatMode int

ValueFormatMode specifies how row values should be formatted before being passed to a formatter. This allows formatters to declare their value formatting requirements, decoupling the value formatting decision from mode-name checks in execute_sql.go.

const (
	// DisplayValues formats values for human display (e.g., NULL as "NULL" text,
	// timestamps in readable format). This is the default for built-in modes.
	DisplayValues ValueFormatMode = iota

	// SQLLiteralValues formats values as valid SQL literals (e.g., NULL keyword,
	// strings quoted, bytes as hex). Used by SQL export modes.
	SQLLiteralValues
)

func ValueFormatModeFor added in v0.28.0

func ValueFormatModeFor(mode Mode) ValueFormatMode

ValueFormatModeFor returns the ValueFormatMode declared for the given Mode. Built-in modes return DisplayValues. Registered modes return their declared value.

type VerticalFormatter

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

VerticalFormatter provides shared vertical formatting logic.

func NewVerticalFormatter

func NewVerticalFormatter(out io.Writer) *VerticalFormatter

NewVerticalFormatter creates a new vertical formatter.

func (*VerticalFormatter) FinishFormat

func (f *VerticalFormatter) FinishFormat() error

FinishFormat completes vertical format output.

func (*VerticalFormatter) InitFormat

func (f *VerticalFormatter) InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

InitFormat prepares vertical format output.

func (*VerticalFormatter) WriteRow

func (f *VerticalFormatter) WriteRow(row Row) error

WriteRow writes a single row in vertical format.

type WidthCount

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

WidthCount tracks the width and frequency of column values.

func (WidthCount) Count

func (wc WidthCount) Count() int

Count returns the frequency count.

func (WidthCount) Length

func (wc WidthCount) Length() int

Length returns the width value.

type WidthStrategy added in v0.29.0

type WidthStrategy interface {
	CalculateWidths(wc *widthCalculator, availableWidth int,
		headers []string, rows []Row, hints []ColumnHint) []int
}

WidthStrategy defines the interface for pluggable column width algorithms. Strategies receive availableWidth already overhead-subtracted (caller handles table border overhead). The returned slice must have len(headers) elements, each >= minColumnWidth.

func NewWidthStrategy added in v0.29.0

func NewWidthStrategy(ws enums.WidthStrategy) WidthStrategy

NewWidthStrategy returns a WidthStrategy for the given enum value.

type XMLFormatter

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

XMLFormatter provides streaming XML output.

func NewXMLFormatter

func NewXMLFormatter(out io.Writer, skipHeaders bool) *XMLFormatter

NewXMLFormatter creates a new XML streaming formatter.

func (*XMLFormatter) FinishFormat

func (f *XMLFormatter) FinishFormat() error

FinishFormat completes the XML output.

func (*XMLFormatter) InitFormat

func (f *XMLFormatter) InitFormat(columnNames []string, config FormatConfig, previewRows []Row) error

InitFormat writes the XML declaration and starts the result set.

func (*XMLFormatter) WriteRow

func (f *XMLFormatter) WriteRow(row Row) error

WriteRow writes a single XML row.

Jump to

Keyboard shortcuts

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