api

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultCacheConfig = CacheConfig{
	Enabled: true,
	TTL:     5 * time.Minute,
	MaxSize: 1000,
}

DefaultCacheConfig 默认缓存配置

Functions

func GetErrorMessage

func GetErrorMessage(err error) string

GetErrorMessage 获取错误消息

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode 检查错误码

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 ParseBool

func ParseBool(s string) (bool, error)

ParseBool parses a string to bool with error handling

func ParseFloat

func ParseFloat(s string) (float64, error)

ParseFloat parses a string to float64 with error handling

func ParseInt

func ParseInt(s string) (int, error)

ParseInt parses a string to int with error handling

func ParseInt64

func ParseInt64(s string) (int64, error)

ParseInt64 parses a string to int64 with error handling

Types

type CacheConfig

type CacheConfig struct {
	Enabled bool
	TTL     time.Duration // 缓存过期时间
	MaxSize int           // 最大缓存条目数
}

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 缓存统计信息

func (CacheStats) String

func (s CacheStats) String() string

String 返回统计信息的字符串表示

type DB

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

DB is the main database object for managing datasources and creating sessions

func NewDB

func NewDB(config *DBConfig) (*DB, error)

NewDB creates a new DB object with the given configuration

Example
// Create a new DB instance
db, _ := NewDB(nil)
_ = db

func (*DB) ClearCache

func (db *DB) ClearCache()

ClearCache clears the entire query cache

func (*DB) ClearTableCache

func (db *DB) ClearTableCache(tableName string)

ClearTableCache clears cache entries for a specific table

func (*DB) Close

func (db *DB) Close() error

Close closes all datasources and releases resources

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

func (db *DB) GetDataSourceNames() []string

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

func (db *DB) GetLogger() Logger

GetLogger returns the current logger

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

func (db *DB) Session() *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

func (db *DB) SetDefaultDataSource(name string) error

SetDefaultDataSource sets the default datasource

func (*DB) SetLogger

func (db *DB) SetLogger(logger Logger)

SetLogger sets the logger for the DB object

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

func (l *DefaultLogger) GetLevel() LogLevel

GetLevel 获取日志级别

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(format string, args ...interface{})

Info 输出 INFO 级别日志

func (*DefaultLogger) SetLevel

func (l *DefaultLogger) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(format string, args ...interface{})

Warn 输出 WARN 级别日志

type Error

type Error struct {
	Code    ErrorCode
	Message string
	Stack   []string // 调用堆栈
	Cause   error    // 原始错误
}

Error 错误类型(带堆栈)

Example
err := NewError(ErrCodeInvalidParam, "invalid parameter", nil)
fmt.Println(err.Error())
Output:

[INVALID_PARAM] invalid parameter

func NewError

func NewError(code ErrorCode, message string, cause error) *Error

NewError 创建错误

func WrapError

func WrapError(err error, code ErrorCode, message string) *Error

WrapError 包装错误

Example
originalErr := errors.New("connection failed")
wrappedErr := WrapError(originalErr, ErrCodeInternal, "database error")
fmt.Println(wrappedErr.Error())
Output:

[INTERNAL] database error: connection failed

func (*Error) Error

func (e *Error) Error() string

Error 接口实现

func (*Error) StackTrace

func (e *Error) StackTrace() []string

StackTrace 返回调用堆栈

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap 返回原始错误

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

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode 获取错误码

type ExplainEntry

type ExplainEntry struct {
	Explain   string
	CreatedAt time.Time
	ExpiresAt time.Time
	Hits      int64
}

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 LogLevel

type LogLevel int

LogLevel 日志级别

const (
	LogError LogLevel = iota
	LogWarn
	LogInfo
	LogDebug
)

func (LogLevel) String

func (l LogLevel) String() 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 NewNoOpLogger

func NewNoOpLogger() *NoOpLogger

NewNoOpLogger 创建空日志

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

func (*Query) Close

func (q *Query) Close() error

Close 关闭查询

func (*Query) Columns

func (q *Query) Columns() []domain.ColumnInfo

Columns 获取列信息

func (*Query) Err

func (q *Query) Err() error

Err returns the error that occurred during query execution

func (*Query) Iter

func (q *Query) Iter(fn func(row domain.Row) error) error

Iter 遍历所有行(回调函数)

func (*Query) Next

func (q *Query) Next() bool

Next 移动到下一行

func (*Query) Row

func (q *Query) Row() domain.Row

Row 获取当前行(map 形式)

func (*Query) RowsCount

func (q *Query) RowsCount() int

RowsCount 获取总行数

func (*Query) Scan

func (q *Query) Scan(dest ...interface{}) error

Scan 扫描当前行到变量

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 NewQueryCache

func NewQueryCache(config CacheConfig) *QueryCache

NewQueryCache 创建查询缓存

func (*QueryCache) Clear

func (c *QueryCache) Clear()

Clear 清空所有缓存

func (*QueryCache) ClearExpired

func (c *QueryCache) ClearExpired()

ClearExpired 清空过期的缓存

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 缓存

func (*QueryCache) Stats

func (c *QueryCache) Stats() CacheStats

Stats 获取缓存统计信息

type Result

type Result struct {
	RowsAffected int64
	LastInsertID int64
	// contains filtered or unexported fields
}

Result 命令执行结果

func NewResult

func NewResult(rowsAffected, lastInsertID int64, err error) *Result

NewResult 创建 Result

func (*Result) Err

func (r *Result) Err() error

LastError 获取错误

func (*Result) Error

func (r *Result) Error() string

Error 实现 error 接口

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

func (s *Session) Close() error

Close closes the session and releases resources Temporary tables created in this session are automatically dropped

func (*Session) CreateTempTable

func (s *Session) CreateTempTable(name string, schema *domain.TableInfo) error

CreateTempTable creates a temporary table in this session Temporary tables are automatically dropped when session is closed

func (*Session) Execute

func (s *Session) Execute(sql string, args ...interface{}) (*Result, error)

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

func (s *Session) Explain(sql string, args ...interface{}) (string, error)

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

func (s *Session) GetCurrentDB() string

GetCurrentDB returns the current database for this session

func (*Session) GetDB

func (s *Session) GetDB() *DB

GetDB returns DB object that created this session

func (*Session) GetThreadID

func (s *Session) GetThreadID() uint32

GetThreadID 获取线程ID

func (*Session) GetTraceID

func (s *Session) GetTraceID() string

GetTraceID 获取追踪ID

func (*Session) GetUser

func (s *Session) GetUser() string

GetUser 获取当前用户名

func (*Session) InTransaction

func (s *Session) InTransaction() bool

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

func (s *Session) Query(sql string, args ...interface{}) (*Query, error)

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

func (s *Session) QueryAll(sql string, args ...interface{}) ([]domain.Row, error)

QueryAll executes a query and returns all rows at once Supports parameter binding with ? placeholders

func (*Session) QueryOne

func (s *Session) QueryOne(sql string, args ...interface{}) (domain.Row, error)

QueryOne executes a query and returns first row only Supports parameter binding with ? placeholders

func (*Session) SetCurrentDB

func (s *Session) SetCurrentDB(dbName string)

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

func (s *Session) SetThreadID(threadID uint32)

SetThreadID 设置线程ID (用于KILL查询)

func (*Session) SetTraceID

func (s *Session) SetTraceID(traceID string)

SetTraceID 设置追踪ID(传播到 CoreSession)

func (*Session) SetUser

func (s *Session) SetUser(user string)

SetUser 设置当前用户名

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

func (t *Transaction) Close() error

Close 关闭事务(等同于 Rollback)

func (*Transaction) Commit

func (t *Transaction) Commit() error

Commit 提交事务

func (*Transaction) Execute

func (t *Transaction) Execute(sql string, args ...interface{}) (*Result, error)

Execute 事务内执行命令 Supports parameter binding with ? placeholders

func (*Transaction) IsActive

func (t *Transaction) IsActive() bool

IsActive 检查事务是否活跃

func (*Transaction) Query

func (t *Transaction) Query(sql string, args ...interface{}) (*Query, error)

Query 事务内查询 Supports parameter binding with ? placeholders

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback 回滚事务

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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