Documentation
¶
Overview ¶
Package output provides output formatting for the gosqlx CLI.
Overview ¶
This package implements multiple output formats for CLI commands, enabling integration with various tools and workflows. It provides structured output generation for validation results, analysis reports, and parsing results.
Supported Formats ¶
## JSON Format
Structured JSON output for programmatic consumption. Used for:
- Validation results
- Parse results (AST representation)
- Analysis reports
- Configuration display
Features:
- Indented JSON for readability
- Consistent field naming (snake_case)
- Comprehensive error information
- Metadata inclusion (version, timestamp)
Example:
{
"version": "1.6.0",
"timestamp": "2024-01-15T10:30:00Z",
"results": [...],
"summary": {...}
}
## YAML Format
YAML output for configuration-style consumption. Used for:
- Configuration display
- Parse results (alternative to JSON)
- Analysis reports (human-readable structured)
Features:
- Clean YAML formatting
- Comment support for documentation
- Compatible with configuration files
Example:
version: 1.6.0
timestamp: 2024-01-15T10:30:00Z
results:
- file: query.sql
valid: true
## SARIF Format (Static Analysis Results Interchange Format)
SARIF 2.1.0 format for GitHub Code Scanning integration. Used for:
- Validation results with file locations
- Security analysis results
- Linting violations
Features:
- GitHub Code Scanning integration
- Precise error locations (line, column)
- Severity levels (error, warning, note)
- Rule documentation links
- Multi-file support
Example:
{
"version": "2.1.0",
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"runs": [{
"tool": {
"driver": {
"name": "GoSQLX",
"version": "1.6.0"
}
},
"results": [...]
}]
}
## Text Format
Human-readable text output with emojis and formatting. Used for:
- Default console output
- Interactive use
- Verbose mode
Features:
- Colored output (when supported)
- Emoji indicators (✅, ❌, ⚠️)
- Progress indicators
- Summary statistics
## Table Format
Tabular output for structured data display. Used for:
- Token listings
- Statistics summaries
- Multi-column data
Features:
- Aligned columns
- Header rows
- Separator lines
- Compact presentation
## Tree Format
Tree visualization for hierarchical data. Used for:
- AST structure display
- Directory listings
- Nested data
Features:
- Unicode tree characters (├──, └──)
- Indentation for hierarchy
- Collapsible sections
Output Types ¶
## ValidationResult
Contains results from SQL validation operations:
type ValidationResult struct {
Files []FileValidationResult
TotalFiles int
ValidFiles int
InvalidFiles int
TotalBytes int64
Duration time.Duration
}
Used by:
- validate command
- SARIF output
- JSON validation output
## FileValidationResult
Contains validation result for a single file:
type FileValidationResult struct {
Path string
Valid bool
Error error
Size int64
}
Includes:
- File path and size
- Validation status (valid/invalid)
- Error information with location
## ParseResult
Contains results from SQL parsing operations:
type ParseResult struct {
AST *ast.AST
Tokens []models.TokenWithSpan
Metadata map[string]interface{}
}
Used by:
- parse command
- JSON parse output
- Tree visualization
## AnalysisResult
Contains results from SQL analysis operations:
type AnalysisResult struct {
SecurityScore int
PerformanceScore int
ComplexityScore int
Issues []Issue
Recommendations []string
}
Used by:
- analyze command
- Security reports
- JSON analysis output
Functions ¶
## FormatValidationJSON
Formats validation results as JSON:
func FormatValidationJSON(result *ValidationResult, files []string, showStats bool) ([]byte, error)
Parameters:
- result: Validation results to format
- files: List of processed files
- showStats: Include performance statistics
Returns:
- JSON-encoded bytes
- Error if formatting fails
Usage:
jsonData, err := output.FormatValidationJSON(result, files, true)
if err != nil {
return err
}
fmt.Println(string(jsonData))
## FormatSARIF
Formats validation results as SARIF 2.1.0:
func FormatSARIF(result *ValidationResult, version string) ([]byte, error)
Parameters:
- result: Validation results to format
- version: Tool version string
Returns:
- SARIF-encoded JSON bytes
- Error if formatting fails
SARIF features:
- Compliant with SARIF 2.1.0 schema
- GitHub Code Scanning compatible
- Precise error locations
- Rule metadata and help
Usage:
sarifData, err := output.FormatSARIF(result, "1.6.0")
if err != nil {
return err
}
os.WriteFile("results.sarif", sarifData, 0600)
## FormatParseJSON
Formats parse results as JSON:
func FormatParseJSON(astObj *ast.AST, source string, includeTokens bool, tokens []models.TokenWithSpan) ([]byte, error)
Parameters:
- astObj: AST to format
- source: Source file or input description
- includeTokens: Whether to include token list
- tokens: Token list (if includeTokens is true)
Returns:
- JSON-encoded bytes
- Error if formatting fails
Output includes:
- AST structure (statements, expressions)
- Token information (optional)
- Metadata (parser version, features)
Usage:
jsonData, err := output.FormatParseJSON(astObj, "query.sql", true, tokens)
if err != nil {
return err
}
fmt.Println(string(jsonData))
## FormatPRComment
Formats validation results as GitHub PR comment:
func FormatPRComment(result *ValidationResult, files []string) string
Parameters:
- result: Validation results to format
- files: List of processed files
Returns:
- Markdown-formatted PR comment
Features:
- Markdown formatting
- File-by-file breakdown
- Summary statistics
- Error highlighting
Usage:
comment := output.FormatPRComment(result, files) // Post to GitHub PR via API
GitHub Integration ¶
## GitHub Code Scanning
SARIF output integrates with GitHub Code Scanning:
# GitHub Actions workflow
- name: Validate SQL
run: gosqlx validate --output-format sarif --output-file results.sarif ./sql/
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: results.sarif
Results appear in:
- Pull request checks
- Security tab
- Code scanning alerts
## GitHub Pull Request Comments
PR comments provide inline feedback:
# GitHub Actions workflow
- name: Validate SQL
id: validate
run: gosqlx validate -o results.json --output-format json ./sql/
- name: Comment PR
uses: actions/github-script@v6
with:
script: |
const results = require('./results.json');
const comment = formatPRComment(results);
github.rest.issues.createComment({...});
CI/CD Integration ¶
Output formats support various CI/CD systems:
## GitLab CI
JSON output for GitLab Code Quality:
script:
- gosqlx validate --output-format json -o gl-code-quality-report.json ./sql/
artifacts:
reports:
codequality: gl-code-quality-report.json
## Jenkins
JSON output for Jenkins warnings plugin:
sh 'gosqlx validate --output-format json -o results.json ./sql/' recordIssues(tools: [java(pattern: 'results.json')])
## Azure DevOps
SARIF output for Azure DevOps:
- task: PublishSecurityAnalysisLogs@3 inputs: ArtifactName: 'CodeAnalysisLogs' AllTools: false APIScan: false BinSkim: false CredScan: false SARIF: true
Error Handling ¶
Output formatters handle errors gracefully:
jsonData, err := output.FormatValidationJSON(result, files, true)
if err != nil {
// Possible errors:
// - JSON marshaling failure
// - Invalid result structure
// - Memory allocation failure
return fmt.Errorf("failed to format output: %w", err)
}
Formatting errors include context about the failure.
Performance Considerations ¶
Output formatting is optimized for performance:
- JSON encoding uses standard library (efficient)
- SARIF generation reuses data structures
- Large outputs are streamed when possible
- Buffer pooling for I/O operations
For large result sets (1000+ files), consider:
- Streaming output to file
- Batch processing
- Compressed output
Testing ¶
The package includes comprehensive tests:
- json_test.go: JSON formatting tests
- sarif_test.go: SARIF format compliance tests
- pr_comment_test.go: PR comment formatting tests
Test coverage includes:
- Valid results formatting
- Error handling
- Edge cases (empty results, large files)
- Schema compliance (SARIF)
Examples ¶
## Validation Output
Generate JSON validation output:
result := &output.ValidationResult{
Files: []output.FileValidationResult{
{Path: "query.sql", Valid: true, Size: 1024},
{Path: "broken.sql", Valid: false, Error: errors.New("parse error")},
},
TotalFiles: 2,
ValidFiles: 1,
InvalidFiles: 1,
Duration: 10 * time.Millisecond,
}
jsonData, _ := output.FormatValidationJSON(result, []string{"query.sql", "broken.sql"}, true)
fmt.Println(string(jsonData))
## SARIF Output
Generate SARIF for GitHub Code Scanning:
result := &output.ValidationResult{
Files: []output.FileValidationResult{
{Path: "query.sql", Valid: false, Error: errors.New("syntax error at line 5")},
},
}
sarifData, _ := output.FormatSARIF(result, "1.6.0")
os.WriteFile("results.sarif", sarifData, 0600)
## Parse Output
Generate JSON for AST:
astObj := parser.ParseFromModelTokens(tokensWithSpan) jsonData, _ := output.FormatParseJSON(astObj, "query.sql", false, nil) fmt.Println(string(jsonData))
See Also ¶
- cmd/gosqlx/cmd/validate.go - Validation command implementation
- cmd/gosqlx/cmd/analyze.go - Analysis command implementation
- cmd/gosqlx/cmd/parse.go - Parse command implementation
- https://sarifweb.azurewebsites.net/ - SARIF specification
- https://docs.github.com/en/code-security/code-scanning - GitHub Code Scanning docs
Index ¶
- func FormatPRComment(result *ValidationResult) string
- func FormatPRCommentCompact(result *ValidationResult, maxErrors int) string
- func FormatParseErrorJSON(err error, inputSource string) ([]byte, error)
- func FormatParseJSON(astObj *ast.AST, inputSource string, showTokens bool, tokens interface{}, ...) ([]byte, error)
- func FormatSARIF(result *ValidationResult, toolVersion string) ([]byte, error)
- func FormatValidationJSON(result *ValidationResult, inputFiles []string, includeStats bool) ([]byte, error)
- type FileValidationResult
- type JSONASTRepresentation
- type JSONInputInfo
- type JSONParseError
- type JSONParseMetadata
- type JSONParseOutput
- type JSONParseResult
- type JSONPosition
- type JSONStatement
- type JSONToken
- type JSONValidationError
- type JSONValidationOutput
- type JSONValidationResults
- type JSONValidationStats
- type SARIF
- type SARIFArtifactLocation
- type SARIFDriver
- type SARIFLocation
- type SARIFMessage
- type SARIFPhysicalLocation
- type SARIFRegion
- type SARIFResult
- type SARIFRule
- type SARIFRun
- type SARIFTool
- type ValidationResult
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatPRComment ¶
func FormatPRComment(result *ValidationResult) string
FormatPRComment formats validation results as a GitHub PR comment with markdown.
Generates a comprehensive, well-formatted Markdown comment suitable for posting to GitHub Pull Requests. The comment includes summary statistics, detailed error information, and performance metrics.
Parameters:
- result: Validation results to format
Returns:
- Markdown-formatted string ready for PR comment
Output includes:
- Header with validation status (✅ success or ❌ failure)
- Summary statistics table (total files, valid/invalid counts, duration)
- Performance metrics (throughput)
- Detailed error listing for each invalid file
- Footer with tool attribution
Example:
result := &ValidationResult{
TotalFiles: 2,
ValidFiles: 1,
InvalidFiles: 1,
Duration: 10 * time.Millisecond,
Files: []FileValidationResult{
{Path: "broken.sql", Valid: false, Error: errors.New("syntax error")},
},
}
comment := FormatPRComment(result)
// Post comment to GitHub PR via API
Usage in GitHub Actions:
- name: Validate SQL id: validate run: gosqlx validate ./sql/ > results.txt
- name: Comment PR uses: actions/github-script@v6 with: script: | const comment = require('fs').readFileSync('results.txt', 'utf8'); github.rest.issues.createComment({...});
FormatPRComment formats validation results as a GitHub PR comment with markdown
func FormatPRCommentCompact ¶
func FormatPRCommentCompact(result *ValidationResult, maxErrors int) string
FormatPRCommentCompact formats validation results as a compact PR comment.
Generates a concise PR comment with limited error display, suitable for large validation runs where the full comment would be too long.
Parameters:
- result: Validation results to format
- maxErrors: Maximum number of errors to display in the comment
Returns:
- Compact Markdown-formatted string for PR comment
The compact format includes:
- Single-line header with status
- Brief error listing (up to maxErrors)
- Truncation notice if more errors exist
- Performance metrics footer
This format is useful when:
- Validating large numbers of files (100+)
- Many files have errors (10+)
- GitHub's comment size limits may be reached
- Quick overview is preferred over detailed breakdown
Example:
result := &ValidationResult{
TotalFiles: 100,
InvalidFiles: 25,
}
comment := FormatPRCommentCompact(result, 5) // Show only first 5 errors
// Posts "## ❌ GoSQLX: Found issues in 25/100 files" with top 5 errors
FormatPRCommentCompact formats validation results as a compact PR comment Useful for large validation runs to avoid overly long comments
func FormatParseErrorJSON ¶
FormatParseErrorJSON creates a JSON error output for parse failures
func FormatParseJSON ¶
func FormatParseJSON(astObj *ast.AST, inputSource string, showTokens bool, tokens interface{}, tokenCount int) ([]byte, error)
FormatParseJSON converts parse results to JSON format
func FormatSARIF ¶
func FormatSARIF(result *ValidationResult, toolVersion string) ([]byte, error)
FormatSARIF converts validation results to SARIF 2.1.0 format.
This function generates a SARIF document from validation results, suitable for GitHub Code Scanning integration and other static analysis tools.
The generated SARIF includes:
- Tool information (name, version, repository URL)
- Rule definitions for SQL validation errors
- Individual results for each validation error with file locations
- Fingerprints for result deduplication
Parameters:
- result: Validation results to format
- toolVersion: GoSQLX version string (e.g., "1.6.0")
Returns:
- JSON-encoded SARIF document
- Error if formatting fails
Example:
result := &ValidationResult{
Files: []FileValidationResult{
{Path: "query.sql", Valid: false, Error: errors.New("syntax error")},
},
}
sarifData, err := FormatSARIF(result, "1.6.0")
if err != nil {
log.Fatal(err)
}
os.WriteFile("results.sarif", sarifData, 0600)
SARIF Compliance:
- Complies with SARIF 2.1.0 specification
- Compatible with GitHub Code Scanning
- Includes proper schema reference
- Uses standard severity levels (error, warning, note)
FormatSARIF converts validation results to SARIF 2.1.0 format
func FormatValidationJSON ¶
func FormatValidationJSON(result *ValidationResult, inputFiles []string, includeStats bool) ([]byte, error)
FormatValidationJSON converts validation results to JSON format.
Generates structured JSON output from validation results, suitable for programmatic consumption, CI/CD integration, and automated processing.
Parameters:
- result: Validation results to format
- inputFiles: Array of input file paths
- includeStats: Whether to include performance statistics
Returns:
- JSON-encoded bytes with indentation for readability
- Error if marshaling fails
Example:
result := &ValidationResult{
TotalFiles: 2,
ValidFiles: 1,
InvalidFiles: 1,
}
jsonData, err := FormatValidationJSON(result, []string{"query.sql"}, true)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(jsonData))
FormatValidationJSON converts validation results to JSON format
Types ¶
type FileValidationResult ¶
FileValidationResult contains the result for a single file.
Represents the validation outcome for one SQL file including success status, file metadata, and any validation errors.
Fields:
- Path: File path (absolute or relative)
- Valid: True if validation succeeded, false otherwise
- Size: File size in bytes
- Error: Validation error if validation failed, nil otherwise
Example:
fileResult := FileValidationResult{
Path: "query.sql",
Valid: false,
Size: 1024,
Error: errors.New("syntax error at line 5"),
}
type JSONASTRepresentation ¶
type JSONASTRepresentation struct {
Type string `json:"type"`
Statements []JSONStatement `json:"statements"`
Count int `json:"statement_count"`
}
JSONASTRepresentation represents the AST structure.
Provides a JSON-friendly representation of the Abstract Syntax Tree generated from SQL parsing.
Fields:
- Type: AST type ("AST")
- Statements: Array of top-level SQL statements
- Count: Number of statements in the AST
type JSONInputInfo ¶
type JSONInputInfo struct {
Type string `json:"type"` // "file", "files", "stdin", "directory"
Files []string `json:"files,omitempty"`
Count int `json:"count"`
}
JSONInputInfo contains information about the input.
Describes the input source and files processed in the validation run.
Fields:
- Type: Input type ("file", "files", "stdin", "directory")
- Files: Array of file paths processed
- Count: Number of files processed
type JSONParseError ¶
type JSONParseError struct {
Message string `json:"message"`
Code string `json:"code,omitempty"`
Type string `json:"type"` // "tokenization", "parsing", "io"
Position *JSONPosition `json:"position,omitempty"`
}
JSONParseError represents a parsing error.
Contains detailed information about parsing failures including error type, message, code, and source position.
Fields:
- Message: Error message text
- Code: Error code (e.g., "E2001") if available
- Type: Error category ("tokenization", "parsing", "io")
- Position: Source position where error occurred (optional)
type JSONParseMetadata ¶
type JSONParseMetadata struct {
ParserVersion string `json:"parser_version"`
SQLCompliance string `json:"sql_compliance"`
Features []string `json:"features"`
}
JSONParseMetadata contains metadata about the parsing.
Provides information about the parser capabilities and configuration.
Fields:
- ParserVersion: Parser version string
- SQLCompliance: SQL standard compliance level (e.g., "~80-85% SQL-99")
- Features: Supported SQL features (CTEs, Window Functions, etc.)
type JSONParseOutput ¶
type JSONParseOutput struct {
Command string `json:"command"`
Input JSONInputInfo `json:"input"`
Status string `json:"status"`
Results *JSONParseResult `json:"results,omitempty"`
Error *JSONParseError `json:"error,omitempty"`
}
JSONParseOutput represents the JSON output format for parse command.
Provides structured JSON output for SQL parsing results, including AST structure, token information, and metadata.
Fields:
- Command: Command name ("parse")
- Input: Input metadata
- Status: Parse status ("success" or "error")
- Results: Parse results (AST, tokens, metadata) if successful
- Error: Error information if parsing failed
type JSONParseResult ¶
type JSONParseResult struct {
AST *JSONASTRepresentation `json:"ast,omitempty"`
Tokens []JSONToken `json:"tokens,omitempty"`
TokenCount int `json:"token_count"`
Metadata JSONParseMetadata `json:"metadata"`
}
JSONParseResult contains parse results.
Represents the successful parsing of SQL including AST structure, token information, and parsing metadata.
Fields:
- AST: Abstract Syntax Tree representation
- Tokens: Token stream (optional, if requested)
- TokenCount: Number of tokens generated
- Metadata: Parser metadata (version, compliance, features)
type JSONPosition ¶
type JSONPosition struct {
Line int `json:"line"`
Column int `json:"column"`
Offset int `json:"offset,omitempty"`
}
JSONPosition represents a position in the source.
Identifies a specific location in the SQL source text using line, column, and optional byte offset.
Fields:
- Line: Line number (1-based)
- Column: Column number (1-based)
- Offset: Byte offset from start (optional)
type JSONStatement ¶
type JSONStatement struct {
Type string `json:"type"`
Details map[string]interface{} `json:"details,omitempty"`
Position *JSONPosition `json:"position,omitempty"`
}
JSONStatement represents a single AST statement.
Represents one SQL statement from the AST with type information, details, and optional position information.
Fields:
- Type: Statement type (e.g., "SelectStatement", "InsertStatement")
- Details: Type-specific details (columns, tables, clauses)
- Position: Source position (optional)
type JSONToken ¶
type JSONToken struct {
Type string `json:"type"`
Value string `json:"value"`
Position *JSONPosition `json:"position"`
}
JSONToken represents a single token.
Represents a lexical token from SQL tokenization with type, value, and source position.
Fields:
- Type: Token type (e.g., "KEYWORD", "IDENTIFIER", "NUMBER")
- Value: Token text value
- Position: Source position (line, column)
type JSONValidationError ¶
type JSONValidationError struct {
File string `json:"file"`
Message string `json:"message"`
Code string `json:"code,omitempty"`
Type string `json:"type"` // "tokenization", "parsing", "syntax", "io"
}
JSONValidationError represents a single validation error.
Contains detailed information about a validation failure for one file.
Fields:
- File: File path where error occurred
- Message: Error message text
- Code: Error code (e.g., "E1001") if available
- Type: Error category ("tokenization", "parsing", "syntax", "io")
type JSONValidationOutput ¶
type JSONValidationOutput struct {
Command string `json:"command"`
Input JSONInputInfo `json:"input"`
Status string `json:"status"`
Results JSONValidationResults `json:"results"`
Errors []JSONValidationError `json:"errors,omitempty"`
Stats *JSONValidationStats `json:"stats,omitempty"`
}
JSONValidationOutput represents the JSON output format for validation command.
Provides structured JSON output for SQL validation results, suitable for programmatic consumption, CI/CD integration, and automated processing.
Fields:
- Command: Command name ("validate")
- Input: Input metadata (type, files, count)
- Status: Overall status ("success", "failure", "no_files")
- Results: Validation results summary
- Errors: Array of validation errors (empty if all valid)
- Stats: Performance statistics (optional)
type JSONValidationResults ¶
type JSONValidationResults struct {
Valid bool `json:"valid"`
TotalFiles int `json:"total_files"`
ValidFiles int `json:"valid_files"`
InvalidFiles int `json:"invalid_files"`
}
JSONValidationResults contains validation results.
Provides summary statistics about validation outcomes.
Fields:
- Valid: True if all files passed validation
- TotalFiles: Total number of files processed
- ValidFiles: Number of files that passed validation
- InvalidFiles: Number of files with validation errors
type JSONValidationStats ¶
type JSONValidationStats struct {
Duration string `json:"duration"`
DurationMs float64 `json:"duration_ms"`
TotalBytes int64 `json:"total_bytes"`
ThroughputFPS float64 `json:"throughput_files_per_sec,omitempty"`
ThroughputBPS int64 `json:"throughput_bytes_per_sec,omitempty"`
}
JSONValidationStats contains performance statistics.
Provides detailed performance metrics for the validation run.
Fields:
- Duration: Human-readable duration string (e.g., "10ms")
- DurationMs: Duration in milliseconds
- TotalBytes: Total size of processed files in bytes
- ThroughputFPS: Files processed per second
- ThroughputBPS: Bytes processed per second
type SARIF ¶
type SARIF struct {
Schema string `json:"$schema"`
Version string `json:"version"`
Runs []SARIFRun `json:"runs"`
}
SARIF represents a SARIF 2.1.0 document.
SARIF (Static Analysis Results Interchange Format) is a standard format for representing static analysis results. This implementation complies with SARIF 2.1.0 specification for integration with GitHub Code Scanning and other static analysis tools.
Fields:
- Schema: JSON schema URL for SARIF 2.1.0
- Version: SARIF format version (always "2.1.0")
- Runs: Array of analysis runs (typically one run per invocation)
Specification: https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html
type SARIFArtifactLocation ¶
type SARIFArtifactLocation struct {
URI string `json:"uri"`
URIBaseID string `json:"uriBaseId,omitempty"`
}
SARIFArtifactLocation identifies the file.
Specifies which file contains the finding using a URI and optional base ID.
Fields:
- URI: File path as URI (forward slashes, relative path)
- URIBaseID: Optional base ID for resolving relative paths ("%SRCROOT%")
type SARIFDriver ¶
type SARIFDriver struct {
Name string `json:"name"`
Version string `json:"version,omitempty"`
InformationURI string `json:"informationUri,omitempty"`
Rules []SARIFRule `json:"rules,omitempty"`
SemanticVersion string `json:"semanticVersion,omitempty"`
}
SARIFDriver contains tool information.
Provides detailed information about the analysis tool including name, version, and rule definitions.
Fields:
- Name: Tool name ("GoSQLX")
- Version: Tool version (e.g., "1.6.0")
- InformationURI: URL to tool documentation
- Rules: Array of rule definitions
- SemanticVersion: Semantic version string
type SARIFLocation ¶
type SARIFLocation struct {
PhysicalLocation SARIFPhysicalLocation `json:"physicalLocation"`
}
SARIFLocation specifies where a result was found.
Provides the physical location of a finding in source code.
Fields:
- PhysicalLocation: File and position information
type SARIFMessage ¶
type SARIFMessage struct {
Text string `json:"text"`
}
SARIFMessage contains text content.
A simple text message used throughout SARIF for descriptions, help text, and result messages.
Fields:
- Text: The message text
type SARIFPhysicalLocation ¶
type SARIFPhysicalLocation struct {
ArtifactLocation SARIFArtifactLocation `json:"artifactLocation"`
Region SARIFRegion `json:"region"`
}
SARIFPhysicalLocation provides file and region information.
Contains both the file identifier and the specific region within the file where the finding occurred.
Fields:
- ArtifactLocation: File identification
- Region: Line and column information
type SARIFRegion ¶
type SARIFRegion struct {
StartLine int `json:"startLine"`
StartColumn int `json:"startColumn,omitempty"`
EndLine int `json:"endLine,omitempty"`
EndColumn int `json:"endColumn,omitempty"`
}
SARIFRegion specifies the location within a file.
Defines the specific lines and columns where a finding occurred. Line and column numbers are 1-based per SARIF specification.
Fields:
- StartLine: Starting line number (1-based)
- StartColumn: Starting column number (1-based, optional)
- EndLine: Ending line number (optional)
- EndColumn: Ending column number (optional)
type SARIFResult ¶
type SARIFResult struct {
RuleID string `json:"ruleId"`
Level string `json:"level"`
Message SARIFMessage `json:"message"`
Locations []SARIFLocation `json:"locations"`
PartialFingerprints map[string]string `json:"partialFingerprints,omitempty"`
}
SARIFResult represents a single finding.
A result represents one specific violation or issue found during analysis. Each result is associated with a rule and has a location in the source code.
Fields:
- RuleID: ID of the rule that was violated
- Level: Severity level ("error", "warning", "note")
- Message: Description of the violation
- Locations: Where the violation occurred (file, line, column)
- PartialFingerprints: Fingerprints for result deduplication
type SARIFRule ¶
type SARIFRule struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
ShortDescription SARIFMessage `json:"shortDescription,omitempty"`
FullDescription SARIFMessage `json:"fullDescription,omitempty"`
Help SARIFMessage `json:"help,omitempty"`
DefaultLevel string `json:"defaultConfiguration,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
}
SARIFRule describes a validation rule.
Defines a specific validation rule that can be violated in the analysis. Rules provide metadata about what was checked and how to fix violations.
Fields:
- ID: Unique rule identifier (e.g., "sql-syntax-error")
- Name: Human-readable rule name
- ShortDescription: Brief description of the rule
- FullDescription: Detailed description of what the rule checks
- Help: Guidance on how to fix violations
- DefaultLevel: Default severity level (not used in current implementation)
- Properties: Additional rule metadata (category, tags)
type SARIFRun ¶
type SARIFRun struct {
Tool SARIFTool `json:"tool"`
Results []SARIFResult `json:"results"`
}
SARIFRun represents a single analysis run.
A run represents a single invocation of an analysis tool on a set of files. Each run contains tool information, rules, and results.
Fields:
- Tool: Information about the analysis tool (GoSQLX)
- Results: Array of findings from the analysis
type SARIFTool ¶
type SARIFTool struct {
Driver SARIFDriver `json:"driver"`
}
SARIFTool describes the analysis tool.
Contains metadata about the tool that produced the analysis results.
Fields:
- Driver: Tool driver information (name, version, rules)
type ValidationResult ¶
type ValidationResult struct {
TotalFiles int
ValidFiles int
InvalidFiles int
TotalBytes int64
Duration time.Duration
Files []FileValidationResult
}
ValidationResult contains the results of a validation run.
This structure aggregates validation results across multiple files, providing summary statistics and individual file results.
Fields:
- TotalFiles: Total number of files processed
- ValidFiles: Number of files that passed validation
- InvalidFiles: Number of files with validation errors
- TotalBytes: Total size of all processed files in bytes
- Duration: Time taken to process all files
- Files: Individual file validation results
Example:
result := &ValidationResult{
TotalFiles: 2,
ValidFiles: 1,
InvalidFiles: 1,
Duration: 10 * time.Millisecond,
}