dbx

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: AGPL-3.0 Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dbx runs classified SQL against a conn and turns the result into plain JSON values. Without write it uses a read-only transaction, so the database itself refuses changes the classifier may have missed.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Activity

func Activity(ctx context.Context, db *sql.DB, kind string, all bool, timeout time.Duration) ([]map[string]any, error)

Activity lists sessions: by default only those running something.

func ClassifyMongo added in v0.7.0

func ClassifyMongo(cmd bson.D) driver.Verdict

ClassifyMongo rates a command document.

func Dump

func Dump(ctx context.Context, db *sql.DB, kind string, o DumpOptions, w io.Writer) error

Dump writes a plain SQL backup of the database, made by komando itself (no pg_dump or mysqldump). It reads inside one consistent snapshot. Objects it cannot write faithfully stop it with their names, so a dump never silently misses something.

func GrantSQL added in v0.3.0

func GrantSQL(ctx context.Context, db *sql.DB, kind string, g Grant) (string, error)

GrantSQL builds the statement for g.

func Grants added in v0.3.0

func Grants(ctx context.Context, db *sql.DB, kind, user, host string, timeout time.Duration) ([]map[string]any, error)

Grants lists what a user may do.

func Info

func Info(ctx context.Context, db *sql.DB, kind string, timeout time.Duration) (map[string]any, error)

Info is the server at a glance: version, uptime, size, connections, and whether it is a primary or a read-only replica.

func IsMariaDB

func IsMariaDB(ctx context.Context, q querier) bool

IsMariaDB reports whether a mysql conn is MariaDB, whose syntax differs in places (ANALYZE instead of EXPLAIN ANALYZE).

func Kill

func Kill(ctx context.Context, db *sql.DB, kind string, pid int64, session bool) error

Kill cancels the session's running query, or with session ends the connection.

func Locks

func Locks(ctx context.Context, db *sql.DB, kind string, timeout time.Duration) ([]map[string]any, error)

Locks lists sessions that wait for a lock, with the session holding it.

func MongoInfo added in v0.7.0

func MongoInfo(ctx context.Context, m *Mongo) (map[string]any, error)

MongoInfo is `db info`: version, role in a replica set, and sizes.

func MongoRules added in v0.7.0

func MongoRules() []driver.Rule

MongoRules lists the rules ClassifyMongo can report.

func MongoVersion added in v0.7.0

func MongoVersion(ctx context.Context, m *Mongo) string

MongoVersion is the server version, for `conn test`.

func Open

func Open(ctx context.Context, rawURL string, t driver.Target, password string, dial DialFunc, readOnly bool, appName string) (*sql.DB, error)

Open connects to t. dial is nil for a direct connection. readOnly opens file databases read-only as well.

func ParseMongoCommand added in v0.7.0

func ParseMongoCommand(text string) (bson.D, string, error)

ParseMongoCommand reads a command document written as JSON (MongoDB Extended JSON: {"$oid": ...}, {"$date": ...} work). A "$db" key names the database for this command and is taken out.

func Restore

func Restore(ctx context.Context, db *sql.DB, kind string, r io.Reader) error

Restore runs a plain SQL backup (komando's own, pg_dump's or mysqldump's) without psql or mysql. PostgreSQL restores in one transaction and stops at the first error, like psql --single-transaction -v ON_ERROR_STOP=1; COPY ... FROM stdin blocks are streamed. MySQL runs the statements in order and understands DELIMITER. The file must have passed driver.CheckRestore.

func Session

func Session(ctx context.Context, db *sql.DB, kind string, pid int64) (map[string]any, error)

Session reads one session by its id, so a kill can say what it stops.

func Sizes

func Sizes(ctx context.Context, db *sql.DB, kind string, limit int, timeout time.Duration) (map[string]any, error)

Sizes lists databases, the biggest tables and the biggest indexes.

func UserChange added in v0.3.0

func UserChange(ctx context.Context, db *sql.DB, kind, action string, u UserSpec, dry bool) (string, error)

UserChange runs an action on a user (add, passwd, rm) and returns the statement as it may be shown. With dry, nothing runs.

func Users added in v0.3.0

func Users(ctx context.Context, db *sql.DB, kind string, timeout time.Duration) ([]map[string]any, error)

Users lists users and roles with their main attributes.

Types

type Column

type Column struct {
	Name string `json:"name"`
	Type string `json:"type,omitempty"`
}

Column describes a result column.

type Constraint

type Constraint struct {
	Name       string `json:"name"`
	Type       string `json:"type"` // foreign key | check | unique | exclusion
	Definition string `json:"definition"`
}

type DialFunc

type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)

DialFunc opens a TCP connection, possibly through an SSH host.

type DumpOptions

type DumpOptions struct {
	SchemaOnly bool
	Tables     []string
}

DumpOptions narrow a built-in dump.

type Grant added in v0.3.0

type Grant struct {
	User   string
	Host   string   // MySQL account host
	Privs  []string // SELECT, INSERT ...; empty with Role
	On     string   // database:NAME, schema:NAME, table:NAME, all-tables:SCHEMA (PostgreSQL); DB.* or DB.TABLE (MySQL)
	Role   string   // grant membership in this role instead
	Revoke bool
}

Grant is a GRANT or REVOKE: privileges on one object, or a role.

type Index

type Index struct {
	Name       string `json:"name"`
	Definition string `json:"definition,omitempty"`
}

type Mongo added in v0.7.0

type Mongo struct {
	C  *mongo.Client
	DB string
}

Mongo is an open MongoDB conn and the database its commands use.

func OpenMongo added in v0.7.0

func OpenMongo(ctx context.Context, rawURL string, t driver.Target, password string, dial DialFunc, appName string, timeout time.Duration) (*Mongo, error)

OpenMongo connects to a MongoDB conn: the URL as the driver reads it (hosts, replicaSet, authSource, tls), the password from the vault, every member through dial when there is one, and ?ca= for its certificate.

func (*Mongo) Close added in v0.7.0

func (m *Mongo) Close()

Close disconnects.

type MongoCollection added in v0.7.0

type MongoCollection struct {
	Name      string       `json:"name"`
	Type      string       `json:"type,omitempty"` // view, timeseries
	Documents int64        `json:"documents"`      // an estimate, from the collection's metadata
	Indexes   []string     `json:"indexes,omitempty"`
	Fields    []MongoField `json:"fields,omitempty"`
	Sampled   int          `json:"sampled,omitempty"`
}

MongoCollection is one collection in `db schema`: its size and indexes, and with a name given, the fields of a sample of its documents.

func MongoSchema added in v0.7.0

func MongoSchema(ctx context.Context, m *Mongo, names []string) ([]MongoCollection, error)

MongoSchema lists the collections, or describes the named ones from a sample of up to 100 documents each.

type MongoField added in v0.7.0

type MongoField struct {
	Path  string   `json:"path"`
	Types []string `json:"types"`
	Seen  int      `json:"seen"`
}

MongoField is a field path seen in sampled documents, with its types and how many of them had it.

type MongoResult added in v0.7.0

type MongoResult struct {
	Documents []any  `json:"documents,omitempty"`
	Count     int    `json:"count"`
	Truncated string `json:"truncated,omitempty"` // "documents" (--limit) or "bytes" (--max-output)
	Reply     any    `json:"reply,omitempty"`
}

MongoResult is what one command gave: documents for the commands that return a cursor (find, aggregate, listCollections, ...), else the reply.

func RunMongo added in v0.7.0

func RunMongo(ctx context.Context, m *Mongo, db string, cmd bson.D, limit, maxBytes int) (*MongoResult, error)

RunMongo sends cmd to database db and reads at most limit documents (0: no limit) and maxBytes of them.

type Options

type Options struct {
	Write    bool
	DryRun   bool
	Limit    int // max rows per statement
	MaxBytes int // rough cap on the JSON size of all rows
	Timeout  time.Duration
	Args     []any
}

Options control one Run.

type Result

type Result struct {
	Results    []StatementResult `json:"results"`
	Committed  bool              `json:"committed"`
	RolledBack bool              `json:"rolled_back,omitempty"`
}

Result is the outcome of a Run.

func Run

func Run(ctx context.Context, db *sql.DB, kind string, plan driver.SQLPlan, o Options) (*Result, error)

Run executes plan on db in one transaction. Without Write the transaction is read-only and always rolled back; with DryRun it is rolled back too. Statements that cannot run in a transaction must be alone in the plan; in a dry run they are reported but not executed.

type StatementResult

type StatementResult struct {
	SQL          string   `json:"sql"`
	Keyword      string   `json:"keyword"`
	Risk         string   `json:"risk"`
	Columns      []Column `json:"columns,omitempty"`
	Rows         [][]any  `json:"-"`
	RowCount     int      `json:"-"`
	Truncated    string   `json:"truncated,omitempty"` // which cap cut the rows: "rows" (--limit) or "bytes" (--max-output)
	RowsAffected *int64   `json:"rows_affected,omitempty"`
	Skipped      string   `json:"skipped,omitempty"` // why it did not run (dry run of a non-rollbackable statement)
}

StatementResult is the outcome of one statement. A statement that returns rows has columns, rows and row_count (rows may be empty); one that changes rows has rows_affected; other statements (DDL, SET) have neither.

func (StatementResult) MarshalJSON

func (r StatementResult) MarshalJSON() ([]byte, error)

type Table

type Table struct {
	Schema      string        `json:"schema,omitempty"`
	Name        string        `json:"name"`
	Type        string        `json:"type"`
	RowEstimate *int64        `json:"row_estimate,omitempty"`
	Columns     []TableColumn `json:"columns,omitempty"`
	Indexes     []Index       `json:"indexes,omitempty"`
	// Constraints are foreign keys, checks and unique constraints.
	Constraints []Constraint `json:"constraints,omitempty"`
}

Table describes one table or view. Columns and Indexes are filled only when the table was asked for by name.

func Schema

func Schema(ctx context.Context, db *sql.DB, kind string, names []string, timeout time.Duration) ([]Table, error)

Schema lists tables, or describes the named ones (NAME or SCHEMA.NAME). It runs in a read-only transaction.

type TableColumn

type TableColumn struct {
	Name       string  `json:"name"`
	Type       string  `json:"type"`
	Nullable   bool    `json:"nullable"`
	Default    *string `json:"default,omitempty"`
	PrimaryKey bool    `json:"primary_key,omitempty"`
	// Identity says the database numbers the column itself: "auto_increment"
	// (MySQL, SQLite AUTOINCREMENT), "always" or "by default" (PostgreSQL).
	Identity string `json:"identity,omitempty"`
}

type UnsupportedError

type UnsupportedError struct{ Objects []string }

UnsupportedError lists objects the built-in dump does not write.

func (*UnsupportedError) Error

func (e *UnsupportedError) Error() string

type UserSpec added in v0.3.0

type UserSpec struct {
	Name     string
	Host     string // MySQL account host; "%" when empty
	Password string
	NoLogin  bool // PostgreSQL: a role that cannot log in (a group)
}

UserSpec is a user to create or change.

Jump to

Keyboard shortcuts

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