refactor(db): 重构数据库查询构建器以支持多数据库方言和标识符处理
- 实现了标识符处理器,统一处理表名、字段名的前缀添加和引号转换 - 添加对 MySQL、PostgreSQL、SQLite 三种数据库方言的支持 - 引入 ProcessTableName、ProcessColumn、ProcessConditionString 等方法处理标识符 - 为 HoTimeDB 添加 T() 和 C() 辅助方法用于手动构建 SQL 查询 - 重构 CRUD 操作中的表名和字段名处理逻辑,统一使用标识符处理器 - 添加完整的单元测试验证不同数据库方言下的标识符处理功能 - 优化 JOIN 操作中表名和条件字符串的处理方式
This commit is contained in:
@@ -4,10 +4,12 @@ import (
|
||||
"code.hoteas.com/golang/hotime/cache"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"database/sql"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/sirupsen/logrus"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// HoTimeDB 数据库操作核心结构体
|
||||
@@ -98,3 +100,48 @@ func (that *HoTimeDB) GetType() string {
|
||||
func (that *HoTimeDB) GetPrefix() string {
|
||||
return that.Prefix
|
||||
}
|
||||
|
||||
// GetProcessor 获取标识符处理器
|
||||
// 用于处理表名、字段名的前缀添加和引号转换
|
||||
func (that *HoTimeDB) GetProcessor() *IdentifierProcessor {
|
||||
return NewIdentifierProcessor(that.GetDialect(), that.Prefix)
|
||||
}
|
||||
|
||||
// T 辅助方法:获取带前缀和引号的表名
|
||||
// 用于手动构建 SQL 时使用
|
||||
// 示例: db.T("order") 返回 "`app_order`" (MySQL) 或 "\"app_order\"" (PostgreSQL)
|
||||
func (that *HoTimeDB) T(table string) string {
|
||||
return that.GetProcessor().ProcessTableName(table)
|
||||
}
|
||||
|
||||
// C 辅助方法:获取带前缀和引号的 table.column
|
||||
// 支持两种调用方式:
|
||||
// - db.C("order", "name") 返回 "`app_order`.`name`"
|
||||
// - db.C("order.name") 返回 "`app_order`.`name`"
|
||||
func (that *HoTimeDB) C(args ...string) string {
|
||||
if len(args) == 0 {
|
||||
return ""
|
||||
}
|
||||
if len(args) == 1 {
|
||||
return that.GetProcessor().ProcessColumn(args[0])
|
||||
}
|
||||
// 两个参数: table, column
|
||||
dialect := that.GetDialect()
|
||||
table := args[0]
|
||||
column := args[1]
|
||||
// 去除已有引号
|
||||
table = trimQuotes(table)
|
||||
column = trimQuotes(column)
|
||||
return dialect.QuoteIdentifier(that.Prefix+table) + "." + dialect.QuoteIdentifier(column)
|
||||
}
|
||||
|
||||
// trimQuotes 去除字符串两端的引号
|
||||
func trimQuotes(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) >= 2 {
|
||||
if (s[0] == '`' && s[len(s)-1] == '`') || (s[0] == '"' && s[len(s)-1] == '"') {
|
||||
return s[1 : len(s)-1]
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user