query

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package query provides a query language parser and SQL compiler for CodeAI.

Index

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 @>
)

func (CompareOp) String

func (op CompareOp) String() string

String returns a string representation of the CompareOp.

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
)

func (ErrorType) String

func (et ErrorType) String() string

String returns the string representation of ErrorType.

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) Execute

func (e *Executor) Execute(ctx context.Context, q *Query) ([]map[string]interface{}, error)

Execute executes a query and returns the results as maps.

func (*Executor) ExecuteAggregate

func (e *Executor) ExecuteAggregate(ctx context.Context, q *Query) (interface{}, error)

ExecuteAggregate executes an aggregate query (SUM, AVG, MIN, MAX) and returns the result.

func (*Executor) ExecuteCount

func (e *Executor) ExecuteCount(ctx context.Context, q *Query) (int64, error)

ExecuteCount executes a COUNT query and returns the count.

func (*Executor) ExecuteDelete

func (e *Executor) ExecuteDelete(ctx context.Context, q *Query) (int64, error)

ExecuteDelete executes a DELETE query and returns the number of affected rows.

func (*Executor) ExecuteOne

func (e *Executor) ExecuteOne(ctx context.Context, q *Query) (map[string]interface{}, error)

ExecuteOne executes a query and returns a single result.

func (*Executor) ExecuteString

func (e *Executor) ExecuteString(ctx context.Context, queryStr string) ([]map[string]interface{}, error)

ExecuteString parses and executes a query string.

func (*Executor) ExecuteUpdate

func (e *Executor) ExecuteUpdate(ctx context.Context, q *Query) (int64, error)

ExecuteUpdate executes an UPDATE query and returns the number of affected rows.

type Lexer

type Lexer struct {
	// contains filtered or unexported fields
}

Lexer tokenizes a query string.

func NewLexer

func NewLexer(input string) *Lexer

NewLexer creates a new Lexer for the given input.

func (*Lexer) Tokenize

func (l *Lexer) Tokenize() ([]Token, error)

Tokenize scans the input and returns all tokens.

type LogicalOp

type LogicalOp int

LogicalOp represents a logical operator (AND/OR).

const (
	LogicalAnd LogicalOp = iota
	LogicalOr
)

func (LogicalOp) String

func (op LogicalOp) String() string

String returns a string representation of the LogicalOp.

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.

func NewParser

func NewParser(tokens []Token) *Parser

NewParser creates a new parser for the given tokens.

func (*Parser) Parse

func (p *Parser) Parse() (*Query, error)

Parse parses the tokens and returns a Query AST.

type Position

type Position struct {
	Offset int
	Line   int
	Column int
}

Position represents a location in the query string.

func (Position) IsValid

func (p Position) IsValid() bool

IsValid returns true if the position is valid.

func (Position) String

func (p Position) String() string

String returns a human-readable position 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 Parse

func Parse(input string) (*Query, error)

Parse parses a query string and returns the Query AST.

func ParseSimple

func ParseSimple(input string) (*Query, error)

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 Count

func Count(entity string) *QueryBuilder

Count creates a new COUNT query builder.

func Delete

func Delete(entity string) *QueryBuilder

Delete creates a new DELETE query builder.

func Select

func Select(entity string) *QueryBuilder

Select creates a new SELECT query builder.

func Update

func Update(entity string) *QueryBuilder

Update creates a new UPDATE query builder.

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 QueryType

type QueryType int

QueryType represents the type of query operation.

const (
	QuerySelect QueryType = iota
	QueryCount
	QuerySum
	QueryAvg
	QueryMin
	QueryMax
	QueryUpdate
	QueryDelete
)

func (QueryType) String

func (qt QueryType) String() string

String returns a string representation of the QueryType.

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 Token

type Token struct {
	Type   TokenType
	Value  string
	Pos    int
	Line   int
	Column int
}

Token represents a lexical token.

func (Token) String

func (t Token) String() string

String returns a string representation of the token.

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 UpdateOp

type UpdateOp int

UpdateOp represents the type of update operation.

const (
	UpdateSetValue UpdateOp = iota
	UpdateIncrement
	UpdateDecrement
	UpdateAppend
	UpdateRemove
)

func (UpdateOp) String

func (op UpdateOp) String() string

String returns a string representation of the UpdateOp.

type UpdateSet

type UpdateSet struct {
	Field string
	Value interface{}
	Op    UpdateOp
}

UpdateSet represents a field update in an UPDATE query.

type WhereClause

type WhereClause struct {
	Conditions []Condition
	Operator   LogicalOp
	Groups     []*WhereClause // Nested groups for complex expressions
}

WhereClause represents a WHERE clause with conditions.

Jump to

Keyboard shortcuts

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