dbviewer

package
v1.5.11 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 21 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 dbviewer runs read-only (and, when explicitly allowed, write) SQL against a managed database by exec'ing the engine's own client inside its container. Credentials never leave the container.

Index

Constants

View Source
const (
	KindQuery   = "query"
	KindExplain = "explain"
	KindShow    = "show"
	KindWrite   = "write"
)

Statement kinds the guard classifies an accepted statement into.

View Source
const (
	EnvQueryTimeout  = "APP_DB_QUERY_TIMEOUT"
	EnvQueryMaxRows  = "APP_DB_QUERY_MAX_ROWS"
	EnvQueryMaxBytes = "APP_DB_QUERY_MAX_BYTES"
	EnvQueryMaxCell  = "APP_DB_QUERY_MAX_CELL_BYTES"
	EnvSchemaMaxRows = "APP_DB_SCHEMA_MAX_ROWS"
	EnvQueryMaxSQL   = "APP_DB_QUERY_MAX_SQL_BYTES"
	EnvHistoryKeep   = "APP_DB_QUERY_HISTORY_KEEP"
)

Environment variables that tune the console. Each has a default so an unset variable behaves the same on every install.

View Source
const (
	OpContains = "contains"
	OpEquals   = "equals"
	OpIsNull   = "is_null"
	OpNotNull  = "not_null"
)

Filter operators accepted by a table page.

View Source
const MaxFilters = 8

MaxFilters bounds how many column filters one page request may combine.

Variables

View Source
var (
	ErrEmpty             = errors.New("statement is empty")
	ErrMultiStatement    = errors.New("only a single statement is allowed")
	ErrBackslash         = errors.New("backslash is not allowed in console statements")
	ErrControlChar       = errors.New("statement contains a control character")
	ErrUnterminated      = errors.New("unterminated string, identifier, or comment")
	ErrExecutableComment = errors.New("executable comments are not allowed")
	ErrUnicodeEscape     = errors.New("unicode escape syntax is not allowed")
	ErrNotAllowed        = errors.New("statement type is not allowed in read-only mode")
	ErrDenied            = errors.New("statement uses a function or keyword that is not allowed")
)

Rejection reasons, exported so handlers can map them to a 400.

View Source
var ErrDynamoDenied = errors.New("dynamodb request is not allowed")

ErrDynamoDenied reports a request the DynamoDB guard refuses.

View Source
var ErrMongoDenied = errors.New("mongodb request is not allowed")

ErrMongoDenied reports a request the Mongo guard refuses.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound reports a table or column the database does not have.

View Source
var ErrTimeout = errors.New("query exceeded the configured timeout")

ErrTimeout reports that the statement ran past the configured timeout.

Functions

func CapabilityEngines

func CapabilityEngines() []string

CapabilityEngines lists the engines in the registry (for tests and docs).

func HistoryKeepFromEnv

func HistoryKeepFromEnv(lookup func(string) (string, bool)) int

HistoryKeepFromEnv is how many history rows to keep per user and database.

Types

type Capabilities

type Capabilities struct {
	Browse        Capability `json:"browse"`
	Query         Capability `json:"query"`
	WriteQuery    Capability `json:"write_query"`
	Edit          Capability `json:"edit"`
	Import        Capability `json:"import"`
	Export        Capability `json:"export"`
	Explain       Capability `json:"explain"`
	SchemaObjects Capability `json:"schema_objects"`
	KeyBrowse     Capability `json:"key_browse"`
	Documents     Capability `json:"documents"`
	Aggregation   Capability `json:"aggregation"`
	Stats         Capability `json:"stats"`
	Indexes       Capability `json:"indexes"`
	Users         Capability `json:"users"`
}

Capabilities lists every explorer feature the UI can render for an engine.

type Capability

type Capability struct {
	Status Status `json:"status"`
	Reason string `json:"reason,omitempty"`
}

Capability is one feature switch. Reason is an i18n key suffix the UI maps to text, empty when the capability is available.

type Column

type Column struct {
	Name       string `json:"name"`
	Type       string `json:"type"`
	Nullable   bool   `json:"nullable"`
	Default    string `json:"default,omitempty"`
	PrimaryKey bool   `json:"primary_key"`
}

Column is one table column.

type Dialect

type Dialect string

Dialect selects the lexing and deny-list rules for one SQL family.

const (
	DialectPostgres Dialect = "postgres"
	DialectMySQL    Dialect = "mysql"
	DialectMariaDB  Dialect = "mariadb"
)

Supported dialects.

const DialectDynamoDB Dialect = "dynamodb"

DialectDynamoDB marks a DynamoDB local target. It is never a SQL dialect: only typed requests reach it.

const DialectMongo Dialect = "mongodb"

DialectMongo marks a MongoDB target. It is never a SQL dialect: only the typed Mongo requests below reach it.

type DynamoLimits

type DynamoLimits struct {
	PageItems    int
	PageItemsMax int
	DescribeMax  int
}

DynamoLimits holds the page sizes, read from env like the other viewer limits.

func DynamoLimitsFromEnv

func DynamoLimitsFromEnv(lookup func(string) (string, bool)) DynamoLimits

DynamoLimitsFromEnv reads the page limits, falling back to defaults for unset or invalid values.

type DynamoOp

type DynamoOp string

DynamoOp is one allow-listed read operation. Writes and table changes have no constant here, so they cannot be built.

const (
	DynamoListTables    DynamoOp = "ListTables"
	DynamoDescribeTable DynamoOp = "DescribeTable"
	DynamoDescribeTTL   DynamoOp = "DescribeTimeToLive"
	DynamoQuery         DynamoOp = "Query"
	DynamoScan          DynamoOp = "Scan"
)

Allowed operations; the value is the DynamoDB API action name.

type DynamoPrepared

type DynamoPrepared struct {
	Op          DynamoOp
	Limit       int
	Fingerprint string
	// contains filtered or unexported fields
}

DynamoPrepared is a request the guard accepted, with its body ready to send.

func CheckDynamo

func CheckDynamo(req DynamoRequest, lim Limits, dl DynamoLimits) (DynamoPrepared, error)

CheckDynamo validates a request against the allow-list and the limits, then builds the body from re-serialised data.

type DynamoRequest

type DynamoRequest struct {
	Op    DynamoOp
	Table string
	Index string
	// KeyName and KeyValue are the partition key equality of a Query; KeyValue is DynamoDB JSON such as {"S":"x"}.
	KeyName  string
	KeyValue json.RawMessage
	Sort     *DynamoSortCond
	Limit    int
	// StartKey is the previous page's LastEvaluatedKey, DynamoDB JSON.
	StartKey json.RawMessage
	// Confirm must be true for a Scan: it reads every item it passes and is slow on large tables.
	Confirm bool
	// StartTable pages ListTables.
	StartTable string
}

DynamoRequest is the typed input; no field is ever executed or concatenated into a command.

type DynamoResult

type DynamoResult struct {
	Tables           []string          `json:"tables,omitempty"`
	LastTable        string            `json:"last_table,omitempty"`
	Table            json.RawMessage   `json:"table,omitempty"`
	TTL              json.RawMessage   `json:"ttl,omitempty"`
	Items            []json.RawMessage `json:"items"`
	Count            int               `json:"count"`
	ScannedCount     int               `json:"scanned_count"`
	LastKey          json.RawMessage   `json:"last_evaluated_key,omitempty"`
	ConsumedCapacity json.RawMessage   `json:"consumed_capacity,omitempty"`
	Truncated        bool              `json:"truncated"`
	DurationMs       int64             `json:"duration_ms"`
}

DynamoResult is the engine answer, trimmed to the caps. Items stay DynamoDB JSON.

type DynamoSortCond

type DynamoSortCond struct {
	Name  string          `json:"name"`
	Op    string          `json:"op"`
	Value json.RawMessage `json:"value"`
}

DynamoSortCond is an optional condition on the sort key of a Query.

type EngineCapabilities

type EngineCapabilities struct {
	Engine       string       `json:"engine"`
	Kind         Kind         `json:"kind"`
	Planned      bool         `json:"planned"`
	Capabilities Capabilities `json:"capabilities"`
}

EngineCapabilities is the registry row for one engine. Planned marks an engine whose explorer is being built, so the UI shows "not ready".

func CapabilitiesFor

func CapabilitiesFor(engine string) EngineCapabilities

CapabilitiesFor returns the registry row for an engine. Unknown engines get an all unsupported row so the UI degrades instead of failing.

func ExternalCapabilitiesFor

func ExternalCapabilitiesFor(engine string) EngineCapabilities

ExternalCapabilitiesFor is CapabilitiesFor for a connected (not run) database: the viewer reaches only SQL engines there, and writes need the managed path.

type Evidence

type Evidence struct {
	DatabaseSizeBytes int64    `json:"database_size_bytes"`
	SchemasScanned    int      `json:"schemas_scanned"`
	UserTables        int64    `json:"user_tables"`
	ExcludedSchemas   []string `json:"excluded_schemas"`
}

Evidence is what the catalog says about a database independent of the schema listing, so an empty listing can be checked against it.

type Execer

type Execer interface {
	ExecWithInput(ctx context.Context, containerID string, cmd []string, stdin io.Reader) (io.ReadCloser, error)
}

Execer is the slice of docker.Runtime the console needs.

type Filter

type Filter struct {
	Column string `json:"column"`
	Op     string `json:"op"`
	Value  string `json:"value"`
}

Filter restricts one column of a table page.

type ForeignKey

type ForeignKey struct {
	Name       string   `json:"name"`
	Schema     string   `json:"schema"`
	Table      string   `json:"table"`
	Columns    []string `json:"columns"`
	RefSchema  string   `json:"ref_schema"`
	RefTable   string   `json:"ref_table"`
	RefColumns []string `json:"ref_columns"`
}

ForeignKey is one foreign key constraint. Schema and Table name the table that owns it; RefSchema and RefTable the table it points at.

type Index

type Index struct {
	Name       string `json:"name"`
	Definition string `json:"definition"`
	Unique     bool   `json:"unique"`
	Primary    bool   `json:"primary"`
}

Index is one table index.

type Kind

type Kind string

Kind groups engines by the shape of their data, so the UI picks a layout.

const (
	KindSQL      Kind = "sql"
	KindDocument Kind = "document"
	KindKeyValue Kind = "keyvalue"
	KindSearch   Kind = "search"
	KindStats    Kind = "stats"
	// KindTable is a key and attribute table store with typed items.
	KindTable Kind = "table"
)

Engine kinds the UI renders.

type Limits

type Limits struct {
	Timeout      time.Duration
	MaxRows      int
	MaxBytes     int
	MaxCellBytes int
	SchemaRows   int
	SQLBytes     int
}

Limits bounds one console execution.

func LimitsFromEnv

func LimitsFromEnv(lookup func(string) (string, bool)) Limits

LimitsFromEnv reads the limits, falling back to defaults for unset or invalid values.

type MongoOp

type MongoOp string

MongoOp is one allow-listed read operation.

const (
	MongoListDatabases   MongoOp = "listDatabases"
	MongoListCollections MongoOp = "listCollections"
	MongoCollections     MongoOp = "collections"
	MongoFind            MongoOp = "find"
	MongoCountDocuments  MongoOp = "countDocuments"
	MongoEstimatedCount  MongoOp = "estimatedDocumentCount"
	MongoGetIndexes      MongoOp = "getIndexes"
	MongoStats           MongoOp = "stats"
)

Allowed operations. Anything else is rejected before a script is built.

type MongoQuery

type MongoQuery struct {
	Op          MongoOp
	Limit       int
	Fingerprint string
	// contains filtered or unexported fields
}

MongoQuery is a request the guard accepted, with its script ready to run.

func CheckMongo

func CheckMongo(req MongoRequest, lim Limits) (MongoQuery, error)

CheckMongo validates a request against the allow-list and the limits and builds the script from the re-serialised, validated data only.

type MongoRequest

type MongoRequest struct {
	Op         MongoOp
	Database   string
	Collection string
	Filter     json.RawMessage
	Sort       json.RawMessage
	Projection json.RawMessage
	// After is the _id of the last document of the previous page.
	After json.RawMessage
	Limit int
}

MongoRequest is the typed input; no field is ever executed as script text.

type MongoResult

type MongoResult struct {
	Documents []json.RawMessage `json:"documents"`
	Truncated bool              `json:"truncated"`
	// NextAfter is the canonical extended JSON _id of the last document when more exist.
	NextAfter  json.RawMessage `json:"next_after,omitempty"`
	DurationMs int64           `json:"duration_ms"`
}

MongoResult holds the lines one Mongo operation produced.

type Page

type Page struct {
	Result
	HasMore bool `json:"has_more"`
}

Page is one page of rows. HasMore is true when rows exist past this page.

type PageQuery

type PageQuery struct {
	Schema, Table string
	Limit, Offset int
	SortColumn    string
	SortDesc      bool
	FilterColumn  string
	FilterOp      string
	FilterValue   string
	Filters       []Filter
}

PageQuery asks for one page of a table. FilterColumn/FilterOp/FilterValue are the first filter; Filters adds more, all combined with AND.

type QueryError

type QueryError struct{ Message string }

QueryError carries the database's own error text, which is safe to show: it describes the caller's statement and never contains credentials.

func (*QueryError) Error

func (e *QueryError) Error() string

type RedisClient

type RedisClient struct {
	ID    string `json:"id"`
	Addr  string `json:"addr"`
	Age   int64  `json:"age"`
	Idle  int64  `json:"idle"`
	Flags string `json:"flags"`
	DB    string `json:"db"`
	Cmd   string `json:"cmd"`
	User  string `json:"user"`
}

RedisClient is one connected client. Names can hold secrets, so they are not returned.

func ParseRedisClients

func ParseRedisClients(lines []string) []RedisClient

ParseRedisClients reads CLIENT LIST lines, keeping only safe fields.

type RedisClients

type RedisClients struct {
	Clients   []RedisClient `json:"clients"`
	Truncated bool          `json:"truncated"`
}

RedisClients is the capped CLIENT LIST result.

type RedisEntry

type RedisEntry struct {
	ID    string      `json:"id,omitempty"`
	Field string      `json:"field,omitempty"`
	Value string      `json:"value,omitempty"`
	Score string      `json:"score,omitempty"`
	Pairs []RedisPair `json:"pairs,omitempty"`
}

RedisEntry is one element of a typed value: a list item, set member, hash field, sorted set member with score, or stream entry with its pairs.

type RedisInfo

type RedisInfo struct {
	Sections []RedisInfoSection `json:"sections"`
}

RedisInfo is the INFO panel. Paths, run ids and anything secret-shaped are never in the allow list.

func ParseRedisInfo

func ParseRedisInfo(lines []string) RedisInfo

ParseRedisInfo splits INFO output into allow listed sections.

type RedisInfoField

type RedisInfoField struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

RedisInfoField is one allow listed INFO value.

type RedisInfoSection

type RedisInfoSection struct {
	Name   string           `json:"name"`
	Fields []RedisInfoField `json:"fields"`
}

RedisInfoSection is one INFO section with only its allow listed fields.

type RedisKey

type RedisKey struct {
	Key  string `json:"key"`
	Type string `json:"type"`
	TTL  int64  `json:"ttl"`
}

RedisKey is one scanned key with its type and TTL (seconds, -1 for none).

type RedisPair

type RedisPair struct {
	Field string `json:"field"`
	Value string `json:"value"`
}

RedisPair is one field and value of a stream entry.

type RedisScan

type RedisScan struct {
	Cursor string     `json:"cursor"`
	Keys   []RedisKey `json:"keys"`
}

RedisScan is one SCAN step. Cursor "0" means the scan is complete.

type RedisSlowEntry

type RedisSlowEntry struct {
	ID         int64  `json:"id"`
	Time       int64  `json:"time"`
	DurationUS int64  `json:"durationUs"`
	Command    string `json:"command"`
	ArgCount   int    `json:"argCount"`
	Client     string `json:"client,omitempty"`
}

RedisSlowEntry never carries arguments: only the command name, how many arguments there were and their total size.

func ParseRedisSlowlog

func ParseRedisSlowlog(lines []string) []RedisSlowEntry

ParseRedisSlowlog reads `redis-cli --no-raw SLOWLOG GET` output. Argument values are never collected: only the command name (the first element of field 4) and the number of further argument lines are kept. Labels are right aligned past nine items, so lines are read by trimmed position.

type RedisSlowlog

type RedisSlowlog struct {
	Entries   []RedisSlowEntry `json:"entries"`
	Truncated bool             `json:"truncated"`
}

RedisSlowlog is the capped SLOWLOG GET result.

type RedisValue

type RedisValue struct {
	Type      string   `json:"type"`
	TTL       int64    `json:"ttl"`
	Lines     []string `json:"lines"`
	Truncated bool     `json:"truncated"`
	// Typed detail (redis_typed.go). Size and MemoryBytes are -1 when unknown.
	Encoding    string       `json:"encoding"`
	Size        int64        `json:"size"`
	MemoryBytes int64        `json:"memoryBytes"`
	Subtype     string       `json:"subtype,omitempty"`
	BitLength   int64        `json:"bitLength,omitempty"`
	BitCount    int64        `json:"bitCount,omitempty"`
	Unsupported bool         `json:"unsupported,omitempty"`
	Entries     []RedisEntry `json:"entries"`
}

RedisValue is a key's value rendered as text lines, capped by Limits.

type Result

type Result struct {
	Columns    []string    `json:"columns"`
	Rows       [][]*string `json:"rows"`
	RowCount   int         `json:"row_count"`
	Truncated  bool        `json:"truncated"`
	DurationMs int64       `json:"duration_ms"`
}

Result is one statement's output. A nil cell is SQL NULL.

type SchemaNode

type SchemaNode struct {
	Name   string  `json:"name"`
	Tables []Table `json:"tables"`
}

SchemaNode groups tables under one schema (a MySQL database).

type Statement

type Statement struct {
	// SQL is the statement with its trailing semicolon removed.
	SQL         string
	Kind        string
	Fingerprint string
	// First is the lowercased leading keyword.
	First string
}

Statement is a statement the guard accepted.

func Check

func Check(d Dialect, sql string, allowWrites bool) (Statement, error)

Check lexes sql and decides whether it may run. A rejected statement is never sent to the database. This is defense in depth: the read-only transaction and PGOPTIONS the runner sets are the real enforcement.

type Status

type Status string

Status says whether one explorer capability works for an engine today.

const (
	StatusAvailable   Status = "available"
	StatusPlanned     Status = "planned"
	StatusUnsupported Status = "unsupported"
)

Capability statuses the UI renders.

type Structure

type Structure struct {
	Schema       string       `json:"schema"`
	Name         string       `json:"name"`
	Kind         string       `json:"kind"`
	RowEstimate  int64        `json:"row_estimate"`
	SizeBytes    int64        `json:"size_bytes"`
	Columns      []Column     `json:"columns"`
	Indexes      []Index      `json:"indexes"`
	ForeignKeys  []ForeignKey `json:"foreign_keys"`
	ReferencedBy []ForeignKey `json:"referenced_by"`
	DDL          string       `json:"ddl"`
}

Structure is the full detail of one table, what the schema outline leaves out. ForeignKeys point away from the table, ReferencedBy point at it.

type Table

type Table struct {
	Name        string   `json:"name"`
	Kind        string   `json:"kind"`
	RowEstimate int64    `json:"row_estimate"`
	SizeBytes   int64    `json:"size_bytes"`
	Columns     []Column `json:"columns"`
	Indexes     []Index  `json:"indexes"`
}

Table is a table, view, or other relation.

type Target

type Target struct {
	Exec        Execer
	ContainerID string
	Dialect     Dialect
	Limits      Limits
	// External marks a database this platform does not run: Exec starts a
	// helper that carries the connection, and ContainerID is unused.
	External bool
}

Target is one running database container.

func (Target) Clients

func (t Target) Clients(ctx context.Context) (RedisClients, error)

Clients lists connected clients, capped by the row limit.

func (Target) Evidence

func (t Target) Evidence(ctx context.Context) (Evidence, error)

Evidence counts schemas, tables and bytes straight from the catalog.

func (Target) Explain

func (t Target) Explain(ctx context.Context, st Statement, analyze bool) (Result, error)

Explain returns the plan for a read statement as text lines (Postgres, MySQL, and MariaDB all accept an EXPLAIN prefix).

func (Target) GetKey

func (t Target) GetKey(ctx context.Context, key string) (RedisValue, error)

GetKey reads one key with fixed read-only commands chosen by type. The key is only ever sent through redisQuote, and every reply is bounded before it is read.

func (Target) Info

func (t Target) Info(ctx context.Context) (RedisInfo, error)

Info runs fixed INFO section commands.

func (Target) Run

func (t Target) Run(ctx context.Context, st Statement, write bool) (Result, error)

Run executes a guard-approved statement. write must match the allowWrites value the statement was checked with.

func (Target) RunDynamo

func (t Target) RunDynamo(ctx context.Context, q DynamoPrepared) (DynamoResult, error)

RunDynamo executes a guard-approved request inside the container and parses the answer.

func (Target) RunMongo

func (t Target) RunMongo(ctx context.Context, q MongoQuery) (MongoResult, error)

RunMongo executes a guard-approved query and collects its output lines.

func (Target) RunTrusted

func (t Target) RunTrusted(ctx context.Context, sql string) (Result, error)

RunTrusted executes SQL the control plane built itself (introspection, table pages). It still runs in a read-only transaction.

func (Target) ScanKeys

func (t Target) ScanKeys(ctx context.Context, cursor, pattern string, count int) (RedisScan, error)

ScanKeys runs one SCAN step and looks up each key's type and TTL.

func (Target) Schema

func (t Target) Schema(ctx context.Context) ([]SchemaNode, error)

Schema lists every user schema with its tables, columns, and indexes.

func (Target) SchemaOutline

func (t Target) SchemaOutline(ctx context.Context) ([]SchemaNode, error)

SchemaOutline lists every user schema with its tables, row estimates and sizes but no columns or indexes, so a database with thousands of tables stays a small document. Per-table detail comes from TableStructure.

func (Target) Slowlog

func (t Target) Slowlog(ctx context.Context, count int) (RedisSlowlog, error)

Slowlog reads the newest count entries (clamped to the row cap).

func (Target) TablePage

func (t Target) TablePage(ctx context.Context, q PageQuery) (Page, error)

TablePage reads one page. Schema, table, and column names are checked against the database's own catalog before they are quoted into SQL.

func (Target) TableStructure

func (t Target) TableStructure(ctx context.Context, schema, table string) (Structure, error)

TableStructure returns the columns, indexes, foreign keys in both directions, and DDL of one table, or ErrNotFound.

Jump to

Keyboard shortcuts

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