errors

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2025 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

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.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func AnalyzeTokenError(tokenType, tokenValue, expectedType string) string

AnalyzeTokenError analyzes token-based errors and provides context-aware suggestions

func ExtractLocation

func ExtractLocation(err error) (models.Location, bool)

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

func FormatErrorList(errors []*Error) string

FormatErrorList formats multiple errors in a readable list

func FormatErrorSummary

func FormatErrorSummary(err error) string

FormatErrorSummary provides a brief summary of an error without full context Useful for logging or when SQL context is not needed

func FormatErrorWithContext

func FormatErrorWithContext(err error, sql string) string

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

func FormatMultiLineContext(sql string, location models.Location, highlightLen int) string

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

func GenerateDidYouMean(actual string, possibleValues []string) string

GenerateDidYouMean generates "Did you mean?" suggestions for typos

func GenerateHint

func GenerateHint(code ErrorCode, expected, found string) string

GenerateHint generates an intelligent hint based on the error type and context

func GetAdvancedFeatureHint

func GetAdvancedFeatureHint(feature string) string

GetAdvancedFeatureHint returns hints for advanced SQL features

func GetCommonHint

func GetCommonHint(key string) string

GetCommonHint retrieves a pre-defined hint by key

func IsCode

func IsCode(err error, code ErrorCode) bool

IsCode checks if an error has a specific error code

func IsStructuredError

func IsStructuredError(err error) bool

IsStructuredError checks if an error is a structured GoSQLX error

func SuggestForCTE

func SuggestForCTE(context string) string

SuggestForCTE provides suggestions for Common Table Expression errors

func SuggestForIncompleteStatement

func SuggestForIncompleteStatement(lastKeyword string) string

SuggestForIncompleteStatement provides suggestions for incomplete SQL statements

func SuggestForJoinError

func SuggestForJoinError(joinType, context string) string

SuggestForJoinError provides enhanced suggestions for JOIN-related errors

func SuggestForSetOperation

func SuggestForSetOperation(operation, context string) string

SuggestForSetOperation provides suggestions for UNION/INTERSECT/EXCEPT errors

func SuggestForSyntaxError

func SuggestForSyntaxError(context, expectedToken string) string

SuggestForSyntaxError provides context-aware suggestions for syntax errors

func SuggestForWindowFunction

func SuggestForWindowFunction(context, functionName string) string

SuggestForWindowFunction provides suggestions for window function errors

func SuggestFromPattern

func SuggestFromPattern(errorMessage string) string

SuggestFromPattern tries to match error message against known patterns

func SuggestKeyword

func SuggestKeyword(input string) string

SuggestKeyword uses Levenshtein distance to suggest the closest matching keyword

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

func ExpectedTokenError

func ExpectedTokenError(expected, got string, location models.Location, sql string) *Error

ExpectedTokenError creates an error for missing expected token

func IncompleteStatementError

func IncompleteStatementError(location models.Location, sql string) *Error

IncompleteStatementError creates an error for incomplete SQL statement

func InputTooLargeError

func InputTooLargeError(size, maxSize int64, location models.Location) *Error

InputTooLargeError creates an error for input exceeding size limits

func InvalidCTEError

func InvalidCTEError(description string, location models.Location, sql string) *Error

InvalidCTEError creates an error for invalid CTE (WITH clause) syntax

func InvalidNumberError

func InvalidNumberError(value string, location models.Location, sql string) *Error

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

func InvalidSyntaxError(description string, location models.Location, sql string) *Error

InvalidSyntaxError creates a general syntax error

func MissingClauseError

func MissingClauseError(clause string, location models.Location, sql string) *Error

MissingClauseError creates an error for missing required SQL clause

func NewError

func NewError(code ErrorCode, message string, location models.Location) *Error

NewError creates a new structured error

func RecursionDepthLimitError

func RecursionDepthLimitError(depth, maxDepth int, location models.Location, sql string) *Error

RecursionDepthLimitError creates an error for recursion depth exceeded

func TokenLimitReachedError

func TokenLimitReachedError(count, maxTokens int, location models.Location, sql string) *Error

TokenLimitReachedError creates an error for token count exceeding limit

func TokenizerPanicError

func TokenizerPanicError(panicValue interface{}, location models.Location) *Error

TokenizerPanicError creates an error for recovered tokenizer panic

func UnexpectedCharError

func UnexpectedCharError(char rune, location models.Location, sql string) *Error

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

func UnsupportedConstraintError(constraint string, location models.Location, sql string) *Error

UnsupportedConstraintError creates an error for unsupported constraint

func UnsupportedDataTypeError

func UnsupportedDataTypeError(dataType string, location models.Location, sql string) *Error

UnsupportedDataTypeError creates an error for unsupported data type

func UnsupportedFeatureError

func UnsupportedFeatureError(feature string, location models.Location, sql string) *Error

UnsupportedFeatureError creates an error for unsupported SQL features

func UnsupportedJoinError

func UnsupportedJoinError(joinType string, location models.Location, sql string) *Error

UnsupportedJoinError creates an error for unsupported JOIN type

func UnterminatedStringError

func UnterminatedStringError(location models.Location, sql string) *Error

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

func (e *Error) Error() string

Error implements the error interface

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause adds an underlying cause error

func (*Error) WithContext

func (e *Error) WithContext(sql string, highlightLen int) *Error

WithContext adds SQL context to the error

func (*Error) WithHint

func (e *Error) WithHint(hint string) *Error

WithHint adds a suggestion hint to the error

type ErrorCode

type ErrorCode string

ErrorCode represents a unique error code for programmatic handling

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

func ExtractErrorCode(err error) (ErrorCode, bool)

ExtractErrorCode extracts the error code from an error

func GetCode

func GetCode(err error) ErrorCode

GetCode returns the error code from an error, or empty string if not a structured error

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

type ErrorPattern

type ErrorPattern struct {
	Pattern     *regexp.Regexp
	Description string
	Suggestion  string
}

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

Jump to

Keyboard shortcuts

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