Documentation
¶
Overview ¶
Package lint provides a small analysis framework, modeled on golang.org/x/tools/go/analysis, for reporting style and correctness warnings on SQL that already analyzes without errors.
Index ¶
- Constants
- Variables
- func FindConfigFile(dir string) (string, bool)
- func HasComment(src string) bool
- func NullReplacement(op string) (string, bool)
- type Analyzer
- type BytesProcessedThresholdOptions
- type Config
- type Diagnostic
- type Env
- type IgnoreLine
- type LineState
- type NullComparisonParts
- type Pass
- type SelectStarOptions
- type Severity
- type SuggestedFix
- type Suppressions
- type TableMetadataLookup
- type TimestampStringLiteralOptions
Constants ¶
const ConfigFileName = ".bqls.yaml"
ConfigFileName is the settings file shared by the CLI and the language server.
Variables ¶
var Analyzers = []*Analyzer{ NullComparison, InNull, NotInNullable, UnusedCTE, UnusedColumnInCTE, UnusedDeclare, UnusedTempFunction, UnusedTempFunctionArgument, PartitionFilter, PartitionFilterNotPrunable, OrderByInSubquery, UnusedJoin, WildcardTableSuffix, WildcardTableSuffixNotConstant, CrossJoin, UnionColumnOrder, InsertColumnOrder, InsertNullIntoRequired, InsertMissingRequired, BytesProcessedThreshold, SelectStar, LeftJoinAsInner, VariableColumnShadow, JoinKeyImplicitCast, SelfComparison, MissingOrderBy, TimestampStringLiteral, NondeterministicCTE, WindowDefaultFrame, RegexpLiteral, ArrayNullElement, }
Analyzers is every rule bqls ships; Config decides which of them run.
var ArrayNullElement = &Analyzer{ Name: "array-null-element", Doc: "reports arrays that may hold a NULL element and reach the result, which BigQuery fails to write", DefaultEnabled: false, Run: runArrayNullElement, }
var BytesProcessedThreshold = &Analyzer{ Name: "bytes-processed-threshold", Doc: "reports queries whose dry-run estimate exceeds max_bytes", DefaultEnabled: false, NewOptions: func() any { return &BytesProcessedThresholdOptions{MaxBytes: 1 << 40} }, Run: runBytesProcessedThreshold, }
BytesProcessedThreshold is off by default because it only has input when a dry-run has been run, which costs a BigQuery API call.
var CrossJoin = &Analyzer{ Name: "cross-join", Doc: "reports joins without a join condition, which return the Cartesian product of both sides", DefaultEnabled: true, Run: runCrossJoin, }
var InNull = &Analyzer{ Name: "in-null", Doc: "reports `IN (NULL)` / `NOT IN (NULL)` lists of only NULLs, which always yield NULL, and `NOT IN` lists with a NULL, which never yield TRUE", DefaultEnabled: true, Run: runInNull, }
var InsertColumnOrder = &Analyzer{ Name: "insert-column-order", Doc: "reports INSERT queries whose columns are the target columns in a different order", DefaultEnabled: true, Run: runInsertColumnOrder, }
var InsertMissingRequired = &Analyzer{ Name: "insert-missing-required", Doc: "reports INSERT column lists, also in MERGE, that leave out a REQUIRED column without a default value, which BigQuery rejects only at run time", DefaultEnabled: true, Run: runInsertMissingRequired, }
var InsertNullIntoRequired = &Analyzer{
Name: "insert-null-into-required",
Doc: "reports INSERT, UPDATE and MERGE statements that write a value that may be NULL into a REQUIRED column, which BigQuery rejects only at run time",
Run: runInsertNullIntoRequired,
}
var JoinKeyImplicitCast = &Analyzer{ Name: "join-key-implicit-cast", Doc: "reports join keys in ON / USING whose types differ, so one side is implicitly cast", DefaultEnabled: true, Run: runJoinKeyImplicitCast, }
var LeftJoinAsInner = &Analyzer{ Name: "left-join-as-inner", Doc: "reports LEFT / RIGHT JOINs whose WHERE clause rejects the NULL rows of the optional side, so they behave as INNER JOINs", DefaultEnabled: true, Run: runLeftJoinAsInner, }
var MissingOrderBy = &Analyzer{
Name: "missing-order-by",
Doc: "reports ROW_NUMBER filters, ARRAY_AGG / STRING_AGG with LIMIT, and indexed ARRAY_AGG results that have no ORDER BY, so they pick arbitrary rows",
Run: runMissingOrderBy,
}
var NondeterministicCTE = &Analyzer{ Name: "nondeterministic-cte", Doc: "reports RAND() / GENERATE_UUID() in a CTE that is evaluated more than once", DefaultEnabled: true, Run: runNondeterministicCTE, }
var NotInNullable = &Analyzer{ Name: "not-in-nullable", Doc: "reports `x NOT IN (subquery)` whose subquery returns a NULLABLE table column, which yields no rows once that column holds a NULL", DefaultEnabled: true, Run: runNotInNullable, }
var NullComparison = &Analyzer{ Name: "null-comparison", Doc: "reports `= NULL` / `!= NULL` comparisons, which always yield NULL", DefaultEnabled: true, Run: runNullComparison, }
var OrderByInSubquery = &Analyzer{ Name: "order-by-in-subquery", Doc: "reports ORDER BY in a subquery, CTE or derived table whose order cannot reach the result", DefaultEnabled: true, Run: runOrderByInSubquery, }
var PartitionFilter = &Analyzer{ Name: "partition-filter", Doc: "reports queries on partitioned tables that never filter on the partition column", DefaultEnabled: true, Run: runPartitionFilter, }
var PartitionFilterNotPrunable = &Analyzer{ Name: "partition-filter-not-prunable", Doc: "reports partition column filters written in a form BigQuery documents as unable to prune partitions", DefaultEnabled: false, Run: runPartitionFilterNotPrunable, }
PartitionFilterNotPrunable is off by default because its patterns come from the BigQuery documentation rather than from the optimizer itself, which may learn to prune some of them, and bqls cannot confirm pruning per table.
var RegexpLiteral = &Analyzer{ Name: "regexp-literal", Doc: "reports constant regular expressions that BigQuery rejects when evaluated", DefaultEnabled: true, Run: runRegexpLiteral, }
var SelectStar = &Analyzer{ Name: "select-star", Doc: "reports SELECT * that reads at least min_columns columns of a table", DefaultEnabled: false, NewOptions: func() any { return &SelectStarOptions{MinColumns: 50} }, Run: runSelectStar, }
SelectStar is off by default because whether reading every column is wasteful depends on intent (ad-hoc exploration, a deliberate full-row dump), and so does a sensible min_columns.
var SelfComparison = &Analyzer{ Name: "self-comparison", Doc: "reports a comparison whose two operands are the same column, which is usually a typo for another column", DefaultEnabled: true, Run: runSelfComparison, }
var TimestampStringLiteral = &Analyzer{ Name: "timestamp-string-literal", Doc: "reports a string literal without a time zone implicitly converted to TIMESTAMP in a comparison", DefaultEnabled: false, NewOptions: func() any { return &TimestampStringLiteralOptions{} }, Run: runTimestampStringLiteral, }
var UnionColumnOrder = &Analyzer{ Name: "union-column-order", Doc: "reports set operation inputs whose columns are the first input's columns in a different order", DefaultEnabled: true, Run: runUnionColumnOrder, }
var UnusedCTE = &Analyzer{ Name: "unused-cte", Doc: "reports WITH entries that are never referenced", DefaultEnabled: true, Run: runUnusedCTE, }
var UnusedColumnInCTE = &Analyzer{ Name: "unused-column-in-cte", Doc: "reports CTE output columns that nothing downstream reads", DefaultEnabled: true, Run: runUnusedColumnInCTE, }
var UnusedDeclare = &Analyzer{ Name: "unused-declare", Doc: "reports DECLARE variables that are never referenced", DefaultEnabled: true, Run: runUnusedDeclare, }
var UnusedJoin = &Analyzer{ Name: "unused-join", Doc: "reports LEFT / RIGHT JOINs whose optional side is never used outside the join condition", DefaultEnabled: true, Run: runUnusedJoin, }
var UnusedTempFunction = &Analyzer{ Name: "unused-temp-function", Doc: "reports CREATE TEMP FUNCTION definitions that are never called", DefaultEnabled: true, Run: runUnusedTempFunction, }
var UnusedTempFunctionArgument = &Analyzer{ Name: "unused-temp-function-argument", Doc: "reports arguments of SQL temp functions that the body never references", DefaultEnabled: true, Run: runUnusedTempFunctionArgument, }
var VariableColumnShadow = &Analyzer{ Name: "variable-column-shadow", Doc: "reports a column compared with itself because its bare name was meant as a same-named DECLARE variable", DefaultEnabled: true, Run: runVariableColumnShadow, }
var WildcardTableSuffix = &Analyzer{ Name: "wildcard-table-suffix", Doc: "reports wildcard table queries that never filter on _TABLE_SUFFIX", DefaultEnabled: true, Run: runWildcardTableSuffix, }
var WildcardTableSuffixNotConstant = &Analyzer{ Name: "wildcard-table-suffix-not-constant", Doc: "reports _TABLE_SUFFIX filters that BigQuery documents as unable to limit the tables a wildcard table query scans", DefaultEnabled: false, Run: runWildcardTableSuffixNotConstant, }
WildcardTableSuffixNotConstant is off by default for the same reason as PartitionFilterNotPrunable: its patterns come from the documentation.
var WindowDefaultFrame = &Analyzer{ Name: "window-default-frame", Doc: "reports LAST_VALUE / NTH_VALUE whose window has ORDER BY but no frame, so the default frame ends at the current row instead of the end of the partition", DefaultEnabled: true, Run: runWindowDefaultFrame, }
Functions ¶
func FindConfigFile ¶ added in v0.8.1
FindConfigFile looks for ConfigFileName in dir and its parents, stopping at the repository root (a directory containing .git, which is a file in worktrees) so that a checkout never picks up settings from outside it.
func HasComment ¶
HasComment reports whether src contains a comment. Comment markers inside string literals and quoted identifiers are not comments.
func NullReplacement ¶
NullReplacement returns the IS [NOT] NULL form for a written comparison operator.
Types ¶
type Analyzer ¶
type Analyzer struct {
// Name is the rule identifier used in settings, suppression comments,
// and as the LSP diagnostic code.
Name string
Doc string
DefaultEnabled bool
// NewOptions returns a pointer to the rule's default options, which the
// configured options are decoded onto as JSON (unknown fields are
// rejected) and handed to Run as Pass.Options. Nil means the rule takes
// no options.
NewOptions func() any
Run func(*Pass)
}
Analyzer is a single lint rule.
type BytesProcessedThresholdOptions ¶ added in v0.8.2
func (*BytesProcessedThresholdOptions) Validate ¶ added in v0.8.2
func (o *BytesProcessedThresholdOptions) Validate() error
type Config ¶
type Config struct {
Rules map[string]bool `json:"rules,omitempty"`
// Options holds each rule's options object without "enabled". It is
// decoded into the rule's NewOptions value only when the rule runs, so
// a config can be parsed without knowing the rules.
Options map[string]json.RawMessage `json:"-"`
}
Config is the user-facing lint settings. Each entry under "rules" is either a bool or an object with an optional "enabled" and the rule's options:
{"rules": {"null-comparison": false, "some-rule": {"enabled": true, "max": 3}}}
The Diagnose cache in package source compares configs with Equal, so update it when adding a field.
func LoadConfigFile ¶ added in v0.8.1
func ParseConfigFile ¶ added in v0.8.1
ParseConfigFile reads the "lint" section of a config file. Other top-level keys are left for other features.
func (Config) Clone ¶ added in v0.8.1
Clone returns a deep copy, so a caller can keep c while others mutate theirs.
func (Config) Enabled ¶
Enabled reports whether a is enabled, letting user settings override the default.
func (Config) Override ¶ added in v0.8.1
Override returns c with the settings in o applied on top. Options are merged key by key, so o can change one option without restating the rest. Neither c nor o is modified.
func (*Config) UnmarshalJSON ¶ added in v0.8.1
type Diagnostic ¶
type Diagnostic struct {
Rule string
Range lsp.Range
Message string
Severity Severity
SuggestedFixes []SuggestedFix
}
func Run ¶
func Run(ctx context.Context, f file.ParsedFile, cfg Config, env Env, analyzers ...*Analyzer) []Diagnostic
Run executes the enabled analyzers over f and returns unsuppressed diagnostics. Files that failed analysis are skipped because rules rely on a complete resolved AST and would otherwise produce noise on top of real errors.
type Env ¶
type Env struct {
LookupTable TableMetadataLookup
DryRun *bq.JobStatus
}
Env carries optional external inputs to analyzers. Every field may be nil.
type IgnoreLine ¶
type IgnoreLine struct {
// Rules is empty when every rule is ignored.
Rules []string
// RulesEnd is the byte offset in the line where another rule name can be
// appended.
RulesEnd int
}
IgnoreLine is a line consisting only of a `bqls:ignore` comment.
func ParseIgnoreLine ¶
func ParseIgnoreLine(line string) (IgnoreLine, bool)
ParseIgnoreLine reports whether line is a standalone `bqls:ignore` directive, which ParseSuppressions applies to the following line.
type LineState ¶
type LineState struct {
// StartsInCode is false when the line begins inside a string literal or
// block comment opened on an earlier line.
StartsInCode bool
// EndsInCode is false when the line ends inside a string literal or a
// comment.
EndsInCode bool
}
LineState tells whether a line's edges are outside string literals and comments, i.e. whether text inserted there would be read as code.
func LineStates ¶
LineStates returns the LineState of every line in src.
type NullComparisonParts ¶
NullComparisonParts is a `<other> <op> <null>` comparison split from its source text.
func SplitNullComparison ¶
func SplitNullComparison(cmpSrc, nullSrc string, nullOnRight bool) (NullComparisonParts, bool)
SplitNullComparison slices the non-NULL operand and the operator out of the comparison's own source text rather than using the operand's location, because locations exclude parentheses the user wrote around either side.
type Pass ¶
type Pass struct {
Context context.Context
Analyzer *Analyzer
File file.ParsedFile
// LookupTable is nil-safe to call; it returns (nil, nil) when no lookup is configured.
LookupTable TableMetadataLookup
DryRun *bq.JobStatus
// Options is the value from Analyzer.NewOptions with the configured
// options applied, or nil when the analyzer takes none.
Options any
// contains filtered or unexported fields
}
Pass is the input to a single Analyzer run over one file.
func (*Pass) Report ¶
func (p *Pass) Report(d Diagnostic)
Report records a diagnostic. Rule defaults to the analyzer's name, and any severity other than Information is reported as Warning.
type SelectStarOptions ¶ added in v0.8.2
type SelectStarOptions struct {
MinColumns int `json:"min_columns"`
}
func (*SelectStarOptions) Validate ¶ added in v0.8.2
func (o *SelectStarOptions) Validate() error
type Severity ¶
type Severity = lsp.DiagnosticSeverity
Severity is restricted to non-error levels so that lint findings never look like analysis failures.
type SuggestedFix ¶
func LiteralNullComparisonFix ¶
func LiteralNullComparisonFix(f file.ParsedFile, e file.Error) (SuggestedFix, bool)
LiteralNullComparisonFix builds an IS [NOT] NULL rewrite for GoogleSQL's "Operands of = cannot be literal NULL" analysis error. Lint never runs on files with errors, so this fix hangs off the error diagnostic instead.
type Suppressions ¶
type Suppressions map[int]suppression
Suppressions maps a 0-based line number to the rules suppressed on it.
func ParseSuppressions ¶
func ParseSuppressions(src string) Suppressions
ParseSuppressions scans src for `bqls:ignore` comment directives.
A directive in a comment that follows code on the same line suppresses that line; a directive in a comment alone on its line suppresses the next line. Without rule names, every rule is suppressed.
func (Suppressions) Suppressed ¶
func (s Suppressions) Suppressed(rule string, line int) bool
Suppressed reports whether diagnostics of rule starting on line are suppressed.
type TableMetadataLookup ¶
TableMetadataLookup fetches metadata for a `project.dataset.table` path.
type TimestampStringLiteralOptions ¶ added in v0.8.2
type TimestampStringLiteralOptions struct {
// TimeZone is the zone the literals are usually meant in, offered as a
// second quick fix.
TimeZone string `json:"time_zone"`
}
func (*TimestampStringLiteralOptions) Validate ¶ added in v0.8.2
func (o *TimestampStringLiteralOptions) Validate() error
Source Files
¶
- analyzers.go
- array_null_element.go
- bytes_processed_threshold.go
- column_order.go
- config.go
- config_file.go
- cross_join.go
- in_null.go
- insert_column_order.go
- insert_missing_required.go
- insert_null_into_required.go
- join_key_implicit_cast.go
- left_join_as_inner.go
- lint.go
- missing_order_by.go
- nondeterministic_cte.go
- not_in_nullable.go
- null_comparison.go
- null_literal_error.go
- order_by_in_subquery.go
- partition_filter.go
- partition_filter_not_prunable.go
- regexp_literal.go
- select_star.go
- self_comparison.go
- suppress.go
- timestamp_string_literal.go
- union_column_order.go
- unused_column_in_cte.go
- unused_cte.go
- unused_declare.go
- unused_join.go
- unused_temp_function.go
- unused_temp_function_argument.go
- variable_column_shadow.go
- wildcard_table_suffix.go
- wildcard_table_suffix_not_constant.go
- window_default_frame.go