Documentation
¶
Overview ¶
Package dsl provides a domain-specific language for defining custom SQL analysis rules.
Index ¶
- Variables
- func BuiltinFunctionDescriptions() map[string]string
- func BuiltinRuleDescriptions() map[string]string
- func BuiltinVariableDescriptions() map[string]string
- func ExtractQueryType(query string) string
- func ExtractTableNames(query string) []string
- func GetBuiltinFunctionNames() []string
- func GetBuiltinRules() []string
- func HasJoinClause(query string) bool
- func HasWhereClause(query string) bool
- func IsBuiltinRule(id string) bool
- func JSONSchema() string
- func LoadAndCreateAnalyzer(configPath string) (*analysis.Analyzer, error)
- func MetavariableDescriptions() map[string]string
- func SchemaURL() string
- type Action
- type CompiledPattern
- type CompiledRule
- type Compiler
- type Config
- type DSLAnalyzer
- type EvalContext
- type Evaluator
- type LegacyConfig
- type Match
- type Parser
- func (p *Parser) DefaultConfig() *Config
- func (p *Parser) FindConfigFile(startDir string) string
- func (p *Parser) LoadConfig(startDir string) (*Config, error)
- func (p *Parser) MergeConfigs(configs ...*Config) *Config
- func (p *Parser) Parse(data []byte) (*Config, error)
- func (p *Parser) ParseFile(path string) (*Config, error)
- type PatternCompiler
- type Rule
- type Severity
Constants ¶
This section is empty.
Variables ¶
var BuiltinFunctions = map[string]interface{}{ "contains": strings.Contains, "hasPrefix": strings.HasPrefix, "hasSuffix": strings.HasSuffix, "toLower": strings.ToLower, "toUpper": strings.ToUpper, "trim": strings.TrimSpace, "startsWith": strings.HasPrefix, "endsWith": strings.HasSuffix, "matches": matchesRegex, "notMatches": notMatchesRegex, "isSystemTable": isSystemTable, "isAggregate": isAggregate, "isTempTable": isTempTable, "len": length, "any": anyMatch, "all": allMatch, "contains_any": containsAny, }
BuiltinFunctions provides functions available in DSL conditions. These are registered with expr-lang for use in "when" expressions.
var SQLKeywords = []string{
"SELECT", "FROM", "WHERE", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER",
"ON", "AND", "OR", "NOT", "IN", "EXISTS", "BETWEEN", "LIKE", "IS",
"NULL", "ORDER", "BY", "GROUP", "HAVING", "LIMIT", "OFFSET",
"INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE",
"CREATE", "ALTER", "DROP", "TABLE", "INDEX", "VIEW",
"UNION", "INTERSECT", "EXCEPT", "ALL", "DISTINCT",
"AS", "ASC", "DESC", "CASE", "WHEN", "THEN", "ELSE", "END",
}
SQLKeywords contains common SQL keywords for pattern matching.
Functions ¶
func BuiltinFunctionDescriptions ¶
BuiltinFunctionDescriptions returns descriptions for DSL functions.
func BuiltinRuleDescriptions ¶
BuiltinRuleDescriptions returns descriptions for built-in rules.
func BuiltinVariableDescriptions ¶
BuiltinVariableDescriptions returns descriptions for DSL variables.
func ExtractQueryType ¶
ExtractQueryType extracts the type of SQL query (SELECT, INSERT, etc.).
func ExtractTableNames ¶
ExtractTableNames attempts to extract table names from a query. This is a simple implementation - for complex queries, use a proper SQL parser.
func GetBuiltinFunctionNames ¶
func GetBuiltinFunctionNames() []string
GetBuiltinFunctionNames returns the names of all built-in functions.
func GetBuiltinRules ¶
func GetBuiltinRules() []string
GetBuiltinRules returns the IDs of built-in rules.
func HasJoinClause ¶
HasJoinClause checks if a query has a JOIN clause.
func HasWhereClause ¶
HasWhereClause checks if a query has a WHERE clause.
func IsBuiltinRule ¶
IsBuiltinRule checks if a rule ID is a built-in rule.
func JSONSchema ¶
func JSONSchema() string
JSONSchema returns the JSON Schema for .unqueryvet.yaml configuration. This can be used by IDEs for validation and autocompletion.
func LoadAndCreateAnalyzer ¶
LoadAndCreateAnalyzer loads config from file and creates an analyzer.
func MetavariableDescriptions ¶
MetavariableDescriptions returns descriptions for pattern metavariables.
Types ¶
type CompiledPattern ¶
type CompiledPattern struct {
Original string
Regex *regexp.Regexp
Metavars []string // Names of metavariables in order of capture groups
IsNegated bool // Pattern starts with !
IsMultiline bool // Pattern spans multiple lines
}
CompiledPattern holds a compiled pattern with metavariable extraction.
type CompiledRule ¶
type CompiledRule struct {
Rule *Rule
Patterns []*CompiledPattern
ConditionProgram *vm.Program
}
CompiledRule is a rule ready for evaluation.
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler compiles DSL rules for efficient evaluation.
func (*Compiler) ClearCache ¶
func (c *Compiler) ClearCache()
ClearCache clears the compiled program cache.
func (*Compiler) Compile ¶
func (c *Compiler) Compile(rule *Rule) (*CompiledRule, error)
Compile compiles a single rule.
func (*Compiler) CompileConfig ¶
func (c *Compiler) CompileConfig(config *Config) ([]*CompiledRule, error)
CompileConfig compiles all rules in a configuration.
type Config ¶
type Config struct {
// Rules is a map of built-in rule IDs to their severity.
// Example: {"select-star": "error", "n1-queries": "warning"}
Rules map[string]Severity `yaml:"rules,omitempty"`
// Ignore is a list of file patterns to ignore.
Ignore []string `yaml:"ignore,omitempty"`
// Allow is a list of SQL patterns to allow (whitelist).
Allow []string `yaml:"allow,omitempty"`
// CustomRules is a list of user-defined rules.
CustomRules []Rule `yaml:"custom-rules,omitempty"`
// LegacyConfig holds backward-compatible options.
LegacyConfig `yaml:",inline"`
}
Config represents the complete DSL configuration.
type DSLAnalyzer ¶
type DSLAnalyzer struct {
// contains filtered or unexported fields
}
DSLAnalyzer wraps the DSL evaluator for use with go/analysis.
func NewDSLAnalyzer ¶
func NewDSLAnalyzer(config *Config) (*DSLAnalyzer, error)
NewDSLAnalyzer creates a new DSL-based analyzer.
func (*DSLAnalyzer) CreateAnalyzer ¶
func (d *DSLAnalyzer) CreateAnalyzer() *analysis.Analyzer
CreateAnalyzer creates a go/analysis.Analyzer using DSL rules.
type EvalContext ¶
type EvalContext struct {
// File context
File string `expr:"file"`
Package string `expr:"package"`
Function string `expr:"function"`
// SQL context
Query string `expr:"query"`
QueryType string `expr:"query_type"` // SELECT, INSERT, UPDATE, DELETE
Table string `expr:"table"`
Tables []string `expr:"tables"`
Columns []string `expr:"columns"`
HasJoin bool `expr:"has_join"`
HasWhere bool `expr:"has_where"`
// Code context
InLoop bool `expr:"in_loop"`
LoopDepth int `expr:"loop_depth"`
Builder string `expr:"builder"` // gorm, squirrel, sqlx, etc.
// Metavariables captured from pattern matching
Metavars map[string]string `expr:"metavars"`
}
EvalContext provides context for evaluating rule conditions.
type Evaluator ¶
type Evaluator struct {
// contains filtered or unexported fields
}
Evaluator executes compiled DSL rules against code/SQL.
func NewEvaluator ¶
NewEvaluator creates a new rule evaluator.
func (*Evaluator) EvaluateSQL ¶
func (e *Evaluator) EvaluateSQL(ctx *EvalContext, query string) ([]*Match, error)
EvaluateSQL evaluates all rules against a SQL query.
func (*Evaluator) GetRuleSeverity ¶
GetRuleSeverity returns the severity for a rule from config.
func (*Evaluator) ShouldIgnoreFile ¶
ShouldIgnoreFile checks if a file should be ignored based on config.
type LegacyConfig ¶
type LegacyConfig struct {
CheckSQLBuilders bool `yaml:"check-sql-builders,omitempty"`
AllowedPatterns []string `yaml:"allowed-patterns,omitempty"`
IgnoredFiles []string `yaml:"ignored-files,omitempty"`
}
LegacyConfig holds options from the original .unqueryvet.yaml format.
type Match ¶
type Match struct {
Rule *Rule
File string
Line int
Column int
Message string
Severity Severity
Fix string
Metavars map[string]string
}
Match represents a single match of a rule against code.
type Parser ¶
type Parser struct{}
Parser handles parsing of DSL configuration files.
func (*Parser) DefaultConfig ¶
DefaultConfig returns a sensible default configuration.
func (*Parser) FindConfigFile ¶
FindConfigFile searches for a configuration file in standard locations. Returns empty string if no config file is found.
func (*Parser) LoadConfig ¶
LoadConfig loads configuration from the first found config file. If no config file is found, returns a default configuration.
func (*Parser) MergeConfigs ¶
MergeConfigs merges multiple configs, with later configs taking precedence.
type PatternCompiler ¶
type PatternCompiler struct {
// contains filtered or unexported fields
}
PatternCompiler compiles DSL patterns into regex patterns.
func NewPatternCompiler ¶
func NewPatternCompiler() *PatternCompiler
NewPatternCompiler creates a new pattern compiler.
func (*PatternCompiler) Compile ¶
func (pc *PatternCompiler) Compile(pattern string) (*CompiledPattern, error)
Compile compiles a DSL pattern into a regex-based CompiledPattern. Patterns support: - $VAR: matches any identifier (alphanumeric + underscore) - $TABLE: matches a table name - $QUERY: matches a string literal - Literal text: matched exactly (with regex escaping) - !pattern: negated pattern
func (*PatternCompiler) CompilePatterns ¶
func (pc *PatternCompiler) CompilePatterns(patterns []string) ([]*CompiledPattern, error)
CompilePatterns compiles multiple patterns.
type Rule ¶
type Rule struct {
// ID is a unique identifier for the rule.
ID string `yaml:"id"`
// Pattern is the SQL or code pattern to match.
// Supports metavariables like $TABLE, $VAR, etc.
Pattern string `yaml:"pattern"`
// Patterns allows multiple patterns for a single rule.
Patterns []string `yaml:"patterns,omitempty"`
// When is an optional condition expression (evaluated with expr-lang).
// Available variables: file, package, function, query, table, in_loop, etc.
When string `yaml:"when,omitempty"`
// Message is the diagnostic message shown when the rule triggers.
Message string `yaml:"message,omitempty"`
// Severity is the severity level (error, warning, info, ignore).
Severity Severity `yaml:"severity,omitempty"`
// Action determines what to do when the pattern matches.
Action Action `yaml:"action,omitempty"`
// Fix is an optional suggested fix message.
Fix string `yaml:"fix,omitempty"`
}
Rule represents a custom analysis rule.
func (*Rule) GetMessage ¶
GetMessage returns the message, or a default if not set.
func (*Rule) GetPatterns ¶
GetPatterns returns all patterns for the rule.
func (*Rule) GetSeverity ¶
GetSeverity returns the severity, defaulting to warning if not set.