query

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 21 Imported by: ? 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 query ...

Package query provides a fluent, value-immutable builder (QueryObj) that wraps a *session.SQLSession and dispatches Execute / Stream / Explain.

Each WithX method returns a NEW *QueryObj; the receiver is left untouched, so a base builder can be safely reused across goroutines as a template. Concurrency control still lives entirely in SQLSession — QueryObj is a pure builder.

Index

Constants

This section is empty.

Variables

View Source
var ErrEmptyStatement = errors.New("query: empty statement")

ErrEmptyStatement is returned by Execute / Stream / Explain when the QueryObj was constructed (or derived) with an empty SQL string. New itself never errors — empty SQL is only rejected at dispatch.

View Source
var ErrIncompatible = errors.New("query: history database has a newer schema than this binary supports")

ErrIncompatible is returned by migrate when the on-disk database has a schema version higher than the highest embedded migration. This signals that the binary is older than the database and refuses to touch it.

Functions

func EffectiveAnalyze

func EffectiveAnalyze(sql string, readOnly bool, requested bool) bool

EffectiveAnalyze decides whether an EXPLAIN ANALYZE (which executes the statement) is safe to run. It is a fail-closed gate, pure and reusable.

ANALYZE is permitted only when it was requested AND either:

  • the connection is read-only (the server itself rejects writes, so an accidental write statement cannot mutate data), or
  • the statement is not a DML/DDL statement (Classify == KindOther) and no whole-word DML token (INSERT/UPDATE/DELETE/MERGE) nor DDL token (CREATE/ALTER/DROP/…) appears anywhere in it (closing the writable-CTE and DDL-in-CTE holes).

readOnly is passed as a bool rather than a *models.Connection to keep this package free of a models dependency and to keep the helper trivially testable.

Types

type History

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

History persists executed statements to a SQLite file with FTS5 search on the sql column. Record is non-blocking; on overflow the oldest queued entry is dropped to make room for the newest.

func New

func New(path string) (*History, error)

New opens (creating if needed) the SQLite history database at path, runs migrations, and starts the background writer goroutine.

func (*History) AsSessionRecorder

func (h *History) AsSessionRecorder(connID string) session.HistoryRecorder

AsSessionRecorder returns an adapter that satisfies session.HistoryRecorder by forwarding every Record call to the underlying *History with the captured connID. *History itself has a 5-arg Record (canonical) and is bridged here.

func (*History) Close

func (h *History) Close() error

Close stops the writer (after draining queued entries) and closes the underlying *sql.DB. Idempotent.

func (*History) Dropped

func (h *History) Dropped() uint64

Dropped reports the count of evicted entries since startup.

func (*History) Recent

func (h *History) Recent(ctx context.Context, limit int) ([]HistoryRow, error)

Recent returns up to limit rows from history, newest first (id DESC). limit <= 0 returns an empty (non-nil) slice and a nil error.

func (*History) Record

func (h *History) Record(stmt string, durMs int64, rowsAffected int64, succeeded bool, connID string)

Record enqueues a row for asynchronous insertion. It never blocks: if the queue is full, the oldest queued entry is evicted and the new one takes its slot. The dropped counter increments per eviction.

func (*History) SearchByPrefix

func (h *History) SearchByPrefix(ctx context.Context, prefix string, limit int) ([]string, error)

SearchByPrefix returns up to limit distinct sql statements from history whose FTS5 token stream contains a token starting with prefix, ordered by most recent first. limit <= 0 or an empty/blank prefix returns an empty slice.

The query uses quoted FTS5 prefix syntax (`MATCH '"sanitized"*'`); the prefix is sanitized to a single contiguous run of alphanumerics + underscore. Quoting makes operator words such as AND literal; the star stays outside the quotes to match longer tokens. Empty sanitization returns ([]string{}, nil).

De-duplication is performed in Go after streaming rows newest-first; the query itself avoids GROUP BY so the FTS5 + index path can short-circuit once `limit` distinct rows have been seen, keeping p99 under 50ms over 100k-row tables.

type HistoryRow

type HistoryRow struct {
	ID           int64
	ExecutedAt   int64
	SQL          string
	DurationMS   int64
	Succeeded    bool
	ConnectionID string
}

HistoryRow is a single recorded statement read back from the history store.

type QueryObj

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

QueryObj is the fluent builder. Construct via New and chain WithX methods; each WithX returns a copy. The zero value is not useful — use New.

func NewQueryObj

func NewQueryObj(sess *session.SQLSession, sql string) *QueryObj

NewQueryObj constructs a QueryObj over sess for sql. sql may be empty; the empty-statement check is deferred to dispatch (Execute / Stream / Explain) so callers can build a template and fill it in later.

(Named NewQueryObj rather than New because pkg/query already exports New as the constructor for the History type.)

func (*QueryObj) Bind

func (q *QueryObj) Bind(args ...any) *QueryObj

Bind sets the bound arguments. Calling Bind a second time REPLACES the previous arguments rather than appending — the test contract.

func (*QueryObj) DontLog

func (q *QueryObj) DontLog() *QueryObj

DontLog suppresses HistoryRecorder.Record for this dispatch by wrapping the context with session.WithoutLogging before delegating.

func (*QueryObj) Execute

func (q *QueryObj) Execute(ctx context.Context) (models.Result, error)

Execute dispatches an Execute on the underlying SQLSession.

func (*QueryObj) Explain

func (q *QueryObj) Explain(ctx context.Context, analyze bool) (models.Plan, error)

Explain dispatches an Explain on the underlying SQLSession with the supplied analyze flag.

func (*QueryObj) Stream

func (q *QueryObj) Stream(ctx context.Context) (*session.RunHandle, error)

Stream dispatches a Stream and returns the RunHandle the SQLSession produced. The handle is passed through unwrapped.

func (*QueryObj) WithTimeout

func (q *QueryObj) WithTimeout(d time.Duration) *QueryObj

WithTimeout sets the per-query timeout passed through to models.Query. A zero duration is preserved and means "no timeout" at the driver layer.

func (*QueryObj) WithTx

func (q *QueryObj) WithTx(tx drivers.Transaction) *QueryObj

WithTx records an intent to run inside tx. v1 limitation: SQLSession uses the session's in-progress transaction implicitly (driver-side tracking), so WithTx is a no-op assertion — the value is stored but not re-routed at dispatch time. Passing nil is equivalent to omitting.

type ResultIdentity

type ResultIdentity struct {
	// BaseTable is the qualified table name in the form "<schema>.<table>"
	// when a schema qualifier is present, or just "<table>" otherwise.
	// Unquoted identifiers are lowercased; quoted identifiers preserve
	// their inner casing and may legally contain dots (e.g. "weird.name").
	BaseTable string

	// HasRowIdentity is true when the query is judged to have a stable
	// row identity backed by BaseTable.
	HasRowIdentity bool

	// Editable, RowIdentity, and DisabledReason are populated by callers
	// AFTER pg_class+pg_index introspection runs (see
	// pkg/drivers/pg.EditabilityIntrospect). DetectFromQuery leaves them
	// zero — SQL parsing alone cannot distinguish a base table from a
	// view, materialised view, or partition parent.
	Editable       bool
	RowIdentity    []int
	DisabledReason string
}

ResultIdentity describes whether a query's result set has a stable 1:1 mapping back to rows in a single base table — the prerequisite for features like editable cells, per-table hidden-column persistence (T6), and SQL-INSERTs export (T9).

DetectFromQuery is conservative: it returns HasRowIdentity=true only when the SQL is a single SELECT against a single base table with no joins, CTEs, subqueries, set operations, aggregates, or table-valued functions. When in doubt, it returns the zero value.

func DetectFromQuery

func DetectFromQuery(sql string) ResultIdentity

DetectFromQuery runs the heuristic over sql and returns a ResultIdentity. The detector accepts only this shape:

SELECT ( * | <col-list> ) FROM (<schema>.)?<table>
  ( WHERE … | ORDER BY … | LIMIT … | ; | EOF )

Multi-statement input is supported: if any statement is rejected, the whole result is the zero value. Comments are stripped before tokenization, but the stripper respects string literals so a payload like `WHERE name='a--b'` is preserved verbatim.

type StatementKind

type StatementKind int

StatementKind classifies a SQL statement by its leading keyword. It is a coarse, parser-free classification used to decide whether a statement needs a confirmation prompt before execution, not a full SQL grammar.

const (
	// KindOther covers read-only and miscellaneous statements (SELECT,
	// WITH, SHOW, EXPLAIN, SET, BEGIN, ...). These never trigger a
	// confirmation prompt.
	KindOther StatementKind = iota
	// KindDML is a data-mutating statement (INSERT, UPDATE, DELETE, MERGE).
	KindDML
	// KindDDL is a schema/permission-mutating statement (CREATE, ALTER,
	// DROP, TRUNCATE, COMMENT, GRANT, REVOKE).
	KindDDL
)

func Classify

func Classify(sql string) StatementKind

Classify returns the StatementKind of sql based on its first keyword, skipping leading whitespace, line comments (-- … EOL), and block comments (/* … */).

func EffectiveKind

func EffectiveKind(sql string) StatementKind

EffectiveKind returns the StatementKind used for confirmation decisions. It keeps Classify's leading-keyword result for plain statements (a plain SELECT stays KindOther, a plain DELETE stays KindDML) but ELEVATES a non-mutating leading keyword to KindDML when a whole-word DML token (INSERT/UPDATE/DELETE/MERGE) appears anywhere in the statement. This closes the writable-CTE confirm hole: WITH d AS (DELETE FROM t RETURNING *) SELECT … leads with WITH (KindOther) yet performs a write, so ConfirmWrites must fire.

The scan reuses dmlTokenRE (explain_gate.go) — a whole-word regex, not a SQL parser. A DML keyword inside a string literal (e.g. 'DELETE' as a value) can still falsely elevate; matching the existing gate's rigor, this is accepted as a fail-closed bias (extra confirm prompts beat silent writes).

DDL-CTE note: there is deliberately NO "DDL elevation" here. Postgres CTEs may contain only SELECT/INSERT/UPDATE/ DELETE — never DDL — so a real WITH-led statement can never execute DDL; a plain DDL statement leads with its own keyword (CREATE/ALTER/DROP/…), which Classify already returns as KindDDL. Adding a ddlTokenRE elevation would over-fire: a benign read-only SELECT with a column named "comment" or "drop" would whole-word-match and be misclassified KindDDL, spuriously tripping the pre-run ConfirmDDL prompt. So EffectiveKind is already correct for the DDL case; only the DML writable-CTE hole needs closing.

Directories

Path Synopsis
Package plandoctor is a pure, offline EXPLAIN-plan insight engine.
Package plandoctor is a pure, offline EXPLAIN-plan insight engine.

Jump to

Keyboard shortcuts

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