Documentation
¶
Overview ¶
Package sqlite provides a pure-Go SQLite implementation with zero external dependencies. It implements the SQLite file format directly, supporting reading and writing .db files compatible with the standard SQLite library, and provides a database/sql driver.
Index ¶
- Constants
- Variables
- func CloseDB(db *sql.DB)
- func ComputePayloadSizes(payloadLen, usableSize int, isLeaf bool) (localSize, overflowSize int)
- func DecodeVarint(data []byte) (int64, int, error)
- func DecodeVarintRaw(data []byte) (uint64, int, error)
- func EncodeVarint(v int64) []byte
- func EncodeVarintInto(v uint64, buf []byte, off int) int
- func EncodeVarintRaw(v uint64) []byte
- func ExprString(expr Expr) string
- func MaxOverflowPayload(usableSize int) int
- func Open() (*sql.DB, error)
- func OpenFile(path string) (*sql.DB, error)
- func OpenWithData(data []byte) (*sql.DB, error)
- func PutRecord(r *Record)
- func ReadCellPointers(data []byte, offset int, count int) []uint16
- func ReadOverflowPage(data []byte, usableSize int) (nextPage uint32, payload []byte, err error)
- func ReadRecordIntoRecord(data []byte, rec *Record, buf []Value) error
- func VarintSize(v uint64) int
- func WriteCell(c *Cell) []byte
- func WriteCellPointers(ptrs []uint16) []byte
- func WriteFreelistTrunk(trunk *FreelistTrunk, usableSize int) []byte
- func WriteHeader(h *DatabaseHeader) []byte
- func WriteInteriorTableCell(c *Cell) []byte
- func WriteLeafTableCell(c *Cell) []byte
- func WriteOverflowPage(nextPage uint32, payload []byte, usableSize int) []byte
- func WritePageHeader(h *PageHeader) []byte
- func WritePageHeaderTo(data []byte, h PageHeader)
- func WriteRecord(r *Record) []byte
- type AlterAddColumnStmt
- type AlterRenameColumnStmt
- type AlterRenameTableStmt
- type BTree
- type BTreeCursor
- type BTreeInterface
- type BeginStmt
- type BetweenExpr
- type BinaryExpr
- type BinaryOp
- type CaseExpr
- type CaseWhen
- type CastExpr
- type Cell
- type ColumnAffinity
- type ColumnConstraint
- type ColumnDef
- type ColumnDefAST
- type ColumnRef
- type CommitStmt
- type CompareResult
- type CompoundSelect
- type ConstraintType
- type CreateIndexStmt
- type CreateTableStmt
- type CreateViewStmt
- type CursorInterface
- type DataType
- type DatabaseHeader
- type DeleteStmt
- type DiskFile
- type DropIndexStmt
- type DropTableStmt
- type DropViewStmt
- type Engine
- func (e *Engine) Close() error
- func (e *Engine) Execute(sql string, params ...Value) (*Result, error)
- func (e *Engine) ExecuteAll(sql string, params ...Value) ([]*Result, error)
- func (e *Engine) ExecuteStatement(stmt Statement, params ...Value) (*Result, error)
- func (e *Engine) ExecuteWithCache(sql string, params ...Value) (*Result, error)
- func (e *Engine) LoadSchema() error
- func (e *Engine) SaveSchema() error
- func (e *Engine) Schema() *Schema
- type Expr
- type ExprEval
- type FileBackend
- type ForeignKeyInfo
- type FreelistTrunk
- type FromClause
- type FunctionCall
- type InExpr
- type IndexInfo
- type IndexedColumn
- type InsertStmt
- type IsNullExpr
- type JoinClause
- type JoinType
- type Lexer
- type LikeExpr
- type LikeOp
- type LiteralExpr
- type MemFile
- type OrderItem
- type PageHeader
- type Pager
- func (p *Pager) AllocatePage() (int, error)
- func (p *Pager) BeginTxn()
- func (p *Pager) Close() error
- func (p *Pager) CommitTxn()
- func (p *Pager) Flush() error
- func (p *Pager) GetHeader() *DatabaseHeader
- func (p *Pager) GetPageBuffer() []byte
- func (p *Pager) GetPageData(num int) ([]byte, error)
- func (p *Pager) GetPageDataMutable(num int) ([]byte, error)
- func (p *Pager) GetPageDataReadOnly(num int) ([]byte, error)
- func (p *Pager) GetPageSize() int
- func (p *Pager) GetSchemaPage() int
- func (p *Pager) InitNew() error
- func (p *Pager) LoadHeader() error
- func (p *Pager) PageCount() int
- func (p *Pager) PageHeaderOffset(pageNum int) int
- func (p *Pager) PutPageBuffer(b []byte)
- func (p *Pager) Restore(data []byte) error
- func (p *Pager) RollbackTxn() error
- func (p *Pager) SetPageData(num int, data []byte) error
- func (p *Pager) SetSchemaPage(page int)
- func (p *Pager) Snapshot() []byte
- func (p *Pager) UpdateHeader(h *DatabaseHeader) error
- type PagerInterface
- type ParamExpr
- type ParenExpr
- type ParseError
- type Parser
- type PragmaStmt
- type Record
- type ReindexStmt
- type Result
- type RollbackStmt
- type RowIDExpr
- type Schema
- func (s *Schema) AddIndex(info *IndexInfo)
- func (s *Schema) AddTable(info *TableInfo)
- func (s *Schema) Copy() *Schema
- func (s *Schema) DropIndex(name string) bool
- func (s *Schema) DropTable(name string) bool
- func (s *Schema) GetIndex(name string) (*IndexInfo, bool)
- func (s *Schema) GetTable(name string) (*TableInfo, bool)
- func (s *Schema) IndexNames() []string
- func (s *Schema) IndexesForTable(tableName string) []*IndexInfo
- func (s *Schema) RenameTable(oldName, newName string) bool
- func (s *Schema) TableNames() []string
- type SelectColumn
- type SelectStmt
- type SetClause
- type SetOp
- type StarColumn
- type Statement
- type SubqueryExpr
- type TableInfo
- type TableRef
- type Token
- type TokenType
- type UnaryExpr
- type UnaryOp
- type UpdateStmt
- type VacuumStmt
- type Value
- type ViewInfo
Constants ¶
const OverflowPageHeaderSize = 4
OverflowPageHeaderSize is the size of an overflow page header (4 bytes for the next overflow page pointer).
Variables ¶
var ( ErrBadMagic = errors.New("sqlite: bad magic header") ErrHeaderTooSmall = errors.New("sqlite: header data too small") ErrBadPageSize = errors.New("sqlite: invalid page size") ErrBadPayloadFrac = errors.New("sqlite: invalid payload fraction") ErrBadPageType = errors.New("sqlite: invalid page type") ErrPageHeaderTooSmall = errors.New("sqlite: page header data too small") ErrCellTooSmall = errors.New("sqlite: cell data too small") ErrRecordTooSmall = errors.New("sqlite: record data too small") ErrBadSerialType = errors.New("sqlite: invalid serial type") ErrTruncatedRecord = errors.New("sqlite: truncated record body") ErrNoColumns = errors.New("sqlite: record has no columns") )
var KeywordMap = map[string]TokenType{ "SELECT": TokenSELECT, "FROM": TokenFROM, "WHERE": TokenWHERE, "INSERT": TokenINSERT, "INTO": TokenINTO, "VALUES": TokenVALUES, "UPDATE": TokenUPDATE, "SET": TokenSET, "DELETE": TokenDELETE, "CREATE": TokenCREATE, "TABLE": TokenTABLE, "DROP": TokenDROP, "INDEX": TokenINDEX, "IF": TokenIF, "NOT": TokenNOT, "NULL": TokenNULL, "EXISTS": TokenEXISTS, "PRIMARY": TokenPRIMARY, "KEY": TokenKEY, "UNIQUE": TokenUNIQUE, "DEFAULT": TokenDEFAULT, "CHECK": TokenCHECK, "FOREIGN": TokenFOREIGN, "REFERENCES": TokenREFERENCES, "BEGIN": TokenBEGIN, "COMMIT": TokenCOMMIT, "ROLLBACK": TokenROLLBACK, "TRANSACTION": TokenTRANSACTION, "AND": TokenAND, "OR": TokenOR, "ORDER": TokenORDER, "BY": TokenBY, "ASC": TokenASC, "DESC": TokenDESC, "LIMIT": TokenLIMIT, "OFFSET": TokenOFFSET, "AS": TokenAS, "ON": TokenON, "LEFT": TokenLEFT, "RIGHT": TokenRIGHT, "INNER": TokenINNER, "OUTER": TokenOUTER, "JOIN": TokenJOIN, "IN": TokenIN, "IS": TokenIS, "LIKE": TokenLIKE, "GLOB": TokenGLOB, "BETWEEN": TokenBETWEEN, "CASE": TokenCASE, "WHEN": TokenWHEN, "THEN": TokenTHEN, "ELSE": TokenELSE, "END": TokenEND, "CAST": TokenCAST, "COLLATE": TokenCOLLATE, "DISTINCT": TokenDISTINCT, "ALL": TokenALL, "HAVING": TokenHAVING, "GROUP": TokenGROUP, "UNION": TokenUNION, "INTERSECT": TokenINTERSECT, "EXCEPT": TokenEXCEPT, "INTEGER": TokenINTEGER_KW, "TEXT": TokenTEXT_KW, "REAL": TokenREAL_KW, "BLOB": TokenBLOB_KW, "AUTOINCREMENT": TokenAUTOINCREMENT, "ROWID": TokenROWID, "VACUUM": TokenVACUUM, "REINDEX": TokenREINDEX, "ALTER": TokenALTER, "PRAGMA": TokenPRAGMA, "VIEW": TokenVIEW, "ADD": TokenADD, "COLUMN": TokenCOLUMN, "RENAME": TokenRENAME, "TO": TokenTO, }
KeywordMap maps keyword strings (uppercase) to their token types.
var NullValue = Value{Type: DataTypeNull}
NullValue is a convenience constant for NULL values.
Functions ¶
func ComputePayloadSizes ¶
ComputePayloadSizes computes how many bytes of a payload fit on the current page (localSize) vs how many must go to overflow pages (overflowSize).
Parameters:
- payloadLen: total payload size in bytes
- usableSize: usable page size (pageSize - reservedSpace)
- isLeaf: true for leaf table B-tree cells, false for interior
For leaf table cells:
maxLocal = usableSize - 35 minLocal = ((usableSize - 12) * 32 / 255) - 23
For interior table cells:
maxLocal = ((usableSize - 12) * 64 / 255) - 23 minLocal = ((usableSize - 12) * 32 / 255) - 23
func DecodeVarint ¶
DecodeVarint decodes a signed SQLite varint (ZigZag encoded) from a byte slice.
func DecodeVarintRaw ¶
DecodeVarintRaw decodes a raw unsigned SQLite varint. SQLite varint format:
- Bytes 1-8: high bit is continuation flag, low 7 bits are data (MSB first)
- Byte 9 (if present): all 8 bits are data
func EncodeVarint ¶
EncodeVarint encodes a signed integer as a SQLite varint (1-9 bytes). Uses ZigZag encoding for signed values.
func EncodeVarintInto ¶
EncodeVarintRaw encodes an unsigned integer as a SQLite varint. The bytes are in MSB-first order with continuation bits on all bytes except the last. EncodeVarintInto writes the varint encoding of v into buf starting at offset. Returns the number of bytes written.
func EncodeVarintRaw ¶
func ExprString ¶
ExprString returns a string representation of an expression.
func MaxOverflowPayload ¶
MaxOverflowPayload returns the maximum payload bytes that fit on a single overflow page.
func OpenWithData ¶
OpenWithData opens a database from existing data bytes (in-memory).
func ReadCellPointers ¶
ReadCellPointers reads the 2-byte cell pointer array from a page. offset is where the cell pointer array starts (after the page header).
func ReadOverflowPage ¶
ReadOverflowPage reads an overflow page, returning the next overflow page number (0 = end of chain) and the payload data.
func ReadRecordIntoRecord ¶
ReadRecordIntoRecord decodes a record into an existing Record struct, avoiding the per-call *Record allocation.
func VarintSize ¶
VarintSize returns the number of bytes needed to encode v as a raw varint.
func WriteCellPointers ¶
WriteCellPointers writes a 2-byte cell pointer array.
func WriteFreelistTrunk ¶
func WriteFreelistTrunk(trunk *FreelistTrunk, usableSize int) []byte
WriteFreelistTrunk serializes a freelist trunk page.
func WriteHeader ¶
func WriteHeader(h *DatabaseHeader) []byte
WriteHeader serializes a DatabaseHeader to exactly 100 bytes.
func WriteInteriorTableCell ¶
WriteInteriorTableCell serializes an interior table cell explicitly.
func WriteLeafTableCell ¶
WriteLeafTableCell serializes a leaf table cell explicitly.
func WriteOverflowPage ¶
WriteOverflowPage serializes an overflow page.
func WritePageHeader ¶
func WritePageHeader(h *PageHeader) []byte
WritePageHeader serializes a PageHeader to its byte representation.
func WritePageHeaderTo ¶
func WritePageHeaderTo(data []byte, h PageHeader)
WritePageHeaderTo writes a page header to raw bytes.
Types ¶
type AlterAddColumnStmt ¶
type AlterAddColumnStmt struct {
Table string
Column ColumnDefAST
}
AlterAddColumnStmt represents ALTER TABLE ... ADD COLUMN ...
type AlterRenameColumnStmt ¶
AlterRenameColumnStmt represents ALTER TABLE ... RENAME COLUMN ... TO ...
type AlterRenameTableStmt ¶
AlterRenameTableStmt represents ALTER TABLE ... RENAME TO ...
type BTree ¶
type BTree struct {
// contains filtered or unexported fields
}
BTree manages a B-tree structure for table data.
func (*BTree) CreateBTree ¶
CreateBTree creates a new B-tree (single leaf page) and returns the root page number.
type BTreeCursor ¶
type BTreeCursor struct {
// contains filtered or unexported fields
}
BTreeCursor iterates over rows in a B-tree in rowid order. Uses lazy page-by-page iteration instead of eager collection.
func (*BTreeCursor) Get ¶
func (c *BTreeCursor) Get() (int64, *Record, error)
Get returns the current rowid and record.
func (*BTreeCursor) Next ¶
func (c *BTreeCursor) Next() bool
Next advances the cursor to the next row.
func (*BTreeCursor) RawRecordData ¶
func (c *BTreeCursor) RawRecordData() []byte
RawRecordData returns the raw record bytes for the current cell, skipping the payload-size and rowid varint prefixes.
func (*BTreeCursor) SeekToRowid ¶
func (c *BTreeCursor) SeekToRowid(target int64) error
Scan returns a cursor for iterating all rows in the B-tree. SeekToRowid positions the cursor at the first row with rowid >= target. This is equivalent to a B-tree seek followed by sequential scan.
type BTreeInterface ¶
type BTreeInterface interface {
CreateBTree() (int, error)
Insert(rootPage int, rowid int64, record *Record) error
Delete(rootPage int, rowid int64) error
Search(rootPage int, rowid int64) (*Record, error)
Scan(rootPage int) (CursorInterface, error)
}
BTreeInterface abstracts B-tree operations.
type BetweenExpr ¶
BetweenExpr represents BETWEEN ... AND ...
func (BetweenExpr) String ¶
func (e BetweenExpr) String() string
type BinaryExpr ¶
BinaryExpr represents a binary operator expression.
func (BinaryExpr) String ¶
func (e BinaryExpr) String() string
type Cell ¶
type Cell struct {
// Interior table cells
LeftChildPage uint32
// Leaf table cells (and index cells)
PayloadSize uint64 // varint: total payload length
RowID uint64 // varint: rowid (leaf table only)
Key uint64 // varint: key for interior table (= rowid)
// Payload data (local portion only; overflow handled externally)
Payload []byte
// Overflow page number (0 = no overflow)
OverflowPage uint32
// Whether this is a leaf cell (has payload + rowid) or interior cell (has left child + key)
IsLeaf bool
}
Cell represents a B-tree cell. It can be either a leaf table cell or an interior table cell (or index cells, which use Payload + optional overflow).
type ColumnAffinity ¶
type ColumnAffinity int
ColumnAffinity represents the type affinity of a column.
const ( AffinityBlob ColumnAffinity = iota // "BLOB" (also called "ANY") AffinityText // "TEXT" AffinityNumeric // "NUMERIC" AffinityInteger // "INTEGER" AffinityReal // "REAL" )
func ResolveColumnAffinity ¶
func ResolveColumnAffinity(typeStr string) ColumnAffinity
ResolveColumnAffinity determines the column affinity from the type string. SQLite rules: https://www.sqlite.org/datatype3.html
type ColumnConstraint ¶
type ColumnConstraint struct {
Type ConstraintType
Name string // Named constraint
Value Expr // For DEFAULT, CHECK
Collate string // For COLLATE
RefTable string // For REFERENCES
RefCols []string // For REFERENCES
}
ColumnConstraint represents a constraint on a column.
type ColumnDef ¶
type ColumnDef struct {
Name string
Type string // Original type string from SQL
Affinity ColumnAffinity
NotNull bool
Default *Value // Default value, nil means no default
IsPrimaryKey bool
IsRowID bool // True if this is the INTEGER PRIMARY KEY (aliased to rowid)
}
ColumnDef defines a column in a table.
type ColumnDefAST ¶
type ColumnDefAST struct {
Name string
Type string
Constraints []ColumnConstraint
}
ColumnDefAST is the AST version of a column definition (before resolution).
type ColumnRef ¶
ColumnRef represents a reference to a column (optionally table-qualified).
func CollectColumnRefs ¶
CollectColumnRefs walks an expression tree and collects all ColumnRef nodes.
type CompareResult ¶
type CompareResult int
CompareResult represents the outcome of comparing two values.
const ( CompareLess CompareResult = -1 CompareEqual CompareResult = 0 CompareGreater CompareResult = 1 )
func CompareValues ¶
func CompareValues(a, b Value) CompareResult
CompareValues compares two Values using SQLite type affinity rules. Returns CompareLess, CompareEqual, or CompareGreater.
type CompoundSelect ¶
type CompoundSelect struct {
Left Statement // SelectStmt or CompoundSelect
Right Statement // SelectStmt or CompoundSelect
Op SetOp
OrderBy []OrderItem
Limit Expr
Offset Expr
}
CompoundSelect represents a compound SELECT (UNION, INTERSECT, EXCEPT).
type ConstraintType ¶
type ConstraintType int
ConstraintType represents the type of column constraint.
const ( ConstraintPrimaryKey ConstraintType = iota ConstraintNotNull ConstraintUnique ConstraintDefault ConstraintCheck ConstraintForeignKey )
type CreateIndexStmt ¶
type CreateIndexStmt struct {
IfNotExists bool
Name string
Table string
Columns []IndexedColumn
Unique bool
Where Expr // Partial index
}
CreateIndexStmt represents a CREATE INDEX statement.
type CreateTableStmt ¶
type CreateTableStmt struct {
IfNotExists bool
Name string
Columns []ColumnDefAST
}
CreateTableStmt represents a CREATE TABLE statement.
type CreateViewStmt ¶
type CursorInterface ¶
type CursorInterface interface {
Next() bool
Get() (int64, *Record, error)
RawRecordData() []byte
Close() error
}
CursorInterface abstracts cursor operations.
type DataType ¶
type DataType int
DataType represents the type of a value stored in a SQLite record.
type DatabaseHeader ¶
type DatabaseHeader struct {
Magic [16]byte
PageSize int // actual page size (65536 is valid, 0 in header means 65536)
FileFormatWriteVersion uint8
FileFormatReadVersion uint8
ReservedSpace uint8
MaxEmbeddedPayloadFrac uint8
MinEmbeddedPayloadFrac uint8
LeafPayloadFrac uint8
FileChangeCounter uint32
DatabaseSizePages uint32
FirstFreelistTrunkPage uint32
TotalFreelistPages uint32
SchemaCookie uint32
SchemaFormatNumber uint32
DefaultPageCacheSize uint32
LargestRootBTreePage uint32
TextEncoding uint32
UserVersion uint32
IncrementalVacuum uint32
ApplicationID uint32
ReservedExpansion [20]byte
VersionValidFor uint32
SQLiteVersionNumber uint32
}
DatabaseHeader represents the 100-byte SQLite database header found at the start of every database file (first page).
func ReadHeader ¶
func ReadHeader(data []byte) (*DatabaseHeader, error)
ReadHeader parses the 100-byte database header from data.
type DeleteStmt ¶
DeleteStmt represents a DELETE statement.
type DiskFile ¶
type DiskFile struct {
// contains filtered or unexported fields
}
DiskFile wraps an *os.File to implement FileBackend.
func OpenDiskFile ¶
OpenDiskFile opens or creates a database file at the given path.
type DropIndexStmt ¶
DropIndexStmt represents a DROP INDEX statement.
type DropTableStmt ¶
DropTableStmt represents a DROP TABLE statement.
type DropViewStmt ¶
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the SQL execution engine. It coordinates between the pager, B-tree, schema, and parser.
func NewEngine ¶
func NewEngine(pager PagerInterface, btree BTreeInterface) *Engine
NewEngine creates a new execution engine.
func (*Engine) ExecuteAll ¶
ExecuteAll parses and executes multiple SQL statements separated by semicolons.
func (*Engine) ExecuteStatement ¶
ExecuteStatement executes a parsed statement.
func (*Engine) ExecuteWithCache ¶
ExecuteWithCache uses the statement cache to avoid re-parsing.
func (*Engine) LoadSchema ¶
LoadSchema loads the schema from the database.
func (*Engine) SaveSchema ¶
SaveSchema persists the current schema to the database.
type Expr ¶
type Expr interface {
// contains filtered or unexported methods
}
Expr represents an expression in a SQL statement.
type ExprEval ¶
type ExprEval struct {
Row []Value
ColumnMap map[string]int // column name -> index
TableMap map[string]map[string]int // table name -> column map
Params []Value // Parameter values (?1, ?2, etc.)
Engine *Engine // for subquery execution
}
ExprEval evaluates an expression against a row of values. The row is a slice of Values corresponding to the columns in the table. columnMap maps column names to their indices in the row.
func NewExprEval ¶
NewExprEval creates a new expression evaluator for a row.
func (*ExprEval) EvalAggregateAware ¶
func (e *ExprEval) EvalAggregateAware(expr Expr, outputCols []outCol, aggRow []Value, groupRows [][]Value) (Value, error)
EvalAggregateAware evaluates an expression, resolving aggregate function calls (COUNT, SUM, AVG, MIN, MAX) by matching them to output columns in the aggregate row. If the aggregate is not in outputCols, it falls back to computing from groupRows.
type FileBackend ¶
type FileBackend interface {
ReadAt(p []byte, off int64) (int, error)
WriteAt(p []byte, off int64) (int, error)
Truncate(size int64) error
Len() int64
Sync() error
Close() error
}
FileBackend is the interface for database storage backends.
type ForeignKeyInfo ¶
type ForeignKeyInfo struct {
FromCol int // Column index in this table
ToTable string // Referenced table name
ToCols []string // Referenced column names
}
ForeignKeyInfo stores metadata about a foreign key relationship.
type FreelistTrunk ¶
FreelistTrunk represents a freelist trunk page.
func ReadFreelistTrunk ¶
func ReadFreelistTrunk(data []byte, usableSize int) (*FreelistTrunk, error)
ReadFreelistTrunk parses a freelist trunk page.
type FromClause ¶
type FromClause struct {
Table *TableRef
Joins []JoinClause
}
FromClause represents the FROM clause of a SELECT.
type FunctionCall ¶
FunctionCall represents a function call.
func (FunctionCall) String ¶
func (e FunctionCall) String() string
type InExpr ¶
type InExpr struct {
Expr Expr
Values []Expr // Explicit list
Select *SelectStmt // Subquery
Negate bool
}
InExpr represents IN (...) or IN (SELECT ...).
type IndexInfo ¶
type IndexInfo struct {
Name string
TableName string
RootPage int
Columns []string
Unique bool
Where string // Partial index WHERE clause
SQL string // Original CREATE INDEX statement
}
IndexInfo stores metadata about an index.
type IndexedColumn ¶
IndexedColumn represents a column in a CREATE INDEX.
type InsertStmt ¶
type InsertStmt struct {
Table TableRef
Columns []string // Column names, empty means all columns in order
Values [][]Expr // Multiple rows of values
Select *SelectStmt // INSERT ... SELECT ...
}
InsertStmt represents an INSERT statement.
type IsNullExpr ¶
IsNullExpr represents IS NULL / IS NOT NULL.
func (IsNullExpr) String ¶
func (e IsNullExpr) String() string
type JoinClause ¶
JoinClause represents a JOIN.
type Lexer ¶
type Lexer struct {
// contains filtered or unexported fields
}
Lexer tokenizes a SQL input string.
type LiteralExpr ¶
type LiteralExpr struct {
Type DataType
IntVal int64
FloatVal float64
TextVal string
BlobVal []byte
}
LiteralExpr represents a literal value (integer, float, string, NULL, blob).
func (LiteralExpr) String ¶
func (e LiteralExpr) String() string
type MemFile ¶
type MemFile struct {
// contains filtered or unexported fields
}
MemFile is an in-memory byte buffer that simulates a file.
type PageHeader ¶
type PageHeader struct {
PageType byte
FirstFreeblock uint16
CellCount uint16
ContentOffset uint16
FragmentedBytes uint8
RightMostPtr uint32 // Only valid for interior pages (0x02, 0x05)
}
PageHeader represents the header of a B-tree page. For leaf table pages (0x0d) and leaf index pages (0x0a) the header is 8 bytes. For interior table pages (0x05) and interior index pages (0x02) the header is 12 bytes.
func ReadPageHeader ¶
func ReadPageHeader(data []byte, isFirst bool) (*PageHeader, error)
ReadPageHeader parses a B-tree page header from data. isFirst indicates this is page 1 (which has the 100-byte DB header before the B-tree header).
func ReadPageHeaderFrom ¶
func ReadPageHeaderFrom(data []byte) PageHeader
ReadPageHeaderFrom reads a page header from raw bytes.
func (*PageHeader) HeaderSize ¶
func (h *PageHeader) HeaderSize() int
HeaderSize returns the size of the serialized page header in bytes.
type Pager ¶
type Pager struct {
// contains filtered or unexported fields
}
Pager manages pages in a database file.
func NewPager ¶
func NewPager(file FileBackend, pageSize int) (*Pager, error)
NewPager creates a new Pager.
func (*Pager) AllocatePage ¶
AllocatePage allocates a new page and returns its page number (1-indexed).
func (*Pager) CommitTxn ¶
func (p *Pager) CommitTxn()
CommitTxn finishes a COW transaction, discarding saved originals.
func (*Pager) GetHeader ¶
func (p *Pager) GetHeader() *DatabaseHeader
GetHeader returns the database header. GetHeader returns the database header, reading from page 1 if needed.
func (*Pager) GetPageBuffer ¶
GetPageBuffer returns a zeroed page-sized buffer from the pool.
func (*Pager) GetPageData ¶
GetPageData returns a copy of the page data for the given page number.
func (*Pager) GetPageDataMutable ¶
SetPageData sets the page data for the given page number. GetPageDataMutable returns a direct reference to the page buffer for in-place modification. The caller MUST NOT hold the reference after calling any other pager methods. The page is automatically marked dirty.
func (*Pager) GetPageDataReadOnly ¶
GetPageDataReadOnly returns the page data without copying. Caller must not modify the returned slice.
func (*Pager) GetSchemaPage ¶
func (*Pager) LoadHeader ¶
LoadHeader reads the header from disk and returns an error on failure.
func (*Pager) PageHeaderOffset ¶
PageHeaderOffset returns the offset of the page header within the page data.
func (*Pager) PutPageBuffer ¶
PutPageBuffer returns a buffer to the pool.
func (*Pager) RollbackTxn ¶
RollbackTxn restores only the pages that were modified during the transaction.
func (*Pager) SetSchemaPage ¶
func (*Pager) Snapshot ¶
Snapshot returns a byte snapshot of all pager state for transaction rollback.
func (*Pager) UpdateHeader ¶
func (p *Pager) UpdateHeader(h *DatabaseHeader) error
UpdateHeader writes the current header to page 1.
type PagerInterface ¶
type PagerInterface interface {
GetPageSize() int
PageCount() int
AllocatePage() (int, error)
GetPageData(num int) ([]byte, error)
GetPageDataMutable(num int) ([]byte, error)
SetPageData(num int, data []byte) error
Flush() error
Close() error
Snapshot() []byte
Restore([]byte) error
GetSchemaPage() int
SetSchemaPage(page int)
BeginTxn()
CommitTxn()
RollbackTxn() error
}
PagerInterface abstracts pager operations the engine needs.
type ParamExpr ¶
type ParamExpr struct {
Name string // empty for positional (?)
Index int // 1-based position for positional params
}
ParamExpr represents a parameter placeholder (? or $name).
type ParenExpr ¶
type ParenExpr struct {
Expr Expr
}
ParenExpr represents a parenthesized expression.
type ParseError ¶
ParseError represents a parse error.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser parses SQL statements into AST nodes.
type PragmaStmt ¶
PragmaStmt represents a PRAGMA statement.
type Record ¶
type Record struct {
Columns []Value
}
Record represents a SQLite record (the payload of a leaf table cell or index cell). It consists of a header (serial types for each column) followed by the body (the actual column values).
func ReadRecord ¶
ReadRecord parses a record from payload bytes.
type ReindexStmt ¶
type ReindexStmt struct {
TableName string // empty for all tables
}
type RollbackStmt ¶
type RollbackStmt struct{}
RollbackStmt represents a ROLLBACK [TRANSACTION] statement.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema represents the database schema (metadata tables).
func (*Schema) IndexNames ¶
IndexNames returns all index names.
func (*Schema) IndexesForTable ¶
IndexesForTable returns all indexes for a given table.
func (*Schema) RenameTable ¶
func (*Schema) TableNames ¶
TableNames returns all table names.
type SelectColumn ¶
SelectColumn represents a column (or expression) in a SELECT list.
type SelectStmt ¶
type SelectStmt struct {
Distinct bool
Columns []SelectColumn // nil means SELECT *
From *FromClause
Where Expr
GroupBy []Expr
Having Expr
OrderBy []OrderItem
Limit Expr
Offset Expr
}
SelectStmt represents a SELECT statement.
type StarColumn ¶
type StarColumn struct{}
StarColumn is a sentinel Expr meaning "all columns" (SELECT *).
func (StarColumn) String ¶
func (e StarColumn) String() string
type Statement ¶
type Statement interface {
// contains filtered or unexported methods
}
Statement represents a parsed SQL statement.
type SubqueryExpr ¶
type SubqueryExpr struct {
Select *SelectStmt
}
SubqueryExpr represents a scalar subquery used as an expression: (SELECT ...)
type TableInfo ¶
type TableInfo struct {
Name string
RootPage int
Columns []ColumnDef
PrimaryKey int // Column index of INTEGER PRIMARY KEY, -1 if none
SQL string // Original CREATE TABLE statement
AutoInc int64 // Next autoincrement value, 0 if not autoincrement
ForeignKeys []ForeignKeyInfo
}
TableInfo stores metadata about a table.
func BuildTableInfo ¶
func BuildTableInfo(stmt *CreateTableStmt, rootPage int) *TableInfo
BuildTableInfo creates a TableInfo from a parsed CREATE TABLE statement.
func (*TableInfo) ColumnByName ¶
ColumnByName returns the ColumnDef for a named column.
func (*TableInfo) ColumnIndex ¶
ColumnIndex returns the index of a column in a table, or -1.
func (*TableInfo) HasRowIDAlias ¶
HasRowIDAlias returns true if this table has an INTEGER PRIMARY KEY that aliases to the rowid.
func (*TableInfo) NextAutoIncrement ¶
NextAutoIncrement returns the next autoincrement value.
func (*TableInfo) RowIDAliasColumn ¶
RowIDAliasColumn returns the column name that aliases to rowid, or "".
func (*TableInfo) SetAutoIncrement ¶
SetAutoIncrement ensures AutoInc is at least v.
type Token ¶
type Token struct {
Type TokenType
Value string // Raw text of the token
Pos int // Byte offset in the input
Line int // Line number (1-based)
Col int // Column number (1-based)
}
Token represents a lexical token in a SQL statement.
type TokenType ¶
type TokenType int
TokenType represents the type of a SQL token.
const ( // Special tokens TokenEOF TokenType = iota TokenError // Lexer error // Literals TokenInteger // 123, 0x1F TokenFloat // 3.14, 1.0e10 TokenString // 'hello', 'it”s' TokenBlob // X'0123AB' // Identifiers TokenIdent // unquoted identifier TokenQuotedID // "quoted identifier" // Operators TokenPlus // + TokenMinus // - TokenStar // * TokenSlash // / TokenPercent // % TokenEqual // = TokenDoubleEqual // == (treated as =) TokenNotEqual // != or <> TokenLess // < TokenLessEq // <= TokenGreater // > TokenGreaterEq // >= TokenAnd // AND keyword (but lexed as keyword) TokenOr // OR keyword (but lexed as keyword) TokenNot // NOT keyword TokenConcat // || // Punctuation TokenLParen // ( TokenRParen // ) TokenComma // , TokenDot // . TokenSemicolon // ; TokenTilde // ~ (bitwise NOT) // Keywords (a selection — we'll lex these as identifiers and check in parser) // We keep keyword tokens for better error messages TokenSELECT TokenFROM TokenWHERE TokenINSERT TokenINTO TokenVALUES TokenUPDATE TokenSET TokenDELETE TokenCREATE TokenTABLE TokenDROP TokenINDEX TokenIF TokenNOT TokenNULL TokenEXISTS TokenPRIMARY TokenKEY TokenUNIQUE TokenDEFAULT TokenCHECK TokenFOREIGN TokenREFERENCES TokenBEGIN TokenCOMMIT TokenROLLBACK TokenTRANSACTION TokenAND TokenOR TokenORDER TokenBY TokenASC TokenDESC TokenLIMIT TokenOFFSET TokenAS TokenON TokenLEFT TokenRIGHT TokenINNER TokenOUTER TokenJOIN TokenIN TokenIS TokenLIKE TokenGLOB TokenBETWEEN TokenCASE TokenWHEN TokenTHEN TokenELSE TokenEND TokenCAST TokenCOLLATE TokenDISTINCT TokenALL TokenHAVING TokenGROUP TokenUNION TokenINTERSECT TokenEXCEPT TokenINTEGER_KW TokenTEXT_KW TokenREAL_KW TokenBLOB_KW TokenAUTOINCREMENT TokenROWID TokenVACUUM TokenREINDEX TokenALTER TokenPRAGMA TokenVIEW TokenADD TokenCOLUMN TokenRENAME TokenTO TokenQuestion // ? parameter placeholder )
type UpdateStmt ¶
UpdateStmt represents an UPDATE statement.
type VacuumStmt ¶
type VacuumStmt struct{}
type Value ¶
Value represents a SQLite value with its type.
func ApplyAffinity ¶
func ApplyAffinity(v Value, affinity ColumnAffinity) Value
ApplyAffinity applies type affinity to a value. Returns the value possibly coerced to the affinity type.
func DecodeRecordColumn ¶
decodeSerialValue decodes a single value from the record body given a serial type. DecodeRecordColumn decodes a single column by index from raw record bytes. Returns the Value without decoding other columns. Returns error if colIdx is out of range.