Documentation
¶
Index ¶
- Variables
- func GetErrorMessage(err error) string
- func IsErrorCode(err error, code ErrorCode) bool
- func NewMockDataSourceWithTableInfo(name string, columns []domain.ColumnInfo) domain.DataSource
- func ParamToString(v interface{}) string
- func ParseBool(s string) (bool, error)
- func ParseFloat(s string) (float64, error)
- func ParseInt(s string) (int, error)
- func ParseInt64(s string) (int64, error)
- type CacheConfig
- type CacheEntry
- type CacheStats
- type DB
- func (db *DB) ClearCache()
- func (db *DB) ClearTableCache(tableName string)
- func (db *DB) Close() error
- func (db *DB) GetCacheStats() CacheStats
- func (db *DB) GetDSManager() *application.DataSourceManager
- func (db *DB) GetDataSource(name string) (domain.DataSource, error)
- func (db *DB) GetDataSourceNames() []string
- func (db *DB) GetDefaultDataSource() (domain.DataSource, error)
- func (db *DB) GetLogger() Logger
- func (db *DB) RegisterDataSource(name string, ds domain.DataSource) error
- func (db *DB) Session() *Session
- func (db *DB) SessionWithOptions(opts *SessionOptions) *Session
- func (db *DB) SetDefaultDataSource(name string) error
- func (db *DB) SetLogger(logger Logger)
- type DBConfig
- type DefaultLogger
- func (l *DefaultLogger) Debug(format string, args ...interface{})
- func (l *DefaultLogger) Error(format string, args ...interface{})
- func (l *DefaultLogger) GetLevel() LogLevel
- func (l *DefaultLogger) Info(format string, args ...interface{})
- func (l *DefaultLogger) SetLevel(level LogLevel)
- func (l *DefaultLogger) Warn(format string, args ...interface{})
- type Error
- type ErrorCode
- type ExplainEntry
- type IsolationLevel
- type LogLevel
- type Logger
- type NoOpLogger
- func (l *NoOpLogger) Debug(format string, args ...interface{})
- func (l *NoOpLogger) Error(format string, args ...interface{})
- func (l *NoOpLogger) GetLevel() LogLevel
- func (l *NoOpLogger) Info(format string, args ...interface{})
- func (l *NoOpLogger) SetLevel(level LogLevel)
- func (l *NoOpLogger) Warn(format string, args ...interface{})
- type Query
- func (q *Query) Close() error
- func (q *Query) Columns() []domain.ColumnInfo
- func (q *Query) Err() error
- func (q *Query) Iter(fn func(row domain.Row) error) error
- func (q *Query) Next() bool
- func (q *Query) Row() domain.Row
- func (q *Query) RowsCount() int
- func (q *Query) Scan(dest ...interface{}) error
- type QueryCache
- func (c *QueryCache) Clear()
- func (c *QueryCache) ClearExpired()
- func (c *QueryCache) ClearTable(tableName string)
- func (c *QueryCache) Get(sql string, params []interface{}) (*domain.QueryResult, bool)
- func (c *QueryCache) GetExplain(sql string) (string, bool)
- func (c *QueryCache) Set(sql string, params []interface{}, result *domain.QueryResult)
- func (c *QueryCache) SetCurrentDB(dbName string)
- func (c *QueryCache) SetExplain(sql string, explain string)
- func (c *QueryCache) Stats() CacheStats
- type Result
- type SelectStmt
- type Session
- func (s *Session) Begin() (*Transaction, error)
- func (s *Session) Close() error
- func (s *Session) CreateTempTable(name string, schema *domain.TableInfo) error
- func (s *Session) Execute(sql string, args ...interface{}) (*Result, error)
- func (s *Session) Explain(sql string, args ...interface{}) (string, error)
- func (s *Session) GetCurrentDB() string
- func (s *Session) GetDB() *DB
- func (s *Session) GetThreadID() uint32
- func (s *Session) GetTraceID() string
- func (s *Session) GetUser() string
- func (s *Session) InTransaction() bool
- func (s *Session) IsolationLevel() IsolationLevel
- func (s *Session) Query(sql string, args ...interface{}) (*Query, error)
- func (s *Session) QueryAll(sql string, args ...interface{}) ([]domain.Row, error)
- func (s *Session) QueryOne(sql string, args ...interface{}) (domain.Row, error)
- func (s *Session) SetCurrentDB(dbName string)
- func (s *Session) SetIsolationLevel(level IsolationLevel)
- func (s *Session) SetThreadID(threadID uint32)
- func (s *Session) SetTraceID(traceID string)
- func (s *Session) SetUser(user string)
- func (s *Session) SetVirtualDBRegistry(registry *virtual.VirtualDatabaseRegistry)
- type SessionOptions
- type Transaction
- func (t *Transaction) Close() error
- func (t *Transaction) Commit() error
- func (t *Transaction) Execute(sql string, args ...interface{}) (*Result, error)
- func (t *Transaction) IsActive() bool
- func (t *Transaction) Query(sql string, args ...interface{}) (*Query, error)
- func (t *Transaction) Rollback() error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultCacheConfig = CacheConfig{ Enabled: true, TTL: 5 * time.Minute, MaxSize: 1000, }
DefaultCacheConfig 默认缓存配置
Functions ¶
func NewMockDataSourceWithTableInfo ¶
func NewMockDataSourceWithTableInfo(name string, columns []domain.ColumnInfo) domain.DataSource
NewMockDataSourceWithTableInfo creates a mock datasource with specific table info
func ParamToString ¶
func ParamToString(v interface{}) string
ParamToString converts a parameter to string representation
func ParseFloat ¶
ParseFloat parses a string to float64 with error handling
func ParseInt64 ¶
ParseInt64 parses a string to int64 with error handling
Types ¶
type CacheConfig ¶
CacheConfig 缓存配置
type CacheEntry ¶
type CacheEntry struct {
SQL string // original SQL for table-level invalidation
Result *domain.QueryResult
Params []interface{}
CreatedAt time.Time
ExpiresAt time.Time
Hits int64
}
CacheEntry 缓存条目
type CacheStats ¶
type CacheStats struct {
Size int // 当前缓存条目数
MaxSize int // 最大缓存条目数
TotalHits int64 // 总命中次数
Oldest time.Time // 最老的缓存创建时间
Newest time.Time // 最新的缓存创建时间
}
CacheStats 缓存统计信息
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is the main database object for managing datasources and creating sessions
func NewDB ¶
NewDB creates a new DB object with the given configuration
Example ¶
// Create a new DB instance db, _ := NewDB(nil) _ = db
func (*DB) ClearTableCache ¶
ClearTableCache clears cache entries for a specific table
func (*DB) GetCacheStats ¶
func (db *DB) GetCacheStats() CacheStats
GetCacheStats returns statistics about the query cache
func (*DB) GetDSManager ¶
func (db *DB) GetDSManager() *application.DataSourceManager
GetDSManager returns the DataSourceManager
func (*DB) GetDataSource ¶
func (db *DB) GetDataSource(name string) (domain.DataSource, error)
GetDataSource returns the datasource with the given name
func (*DB) GetDataSourceNames ¶
GetDataSourceNames returns a list of all registered datasource names
func (*DB) GetDefaultDataSource ¶
func (db *DB) GetDefaultDataSource() (domain.DataSource, error)
GetDefaultDataSource returns the default datasource
func (*DB) RegisterDataSource ¶
func (db *DB) RegisterDataSource(name string, ds domain.DataSource) error
RegisterDataSource registers a datasource with the given name
Example ¶
db, _ := NewDB(nil)
dataSource := newMockDataSource()
// Register a datasource
_ = db.RegisterDataSource("main", dataSource)
func (*DB) Session ¶
Session creates a new session with the default datasource and default options
Example ¶
db, _ := NewDB(nil) // Create a new session session := db.Session() defer session.Close() // Use the session... _ = session
func (*DB) SessionWithOptions ¶
func (db *DB) SessionWithOptions(opts *SessionOptions) *Session
SessionWithOptions creates a new session with custom options
func (*DB) SetDefaultDataSource ¶
SetDefaultDataSource sets the default datasource
type DBConfig ¶
type DBConfig struct {
CacheEnabled bool
CacheSize int
CacheTTL int // seconds
DefaultLogger Logger
DebugMode bool
QueryTimeout time.Duration // 全局查询超时, 0表示不限制
UseEnhancedOptimizer bool // 是否使用增强优化器(默认true)
}
DBConfig contains configuration options for the DB object
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger 默认日志实现
Example ¶
logger := NewDefaultLogger(LogInfo)
logger.Info("Application started")
logger.Debug("This won't be shown due to log level")
logger.Error("An error occurred")
func NewDefaultLogger ¶
func NewDefaultLogger(level LogLevel) *DefaultLogger
NewDefaultLogger 创建默认日志
func NewDefaultLoggerWithOutput ¶
func NewDefaultLoggerWithOutput(level LogLevel, output io.Writer) *DefaultLogger
NewDefaultLoggerWithOutput 创建带输出的默认日志
func (*DefaultLogger) Debug ¶
func (l *DefaultLogger) Debug(format string, args ...interface{})
Debug 输出 DEBUG 级别日志
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(format string, args ...interface{})
Error 输出 ERROR 级别日志
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(format string, args ...interface{})
Info 输出 INFO 级别日志
func (*DefaultLogger) Warn ¶
func (l *DefaultLogger) Warn(format string, args ...interface{})
Warn 输出 WARN 级别日志
type Error ¶
Error 错误类型(带堆栈)
Example ¶
err := NewError(ErrCodeInvalidParam, "invalid parameter", nil) fmt.Println(err.Error())
Output: [INVALID_PARAM] invalid parameter
type ErrorCode ¶
type ErrorCode string
ErrorCode 错误码
const ( ErrCodeDSNotFound ErrorCode = "DS_NOT_FOUND" ErrCodeDSAlreadyExists ErrorCode = "DS_ALREADY_EXISTS" ErrCodeTableNotFound ErrorCode = "TABLE_NOT_FOUND" ErrCodeColumnNotFound ErrorCode = "COLUMN_NOT_FOUND" ErrCodeSyntax ErrorCode = "SYNTAX_ERROR" ErrCodeConstraint ErrorCode = "CONSTRAINT" ErrCodeTransaction ErrorCode = "TRANSACTION" ErrCodeTimeout ErrorCode = "TIMEOUT" ErrCodeQueryKilled ErrorCode = "QUERY_KILLED" ErrCodeInvalidParam ErrorCode = "INVALID_PARAM" ErrCodeNotSupported ErrorCode = "NOT_SUPPORTED" ErrCodeClosed ErrorCode = "CLOSED" ErrCodeInternal ErrorCode = "INTERNAL" )
type ExplainEntry ¶
ExplainEntry Explain 缓存条目
type IsolationLevel ¶
type IsolationLevel int
IsolationLevel represents transaction isolation level
const ( IsolationReadUncommitted IsolationLevel = iota IsolationReadCommitted IsolationRepeatableRead IsolationSerializable )
func (IsolationLevel) String ¶
func (l IsolationLevel) String() string
type Logger ¶
type Logger interface {
Debug(format string, args ...interface{})
Info(format string, args ...interface{})
Warn(format string, args ...interface{})
Error(format string, args ...interface{})
SetLevel(level LogLevel)
GetLevel() LogLevel
}
Logger 日志接口
type NoOpLogger ¶
type NoOpLogger struct{}
NoOpLogger 空日志实现(用于禁用日志)
func (*NoOpLogger) Debug ¶
func (l *NoOpLogger) Debug(format string, args ...interface{})
func (*NoOpLogger) Error ¶
func (l *NoOpLogger) Error(format string, args ...interface{})
func (*NoOpLogger) GetLevel ¶
func (l *NoOpLogger) GetLevel() LogLevel
func (*NoOpLogger) Info ¶
func (l *NoOpLogger) Info(format string, args ...interface{})
func (*NoOpLogger) SetLevel ¶
func (l *NoOpLogger) SetLevel(level LogLevel)
func (*NoOpLogger) Warn ¶
func (l *NoOpLogger) Warn(format string, args ...interface{})
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query 查询结果对象
func NewQuery ¶
func NewQuery(session *Session, result *domain.QueryResult, sql string, params []interface{}) *Query
NewQuery 创建 Query
type QueryCache ¶
type QueryCache struct {
// contains filtered or unexported fields
}
QueryCache 查询缓存
Example ¶
cache := NewQueryCache(CacheConfig{
Enabled: true,
TTL: 300 * time.Second,
MaxSize: 100,
})
result := &domain.QueryResult{
Rows: []domain.Row{{"id": int64(1)}},
}
// Store result in cache
cache.Set("SELECT * FROM users", nil, result)
// Retrieve result from cache
cached, found := cache.Get("SELECT * FROM users", nil)
if found {
// Use cached result
_ = cached
}
func (*QueryCache) ClearTable ¶
func (c *QueryCache) ClearTable(tableName string)
ClearTable 清空指定表的缓存
func (*QueryCache) Get ¶
func (c *QueryCache) Get(sql string, params []interface{}) (*domain.QueryResult, bool)
Get 获取缓存
func (*QueryCache) GetExplain ¶
func (c *QueryCache) GetExplain(sql string) (string, bool)
GetExplain 获取 Explain 缓存
func (*QueryCache) Set ¶
func (c *QueryCache) Set(sql string, params []interface{}, result *domain.QueryResult)
Set 设置缓存
func (*QueryCache) SetCurrentDB ¶
func (c *QueryCache) SetCurrentDB(dbName string)
SetCurrentDB 设置当前数据库上下文
func (*QueryCache) SetExplain ¶
func (c *QueryCache) SetExplain(sql string, explain string)
SetExplain 设置 Explain 缓存
type Result ¶
type Result struct {
RowsAffected int64
LastInsertID int64
// contains filtered or unexported fields
}
Result 命令执行结果
type SelectStmt ¶
type SelectStmt interface {
GetFrom() string
}
SelectStmt interface for accessing Select statement
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a database session (like a MySQL connection) It is concurrent safe and can be used across multiple goroutines
func (*Session) Begin ¶
func (s *Session) Begin() (*Transaction, error)
Begin starts a new transaction If already in a transaction, returns an error (no nesting allowed)
func (*Session) Close ¶
Close closes the session and releases resources Temporary tables created in this session are automatically dropped
func (*Session) CreateTempTable ¶
CreateTempTable creates a temporary table in this session Temporary tables are automatically dropped when session is closed
func (*Session) Execute ¶
Execute executes an INSERT, UPDATE, or DELETE statement and returns number of affected rows Supports parameter binding with ? placeholders For SELECT, SHOW, DESCRIBE, and EXPLAIN statements, use Query() or Explain() method instead
func (*Session) Explain ¶
Explain executes an EXPLAIN statement and returns execution plan Supports parameter binding with ? placeholders Example: session.Explain("SELECT * FROM users WHERE id = ?", 1) This uses actual optimizer to generate execution plans
func (*Session) GetCurrentDB ¶
GetCurrentDB returns the current database for this session
func (*Session) InTransaction ¶
InTransaction returns true if session is currently in a transaction
func (*Session) IsolationLevel ¶
func (s *Session) IsolationLevel() IsolationLevel
IsolationLevel returns current transaction isolation level
func (*Session) Query ¶
Query executes a SELECT, SHOW, or DESCRIBE query and returns a Query object for iterating through results Supports parameter binding with ? placeholders Example: session.Query("SELECT * FROM users WHERE id = ?", 1)
func (*Session) QueryAll ¶
QueryAll executes a query and returns all rows at once Supports parameter binding with ? placeholders
func (*Session) QueryOne ¶
QueryOne executes a query and returns first row only Supports parameter binding with ? placeholders
func (*Session) SetCurrentDB ¶
SetCurrentDB sets the current database for this session This is used by the MySQL protocol handler when COM_INIT_DB is received
func (*Session) SetIsolationLevel ¶
func (s *Session) SetIsolationLevel(level IsolationLevel)
SetIsolationLevel sets transaction isolation level for new transactions
func (*Session) SetThreadID ¶
SetThreadID 设置线程ID (用于KILL查询)
func (*Session) SetTraceID ¶
SetTraceID 设置追踪ID(传播到 CoreSession)
func (*Session) SetVirtualDBRegistry ¶
func (s *Session) SetVirtualDBRegistry(registry *virtual.VirtualDatabaseRegistry)
SetVirtualDBRegistry 设置虚拟数据库注册表
type SessionOptions ¶
type SessionOptions struct {
DataSourceName string
Isolation IsolationLevel
ReadOnly bool
CacheEnabled bool
QueryTimeout time.Duration // 会话级查询超时, 覆盖DB配置
UseEnhancedOptimizer *bool // 是否使用增强优化器(nil表示使用DB配置)
}
SessionOptions contains configuration options for creating a session
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction 事务对象(不支持嵌套)
func NewTransaction ¶
func NewTransaction(session *Session, tx domain.Transaction) *Transaction
NewTransaction 创建 Transaction
func (*Transaction) Execute ¶
func (t *Transaction) Execute(sql string, args ...interface{}) (*Result, error)
Execute 事务内执行命令 Supports parameter binding with ? placeholders