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 ¶
- Variables
- func AppendHistory(ctx context.Context, path string, event HistoryEvent) (result error)
- func EffectiveAnalyze(sql string, readOnly bool, requested bool) bool
- type CLIStatement
- type CLIStatementAnalysis
- type History
- func (h *History) AsSessionRecorder(connID string) session.HistoryRecorder
- func (h *History) Close() error
- func (h *History) Dropped() uint64
- func (h *History) Recent(ctx context.Context, limit int) ([]HistoryRow, error)
- func (h *History) Record(stmt string, durMs int64, rowsAffected int64, succeeded bool, connID string)
- func (h *History) RecordEntry(event HistoryEvent) error
- func (h *History) SearchByPrefix(ctx context.Context, prefix string, limit int) ([]string, error)
- type HistoryEvent
- type HistoryRow
- type QueryObj
- func (q *QueryObj) Bind(args ...any) *QueryObj
- func (q *QueryObj) DontLog() *QueryObj
- func (q *QueryObj) Execute(ctx context.Context) (models.Result, error)
- func (q *QueryObj) Explain(ctx context.Context, analyze bool) (models.Plan, error)
- func (q *QueryObj) Stream(ctx context.Context) (*session.RunHandle, error)
- func (q *QueryObj) WithTimeout(d time.Duration) *QueryObj
- func (q *QueryObj) WithTx(tx drivers.Transaction) *QueryObj
- type ResultIdentity
- type StatementKind
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidCLIInput = errors.New("query: invalid CLI input") ErrUnsupportedCLISQL = errors.New("query: unsupported CLI SQL") )
var ( // Existing broad-access stores require manual permission remediation. ErrHistoryUnavailable = errors.New("query: history unavailable") // ErrHistoryUpgradeRequired means a known upgrade exhausted its budget. // Open the new TUI once to upgrade, then retry the CLI invocation. ErrHistoryUpgradeRequired = errors.New("query: history upgrade required") )
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.
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 AppendHistory ¶ added in v0.13.0
func AppendHistory(ctx context.Context, path string, event HistoryEvent) (result error)
AppendHistory commits one event synchronously, without starting a TUI writer. The caller owns the total history-work budget; cancellation never starts a separate timeout or an abandoned writer. SQL literals/comments are retained.
func EffectiveAnalyze ¶
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 CLIStatement ¶ added in v0.15.0
type CLIStatement struct {
Start, End int
Kind StatementKind
}
CLIStatement is a half-open original byte range, excluding its separator. Leading/trailing whitespace and comments are retained, not normalized.
type CLIStatementAnalysis ¶ added in v0.15.0
type CLIStatementAnalysis struct {
Statements []CLIStatement
WritesApprovalRequired bool
DDLApprovalRequired bool
}
func AnalyzeCLIStatements ¶ added in v0.15.0
func AnalyzeCLIStatements(ctx context.Context, sql string, parameterCount int, confirmWrites, confirmDDL bool) (CLIStatementAnalysis, error)
AnalyzeCLIStatements analyzes but never rewrites or executes SQL. Its lexical contract is PostgreSQL 17/18 with standard_conforming_strings=on and UTF-8. Approval deliberately retains EffectiveKind's heuristic, including its gaps.
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 ¶
New opens (creating if needed) the SQLite history database at path, runs migrations, and starts the background writer goroutine. Startup is best-effort: lock contention must not prevent the TUI from opening without history.
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 ¶
Close stops the writer (after draining queued entries) and closes the underlying *sql.DB. Idempotent.
func (*History) Recent ¶
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) RecordEntry ¶ added in v0.13.0
func (h *History) RecordEntry(event HistoryEvent) error
RecordEntry validates and enqueues an attempt using Record's best-effort, nonblocking queue. A nil error means admission, not committed persistence. Source must be tui or cli; Outcome must be succeeded, failed or blocked.
func (*History) SearchByPrefix ¶
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).
Blocked attempts remain manually recallable through Recent, but never supply completion candidates. De-duplication streams newest-first without GROUP BY.
type HistoryEvent ¶ added in v0.13.0
type HistoryEvent struct {
ExecutedAt int64
SQL string
DurationMS int64
ConnectionID string
Source string
Outcome string
}
HistoryEvent records an attempt, not result data or output delivery. ExecutedAt is its completion time in Unix milliseconds; DurationMS includes DB cleanup. SQL literals and comments are retained. Parameters and result/error objects deliberately have no representation here.
type HistoryRow ¶
type HistoryRow struct {
ID int64
ExecutedAt int64
SQL string
DurationMS int64
Succeeded bool
ConnectionID string
Source string
Outcome 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 ¶
Bind sets the bound arguments. Calling Bind a second time REPLACES the previous arguments rather than appending — the test contract.
func (*QueryObj) DontLog ¶
DontLog suppresses HistoryRecorder.Record for this dispatch by wrapping the context with session.WithoutLogging before delegating.
func (*QueryObj) Explain ¶
Explain dispatches an Explain on the underlying SQLSession with the supplied analyze flag.
func (*QueryObj) Stream ¶
Stream dispatches a Stream and returns the RunHandle the SQLSession produced. The handle is passed through unwrapped.
func (*QueryObj) WithTimeout ¶
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package plandoctor is a pure, offline EXPLAIN-plan insight engine.
|
Package plandoctor is a pure, offline EXPLAIN-plan insight engine. |