lint

package
v0.8.7 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 23 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 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

View Source
const ConfigFileName = ".bqls.yaml"

ConfigFileName is the settings file shared by the CLI and the language server.

Variables

Analyzers is every rule bqls ships; Config decides which of them run.

View Source
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,
}
View Source
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.

View Source
var CastDivisionRounds = &Analyzer{
	Name:           "cast-division-rounds",
	Doc:            "reports CAST(a / b AS INT64) of integers, which rounds the FLOAT64 quotient instead of truncating it",
	DefaultEnabled: true,
	Run:            runCastDivisionRounds,
}
View Source
var ClusterFilter = &Analyzer{
	Name:           "cluster-filter",
	Doc:            "reports clustered tables read without a filter on the first clustering column, or with a clustering column skipped",
	DefaultEnabled: false,
	Run:            runClusterFilter,
}

Both clustering rules are off by default: clustering only lowers the cost under on-demand pricing, BigQuery does not show the saving in a dry run, and reading a clustered table in full is often intended.

View Source
var ClusterFilterNotPrunable = &Analyzer{
	Name:           "cluster-filter-not-prunable",
	Doc:            "reports clustering column filters written in a form BigQuery documents as unable to reduce the data read",
	DefaultEnabled: false,
	Run:            runClusterFilterNotPrunable,
}
View Source
var ComparisonImplicitCast = &Analyzer{
	Name:           "comparison-implicit-cast",
	Doc:            "reports comparisons outside join keys between columns of different types, so one side is implicitly cast",
	DefaultEnabled: true,
	Run:            runComparisonImplicitCast,
}
View Source
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,
}
View Source
var DateBoundOnDatetime = &Analyzer{
	Name:           "date-bound-on-datetime",
	Doc:            "reports DATETIME / TIMESTAMP values whose upper bound or equality is written as a date, which stands for midnight",
	DefaultEnabled: true,
	Run:            runDateBoundOnDatetime,
}
View Source
var ImplicitOuterReference = &Analyzer{
	Name:           "implicit-outer-reference",
	Doc:            "reports unqualified column names in a subquery that refer to a column of the outer query",
	DefaultEnabled: true,
	Run:            runImplicitOuterReference,
}
View Source
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,
}
View Source
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,
}
View Source
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,
}
View Source
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,
}
View Source
var InsertWithoutColumnList = &Analyzer{
	Name:           "insert-without-column-list",
	Doc:            "reports INSERT statements without a column list, whose values are matched to the table's columns by position",
	DefaultEnabled: true,
	Run:            runInsertWithoutColumnList,
}
View Source
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,
}
View Source
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,
}
View Source
var LimitWithoutOrderBy = &Analyzer{
	Name:           "limit-without-order-by",
	Doc:            "reports LIMIT without ORDER BY in subqueries, CTEs and DML, and LIMIT ... OFFSET without ORDER BY, which keep arbitrary rows",
	DefaultEnabled: false,
	Run:            runLimitWithoutOrderBy,
}
View Source
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,
}
View Source
var NondeterministicCTE = &Analyzer{
	Name:           "nondeterministic-cte",
	Doc:            "reports RAND() / GENERATE_UUID() in a CTE that is evaluated more than once",
	DefaultEnabled: true,
	Run:            runNondeterministicCTE,
}
View Source
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,
}
View Source
var NullComparison = &Analyzer{
	Name:           "null-comparison",
	Doc:            "reports `= NULL` / `!= NULL` comparisons, which always yield NULL",
	DefaultEnabled: true,
	Run:            runNullComparison,
}
View Source
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,
}
View Source
var PartitionFilter = &Analyzer{
	Name:           "partition-filter",
	Doc:            "reports queries on partitioned tables that never filter on the partition column",
	DefaultEnabled: true,
	Run:            runPartitionFilter,
}
View Source
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.

View Source
var RegexpLiteral = &Analyzer{
	Name:           "regexp-literal",
	Doc:            "reports constant regular expressions that BigQuery rejects when evaluated",
	DefaultEnabled: true,
	Run:            runRegexpLiteral,
}
View Source
var RepeatedCTEEvaluation = &Analyzer{
	Name:           "repeated-cte-evaluation",
	Doc:            "reports CTEs that join, aggregate or use window functions over tables and are evaluated more than once",
	DefaultEnabled: false,
	Run:            runRepeatedCTEEvaluation,
}
View Source
var RepeatedNullCheck = &Analyzer{
	Name:           "repeated-null-check",
	Doc:            "reports IS [NOT] NULL on a REPEATED table column, which BigQuery never stores as NULL",
	DefaultEnabled: true,
	Run:            runRepeatedNullCheck,
}
View Source
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.

View Source
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,
}
View Source
var SetOperationImplicitCast = &Analyzer{
	Name:           "set-operation-implicit-cast",
	Doc:            "reports set operation columns that are implicitly cast to FLOAT64 because another input has a FLOAT64 there",
	DefaultEnabled: true,
	Run:            runSetOperationImplicitCast,
}
View Source
var TimestampDateWithoutZone = &Analyzer{
	Name:           "timestamp-date-without-zone",
	Doc:            "reports DATE / EXTRACT / TIMESTAMP_TRUNC and friends of a TIMESTAMP without a time zone, which work in UTC",
	DefaultEnabled: false,
	NewOptions:     func() any { return &TimestampDateWithoutZoneOptions{} },
	Run:            runTimestampDateWithoutZone,
}
View Source
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,
}
View Source
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,
}
View Source
var UnusedCTE = &Analyzer{
	Name:           "unused-cte",
	Doc:            "reports WITH entries that are never referenced",
	DefaultEnabled: true,
	Run:            runUnusedCTE,
}
View Source
var UnusedColumnInCTE = &Analyzer{
	Name:           "unused-column-in-cte",
	Doc:            "reports CTE output columns that nothing downstream reads",
	DefaultEnabled: true,
	Run:            runUnusedColumnInCTE,
}
View Source
var UnusedDeclare = &Analyzer{
	Name:           "unused-declare",
	Doc:            "reports DECLARE variables that are never referenced",
	DefaultEnabled: true,
	Run:            runUnusedDeclare,
}
View Source
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,
}
View Source
var UnusedTempFunction = &Analyzer{
	Name:           "unused-temp-function",
	Doc:            "reports CREATE TEMP FUNCTION definitions that are never called",
	DefaultEnabled: true,
	Run:            runUnusedTempFunction,
}
View Source
var UnusedTempFunctionArgument = &Analyzer{
	Name:           "unused-temp-function-argument",
	Doc:            "reports arguments of SQL temp functions that the body never references",
	DefaultEnabled: true,
	Run:            runUnusedTempFunctionArgument,
}
View Source
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,
}
View Source
var WildcardTableSuffix = &Analyzer{
	Name:           "wildcard-table-suffix",
	Doc:            "reports wildcard table queries that never filter on _TABLE_SUFFIX",
	DefaultEnabled: true,
	Run:            runWildcardTableSuffix,
}
View Source
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.

View Source
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

func FindConfigFile(dir string) (string, bool)

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

func HasComment(src string) bool

HasComment reports whether src contains a comment. Comment markers inside string literals and quoted identifiers are not comments.

func NullReplacement

func NullReplacement(op string) (string, bool)

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

type BytesProcessedThresholdOptions struct {
	MaxBytes helper.ByteSize `json:"max_bytes"`
}

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 LoadConfigFile(path string) (Config, error)

func ParseConfigFile added in v0.8.1

func ParseConfigFile(b []byte) (Config, error)

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

func (c Config) Clone() Config

Clone returns a deep copy, so a caller can keep c while others mutate theirs.

func (Config) Enabled

func (c Config) Enabled(a *Analyzer) bool

Enabled reports whether a is enabled, letting user settings override the default.

func (Config) Equal added in v0.8.1

func (c Config) Equal(o Config) bool

func (Config) Override added in v0.8.1

func (c Config) Override(o Config) (Config, error)

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

func (c *Config) UnmarshalJSON(b []byte) error

func (Config) Validate added in v0.8.1

func (c Config) Validate(analyzers []*Analyzer) error

Validate reports rules that are not among analyzers and options that the rule would reject, so users see typos instead of silently ignored settings.

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

func LineStates(src string) []LineState

LineStates returns the LineState of every line in src.

type NullComparisonParts

type NullComparisonParts struct {
	Other string
	Op    string
}

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.

const (
	SeverityWarning     Severity = lsp.Warning
	SeverityInformation Severity = lsp.Information
)

type SuggestedFix

type SuggestedFix struct {
	Title string
	Edits []lsp.TextEdit
	// ChangesResult marks a fix that changes what the query computes, such
	// as one that rewrites it to what was probably meant. It is never the
	// preferred fix, so `bqls lint --fix` leaves it to the user.
	ChangesResult bool
}

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

type TableMetadataLookup func(ctx context.Context, path string) (*bq.TableMetadata, error)

TableMetadataLookup fetches metadata for a `project.dataset.table` path.

type TimestampDateWithoutZoneOptions added in v0.8.7

type TimestampDateWithoutZoneOptions struct {
	TimestampStringLiteralOptions
}

TimestampDateWithoutZoneOptions takes the same time_zone as timestamp-string-literal, offered as a second quick fix.

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

Jump to

Keyboard shortcuts

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