analyzer

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package analyzer provides the SQL static analysis implementation for detecting SELECT * usage.

Package analyzer provides the SQL static analysis implementation for detecting SELECT * usage.

Package analyzer provides the SQL static analysis implementation for detecting SELECT * usage.

Package analyzer provides the SQL static analysis implementation for detecting SELECT * usage.

Package analyzer provides the SQL static analysis implementation for detecting SELECT * usage.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnalyzeN1 added in v1.5.0

func AnalyzeN1(pass *analysis.Pass, file *ast.File)

AnalyzeN1 is a convenience function to run N+1 detection on a file.

func AnalyzeSQLInjection added in v1.5.0

func AnalyzeSQLInjection(pass *analysis.Pass, file *ast.File)

AnalyzeSQLInjection is a convenience function to run SQL injection scanning.

func AnalyzeTxLeaks added in v1.5.3

func AnalyzeTxLeaks(pass *analysis.Pass, file *ast.File)

AnalyzeTxLeaks is a convenience function to run transaction leak detection on a file.

func CheckConcatenation added in v1.4.0

func CheckConcatenation(pass *analysis.Pass, expr *ast.BinaryExpr, cfg *config.UnqueryvetSettings) bool

CheckConcatenation is a convenience function to check a binary expression for SELECT *. It creates an analyzer and performs the check in one call.

func CheckFormatFunction added in v1.4.0

func CheckFormatFunction(pass *analysis.Pass, call *ast.CallExpr, cfg *config.UnqueryvetSettings) bool

CheckFormatFunction is a convenience function to check a call expression for SELECT *. It creates an analyzer and performs the check in one call.

func CreateDiagnosticWithFix added in v1.4.0

func CreateDiagnosticWithFix(
	pos token.Pos,
	end token.Pos,
	message string,
	originalText string,
	violationType string,
	fset *token.FileSet,
) analysis.Diagnostic

CreateDiagnosticWithFix creates a Diagnostic with an optional SuggestedFix.

func IsFormatFunction added in v1.4.0

func IsFormatFunction(call *ast.CallExpr) bool

IsFormatFunction checks if a call expression is a known format function.

func IsRuleEnabledExported added in v1.5.1

func IsRuleEnabledExported(rules config.RuleSeverity, ruleID string) bool

IsRuleEnabledExported checks if a rule is enabled in the configuration. A rule is enabled if it exists in the Rules map and its severity is not "ignore".

func IsSelectStarQuery

func IsSelectStarQuery(query string, cfg *config.UnqueryvetSettings) bool

IsSelectStarQuery determines if query contains SELECT * with enhanced allowed patterns support. Exported for testing purposes.

func NewAnalyzer

func NewAnalyzer() *analysis.Analyzer

NewAnalyzer creates the Unqueryvet analyzer with enhanced logic for production use

func NewAnalyzerWithSettings

func NewAnalyzerWithSettings(s config.UnqueryvetSettings) *analysis.Analyzer

NewAnalyzerWithSettings creates analyzer with provided settings for golangci-lint integration

func NormalizeSQLQuery

func NormalizeSQLQuery(query string) string

NormalizeSQLQuery normalizes SQL query for analysis with advanced escape sequence handling. Exported for testing purposes.

func RunWithConfig

func RunWithConfig(pass *analysis.Pass, cfg *config.UnqueryvetSettings) (any, error)

RunWithConfig performs analysis with provided configuration This is the main entry point for configured analysis

Types

type FilterContext added in v1.4.0

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

FilterContext holds precompiled patterns for filtering files, functions, and queries. It provides efficient filtering by compiling regex patterns once during initialization.

func NewFilterContext added in v1.4.0

func NewFilterContext(cfg *config.UnqueryvetSettings) (*FilterContext, error)

NewFilterContext creates a new FilterContext from settings. It precompiles all regex patterns for efficient filtering. Returns an error if any pattern is invalid.

func (*FilterContext) IsAllowedPattern added in v1.4.0

func (fc *FilterContext) IsAllowedPattern(query string) bool

IsAllowedPattern checks if a query matches any of the allowed patterns. Returns true if the query should be allowed (not reported as a violation).

func (*FilterContext) IsIgnoredFile added in v1.4.0

func (fc *FilterContext) IsIgnoredFile(filePath string) bool

IsIgnoredFile checks if a file path matches any of the ignored file patterns. Supports glob patterns like "*_test.go", "testdata/**", "mock_*.go".

func (*FilterContext) IsIgnoredFunction added in v1.4.0

func (fc *FilterContext) IsIgnoredFunction(call *ast.CallExpr) bool

IsIgnoredFunction checks if a function call should be ignored based on configured patterns. It extracts the full function name (package.function or receiver.method) and matches against patterns.

type FormatStringAnalyzer added in v1.4.0

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

FormatStringAnalyzer analyzes format functions like fmt.Sprintf for SELECT * patterns.

func NewFormatStringAnalyzer added in v1.4.0

func NewFormatStringAnalyzer(pass *analysis.Pass, cfg *config.UnqueryvetSettings) *FormatStringAnalyzer

NewFormatStringAnalyzer creates a new FormatStringAnalyzer.

func (*FormatStringAnalyzer) AnalyzeFormatCall added in v1.4.0

func (fsa *FormatStringAnalyzer) AnalyzeFormatCall(call *ast.CallExpr) bool

AnalyzeFormatCall analyzes a function call for format string patterns with SELECT *. Returns true if SELECT * was detected in the format string.

type N1Detector added in v1.5.0

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

N1Detector detects potential N+1 query problems. An N+1 query problem occurs when a SQL query is executed inside a loop, causing one query per iteration instead of a single batch query.

func NewN1Detector added in v1.5.0

func NewN1Detector() *N1Detector

NewN1Detector creates a new N+1 query detector.

func (*N1Detector) CheckN1Queries added in v1.5.0

func (d *N1Detector) CheckN1Queries(pass *analysis.Pass, file *ast.File) []N1Violation

CheckN1Queries analyzes the file for N+1 query patterns.

func (*N1Detector) CheckN1QueriesNoPass added in v1.5.1

func (d *N1Detector) CheckN1QueriesNoPass(file *ast.File) []N1Violation

CheckN1QueriesNoPass is a method to check for N+1 queries without analysis.Pass. This is useful for testing.

type N1Severity added in v1.5.0

type N1Severity string

N1Severity represents the severity level of an N+1 violation.

const (
	N1SeverityCritical N1Severity = "critical" // Direct query in loop
	N1SeverityHigh     N1Severity = "high"     // ORM method in loop
	N1SeverityMedium   N1Severity = "medium"   // Indirect query via function call
	N1SeverityLow      N1Severity = "low"      // Potential issue, needs review
)

type N1Violation added in v1.5.0

type N1Violation struct {
	Pos          token.Pos
	End          token.Pos
	Message      string
	LoopType     string     // "for", "range", or "while-like"
	QueryType    string     // The method name that was called
	Severity     N1Severity // Severity level
	Suggestion   string     // Suggested fix
	IsIndirect   bool       // True if detected via function call
	FunctionName string     // Name of the function if indirect
}

N1Violation represents a detected N+1 query problem.

func DetectN1InAST added in v1.5.0

func DetectN1InAST(fset *token.FileSet, file *ast.File) []N1Violation

DetectN1InAST detects N+1 query problems in an AST file without analysis.Pass. This is designed for use in LSP server where we don't have a full analysis pass.

func GetN1Violations added in v1.5.0

func GetN1Violations(pass *analysis.Pass, file *ast.File) []N1Violation

GetN1Violations returns all N+1 violations for external use.

type SQLISeverity added in v1.5.0

type SQLISeverity string

SQLISeverity represents the severity level of SQL injection vulnerability.

const (
	SQLISeverityCritical SQLISeverity = "critical" // Direct user input in query
	SQLISeverityHigh     SQLISeverity = "high"     // Format string with variables
	SQLISeverityMedium   SQLISeverity = "medium"   // String concatenation
	SQLISeverityLow      SQLISeverity = "low"      // Potential issue, needs review
)

type SQLInjectionScanner added in v1.5.0

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

SQLInjectionScanner detects potential SQL injection vulnerabilities.

func NewSQLInjectionScanner added in v1.5.0

func NewSQLInjectionScanner() *SQLInjectionScanner

NewSQLInjectionScanner creates a new SQL injection scanner.

func (*SQLInjectionScanner) MarkVariableAsTainted added in v1.5.0

func (s *SQLInjectionScanner) MarkVariableAsTainted(name string)

MarkVariableAsTainted marks a variable as containing user input.

func (*SQLInjectionScanner) ScanFile added in v1.5.0

func (s *SQLInjectionScanner) ScanFile(pass *analysis.Pass, file *ast.File) []SQLInjectionViolation

ScanFile scans a file for SQL injection vulnerabilities.

func (*SQLInjectionScanner) ScanFileNoPass added in v1.5.1

func (s *SQLInjectionScanner) ScanFileNoPass(fset *token.FileSet, file *ast.File) []SQLInjectionViolation

ScanFileNoPass scans a file for SQL injection vulnerabilities without analysis.Pass. This is a method version for testing purposes.

type SQLInjectionViolation added in v1.5.0

type SQLInjectionViolation struct {
	Pos        token.Pos
	End        token.Pos
	Message    string
	Severity   SQLISeverity
	VulnType   string // "concat", "sprintf", "exec", "tainted", "orm_raw"
	Suggestion string
	CodeFix    string // Suggested code fix
}

SQLInjectionViolation represents a detected SQL injection vulnerability.

func GetSQLInjectionViolations added in v1.5.0

func GetSQLInjectionViolations(pass *analysis.Pass, file *ast.File) []SQLInjectionViolation

GetSQLInjectionViolations returns all SQL injection violations for external use.

func ScanFileAST added in v1.5.0

func ScanFileAST(fset *token.FileSet, file *ast.File) []SQLInjectionViolation

ScanFileAST scans a file for SQL injection vulnerabilities without analysis.Pass. This is designed for use in LSP server where we don't have a full analysis pass.

type StringConcatAnalyzer added in v1.4.0

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

StringConcatAnalyzer analyzes string concatenation expressions for SELECT * patterns. It traverses binary expressions to combine string parts and check for SELECT * usage.

func NewStringConcatAnalyzer added in v1.4.0

func NewStringConcatAnalyzer(pass *analysis.Pass, cfg *config.UnqueryvetSettings) *StringConcatAnalyzer

NewStringConcatAnalyzer creates a new StringConcatAnalyzer.

func (*StringConcatAnalyzer) AnalyzeBinaryExpr added in v1.4.0

func (sca *StringConcatAnalyzer) AnalyzeBinaryExpr(expr *ast.BinaryExpr) bool

AnalyzeBinaryExpr analyzes a binary expression for string concatenation with SELECT *. Returns true if SELECT * was detected in the concatenated string.

type SuggestedFixGenerator added in v1.4.0

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

SuggestedFixGenerator generates auto-fix suggestions for SELECT * violations.

func NewSuggestedFixGenerator added in v1.4.0

func NewSuggestedFixGenerator(fset *token.FileSet) *SuggestedFixGenerator

NewSuggestedFixGenerator creates a new SuggestedFixGenerator.

func (*SuggestedFixGenerator) GenerateAliasedColumnPlaceholder added in v1.4.0

func (sfg *SuggestedFixGenerator) GenerateAliasedColumnPlaceholder(alias string) string

GenerateAliasedColumnPlaceholder returns a placeholder with table alias.

func (*SuggestedFixGenerator) GenerateColumnPlaceholder added in v1.4.0

func (sfg *SuggestedFixGenerator) GenerateColumnPlaceholder() string

GenerateColumnPlaceholder returns a placeholder string for explicit columns.

func (*SuggestedFixGenerator) GenerateFix added in v1.4.0

func (sfg *SuggestedFixGenerator) GenerateFix(
	pos token.Pos,
	end token.Pos,
	originalText string,
	violationType string,
) *analysis.SuggestedFix

GenerateFix creates a SuggestedFix for a SELECT * violation.

type TxLeakDetector added in v1.5.3

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

TxLeakDetector detects unclosed SQL transactions.

func NewTxLeakDetector added in v1.5.3

func NewTxLeakDetector() *TxLeakDetector

NewTxLeakDetector creates a new transaction leak detector.

func (*TxLeakDetector) CheckTxLeaks added in v1.5.3

func (d *TxLeakDetector) CheckTxLeaks(pass *analysis.Pass, file *ast.File) []TxLeakViolation

CheckTxLeaks analyzes a file for unclosed transaction patterns.

type TxLeakSeverity added in v1.5.3

type TxLeakSeverity string

TxLeakSeverity represents the severity level of a transaction leak.

const (
	TxLeakSeverityCritical TxLeakSeverity = "critical" // Begin without any Commit/Rollback
	TxLeakSeverityHigh     TxLeakSeverity = "high"     // Begin with Commit but no Rollback in error path
	TxLeakSeverityMedium   TxLeakSeverity = "medium"   // Begin with Rollback but no Commit
	TxLeakSeverityLow      TxLeakSeverity = "low"      // Informational - potential issue
)

type TxLeakViolation added in v1.5.3

type TxLeakViolation struct {
	Pos           token.Pos
	End           token.Pos
	Message       string
	Severity      TxLeakSeverity
	ViolationType string // violation type identifier
	TxVarName     string // Name of the transaction variable
	Suggestion    string
}

TxLeakViolation represents a detected unclosed transaction.

func DetectTxLeaksInAST added in v1.5.3

func DetectTxLeaksInAST(fset *token.FileSet, file *ast.File) []TxLeakViolation

DetectTxLeaksInAST detects transaction leak problems in an AST file without analysis.Pass. This is designed for use in LSP server where we don't have a full analysis pass.

func GetTxLeakViolations added in v1.5.3

func GetTxLeakViolations(pass *analysis.Pass, file *ast.File) []TxLeakViolation

GetTxLeakViolations returns all transaction leak violations for external use.

type TxState added in v1.5.3

type TxState struct {
	VarName               string
	BeginPos              token.Pos
	BeginEnd              token.Pos
	HasCommit             bool
	HasRollback           bool
	HasDefer              bool      // Rollback/Commit in defer
	HasDeferredCommit     bool      // Commit() is in defer - antipattern
	IsReturned            bool      // Transaction returned to caller
	IsReturnedInClosure   bool      // Transaction captured by returned closure
	IsCallback            bool      // Transaction used in callback pattern
	IsPassedToFunc        bool      // Transaction passed to another function
	IsSentToChannel       bool      // Transaction sent through channel (ch <- tx)
	IsStoredInStruct      bool      // Transaction stored in struct field
	IsStoredInCollection  bool      // Transaction stored in map or slice
	IsCapturedByGoroutine bool      // Transaction captured by goroutine
	IsShadowed            bool      // Variable is shadowed in inner scope
	ShadowedBy            token.Pos // Position where shadowing occurs
	HasPanicPath          bool      // Function has panic() without deferred rollback
	HasFatalPath          bool      // Function has os.Exit/log.Fatal without deferred rollback
	HasEarlyReturn        bool      // Has return before commit without defer
	CommitInConditional   bool      // Commit is inside conditional block
	CommitInSwitch        bool      // Commit is inside switch/case that might not execute
	CommitInSelect        bool      // Commit is inside select/case that might not execute
	CommitInLoop          bool      // Commit is inside loop that might not iterate
	IsReassigned          bool      // Transaction variable is reassigned
	CommitErrorIgnored    bool      // Commit() error is ignored with blank identifier
	RollbackErrorIgnored  bool      // Rollback() error is ignored with blank identifier
	HasDeferInLoop        bool      // Transaction has defer inside a loop (antipattern)
	Scope                 int       // Scope depth where transaction was created
}

TxState tracks the state of a transaction variable within a function.

Directories

Path Synopsis
Package sqlbuilders provides SQL builder library-specific checkers for SELECT * detection.
Package sqlbuilders provides SQL builder library-specific checkers for SELECT * detection.

Jump to

Keyboard shortcuts

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