Help us shape the future of Go! Take the 2026 Go Developer Survey

sdb

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package sdb is the API surface handed to Go scripts. A script is a plain Go file (package main) defining:

func Run(s *sdb.S) error

It can query any configured connection, loop with parameters, push results into the results view, and export in any supported format.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsCanceled

func IsCanceled(err error) bool

IsCanceled reports whether an error from Query or Exec is the user stopping the run, as opposed to a genuine failure — so a script can unwind quietly:

if err != nil {
	if sdb.IsCanceled(err) {
		return nil
	}
	return err
}

Errors from Copy, Reader and Writer carry context.Canceled instead: the etl package does not depend on db, so both are recognised here.

Types

type CopyOpts added in v0.9.0

type CopyOpts = etl.CopyOptions

CopyOpts shapes s.Copy: destination name, a Where or a whole Query as the source, a column subset, Create/Truncate of the destination, a per-row Transform. The zero value copies the whole table into an existing table of the same name. Set ProgressEvery to have the script output report the running row count.

type CopyStats added in v0.9.0

type CopyStats = etl.CopyStats

CopyStats reports a finished copy; its String() is a one-line summary.

type Plan

type Plan = explain.Plan

Plan is an explained statement: its steps (Root, Nodes), what it cost or took, and dbc's findings about it (Insights). See package explain.

type PlanText

type PlanText = explain.TextOptions

PlanText shapes Plan.Text: width, the metric bars are sized by, color, and whether the findings are appended.

type Reader added in v0.9.0

type Reader = etl.Reader

Reader streams a query's rows: for rd.Next() { row := rd.Row() }, then rd.Err(). Close it (defer rd.Close()) if you stop before the end.

type Result

type Result = model.Result

Result is the tabular result type scripts receive from Query.

type S

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

S is the session handle passed to a script's Run function.

func New

func New(mgr *db.Manager, show func(*model.Result), print func(string)) *S

New builds a script session. show receives results pushed via Show; print receives Print output (results table / log pane in the TUI, stdout in headless mode).

func (*S) Canceled

func (s *S) Canceled() bool

Canceled reports whether the user has stopped this run.

func (*S) CatalogChanged added in v0.9.1

func (s *S) CatalogChanged(conn string) bool

CatalogChanged reports whether the session has run a statement that may change conn's catalog (sqlsplit.ChangesCatalog: CREATE, ALTER, DROP, RENAME, COMMENT, ATTACH, DETACH) — through Query, Exec, or what Copy and Writer run to ready a destination. The host asks it once the script has returned, to decide whether the sidebar should list the tables again. Statements run through DB's raw handle are out of its sight, as they are out of the DDL log's.

func (*S) Conns

func (s *S) Conns() []string

Conns returns the configured connection names.

func (*S) Copy added in v0.9.0

func (s *S) Copy(src, dst, table string, opt CopyOpts) (CopyStats, error)

Copy copies table from connection src into connection dst:

st, err := s.Copy("prod", "local", "public.orders", sdb.CopyOpts{
	Create: true, Truncate: true, Where: "created_at >= now() - interval '7 days'",
})
s.Print("%s", st) // copied 48213 rows prod:public.orders → local:public.orders in 1.4s (direct COPY)

Postgres to Postgres without a Transform or Args streams COPY to COPY and never decodes a row; every other pairing goes row by row. Either way the destination is loaded in one transaction (with its Create and Truncate), so a failed or stopped copy leaves it as it was.

func (*S) Ctx

func (s *S) Ctx() context.Context

Ctx returns the session's context. Long-running scripts can select on s.Ctx().Done() (or check s.Canceled()) to bail out early.

func (*S) DB

func (s *S) DB(conn string) (*sql.DB, error)

DB exposes the raw *database/sql.DB for a connection — the escape hatch for transactions, prepared statements, or anything else database/sql can do.

func (*S) Exec

func (s *S) Exec(conn, stmt string, args ...any) (int64, error)

Exec runs a non-query statement and returns the rows affected. Its server notices are printed as Query's are.

func (*S) Explain

func (s *S) Explain(conn, stmt string, analyze bool) (*Plan, error)

Explain describes how conn's database runs stmt, as the TUI's Ctrl+X and `dbc explain` do. analyze runs the statement to measure it: on Postgres a write is analyzed inside a transaction that is rolled back; on the other engines a write is explained but not run. It runs on its own session, not one the script shares with Query.

p, err := s.Explain("pg", "SELECT * FROM orders WHERE user_id = 42", true)
s.Print("%s", p.Text(sdb.PlanText{Insights: true}))
for _, in := range p.Insights { if in.Severity != "info" { … } }

func (*S) Export

func (s *S) Export(r *Result, format, path string) error

Export renders a result in the named format (csv|tsv|markdown|html|json|text) and writes it to path — or to the system clipboard when path is empty.

func (*S) LogDDL added in v0.9.0

func (s *S) LogDDL() *S

LogDDL turns on the DDL log for the rest of the session: every data definition statement it runs (sqlsplit.IsDDL: CREATE, ALTER, DROP, TRUNCATE, RENAME, COMMENT, GRANT, REVOKE) is written to the script output, as Print does, the moment before it runs:

DDL warehouse: CREATE INDEX orders_user_idx ON orders (user_id)

That covers a script's Query and Exec and what Copy and Writer run to ready a destination (a Create's CREATE TABLE, Truncate, a Writer's Setup). Statements a script runs through DB's raw handle are out of its sight.

Logging before the statement, as Postgres's log_statement = 'ddl' does, rather than after it, puts a long CREATE INDEX or an ALTER stuck behind a lock in the log while it is still running. A Query or Exec that then fails adds a "DDL <conn> failed" line, since a script may carry on past the error; a failed Copy or Writer stops with an error naming the statement anyway.

script.Run turns this on for every script, whichever UI runs it. The session's other host, dbc copy, leaves it off. There is deliberately no way to turn it off again, so a script cannot opt out of its own log.

func (*S) Print

func (s *S) Print(format string, args ...any)

Print writes a Printf-style message to the script output.

func (*S) Query

func (s *S) Query(conn, query string, args ...any) (*Result, error)

Query runs a statement with parameters on the named connection and returns the result set. Use the placeholder style of the target driver ($1 for postgres/bytdb, ? for mysql/sqlite).

Server notices the statement raises (Postgres RAISE NOTICE and its kin) are written to the script output, as Print does, before Query returns — whether or not the statement failed.

func (*S) Reader added in v0.9.0

func (s *S) Reader(conn, query string, args ...any) (*Reader, error)

Reader runs query on conn and streams its rows. Use the placeholder style of the connection's driver ($1 postgres/bytdb, ? mysql/sqlite).

func (*S) Release added in v0.9.0

func (s *S) Release()

Release closes every Reader and rolls back every Writer the script left open. The host calls it when the script's Run returns (or panics): a forgotten Writer would otherwise hold a connection and an open transaction — and its locks — for the rest of the process. It rolls back rather than commits, because only an explicit Close says the load is complete. Both are no-ops on what the script already closed.

func (*S) Show

func (s *S) Show(r *Result)

Show pushes a result to the results view (TUI) or prints it (headless).

func (*S) WithContext

func (s *S) WithContext(ctx context.Context) *S

WithContext attaches a cancellation context to the session and returns it. The host — not the script — sets this: when the user stops a run, the query in flight is aborted and every later Query or Exec fails immediately, so a looping script unwinds through its own error handling.

func (*S) Writer added in v0.9.0

func (s *S) Writer(conn, table string, cols []string, opt WriteOpts) (*Writer, error)

Writer starts a load into table on conn; rows passed to Write line up with cols. Nothing is visible to other sessions until Close commits.

type WriteOpts added in v0.9.0

type WriteOpts = etl.WriteOptions

WriteOpts shapes s.Writer: Setup statements and Truncate run first, in the load's transaction; BatchSize tunes INSERT batching off Postgres.

type Writer added in v0.9.0

type Writer = etl.Writer

Writer loads rows into one table in one transaction: w.Write(row) per row, then w.Close() to commit. defer w.Abort() rolls back on any early return; it is a no-op after Close.

Directories

Path Synopsis
Package sdbapi describes the sdb package — what a script can call on s *sdb.S, and the fields and methods of the types it hands back — as data, for the script editor's completion and hover in dbc web.
Package sdbapi describes the sdb package — what a script can call on s *sdb.S, and the fields and methods of the types it hands back — as data, for the script editor's completion and hover in dbc web.

Jump to

Keyboard shortcuts

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