engine

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: AGPL-3.0 Imports: 39 Imported by: 0

Documentation

Overview

Audit logging hook for Execute (see internal/storage/audit.go for the hash-chained log itself).

Execute receives a parsed Statement, not the original SQL text — there's no reliable way to reconstruct exact SQL from an AST (the trigger-body bug fixed earlier this session, where a from-scratch AST-to-SQL printer silently produced non-executable text, is exactly why this doesn't attempt that). Callers that already have the original text (cmd/server, internal/driver — both parse from a string themselves) can attach it via WithAuditText so the audit trail records the real query; callers that only ever construct/receive an AST get a best-effort "<*engine.Insert>" style fallback identifying the statement kind, which is still enough to see *that* a mutation happened even without the exact text.

Package engine provides SQL parsing, planning, and execution for tinySQL.

This file focuses on the query compilation cache:

  • What: A lightweight in-memory LRU cache that stores parsed/compiled representations of SQL statements (CompiledQuery).
  • How: Queries are keyed by their exact SQL string. The cache holds a Statement AST plus metadata (ParsedAt) and returns it to callers to avoid re-parsing. LRU eviction using container/list keeps the cache within a fixed size with O(1) eviction.
  • Why: Parsing is comparatively expensive and often repeated in loops or hot paths. Caching reduces parse overhead, improves latency, and keeps the execution path predictable while remaining simple and thread-safe.

Package engine implements the tinySQL execution engine.

What: This module evaluates parsed SQL statements (AST) against the storage layer and produces ResultSets. It covers DDL/DML/SELECT, joins, grouping, aggregates, expression evaluation, simple functions (JSON_*, DATEDIFF, etc.), and a minimal tri-state boolean logic (true/false/unknown).

How: The executor converts tables to row maps with both qualified and unqualified column keys, applies WHERE/GROUP/HAVING/ORDER/LIMIT/OFFSET, and optionally combines results with UNION/EXCEPT/INTERSECT. Expression evaluation is recursive over a small algebra of literals, variables, unary/ binary ops, IS NULL, and function calls. Aggregate evaluation runs per- group with reusable helpers shared with the scalar evaluator.

Why: Keeping execution self-contained and data-structure driven (Row maps and simple slices) makes the engine easy to reason about and to extend with new functions, operators, and clauses without introducing heavy planners.

Package engine provides helper functions for the YAML, URL, HASH, BITMAP, and BLOB extra column types added to tinySQL.

Note: MD5 and SHA1 are provided for compatibility and checksum use cases only. They are cryptographically broken and must NOT be used for security-sensitive operations (passwords, signatures, etc.). Prefer SHA256 or SHA512 instead.

Package engine: foreign key referential action enforcement.

Before this, FOREIGN KEY constraints only protected the child side: an INSERT/UPDATE into a table with a FOREIGN KEY column checked that the referenced row existed (validateRowConstraints in exec.go), but nothing checked the parent side — DELETE (or UPDATE of a referenced column) on the parent table silently orphaned any referencing child rows, regardless of an ON DELETE/ON UPDATE clause (which didn't even parse). This file adds that missing half: RESTRICT (the default when no clause is given, matching how tinySQL checks constraints immediately rather than deferring them), CASCADE, and SET NULL.

Package engine provides a lightweight Full-Text Search (FTS) engine inspired by SQLite FTS5.

Design:

  • CREATE VIRTUAL TABLE t USING fts(col1, col2) creates a regular tinySQL table with FTS indexing enabled.
  • INSERT/UPDATE/DELETE automatically maintain an in-memory inverted index.
  • FTS_MATCH(text, query) – boolean match check with phrase/boolean query support
  • FTS_RANK(text, query) – BM25-like relevance score
  • FTS_SNIPPET(text, query [, before, after, ellipsis, max_tokens]) – highlighted snippet
  • FTS_HIGHLIGHT(text, query [, before, after]) – full-text highlighting alias
  • BM25(text, query) – alias for FTS_RANK
  • FTS_SEARCH table-valued function for corpus-level k-nearest search

Query syntax supported by FTS_MATCH / FTS_RANK:

word         – single term
"phrase"     – exact phrase (consecutive tokens)
word*        – prefix wildcard
A AND B      – both terms must match
A OR B       – either term must match
NOT A        – term must not match
A B          – implicit AND (same as A AND B)

Package engine contains the SQL lexer used by the parser.

What: A minimal, whitespace- and comment-aware tokenizer that recognizes identifiers, keywords, numeric and string literals, and symbols. How: Single-pass rune-based scanner supporting -- and /* */ comments, uppercasing keywords, and preserving identifier case. Keywords are a fixed allow-list tailored to tinySQL features. Why: A compact lexer reduces parser complexity and keeps error messages local and actionable without external dependencies.

Package engine provides a hand-written SQL parser for tinySQL.

What: It parses a practical subset of SQL into an AST (statements and expressions) used by the execution engine. Supported features include DDL, DML, SELECT with JOIN/GROUP/HAVING/ORDER/LIMIT/OFFSET, and set ops. How: A straightforward recursive-descent parser over a small token stream from the lexer. It favors clarity and precise error messages. Ident-like parsing accepts keywords as identifiers to keep the grammar practical for common column names. Why: A small, readable parser is easy to extend and reason about, enabling rapid iteration on language features without a complex generator toolchain.

RBAC enforcement for Execute (see internal/storage/rbac.go for the underlying users/roles/grants model).

The acting user travels via context.Context (WithUser/UserFromContext), not as an Execute parameter — adding a parameter would break every existing caller's signature (internal/driver, cmd/server, every test in this module). A context key is the idiomatic Go way to thread an optional, cross-cutting value like this without an API break, and it composes with context.WithTimeout/WithCancel that callers already use.

Enforcement itself is opt-in at the database level: checkPermission is a no-op unless db.IsRBACEnabled() is true (which itself is false until the first CreateUser call), so every existing embedder and test that never creates a user sees zero behavior change. Call db.SetRBACEnabled(false) to force enforcement off even after users/roles have been created — for a setup that provisions accounts ahead of time but isn't ready to enforce yet, or a dev/test environment that wants audit-log attribution via WithUser without access checks getting in the way.

Parser and AST for RBAC DDL: CREATE/DROP/ALTER USER, CREATE/DROP ROLE, and GRANT/REVOKE. Enforcement lives in rbac.go; the underlying users/roles/grants model is internal/storage/rbac.go.

Grammar (see parser_test-style examples in rbac_parser_test.go):

CREATE USER name WITH PASSWORD 'secret' [ROLE role1 [, role2 ...]]
DROP USER name
ALTER USER name ENABLE | DISABLE
ALTER USER name WITH PASSWORD 'newsecret'
CREATE ROLE name
DROP ROLE name
GRANT perm [, perm ...] ON [schema.]table TO ROLE role
GRANT perm [, perm ...] ON * TO ROLE role
REVOKE perm [, perm ...] ON [schema.]table FROM ROLE role
GRANT ROLE role TO USER user
REVOKE ROLE role FROM USER user

Package engine provides plaintext/fulltext utility functions and table-valued functions for RAG (Retrieval-Augmented Generation) workloads.

TEXT_CHUNKS(text, chunk_size [, overlap [, unit]])

Splits text into overlapping chunks suitable for embedding and retrieval.

Parameters:
  text       – the source document text
  chunk_size – maximum tokens (words) per chunk (default 100)
  overlap    – number of tokens shared between adjacent chunks (default 20)
  unit       – 'words' (default) or 'chars'

Returns columns: chunk_index INT, chunk_text TEXT, start_pos INT, end_pos INT

TEXT_WORD_COUNT(text) – count of whitespace-separated words TEXT_CHAR_COUNT(text) – count of Unicode characters TEXT_TRUNCATE(text, max_len [, ellipsis]) – truncate to max_len chars

Package engine implements trigger execution for tinySQL. Triggers fire BEFORE or AFTER INSERT, UPDATE, and DELETE operations. NEW refers to the new row (INSERT/UPDATE), OLD refers to the old row (UPDATE/DELETE).

Package engine provides vector/embedding functions for tinySQL, enabling RAG (Retrieval-Augmented Generation) workloads and vector similarity search.

Supported functions:

VEC_FROM_JSON(json_string)           – parse "[1.0, 2.0, 3.0]" → []float64
VEC_TO_JSON(vector)                  – serialize vector → JSON string
RECENCY_SCORE(ts, half_life_days [, now]) – exponential decay score in [0, 1]
RAG_HYBRID_SCORE(similarity, ts, half_life_days [, sim_weight, now]) – blend of
                                                                 normalized similarity and recency
RAG_RANK_SCORE(similarity, ts, half_life_days, quality [, sim_w, recency_w, quality_w, now])
                                      – weighted RAG score over similarity, freshness and quality
VEC_DIM(vector)                      – number of dimensions
VEC_NORM(vector)                     – L2 (Euclidean) norm
VEC_NORMALIZE(vector)                – unit-length normalised copy
VEC_ADD(v1, v2)                      – element-wise addition
VEC_SUB(v1, v2)                      – element-wise subtraction
VEC_MUL(v1, v2)                      – element-wise multiplication (Hadamard)
VEC_SCALE(vector, scalar)            – scalar multiplication
VEC_DOT(v1, v2)                      – dot / inner product
VEC_COSINE_SIMILARITY(v1, v2)        – cosine similarity  ∈ [-1, 1]
VEC_COSINE_DISTANCE(v1, v2)          – 1 - cosine similarity ∈ [0, 2]
VEC_L2_DISTANCE(v1, v2)              – Euclidean distance
VEC_MANHATTAN_DISTANCE(v1, v2)       – L1 / Manhattan distance
VEC_DISTANCE(v1, v2 [, metric])      – generic distance, metric = 'cosine' | 'l2' | 'manhattan' | 'dot'
VEC_SLICE(vector, start, length)     – sub-vector extraction
VEC_CONCAT(v1, v2)                   – vector concatenation
VEC_QUANTIZE(vector, bits)           – quantize to reduced precision (8/16 bit simulation)
VEC_RANDOM(dimensions [, seed])      – random unit vector of given dimension

Package engine provides a VEC_SEARCH table-valued function for k-nearest neighbor (k-NN) vector search — the core building block for Retrieval-Augmented Generation (RAG) workloads in tinySQL.

Usage:

SELECT * FROM VEC_SEARCH('table_name', 'vector_column', query_vector, k [, 'metric' [, 'index']])

Parameters:

table_name     – name of the table containing vectors
vector_column  – column storing VECTOR ([]float64) values
query_vector   – the search vector ([]float64 or JSON string)
k              – number of nearest neighbors to return
metric         – optional distance metric: 'cosine' (default), 'l2', 'manhattan', 'dot'
index          – optional index mode: 'flat' (default exact), 'ivf', 'hnsw'

Returns all original columns plus:

_vec_distance  – computed distance from query_vector
_vec_rank      – 1-based rank (1 = closest)

The results are returned in ascending order of distance (closest first).

VEC_WARM — eager warm-up for vector search structures.

Usage:

SELECT * FROM VEC_WARM('table_name', 'vector_column' [, 'metric' [, 'index']])

Prebuilds the vector column cache (and, for cosine, the L2 norms) plus the requested ANN index (ivf or hnsw). This shifts the one-time O(n log n) index-build cost from the first query to an explicit warm-up step — e.g. right after a nightly bulk load — so serving queries never pay it.

Returns a single row describing what was warmed:

table_name, column_name, metric, index_mode, row_count, vector_count, dims

Automatic AdvancedWAL logging for INSERT/UPDATE/DELETE.

Before this, tinySQL had two WAL implementations — the basic WALManager (whole-table snapshot diffing, used by internal/driver's explicit BeginTx/Commit) and AdvancedWAL (row-level, LSN-based, with real REDO/recovery) — but nothing in the engine's own INSERT/UPDATE/DELETE path ever called AdvancedWAL's LogInsert/LogUpdate/LogDelete. A caller using ModeAdvancedWAL and writing through the ordinary tinysql.Execute API (not through internal/driver's transaction machinery) got no durability logging at all — a silent gap, since nothing errored or warned about it.

walAuto wraps each mutating statement in its own implicit, autocommitted WAL transaction (LogBegin before the row loop, LogCommit after) and logs every row change as it happens. It is a complete no-op — zero calls, zero overhead beyond one nil check — when no AdvancedWAL is attached, which remains the default for ModeMemory/ModeDisk/ModeJSON/ModeHybrid/ModeWAL.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterExternalTableFunc added in v0.8.0

func RegisterExternalTableFunc(fn ExternalTableFunc)

RegisterExternalTableFunc wraps fn in an adapter and registers it so that it can be used in SQL FROM clauses and JOINs.

func RegisterStoredProcedure added in v0.14.0

func RegisterStoredProcedure(name string, fn StoredProcedureFunc) error

RegisterStoredProcedure registers an in-memory stored procedure by name. Names are case-insensitive. Re-registering the same name replaces the previous handler. Procedures are process-local and are not persisted.

func RegisterTableFunc added in v0.5.1

func RegisterTableFunc(fn TableFunction)

RegisterTableFunc registers a table-valued function globally

func UnregisterStoredProcedure added in v0.14.0

func UnregisterStoredProcedure(name string) bool

UnregisterStoredProcedure removes a procedure. It returns true when a registered procedure existed.

func UserFromContext added in v0.12.0

func UserFromContext(ctx context.Context) (string, bool)

UserFromContext returns the username set by WithUser, if any.

func Version added in v0.5.4

func Version() string

Version returns the tinySQL version string. It attempts to read the module version from debug.ReadBuildInfo and falls back to "dev".

func WithAuditText added in v0.13.0

func WithAuditText(ctx context.Context, sqlText string) context.Context

WithAuditText attaches the original SQL text of the statement about to be executed, for the audit log to record verbatim. Compose with WithUser: engine.WithAuditText(engine.WithUser(ctx, user), sqlText).

func WithUser added in v0.12.0

func WithUser(ctx context.Context, username string) context.Context

WithUser returns a context carrying the acting username for RBAC checks. Pass it to Execute via the context.Context parameter, e.g. Execute(engine.WithUser(ctx, "alice"), db, tenant, stmt).

Types

type AlterJob added in v0.5.1

type AlterJob struct {
	Name   string
	Enable *bool // nil means no-op
}

AlterJob represents ALTER JOB ... ENABLE/DISABLE

type AlterMaterializedViewToView added in v0.11.0

type AlterMaterializedViewToView struct {
	Name string
}

AlterMaterializedViewToView represents ALTER MATERIALIZED VIEW ... TO VIEW.

type AlterTable added in v0.3.0

type AlterTable struct {
	Table     string
	AddColumn *storage.Column // For ADD COLUMN

}

AlterTable represents an ALTER TABLE statement.

type AlterUser added in v0.12.0

type AlterUser struct {
	Name        string
	SetEnabled  *bool
	NewPassword *string
}

AlterUser represents ALTER USER name {ENABLE|DISABLE|WITH PASSWORD '...'}. Exactly one of SetEnabled/NewPassword is set per statement (the grammar only allows one clause); both nil would be a no-op, which the parser never produces.

type AlterViewMaterialize added in v0.11.0

type AlterViewMaterialize struct {
	Name               string
	WithData           bool
	StaleAfterMs       int64
	RefreshEveryMs     int64
	DailyAt            string
	Timezone           string
	InvalidateOnChange bool
}

AlterViewMaterialize represents ALTER VIEW ... MATERIALIZE.

type BetweenExpr added in v0.12.0

type BetweenExpr struct {
	Expr   Expr
	Lo     Expr
	Hi     Expr
	Negate bool
}

BetweenExpr represents "expr [NOT] BETWEEN lo AND hi" when expr is not a plain column or literal. Unlike the desugared form (expr >= lo AND expr <= hi) it evaluates expr exactly once, which is faster for expensive expressions and correct for non-deterministic ones (e.g. RANDOM() BETWEEN 1 AND 10).

type Binary

type Binary struct {
	Op          string
	Left, Right Expr
}

Binary represents binary operators (+,-,*,/, comparisons, AND/OR).

type CSVTableFunc added in v0.5.1

type CSVTableFunc struct{}

CSVTableFunc implements table_from_csv(source, options)

func (*CSVTableFunc) Execute added in v0.5.1

func (f *CSVTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*CSVTableFunc) Name added in v0.5.1

func (f *CSVTableFunc) Name() string

func (*CSVTableFunc) ValidateArgs added in v0.5.1

func (f *CSVTableFunc) ValidateArgs(args []Expr) error

type CTE

type CTE struct {
	Name   string
	Select *Select
	// Recursive indicates this CTE was declared under WITH RECURSIVE
	Recursive bool
}

CTE represents a Common Table Expression (WITH clause)

type CallProcedure added in v0.14.0

type CallProcedure struct {
	Name string
	Args []Expr
}

CallProcedure represents CALL proc_name(arg1, arg2, ...).

type CaseExpr added in v0.3.0

type CaseExpr struct {
	Operand Expr
	Whens   []CaseWhen
	Else    Expr
}

CaseExpr represents a CASE ... WHEN ... THEN ... [ELSE ...] END expression.

type CaseWhen added in v0.3.0

type CaseWhen struct {
	When Expr
	Then Expr
}

CaseWhen pairs WHEN condition and THEN result expressions.

type ColumnIndex added in v0.3.1

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

ColumnIndex provides fast column lookups for better performance

func NewColumnIndex added in v0.3.1

func NewColumnIndex(rows []Row, columns []string) *ColumnIndex

NewColumnIndex creates an index for the given rows and columns

func (*ColumnIndex) GetRows added in v0.3.1

func (idx *ColumnIndex) GetRows(indices []int) []Row

GetRows returns the rows at the given indices

func (*ColumnIndex) Lookup added in v0.3.1

func (idx *ColumnIndex) Lookup(column string, value any) []int

Lookup returns row indices that match the given column value

type CompiledQuery

type CompiledQuery struct {
	SQL       string
	Statement Statement
	ParsedAt  time.Time
}

CompiledQuery represents a pre-parsed and cached SQL query.

func (*CompiledQuery) Execute

func (cq *CompiledQuery) Execute(ctx context.Context, db *storage.DB, tenant string) (*ResultSet, error)

Execute runs a compiled query against the database.

type CreateIndex added in v0.3.0

type CreateIndex struct {
	Name        string
	Table       string
	Columns     []string
	Unique      bool
	IfNotExists bool
}

CreateIndex represents a CREATE INDEX statement.

type CreateJob added in v0.5.1

type CreateJob struct {
	Name         string
	ScheduleType string // CRON, INTERVAL, ONCE
	CronExpr     string
	IntervalMs   int64
	RunAt        *time.Time
	Timezone     string
	MaxRuntimeMs int64
	NoOverlap    bool
	CatchUp      bool
	Enabled      bool
	SQLText      string
}

CreateJob represents a CREATE JOB statement.

type CreateMaterializedView added in v0.11.0

type CreateMaterializedView struct {
	Name               string
	Select             *Select
	SQLText            string
	IfNotExists        bool
	OrReplace          bool
	WithData           bool
	StaleAfterMs       int64
	RefreshEveryMs     int64
	DailyAt            string
	Timezone           string
	InvalidateOnChange bool
}

CreateMaterializedView represents a CREATE MATERIALIZED VIEW statement.

type CreateRole added in v0.12.0

type CreateRole struct {
	Name string
}

CreateRole represents CREATE ROLE name.

type CreateTable

type CreateTable struct {
	Name         string
	Cols         []storage.Column
	IsTemp       bool
	AsSelect     *Select
	IfNotExists  bool     // IF NOT EXISTS clause
	VirtualTable bool     // CREATE VIRTUAL TABLE
	Using        string   // e.g. "fts"
	FTSColumns   []string // columns passed to fts(...)
}

CreateTable represents a CREATE TABLE statement.

type CreateTrigger added in v0.9.0

type CreateTrigger struct {
	Name        string
	Timing      string // "BEFORE", "AFTER", "INSTEAD OF"
	Event       string // "INSERT", "UPDATE", "DELETE"
	Table       string
	ForEachRow  bool
	WhenExpr    Expr        // optional WHEN condition
	Body        []Statement // trigger body statements, parsed once to validate syntax at CREATE TRIGGER time
	BodyText    string      // verbatim source text of the body (between BEGIN and END), stored for re-parsing on each fire
	IfNotExists bool
}

CreateTrigger represents a CREATE TRIGGER statement.

type CreateUser added in v0.12.0

type CreateUser struct {
	Name     string
	Password string
	Roles    []string
}

CreateUser represents CREATE USER name WITH PASSWORD '...' [ROLE ...].

type CreateView added in v0.3.0

type CreateView struct {
	Name        string
	Select      *Select
	SQLText     string
	IfNotExists bool
	OrReplace   bool
}

CreateView represents a CREATE VIEW statement.

type Delete

type Delete struct {
	Table     string
	Where     Expr
	Returning []SelectItem
}

Delete represents a DELETE statement.

type DropIndex added in v0.3.0

type DropIndex struct {
	Name     string
	Table    string // Optional: some DBs require table name
	IfExists bool
}

DropIndex represents a DROP INDEX statement.

type DropJob added in v0.5.1

type DropJob struct {
	Name string
}

DropJob represents DROP JOB <name>

type DropMaterializedView added in v0.11.0

type DropMaterializedView struct {
	Name     string
	IfExists bool
}

DropMaterializedView represents a DROP MATERIALIZED VIEW statement.

type DropRole added in v0.12.0

type DropRole struct {
	Name string
}

DropRole represents DROP ROLE name.

type DropTable

type DropTable struct {
	Name     string
	IfExists bool // IF EXISTS clause
}

DropTable represents a DROP TABLE statement.

type DropTrigger added in v0.9.0

type DropTrigger struct {
	Name     string
	IfExists bool
}

DropTrigger represents a DROP TRIGGER statement.

type DropUser added in v0.12.0

type DropUser struct {
	Name string
}

DropUser represents DROP USER name.

type DropView added in v0.3.0

type DropView struct {
	Name     string
	IfExists bool
}

DropView represents a DROP VIEW statement.

type ExecEnv

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

type ExistsExpr added in v0.10.0

type ExistsExpr struct {
	Select *Select
}

ExistsExpr represents "EXISTS (subquery)".

type Explain added in v0.11.0

type Explain struct {
	Statement Statement
}

Explain represents an EXPLAIN statement around another statement.

type Expr

type Expr interface{}

type ExpressionCache added in v0.3.1

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

ExpressionCache provides caching for frequently evaluated expressions

func NewExpressionCache added in v0.3.1

func NewExpressionCache() *ExpressionCache

NewExpressionCache creates a new expression cache

func (*ExpressionCache) Clear added in v0.3.1

func (ec *ExpressionCache) Clear()

Clear empties the cache

func (*ExpressionCache) Get added in v0.3.1

func (ec *ExpressionCache) Get(exprStr string, row Row) (any, bool)

Get retrieves a cached result for the given expression and row

func (*ExpressionCache) Set added in v0.3.1

func (ec *ExpressionCache) Set(exprStr string, row Row, result any)

Set stores a result in the cache

func (*ExpressionCache) Stats added in v0.3.1

func (ec *ExpressionCache) Stats() (hits, misses int, hitRate float64)

Stats returns cache performance statistics

type ExternalTableFunc added in v0.8.0

type ExternalTableFunc interface {
	Name() string
	ValidateArgCount(n int) error
	Execute(ctx context.Context, args []any) (*ResultSet, error)
}

ExternalTableFunc is the public interface for domain-specific table-valued functions (e.g. FSQL filesystem functions). Its Execute method receives pre-evaluated argument values rather than raw AST nodes.

type FTSSearchTableFunc added in v0.11.0

type FTSSearchTableFunc struct{}

FTSSearchTableFunc implements FTS_SEARCH(table, query, k [, columns...]). Usage:

SELECT * FROM FTS_SEARCH('table_name', 'query text', 10)

Returns all columns from the source table plus:

_fts_score – BM25 relevance score
_fts_rank  – 1-based rank (1 = most relevant)

func (*FTSSearchTableFunc) Execute added in v0.11.0

func (f *FTSSearchTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*FTSSearchTableFunc) Name added in v0.11.0

func (f *FTSSearchTableFunc) Name() string

func (*FTSSearchTableFunc) ValidateArgs added in v0.11.0

func (f *FTSSearchTableFunc) ValidateArgs(args []Expr) error

type FromItem

type FromItem struct {
	Table     string         // Tabellenname (wenn echte Tabelle)
	Alias     string         // Alias für Tabelle oder Subselect
	Subquery  *Select        // Falls abgeleitete Tabelle: das Select-Statement
	TableFunc *TableFuncCall // Wenn FROM eine table-valued function ist
}

FromItem kann eine echte Tabelle oder ein Subselect (Derived Table) sein.

type FuncCall

type FuncCall struct {
	Name     string
	Args     []Expr
	Star     bool
	Distinct bool        // For COUNT(DISTINCT col)
	Over     *OverClause // For window functions
}

FuncCall represents a function call, optionally with a star (COUNT(*)).

type GrantPrivilege added in v0.12.0

type GrantPrivilege struct {
	Permissions []storage.Permission
	Schema      string // "*" for "every schema"
	Table       string // "*" for "every table"
	RoleName    string
}

GrantPrivilege represents GRANT perm[,...] ON target TO ROLE role.

type GrantRoleStmt added in v0.12.0

type GrantRoleStmt struct {
	RoleName string
	UserName string
}

GrantRoleStmt represents GRANT ROLE role TO USER user.

type HashJoinOptimizer added in v0.3.1

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

HashJoinOptimizer provides hash-based join optimizations

func (*HashJoinOptimizer) ProcessOptimizedJoin added in v0.3.1

func (h *HashJoinOptimizer) ProcessOptimizedJoin(leftRows, rightRows []Row, condition Expr, joinType OptimizedJoinType) ([]Row, error)

OptimizedJoinProcessor handles optimized join operations

type InExpr added in v0.3.0

type InExpr struct {
	Expr   Expr
	Values []Expr
	Negate bool // For NOT IN
}

InExpr represents "expr IN (val1, val2, ...)"

type Insert

type Insert struct {
	Table     string
	Cols      []string
	Rows      [][]Expr
	Returning []SelectItem
}

Insert represents an INSERT statement.

type IsNull

type IsNull struct {
	Expr   Expr
	Negate bool
}

IsNull represents IS [NOT] NULL predicate.

type JSONLinesTableFunc added in v0.5.1

type JSONLinesTableFunc struct{}

JSONLinesTableFunc implements table_from_json_lines(source)

func (*JSONLinesTableFunc) Execute added in v0.5.1

func (f *JSONLinesTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*JSONLinesTableFunc) Name added in v0.5.1

func (f *JSONLinesTableFunc) Name() string

func (*JSONLinesTableFunc) ValidateArgs added in v0.5.1

func (f *JSONLinesTableFunc) ValidateArgs(args []Expr) error

type JSONTableFunc added in v0.5.1

type JSONTableFunc struct{}

JSONTableFunc implements table_from_json(source, spec)

func (*JSONTableFunc) Execute added in v0.5.1

func (f *JSONTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*JSONTableFunc) Name added in v0.5.1

func (f *JSONTableFunc) Name() string

func (*JSONTableFunc) ValidateArgs added in v0.5.1

func (f *JSONTableFunc) ValidateArgs(args []Expr) error

type JoinClause

type JoinClause struct {
	Type  JoinType
	Right FromItem
	On    Expr
}

JoinClause holds a JOIN type with the right side and join condition.

type JoinCondition added in v0.3.1

type JoinCondition struct {
	LeftColumn  string
	RightColumn string
	Operator    string
	IsEquiJoin  bool
}

JoinCondition represents a parsed join condition

type JoinType

type JoinType int
const (
	// JoinInner represents INNER JOIN.
	JoinInner JoinType = iota
	// JoinLeft represents LEFT (OUTER) JOIN.
	JoinLeft
	// JoinRight represents RIGHT (OUTER) JOIN.
	JoinRight
	// JoinFull represents FULL (OUTER) JOIN.
	JoinFull
	// JoinCross represents CROSS JOIN (unconditional Cartesian product; no ON clause).
	JoinCross
)

func (JoinType) String added in v0.12.0

func (t JoinType) String() string

String returns the SQL keyword form of the join type, e.g. "LEFT JOIN".

type LikeExpr added in v0.3.0

type LikeExpr struct {
	Expr            Expr
	Pattern         Expr
	Escape          Expr // Optional ESCAPE character
	Negate          bool // For NOT LIKE / NOT ILIKE / NOT GLOB
	CaseInsensitive bool // For ILIKE
	GlobStyle       bool // For GLOB (* and ? wildcards instead of % and _)
}

LikeExpr represents "expr LIKE pattern [ESCAPE char]"

type Literal

type Literal struct{ Val any }

Literal holds a constant value (number, string, bool, NULL).

type OptimizedJoinType added in v0.3.1

type OptimizedJoinType int

OptimizedJoinType defines the type of join operation for optimizations

const (
	OptimizedJoinTypeInner OptimizedJoinType = iota
	OptimizedJoinTypeLeft
	OptimizedJoinTypeRight
)

type OrderItem

type OrderItem struct {
	Col  string
	Desc bool
}

OrderItem specifies ordering column and direction.

type OverClause added in v0.5.0

type OverClause struct {
	PartitionBy []Expr       // PARTITION BY expressions
	OrderBy     []OrderItem  // ORDER BY items
	Frame       *WindowFrame // ROWS/RANGE frame specification
}

OverClause represents the OVER clause for window functions.

type Parser

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

Parser holds the lexer and current/peek tokens for recursive-descent parsing.

func NewParser

func NewParser(sql string) *Parser

NewParser creates a new SQL parser for the provided input string.

func (*Parser) ParseStatement

func (p *Parser) ParseStatement() (Statement, error)

ParseStatement parses a single SQL statement into an AST.

type PivotClause added in v0.12.0

type PivotClause struct {
	AggFunc   string // e.g. SUM, COUNT, AVG, MIN, MAX
	ValueExpr Expr
	PivotCol  string
	Values    []PivotValue
}

PivotClause represents "PIVOT (agg(value_expr) FOR pivot_col IN (v1 [AS a1], v2 [AS a2], ...))". It reshapes the WHERE-filtered row set: each distinct value listed in the IN-list becomes its own output column (named by its alias, or by the value's literal text if no alias is given), holding agg(value_expr) over the rows where pivot_col equals that value. Every other selected column acts as an implicit GROUP BY key, matching standard SQL PIVOT semantics.

Scope: a single aggregate function and a static (literal) value list — no dynamic pivot driven by a subquery. This covers the overwhelmingly common case (a known, fixed set of categories to spread into columns) without the complexity of a fully dynamic PIVOT.

type PivotValue added in v0.12.0

type PivotValue struct {
	Expr  Expr
	Alias string // output column name; defaults to the value's text form
}

PivotValue is one entry in a PIVOT's IN (...) list.

type Pragma added in v0.11.0

type Pragma struct {
	Name   string
	Schema string
	Args   []string
	Value  *string
}

Pragma represents a SQLite-compatible PRAGMA statement.

type ProcedureContext added in v0.14.0

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

ProcedureContext is passed to registered in-memory stored procedures. It lets procedures run SQL against the same DB/tenant without re-entering Execute's content lock.

func (ProcedureContext) Context added in v0.14.0

func (pc ProcedureContext) Context() context.Context

Context returns the statement context passed to Execute.

func (ProcedureContext) Execute added in v0.14.0

func (pc ProcedureContext) Execute(stmt Statement) (*ResultSet, error)

Execute executes a parsed statement inside the current CALL.

func (ProcedureContext) ExecuteSQL added in v0.14.0

func (pc ProcedureContext) ExecuteSQL(sql string) (*ResultSet, error)

ExecuteSQL parses and executes sql inside the current CALL. It reuses the current statement lock, so procedures can compose ordinary tinySQL statements without deadlocking.

func (ProcedureContext) Tenant added in v0.14.0

func (pc ProcedureContext) Tenant() string

Tenant returns the tenant/schema namespace used by the CALL statement.

type QueryCache

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

QueryCache manages compiled queries with LRU eviction.

func NewQueryCache

func NewQueryCache(maxSize int) *QueryCache

NewQueryCache creates a new query cache with the specified maximum size.

func (*QueryCache) Clear

func (qc *QueryCache) Clear()

Clear removes all cached queries.

func (*QueryCache) Compile

func (qc *QueryCache) Compile(sql string) (*CompiledQuery, error)

Compile parses and caches a SQL query for reuse.

func (*QueryCache) MustCompile

func (qc *QueryCache) MustCompile(sql string) *CompiledQuery

MustCompile is like Compile but panics on error (similar to regexp.MustCompile).

func (*QueryCache) Size

func (qc *QueryCache) Size() int

Size returns the number of cached queries.

func (*QueryCache) Stats

func (qc *QueryCache) Stats() map[string]interface{}

Stats returns cache statistics.

type RAGContextFromTableFunc added in v0.11.0

type RAGContextFromTableFunc struct{}

RAG_CONTEXT_FROM expands multiple retrieval hits into neighboring chunks.

Usage:

WITH topk AS (...)
SELECT * FROM RAG_CONTEXT_FROM('chunks', 'doc_id', 'chunk_index',
                               'topk', 'doc_id', 'chunk_index', 1 [, 1])

func (*RAGContextFromTableFunc) Execute added in v0.11.0

func (f *RAGContextFromTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*RAGContextFromTableFunc) Name added in v0.11.0

func (f *RAGContextFromTableFunc) Name() string

func (*RAGContextFromTableFunc) ValidateArgs added in v0.11.0

func (f *RAGContextFromTableFunc) ValidateArgs(args []Expr) error

type RAGContextTableFunc added in v0.11.0

type RAGContextTableFunc struct{}

RAG_CONTEXT loads neighboring chunks for a single retrieved chunk.

Usage:

SELECT * FROM RAG_CONTEXT('chunks', 'doc_id', 'chunk_index', 'doc-1', 7, 2 [, 1])

Arguments:

source table/CTE, document id column, chunk index column,
document id, center chunk index, chunks before, optional chunks after.

func (*RAGContextTableFunc) Execute added in v0.11.0

func (f *RAGContextTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*RAGContextTableFunc) Name added in v0.11.0

func (f *RAGContextTableFunc) Name() string

func (*RAGContextTableFunc) ValidateArgs added in v0.11.0

func (f *RAGContextTableFunc) ValidateArgs(args []Expr) error

type RefreshMaterializedView added in v0.11.0

type RefreshMaterializedView struct {
	Name         string
	Concurrently bool
}

RefreshMaterializedView represents REFRESH MATERIALIZED VIEW.

type RegexpExpr added in v0.10.0

type RegexpExpr struct {
	Expr      Expr
	Pattern   Expr
	Negate    bool // For NOT REGEXP / NOT RLIKE / NOT SIMILAR TO
	SimilarTo bool // Pattern uses SQL SIMILAR TO syntax (% and _ wildcards)
}

RegexpExpr represents "expr REGEXP/RLIKE pattern" and "expr SIMILAR TO pattern".

type ResultSet

type ResultSet struct {
	Cols []string
	Rows []Row
}

ResultSet holds the column order and the returned rows from a query. Cols preserve the display order; Rows store values in a case-insensitive map.

func Execute

func Execute(ctx context.Context, db *storage.DB, tenant string, stmt Statement) (rs *ResultSet, err error)

Execute runs a parsed SQL statement against the given storage DB and tenant. It dispatches to handlers per statement kind and returns a ResultSet for SELECT (nil for DDL/DML). The context is checked at safe points to support cancellation.

Concurrency: storage.DB's own mutex only protects the tenant->table map structure, not the contents of a *storage.Table (Rows/Cols/Version) once a caller holds one — INSERT/UPDATE/DELETE mutate Table.Rows with no lock of their own, so two goroutines calling Execute concurrently on the same DB would otherwise race on that slice (a real data race, not just stale reads: concurrent unsynchronized slice append + range is undefined behavior in Go). Execute closes that gap with a single coarse read/write lock around the whole statement: SELECT/EXPLAIN/PRAGMA take a shared read lock (so concurrent reads still run in parallel with each other), everything else takes an exclusive write lock. This is coarser than per-table locking — a write to table A blocks a concurrent read of unrelated table B — but it is correct and simple to audit, which matters more for a safety fix than maximum parallelism.

type RevokePrivilege added in v0.12.0

type RevokePrivilege struct {
	Permissions []storage.Permission
	Schema      string
	Table       string
	RoleName    string
}

RevokePrivilege represents REVOKE perm[,...] ON target FROM ROLE role.

type RevokeRoleStmt added in v0.12.0

type RevokeRoleStmt struct {
	RoleName string
	UserName string
}

RevokeRoleStmt represents REVOKE ROLE role FROM USER user.

type Row

type Row map[string]any

Row represents a single result row mapped by lower-cased column name. Keys include both qualified (table.column) and unqualified (column) names to simplify expression evaluation and projection.

type Select

type Select struct {
	Distinct   bool
	DistinctOn []Expr
	From       FromItem
	Joins      []JoinClause
	Projs      []SelectItem
	Where      Expr
	Pivot      *PivotClause
	GroupBy    []Expr
	Having     Expr
	OrderBy    []OrderItem
	Limit      *int
	Offset     *int
	Union      *UnionClause // For UNION operations
	CTEs       []CTE        // Common Table Expressions
}

Select represents a SELECT query and its clauses.

type SelectItem

type SelectItem struct {
	Expr  Expr
	Alias string
	Star  bool
}

SelectItem represents a projection item, optionally with alias or *.

type Statement

type Statement interface{}

Statement is the root interface for all parsed SQL statements.

type StoredProcedureFunc added in v0.14.0

type StoredProcedureFunc func(ctx ProcedureContext, args []any) (*ResultSet, error)

StoredProcedureFunc is the Go handler signature for in-memory stored procedures registered with RegisterStoredProcedure.

type StoredProcedureInfo added in v0.14.0

type StoredProcedureInfo struct {
	Name         string
	RegisteredAt time.Time
}

StoredProcedureInfo describes one registered procedure.

func ListStoredProcedures added in v0.14.0

func ListStoredProcedures() []StoredProcedureInfo

ListStoredProcedures returns registered in-memory procedures sorted by name.

type SubqueryExpr added in v0.3.0

type SubqueryExpr struct {
	Select *Select
}

SubqueryExpr wraps a SELECT used as an expression (scalar subquery).

type TableFuncCall added in v0.5.1

type TableFuncCall struct {
	Name  string
	Args  []Expr
	Alias string // Optional table alias
}

TableFuncCall represents a table function call in a FROM clause

type TableFunction added in v0.5.1

type TableFunction interface {
	// Name returns the function name (e.g., "table_from_json")
	Name() string

	// Execute evaluates the TVF and returns a result set (columns + rows)
	Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

	// ValidateArgs checks if the provided arguments are valid
	ValidateArgs(args []Expr) error
}

TableFunction represents a table-valued function that can be used in FROM clauses Example: SELECT * FROM table_from_json(http('...'), spec)

func GetTableFunc added in v0.5.1

func GetTableFunc(name string) (TableFunction, bool)

GetTableFunc retrieves a registered table function by name

type TextChunksTableFunc added in v0.11.0

type TextChunksTableFunc struct{}

TextChunksTableFunc implements TEXT_CHUNKS(text, chunk_size [, overlap [, unit]]).

func (*TextChunksTableFunc) Execute added in v0.11.0

func (f *TextChunksTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*TextChunksTableFunc) Name added in v0.11.0

func (f *TextChunksTableFunc) Name() string

func (*TextChunksTableFunc) ValidateArgs added in v0.11.0

func (f *TextChunksTableFunc) ValidateArgs(args []Expr) error

type Unary

type Unary struct {
	Op   string
	Expr Expr
}

Unary represents unary operators like +, -, NOT.

type UnionClause

type UnionClause struct {
	Type  UnionType
	Right *Select
	Next  *UnionClause // For chaining multiple UNIONs
}

UnionClause represents a set operation chaining RIGHT select with current one.

type UnionType

type UnionType int
const (
	// UnionDistinct corresponds to UNION (distinct).
	UnionDistinct UnionType = iota
	// UnionAll corresponds to UNION ALL.
	UnionAll
	// Except corresponds to EXCEPT.
	Except
	// Intersect corresponds to INTERSECT.
	Intersect
)

func (UnionType) String added in v0.12.0

func (t UnionType) String() string

String returns the SQL keyword form of the union type, e.g. "UNION ALL".

type Update

type Update struct {
	Table     string
	Sets      map[string]Expr
	Where     Expr
	Returning []SelectItem
}

Update represents an UPDATE statement.

type VarRef

type VarRef struct {
	Name  string
	Lower string
}

VarRef refers to a column (qualified or unqualified) in expressions.

type VecSearchTableFunc added in v0.5.4

type VecSearchTableFunc struct{}

VecSearchTableFunc implements the VEC_SEARCH table-valued function.

func (*VecSearchTableFunc) Execute added in v0.5.4

func (f *VecSearchTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*VecSearchTableFunc) Name added in v0.5.4

func (f *VecSearchTableFunc) Name() string

func (*VecSearchTableFunc) ValidateArgs added in v0.5.4

func (f *VecSearchTableFunc) ValidateArgs(args []Expr) error

type VecTopKTableFunc added in v0.5.4

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

VecTopKTableFunc implements VEC_TOP_K — alias/alternative API for k-NN search. Usage: SELECT * FROM VEC_TOP_K('table', 'column', query_vec, k [, 'metric'])

func (*VecTopKTableFunc) Execute added in v0.5.4

func (f *VecTopKTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*VecTopKTableFunc) Name added in v0.5.4

func (f *VecTopKTableFunc) Name() string

func (*VecTopKTableFunc) ValidateArgs added in v0.5.4

func (f *VecTopKTableFunc) ValidateArgs(args []Expr) error

type VecWarmTableFunc added in v0.11.0

type VecWarmTableFunc struct{}

VecWarmTableFunc implements the VEC_WARM table-valued function.

func (*VecWarmTableFunc) Execute added in v0.11.0

func (f *VecWarmTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*VecWarmTableFunc) Name added in v0.11.0

func (f *VecWarmTableFunc) Name() string

func (*VecWarmTableFunc) ValidateArgs added in v0.11.0

func (f *VecWarmTableFunc) ValidateArgs(args []Expr) error

type WindowFrame added in v0.5.0

type WindowFrame struct {
	Mode       string // "ROWS" or "RANGE"
	StartType  string // "UNBOUNDED", "CURRENT", or "OFFSET"
	StartValue int    // Offset value for PRECEDING/FOLLOWING
	EndType    string // "UNBOUNDED", "CURRENT", or "OFFSET"
	EndValue   int    // Offset value for PRECEDING/FOLLOWING
}

WindowFrame represents ROWS/RANGE BETWEEN frame specification.

type XMLTableFunc added in v0.5.1

type XMLTableFunc struct{}

XMLTableFunc implements table_from_xml(source, record_name)

func (*XMLTableFunc) Execute added in v0.5.1

func (f *XMLTableFunc) Execute(ctx context.Context, args []Expr, env ExecEnv, row Row) (*ResultSet, error)

func (*XMLTableFunc) Name added in v0.5.1

func (f *XMLTableFunc) Name() string

func (*XMLTableFunc) ValidateArgs added in v0.5.1

func (f *XMLTableFunc) ValidateArgs(args []Expr) error

Jump to

Keyboard shortcuts

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