Documentation
¶
Overview ¶
Package query provides a query language parser and SQL compiler for CodeAI.
Index ¶
- type BetweenValue
- type CompareOp
- type CompiledQuery
- type Condition
- type DB
- type EntityMeta
- type ErrorType
- type Executor
- func (e *Executor) Execute(ctx context.Context, q *Query) ([]map[string]interface{}, error)
- func (e *Executor) ExecuteAggregate(ctx context.Context, q *Query) (interface{}, error)
- func (e *Executor) ExecuteCount(ctx context.Context, q *Query) (int64, error)
- func (e *Executor) ExecuteDelete(ctx context.Context, q *Query) (int64, error)
- func (e *Executor) ExecuteOne(ctx context.Context, q *Query) (map[string]interface{}, error)
- func (e *Executor) ExecuteString(ctx context.Context, queryStr string) ([]map[string]interface{}, error)
- func (e *Executor) ExecuteUpdate(ctx context.Context, q *Query) (int64, error)
- type Lexer
- type LogicalOp
- type OrderClause
- type OrderDirection
- type Parameter
- type Parser
- type Position
- type Query
- type QueryBuilder
- func (qb *QueryBuilder) Build() *Query
- func (qb *QueryBuilder) Decrement(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Execute(ctx context.Context, exec *Executor) ([]map[string]interface{}, error)
- func (qb *QueryBuilder) ExecuteOne(ctx context.Context, exec *Executor) (map[string]interface{}, error)
- func (qb *QueryBuilder) Fields(fields ...string) *QueryBuilder
- func (qb *QueryBuilder) Include(relations ...string) *QueryBuilder
- func (qb *QueryBuilder) Increment(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
- func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
- func (qb *QueryBuilder) OrderBy(field string, direction OrderDirection) *QueryBuilder
- func (qb *QueryBuilder) Set(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Where(field string, op CompareOp, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) WhereClause(where *WhereClause) *QueryBuilder
- type QueryError
- func ErrInvalidLimit(value string) *QueryError
- func ErrInvalidOffset(value string) *QueryError
- func ErrInvalidOperator(tok Token) *QueryError
- func ErrInvalidQueryType(queryType QueryType) *QueryError
- func ErrInvalidValue(tok Token, expected string) *QueryError
- func ErrMissingEntity() *QueryError
- func ErrNestedGroupDepth(maxDepth int) *QueryError
- func ErrTypeMismatch(field, expectedType, gotType string) *QueryError
- func ErrUnexpectedEOF(expected string) *QueryError
- func ErrUnexpectedToken(tok Token, expected string) *QueryError
- func ErrUnknownEntity(name string) *QueryError
- func ErrUnknownField(entity, field string) *QueryError
- func NewCompilerError(message string) *QueryError
- func NewCompilerErrorWithPosition(pos Position, message string) *QueryError
- func NewExecutionError(message string) *QueryError
- func NewLexerError(pos Position, message string) *QueryError
- func NewLexerErrorWithToken(tok Token, message string) *QueryError
- func NewParserError(pos Position, message string) *QueryError
- func NewParserErrorWithToken(tok Token, message string) *QueryError
- func NewSemanticError(pos Position, message string) *QueryError
- type QueryErrors
- type QueryType
- type RelationMeta
- type RelationType
- type SQLCompiler
- type Token
- type TokenType
- type UpdateOp
- type UpdateSet
- type WhereClause
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BetweenValue ¶
type BetweenValue struct {
Low interface{}
High interface{}
}
BetweenValue represents a range for BETWEEN operator.
type CompareOp ¶
type CompareOp int
CompareOp represents a comparison operator.
const ( OpEquals CompareOp = iota OpNotEquals OpGreaterThan OpGreaterThanOrEqual OpLessThan OpLessThanOrEqual OpContains OpStartsWith OpEndsWith OpIn OpNotIn OpIsNull OpIsNotNull OpIncludes // For arrays OpLike OpILike OpBetween OpFuzzy // For fuzzy search (~) OpExact // For exact phrase search OpArrayContains // For PostgreSQL @> )
type CompiledQuery ¶
type CompiledQuery struct {
SQL string
Params []interface{}
}
CompiledQuery represents a compiled SQL query with parameters.
type Condition ¶
type Condition struct {
Field string
Operator CompareOp
Value interface{}
Not bool // For NOT prefix
SubQuery *Query // For subqueries
Nested *WhereClause // For grouped conditions (a OR b) AND c
}
Condition represents a single condition in a WHERE clause.
type DB ¶
type DB interface {
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}
DB is the interface for database operations.
type EntityMeta ¶
type EntityMeta struct {
TableName string
PrimaryKey string
SoftDelete string // Column name for soft delete (e.g., "deleted_at")
Columns map[string]string // Maps field names to column names
JSONColumns map[string]bool // Columns that store JSON data
TSVColumns map[string]string // Full-text search columns (field -> tsvector column)
Relations map[string]*RelationMeta
}
EntityMeta contains metadata about an entity for SQL compilation.
type ErrorType ¶
type ErrorType int
ErrorType categorizes query errors for structured handling.
const ( // ErrorLexer indicates a lexical error (invalid token). ErrorLexer ErrorType = iota // ErrorParser indicates a syntax error during parsing. ErrorParser // ErrorSemantic indicates a semantic error (e.g., unknown entity). ErrorSemantic // ErrorCompiler indicates an error during SQL compilation. ErrorCompiler // ErrorExecution indicates an error during query execution. ErrorExecution )
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor executes compiled queries against a database.
func NewExecutor ¶
func NewExecutor(db DB, entities map[string]*EntityMeta) *Executor
NewExecutor creates a new query executor.
func (*Executor) ExecuteAggregate ¶
ExecuteAggregate executes an aggregate query (SUM, AVG, MIN, MAX) and returns the result.
func (*Executor) ExecuteCount ¶
ExecuteCount executes a COUNT query and returns the count.
func (*Executor) ExecuteDelete ¶
ExecuteDelete executes a DELETE query and returns the number of affected rows.
func (*Executor) ExecuteOne ¶
ExecuteOne executes a query and returns a single result.
type Lexer ¶
type Lexer struct {
// contains filtered or unexported fields
}
Lexer tokenizes a query string.
type OrderClause ¶
type OrderClause struct {
Field string
Direction OrderDirection
}
OrderClause represents an ORDER BY clause.
type OrderDirection ¶
type OrderDirection int
OrderDirection represents the sort direction.
const ( OrderAsc OrderDirection = iota OrderDesc )
func (OrderDirection) String ¶
func (od OrderDirection) String() string
String returns a string representation of the OrderDirection.
type Parameter ¶
type Parameter struct {
Name string
}
Parameter represents a named parameter in a query.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser parses query tokens into a Query AST.
type Position ¶
Position represents a location in the query string.
type Query ¶
type Query struct {
Type QueryType
Entity string
Fields []string // SELECT fields, empty = all
Where *WhereClause
OrderBy []OrderClause
Limit *int
Offset *int
Include []string // Relations to load
GroupBy []string
Having *WhereClause
Updates []UpdateSet // For UPDATE queries
AggField string // Field for aggregate functions (SUM, AVG, etc.)
}
Query represents a parsed query.
func ParseSimple ¶
ParseSimple parses a simple filter expression like "status:active priority:1"
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder provides a fluent interface for building queries.
func (*QueryBuilder) Build ¶
func (qb *QueryBuilder) Build() *Query
Build returns the constructed query.
func (*QueryBuilder) Decrement ¶
func (qb *QueryBuilder) Decrement(field string, value interface{}) *QueryBuilder
Decrement adds a decrement operation.
func (*QueryBuilder) Execute ¶
func (qb *QueryBuilder) Execute(ctx context.Context, exec *Executor) ([]map[string]interface{}, error)
Execute executes the query using the provided executor.
func (*QueryBuilder) ExecuteOne ¶
func (qb *QueryBuilder) ExecuteOne(ctx context.Context, exec *Executor) (map[string]interface{}, error)
ExecuteOne executes the query and returns a single result.
func (*QueryBuilder) Fields ¶
func (qb *QueryBuilder) Fields(fields ...string) *QueryBuilder
Fields specifies the fields to select.
func (*QueryBuilder) Include ¶
func (qb *QueryBuilder) Include(relations ...string) *QueryBuilder
Include adds related entities to load.
func (*QueryBuilder) Increment ¶
func (qb *QueryBuilder) Increment(field string, value interface{}) *QueryBuilder
Increment adds an increment operation.
func (*QueryBuilder) Limit ¶
func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
Limit sets the LIMIT.
func (*QueryBuilder) Offset ¶
func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
Offset sets the OFFSET.
func (*QueryBuilder) OrderBy ¶
func (qb *QueryBuilder) OrderBy(field string, direction OrderDirection) *QueryBuilder
OrderBy adds an ORDER BY clause.
func (*QueryBuilder) Set ¶
func (qb *QueryBuilder) Set(field string, value interface{}) *QueryBuilder
Set adds an update set operation.
func (*QueryBuilder) Where ¶
func (qb *QueryBuilder) Where(field string, op CompareOp, value interface{}) *QueryBuilder
Where adds a WHERE condition.
func (*QueryBuilder) WhereClause ¶
func (qb *QueryBuilder) WhereClause(where *WhereClause) *QueryBuilder
WhereClause sets the entire WHERE clause.
type QueryError ¶
type QueryError struct {
Position Position
Message string
Type ErrorType
Token *Token // The token that caused the error, if applicable
}
QueryError represents a single query error.
func ErrInvalidLimit ¶
func ErrInvalidLimit(value string) *QueryError
ErrInvalidLimit creates an error for invalid LIMIT value.
func ErrInvalidOffset ¶
func ErrInvalidOffset(value string) *QueryError
ErrInvalidOffset creates an error for invalid OFFSET value.
func ErrInvalidOperator ¶
func ErrInvalidOperator(tok Token) *QueryError
ErrInvalidOperator creates an error for an invalid operator.
func ErrInvalidQueryType ¶
func ErrInvalidQueryType(queryType QueryType) *QueryError
ErrInvalidQueryType creates an error for invalid query type.
func ErrInvalidValue ¶
func ErrInvalidValue(tok Token, expected string) *QueryError
ErrInvalidValue creates an error for an invalid value.
func ErrMissingEntity ¶
func ErrMissingEntity() *QueryError
ErrMissingEntity creates an error for missing entity in query.
func ErrNestedGroupDepth ¶
func ErrNestedGroupDepth(maxDepth int) *QueryError
ErrNestedGroupDepth creates an error for too deeply nested groups.
func ErrTypeMismatch ¶
func ErrTypeMismatch(field, expectedType, gotType string) *QueryError
ErrTypeMismatch creates an error for type mismatch.
func ErrUnexpectedEOF ¶
func ErrUnexpectedEOF(expected string) *QueryError
ErrUnexpectedEOF creates an error for unexpected end of input.
func ErrUnexpectedToken ¶
func ErrUnexpectedToken(tok Token, expected string) *QueryError
ErrUnexpectedToken creates an error for an unexpected token.
func ErrUnknownEntity ¶
func ErrUnknownEntity(name string) *QueryError
ErrUnknownEntity creates an error for an unknown entity.
func ErrUnknownField ¶
func ErrUnknownField(entity, field string) *QueryError
ErrUnknownField creates an error for an unknown field.
func NewCompilerError ¶
func NewCompilerError(message string) *QueryError
NewCompilerError creates a compiler error.
func NewCompilerErrorWithPosition ¶
func NewCompilerErrorWithPosition(pos Position, message string) *QueryError
NewCompilerErrorWithPosition creates a compiler error with position.
func NewExecutionError ¶
func NewExecutionError(message string) *QueryError
NewExecutionError creates an execution error.
func NewLexerError ¶
func NewLexerError(pos Position, message string) *QueryError
NewLexerError creates a lexer error.
func NewLexerErrorWithToken ¶
func NewLexerErrorWithToken(tok Token, message string) *QueryError
NewLexerErrorWithToken creates a lexer error with the associated token.
func NewParserError ¶
func NewParserError(pos Position, message string) *QueryError
NewParserError creates a parser error.
func NewParserErrorWithToken ¶
func NewParserErrorWithToken(tok Token, message string) *QueryError
NewParserErrorWithToken creates a parser error with the associated token.
func NewSemanticError ¶
func NewSemanticError(pos Position, message string) *QueryError
NewSemanticError creates a semantic error.
func (*QueryError) Error ¶
func (e *QueryError) Error() string
Error implements the error interface.
func (*QueryError) Unwrap ¶
func (e *QueryError) Unwrap() error
Unwrap returns nil as QueryError doesn't wrap other errors.
type QueryErrors ¶
type QueryErrors struct {
Errors []*QueryError
}
QueryErrors aggregates multiple query errors.
func NewQueryErrors ¶
func NewQueryErrors() *QueryErrors
NewQueryErrors creates a new empty QueryErrors.
func (*QueryErrors) Add ¶
func (qe *QueryErrors) Add(err *QueryError)
Add appends a query error to the collection.
func (*QueryErrors) Error ¶
func (qe *QueryErrors) Error() string
Error implements the error interface, formatting all errors.
func (*QueryErrors) HasErrors ¶
func (qe *QueryErrors) HasErrors() bool
HasErrors returns true if there are any query errors.
func (*QueryErrors) Unwrap ¶
func (qe *QueryErrors) Unwrap() []error
Unwrap returns the underlying errors for errors.Is/As compatibility.
type RelationMeta ¶
type RelationMeta struct {
Entity string
Type RelationType
ForeignKey string
JoinTable string // For many-to-many
JoinColumn string
InverseColumn string
}
RelationMeta describes a relation to another entity.
type RelationType ¶
type RelationType int
RelationType represents the type of relation.
const ( RelationHasOne RelationType = iota RelationHasMany RelationBelongsTo RelationManyToMany )
func (RelationType) String ¶
func (rt RelationType) String() string
String returns a string representation of the RelationType.
type SQLCompiler ¶
type SQLCompiler struct {
// contains filtered or unexported fields
}
SQLCompiler compiles Query AST to parameterized SQL.
func NewSQLCompiler ¶
func NewSQLCompiler(entities map[string]*EntityMeta) *SQLCompiler
NewSQLCompiler creates a new SQL compiler with entity metadata.
func (*SQLCompiler) Compile ¶
func (c *SQLCompiler) Compile(q *Query) (*CompiledQuery, error)
Compile compiles a Query to SQL.
type TokenType ¶
type TokenType int
TokenType represents the type of a lexical token.
const ( TokenEOF TokenType = iota TokenError // Keywords TokenSelect TokenCount TokenSum TokenAvg TokenMin TokenMax TokenUpdate TokenDelete TokenFrom TokenWhere TokenAnd TokenOr TokenNot TokenIn TokenIs TokenNull TokenOrder TokenBy TokenAsc TokenDesc TokenLimit TokenOffset TokenWith TokenInclude TokenSet TokenTrue TokenFalse TokenLike TokenILike TokenBetween TokenHaving TokenGroup TokenGroupBy // Operators TokenEquals TokenNotEquals TokenGreater TokenGreaterEq TokenLess TokenLessEq TokenContains TokenStartsWith TokenEndsWith // Literals TokenIdent TokenString TokenNumber TokenParam // Punctuation TokenLParen TokenRParen TokenLBracket TokenRBracket TokenComma TokenDot TokenColon TokenTilde )
type WhereClause ¶
type WhereClause struct {
Conditions []Condition
Operator LogicalOp
Groups []*WhereClause // Nested groups for complex expressions
}
WhereClause represents a WHERE clause with conditions.