Overview
TheRule interface is the foundation of pgvet’s static analysis system. Every rule in pgvet implements this interface to check SQL statements and report diagnostics.
Rule Interface
All pgvet rules must implement theRule interface:
Methods
Returns the unique identifier for the rule. This name is used in diagnostic output and configuration.Example:
"delete-without-where"Returns a human-readable description of what the rule checks for.Example:
"DELETE without WHERE deletes every row in the table"Analyzes a single SQL statement and returns a slice of diagnostics for any issues found.Parameters:
stmt: The parsed PostgreSQL statement AST from pg_query_gosql: The original SQL text as a string
Diagnostic structs (empty if no issues found)Diagnostic Struct
TheDiagnostic struct represents a single issue found by a rule:
Fields
The name of the rule that generated this diagnostic (should match
Rule.Name())A descriptive message explaining the issue
The file path where the issue was found. This is typically set by the analyzer, not the rule itself.
The line number where the issue occurs (1-based)
The column number where the issue occurs (1-based)
The severity level: either
SeverityWarning or SeverityErrorSeverity Constants
Two severity levels are available:Use for issues that are potentially problematic but may be intentional. Value:
"warning"Use for serious issues that are likely bugs or will cause problems. Value:
"error"Working with RawStmt
The*pg_query.RawStmt parameter contains the parsed PostgreSQL AST. To access specific statement types, use the getter methods:
GetSelectStmt()- SELECT queriesGetInsertStmt()- INSERT statementsGetUpdateStmt()- UPDATE statementsGetDeleteStmt()- DELETE statementsGetCreateStmt()- CREATE statementsGetAlterTableStmt()- ALTER TABLE statements
Complete Example
Here’s a complete implementation of a rule that detects DELETE statements without WHERE clauses:Best Practices
- Return early: If the statement type doesn’t match what your rule checks, return
nilimmediately - Use helper functions: The
offsetToLineColfunction converts byte offsets to line/column numbers - Set appropriate severity: Use
SeverityWarningfor style/best-practice issues,SeverityErrorfor bugs - Keep rules focused: Each rule should check for one specific issue
- Don’t set File field: The analyzer automatically sets the
Filefield on diagnostics
See Also
- Analyzer - Run rules against SQL files
- Walker - Traverse the PostgreSQL AST
- Built-in Rules - See examples of all built-in rules