Documentation
¶
Overview ¶
package mist provides an in-memory MySQL-compatible database engine.
Mist is a lightweight, thread-safe SQL database that supports basic SQL operations including CREATE TABLE, INSERT, SELECT, UPDATE, DELETE, JOIN, nested transactions, and more. It uses the TiDB parser for MySQL-compatible SQL parsing.
Example usage:
engine := mist.NewSQLEngine()
// Create a table
_, err := engine.Execute("CREATE TABLE users (id INT, name VARCHAR(50), age INT)")
if err != nil {
log.Fatal(err)
}
// Insert data
_, err = engine.Execute("INSERT INTO users VALUES (1, 'Alice', 30)")
if err != nil {
log.Fatal(err)
}
// Query data
result, err := engine.Execute("SELECT * FROM users WHERE age > 25")
if err != nil {
log.Fatal(err)
}
// Print results
mist.PrintResult(result)
// Use nested transactions and savepoints
_, err = engine.Execute("START TRANSACTION")
if err != nil {
log.Fatal(err)
}
_, err = engine.Execute("INSERT INTO users VALUES (2, 'Bob', 25)")
if err != nil {
log.Fatal(err)
}
_, err = engine.Execute("SAVEPOINT sp1")
if err != nil {
log.Fatal(err)
}
_, err = engine.Execute("BEGIN") // Nested transaction
if err != nil {
log.Fatal(err)
}
_, err = engine.Execute("INSERT INTO users VALUES (3, 'Charlie', 35)")
if err != nil {
log.Fatal(err)
}
_, err = engine.Execute("ROLLBACK") // Rollback nested transaction
if err != nil {
log.Fatal(err)
}
_, err = engine.Execute("COMMIT") // Commit outer transaction
if err != nil {
log.Fatal(err)
}
// Import SQL files
results, err := engine.ImportSQLFile("schema.sql")
if err != nil {
log.Fatal(err)
}
Index ¶
- func ExecuteAlterTable(db *Database, stmt *ast.AlterTableStmt) error
- func ExecuteCreateIndex(db *Database, stmt *ast.CreateIndexStmt) error
- func ExecuteCreateTable(db *Database, stmt *ast.CreateTableStmt) error
- func ExecuteDelete(db *Database, stmt *ast.DeleteStmt) (int, error)
- func ExecuteDeleteAll(table *Table) int
- func ExecuteDropIndex(db *Database, stmt *ast.DropIndexStmt) error
- func ExecuteDropTable(db *Database, stmt *ast.DropTableStmt) error
- func ExecuteFunction(funcName string, args []interface{}) (interface{}, error)
- func ExecuteInsert(db *Database, stmt *ast.InsertStmt) error
- func ExecuteTruncateTable(db *Database, stmt *ast.TruncateTableStmt) error
- func ExecuteUpdate(db *Database, stmt *ast.UpdateStmt) (int, error)
- func Interactive(engine *SQLEngine)
- func PrintResult(result interface{})
- func PrintSelectResult(result *SelectResult)
- func RunDaemon(port int) error
- func RunSimpleDaemon(port int) error
- func RunSimpleDaemonWithOptions(port int, options PersistenceOptions) error
- func StartDaemonWithContext(ctx context.Context, port int) error
- func StartSimpleDaemonWithContext(ctx context.Context, port int) error
- func Version() string
- type AggregateFunction
- type AggregateResult
- type AggregateType
- type BuiltinFunction
- type Column
- type ColumnType
- type Database
- func (db *Database) CreateTable(name string, columns []Column) error
- func (db *Database) ExecuteForeignKeyDeletionActions(table *Table, row Row) error
- func (db *Database) GetTable(name string) (*Table, error)
- func (db *Database) ListTables() []string
- func (db *Database) ValidateForeignKeyDeletion(table *Table, row Row) error
- func (db *Database) ValidateForeignKeys(table *Table, values []interface{}) error
- type ForeignKey
- type ForeignKeyAction
- type FunctionType
- type Index
- type IndexManager
- func (im *IndexManager) AddRowToIndexes(tableName string, rowIndex int, row Row, table *Table)
- func (im *IndexManager) ClearTableIndexes(tableName string)
- func (im *IndexManager) CreateCompositeIndex(name, tableName string, columnNames []string, indexType IndexType, ...) error
- func (im *IndexManager) CreateIndex(name, tableName, columnName string, indexType IndexType, table *Table) error
- func (im *IndexManager) DropIndex(name string) error
- func (im *IndexManager) DropTableIndexes(tableName string)
- func (im *IndexManager) GetIndex(name string) (*Index, bool)
- func (im *IndexManager) GetIndexesForTable(tableName, columnName string) []*Index
- func (im *IndexManager) ListIndexes() []string
- func (im *IndexManager) RemoveRowFromIndexes(tableName string, rowIndex int, row Row, table *Table)
- func (im *IndexManager) UpdateIndexes(tableName string, rowIndex int, oldRow, newRow *Row, table *Table)
- type IndexType
- type JoinInfo
- type JoinResult
- type PersistenceOptions
- type Row
- type SQLEngine
- func (engine *SQLEngine) Close() error
- func (engine *SQLEngine) EndRecording()
- func (engine *SQLEngine) Execute(sql string) (interface{}, error)
- func (engine *SQLEngine) ExecuteMultiple(sql string) ([]interface{}, error)
- func (engine *SQLEngine) GetDatabase() *Database
- func (engine *SQLEngine) GetRecordedQueries() []string
- func (engine *SQLEngine) ImportSQLFile(filename string) ([]interface{}, error)
- func (engine *SQLEngine) ImportSQLFileFromReader(reader io.Reader) ([]interface{}, error)
- func (engine *SQLEngine) ImportSQLFileWithProgress(filename string, progressCallback func(current, total int, statement string)) ([]interface{}, error)
- func (engine *SQLEngine) LoadAof() error
- func (engine *SQLEngine) LoadSnapshot() error
- func (engine *SQLEngine) LoadSnapshotFromReader(r io.Reader) error
- func (engine *SQLEngine) SaveSnapshot() error
- func (engine *SQLEngine) SaveSnapshotToWriter(w io.Writer) error
- func (engine *SQLEngine) StartRecording()
- type Savepoint
- type SelectResult
- func ExecuteSelect(db *Database, stmt *ast.SelectStmt) (*SelectResult, error)
- func ExecuteSelectWithCorrelatedContext(db *Database, stmt *ast.SelectStmt, outerTable *Table, outerRow Row) (*SelectResult, error)
- func ExecuteSelectWithJoin(db *Database, stmt *ast.SelectStmt) (*SelectResult, error)
- func ExecuteSetOperation(db *Database, stmt *ast.SetOprStmt) (*SelectResult, error)
- func ExecuteShowIndexes(db *Database, tableName string) (*SelectResult, error)
- func ExecuteUnion(db *Database, stmt *ast.SetOprStmt) (*SelectResult, error)
- type SimpleMistServer
- type Snapshot
- type SnapshotIndex
- type SnapshotTable
- type Table
- func (t *Table) AddForeignKey(fk ForeignKey) error
- func (t *Table) AddRow(values []interface{}) error
- func (t *Table) AddRowWithIndexManager(values []interface{}, indexManager *IndexManager) error
- func (t *Table) GetAutoIncrementColumn() int
- func (t *Table) GetColumnIndex(name string) int
- func (t *Table) GetNextAutoIncrementValue() int64
- func (t *Table) GetRows() []Row
- type TransactionChange
- type TransactionData
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExecuteAlterTable ¶
func ExecuteAlterTable(db *Database, stmt *ast.AlterTableStmt) error
ExecuteAlterTable processes an ALTER TABLE statement
func ExecuteCreateIndex ¶
func ExecuteCreateIndex(db *Database, stmt *ast.CreateIndexStmt) error
ExecuteCreateIndex processes a CREATE INDEX statement
func ExecuteCreateTable ¶
func ExecuteCreateTable(db *Database, stmt *ast.CreateTableStmt) error
ExecuteCreateTable processes a CREATE TABLE statement
func ExecuteDelete ¶
func ExecuteDelete(db *Database, stmt *ast.DeleteStmt) (int, error)
ExecuteDelete processes a DELETE statement
func ExecuteDeleteAll ¶
ExecuteDeleteAll deletes all rows from a table (DELETE FROM table without WHERE)
func ExecuteDropIndex ¶
func ExecuteDropIndex(db *Database, stmt *ast.DropIndexStmt) error
ExecuteDropIndex processes a DROP INDEX statement
func ExecuteDropTable ¶
func ExecuteDropTable(db *Database, stmt *ast.DropTableStmt) error
ExecuteDropTable handles DROP TABLE statements
func ExecuteFunction ¶
ExecuteFunction executes a function call with the given arguments
func ExecuteInsert ¶
func ExecuteInsert(db *Database, stmt *ast.InsertStmt) error
ExecuteInsert processes an INSERT statement
func ExecuteTruncateTable ¶
func ExecuteTruncateTable(db *Database, stmt *ast.TruncateTableStmt) error
ExecuteTruncateTable handles TRUNCATE TABLE statements
func ExecuteUpdate ¶
func ExecuteUpdate(db *Database, stmt *ast.UpdateStmt) (int, error)
ExecuteUpdate processes an UPDATE statement
func Interactive ¶
func Interactive(engine *SQLEngine)
Interactive starts an interactive SQL session with the given engine
func PrintResult ¶
func PrintResult(result interface{})
PrintResult prints the result of a SQL execution in a user-friendly format
func PrintSelectResult ¶
func PrintSelectResult(result *SelectResult)
PrintSelectResult prints a SELECT result in a formatted table
func RunSimpleDaemon ¶
RunSimpleDaemon starts the simple Mist daemon and handles graceful shutdown
func RunSimpleDaemonWithOptions ¶
func RunSimpleDaemonWithOptions(port int, options PersistenceOptions) error
RunSimpleDaemonWithOptions starts the simple Mist daemon with persistence options
func StartSimpleDaemonWithContext ¶
StartSimpleDaemonWithContext starts the daemon with a context for programmatic control
Types ¶
type AggregateFunction ¶
type AggregateFunction struct {
Type AggregateType
Column string
IsDistinct bool
IsStar bool // for COUNT(*)
}
AggregateFunction represents an aggregate function in a query
type AggregateResult ¶
type AggregateResult struct {
Functions []AggregateFunction
Values []interface{}
}
AggregateResult holds the result of aggregate computation
type AggregateType ¶
type AggregateType int
AggregateType represents different types of aggregate functions
const ( AggCount AggregateType = iota AggSum AggAvg AggMin AggMax )
func (AggregateType) String ¶
func (at AggregateType) String() string
type BuiltinFunction ¶
type BuiltinFunction struct {
Name string
Type FunctionType
MinArgs int
MaxArgs int // -1 for unlimited
Executor func(args []interface{}) (interface{}, error)
}
BuiltinFunction represents a built-in function implementation
func GetBuiltinFunction ¶
func GetBuiltinFunction(name string) (*BuiltinFunction, bool)
GetBuiltinFunction returns a builtin function by name
type Column ¶
type Column struct {
Name string
Type ColumnType
Length int // for VARCHAR
Precision int // for DECIMAL (total digits)
Scale int // for DECIMAL (digits after decimal point)
NotNull bool
Primary bool
Unique bool // UNIQUE constraint
AutoIncr bool
Default interface{} // default value for the column
OnUpdate interface{} // ON UPDATE value (e.g., CURRENT_TIMESTAMP)
EnumValues []string // for ENUM type
SetValues []string // for SET type
ForeignKey *ForeignKey // foreign key constraint, if any
}
Column represents a table column definition
type ColumnType ¶
type ColumnType int
ColumnType represents the data type of a column
const ( TypeInt ColumnType = iota TypeVarchar TypeText TypeFloat TypeBool TypeDecimal TypeTimestamp TypeDate TypeEnum TypeTime TypeYear TypeSet )
func (ColumnType) String ¶
func (ct ColumnType) String() string
type Database ¶
type Database struct {
Tables map[string]*Table
IndexManager *IndexManager
// contains filtered or unexported fields
}
Database represents the in-memory database
func (*Database) CreateTable ¶
CreateTable creates a new table in the database
func (*Database) ExecuteForeignKeyDeletionActions ¶
ExecuteForeignKeyDeletionActions executes the foreign key actions (CASCADE, SET NULL, SET DEFAULT) when deleting a row
func (*Database) ListTables ¶
ListTables returns all table names
func (*Database) ValidateForeignKeyDeletion ¶
ValidateForeignKeyDeletion validates that a row can be deleted without violating foreign key constraints
func (*Database) ValidateForeignKeys ¶
ValidateForeignKeys validates foreign key constraints for a row
type ForeignKey ¶
type ForeignKey struct {
Name string // constraint name
LocalColumns []string // local column names
RefTable string // referenced table name
RefColumns []string // referenced column names
OnUpdate ForeignKeyAction // action on update
OnDelete ForeignKeyAction // action on delete
}
ForeignKey represents a foreign key constraint
type ForeignKeyAction ¶
type ForeignKeyAction int
ForeignKeyAction represents the action to take on foreign key violations
const ( FKActionNoAction ForeignKeyAction = iota FKActionRestrict FKActionCascade FKActionSetNull FKActionSetDefault )
func (ForeignKeyAction) String ¶
func (fka ForeignKeyAction) String() string
type FunctionType ¶
type FunctionType int
FunctionType represents different categories of built-in functions
const ( FuncString FunctionType = iota FuncDateTime FuncMath FuncConditional FuncTypeConversion )
type Index ¶
type Index struct {
Name string
TableName string
ColumnName string // For single-column indexes (backward compatibility)
ColumnNames []string // For multi-column indexes (composite)
Type IndexType
Data map[interface{}][]int // value -> row indexes
IsParsedOnly bool // True for indexes that are parsed but not functionally implemented
// contains filtered or unexported fields
}
Index represents a database index
func NewCompositeIndex ¶
NewCompositeIndex creates a new multi-column index
func (*Index) RebuildIndex ¶
RebuildIndex rebuilds the entire index from table data
func (*Index) RemoveEntry ¶
RemoveEntry removes an entry from the index
func (*Index) UpdateEntry ¶
UpdateEntry updates an entry in the index (remove old, add new)
type IndexManager ¶
type IndexManager struct {
Indexes map[string]*Index // index name -> index
// contains filtered or unexported fields
}
IndexManager manages all indexes for the database
func NewIndexManager ¶
func NewIndexManager() *IndexManager
NewIndexManager creates a new index manager
func (*IndexManager) AddRowToIndexes ¶
func (im *IndexManager) AddRowToIndexes(tableName string, rowIndex int, row Row, table *Table)
AddRowToIndexes adds a new row to all relevant indexes
func (*IndexManager) ClearTableIndexes ¶
func (im *IndexManager) ClearTableIndexes(tableName string)
ClearTableIndexes clears all index data for a table (used by TRUNCATE)
func (*IndexManager) CreateCompositeIndex ¶
func (im *IndexManager) CreateCompositeIndex(name, tableName string, columnNames []string, indexType IndexType, table *Table) error
CreateCompositeIndex creates a new multi-column index
func (*IndexManager) CreateIndex ¶
func (im *IndexManager) CreateIndex(name, tableName, columnName string, indexType IndexType, table *Table) error
CreateIndex creates a new single-column index
func (*IndexManager) DropIndex ¶
func (im *IndexManager) DropIndex(name string) error
DropIndex removes an index
func (*IndexManager) DropTableIndexes ¶
func (im *IndexManager) DropTableIndexes(tableName string)
DropTableIndexes removes all indexes for a table (used by DROP TABLE)
func (*IndexManager) GetIndex ¶
func (im *IndexManager) GetIndex(name string) (*Index, bool)
GetIndex retrieves an index by name
func (*IndexManager) GetIndexesForTable ¶
func (im *IndexManager) GetIndexesForTable(tableName, columnName string) []*Index
GetIndexesForTable returns all indexes for a specific table and column
func (*IndexManager) ListIndexes ¶
func (im *IndexManager) ListIndexes() []string
ListIndexes returns all index names
func (*IndexManager) RemoveRowFromIndexes ¶
func (im *IndexManager) RemoveRowFromIndexes(tableName string, rowIndex int, row Row, table *Table)
RemoveRowFromIndexes removes a row from all relevant indexes
func (*IndexManager) UpdateIndexes ¶
func (im *IndexManager) UpdateIndexes(tableName string, rowIndex int, oldRow, newRow *Row, table *Table)
UpdateIndexes updates all relevant indexes when a row is modified
type JoinInfo ¶
type JoinInfo struct {
LeftTable *Table
RightTable *Table
LeftAlias string
RightAlias string
JoinType string
OnCondition ast.ExprNode
}
JoinInfo contains information about tables and join conditions
type JoinResult ¶
type JoinResult struct {
Columns []string
TableNames []string // Which table each column comes from
Rows [][]interface{}
}
JoinResult represents the result of a JOIN operation
type PersistenceOptions ¶
type PersistenceOptions struct {
Enabled bool
AofPath string
SnapshotPath string
SyncInterval string // "always", "everysec", "none" (default: "always")
}
PersistenceOptions holds configuration for database persistence
type SQLEngine ¶
type SQLEngine struct {
// contains filtered or unexported fields
}
SQLEngine represents the main SQL execution engine
func NewSQLEngine ¶
func NewSQLEngine() *SQLEngine
NewSQLEngine creates a new SQL engine with an empty database
func NewSQLEngineWithOptions ¶
func NewSQLEngineWithOptions(options PersistenceOptions) *SQLEngine
NewSQLEngineWithOptions creates a new SQL engine with the given persistence options
func (*SQLEngine) EndRecording ¶
func (engine *SQLEngine) EndRecording()
EndRecording stops recording SQL queries
func (*SQLEngine) ExecuteMultiple ¶
ExecuteMultiple executes multiple SQL statements separated by semicolons
func (*SQLEngine) GetDatabase ¶
GetDatabase returns the underlying database (for testing)
func (*SQLEngine) GetRecordedQueries ¶
GetRecordedQueries returns all queries that were recorded between StartRecording and EndRecording Returns a copy of the recorded queries to prevent external modification
func (*SQLEngine) ImportSQLFile ¶
ImportSQLFile reads a .sql file and executes all SQL statements in it The file should contain SQL statements separated by semicolons Returns a slice of results for each executed statement and any error encountered
func (*SQLEngine) ImportSQLFileFromReader ¶
ImportSQLFileFromReader reads SQL statements from an io.Reader and executes them This is useful for reading from strings, network connections, or other sources Returns a slice of results for each executed statement and any error encountered
func (*SQLEngine) ImportSQLFileWithProgress ¶
func (engine *SQLEngine) ImportSQLFileWithProgress(filename string, progressCallback func(current, total int, statement string)) ([]interface{}, error)
ImportSQLFileWithProgress reads a .sql file and executes all SQL statements with progress reporting The progressCallback function is called after each statement with the statement number and total count Returns a slice of results for each executed statement and any error encountered
func (*SQLEngine) LoadSnapshot ¶
LoadSnapshot loads the database state from a snapshot file
func (*SQLEngine) LoadSnapshotFromReader ¶
LoadSnapshotFromReader loads the database state from an io.Reader
func (*SQLEngine) SaveSnapshot ¶
SaveSnapshot saves the current database state to a snapshot file
func (*SQLEngine) SaveSnapshotToWriter ¶
SaveSnapshotToWriter saves the current database state to an io.Writer
func (*SQLEngine) StartRecording ¶
func (engine *SQLEngine) StartRecording()
StartRecording starts recording all SQL queries executed by this engine
type Savepoint ¶
type Savepoint struct {
// contains filtered or unexported fields
}
Savepoint represents a savepoint within a transaction
type SelectResult ¶
type SelectResult struct {
Columns []string
Rows [][]interface{}
}
SelectResult represents the result of a SELECT query
func ExecuteSelect ¶
func ExecuteSelect(db *Database, stmt *ast.SelectStmt) (*SelectResult, error)
ExecuteSelect processes a SELECT statement
func ExecuteSelectWithCorrelatedContext ¶
func ExecuteSelectWithCorrelatedContext(db *Database, stmt *ast.SelectStmt, outerTable *Table, outerRow Row) (*SelectResult, error)
ExecuteSelectWithCorrelatedContext executes a SELECT statement with access to outer table context for correlated subqueries
func ExecuteSelectWithJoin ¶
func ExecuteSelectWithJoin(db *Database, stmt *ast.SelectStmt) (*SelectResult, error)
ExecuteSelectWithJoin processes a SELECT statement with JOIN
func ExecuteSetOperation ¶
func ExecuteSetOperation(db *Database, stmt *ast.SetOprStmt) (*SelectResult, error)
ExecuteSetOperation is the legacy function now redirecting to ExecuteUnion
func ExecuteShowIndexes ¶
func ExecuteShowIndexes(db *Database, tableName string) (*SelectResult, error)
ExecuteShowIndexes shows all indexes for a table
func ExecuteUnion ¶
func ExecuteUnion(db *Database, stmt *ast.SetOprStmt) (*SelectResult, error)
ExecuteUnion executes a UNION statement combining multiple SELECT results
type SimpleMistServer ¶
type SimpleMistServer struct {
// contains filtered or unexported fields
}
SimpleMistServer represents a simple text-protocol MySQL-compatible daemon server
func NewSimpleMistServer ¶
func NewSimpleMistServer(port int) *SimpleMistServer
NewSimpleMistServer creates a new simple MySQL-compatible daemon server
func NewSimpleMistServerWithOptions ¶
func NewSimpleMistServerWithOptions(port int, options PersistenceOptions) *SimpleMistServer
NewSimpleMistServerWithOptions creates a new simple MySQL-compatible daemon server with persistence options
func (*SimpleMistServer) GetEngine ¶
func (s *SimpleMistServer) GetEngine() *SQLEngine
GetEngine returns the underlying SQL engine (for testing/management)
func (*SimpleMistServer) IsRunning ¶
func (s *SimpleMistServer) IsRunning() bool
IsRunning returns whether the server is currently running
func (*SimpleMistServer) Start ¶
func (s *SimpleMistServer) Start() error
Start starts the simple MySQL daemon server
func (*SimpleMistServer) Stop ¶
func (s *SimpleMistServer) Stop() error
Stop stops the MySQL daemon server
type Snapshot ¶
type Snapshot struct {
Tables []SnapshotTable
Indexes []SnapshotIndex
}
Snapshot represents a full database snapshot
type SnapshotIndex ¶
SnapshotIndex represents an index in a snapshot
type SnapshotTable ¶
SnapshotTable represents a table in a snapshot
type Table ¶
type Table struct {
Name string
Columns []Column
Rows []Row
AutoIncrCounter int64 // Counter for auto increment columns
UniqueIndexes map[string]map[interface{}]bool // column name -> value -> exists
ForeignKeys []ForeignKey // foreign key constraints
// contains filtered or unexported fields
}
Table represents a database table
func (*Table) AddForeignKey ¶
func (t *Table) AddForeignKey(fk ForeignKey) error
AddForeignKey adds a foreign key constraint to a table
func (*Table) AddRowWithIndexManager ¶
func (t *Table) AddRowWithIndexManager(values []interface{}, indexManager *IndexManager) error
AddRowWithIndexManager adds a new row to the table and updates indexes
func (*Table) GetAutoIncrementColumn ¶
GetAutoIncrementColumn returns the index of the auto increment column, or -1 if none exists
func (*Table) GetColumnIndex ¶
GetColumnIndex returns the index of a column by name
func (*Table) GetNextAutoIncrementValue ¶
GetNextAutoIncrementValue returns and increments the auto increment counter
type TransactionChange ¶
type TransactionChange struct {
Type string // "INSERT", "UPDATE", "DELETE", "CREATE_TABLE", "ALTER_TABLE"
TableName string
// For rollback purposes
OldRow *Row // for UPDATE and DELETE
NewRow *Row // for INSERT and UPDATE
RowIndex int // for UPDATE and DELETE
}
TransactionChange represents a change made during a transaction
type TransactionData ¶
type TransactionData struct {
// contains filtered or unexported fields
}
TransactionData holds the state of an active transaction