sqlextract

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2026 License: Apache-2.0 Imports: 10 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 sqlextract reassembles SQL held in Go string literals and reports the compositions it could not reassemble. It is the shared substrate for the SQL-aware rule types (sql/statement-predicate, sql/parses, sql/locking-select-order). It knows nothing about rules.

A "candidate" is a maximal compile-time-constant string expression: a lone string literal or a '+'-chain of them, constant-folded. Candidates are NOT split into statements — callers that need statements split them (sqltext) or hand the whole candidate to a real parser (sqlparse).

HEURISTIC LIMITS, AND THE TWO EXTRACTORS DO NOT SHARE THEM. FromGo reports only fmt.Sprint{,f,ln} calls and '+' concats with a non-literal operand as unresolved Sites; literals spread across assignments and strings.Builder are dropped silently, as before. FromGoReassembled RESOLVES both of FromGo's two shapes into fw_expr text and ADDITIONALLY folds straight-line and if-branch assignment flow (`x := …` then `x += …`) into candidates (#36) — but FromGo's candidate set is unchanged (byte-identical for sqltext).

The two limit sets are therefore near-complements, which is what #311 was filed about: the census asked FromGo which compositions a rule declined and attributed the answer to rules that source through FromGoReassembled, so it denied analysis of every composition those rules read and stayed silent about every one they do not. strings.Builder, loop/switch/closure composition and if/else-both-append remain DROPPED in both — and in FromGoReassembled each of them now returns a Site saying so (sites.go), which is the difference between a limit that is disclosed and one that is merely true.

SQL COMMENTS are NOT handled here, and that is a division of labour rather than a gap. Reassembly is a Go-level question — what bytes did this literal hold — and a candidate's text is returned verbatim, comments included. Deciding that a `--` or `/* … */` run is not statement text is a SQL-level question, and it belongs to whoever interprets the candidate: sqltext blanks comments in splitStatements via preprocess.DecommentSQL (#137), and sqlparse hands whole text to pg_query, which lexes them itself. A consumer that reads Candidate.Text and matches tokens over it without decommenting inherits the evasion those two closed — a token carried only by a comment reads as code.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FileKind

func FileKind(path string) string

FileKind classifies a path as an SQL-bearing source: "sql" for .sql, "go" for .go (SQL in string literals), "" otherwise. Case-insensitive on the extension. Shared by sqlparse and sqltext so the .sql/.go/other dispatch logic lives in exactly one place.

func FromGo

func FromGo(path string, src []byte) (resolved []Candidate, unresolved []Site, err error)

FromGo parses src as Go source and returns each reassembled string candidate plus every composition it could not reassemble. A Go parse failure is an error (the engine surfaces it as exit 2), never a silent pass.

The candidate walk (Text, Line, order) is byte-identical to sqltext's former extractGoCandidates. Partial is a post-process: a collected literal whose source position falls inside an unresolved node's [Pos, End) span is a fragment of that unresolvable composition. This adds the Partial signal WITHOUT changing which candidates are collected — sqltext still gets every one, exactly as before.

func FromGoReassembled

func FromGoReassembled(path string, src []byte) ([]Candidate, []Site, error)

FromGoReassembled parses src as Go source and returns, for each top-level SQL-bearing string expression, ONE best-effort *complete* reassembly: unlike FromGo, a composition mixing literal and non-literal parts is not dropped or merely flagged unresolved — every non-literal part is replaced by the synthetic identifier "fw_expr" so the result is a syntactically complete text a real SQL parser can attempt. Partial is always false.

Handled compositions:

  • a lone string literal → its unquoted value;
  • a '+'-chain (BinaryExpr ADD) with at least one string literal somewhere in it → concatenated, each non-literal operand contributing "fw_expr". A chain with no literal text at all (integer arithmetic, two variables) is NOT a candidate: it is left for further descent, since an operand may itself hold SQL;
  • a fmt.Sprintf call whose first arg is a string literal → the format string with each verb (and "%%") substituted;
  • a fmt.Sprint/Sprintln call whose first arg is a string literal → every operand reassembled and concatenated (Sprintln space-separated with a trailing newline). These take no format string, so no verb substitution.

Straight-line and if-branch assignment flow (`x := …` then `x += …`) IS folded here, additively, by the same walk (#36, see fold.go), and an IMMEDIATELY-INVOKED closure's appends are folded in with them WHEN IT IS INVOKED AS A STATEMENT AND ITS BODY IS FULLY MODELLABLE (#72) — one containing so much as a plain function call is not, nor is one invoked in an `if` condition, and in both cases the appends are silently dropped exactly like a named closure's even though the literal provably runs. Other compositions (strings.Builder, loop/switch-built queries, what a NAMED closure, a disqualified IIFE, or a condition-position literal appends, if/else where both branches append, cross-function flow) cannot be reassembled and produce no candidate — never a finding, and since #311 never a silence either: each returns a Site instead (below). The seed literal is emitted by the expression walk regardless, so such a query is analyzed as if the seed were the whole of it. This does not change FromGo's candidate set, byte-identical for sqltext's sake.

A non-literal part standing in for a SQL-syntactic position (e.g. an ORDER BY column or a WHERE-key operand built from a runtime variable) reassembles to the "fw_expr" placeholder, which callers that check structural properties (e.g. sql/locking-select-order) cannot verify — by design, this is treated as unverifiable rather than assumed safe.

EVERY COMPOSITION IT DROPS IS ALSO RETURNED, as a Site (#311). The drops above are the fold's real coverage limits, and until #311 they left no trace anywhere: no candidate, no finding, and nothing for an operator to count. The Sites are that count. They are NOT findings and NOT errors — a consumer reports them as "not read", never as a pass and never as a failure. sites.go holds the collection; coverage.go holds the reasons one can carry.

err is only for a Go AST parse failure.

Types

type Candidate

type Candidate struct {
	Text string
	Line int
	// Col is the 1-based column of the expression this candidate came from.
	// It exists to tell two candidates seeded on ONE physical line apart (#44):
	// consumers dedup .go findings by position, and line alone collapsed
	// genuinely distinct queries into a single finding. Zero when unknown.
	Col     int
	Partial bool
	// InfeasibleBaseRisk marks the `base` world of a variable that has at
	// least one complementary guard pair (#42/#238). `base` drops every
	// optional append, and a complementary pair guarantees one of them fires,
	// so such a world is one no path produces AT THE END of the function.
	//
	// "Risk", not "infeasible", and the hedge is load-bearing: complementarity
	// constrains only the FINAL value. A query observed between the two
	// branches — run(q), an early return, a db.Query — genuinely IS base on a
	// real path, so a consumer must phrase this as a possibility. It is set
	// only where a pair exists, because a marker on every finding carries no
	// information.
	InfeasibleBaseRisk bool
	// ClosureEscapeRisk names the call a closure escaped into whose appends are
	// therefore NOT in this world — `run(add)`, or the inline `run(func(){…})`.
	// Empty when the scope that built this candidate has no such escape (#337).
	//
	// The extractor is parse-only (spec §2 "Out"), so `func run(f func()){ f() }`
	// and `func register(f func()){}` are ONE PROGRAM to it: whether the callee
	// invokes f or merely stores it is cross-function flow. The fold therefore
	// keeps folding rather than untracking — untracking would silence the
	// register() case, where the closure never runs, the world without its
	// appends IS the value, and a finding on it is the hazard the rule exists
	// for. Spec §10 measured that trade: ten findings gone, eight of them true.
	//
	// "Risk", not "is", on InfeasibleBaseRisk's model and for its reason: this
	// world is real whenever the callee does not call f and fabricated whenever
	// it does, and nothing here can tell those apart, so a consumer must phrase
	// it as a possibility. It is set only where the shape exists, because a
	// marker on every finding carries no information.
	ClosureEscapeRisk string
}

Candidate is one maximal reassembled SQL-bearing Go string literal plus the 1-based source line of the string expression it came from. Partial is true when this literal is a fragment of a composition that could not be reassembled (see FromGo) — not a standalone statement.

type Site

type Site struct {
	Path string
	Line int
	// Key is the stable machine-readable name of the shape, so a consumer can
	// switch on it and a disclosure can be checked against it rather than
	// against a prose reason that drifts.
	Key string
	// Reason is the operator-facing phrase, rendered inside "could not be read
	// (…)". A noun phrase naming the construct, never a sentence.
	Reason string
	// Text is the SQL-bearing text this site is about: the reassembled
	// composition for FromGo, the tracked variable's seed for a fold site, the
	// accumulated literal for a builder. It exists so a consumer can tell a
	// declined SQL query from a declined import path — the census would
	// otherwise list every untracked non-SQL string in the repo — and it is
	// never rendered.
	Text string
}

Site is a Go-literal SQL composition an extractor could not read, at the position of the construct that made it unreadable.

THE TWO EXTRACTORS HAVE DIFFERENT LIMITS AND THEREFORE DIFFERENT SITES, and that is the whole reason Key exists (#311). FromGo reports the two shapes it declines to constant-fold; FromGoReassembled folds both of those and reports instead the writes its assignment-flow fold cannot see. A consumer that asks one extractor and attributes the answer to a rule sourcing through the other states the exact opposite of the truth in both directions — it denies analysis of a line the rule just fired on, and stays silent about every composition the rule really cannot read.

type UntrackReason

type UntrackReason struct {
	// Key is the stable machine-readable name. Consumers key on it, so it
	// changes only when the shape it names changes.
	Key string
	// Issue is the issue that named the shape — the one whose Reproduce section
	// holds the source that used to fabricate a world here.
	Issue string
	// Detail is the operator-facing phrase, rendered by the census inside
	// "could not be read (…)". A noun phrase naming the CONSTRUCT, because the
	// site is anchored at the construct and not at the query (sites.go): an
	// operator reading the line has to know what to go and look at.
	Detail string
	// Partial reports that the fold read the composition IN PART and emitted a
	// world from what it read, rather than emitting nothing.
	//
	// It is the difference between the two things a census line can mean, and
	// #311 is what happens when they are confused: a site carrying a
	// non-Partial reason claims the rule analysed nothing here, and putting one
	// on a composition the rule DID read is the false claim this arc closed.
	// A shape the COVERAGE LIMIT block discloses SILENT may only ever be
	// reported with a non-Partial reason, and a shape it discloses FIRES or
	// PASSES only with a Partial one.
	Partial bool
}

UntrackReason is one reason the fold declines to read a composition. It is not an error and not a finding: it is the fold declining to answer, which a consumer must report as "not analysed" rather than let pass as "clean".

func UnreadableReasons

func UnreadableReasons() []UntrackReason

UnreadableReasons returns every reason a Site can carry — the five untrack reasons plus the three compositions the fold declines without untracking, in a fixed order.

This is the list the operator-facing channel enumerates, and it is a superset of UntrackReasons rather than the same list because "no world was emitted" and "no world could be read" are different claims about the same file. An operator auditing a clean run needs the second one.

func UntrackReasons

func UntrackReasons() []UntrackReason

UntrackReasons returns every reason the fold UNTRACKS a variable on, in a fixed order. Exported for the consumers that must disclose the fold's silence: locking.go's COVERAGE LIMIT block, which has to name each of these as a shape the real rule goes SILENT on.

Jump to

Keyboard shortcuts

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