dbm

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 10 Imported by: 1 module, 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 dbm is database monitoring beyond counters (INF-027, APM-008, APM-024): bind-safe statement text, lock/wait chains and blocking sessions. The functions are pure; the engine modules in ../integrations feed them rows read through a read-only connection.

Index

Constants

View Source
const MaxChains = 20

MaxChains bounds the chains reported per round.

View Source
const MaxSampleGroups = 100

MaxSampleGroups bounds the sample records reported per flush.

View Source
const MaxStatements = 200

MaxStatements bounds the per-query series reported per round.

Variables

This section is empty.

Functions

func BindSafe

func BindSafe(q string) string

BindSafe replaces every literal (quoted string, number, dollar-quoted body) with `?` so a sample never carries a bound value, then collapses whitespace and bounds the length.

func EmitSample

func EmitSample(out sink.Sink, system, kind, sev string, payload any, attrs map[string]string, now time.Time)

EmitSample writes one sample record (event.name `db.<kind>`): kind is query.sample, query.plan, wait, keyspace, advice or shard. The payload must already be value-free (BindSafe, Shape, Redact).

func Hash

func Hash(normalized string) string

Hash is the canonical `db.query.hash` of normalized text (SQL from NormalizeSQL, or a document shape, Redis command pattern or Cypher text): XXH3-64, seed 0, as a decimal string.

func HashSQL

func HashSQL(stmt string, pg bool) (string, string)

HashSQL is NormalizeSQL plus the canonical hash.

func KeyPattern

func KeyPattern(k string) string

KeyPattern turns a key into its pattern: `user:1234:cart` -> `user:*:cart`, `sess:9f8e7d6c5b4a` -> `sess:*`. Segments are split on `:`, `/`, `.`, `-` and `_`; a segment holding a digit becomes `*`.

func NormalizeSQL

func NormalizeSQL(stmt string, pg bool) string

NormalizeSQL is the canonical normalization: literals become `?`, comments go, whitespace collapses and `IN (?, ?)` becomes `IN (?+)`. pg is true for postgresql, cockroachdb, redshift.

func ObfuscatePlan

func ObfuscatePlan(plan string) string

ObfuscatePlan makes an EXPLAIN (FORMAT JSON) document bind-safe: every string value (conditions, filters, outputs) goes through BindSafe, so a plan of a statement run with real literals never carries them. Keys and numbers (costs, rows) are kept. "" if it is not JSON.

func PGDialect

func PGDialect(system string) bool

PGDialect reports the engines whose statements are normalized with the pg flag.

func QueryHash

func QueryHash(stmt string, pg bool) string

QueryHash is the canonical decimal db.query.hash of a raw statement.

func Redact

func Redact(args []string, keyArgs int) string

Redact keeps a command's name and replaces each argument with a key pattern (Redis, Memcached): runs of digits and hex ids become `*`, other arguments `?`. Only the first maxArgs are kept.

func Report

func Report(out sink.Sink, engine string, sessions []Session, now time.Time)

Report emits the blocking gauges and one log record per chain. Statement text is bind-safe.

func Shape

func Shape(v any) any

Shape replaces every scalar of a decoded JSON document with "?", keeps keys and operators and collapses each array to its first element's shape, so a document query (MongoDB filter, Elasticsearch DSL, Cypher params) reads as its shape and never carries a value.

func ShapeText

func ShapeText(v any) string

ShapeText is Shape as compact JSON with sorted keys (encoding/json sorts map keys), so equal shapes give equal text and therefore equal hashes.

Types

type Activity

type Activity struct {
	Database   string
	State      string
	WaitType   string // wait_event_type ("" when on CPU)
	Wait       string // wait_event
	QueryID    string
	Query      string // raw text: kept in memory for EXPLAIN only, never reported as is
	DurationMs float64
}

Activity is one non-idle session in one snapshot of the engine's activity view.

type Candidate

type Candidate struct{ QueryID, Query, Raw string }

Candidate is a sampled statement the caller may EXPLAIN: Raw is the text as the engine ran it (with literals), Query its bind-safe form.

type Chain

type Chain struct {
	Root    Session   `json:"root"`
	Waiters []Session `json:"waiters"`
	Depth   int       `json:"depth"`
}

Chain is one blocking tree: Root blocks everything in Waiters (transitively, nearest first).

func BuildChains

func BuildChains(sessions []Session) []Chain

BuildChains turns sessions with their blockers into one chain per root blocker (a session that blocks others and is not itself blocked), longest first. A cycle (a deadlock the engine has not yet broken) has no root and is reported by its lowest pid with Depth counting the members. Chains are capped at MaxChains.

type Deltas

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

Deltas turns cumulative statement rows into per-round deltas. Not safe for concurrent use.

func (*Deltas) Observe

func (d *Deltas) Observe(rows []Statement, limit int) []StatementDelta

Observe takes one round of rows and returns the statements that ran since the previous round, most total time first, at most limit. A statement seen for the first time sets its baseline only (its history is not this round's work). A counter that went down was reset, so its current value is the delta.

type Sampler

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

Sampler aggregates activity snapshots (taken every second) into groups of database, state, wait event and statement, so the agent ships one record per group per flush instead of one per session per second. Not safe for concurrent use.

func (*Sampler) Add

func (s *Sampler) Add(rows []Activity)

Add records one snapshot.

func (*Sampler) Flush

func (s *Sampler) Flush(out sink.Sink, engine string, now time.Time) []Candidate

Flush emits what was sampled since the last flush and resets: `db.activity.sessions` (average sessions per database, state and wait event: active session history) and one `db.query.sample` log record per group, busiest first. It returns one candidate per statement.

func (*Sampler) Ticks

func (s *Sampler) Ticks() int

Ticks is the number of snapshots since the last flush.

type Session

type Session struct {
	PID       int      `json:"pid"`
	BlockedBy []int    `json:"blocked_by,omitempty"`
	State     string   `json:"state,omitempty"`
	WaitEvent string   `json:"wait_event,omitempty"`
	Query     string   `json:"query,omitempty"`
	AgeMs     float64  `json:"age_ms,omitempty"`
	Locks     []string `json:"locks,omitempty"`
}

Session is one database session, as the engine's activity view reports it.

type Statement

type Statement struct {
	Key      string // e.g. database + "/" + queryid
	QueryID  string
	Database string
	Query    string
	Calls    int64
	TotalMs  float64
	Rows     int64
	BlksHit  int64
	BlksRead int64
}

Statement is one row of the engine's statement statistics (pg_stat_statements), cumulative since the engine last reset them.

type StatementDelta

type StatementDelta struct {
	Statement           // running totals
	MeanMs    float64   // of the calls in this round
	Delta     Statement // this round only
}

StatementDelta is one statement's activity since the previous round plus the agent's own running totals of it, which keep counting across an engine reset or eviction.

Jump to

Keyboard shortcuts

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