Documentation
¶
Overview ¶
Package errors provides a structured error system for GoSQLX v1.6.0 with rich context, intelligent suggestions, and comprehensive error codes.
This package delivers production-grade error handling for SQL parsing with:
- Structured Error Codes: E1xxx-E4xxx for programmatic error handling
- Precise Location Tracking: Line and column information for every error
- SQL Context Extraction: Visual error highlighting in source code
- Intelligent Hints: Auto-generated suggestions using Levenshtein distance
- Typo Detection: "Did you mean?" suggestions for common mistakes
- Error Recovery: Graceful degradation with actionable feedback
Error Code Taxonomy ¶
Errors are categorized into four main groups:
E1xxx - Tokenizer Errors:
- E1001: ErrCodeUnexpectedChar - Invalid character in SQL input
- E1002: ErrCodeUnterminatedString - Missing closing quote
- E1003: ErrCodeInvalidNumber - Malformed numeric literal
- E1004: ErrCodeInvalidOperator - Invalid operator sequence
- E1005: ErrCodeInvalidIdentifier - Malformed identifier
- E1006: ErrCodeInputTooLarge - Input exceeds size limits (DoS protection)
- E1007: ErrCodeTokenLimitReached - Token count exceeds limit (DoS protection)
- E1008: ErrCodeTokenizerPanic - Recovered panic (bug detection)
E2xxx - Parser Syntax Errors:
- E2001: ErrCodeUnexpectedToken - Unexpected token in grammar
- E2002: ErrCodeExpectedToken - Missing required token
- E2003: ErrCodeMissingClause - Required SQL clause missing
- E2004: ErrCodeInvalidSyntax - General syntax violation
- E2005: ErrCodeIncompleteStatement - Incomplete SQL statement
- E2006: ErrCodeInvalidExpression - Invalid expression syntax
- E2007: ErrCodeRecursionDepthLimit - Recursion too deep (DoS protection)
- E2008: ErrCodeUnsupportedDataType - Data type not supported
- E2009: ErrCodeUnsupportedConstraint - Constraint type not supported
- E2010: ErrCodeUnsupportedJoin - JOIN type not supported
- E2011: ErrCodeInvalidCTE - Invalid CTE (WITH clause) syntax
- E2012: ErrCodeInvalidSetOperation - Invalid UNION/EXCEPT/INTERSECT
E3xxx - Semantic Errors:
- E3001: ErrCodeUndefinedTable - Table reference not found
- E3002: ErrCodeUndefinedColumn - Column reference not found
- E3003: ErrCodeTypeMismatch - Type incompatibility in expression
- E3004: ErrCodeAmbiguousColumn - Column appears in multiple tables
E4xxx - Unsupported Features:
- E4001: ErrCodeUnsupportedFeature - Feature not yet implemented
- E4002: ErrCodeUnsupportedDialect - SQL dialect not supported
Core Components ¶
Error Structure:
- Error: Main error type with code, message, location, context, hint
- ErrorCode: Strongly-typed error code (string type)
- ErrorContext: SQL source context with highlighting
Builder Functions:
- UnexpectedTokenError, ExpectedTokenError, MissingClauseError
- InvalidSyntaxError, UnsupportedFeatureError, IncompleteStatementError
- All E1xxx-E4xxx errors have dedicated builder functions
Suggestion System:
- GenerateHint: Auto-generates context-aware suggestions
- SuggestKeyword: Levenshtein-based typo correction
- SuggestFromPattern: Regex-based pattern matching
- CommonHints: Pre-built hints for frequent errors
Formatting Functions:
- FormatErrorWithContext: Full error with SQL context
- FormatErrorSummary: Brief error for logging
- FormatErrorList: Multiple errors in readable format
- FormatContextWindow: Larger context (N lines before/after)
Performance and Caching ¶
The error system is optimized for production use:
- Keyword suggestion cache (1000 entries) for fast typo detection
- Cache hit rate: 85%+ in LSP scenarios with repeated typos
- Lock-free atomic metrics for cache statistics
- Partial eviction strategy (keeps 50% on overflow)
- Thread-safe cache operations for concurrent use
Cache Management:
// Check cache statistics
stats := errors.GetSuggestionCacheStats()
fmt.Printf("Hit rate: %.2f%%\n", stats.HitRate*100)
// Clear cache if needed
errors.ClearSuggestionCache()
// Reset metrics
errors.ResetSuggestionCacheStats()
Usage Examples ¶
Basic error creation with context:
err := errors.NewError(
errors.ErrCodeUnexpectedToken,
"unexpected token: COMMA",
models.Location{Line: 5, Column: 20},
)
err = err.WithContext(sqlSource, 1)
err = err.WithHint("Expected FROM keyword after SELECT clause")
Using builder functions:
err := errors.ExpectedTokenError(
"FROM", "FORM",
models.Location{Line: 1, Column: 15},
sqlSource,
)
// Automatically includes context and "Did you mean 'FROM'?" hint
Handling errors in application code:
if err != nil {
if errors.IsCode(err, errors.ErrCodeUnterminatedString) {
// Handle unterminated string specifically
}
code := errors.GetCode(err)
switch code {
case errors.ErrCodeExpectedToken:
// Handle syntax errors
case errors.ErrCodeUndefinedTable:
// Handle semantic errors
}
// Extract location for IDE integration
if loc, ok := errors.ExtractLocation(err); ok {
fmt.Printf("Error at line %d, column %d\n", loc.Line, loc.Column)
}
}
Formatting errors for display:
// Full error with context formatted := errors.FormatErrorWithContext(err, sqlSource) fmt.Println(formatted) // Output: // Error E2002 at line 1, column 15: expected FROM, got FORM // // 1 | SELECT * FORM users WHERE id = 1 // ^^^^ // 2 | // // Hint: Did you mean 'FROM' instead of 'FORM'? // Help: https://docs.gosqlx.dev/errors/E2002 // Brief summary for logging summary := errors.FormatErrorSummary(err) // Output: [E2002] expected FROM, got FORM at line 1, column 15
Intelligent Suggestions ¶
The package provides sophisticated error suggestions:
Typo Detection:
// Detects common SQL keyword typos
suggestion := errors.SuggestKeyword("SELCT")
// Returns: "SELECT"
suggestion = errors.SuggestKeyword("WAHER")
// Returns: "WHERE"
Pattern-Based Suggestions:
// Matches error messages against known patterns
hint := errors.SuggestFromPattern("expected FROM but got FORM")
// Returns: "Check spelling of SQL keywords (e.g., FORM → FROM)"
Context-Aware Suggestions:
// Window function errors
hint := errors.SuggestForWindowFunction("SELECT ROW_NUMBER()", "ROW_NUMBER")
// Returns: "Window function ROW_NUMBER requires OVER clause..."
// CTE errors
hint := errors.SuggestForCTE("WITH cte AS (SELECT * FROM users)")
// Returns: "WITH clause must be followed by SELECT, INSERT, UPDATE..."
// JOIN errors
hint := errors.SuggestForJoinError("INNER", "FROM users INNER JOIN orders")
// Returns: "INNER JOIN requires ON condition or USING clause..."
Common Mistake Detection ¶
The package includes 20+ common SQL mistake patterns:
// Get mistake explanation
if mistake, ok := errors.GetMistakeExplanation("window_function_without_over"); ok {
fmt.Println(errors.FormatMistakeExample(mistake))
// Output:
// Common Mistake: window_function_without_over
// ❌ Wrong: SELECT name, ROW_NUMBER() FROM employees
// ✓ Right: SELECT name, ROW_NUMBER() OVER (ORDER BY salary DESC) FROM employees
// Explanation: Window functions require OVER clause with optional PARTITION BY and ORDER BY
}
Common mistakes include:
- window_function_without_over, partition_by_without_over
- cte_without_select, recursive_cte_without_union
- window_frame_without_order, window_function_in_where
- missing_comma_in_list, missing_join_condition
- wrong_aggregate_syntax, missing_group_by, having_without_group_by
v1.6.0 Feature Support ¶
Error handling for PostgreSQL extensions:
// LATERAL JOIN errors
err := errors.InvalidSyntaxError(
"LATERAL requires subquery or table function",
location, sqlSource,
)
// JSON operator errors
err := errors.UnexpectedTokenError("->", "ARROW", location, sqlSource)
// RETURNING clause errors
err := errors.MissingClauseError("RETURNING", location, sqlSource)
Error handling for advanced SQL features:
// Window function errors
err := errors.InvalidSyntaxError(
"window frame requires ORDER BY clause",
location, sqlSource,
)
// GROUPING SETS errors
err := errors.InvalidSyntaxError(
"GROUPING SETS requires parenthesized expression list",
location, sqlSource,
)
// MERGE statement errors
err := errors.InvalidSyntaxError(
"MERGE requires MATCHED or NOT MATCHED clause",
location, sqlSource,
)
Thread Safety and Concurrency ¶
All error operations are thread-safe:
- Error creation is safe for concurrent use
- Suggestion cache uses sync.RWMutex for concurrent reads
- Atomic operations for cache metrics
- No shared mutable state in error instances
- Safe for use in LSP server with multiple clients
IDE and LSP Integration ¶
The error system integrates seamlessly with IDE tooling:
// Extract location for diagnostic
loc, ok := errors.ExtractLocation(err)
diagnostic := lsp.Diagnostic{
Range: lsp.Range{
Start: lsp.Position{Line: loc.Line - 1, Character: loc.Column - 1},
},
Severity: lsp.DiagnosticSeverityError,
Code: string(errors.GetCode(err)),
Message: err.Error(),
}
Error Recovery and Debugging ¶
DoS Protection Errors:
// Input size limits err := errors.InputTooLargeError(10*1024*1024, 5*1024*1024, location) // Message: "input size 10485760 bytes exceeds limit of 5242880 bytes" // Hint: "Reduce input size to under 5242880 bytes or adjust MaxInputSize configuration" // Token count limits err := errors.TokenLimitReachedError(15000, 10000, location, sqlSource) // Message: "token count 15000 exceeds limit of 10000 tokens" // Hint: "Simplify query or adjust MaxTokens limit (currently 10000)"
Panic Recovery:
err := errors.TokenizerPanicError(panicValue, location) // Message: "tokenizer panic recovered: <panic value>" // Hint: "This indicates a serious tokenizer bug. Please report this issue..."
Design Principles ¶
The error package follows GoSQLX design philosophy:
- Actionable Messages: Every error includes what went wrong and how to fix it
- Precise Location: Exact line/column for every error
- Visual Context: SQL source highlighting for quick debugging
- Smart Suggestions: Levenshtein distance for typo detection
- Caching: Fast repeated suggestions for LSP scenarios
- Extensible: Easy to add new error codes and patterns
Testing and Quality ¶
The package maintains high quality standards:
- Comprehensive test coverage for all error codes
- Suggestion accuracy validation with real typos
- Cache performance benchmarks
- Thread safety validation (go test -race)
- Real-world error message validation
For complete documentation and examples, see:
- docs/GETTING_STARTED.md - Quick start guide
- docs/USAGE_GUIDE.md - Comprehensive usage documentation
- docs/LSP_GUIDE.md - IDE integration with error diagnostics
Package errors provides a structured error system for GoSQLX with error codes, context extraction, and intelligent hints for debugging SQL parsing issues.
This package is designed to provide clear, actionable error messages for SQL parsing failures. It is the production-grade error handling system for GoSQLX v1.6.0 with support for:
- Structured error codes (E1xxx-E4xxx)
- Precise location tracking with line/column information
- SQL context extraction with visual highlighting
- Intelligent suggestions using Levenshtein distance for typo detection
- Cached suggestions for performance in LSP scenarios
- Thread-safe concurrent error handling
See doc.go for comprehensive package documentation and examples.
Example (AllErrorCodes) ¶
Example_allErrorCodes demonstrates all available error codes
package main
import (
"fmt"
)
func main() {
fmt.Println("Available Error Codes:")
fmt.Println()
fmt.Println("Tokenizer Errors (E1xxx):")
fmt.Println(" E1001: Unexpected character")
fmt.Println(" E1002: Unterminated string")
fmt.Println(" E1003: Invalid number")
fmt.Println(" E1004: Invalid operator")
fmt.Println(" E1005: Invalid identifier")
fmt.Println()
fmt.Println("Parser Errors (E2xxx):")
fmt.Println(" E2001: Unexpected token")
fmt.Println(" E2002: Expected token")
fmt.Println(" E2003: Missing clause")
fmt.Println(" E2004: Invalid syntax")
fmt.Println(" E2005: Incomplete statement")
fmt.Println(" E2006: Invalid expression")
fmt.Println()
fmt.Println("Semantic Errors (E3xxx):")
fmt.Println(" E3001: Undefined table")
fmt.Println(" E3002: Undefined column")
fmt.Println(" E3003: Type mismatch")
fmt.Println(" E3004: Ambiguous column")
fmt.Println()
fmt.Println("Unsupported Features (E4xxx):")
fmt.Println(" E4001: Unsupported feature")
fmt.Println(" E4002: Unsupported dialect")
}
Example (BasicError) ¶
Example_basicError demonstrates creating a basic structured error
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FORM users"
location := models.Location{Line: 1, Column: 10}
err := errors.ExpectedTokenError("FROM", "FORM", location, sql)
fmt.Println(err.Error())
// Output includes:
// - Error code
// - Location (line and column)
// - SQL context with position indicator
// - Intelligent hint suggesting the correction
}
Example (BatchValidation) ¶
Example_batchValidation demonstrates validating multiple SQL statements
package main
import (
"fmt"
)
func main() {
statements := []string{
"SELECT * FROM users", // Valid
"SELECT * FORM users", // Typo
"SELECT * FROM", // Incomplete
"SELECT id name FROM users", // Missing comma
"INSERT users VALUES (1, 'x')", // Missing INTO
}
fmt.Println("Batch Validation Results:")
fmt.Println()
for i, stmt := range statements {
fmt.Printf("%d. %s\n", i+1, stmt)
// In real usage, parser would validate each statement
// and report errors with full context
}
fmt.Println()
fmt.Println("Validation would show:")
fmt.Println("✓ Statement 1: Valid")
fmt.Println("✗ Statement 2: Error E2002 - Expected FROM")
fmt.Println("✗ Statement 3: Error E2005 - Incomplete")
fmt.Println("✗ Statement 4: Syntax error - Missing comma")
fmt.Println("✗ Statement 5: Error E2003 - Missing INTO")
}
Example (ChainedErrors) ¶
Example_chainedErrors demonstrates error wrapping
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users"
location := models.Location{Line: 1, Column: 1}
// Create a chain of errors
rootErr := errors.NewError(
errors.ErrCodeInvalidSyntax,
"invalid table reference",
location,
)
wrappedErr := errors.WrapError(
errors.ErrCodeUnexpectedToken,
"parser error",
location,
sql,
rootErr,
)
// Can unwrap to get root cause
if wrappedErr.Unwrap() == rootErr {
fmt.Println("Successfully wrapped error")
}
}
Output: Successfully wrapped error
Example (ComparingErrors) ¶
Example_comparingErrors demonstrates before and after error format
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FORM users"
location := models.Location{Line: 1, Column: 10}
fmt.Println("=== BEFORE: Simple Error ===")
fmt.Println("Error: expected FROM, got FORM")
fmt.Println()
fmt.Println("=== AFTER: Enhanced Error ===")
err := errors.ExpectedTokenError("FROM", "FORM", location, sql)
fmt.Println(err.Error())
fmt.Println()
fmt.Println("Enhancement includes:")
fmt.Println("✓ Error code (E2002)")
fmt.Println("✓ Precise location (line 1, column 10)")
fmt.Println("✓ SQL context with visual indicator")
fmt.Println("✓ Intelligent hint with typo detection")
fmt.Println("✓ Documentation link")
}
Example (ContextExtraction) ¶
Example_contextExtraction demonstrates SQL context in error messages
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
// Multi-line SQL with error on line 2
sql := `SELECT *
FROM users
WHERE age > 18.45.6
ORDER BY name`
location := models.Location{Line: 3, Column: 13}
err := errors.InvalidNumberError("18.45.6", location, sql)
// Error includes:
// - The problematic line from the SQL
// - Position indicator pointing to the error
// - Helpful hint about numeric format
fmt.Println("Error detected in multi-line SQL:")
_ = err // Use the error
}
Example (CustomHints) ¶
Example_customHints demonstrates adding custom hints
package main
import (
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users WHERE"
location := models.Location{Line: 1, Column: 27}
err := errors.NewError(
errors.ErrCodeIncompleteStatement,
"incomplete WHERE clause",
location,
)
err.WithContext(sql, 5)
err.WithHint("Add a condition after WHERE, e.g., WHERE age > 18")
// Error now includes custom context and hint
_ = err
}
Example (CustomHintsEnhanced) ¶
Example_customHintsEnhanced demonstrates adding custom hints to errors
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users WHERE age > '18'"
location := models.Location{Line: 1, Column: 33}
err := errors.NewError(
errors.ErrCodeInvalidSyntax,
"type mismatch in comparison",
location,
)
err.WithContext(sql, 4) // Highlight '18'
err.WithHint("Age comparisons should use numeric values without quotes. Change '18' to 18")
fmt.Println("Custom Hint Example:")
fmt.Println(err.Error())
fmt.Println()
}
Example (EnhancedErrorWithContext) ¶
Example_enhancedErrorWithContext demonstrates the enhanced error formatting with 3 lines of context
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
// Multi-line SQL with an error on line 3
sql := `SELECT id, name, email
FROM users
WHERE age > 18.45.6
ORDER BY name`
location := models.Location{Line: 3, Column: 13}
err := errors.InvalidNumberError("18.45.6", location, sql)
fmt.Println("Enhanced Error Output:")
fmt.Println(err.Error())
fmt.Println()
// Note: This will show:
// - Line 2 (FROM users)
// - Line 3 (WHERE age > 18.45.6) with error indicator
// - Line 4 (ORDER BY name)
}
Example (ErrorChaining) ¶
Example_errorChaining demonstrates wrapping errors
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users"
location := models.Location{Line: 1, Column: 1}
// Create a chain of errors
rootErr := errors.NewError(
errors.ErrCodeInvalidSyntax,
"invalid table reference",
location,
)
wrappedErr := errors.WrapError(
errors.ErrCodeUnexpectedToken,
"parser error while processing SELECT",
location,
sql,
rootErr,
)
fmt.Println("Chained Error:")
fmt.Println(wrappedErr.Error())
fmt.Println()
// Can unwrap to get root cause
if wrappedErr.Unwrap() != nil {
fmt.Println("Root cause available through Unwrap()")
}
// Note: Output includes chained error with context
// Root cause available through Unwrap()
}
Example (ErrorCodeProgrammaticHandling) ¶
Example_errorCodeProgrammaticHandling demonstrates using error codes for logic
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM"
location := models.Location{Line: 1, Column: 14}
err := errors.IncompleteStatementError(location, sql)
// Check error type programmatically
if errors.IsCode(err, errors.ErrCodeIncompleteStatement) {
fmt.Println("Detected incomplete SQL statement")
fmt.Println("Error code:", errors.GetCode(err))
fmt.Println("Can suggest adding table name")
}
}
Output: Detected incomplete SQL statement Error code: E2005 Can suggest adding table name
Example (ErrorCodes) ¶
Example_errorCodes demonstrates programmatic error handling
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM"
location := models.Location{Line: 1, Column: 14}
// Create an error
err := errors.IncompleteStatementError(location, sql)
// Check error code programmatically
if errors.IsCode(err, errors.ErrCodeIncompleteStatement) {
fmt.Println("Detected incomplete SQL statement")
}
// Get error code
code := errors.GetCode(err)
fmt.Printf("Error code: %s\n", code)
}
Output: Detected incomplete SQL statement Error code: E2005
Example (ErrorRecovery) ¶
Example_errorRecovery demonstrates how to handle and recover from errors
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FORM users"
location := models.Location{Line: 1, Column: 10}
err := errors.ExpectedTokenError("FROM", "FORM", location, sql)
// Check if error is recoverable
if errors.IsCode(err, errors.ErrCodeExpectedToken) {
fmt.Println("Detected recoverable syntax error")
fmt.Println("Suggestion: Fix the typo and retry")
// Use the error's hint for auto-correction
if err.Hint != "" {
fmt.Println("Hint:", err.Hint)
}
}
}
Output: Detected recoverable syntax error Suggestion: Fix the typo and retry Hint: Did you mean 'FROM' instead of 'FORM'?
Example (IncompleteStatement) ¶
Example_incompleteStatement demonstrates incomplete SQL statement
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users WHERE"
location := models.Location{Line: 1, Column: 26}
err := errors.IncompleteStatementError(location, sql)
fmt.Println("Incomplete Statement Example:")
fmt.Println(err.Error())
fmt.Println()
}
Example (InvalidNumber) ¶
Example_invalidNumber demonstrates invalid number format error
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM products WHERE price > 19.99.5"
location := models.Location{Line: 1, Column: 38}
err := errors.InvalidNumberError("19.99.5", location, sql)
fmt.Println("Invalid Number Example:")
fmt.Println(err.Error())
fmt.Println()
}
Example (MissingClause) ¶
Example_missingClause demonstrates missing clause error with suggestions
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT id, name, email users WHERE age > 18"
location := models.Location{Line: 1, Column: 24}
err := errors.MissingClauseError("FROM", location, sql)
fmt.Println("Missing Clause Example:")
fmt.Println(err.Error())
fmt.Println()
}
Example (MultiLineError) ¶
Example_multiLineError demonstrates error in multi-line SQL with proper context
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := `SELECT
u.id,
u.name,
u.email
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.age > 18.45.6
AND o.total > 100`
location := models.Location{Line: 7, Column: 15}
err := errors.InvalidNumberError("18.45.6", location, sql)
fmt.Println("Multi-line SQL Error:")
fmt.Println(err.Error())
fmt.Println()
// Shows context with proper line numbering:
// Line 6: JOIN orders o ON u.id = o.user_id
// Line 7: WHERE u.age > 18.45.6 <- Error indicator here
// Line 8: AND o.total > 100
}
Example (MultipleErrors) ¶
Example_multipleErrors demonstrates handling multiple validation errors
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
)
func main() {
queries := []string{
"SELECT * FORM users", // E2002: Expected FROM
"SELECT * FROM", // E2005: Incomplete statement
"SELECT * FROM users WHERE age >", // E2005: Incomplete expression
}
errorCodes := []errors.ErrorCode{}
for _, query := range queries {
// In real usage, you'd call gosqlx.Parse() here
// For this example, we'll simulate errors
_ = query
}
fmt.Printf("Found %d SQL errors\n", len(errorCodes))
}
Example (RealWorldScenario) ¶
Example_realWorldScenario demonstrates a complete real-world error scenario
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
// Simulate a real SQL query with multiple errors
sqlQueries := []struct {
sql string
location models.Location
errType string
}{
{
sql: "SELECT id, name email FROM users",
location: models.Location{Line: 1, Column: 17},
errType: "missing_comma",
},
{
sql: "SELECT * FROM users WHERE age > '18'",
location: models.Location{Line: 1, Column: 33},
errType: "string_instead_of_number",
},
{
sql: "SELECT * FROM users JOIN orders",
location: models.Location{Line: 1, Column: 25},
errType: "missing_join_condition",
},
}
fmt.Println("=== Real-World Error Scenarios ===")
fmt.Println()
for i, query := range sqlQueries {
fmt.Printf("Scenario %d: %s\n", i+1, query.errType)
fmt.Println("Query:", query.sql)
// In real usage, the parser would detect and create these errors
fmt.Println("(Error details would be shown here with full context and suggestions)")
fmt.Println()
}
}
Example (TypoDetection) ¶
Example_typoDetection demonstrates automatic typo detection
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
)
func main() {
// Common SQL keyword typos are automatically detected
// Using a slice to maintain predictable order
typos := []struct {
typo string
correct string
}{
{"FORM", "FROM"},
{"JION", "JOIN"},
{"SELCT", "SELECT"},
{"UPDTE", "UPDATE"},
{"WAHER", "WHERE"},
}
for _, t := range typos {
suggestion := errors.SuggestKeyword(t.typo)
if suggestion == t.correct {
fmt.Printf("%s → %s ✓\n", t.typo, suggestion)
}
}
}
Output: FORM → FROM ✓ JION → JOIN ✓ SELCT → SELECT ✓ UPDTE → UPDATE ✓ WAHER → WHERE ✓
Example (TypoDetectionWithSuggestions) ¶
Example_typoDetectionWithSuggestions demonstrates automatic typo detection
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
// Common SQL keyword typo
sql := "SELECT * FORM users WHERE age > 18"
location := models.Location{Line: 1, Column: 10}
err := errors.ExpectedTokenError("FROM", "FORM", location, sql)
fmt.Println("Typo Detection Example:")
fmt.Println(err.Error())
fmt.Println()
// The error will include:
// - Error code and location
// - SQL context with the typo highlighted
// - Intelligent hint: "Did you mean 'FROM' instead of 'FORM'?"
// - Help URL for documentation
}
Example (UnexpectedCharacter) ¶
Example_unexpectedCharacter demonstrates unexpected character in SQL
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users WHERE age > 18 & active = 1"
location := models.Location{Line: 1, Column: 36}
err := errors.UnexpectedCharError('&', location, sql)
fmt.Println("Unexpected Character Example:")
fmt.Println(err.Error())
fmt.Println()
// Suggests: "Remove or escape the character '&'"
// User should use AND instead of &
}
Example (UnterminatedString) ¶
Example_unterminatedString demonstrates unterminated string error
package main
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
func main() {
sql := "SELECT * FROM users WHERE name = 'John"
location := models.Location{Line: 1, Column: 34}
err := errors.UnterminatedStringError(location, sql)
fmt.Println("Unterminated String Example:")
fmt.Println(err.Error())
fmt.Println()
}
Index ¶
- Variables
- func AnalyzeTokenError(tokenType, tokenValue, expectedType string) string
- func ClearSuggestionCache()
- func ExtractLocation(err error) (models.Location, bool)
- func FormatContextWindow(sql string, location models.Location, highlightLen int, ...) string
- func FormatErrorList(errors []*Error) string
- func FormatErrorSummary(err error) string
- func FormatErrorWithContext(err error, sql string) string
- func FormatErrorWithContextAt(code ErrorCode, message string, location models.Location, sql string, ...) string
- func FormatErrorWithExample(code ErrorCode, message string, location models.Location, sql string, ...) string
- func FormatErrorWithSuggestion(code ErrorCode, message string, location models.Location, sql string, ...) string
- func FormatMistakeExample(mistake MistakePattern) string
- func FormatMultiLineContext(sql string, location models.Location, highlightLen int) string
- func GenerateDidYouMean(actual string, possibleValues []string) string
- func GenerateHint(code ErrorCode, expected, found string) string
- func GetAdvancedFeatureHint(feature string) string
- func GetCommonHint(key string) string
- func IsCode(err error, code ErrorCode) bool
- func IsStructuredError(err error) bool
- func ResetSuggestionCacheStats()
- func SuggestForCTE(context string) string
- func SuggestForIncompleteStatement(lastKeyword string) string
- func SuggestForJoinError(joinType, context string) string
- func SuggestForSetOperation(operation, context string) string
- func SuggestForSyntaxError(context, expectedToken string) string
- func SuggestForWindowFunction(context, functionName string) string
- func SuggestFromPattern(errorMessage string) string
- func SuggestKeyword(input string) string
- func SuggestionCacheSize() int
- type Error
- func AmbiguousColumnError(columnName string, tables []string, location models.Location, sql string) *Error
- func ExpectedTokenError(expected, got string, location models.Location, sql string) *Error
- func IncompleteStatementError(location models.Location, sql string) *Error
- func InputTooLargeError(size, maxSize int64, location models.Location) *Error
- func InvalidCTEError(description string, location models.Location, sql string) *Error
- func InvalidNumberError(value string, location models.Location, sql string) *Error
- func InvalidSetOperationError(operation, description string, location models.Location, sql string) *Error
- func InvalidSyntaxError(description string, location models.Location, sql string) *Error
- func MissingClauseError(clause string, location models.Location, sql string) *Error
- func NewError(code ErrorCode, message string, location models.Location) *Error
- func RecursionDepthLimitError(depth, maxDepth int, location models.Location, sql string) *Error
- func TokenLimitReachedError(count, maxTokens int, location models.Location, sql string) *Error
- func TokenizerPanicError(panicValue interface{}, location models.Location) *Error
- func TypeMismatchError(leftType, rightType, context string, location models.Location, sql string) *Error
- func UndefinedColumnError(columnName, tableName string, location models.Location, sql string) *Error
- func UndefinedTableError(tableName string, location models.Location, sql string) *Error
- func UnexpectedCharError(char rune, location models.Location, sql string) *Error
- func UnexpectedTokenError(tokenType, tokenValue string, location models.Location, sql string) *Error
- func UnsupportedConstraintError(constraint string, location models.Location, sql string) *Error
- func UnsupportedDataTypeError(dataType string, location models.Location, sql string) *Error
- func UnsupportedFeatureError(feature string, location models.Location, sql string) *Error
- func UnsupportedJoinError(joinType string, location models.Location, sql string) *Error
- func UnterminatedStringError(location models.Location, sql string) *Error
- func WrapError(code ErrorCode, message string, location models.Location, sql string, ...) *Error
- type ErrorCode
- type ErrorContext
- type ErrorPattern
- type MistakePattern
- type SuggestionCacheStats
Examples ¶
- Package (AllErrorCodes)
- Package (BasicError)
- Package (BatchValidation)
- Package (ChainedErrors)
- Package (ComparingErrors)
- Package (ContextExtraction)
- Package (CustomHints)
- Package (CustomHintsEnhanced)
- Package (EnhancedErrorWithContext)
- Package (ErrorChaining)
- Package (ErrorCodeProgrammaticHandling)
- Package (ErrorCodes)
- Package (ErrorRecovery)
- Package (IncompleteStatement)
- Package (InvalidNumber)
- Package (MissingClause)
- Package (MultiLineError)
- Package (MultipleErrors)
- Package (RealWorldScenario)
- Package (TypoDetection)
- Package (TypoDetectionWithSuggestions)
- Package (UnexpectedCharacter)
- Package (UnterminatedString)
Constants ¶
This section is empty.
Variables ¶
var CommonHints = map[string]string{
"missing_from": "SELECT statements require a FROM clause unless selecting constants",
"missing_where": "Add a WHERE clause to filter the results",
"unclosed_paren": "Check that all parentheses are properly matched",
"missing_comma": "List items should be separated by commas",
"invalid_join": "JOIN clauses must include ON or USING conditions",
"duplicate_alias": "Each table alias must be unique within the query",
"ambiguous_column": "Qualify the column name with the table name or alias (e.g., table.column)",
}
Common error scenarios with pre-built hints
Functions ¶
func AnalyzeTokenError ¶
AnalyzeTokenError analyzes token-based errors and provides context-aware suggestions
func ClearSuggestionCache ¶ added in v1.6.0
func ClearSuggestionCache()
ClearSuggestionCache clears the keyword suggestion cache. Useful for testing or when keyword list changes.
func ExtractLocation ¶
ExtractLocation extracts location information from an error
func FormatContextWindow ¶
func FormatContextWindow(sql string, location models.Location, highlightLen int, linesBefore, linesAfter int) string
FormatContextWindow formats a larger context window (up to N lines before and after)
func FormatErrorList ¶
FormatErrorList formats multiple errors in a readable list
func FormatErrorSummary ¶
FormatErrorSummary provides a brief summary of an error without full context Useful for logging or when SQL context is not needed
func FormatErrorWithContext ¶
FormatErrorWithContext formats an error with SQL context and visual indicators This is a convenience function that wraps the Error.Error() method
func FormatErrorWithContextAt ¶
func FormatErrorWithContextAt(code ErrorCode, message string, location models.Location, sql string, highlightLen int) string
FormatErrorWithContextAt formats an error at a specific location with SQL context
func FormatErrorWithExample ¶
func FormatErrorWithExample(code ErrorCode, message string, location models.Location, sql string, highlightLen int, wrongExample, correctExample string) string
FormatErrorWithExample formats an error with a corrected example
func FormatErrorWithSuggestion ¶
func FormatErrorWithSuggestion(code ErrorCode, message string, location models.Location, sql string, highlightLen int, suggestion string) string
FormatErrorWithSuggestion formats an error with an intelligent suggestion
func FormatMistakeExample ¶
func FormatMistakeExample(mistake MistakePattern) string
FormatMistakeExample formats a mistake pattern for display
func FormatMultiLineContext ¶
FormatMultiLineContext formats error context for multi-line SQL with extended context Shows up to 3 lines (1 before, error line, 1 after) with proper indentation
func GenerateDidYouMean ¶
GenerateDidYouMean generates "Did you mean?" suggestions for typos
func GenerateHint ¶
GenerateHint generates an intelligent hint based on the error type and context
func GetAdvancedFeatureHint ¶
GetAdvancedFeatureHint returns hints for advanced SQL features
func GetCommonHint ¶
GetCommonHint retrieves a pre-defined hint by key
func IsCode ¶
IsCode checks if an error has a specific error code.
Type-safe way to check error codes for programmatic error handling. Works with both *Error and other error types (returns false for non-Error).
Parameters:
- err: The error to check
- code: The ErrorCode to match against
Returns true if err is a *Error with matching code, false otherwise.
Example:
if errors.IsCode(err, errors.ErrCodeUnterminatedString) {
// Handle unterminated string error specifically
}
if errors.IsCode(err, errors.ErrCodeExpectedToken) {
// Handle expected token error
}
Common pattern:
switch {
case errors.IsCode(err, errors.ErrCodeUnexpectedToken):
// Handle unexpected token
case errors.IsCode(err, errors.ErrCodeMissingClause):
// Handle missing clause
default:
// Handle other errors
}
func IsStructuredError ¶
IsStructuredError checks if an error is a structured GoSQLX error
func ResetSuggestionCacheStats ¶ added in v1.6.0
func ResetSuggestionCacheStats()
ResetSuggestionCacheStats resets the cache statistics counters. Useful for testing and monitoring.
func SuggestForCTE ¶
SuggestForCTE provides suggestions for Common Table Expression errors
func SuggestForIncompleteStatement ¶
SuggestForIncompleteStatement provides suggestions for incomplete SQL statements
func SuggestForJoinError ¶
SuggestForJoinError provides enhanced suggestions for JOIN-related errors
func SuggestForSetOperation ¶
SuggestForSetOperation provides suggestions for UNION/INTERSECT/EXCEPT errors
func SuggestForSyntaxError ¶
SuggestForSyntaxError provides context-aware suggestions for syntax errors
func SuggestForWindowFunction ¶
SuggestForWindowFunction provides suggestions for window function errors
func SuggestFromPattern ¶
SuggestFromPattern tries to match error message against known patterns
func SuggestKeyword ¶
SuggestKeyword uses Levenshtein distance to suggest the closest matching keyword. Results are cached to improve performance in repeated error scenarios.
func SuggestionCacheSize ¶ added in v1.6.0
func SuggestionCacheSize() int
SuggestionCacheSize returns the current size of the suggestion cache. Useful for monitoring and debugging.
Types ¶
type Error ¶
type Error struct {
Code ErrorCode // Unique error code (e.g., "E2001")
Message string // Human-readable error message
Location models.Location // Line and column where error occurred
Context *ErrorContext // SQL context around the error
Hint string // Suggestion to fix the error
HelpURL string // Documentation link for this error
Cause error // Underlying error if any
}
Error represents a structured error with rich context and hints.
Error is the main error type in GoSQLX, providing comprehensive information for debugging and user feedback. It includes error codes, precise locations, SQL context with highlighting, intelligent hints, and help URLs.
Fields:
- Code: Unique error identifier (E1xxx-E4xxx) for programmatic handling
- Message: Human-readable error description
- Location: Precise line/column where error occurred (1-based)
- Context: SQL source context with highlighting (optional)
- Hint: Auto-generated suggestion to fix the error (optional)
- HelpURL: Documentation link for this error code
- Cause: Underlying error if wrapped (optional)
Example creation:
err := errors.NewError(
errors.ErrCodeUnexpectedToken,
"unexpected token: COMMA",
models.Location{Line: 5, Column: 20},
)
err = err.WithContext(sqlSource, 1)
err = err.WithHint("Expected FROM keyword after SELECT clause")
Error output format:
Error E2001 at line 5, column 20: unexpected token: COMMA
4 | SELECT name, email
5 | FROM users, WHERE active = true
^^^^
6 |
Hint: Expected FROM keyword after SELECT clause
Help: https://docs.gosqlx.dev/errors/E2001
Thread Safety: Error instances are immutable after creation. Methods like WithContext, WithHint return new Error instances and are safe for concurrent use.
func AmbiguousColumnError ¶ added in v1.6.0
func AmbiguousColumnError(columnName string, tables []string, location models.Location, sql string) *Error
AmbiguousColumnError creates an error for ambiguous column reference
func ExpectedTokenError ¶
ExpectedTokenError creates an error for missing expected token
func IncompleteStatementError ¶
IncompleteStatementError creates an error for incomplete SQL statement
func InputTooLargeError ¶
InputTooLargeError creates an error for input exceeding size limits
func InvalidCTEError ¶
InvalidCTEError creates an error for invalid CTE (WITH clause) syntax
func InvalidNumberError ¶
InvalidNumberError creates an error for invalid numeric literal
func InvalidSetOperationError ¶
func InvalidSetOperationError(operation, description string, location models.Location, sql string) *Error
InvalidSetOperationError creates an error for invalid set operation
func InvalidSyntaxError ¶
InvalidSyntaxError creates a general syntax error
func MissingClauseError ¶
MissingClauseError creates an error for missing required SQL clause
func NewError ¶
NewError creates a new structured error.
Factory function for creating GoSQLX errors with error code, message, and location. This is the primary way to create errors in the library.
Parameters:
- code: ErrorCode for programmatic error handling (E1xxx-E4xxx)
- message: Human-readable error description
- location: Precise line/column where error occurred
Returns a new Error with the specified fields and auto-generated help URL.
Example:
err := errors.NewError(
errors.ErrCodeUnexpectedToken,
"unexpected token: COMMA",
models.Location{Line: 5, Column: 20},
)
// err.HelpURL is automatically set to https://docs.gosqlx.dev/errors/E2001
The error can be enhanced with additional context:
err = err.WithContext(sqlSource, 1).WithHint("Expected FROM keyword")
func RecursionDepthLimitError ¶
RecursionDepthLimitError creates an error for recursion depth exceeded
func TokenLimitReachedError ¶
TokenLimitReachedError creates an error for token count exceeding limit
func TokenizerPanicError ¶
TokenizerPanicError creates an error for recovered tokenizer panic
func TypeMismatchError ¶ added in v1.6.0
func TypeMismatchError(leftType, rightType, context string, location models.Location, sql string) *Error
TypeMismatchError creates an error for type mismatch in expressions
func UndefinedColumnError ¶ added in v1.6.0
func UndefinedColumnError(columnName, tableName string, location models.Location, sql string) *Error
UndefinedColumnError creates an error for referencing an undefined column
func UndefinedTableError ¶ added in v1.6.0
UndefinedTableError creates an error for referencing an undefined table
func UnexpectedCharError ¶
UnexpectedCharError creates an error for unexpected character in tokenization
func UnexpectedTokenError ¶
func UnexpectedTokenError(tokenType, tokenValue string, location models.Location, sql string) *Error
UnexpectedTokenError creates an error for unexpected token in parsing
func UnsupportedConstraintError ¶
UnsupportedConstraintError creates an error for unsupported constraint
func UnsupportedDataTypeError ¶
UnsupportedDataTypeError creates an error for unsupported data type
func UnsupportedFeatureError ¶
UnsupportedFeatureError creates an error for unsupported SQL features
func UnsupportedJoinError ¶
UnsupportedJoinError creates an error for unsupported JOIN type
func UnterminatedStringError ¶
UnterminatedStringError creates an error for unterminated string literal
func WrapError ¶
func WrapError(code ErrorCode, message string, location models.Location, sql string, cause error) *Error
WrapError wraps an existing error with structured error information
func (*Error) Error ¶
Error implements the error interface.
Returns a formatted error message including:
- Error code and location (line/column)
- Error message
- SQL context with visual highlighting (if available)
- Hint/suggestion (if available)
- Help URL for documentation
Example output:
Error E2002 at line 1, column 15: expected FROM, got FORM
1 | SELECT * FORM users WHERE id = 1
^^^^
Hint: Did you mean 'FROM' instead of 'FORM'?
Help: https://docs.gosqlx.dev/errors/E2002
This method is called automatically when the error is printed or logged.
func (*Error) Unwrap ¶
Unwrap returns the underlying error.
Implements error unwrapping for Go 1.13+ error chains. This allows errors.Is and errors.As to work with wrapped errors.
Example:
originalErr := someFunc()
wrappedErr := errors.NewError(...).WithCause(originalErr)
if errors.Is(wrappedErr, originalErr) {
// Can check for original error
}
func (*Error) WithCause ¶
WithCause adds an underlying cause error.
Wraps another error as the cause of this error, enabling error chaining and unwrapping with errors.Is and errors.As.
Parameters:
- cause: The underlying error that caused this error
Returns the same Error instance with cause added (for method chaining).
Example:
ioErr := os.ReadFile(filename) // Returns error
err := errors.NewError(
errors.ErrCodeInvalidSyntax,
"failed to read SQL file",
location,
).WithCause(ioErr)
// Check for original error
if errors.Is(err, os.ErrNotExist) {
// Handle file not found
}
Note: WithCause modifies the error in-place and returns it for chaining.
func (*Error) WithContext ¶
WithContext adds SQL context to the error.
Attaches SQL source code context with highlighting information for visual error display. The context shows surrounding lines and highlights the specific location of the error.
Parameters:
- sql: Original SQL source code
- highlightLen: Number of characters to highlight (starting at error column)
Returns the same Error instance with context added (for method chaining).
Example:
err := errors.NewError(code, "error message", location)
err = err.WithContext("SELECT * FORM users", 4) // Highlight "FORM"
The context will be displayed as:
1 | SELECT * FORM users
^^^^
Note: WithContext modifies the error in-place and returns it for chaining.
func (*Error) WithHint ¶
WithHint adds a suggestion hint to the error.
Attaches a helpful suggestion for fixing the error. Hints are generated automatically by builder functions or can be added manually.
Parameters:
- hint: Suggestion text (e.g., "Did you mean 'FROM' instead of 'FORM'?")
Returns the same Error instance with hint added (for method chaining).
Example:
err := errors.NewError(code, "message", location)
err = err.WithHint("Expected FROM keyword after SELECT clause")
Auto-generated hints:
err := errors.ExpectedTokenError("FROM", "FORM", location, sql)
// Automatically includes: "Did you mean 'FROM' instead of 'FORM'?"
Note: WithHint modifies the error in-place and returns it for chaining.
type ErrorCode ¶
type ErrorCode string
ErrorCode represents a unique error code for programmatic handling.
ErrorCode is a strongly-typed string for error classification. It enables programmatic error handling, filtering, and logging in production systems.
Error codes follow the pattern: E[category][number]
- E1xxx: Tokenizer/lexical errors
- E2xxx: Parser/syntax errors
- E3xxx: Semantic errors
- E4xxx: Unsupported features
Example usage:
err := errors.NewError(errors.ErrCodeUnexpectedToken, "msg", location)
if errors.IsCode(err, errors.ErrCodeUnexpectedToken) {
// Handle unexpected token error specifically
}
code := errors.GetCode(err)
switch code {
case errors.ErrCodeExpectedToken:
// Handle syntax errors
case errors.ErrCodeUndefinedTable:
// Handle semantic errors
}
const ( // E1xxx: Tokenizer errors ErrCodeUnexpectedChar ErrorCode = "E1001" // Unexpected character in input ErrCodeUnterminatedString ErrorCode = "E1002" // String literal not closed ErrCodeInvalidNumber ErrorCode = "E1003" // Invalid numeric literal ErrCodeInvalidOperator ErrorCode = "E1004" // Invalid operator sequence ErrCodeInvalidIdentifier ErrorCode = "E1005" // Invalid identifier format ErrCodeInputTooLarge ErrorCode = "E1006" // Input exceeds size limits (DoS protection) ErrCodeTokenLimitReached ErrorCode = "E1007" // Token count exceeds limit (DoS protection) ErrCodeTokenizerPanic ErrorCode = "E1008" // Tokenizer panic recovered // E2xxx: Parser syntax errors ErrCodeUnexpectedToken ErrorCode = "E2001" // Unexpected token encountered ErrCodeExpectedToken ErrorCode = "E2002" // Expected specific token not found ErrCodeMissingClause ErrorCode = "E2003" // Required SQL clause missing ErrCodeInvalidSyntax ErrorCode = "E2004" // General syntax error ErrCodeIncompleteStatement ErrorCode = "E2005" // Statement incomplete ErrCodeInvalidExpression ErrorCode = "E2006" // Invalid expression syntax ErrCodeRecursionDepthLimit ErrorCode = "E2007" // Recursion depth exceeded (DoS protection) ErrCodeUnsupportedDataType ErrorCode = "E2008" // Data type not supported ErrCodeUnsupportedConstraint ErrorCode = "E2009" // Constraint type not supported ErrCodeUnsupportedJoin ErrorCode = "E2010" // JOIN type not supported ErrCodeInvalidCTE ErrorCode = "E2011" // Invalid CTE (WITH clause) syntax ErrCodeInvalidSetOperation ErrorCode = "E2012" // Invalid set operation (UNION/EXCEPT/INTERSECT) // E3xxx: Semantic errors ErrCodeUndefinedTable ErrorCode = "E3001" // Table not defined ErrCodeUndefinedColumn ErrorCode = "E3002" // Column not defined ErrCodeTypeMismatch ErrorCode = "E3003" // Type mismatch in expression ErrCodeAmbiguousColumn ErrorCode = "E3004" // Ambiguous column reference // E4xxx: Unsupported features ErrCodeUnsupportedFeature ErrorCode = "E4001" // Feature not yet supported ErrCodeUnsupportedDialect ErrorCode = "E4002" // SQL dialect not supported )
Error code categories
func ExtractErrorCode ¶
ExtractErrorCode extracts the error code from an error
func GetCode ¶
GetCode returns the error code from an error, or empty string if not a structured error.
Extracts the ErrorCode from a *Error. Returns empty string for non-Error types.
Parameters:
- err: The error to extract code from
Returns the ErrorCode if err is a *Error, empty string otherwise.
Example:
code := errors.GetCode(err)
switch code {
case errors.ErrCodeExpectedToken:
// Handle syntax errors
case errors.ErrCodeUndefinedTable:
// Handle semantic errors
case "":
// Not a structured error
}
Logging example:
if code := errors.GetCode(err); code != "" {
log.Printf("SQL error [%s]: %v", code, err)
}
type ErrorContext ¶
type ErrorContext struct {
SQL string // Original SQL query
StartLine int // Starting line number (1-indexed)
EndLine int // Ending line number (1-indexed)
HighlightCol int // Column to highlight (1-indexed)
HighlightLen int // Length of highlight (number of characters)
}
ErrorContext contains the SQL source and position information for display.
ErrorContext provides the SQL source code context around an error with precise highlighting information. Used to generate visual error displays with line numbers and position indicators.
Fields:
- SQL: Original SQL query source code
- StartLine: First line to display in context (1-based)
- EndLine: Last line to display in context (1-based)
- HighlightCol: Column to start highlighting (1-based)
- HighlightLen: Number of characters to highlight
Example:
ctx := &errors.ErrorContext{
SQL: "SELECT * FORM users",
StartLine: 1,
EndLine: 1,
HighlightCol: 10,
HighlightLen: 4, // Highlight "FORM"
}
The context is displayed as:
1 | SELECT * FORM users
^^^^
type ErrorPattern ¶
ErrorPattern represents a common SQL error pattern with suggestions
type MistakePattern ¶
type MistakePattern struct {
Name string
Example string // Example of the mistake
Correct string // Correct version
Explanation string
}
MistakePattern represents common SQL mistakes with explanations
func GetMistakeExplanation ¶
func GetMistakeExplanation(mistakeName string) (MistakePattern, bool)
GetMistakeExplanation returns explanation for a common mistake
type SuggestionCacheStats ¶ added in v1.6.0
type SuggestionCacheStats struct {
Size int
MaxSize int
Hits uint64
Misses uint64
Evictions uint64
HitRate float64
}
SuggestionCacheStats returns cache statistics
func GetSuggestionCacheStats ¶ added in v1.6.0
func GetSuggestionCacheStats() SuggestionCacheStats
GetSuggestionCacheStats returns current cache statistics