Documentation
¶
Overview ¶
Package output provides interfaces and implementations for outputting data and messages. All sq command output should be via one of the writer interfaces defined in this package. The RecordWriterAdapter type provides a bridge between the asynchronous libsq.RecordWriter interface and the simpler synchronous RecordWriter interface defined here.
Index ¶
- Constants
- type ConfigWriter
- type ErrorWriter
- type KeyringMigrateRow
- type KeyringPruneRow
- type KeyringRef
- type KeyringWriter
- type MetadataWriter
- type NewRecordWriterFunc
- type PingWriter
- type Printing
- type RecordInsertWriter
- type RecordWriter
- type RecordWriterAdapter
- type SQLPayload
- type SQLSources
- type SQLWriter
- type SourceWriter
- type StmtExecWriter
- type VersionWriter
- type Writers
Constants ¶
const ( KeyringStatusReferenced = "referenced" // in config and present in the keyring KeyringStatusOrphan = "orphan" // in the keyring, referenced by no source KeyringStatusMissing = "missing" // referenced by a source, absent from the keyring )
KeyringStatus* enumerate the status values surfaced by KeyringWriter.List. The string forms are part of the JSON contract and must not change casually.
const ( KeyringMigrateStatusPlanned = "planned" // dry-run: source would be migrated KeyringMigrateStatusSkip = "skip" // not eligible (no password, malformed, etc.) KeyringMigrateStatusMigrated = "migrated" // applied: keyring entry written, YAML updated KeyringMigrateStatusFailed = "failed" // applied: a step failed (mint/write/save) )
KeyringMigrateStatus enumerates the status values surfaced by KeyringWriter.Migrate. The string forms are part of the JSON contract and must not change casually.
const ( KeyringPruneStatusPlanned = "planned" // dry-run: entry would be deleted KeyringPruneStatusDeleted = "deleted" // applied: entry was deleted KeyringPruneStatusFailed = "failed" // applied: deletion failed )
KeyringPruneStatus* enumerate the status values surfaced by KeyringWriter.Prune. The string forms are part of the JSON contract.
const ( KeyringKindID = "id" // sq-minted opaque Crockford ID KeyringKindNamed = "named" // user-named entry )
KeyringKind* classify a keyring entry's path shape, for display only.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ConfigWriter ¶ added in v0.34.0
type ConfigWriter interface {
// Location prints the config location. The origin may be empty, or one
// of "flag", "env", "default".
Location(loc string, origin config.Origin) error
// Opt prints a single options.Opt.
Opt(o options.Options, opt options.Opt) error
// Options prints config options.
Options(reg *options.Registry, o options.Options) error
// SetOption is called when an option is set.
SetOption(o options.Options, opt options.Opt) error
// UnsetOption is called when an option is unset.
UnsetOption(opt options.Opt) error
// CacheLocation prints the cache location.
CacheLocation(loc string) error
// CacheStat prints cache info. Set arg size to -1 to indicate
// that the size of the cache could not be calculated.
CacheStat(loc string, enabled bool, size int64) error
}
ConfigWriter prints config.
type ErrorWriter ¶
type ErrorWriter interface {
// Error outputs error conditions. It's possible that systemErr and
// humanErr differ; systemErr is the error that occurred, and humanErr
// is the error that should be presented to the user.
Error(systemErr, humanErr error)
}
ErrorWriter outputs errors.
type KeyringMigrateRow ¶ added in v0.54.0
type KeyringMigrateRow struct {
Handle string `json:"handle"`
Status string `json:"status"`
Reason string `json:"reason,omitempty"` // populated for "skip"
NewLocation string `json:"new_location,omitempty"` // populated for "migrated"
Error string `json:"error,omitempty"` // populated for "failed"
}
KeyringMigrateRow describes one source's outcome in a migrate plan (dry-run) or migrate result (applied). Status takes one of the KeyringMigrateStatus* constants.
type KeyringPruneRow ¶ added in v0.54.0
type KeyringPruneRow struct {
Path string `json:"path"`
Kind string `json:"kind"`
Status string `json:"status"`
Error string `json:"error,omitempty"` // populated for "failed"
}
KeyringPruneRow describes one orphaned entry in a prune plan (dry-run) or result (applied). Kind is informational; Status takes one of the KeyringPruneStatus* constants.
type KeyringRef ¶ added in v0.54.0
type KeyringRef struct {
Status string `json:"status"`
Path string `json:"path"`
Handle string `json:"handle"`
Driver string `json:"driver"`
}
KeyringRef is one row of "sq config keyring ls" output. Each row describes one keyring entry: either a ${keyring:<path>} reference reachable from the active source collection, or an entry found in the OS keyring. Status classifies the row.
type KeyringWriter ¶ added in v0.54.0
type KeyringWriter interface {
// List prints the result of "sq config keyring ls".
List(refs []KeyringRef) error
// Get prints the result of "sq config keyring get". When revealed
// is false, the writer should omit the secret value (printing only
// metadata) so callers can pass it through verbatim regardless of
// the --reveal flag.
Get(path, value string, revealed bool) error
// Created prints confirmation of "sq config keyring create".
Created(path string) error
// Updated prints confirmation of "sq config keyring update".
Updated(path string) error
// Rm prints confirmation of "sq config keyring rm". Deleting a
// non-existent entry still calls this — rm is idempotent.
Rm(path string) error
// Migrate prints per-source migration outcomes. When dryRun is true
// the rows describe a plan (statuses: "planned" or "skip"); when
// false the rows describe applied outcomes (statuses: "migrated",
// "skip", or "failed").
Migrate(rows []KeyringMigrateRow, dryRun bool) error
// Prune prints the orphaned entries removed by "sq config keyring
// prune". When dryRun is true every row's status is "planned"; when
// false no row is "planned" — each is "deleted" or "failed".
Prune(rows []KeyringPruneRow, dryRun bool) error
}
KeyringWriter prints output for the "sq config keyring" command group. Implementations live in cli/output/tablew (text/table) and cli/output/jsonw (JSON).
type MetadataWriter ¶
type MetadataWriter interface {
// TableMetadata writes the table metadata.
TableMetadata(tblMeta *metadata.Table) error
// SourceMetadata writes the source metadata.
SourceMetadata(srcMeta *metadata.Source, showSchema bool) error
// DBProperties writes the DB properties.
DBProperties(props map[string]any) error
// DriverMetadata writes the metadata for the drivers.
DriverMetadata(drvrs []driver.Metadata) error
// Catalogs writes the list of catalogs.
Catalogs(currentCatalog string, catalogs []string) error
// Schemata writes the list of schemas.
Schemata(currentSchema string, schemas []*metadata.Schema) error
}
MetadataWriter can output metadata.
type NewRecordWriterFunc ¶ added in v0.36.0
type NewRecordWriterFunc func(out io.Writer, pr *Printing) RecordWriter
NewRecordWriterFunc is a func type that returns an output.RecordWriter.
type PingWriter ¶
type PingWriter interface {
// Open opens the writer to write the supplied sources.
Open(srcs []*source.Source) error
// Result prints a ping result. The ping succeeded if
// err is nil. If err is context.DeadlineExceeded, the d
// arg will be the timeout value.
Result(src *source.Source, d time.Duration, err error) error
// Close is called after all results have been received.
Close() error
}
PingWriter writes ping results.
type Printing ¶ added in v0.34.0
type Printing struct {
// FormatDatetime formats a timestamp e.g. 2020-11-12T13:14:15Z.
// Defaults to timez.DefaultDatetime.
FormatDatetime func(time time.Time) string
// FormatTime formats a time of day, e.g. 13:14:15.
// Defaults to timez.DefaultTime.
FormatTime func(time time.Time) string
// FormatDate formats a date, e.g. 2020-11-12.
// Defaults to timez.DefaultDate.
FormatDate func(time time.Time) string
// GeneratedAt is the time the output was generated (UTC). When non-zero,
// inspect's Markdown/HTML schema documents include a provenance line
// ("`sq inspect` @ `<timestamp>`"). A zero value omits it (e.g. in unit
// tests, so golden output stays deterministic).
GeneratedAt time.Time
// Active is the color for an active handle (or group, etc).
Active *color.Color
// Bold is the color for bold elements.
Bold *color.Color
// Bool is the color for boolean values.
Bool *color.Color
// Bytes is the color for byte / binary values.
Bytes *color.Color
// Datetime is the color for time-related values.
Datetime *color.Color
// Diff contains colors for diff output.
Diff *diffdoc.Colors
// Disabled is the color for disabled elements.
Disabled *color.Color
// Duration is the color for time duration values.
Duration *color.Color
// Enabled is the color for enabled elements.
Enabled *color.Color
// Error is the color for error elements such as an error message.
Error *color.Color
// ErrorHilite is the color used to highlight the offending span
// of input in a syntax error report.
ErrorHilite *color.Color
// Faint is the color for faint elements - the opposite of Hilite.
Faint *color.Color
// Handle is the color for source handles such as "@sakila"
Handle *color.Color
// Header is the color for header elements in a table.
Header *color.Color
// Hilite is the color for highlighted elements.
Hilite *color.Color
// Key is the color for keys such as a JSON field name.
Key *color.Color
// Location is the color for Source.Location values.
Location *color.Color
// Normal is the default color.
Normal *color.Color
// Null is the color for null.
Null *color.Color
// Number is the color for number values, including int, float, decimal etc.
Number *color.Color
// Punc is the color for punctuation such as colons, braces, etc.
Punc *color.Color
// Stack is the color for stack traces.
Stack *color.Color
// StackError is the color for errors attached to a stack trace.
StackError *color.Color
// StackErrorType is the color for the error types attached to a stack trace.
StackErrorType *color.Color
// String is the color for string values.
String *color.Color
// Subdued is the color for visually secondary elements — items
// included for completeness but already conveyed elsewhere.
// Typically renders as [color.Faint] + [color.Italic]; the faint
// attribute matches plain [Faint] intensity while the italic
// attribute makes the element visually distinct from [Faint]
// content on the same line.
Subdued *color.Color
// Success is the color for success elements.
Success *color.Color
// Warning is the color for warning elements.
Warning *color.Color
// NewBufferFn returns a new [ioz.Buffer] instance; it should be preferred
// over [bytes.Buffer] when dealing large/unbounded data.
NewBufferFn func() ioz.Buffer
// Indent is the indent string to use when pretty-printing,
// typically two spaces.
Indent string
// ExcelDatetimeFormat is the format string for datetime values.
// See excelw.OptDatetimeFormat.
ExcelDatetimeFormat string
// ExcelDateFormat is the format string for date values.
// See excelw.OptDateFormat.
ExcelDateFormat string
// ExcelTimeFormat is the format string for time values.
// See excelw.OptTimeFormat.
ExcelTimeFormat string
// FlushThreshold is the size in bytes after which an output writer
// should flush any internal buffer.
FlushThreshold int
// ShowHeader indicates that a header (e.g. a header row) should
// be printed where applicable.
ShowHeader bool
// Verbose indicates that verbose output should be printed where
// applicable.
Verbose bool
// Compact indicates that output should not be pretty-printed.
// Typically this means indentation, new lines, etc., but
// varies by output format.
Compact bool
// Redact indicates that sensitive fields (such as passwords)
// should be redacted (hidden/masked).
Redact bool
// FormatDatetimeAsNumber indicates that datetime values should be
// rendered as naked numbers (instead of as a string) if possible.
// See cli.OptDatetimeFormatAsNumber.
FormatDatetimeAsNumber bool
// FormatTimeAsNumber indicates that time values should be
// rendered as naked numbers (instead of as a string) if possible.
// See cli.OptTimeFormatAsNumber.
FormatTimeAsNumber bool
// FormatDateAsNumber indicates that date values should be
// rendered as naked numbers (instead of as a string) if possible.
// See cli.OptDateFormatAsNumber.
FormatDateAsNumber bool
// DecimalAsNumber renders decimal values as bare numbers rather than
// quoted strings, in formats that distinguish the two (JSON, YAML).
// See cli.OptFormatDecimal and issue #846.
DecimalAsNumber bool
// contains filtered or unexported fields
}
Printing describes color and pretty-printing options.
func NewPrinting ¶ added in v0.34.0
func NewPrinting() *Printing
NewPrinting returns a Printing instance. Color and pretty-print are enabled. The default indent is two spaces.
func (*Printing) EnableColor ¶ added in v0.34.0
EnableColor enables or disables all colors.
func (*Printing) IsMonochrome ¶ added in v0.34.0
IsMonochrome returns true if in monochrome (no color) mode. Default is false (color enabled) for a new instance.
type RecordInsertWriter ¶ added in v0.48.11
type RecordInsertWriter interface {
// RecordsInserted outputs record insertion details, indicating that a count
// of rowsInserted rows were inserted into tbl in destination target.
RecordsInserted(ctx context.Context, target *source.Source, tbl string,
rowsInserted int64, elapsed time.Duration) error
}
RecordInsertWriter outputs details of record insertion into a destination table.
One could ask: why not add the RecordInsertWriter.RecordsInserted method to the RecordWriter interface, instead of creating a new interface? This is because RecordInsertWriter is effectively a user-facing logger, for which sq only guarantees text (tablew) and JSON (jsonw). It doesn't really make sense to force the Excel writer (xlsxw) to implement a "N rows affected" mechanism.
Note that RecordInsertWriter is distinct from StmtExecWriter. StmtExecWriter generically outputs the details of any SQL statement execution, which could be an INSERT, but also could be UPDATE, CREATE, etc.). Meanwhile, RecordInsertWriter outputs the results of the "sq --insert" mechanism, which pipes the results (records) of a query to a destination source/table.
type RecordWriter ¶
type RecordWriter interface {
// Open instructs the writer to prepare to write records
// described by recMeta.
Open(ctx context.Context, recMeta record.Meta) error
// WriteRecords writes rec to the destination.
WriteRecords(ctx context.Context, recs []record.Record) error
// Flush advises the writer to flush any internal
// buffer. Note that the writer may implement an independent
// flushing strategy, or may not buffer at all.
Flush(ctx context.Context) error
// Close closes the writer after flushing any internal buffer.
Close(ctx context.Context) error
}
RecordWriter is an interface for writing records to a destination. In effect, it is a synchronous counterpart to the asynchronous libsq.RecordWriter interface. Being a synchronous interface, it is less tricky to implement than libsq.RecordWriter. The RecordWriterAdapter type defined in this package bridges the two interfaces.
The Open method must be invoked before WriteRecords. Close must be invoked when all records are written. The Flush method advises the writer to flush any internal buffers.
type RecordWriterAdapter ¶
type RecordWriterAdapter struct {
// FlushAfterN indicates that the writer's Flush method
// should be invoked after N invocations of WriteRecords.
// A value of 0 will flush every time a record is written.
// Set to -1 to disable.
FlushAfterN int64
// FlushAfterDuration controls whether the writer's Flush method
// is invoked periodically. A duration <= 0 disables periodic flushing.
FlushAfterDuration time.Duration
// contains filtered or unexported fields
}
RecordWriterAdapter implements libsq.RecordWriter and wraps an output.RecordWriter instance, providing a bridge between the asynchronous libsq.RecordWriter and synchronous output.RecordWriter interfaces.
Note that a writer implementation such as the JSON or CSV writer could directly implement libsq.RecordWriter. But that interface is non-trivial to implement, hence this bridge type.
The FlushAfterN and FlushAfterDuration fields control flushing of the writer.
func NewRecordWriterAdapter ¶
func NewRecordWriterAdapter(ctx context.Context, rw RecordWriter) *RecordWriterAdapter
NewRecordWriterAdapter returns a new RecordWriterAdapter. The size of the internal buffer is controlled by driver.OptTuningRecChanSize.
func (*RecordWriterAdapter) Open ¶
func (w *RecordWriterAdapter) Open(ctx context.Context, cancelFn context.CancelFunc, recMeta record.Meta, ) (chan<- record.Record, <-chan error, error)
Open implements libsq.RecordWriter.
func (*RecordWriterAdapter) Wait ¶
func (w *RecordWriterAdapter) Wait() (written int64, err error)
Wait implements libsq.RecordWriter.
type SQLPayload ¶ added in v0.52.0
type SQLPayload struct {
// Args is the --arg map supplied to the query, if any.
// Values are already substituted into SQL; Args is reported so
// consumers can re-render later with different values.
Args map[string]string `json:"args,omitempty" yaml:"args,omitempty"`
// SLQ is the input SLQ query (post-preprocessing).
SLQ string `json:"slq" yaml:"slq"`
// SQL is the rendered SQL query that would be executed.
SQL string `json:"sql" yaml:"sql"`
// Dialect is the lower-case dialect / driver-type name
// (e.g. "postgres", "sqlite3", "mysql") that SQL was rendered for.
Dialect string `json:"dialect" yaml:"dialect"`
// Sources is the [SQLSources] describing where the SQL would
// execute (Target) and which user-named handles the SLQ
// references (Inputs).
Sources SQLSources `json:"sources" yaml:"sources"`
}
SQLPayload is the structured form of a --render-sql result: enough information to either eyeball the SQL or round-trip it back into a future render. Consumed by SQLWriter implementations and produced by the slq command's --render-sql path.
type SQLSources ¶ added in v0.52.0
type SQLSources struct {
// Target is the handle of the source the rendered SQL would be
// executed against. For single-source queries this is the user
// source itself. For cross-source queries it is the synthetic
// join DB's handle (typically "@join_…"), distinct from any of
// the inputs in Inputs.
Target string `json:"target" yaml:"target"`
// Inputs is the set of input source handles referenced by the
// SLQ. For single-source queries it has one element equal to
// Target. For cross-source queries it lists the user sources
// whose data would be staged into the join DB named by Target.
Inputs []string `json:"inputs" yaml:"inputs"`
}
SQLSources groups the source handles involved in a --render-sql payload, distinguishing where the rendered SQL would execute (Target) from the user-named inputs the SLQ references (Inputs).
type SQLWriter ¶ added in v0.52.0
type SQLWriter interface {
// Render writes p to the writer's output. It is expected to be
// called exactly once per invocation.
Render(p SQLPayload) error
}
SQLWriter writes an SQLPayload in some format-specific representation: plain SQL text, a JSON/YAML object, etc. Used by the slq command's --render-sql path.
type SourceWriter ¶
type SourceWriter interface {
// Collection outputs details of the collection. Specifically it prints
// the sources from coll's active group.
Collection(coll *source.Collection) error
// Source outputs details of the source.
Source(coll *source.Collection, src *source.Source) error
// Added is called when src is added to the collection.
Added(coll *source.Collection, src *source.Source) error
// Removed is called when sources are removed from the collection.
Removed(srcs ...*source.Source) error
// Moved is called when a source is moved from old to nu.
Moved(coll *source.Collection, old, nu *source.Source) error
// Group prints the group.
Group(group *source.Group) error
// SetActiveGroup is called when the group is set.
SetActiveGroup(group *source.Group) error
// Groups prints a list of groups.
Groups(tree *source.Group) error
}
SourceWriter can output data source details.
type StmtExecWriter ¶ added in v0.48.11
type StmtExecWriter interface {
// StmtExecuted writes SQL statement execution details.
StmtExecuted(ctx context.Context, target *source.Source, affected int64, elapsed time.Duration) error
}
StmtExecWriter outputs details of a successfully executed SQL statement.
Note that StmtExecWriter is distinct from RecordInsertWriter. StmtExecWriter generically outputs the details of any SQL statement execution, which could be an INSERT, but also could be UPDATE, CREATE, etc.). Meanwhile, RecordInsertWriter outputs the results of the "sq --insert" mechanism, which pipes the results (records) of a query to a destination source/table.
type VersionWriter ¶ added in v0.21.0
type VersionWriter interface {
// Version prints version info. Arg latestVersion is the latest
// version available from the homebrew repository. The value
// may be empty.
Version(bi buildinfo.Info, latestVersion string, si hostinfo.Info) error
}
VersionWriter prints the CLI version.
type Writers ¶ added in v0.36.0
type Writers struct {
// PrOut is the printing config for stdout.
PrOut *Printing
// PrErr is the printing config for stderr.
PrErr *Printing
Record RecordWriter
RecordInsert RecordInsertWriter
StmtExec StmtExecWriter
Metadata MetadataWriter
Source SourceWriter
Error ErrorWriter
Ping PingWriter
Version VersionWriter
Config ConfigWriter
SQL SQLWriter
Keyring KeyringWriter
}
Writers is a container for the various output Writers.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package commonw contains miscellaneous common output writer functionality.
|
Package commonw contains miscellaneous common output writer functionality. |
|
Package csvw implements writers for CSV.
|
Package csvw implements writers for CSV. |
|
Package erdimgw implements output.MetadataWriter for the "png-erd" and "svg-erd" formats: sq inspect's schema entity-relationship diagram rendered to a PNG or SVG image file.
|
Package erdimgw implements output.MetadataWriter for the "png-erd" and "svg-erd" formats: sq inspect's schema entity-relationship diagram rendered to a PNG or SVG image file. |
|
Package htmlw implements a RecordWriter for HTML.
|
Package htmlw implements a RecordWriter for HTML. |
|
internal
|
|
|
erddot
Package erddot generates Graphviz DOT source describing an entity-relationship diagram from sq table metadata.
|
Package erddot generates Graphviz DOT source describing an entity-relationship diagram from sq table metadata. |
|
erdmodel
Package erdmodel holds the renderer-neutral parts of sq's entity-relationship model shared by the diagram renderers (the Mermaid source generator in package mermaid and the Graphviz DOT generator in package erddot).
|
Package erdmodel holds the renderer-neutral parts of sq's entity-relationship model shared by the diagram renderers (the Mermaid source generator in package mermaid and the Graphviz DOT generator in package erddot). |
|
mermaid
Package mermaid generates Mermaid.js erDiagram source from sq table metadata.
|
Package mermaid generates Mermaid.js erDiagram source from sq table metadata. |
|
Package jsonw implements output writers for JSON.
|
Package jsonw implements output writers for JSON. |
|
Package markdownw implements writers for Markdown.
|
Package markdownw implements writers for Markdown. |
|
Package mermaidw implements output.MetadataWriter for the "mermaid-erd" format: sq inspect's bare Mermaid.js erDiagram source, with none of the surrounding schema document that the markdownw and htmlw writers produce.
|
Package mermaidw implements output.MetadataWriter for the "mermaid-erd" format: sq inspect's bare Mermaid.js erDiagram source, with none of the surrounding schema document that the markdownw and htmlw writers produce. |
|
Package sqlw provides output.SQLWriter implementations for the --render-sql mode of the slq command, where the rendered SQL is printed instead of being executed.
|
Package sqlw provides output.SQLWriter implementations for the --render-sql mode of the slq command, where the rendered SQL is printed instead of being executed. |
|
Package tablew implements text table output writers.
|
Package tablew implements text table output writers. |
|
internal
Package tablewriter creates & generates text based table
|
Package tablewriter creates & generates text based table |
|
Package xlsxw implements output writers for Microsoft Excel.
|
Package xlsxw implements output writers for Microsoft Excel. |
|
Package xmlw implements output writers for XML.
|
Package xmlw implements output writers for XML. |
|
Package yamlw implements output writers for YAML.
|
Package yamlw implements output writers for YAML. |