server

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MYSQL_TYPE_TINY      = mysql.MYSQL_TYPE_TINY
	MYSQL_TYPE_SHORT     = mysql.MYSQL_TYPE_SHORT
	MYSQL_TYPE_LONG      = mysql.MYSQL_TYPE_LONG
	MYSQL_TYPE_LONGLONG  = mysql.MYSQL_TYPE_LONGLONG
	MYSQL_TYPE_FLOAT     = mysql.MYSQL_TYPE_FLOAT
	MYSQL_TYPE_DOUBLE    = mysql.MYSQL_TYPE_DOUBLE
	MYSQL_TYPE_STRING    = mysql.MYSQL_TYPE_STRING
	MYSQL_TYPE_VARCHAR   = mysql.MYSQL_TYPE_VARCHAR
	MYSQL_TYPE_TIMESTAMP = mysql.MYSQL_TYPE_TIMESTAMP
)

MySQL 类型别名(方便使用)

Variables

View Source
var (
	ErrInvalidPort      = errors.New("server: invalid port number")
	ErrServerClosed     = errors.New("server: server closed")
	ErrConnectionLimit  = errors.New("server: connection limit exceeded")
	ErrAuthFailed       = errors.New("server: authentication failed")
	ErrDatabaseNotFound = errors.New("server: database not found")
	ErrTableNotFound    = errors.New("server: table not found")
	ErrQueryFailed      = errors.New("server: query failed")
)

错误定义

Functions

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration 格式化时长

func GetCallerInfo

func GetCallerInfo() (file string, line int, fn string)

GetCallerInfo 获取调用者信息

func GetMySQLType

func GetMySQLType(s series.Series) uint8

GetMySQLType 根据 series 类型获取 MySQL 字段类型

func GetMySQLTypeFromColumnType

func GetMySQLTypeFromColumnType(colType core.ColumnType) uint8

GetMySQLTypeFromColumnType 根据 Column 类型获取 MySQL 字段类型

func GetMySQLTypeName

func GetMySQLTypeName(s series.Series) string

GetMySQLTypeName 根据 series 类型获取 MySQL 字段类型名

func GetMySQLTypeNameFromColumnType

func GetMySQLTypeNameFromColumnType(colType core.ColumnType) string

GetMySQLTypeNameFromColumnType 根据 Column 类型获取 MySQL 字段类型名

func InitConfig

func InitConfig(path string) error

InitConfig 初始化配置(如果不存在则创建默认配置)

func SaveConfig

func SaveConfig(path string, cfg *Config) error

SaveConfig 保存配置到文件

Types

type AdvancedConfig

type AdvancedConfig struct {
	// 性能相关
	MaxAllowedPacket int  `yaml:"max_allowed_packet"` // 最大包大小
	AutoCommit       bool `yaml:"auto_commit"`        // 自动提交

	// 安全相关
	RequireSecureTransport bool `yaml:"require_secure_transport"` // 要求安全传输
	SkipNameResolve        bool `yaml:"skip_name_resolve"`        // 跳过域名解析

	// 兼容性
	LowerCaseTableNames int `yaml:"lower_case_table_names"` // 表名大小写敏感
}

AdvancedConfig 高级配置

type AuditEntry

type AuditEntry struct {
	Timestamp time.Time `json:"timestamp"`
	Event     string    `json:"event"`
	User      string    `json:"user"`
	Host      string    `json:"host"`
	Database  string    `json:"database"`
	Query     string    `json:"query,omitempty"`
	Status    string    `json:"status"`
}

AuditEntry 审计日志条目

type AuditLogConfig

type AuditLogConfig struct {
	Enabled bool   `yaml:"enabled"` // 是否启用
	File    string `yaml:"file"`    // 日志文件路径
}

AuditLogConfig 审计日志配置

type AuditLogger

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

AuditLogger 审计日志

func NewAuditLogger

func NewAuditLogger(logFile string) (*AuditLogger, error)

NewAuditLogger 创建审计日志

func (*AuditLogger) Close

func (a *AuditLogger) Close() error

Close 关闭审计日志

func (*AuditLogger) Log

func (a *AuditLogger) Log(entry *AuditEntry)

Log 记录审计日志

func (*AuditLogger) LogConnect

func (a *AuditLogger) LogConnect(user, host string, success bool)

LogConnect 记录连接事件

func (*AuditLogger) LogDisconnect

func (a *AuditLogger) LogDisconnect(user string)

LogDisconnect 记录断开连接事件

func (*AuditLogger) LogEvent

func (a *AuditLogger) LogEvent(event, user, database, query, status string)

LogEvent 记录事件

func (*AuditLogger) LogQuery

func (a *AuditLogger) LogQuery(user, database, query string, success bool)

LogQuery 记录查询事件

type AuthPlugin

type AuthPlugin string

AuthPlugin 认证插件类型

const (
	// AuthNativePassword MySQL 原生密码认证
	AuthNativePassword AuthPlugin = "mysql_native_password"
	// AuthCachingSha2Password MySQL 8.0 默认认证
	AuthCachingSha2Password AuthPlugin = "caching_sha2_password"
	// AuthSha256Password SHA256 密码认证
	AuthSha256Password AuthPlugin = "sha256_password"
)

type ColumnHandler

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

ColumnHandler MySQL 协议处理器

func NewColumnHandler

func NewColumnHandler(cfg HandlerConfig) *ColumnHandler

NewColumnHandler 创建 ColumnHandler

func (*ColumnHandler) HandleFieldList

func (h *ColumnHandler) HandleFieldList(table string, fieldWildcard string) ([]*mysql.Field, error)

HandleFieldList 处理字段列表 (COM_FIELD_LIST)

func (*ColumnHandler) HandleOtherCommand

func (h *ColumnHandler) HandleOtherCommand(cmd byte, data []byte) error

HandleOtherCommand 处理其他命令

func (*ColumnHandler) HandlePing

func (h *ColumnHandler) HandlePing() error

HandlePing 处理心跳检测 (COM_PING)

func (*ColumnHandler) HandleQuery

func (h *ColumnHandler) HandleQuery(query string) (*mysql.Result, error)

HandleQuery 处理 SQL 查询 (COM_QUERY)

func (*ColumnHandler) HandleStmtClose

func (h *ColumnHandler) HandleStmtClose(context any) error

HandleStmtClose 处理预处理关闭 (COM_STMT_CLOSE)

func (*ColumnHandler) HandleStmtExecute

func (h *ColumnHandler) HandleStmtExecute(context any, query string, args []any) (*mysql.Result, error)

HandleStmtExecute 处理预处理执行 (COM_STMT_EXECUTE)

func (*ColumnHandler) HandleStmtPrepare

func (h *ColumnHandler) HandleStmtPrepare(query string) (int, int, any, error)

HandleStmtPrepare 处理预处理准备 (COM_STMT_PREPARE)

func (*ColumnHandler) UseDB

func (h *ColumnHandler) UseDB(dbName string) error

UseDB 处理 USE 命令 (COM_INIT_DB)

type Config

type Config struct {
	// 基本配置
	Addr       string `yaml:"addr"`        // 监听地址
	Port       int    `yaml:"port"`        // 监听端口
	UnixSocket string `yaml:"unix_socket"` // Unix Socket 路径

	// 认证配置
	DefaultUser     string `yaml:"default_user"`     // 默认用户名
	DefaultPassword string `yaml:"default_password"` // 默认密码
	AuthPlugin      string `yaml:"auth_plugin"`      // 认证插件

	// 数据库配置
	DBPath string `yaml:"db_path"` // 数据库路径

	// 连接配置
	MaxConnections int `yaml:"max_connections"` // 最大连接数

	// 超时配置
	ReadTimeout  time.Duration `yaml:"read_timeout"`  // 读超时
	WriteTimeout time.Duration `yaml:"write_timeout"` // 写超时
	IdleTimeout  time.Duration `yaml:"idle_timeout"`  // 空闲超时

	// 日志配置
	Log LogConfig `yaml:"log"`

	// 慢查询日志配置
	SlowQueryLog SlowQueryLogConfig `yaml:"slow_query_log"`

	// 审计日志配置
	AuditLog AuditLogConfig `yaml:"audit_log"`

	// 连接池配置
	ConnPool ConnPoolConfig `yaml:"conn_pool"`

	// 高级配置
	Advanced AdvancedConfig `yaml:"advanced"`
}

Config 服务器配置

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 返回默认配置

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig 从文件加载配置

func (*Config) GetAddr

func (c *Config) GetAddr() string

GetAddr 获取监听地址

func (*Config) GetAddress

func (c *Config) GetAddress() string

GetAddress 获取地址

func (*Config) GetNetwork

func (c *Config) GetNetwork() string

GetNetwork 获取网络类型

func (*Config) PrintConfig

func (c *Config) PrintConfig()

PrintConfig 打印配置信息

func (*Config) Validate

func (c *Config) Validate() error

Validate 验证配置

type ConnPool

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

ConnPool 连接池

func NewConnPool

func NewConnPool(config ConnPoolConfig) (*ConnPool, error)

NewConnPool 创建连接池

func (*ConnPool) Cleanup

func (p *ConnPool) Cleanup() int

Cleanup 清理过期连接

func (*ConnPool) Close

func (p *ConnPool) Close() error

Close 关闭连接池

func (*ConnPool) Get

func (p *ConnPool) Get(ctx context.Context) (*PooledConn, error)

Get 获取连接

func (*ConnPool) GetStats

func (p *ConnPool) GetStats() ConnPoolStats

GetStats 获取统计信息

func (*ConnPool) Put

func (p *ConnPool) Put(conn *PooledConn)

Put 归还连接

func (*ConnPool) Resize

func (p *ConnPool) Resize(newMaxSize int) error

Resize 调整连接池大小

func (*ConnPool) SetIdleTimeout

func (p *ConnPool) SetIdleTimeout(timeout time.Duration)

SetIdleTimeout 设置空闲超时

func (*ConnPool) String

func (p *ConnPool) String() string

String 返回连接池字符串表示

type ConnPoolConfig

type ConnPoolConfig struct {
	MaxSize     int           `yaml:"max_size"`     // 最大连接数
	MinSize     int           `yaml:"min_size"`     // 最小连接数
	DialTimeout time.Duration `yaml:"dial_timeout"` // 拨号超时
	IdleTimeout time.Duration `yaml:"idle_timeout"` // 空闲超时
	Network     string        `yaml:"network"`      // 网络类型 (tcp/unix)
	Address     string        `yaml:"address"`      // 地址
}

ConnPoolConfig 连接池配置

func DefaultConnPoolConfig

func DefaultConnPoolConfig() ConnPoolConfig

DefaultConnPoolConfig 默认连接池配置

type ConnPoolStats

type ConnPoolStats struct {
	CurrentSize int   `json:"current_size"` // 当前连接数
	MaxSize     int   `json:"max_size"`     // 最大连接数
	MinSize     int   `json:"min_size"`     // 最小连接数
	Available   int   `json:"available"`    // 可用连接数
	InUse       int   `json:"in_use"`       // 使用中连接数
	OpenCount   int64 `json:"open_count"`   // 累计打开次数
	CloseCount  int64 `json:"close_count"`  // 累计关闭次数
}

Stats 连接池统计

type HandlerConfig

type HandlerConfig struct {
	DB           *store.DB
	UserManager  *UserManager
	SessionMgr   *SessionManager
	SlowQueryLog *SlowQueryLog
	AuditLog     *AuditLogger
	Config       *Config
}

HandlerConfig Handler 配置

type LogConfig

type LogConfig struct {
	Level      string `yaml:"level"`       // 日志级别:debug, info, warn, error
	File       string `yaml:"file"`        // 日志文件路径
	MaxSize    int    `yaml:"max_size"`    // 最大文件大小 (MB)
	MaxBackups int    `yaml:"max_backups"` // 最大备份数量
	Format     string `yaml:"format"`      // 日志格式:text, json
}

LogConfig 日志配置

type PooledConn

type PooledConn struct {
	net.Conn
	// contains filtered or unexported fields
}

PooledConn 池化连接

type PreparedStatementInfo

type PreparedStatementInfo struct {
	ID       uint32
	SQL      string
	StmtType sqlengine.StmtType
	Params   []StmtParam
	Columns  []StmtColumn
}

PreparedStatementInfo 预处理语句信息

type Privilege

type Privilege string

Privilege 权限类型

const (
	// PrivSelect SELECT 权限
	PrivSelect Privilege = "SELECT"
	// PrivInsert INSERT 权限
	PrivInsert Privilege = "INSERT"
	// PrivUpdate UPDATE 权限
	PrivUpdate Privilege = "UPDATE"
	// PrivDelete DELETE 权限
	PrivDelete Privilege = "DELETE"
	// PrivCreate CREATE 权限
	PrivCreate Privilege = "CREATE"
	// PrivDrop DROP 权限
	PrivDrop Privilege = "DROP"
	// PrivAlter ALTER 权限
	PrivAlter Privilege = "ALTER"
	// PrivAll 所有权限
	PrivAll Privilege = "ALL"
)

type PrivilegeLevel

type PrivilegeLevel int

PrivilegeLevel 权限级别

const (
	// PrivGlobal 全局级别
	PrivGlobal PrivilegeLevel = iota
	// PrivDatabase 数据库级别
	PrivDatabase
	// PrivTable 表级别
	PrivTable
)

type QueryLogEntry

type QueryLogEntry struct {
	Timestamp time.Time `json:"timestamp"`       // 时间戳
	SessionID uint32    `json:"session_id"`      // 会话 ID
	User      string    `json:"user"`            // 用户
	Database  string    `json:"database"`        // 数据库
	Query     string    `json:"query"`           // SQL 语句
	Duration  int64     `json:"duration_ms"`     // 执行时长 (毫秒)
	Rows      int64     `json:"rows"`            // 影响行数
	Error     string    `json:"error,omitempty"` // 错误信息
	IsSlow    bool      `json:"is_slow"`         // 是否慢查询
	Host      string    `json:"host"`            // 客户端主机
}

QueryLogEntry 查询日志条目

type QueryLogger

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

QueryLogger 查询日志记录器(包装器)

func NewQueryLogger

func NewQueryLogger(slowLog *SlowQueryLog) *QueryLogger

NewQueryLogger 创建查询日志记录器

func (*QueryLogger) Record

func (q *QueryLogger) Record(session *Session, query string, startTime time.Time, rows int64) func(error)

Record 记录查询(使用 defer)

type ResultEncoder

type ResultEncoder struct{}

ResultEncoder 结果集编码器

func (*ResultEncoder) EncodeValues

func (e *ResultEncoder) EncodeValues(
	columns []string,
	data map[string]series.Series,
) ([][]mysql.FieldValue, error)

EncodeValues 编码行数据为 MySQL FieldValue

type Server

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

Server MySQL 服务器

func NewServer

func NewServer(config *Config) (*Server, error)

NewServer 创建服务器

func (*Server) GetConfig

func (s *Server) GetConfig() *Config

GetConfig 获取配置

func (*Server) GetConnectionCount

func (s *Server) GetConnectionCount() int32

GetConnectionCount 获取当前连接数

func (*Server) GetDB

func (s *Server) GetDB() *store.DB

GetDB 获取数据库实例

func (*Server) Start

func (s *Server) Start() error

Start 启动服务器

func (*Server) Stop

func (s *Server) Stop() error

Stop 停止服务器

type Session

type Session struct {
	ID         uint32                            // 会话 ID
	Conn       *server.Conn                      // 连接
	User       string                            // 用户名
	DB         string                            // 当前数据库
	Charset    string                            // 字符集
	TimeZone   *time.Location                    // 时区
	State      SessionState                      // 状态
	Prepared   map[uint32]*PreparedStatementInfo // 预处理语句
	CreatedAt  time.Time                         // 创建时间
	LastActive time.Time                         // 最后活跃时间
	QueryCount int64                             // 查询次数
	LastQuery  time.Time                         // 最后查询时间
	Attrs      map[string]string                 // 会话属性
	// contains filtered or unexported fields
}

Session 会话信息

func NewSession

func NewSession(id uint32, conn *server.Conn) *Session

NewSession 创建新会话

func (*Session) AddPrepared

func (s *Session) AddPrepared(id uint32, stmt *PreparedStatementInfo)

AddPrepared 添加预处理语句

func (*Session) Close

func (s *Session) Close()

Close 关闭会话

func (*Session) GetPrepared

func (s *Session) GetPrepared(id uint32) (*PreparedStatementInfo, bool)

GetPrepared 获取预处理语句

func (*Session) GetStats

func (s *Session) GetStats() SessionStats

GetStats 获取会话统计信息

func (*Session) IncrementQueryCount

func (s *Session) IncrementQueryCount()

IncrementQueryCount 增加查询计数

func (*Session) RemovePrepared

func (s *Session) RemovePrepared(id uint32)

RemovePrepared 删除预处理语句

func (*Session) SetIdle

func (s *Session) SetIdle()

SetIdle 设置为空闲状态

func (*Session) UpdateActive

func (s *Session) UpdateActive()

UpdateActive 更新活跃时间

type SessionManager

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

SessionManager 会话管理器

func NewSessionManager

func NewSessionManager(maxSessions int) *SessionManager

NewSessionManager 创建会话管理器

func (*SessionManager) Cleanup

func (m *SessionManager) Cleanup(interval, timeout time.Duration, stopCh <-chan struct{})

Cleanup 清理过期会话(后台协程)

func (*SessionManager) CloseAll

func (m *SessionManager) CloseAll()

CloseAll 关闭所有会话

func (*SessionManager) CloseIdleSessions

func (m *SessionManager) CloseIdleSessions(timeout time.Duration) int

CloseIdleSessions 关闭空闲会话

func (*SessionManager) CreateSession

func (m *SessionManager) CreateSession(conn *server.Conn) (*Session, error)

CreateSession 创建新会话

func (*SessionManager) GetActiveSessionCount

func (m *SessionManager) GetActiveSessionCount() int

GetActiveSessionCount 获取活跃会话数量

func (*SessionManager) GetSession

func (m *SessionManager) GetSession(id uint32) (*Session, error)

GetSession 获取会话

func (*SessionManager) GetSessionCount

func (m *SessionManager) GetSessionCount() int

GetSessionCount 获取会话数量

func (*SessionManager) GetStats

func (m *SessionManager) GetStats() SessionManagerStats

GetStats 获取会话管理器统计

func (*SessionManager) ListSessions

func (m *SessionManager) ListSessions() []*Session

ListSessions 列出所有会话

func (*SessionManager) RemoveSession

func (m *SessionManager) RemoveSession(id uint32)

RemoveSession 删除会话

type SessionManagerStats

type SessionManagerStats struct {
	Total       int
	Active      int
	Idle        int
	MaxSessions int
}

SessionManagerStats 会话管理器统计

type SessionState

type SessionState int

SessionState 会话状态

const (
	// SessionActive 活跃状态
	SessionActive SessionState = iota
	// SessionIdle 空闲状态
	SessionIdle
	// SessionClosed 已关闭
	SessionClosed
)

func (SessionState) String

func (s SessionState) String() string

type SessionStats

type SessionStats struct {
	ID         uint32
	User       string
	DB         string
	State      SessionState
	CreatedAt  time.Time
	LastActive time.Time
	QueryCount int64
	Duration   time.Duration
	IdleTime   time.Duration
}

SessionStats 会话统计信息

type SlowQueryLog

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

SlowQueryLog 慢查询日志

func NewSlowQueryLog

func NewSlowQueryLog(config SlowQueryLogConfig) (*SlowQueryLog, error)

NewSlowQueryLog 创建慢查询日志

func (*SlowQueryLog) Close

func (s *SlowQueryLog) Close() error

Close 关闭日志

func (*SlowQueryLog) Log

func (s *SlowQueryLog) Log(entry *QueryLogEntry)

Log 记录查询日志

func (*SlowQueryLog) LogQuery

func (s *SlowQueryLog) LogQuery(session *Session, query string, duration time.Duration, rows int64, err error)

LogQuery 便捷方法:记录查询

func (*SlowQueryLog) SetEnabled

func (s *SlowQueryLog) SetEnabled(enabled bool)

SetEnabled 启用/禁用日志

func (*SlowQueryLog) SetSlowThreshold

func (s *SlowQueryLog) SetSlowThreshold(threshold time.Duration)

SetSlowThreshold 设置慢查询阈值

type SlowQueryLogConfig

type SlowQueryLogConfig struct {
	Enabled       bool          `yaml:"enabled"`        // 是否启用
	LogFile       string        `yaml:"log_file"`       // 日志文件路径
	SlowThreshold time.Duration `yaml:"slow_threshold"` // 慢查询阈值
	MaxSize       int64         `yaml:"max_size"`       // 最大文件大小 (MB)
	MaxBackups    int           `yaml:"max_backups"`    // 最大备份数量
}

SlowQueryLogConfig 慢查询日志配置

type StmtColumn

type StmtColumn struct {
	Name string
	Type uint8
}

StmtColumn 预处理语句列信息

type StmtParam

type StmtParam struct {
	Name string
	Type uint8
}

StmtParam 预处理语句参数信息

type User

type User struct {
	Username   string          `yaml:"username"`    // 用户名
	Password   string          `yaml:"password"`    // 密码(加密后)
	AuthPlugin AuthPlugin      `yaml:"auth_plugin"` // 认证插件
	Privileges []UserPrivilege `yaml:"privileges"`  // 权限列表
	Host       string          `yaml:"host"`        // 允许的主机
	MaxConns   int             `yaml:"max_conns"`   // 最大连接数
	Active     bool            `yaml:"active"`      // 是否激活
	// contains filtered or unexported fields
}

User 用户信息

type UserManager

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

UserManager 用户管理器

func NewUserManager

func NewUserManager() *UserManager

NewUserManager 创建用户管理器

func (*UserManager) AddUser

func (m *UserManager) AddUser(user *User) error

AddUser 添加用户

func (*UserManager) Authenticate

func (m *UserManager) Authenticate(username, password string, authData []byte) error

Authenticate 认证用户

func (*UserManager) CheckPrivilege

func (m *UserManager) CheckPrivilege(username, database, table string, priv Privilege) bool

CheckPrivilege 检查用户权限

func (*UserManager) CreateDefaultUser

func (m *UserManager) CreateDefaultUser(username, password string) error

CreateDefaultUser 创建默认用户(用于初始化)

func (*UserManager) GetDefaultAuthPlugin

func (m *UserManager) GetDefaultAuthPlugin() AuthPlugin

GetDefaultAuthPlugin 获取默认认证插件

func (*UserManager) GetUser

func (m *UserManager) GetUser(username string) (*User, error)

GetUser 获取用户

func (*UserManager) GrantPrivilege

func (m *UserManager) GrantPrivilege(username string, priv UserPrivilege) error

GrantPrivilege 授予权限

func (*UserManager) ListUsers

func (m *UserManager) ListUsers() []*User

ListUsers 列出所有用户

func (*UserManager) RemoveUser

func (m *UserManager) RemoveUser(username string) error

RemoveUser 删除用户

func (*UserManager) RevokePrivilege

func (m *UserManager) RevokePrivilege(username string, priv Privilege, database, table string) error

RevokePrivilege 撤销权限

func (*UserManager) SetDefaultAuthPlugin

func (m *UserManager) SetDefaultAuthPlugin(plugin AuthPlugin)

SetDefaultAuthPlugin 设置默认认证插件

type UserPrivilege

type UserPrivilege struct {
	Privilege Privilege      `yaml:"privilege"` // 权限类型
	Level     PrivilegeLevel `yaml:"level"`     // 权限级别
	Database  string         `yaml:"database"`  // 数据库名(数据库级别)
	Table     string         `yaml:"table"`     // 表名(表级别)
}

UserPrivilege 用户权限

Jump to

Keyboard shortcuts

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