Compare commits

..

6 Commits

Author SHA1 Message Date
hoteas 6164dfe9bf feat(db): 实现多数据库方言与表名前缀支持功能
- 扩展 Dialect 接口,添加 QuoteIdentifier 和 QuoteChar 方法
- 新建 identifier.go,实现 IdentifierProcessor 及智能解析逻辑
- 在 db.go 中集成处理器,添加 T() 和 C() 辅助方法
- 修改 crud.go 中 Select/Insert/Update/Delete/buildJoin 等方法
- 修改 where.go 中 varCond 等条件处理方法
- 检查并更新 builder.go 相关功能
- 编写测试用例验证多数据库和前缀功能
- 移除调试日志文件以完成开发任务
2026-01-22 09:18:45 +08:00
hoteas 5ba883cd6b chore(example): 清理调试日志并优化测试代码
- 移除大量 debugLog 调试日志调用
- 修改数据库计数检查代码,使用下划线忽略返回值
- 更新事务测试中的变量声明,统一使用下划线忽略不需要的返回值
- 添加注释说明 admin 表数据检查的目的
- 移除条件查询语法测试中的冗余调试日志
- 优化链式查询测试中的调试信息
- 清理 JOIN 查询测试部分的日志输出
- 移除聚合函数测试中的调试日志
- 删除分页查询测试中的多余日志
- 清理批量插入测试中的调试信息
- 优化 upsert 测试部分的日志输出
- 移除事务测试中的冗余调试日志
- 删除原生 SQL 测试中的大量调试日志
- 移除 IN/NOT IN 数组测试中的 region 注释块
2026-01-22 07:25:41 +08:00
hoteas c2955d2500 feat(db): 实现数据库查询中的数组参数展开和空数组处理
- 在 Get 方法中添加无参数时的默认字段和 LIMIT 1 处理
- 实现 expandArrayPlaceholder 方法,自动展开 IN (?) 和 NOT IN (?) 中的数组参数
- 为空数组的 IN 条件生成 1=0 永假条件,NOT IN 生成 1=1 永真条件
- 在 queryWithRetry 和 execWithRetry 中集成数组占位符预处理
- 修复 where.go 中空切片条件的处理逻辑
- 添加完整的 IN/NOT IN 数组查询测试用例
- 更新 .gitignore 规则格式
2026-01-22 07:16:42 +08:00
hoteas 0e1775f72b remove(config): 移除配置相关JSON文件
- 删除 app.json 应用配置文件
- 删除 config.json 系统配置文件
- 删除 configNote.json 配置注释文件
- 删除 rule.json 规则配置文件
2026-01-22 06:12:26 +08:00
hoteas 1a9e7e19b7 chore(project): 更新 .gitignore 文件
- 添加 /example/config 到忽略列表中
- 防止配置文件被提交到版本控制中
2026-01-22 06:10:51 +08:00
hoteas 4828f3625c chore(config): 更新 .gitignore 配置
- 移除 /example/config/app.json 的忽略规则
- 移除 /example/config/ 目录的忽略规则
- 保留其他现有忽略配置不变
2026-01-22 06:09:19 +08:00
15 changed files with 768 additions and 1414 deletions
-392
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,208 @@
---
name: 多数据库方言与前缀支持
overview: 为 HoTimeDB ORM 实现完整的多数据库(MySQL/PostgreSQL/SQLite)方言支持和自动表前缀功能,同时保持完全向后兼容。
todos:
- id: dialect-interface
content: 扩展 Dialect 接口,添加 QuoteIdentifier 和 QuoteChar 方法
status: pending
- id: identifier-processor
content: 实现 IdentifierProcessor 结构体及其方法
status: pending
- id: db-integration
content: 在 HoTimeDB 中集成处理器,添加辅助方法
status: pending
- id: crud-update
content: 修改 crud.go 中的所有 CRUD 方法使用新处理器
status: pending
- id: where-update
content: 修改 where.go 中的条件处理逻辑
status: pending
- id: builder-update
content: 修改 builder.go 中的链式 JOIN 方法
status: pending
- id: testing
content: 测试多数据库和前缀功能
status: pending
---
# HoTimeDB 多数据库方言与自动前缀支持计划
## 目标
1. **多数据库方言支持**:让所有 ORM 方法正确支持 MySQL、PostgreSQL、SQLite 的标识符引号格式
2. **自动表前缀**:在主表、JOIN 表、WHERE/ON 条件中自动识别并添加表前缀
3. **完全向后兼容**:用户现有写法(`order.name`、`` `order`.name ``)无需修改
## 核心设计
### 标识符处理流程
```mermaid
flowchart TD
Input["用户输入: order.name 或 `order`.name"]
Parse["解析标识符"]
AddPrefix["添加表前缀"]
QuoteByDialect["根据数据库类型添加引号"]
Output["输出: `app_order`.`name` (MySQL) 或 \"app_order\".\"name\" (PG)"]
Input --> Parse
Parse --> AddPrefix
AddPrefix --> QuoteByDialect
QuoteByDialect --> Output
```
## 实现步骤
### 第1步:扩展 Dialect 接口([db/dialect.go](db/dialect.go)
在现有 `Dialect` 接口中添加新方法:
```go
// QuoteIdentifier 处理标识符(支持 table.column 格式)
// 输入: "order" 或 "order.name" 或 "`order`.name"
// 输出: 带正确引号的标识符
QuoteIdentifier(name string) string
// QuoteChar 获取引号字符(用于字符串中的替换检测)
QuoteChar() string
```
为三种数据库实现这些方法,核心逻辑:
- 去除已有的引号(支持反引号和双引号)
- 按点号分割,对每部分单独加引号
- MySQL 使用反引号,PostgreSQL/SQLite 使用双引号
### 第2步:添加标识符处理器([db/dialect.go](db/dialect.go)
新增 `IdentifierProcessor` 结构体:
```go
type IdentifierProcessor struct {
dialect Dialect
prefix string
}
// ProcessTableName 处理表名(添加前缀+引号)
func (p *IdentifierProcessor) ProcessTableName(name string) string
// ProcessColumn 处理字段名(table.column 格式,自动给表名加前缀)
func (p *IdentifierProcessor) ProcessColumn(name string) string
// ProcessCondition 处理 ON/WHERE 条件字符串中的 table.column
func (p *IdentifierProcessor) ProcessCondition(condition string) string
```
关键实现细节:
- 使用正则表达式识别条件字符串中的 `table.column` 模式
- 识别已有的引号包裹(`` `table`.column `` 或 `"table".column`
- 避免误处理字符串字面量中的内容
### 第3步:在 HoTimeDB 中集成处理器([db/db.go](db/db.go)
```go
// GetProcessor 获取标识符处理器(懒加载)
func (that *HoTimeDB) GetProcessor() *IdentifierProcessor
// processTable 内部方法:处理表名
func (that *HoTimeDB) processTable(table string) string
// processColumn 内部方法:处理字段名
func (that *HoTimeDB) processColumn(column string) string
```
### 第4步:修改 CRUD 方法([db/crud.go](db/crud.go)
需要修改的方法及位置:
| 方法 | 修改内容 |
|------|---------|
| `Select` (L77-153) | 表名、字段名处理 |
| `buildJoin` (L156-222) | JOIN 表名、ON 条件处理 |
| `Insert` (L248-302) | 表名、字段名处理 |
| `BatchInsert` (L316-388) | 表名、字段名处理 |
| `Update` (L598-638) | 表名、字段名处理 |
| `Delete` (L640-661) | 表名处理 |
核心改动模式(以 Select 为例):
```go
// 之前
query += " FROM `" + that.Prefix + table + "` "
// 之后
query += " FROM " + that.processTable(table) + " "
```
### 第5步:修改 WHERE 条件处理([db/where.go](db/where.go)
修改 `varCond` 方法(L205-338)中的字段名处理:
```go
// 之前
if !strings.Contains(k, ".") {
k = "`" + k + "`"
}
// 之后
k = that.processColumn(k)
```
同样修改 `handlePlainField``handleDefaultCondition` 等方法。
### 第6步:修改链式构建器([db/builder.go](db/builder.go)
`LeftJoin``RightJoin` 等方法中的表名和条件字符串也需要处理:
```go
func (that *HotimeDBBuilder) LeftJoin(table, joinStr string) *HotimeDBBuilder {
// 处理表名和 ON 条件
table = that.HoTimeDB.processTable(table)
joinStr = that.HoTimeDB.GetProcessor().ProcessCondition(joinStr)
that.Join(Map{"[>]" + table: joinStr})
return that
}
```
## 安全考虑
1. **避免误替换数据**:条件处理只处理 SQL 语法结构中的标识符,不处理:
- 字符串字面量内的内容(通过检测引号边界)
- 已经是占位符 `?` 的参数值
2. **正则表达式设计**:识别 `table.column` 模式时排除:
- 数字开头的标识符
- 函数调用如 `NOW()`
- 特殊运算符如 `>=``<=`
## 测试要点
1. 多数据库类型切换
2. 带前缀和不带前缀场景
3. 复杂 JOIN 查询
4. 嵌套条件查询
5. 特殊字符和保留字作为表名/字段名
## 文件修改清单
| 文件 | 修改类型 |
|------|---------|
| [db/dialect.go](db/dialect.go) | 扩展接口,添加 IdentifierProcessor |
| [db/db.go](db/db.go) | 添加 GetProcessor 和辅助方法 |
| [db/crud.go](db/crud.go) | 修改所有 CRUD 方法 |
| [db/where.go](db/where.go) | 修改条件处理逻辑 |
| [db/builder.go](db/builder.go) | 修改链式构建器的 JOIN 方法 |
@@ -0,0 +1,249 @@
---
name: 多数据库方言与前缀支持
overview: 为 HoTimeDB ORM 实现完整的多数据库(MySQL/PostgreSQL/SQLite)方言支持和自动表前缀功能,采用智能解析+辅助方法兜底的混合策略,保持完全向后兼容。
todos:
- id: dialect-interface
content: 扩展 Dialect 接口,添加 QuoteIdentifier 和 QuoteChar 方法
status: completed
- id: identifier-processor
content: 新建 identifier.go,实现 IdentifierProcessor 及智能解析逻辑
status: completed
- id: db-integration
content: 在 db.go 中集成处理器,添加 T() 和 C() 辅助方法
status: completed
- id: crud-update
content: 修改 crud.go 中 Select/Insert/Update/Delete/buildJoin 等方法
status: completed
- id: where-update
content: 修改 where.go 中 varCond 等条件处理方法
status: completed
- id: builder-check
content: 检查 builder.go 是否需要额外修改
status: completed
- id: testing
content: 编写测试用例验证多数据库和前缀功能
status: completed
- id: todo-1769037903242-d7aip6nh1
content: ""
status: pending
---
# HoTimeDB 多数据库方言与自动前缀支持计划(更新版)
## 目标
1. **多数据库方言支持**MySQL、PostgreSQL、SQLite 标识符引号自动转换
2. **自动表前缀**:主表、JOIN 表、ON/WHERE 条件中的表名自动添加前缀
3. **完全向后兼容**:用户现有写法无需修改
4. **辅助方法兜底**:边缘情况可用 `T()` / `C()` 精确控制
## 混合策略设计
### 各部分处理方式
| 位置 | 处理方式 | 准确度 | 说明 |
|------|---------|--------|------|
| 主表名 | 自动 | 100% | `Select("order")` 自动处理 |
| JOIN 表名 | 自动 | 100% | `[><]order` 中提取表名处理 |
| ON 条件字符串 | 智能解析 | ~95% | 正则匹配 `table.column` 模式 |
| WHERE 条件 Map | 自动 | 100% | Map 的 key 是结构化的 |
| SELECT 字段 | 智能解析 | ~95% | 同 ON 条件 |
### 辅助方法(兜底)
```go
db.T("order") // 返回 "`app_order`" (MySQL) 或 "\"app_order\"" (PG)
db.C("order", "name") // 返回 "`app_order`.`name`"
db.C("order.name") // 同上,支持点号格式
```
## 实现步骤
### 第1步:扩展 Dialect 接口([db/dialect.go](db/dialect.go)
添加新方法到 `Dialect` 接口:
```go
// QuoteIdentifier 处理单个标识符(去除已有引号,添加正确引号)
QuoteIdentifier(name string) string
// QuoteChar 返回引号字符
QuoteChar() string
```
三种方言实现:
- MySQL: 反引号 `` ` ``
- PostgreSQL/SQLite: 双引号 `"`
### 第2步:添加标识符处理器([db/identifier.go](db/identifier.go) 新文件)
```go
type IdentifierProcessor struct {
dialect Dialect
prefix string
}
// ProcessTableName 处理表名(添加前缀+引号)
// "order" → "`app_order`"
func (p *IdentifierProcessor) ProcessTableName(name string) string
// ProcessColumn 处理 table.column 格式
// "order.name" → "`app_order`.`name`"
// "`order`.name" → "`app_order`.`name`"
func (p *IdentifierProcessor) ProcessColumn(name string) string
// ProcessConditionString 智能解析条件字符串
// "user.id = order.user_id" → "`app_user`.`id` = `app_order`.`user_id`"
func (p *IdentifierProcessor) ProcessConditionString(condition string) string
// ProcessFieldList 处理字段列表字符串
// "order.id, user.name AS uname" → "`app_order`.`id`, `app_user`.`name` AS uname"
func (p *IdentifierProcessor) ProcessFieldList(fields string) string
```
**智能解析正则**
```go
// 匹配 table.column 模式,排除已有引号、函数调用等
// 模式: \b([a-zA-Z_][a-zA-Z0-9_]*)\.([a-zA-Z_][a-zA-Z0-9_]*)\b
// 排除: `table`.column, "table".column, FUNC(), 123.456
```
### 第3步:在 HoTimeDB 中集成([db/db.go](db/db.go)
```go
// processor 缓存
var processorOnce sync.Once
var processor *IdentifierProcessor
// GetProcessor 获取标识符处理器
func (that *HoTimeDB) GetProcessor() *IdentifierProcessor
// T 辅助方法:获取带前缀和引号的表名
func (that *HoTimeDB) T(table string) string
// C 辅助方法:获取带前缀和引号的 table.column
func (that *HoTimeDB) C(args ...string) string
```
### 第4步:修改 CRUD 方法([db/crud.go](db/crud.go)
**Select 方法改动**
```go
// L112-116 原代码
if !strings.Contains(table, ".") && !strings.Contains(table, " AS ") {
query += " FROM `" + that.Prefix + table + "` "
} else {
query += " FROM " + that.Prefix + table + " "
}
// 改为
query += " FROM " + that.GetProcessor().ProcessTableName(table) + " "
// 字段列表处理(L90-107
// 如果是字符串,调用 ProcessFieldList 处理
```
**buildJoin 方法改动**L156-222):
```go
// 原代码 L186-190
table := Substr(k, 3, len(k)-3)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " LEFT JOIN " + table + " ON " + v.(string) + " "
// 改为
table := Substr(k, 3, len(k)-3)
table = that.GetProcessor().ProcessTableName(table)
onCondition := that.GetProcessor().ProcessConditionString(v.(string))
query += " LEFT JOIN " + table + " ON " + onCondition + " "
```
**Insert/BatchInsert/Update/Delete** 同样修改表名和字段名处理。
### 第5步:修改 WHERE 条件处理([db/where.go](db/where.go)
**varCond 方法改动**(多处):
```go
// 原代码(多处出现)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
}
// 改为
k = that.GetProcessor().ProcessColumn(k)
```
需要修改的函数:
- `varCond` (L205-338)
- `handleDefaultCondition` (L340-368)
- `handlePlainField` (L370-400)
### 第6步:修改链式构建器([db/builder.go](db/builder.go)
**LeftJoin 等方法需要传递处理器**
由于 builder 持有 HoTimeDB 引用,可以直接使用:
```go
func (that *HotimeDBBuilder) LeftJoin(table, joinStr string) *HotimeDBBuilder {
// 不在这里处理,让 buildJoin 统一处理
that.Join(Map{"[>]" + table: joinStr})
return that
}
```
JOIN 的实际处理在 `crud.go``buildJoin` 中完成。
## 智能解析的边界处理
### 会自动处理的情况
- `user.id = order.user_id` → 正确处理
- `user.id=order.user_id` → 正确处理(无空格)
- `` `user`.id = order.user_id `` → 正确处理(混合格式)
- `user.id = order.user_id AND order.status = 1` → 正确处理
### 需要辅助方法的边缘情况
- 子查询中的表名
- 复杂 CASE WHEN 表达式
- 动态拼接的 SQL 片段
## 文件清单
| 文件 | 操作 | 说明 |
|------|------|------|
| [db/dialect.go](db/dialect.go) | 修改 | 扩展 Dialect 接口 |
| [db/identifier.go](db/identifier.go) | 新增 | IdentifierProcessor 实现 |
| [db/db.go](db/db.go) | 修改 | 集成处理器,添加 T()/C() 方法 |
| [db/crud.go](db/crud.go) | 修改 | 修改所有 CRUD 方法 |
| [db/where.go](db/where.go) | 修改 | 修改条件处理逻辑 |
| [db/builder.go](db/builder.go) | 检查 | 可能无需修改(buildJoin 统一处理)|
## 测试用例
1. **多数据库切换**MySQL → PostgreSQL → SQLite
2. **前缀场景**:有前缀 vs 无前缀
3. **复杂 JOIN**:多表 JOIN + 复杂 ON 条件
4. **混合写法**`order.name` + `` `user`.id `` 混用
5. **辅助方法**`T()``C()` 正确性
+5
View File
@@ -0,0 +1,5 @@
{
"setup-worktree": [
"npm install"
]
}
+2 -3
View File
@@ -1,6 +1,5 @@
/.idea/*
.idea
/example/config/app.json
/example/tpt/demo/
/example/config/
/*.exe
*.exe
/example/config
-19
View File
@@ -1,19 +0,0 @@
{
"flow": {},
"id": "d751713988987e9331980363e24189ce",
"label": "HoTime管理平台",
"labelConfig": {
"add": "添加",
"delete": "删除",
"download": "下载清单",
"edit": "编辑",
"info": "查看详情",
"show": "开启"
},
"menus": [],
"name": "admin",
"stop": [
"role",
"org"
]
}
-38
View File
@@ -1,38 +0,0 @@
{
"cache": {
"memory": {
"db": true,
"session": true,
"timeout": 7200
}
},
"codeConfig": [
{
"config": "config/app.json",
"mode": 0,
"name": "",
"rule": "config/rule.json",
"table": "admin"
}
],
"db": {
"sqlite": {
"path": "config/data.db"
}
},
"defFile": [
"index.html",
"index.htm"
],
"error": {
"1": "内部系统异常",
"2": "访问权限异常",
"3": "请求参数异常",
"4": "数据处理异常",
"5": "数据结果异常"
},
"mode": 2,
"port": "80",
"sessionName": "HOTIME",
"tpt": "tpt"
}
-79
View File
@@ -1,79 +0,0 @@
{
"cache": {
"db": {
"db": "默认false,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
"timeout": "默认60 * 60 * 24 * 30,非必须,过期时间,超时自动删除"
},
"memory": {
"db": "默认true,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
"timeout": "默认60 * 60 * 2,非必须,过期时间,超时自动删除"
},
"redis": {
"db": "默认true,非必须,缓存数据库,启用后能减少数据库的读写压力",
"host": "默认服务ip127.0.0.1,必须,如果需要使用redis服务时配置,",
"password": "默认密码空,必须,如果需要使用redis服务时配置,默认密码空",
"port": "默认服务端口:6379,必须,如果需要使用redis服务时配置,",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
"timeout": "默认60 * 60 * 24 * 15,非必须,过期时间,超时自动删除"
},
"注释": "可配置memorydbredis,默认启用memory,默认优先级为memory\u003eredis\u003edb,memory与数据库缓存设置项一致,缓存数据填充会自动反方向反哺,加入memory缓存过期将自动从redis更新,但memory永远不会更新redis,如果是集群建议不要开启memory,配置即启用"
},
"codeConfig": [
"注释:配置即启用,非必须,默认无",
{
"config": "默认config/app.json,必须,接口描述配置文件",
"configDB": "默认无,非必须,有则每次将数据库数据生成到此目录用于配置读写,无则不生成",
"mode": "默认0,非必须,0为内嵌代码模式,1为生成代码模式",
"name": "默认无,非必须,有则生成代码到此目录,无则采用缺省模式使用表名,如设置为:admin,将在admin目录生成包名为admin的代码",
"rule": "默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成",
"table": "默认admin,必须,根据数据库内当前表名做为用户生成数据"
}
],
"crossDomain": "默认空 非必须,空字符串为不开启,如果需要跨域设置,auto为智能开启所有网站允许跨域,http://www.baidu.com为指定域允许跨域",
"db": {
"mysql": {
"host": "默认127.0.0.1,必须,数据库ip地址",
"name": "默认test,必须,数据库名称",
"password": "默认root,必须,数据库密码",
"port": "默认3306,必须,数据库端口",
"prefix": "默认空,非必须,数据表前缀",
"slave": {
"host": "默认127.0.0.1,必须,数据库ip地址",
"name": "默认test,必须,数据库名称",
"password": "默认root,必须,数据库密码",
"port": "默认3306,必须,数据库端口",
"user": "默认root,必须,数据库用户名",
"注释": "从数据库配置,mysql里配置slave项即启用主从读写,减少数据库压力"
},
"user": "默认root,必须,数据库用户名",
"注释": "除prefix及主从数据库slave项,其他全部必须"
},
"sqlite": {
"path": "默认config/data.db,必须,数据库位置"
},
"注释": "配置即启用,非必须,默认使用sqlite数据库"
},
"defFile": "默认访问index.html或者index.htm文件,必须,默认访问文件类型",
"error": {
"1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用",
"2": "访问权限异常,没有登录或者登录异常等时候使用",
"3": "请求参数异常,request参数不满足要求,比如参数不足,参数类型错误,参数不满足要求等时候使用",
"4": "数据处理异常,数据库操作或者三方请求返回的结果非正常结果,比如数据库突然中断等时候使用",
"5": "数据结果异常,一般用于无法给出response要求的格式要求下使用,比如response需要的是string格式但你只能提供int数据时",
"注释": "web服务内置错误提示,自定义异常建议10开始"
},
"logFile": "无默认,非必须,如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"logLevel": "默认0,必须,0关闭,1打印,日志等级",
"mode": "默认0,非必须,0生产模式,1,测试模式,2开发模式,3内嵌代码模式,在开发模式下会显示更多的数据用于开发测试,并能够辅助研发,自动生成配置文件、代码等功能,web无缓存,数据库不启用缓存",
"modeRouterStrict": "默认false,必须,路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配",
"port": "默认80,必须,web服务开启Http端口,0为不启用http服务,默认80",
"sessionName": "默认HOTIME,必须,设置session的cookie名",
"tlsCert": "默认空,非必须,https证书",
"tlsKey": "默认空,非必须,https密钥",
"tlsPort": "默认空,非必须,web服务https端口,0为不启用https服务",
"tpt": "默认tpt,必须,web静态文件目录,默认为程序目录下tpt目录",
"webConnectLogFile": "无默认,非必须,webConnectLogShow开启之后才能使用,如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"webConnectLogShow": "默认true,非必须,访问日志如果需要web访问链接、访问ip、访问时间打印,false为关闭true开启此功能"
}
View File
-422
View File
@@ -1,422 +0,0 @@
[
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "idcard",
"strict": false,
"type": ""
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "id",
"strict": true,
"type": ""
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "sn",
"strict": false,
"type": ""
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "parent_ids",
"strict": true,
"type": "index"
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "index",
"strict": true,
"type": "index"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "parent_id",
"true": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "amount",
"strict": true,
"type": "money"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "info",
"strict": false,
"type": "textArea"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "status",
"strict": false,
"type": "select"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "state",
"strict": false,
"type": "select"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "sex",
"strict": false,
"type": "select"
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "delete",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "lat",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "lng",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "latitude",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "longitude",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": false,
"list": false,
"must": false,
"name": "password",
"strict": false,
"type": "password"
},
{
"add": true,
"edit": true,
"info": false,
"list": false,
"must": false,
"name": "pwd",
"strict": false,
"type": "password"
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "version",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "seq",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "sort",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "note",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "description",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "abstract",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "content",
"strict": false,
"type": "textArea"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "address",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "full_name",
"strict": false,
"type": ""
},
{
"add": false,
"edit": false,
"info": true,
"list": false,
"must": false,
"name": "create_time",
"strict": true,
"type": "time"
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "modify_time",
"strict": true,
"type": "time"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "image",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "img",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "avatar",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "icon",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "file",
"strict": false,
"type": "file"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "age",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "email",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "time",
"strict": false,
"type": "time"
},
{
"add": false,
"edit": false,
"info": true,
"list": false,
"must": false,
"name": "level",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "rule",
"strict": false,
"type": "form"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "auth",
"strict": false,
"type": "auth"
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "table",
"strict": false,
"type": "table"
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "table_id",
"strict": false,
"type": "table_id"
}
]
+6 -5
View File
@@ -223,15 +223,16 @@ func (that *HoTimeDB) buildJoin(joinData interface{}) string {
// Get 获取单条记录
func (that *HoTimeDB) Get(table string, qu ...interface{}) Map {
if len(qu) == 1 {
if len(qu) == 0 {
// 没有参数时,添加默认字段和 LIMIT
qu = append(qu, "*", Map{"LIMIT": 1})
} else if len(qu) == 1 {
qu = append(qu, Map{"LIMIT": 1})
}
if len(qu) == 2 {
} else if len(qu) == 2 {
temp := qu[1].(Map)
temp["LIMIT"] = 1
qu[1] = temp
}
if len(qu) == 3 {
} else if len(qu) == 3 {
temp := qu[2].(Map)
temp["LIMIT"] = 1
qu[2] = temp
+204 -1
View File
@@ -1,12 +1,13 @@
package db
import (
. "code.hoteas.com/golang/hotime/common"
"database/sql"
"encoding/json"
"errors"
"reflect"
"strings"
. "code.hoteas.com/golang/hotime/common"
)
// md5 生成查询的 MD5 哈希(用于缓存)
@@ -23,6 +24,9 @@ func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
// queryWithRetry 内部查询方法,支持重试标记
func (that *HoTimeDB) queryWithRetry(query string, retried bool, args ...interface{}) []Map {
// 预处理数组占位符 ?[]
query, args = that.expandArrayPlaceholder(query, args)
// 保存调试信息(加锁保护)
that.mu.Lock()
that.LastQuery = query
@@ -82,6 +86,9 @@ func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Erro
// execWithRetry 内部执行方法,支持重试标记
func (that *HoTimeDB) execWithRetry(query string, retried bool, args ...interface{}) (sql.Result, *Error) {
// 预处理数组占位符 ?[]
query, args = that.expandArrayPlaceholder(query, args)
// 保存调试信息(加锁保护)
that.mu.Lock()
that.LastQuery = query
@@ -155,6 +162,202 @@ func (that *HoTimeDB) processArgs(args []interface{}) []interface{} {
return processedArgs
}
// expandArrayPlaceholder 展开 IN (?) / NOT IN (?) 中的数组参数
// 自动识别 IN/NOT IN (?) 模式,当参数是数组时展开为多个 ?
//
// 示例:
//
// db.Query("SELECT * FROM user WHERE id IN (?)", []int{1, 2, 3})
// // 展开为: SELECT * FROM user WHERE id IN (?, ?, ?) 参数: [1, 2, 3]
//
// db.Query("SELECT * FROM user WHERE id IN (?)", []int{})
// // 展开为: SELECT * FROM user WHERE 1=0 参数: [] (空集合的IN永假)
//
// db.Query("SELECT * FROM user WHERE id NOT IN (?)", []int{})
// // 展开为: SELECT * FROM user WHERE 1=1 参数: [] (空集合的NOT IN永真)
//
// db.Query("SELECT * FROM user WHERE id = ?", 1)
// // 保持不变: SELECT * FROM user WHERE id = ? 参数: [1]
func (that *HoTimeDB) expandArrayPlaceholder(query string, args []interface{}) (string, []interface{}) {
if len(args) == 0 || !strings.Contains(query, "?") {
return query, args
}
// 检查是否有数组参数
hasArray := false
for _, arg := range args {
if arg == nil {
continue
}
argType := reflect.ValueOf(arg).Type().String()
if strings.Contains(argType, "[]") || strings.Contains(argType, "Slice") {
hasArray = true
break
}
}
if !hasArray {
return query, args
}
newArgs := make([]interface{}, 0, len(args))
result := strings.Builder{}
argIndex := 0
for i := 0; i < len(query); i++ {
if query[i] == '?' && argIndex < len(args) {
arg := args[argIndex]
argIndex++
if arg == nil {
result.WriteByte('?')
newArgs = append(newArgs, nil)
continue
}
argType := reflect.ValueOf(arg).Type().String()
if strings.Contains(argType, "[]") || strings.Contains(argType, "Slice") {
// 是数组参数,检查是否在 IN (...) 或 NOT IN (...) 中
prevPart := result.String()
prevUpper := strings.ToUpper(prevPart)
// 查找最近的 NOT IN ( 模式
notInIndex := strings.LastIndex(prevUpper, " NOT IN (")
notInIndex2 := strings.LastIndex(prevUpper, " NOT IN(")
if notInIndex2 > notInIndex {
notInIndex = notInIndex2
}
// 查找最近的 IN ( 模式(但要排除 NOT IN 的情况)
inIndex := strings.LastIndex(prevUpper, " IN (")
inIndex2 := strings.LastIndex(prevUpper, " IN(")
if inIndex2 > inIndex {
inIndex = inIndex2
}
// 判断是 NOT IN 还是 IN
// 注意:" NOT IN (" 包含 " IN (",所以如果找到的 IN 位置在 NOT IN 范围内,应该优先判断为 NOT IN
isNotIn := false
matchIndex := -1
if notInIndex != -1 {
// 检查 inIndex 是否在 notInIndex 范围内(即 NOT IN 的 IN 部分)
// NOT IN ( 的 IN ( 部分从 notInIndex + 4 开始
if inIndex != -1 && inIndex >= notInIndex && inIndex <= notInIndex+5 {
// inIndex 是 NOT IN 的一部分,使用 NOT IN
isNotIn = true
matchIndex = notInIndex
} else if inIndex == -1 || notInIndex > inIndex {
// 没有独立的 IN,或 NOT IN 在 IN 之后
isNotIn = true
matchIndex = notInIndex
} else {
// 有独立的 IN 且在 NOT IN 之后
matchIndex = inIndex
}
} else if inIndex != -1 {
matchIndex = inIndex
}
// 检查 IN ( 后面是否只有空格(即当前 ? 紧跟在 IN ( 后面)
isInPattern := false
if matchIndex != -1 {
afterIn := prevPart[matchIndex:]
// 找到 ( 的位置
parenIdx := strings.Index(afterIn, "(")
if parenIdx != -1 {
afterParen := strings.TrimSpace(afterIn[parenIdx+1:])
if afterParen == "" {
isInPattern = true
}
}
}
if isInPattern {
// 在 IN (...) 或 NOT IN (...) 模式中
argList := ObjToSlice(arg)
if len(argList) == 0 {
// 空数组处理:需要找到字段名的开始位置
// 往前找最近的 AND/OR/WHERE/(,以确定条件的开始位置
truncateIndex := matchIndex
searchPart := prevUpper[:matchIndex]
// 找最近的分隔符位置
andIdx := strings.LastIndex(searchPart, " AND ")
orIdx := strings.LastIndex(searchPart, " OR ")
whereIdx := strings.LastIndex(searchPart, " WHERE ")
parenIdx := strings.LastIndex(searchPart, "(")
// 取最靠后的分隔符
sepIndex := -1
sepLen := 0
if andIdx > sepIndex {
sepIndex = andIdx
sepLen = 5 // " AND "
}
if orIdx > sepIndex {
sepIndex = orIdx
sepLen = 4 // " OR "
}
if whereIdx > sepIndex {
sepIndex = whereIdx
sepLen = 7 // " WHERE "
}
if parenIdx > sepIndex {
sepIndex = parenIdx
sepLen = 1 // "("
}
if sepIndex != -1 {
truncateIndex = sepIndex + sepLen
}
result.Reset()
result.WriteString(prevPart[:truncateIndex])
if isNotIn {
// NOT IN 空集合 = 永真
result.WriteString(" 1=1 ")
} else {
// IN 空集合 = 永假
result.WriteString(" 1=0 ")
}
// 跳过后面的 )
for j := i + 1; j < len(query); j++ {
if query[j] == ')' {
i = j
break
}
}
} else if len(argList) == 1 {
// 单元素数组
result.WriteByte('?')
newArgs = append(newArgs, argList[0])
} else {
// 多元素数组,展开为多个 ?
for j := 0; j < len(argList); j++ {
if j > 0 {
result.WriteString(", ")
}
result.WriteByte('?')
newArgs = append(newArgs, argList[j])
}
}
} else {
// 不在 IN 模式中,保持原有行为(数组会被 processArgs 转为逗号字符串)
result.WriteByte('?')
newArgs = append(newArgs, arg)
}
} else {
// 非数组参数
result.WriteByte('?')
newArgs = append(newArgs, arg)
}
} else {
result.WriteByte(query[i])
}
}
return result.String(), newArgs
}
// Row 数据库数据解析
func (that *HoTimeDB) Row(resl *sql.Rows) []Map {
dest := make([]Map, 0)
-332
View File
@@ -1,332 +0,0 @@
-- HoTimeDB 测试表结构
-- 用于测试和示例的MySQL表结构定义
-- 请根据实际需要修改表结构和字段类型
-- 创建数据库(可选)
CREATE DATABASE IF NOT EXISTS `hotimedb_test` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `hotimedb_test`;
-- 用户表
DROP TABLE IF EXISTS `app_user`;
CREATE TABLE `app_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '用户姓名',
`email` varchar(255) NOT NULL DEFAULT '' COMMENT '邮箱地址',
`password` varchar(255) NOT NULL DEFAULT '' COMMENT '密码hash',
`phone` varchar(20) NOT NULL DEFAULT '' COMMENT '手机号',
`age` int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
`gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别 0-未知 1-男 2-女',
`avatar` varchar(500) NOT NULL DEFAULT '' COMMENT '头像URL',
`level` varchar(20) NOT NULL DEFAULT 'normal' COMMENT '用户等级 normal-普通 vip-会员 svip-超级会员',
`balance` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '账户余额',
`login_count` int(11) NOT NULL DEFAULT '0' COMMENT '登录次数',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-正常 0-禁用 -1-删除',
`last_login` datetime DEFAULT NULL COMMENT '最后登录时间',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_email` (`email`),
KEY `idx_status` (`status`),
KEY `idx_level` (`level`),
KEY `idx_created_time` (`created_time`),
KEY `idx_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
-- 用户资料表
DROP TABLE IF EXISTS `app_profile`;
CREATE TABLE `app_profile` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`real_name` varchar(50) NOT NULL DEFAULT '' COMMENT '真实姓名',
`id_card` varchar(20) NOT NULL DEFAULT '' COMMENT '身份证号',
`address` varchar(500) NOT NULL DEFAULT '' COMMENT '地址',
`bio` text COMMENT '个人简介',
`verified` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否认证 1-是 0-否',
`preferences` json DEFAULT NULL COMMENT '用户偏好设置JSON',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_id` (`user_id`),
KEY `idx_verified` (`verified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户资料表';
-- 部门表
DROP TABLE IF EXISTS `app_department`;
CREATE TABLE `app_department` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '部门ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '部门名称',
`parent_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '上级部门ID',
`manager_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '部门经理ID',
`description` text COMMENT '部门描述',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-正常 0-禁用',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_parent_id` (`parent_id`),
KEY `idx_manager_id` (`manager_id`),
KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='部门表';
-- 商品表
DROP TABLE IF EXISTS `app_product`;
CREATE TABLE `app_product` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`title` varchar(200) NOT NULL DEFAULT '' COMMENT '商品标题',
`description` text COMMENT '商品描述',
`price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '商品价格',
`stock` int(11) NOT NULL DEFAULT '0' COMMENT '库存数量',
`category_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '分类ID',
`brand` varchar(100) NOT NULL DEFAULT '' COMMENT '品牌',
`tags` varchar(500) NOT NULL DEFAULT '' COMMENT '标签,逗号分隔',
`images` json DEFAULT NULL COMMENT '商品图片JSON数组',
`attributes` json DEFAULT NULL COMMENT '商品属性JSON',
`sales_count` int(11) NOT NULL DEFAULT '0' COMMENT '销售数量',
`view_count` int(11) NOT NULL DEFAULT '0' COMMENT '浏览数量',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-上架 0-下架',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_category_id` (`category_id`),
KEY `idx_price` (`price`),
KEY `idx_status` (`status`),
KEY `idx_created_time` (`created_time`),
FULLTEXT KEY `ft_title_description` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品表';
-- 订单表
DROP TABLE IF EXISTS `app_order`;
CREATE TABLE `app_order` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`order_no` varchar(50) NOT NULL DEFAULT '' COMMENT '订单号',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`product_id` bigint(20) unsigned NOT NULL COMMENT '商品ID',
`quantity` int(11) NOT NULL DEFAULT '1' COMMENT '数量',
`price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '单价',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总金额',
`discount_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '优惠金额',
`final_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '实付金额',
`status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT '订单状态 pending-待付款 paid-已付款 shipped-已发货 completed-已完成 cancelled-已取消',
`payment_method` varchar(20) NOT NULL DEFAULT '' COMMENT '支付方式',
`shipping_address` json DEFAULT NULL COMMENT '收货地址JSON',
`remark` text COMMENT '订单备注',
`paid_time` datetime DEFAULT NULL COMMENT '支付时间',
`shipped_time` datetime DEFAULT NULL COMMENT '发货时间',
`completed_time` datetime DEFAULT NULL COMMENT '完成时间',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_order_no` (`order_no`),
KEY `idx_user_id` (`user_id`),
KEY `idx_product_id` (`product_id`),
KEY `idx_status` (`status`),
KEY `idx_created_time` (`created_time`),
KEY `idx_paid_time` (`paid_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';
-- 订单详情表
DROP TABLE IF EXISTS `app_order_detail`;
CREATE TABLE `app_order_detail` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`order_id` bigint(20) unsigned NOT NULL COMMENT '订单ID',
`product_id` bigint(20) unsigned NOT NULL COMMENT '商品ID',
`product_title` varchar(200) NOT NULL DEFAULT '' COMMENT '商品标题',
`product_image` varchar(500) NOT NULL DEFAULT '' COMMENT '商品图片',
`price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '单价',
`quantity` int(11) NOT NULL DEFAULT '1' COMMENT '数量',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '小计',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单详情表';
-- 支付日志表
DROP TABLE IF EXISTS `app_payment_log`;
CREATE TABLE `app_payment_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`order_id` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID',
`transaction_id` varchar(100) NOT NULL DEFAULT '' COMMENT '交易ID',
`type` varchar(20) NOT NULL DEFAULT '' COMMENT '类型 order_payment-订单支付 recharge-充值 refund-退款',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '金额',
`method` varchar(20) NOT NULL DEFAULT '' COMMENT '支付方式 balance-余额 alipay-支付宝 wechat-微信',
`status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT '状态 pending-处理中 success-成功 failed-失败',
`description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`extra_data` json DEFAULT NULL COMMENT '额外数据JSON',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_transaction_id` (`transaction_id`),
KEY `idx_type` (`type`),
KEY `idx_status` (`status`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付日志表';
-- 转账日志表
DROP TABLE IF EXISTS `app_transfer_log`;
CREATE TABLE `app_transfer_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`from_user_id` bigint(20) unsigned NOT NULL COMMENT '转出用户ID',
`to_user_id` bigint(20) unsigned NOT NULL COMMENT '转入用户ID',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '转账金额',
`type` varchar(20) NOT NULL DEFAULT 'transfer' COMMENT '类型',
`status` varchar(20) NOT NULL DEFAULT 'success' COMMENT '状态',
`description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_from_user_id` (`from_user_id`),
KEY `idx_to_user_id` (`to_user_id`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='转账日志表';
-- 操作日志表
DROP TABLE IF EXISTS `app_operation_log`;
CREATE TABLE `app_operation_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
`module` varchar(50) NOT NULL DEFAULT '' COMMENT '模块',
`action` varchar(50) NOT NULL DEFAULT '' COMMENT '操作',
`description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`ip` varchar(45) NOT NULL DEFAULT '' COMMENT 'IP地址',
`user_agent` varchar(500) NOT NULL DEFAULT '' COMMENT '用户代理',
`request_data` json DEFAULT NULL COMMENT '请求数据JSON',
`response_data` json DEFAULT NULL COMMENT '响应数据JSON',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-成功 0-失败',
`execution_time` int(11) NOT NULL DEFAULT '0' COMMENT '执行时间(毫秒)',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_module` (`module`),
KEY `idx_action` (`action`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';
-- 缓存表(HoTimeDB内置缓存使用)
DROP TABLE IF EXISTS `app_cached`;
CREATE TABLE `app_cached` (
`key` varchar(255) NOT NULL COMMENT '缓存键',
`value` longtext COMMENT '缓存值',
`expire_time` datetime DEFAULT NULL COMMENT '过期时间',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`key`),
KEY `idx_expire_time` (`expire_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='缓存表';
-- 批量用户表(用于批量操作示例)
DROP TABLE IF EXISTS `app_user_batch`;
CREATE TABLE `app_user_batch` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '用户姓名',
`email` varchar(255) NOT NULL DEFAULT '' COMMENT '邮箱地址',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='批量用户表';
-- 插入测试数据
INSERT INTO `app_user` (`name`, `email`, `password`, `age`, `level`, `balance`, `status`, `created_time`) VALUES
('张三', 'zhangsan@example.com', 'hashed_password_1', 25, 'normal', 1000.00, 1, '2023-01-15 10:30:00'),
('李四', 'lisi@example.com', 'hashed_password_2', 30, 'vip', 5000.00, 1, '2023-02-20 14:20:00'),
('王五', 'wangwu@example.com', 'hashed_password_3', 28, 'svip', 10000.00, 1, '2023-03-10 16:45:00'),
('赵六', 'zhaoliu@example.com', 'hashed_password_4', 35, 'normal', 500.00, 1, '2023-04-05 09:15:00'),
('钱七', 'qianqi@example.com', 'hashed_password_5', 22, 'vip', 2500.00, 0, '2023-05-12 11:30:00');
INSERT INTO `app_profile` (`user_id`, `real_name`, `verified`) VALUES
(1, '张三', 1),
(2, '李四', 1),
(3, '王五', 1),
(4, '赵六', 0),
(5, '钱七', 0);
INSERT INTO `app_department` (`name`, `parent_id`, `description`) VALUES
('技术部', 0, '负责技术开发和维护'),
('产品部', 0, '负责产品设计和规划'),
('市场部', 0, '负责市场推广和销售'),
('前端组', 1, '负责前端开发'),
('后端组', 1, '负责后端开发');
INSERT INTO `app_product` (`title`, `description`, `price`, `stock`, `category_id`, `brand`, `sales_count`) VALUES
('苹果手机', '最新款苹果手机,性能强劲', 6999.00, 100, 1, '苹果', 50),
('华为手机', '国产精品手机,拍照出色', 4999.00, 200, 1, '华为', 80),
('小米手机', '性价比之王,配置丰富', 2999.00, 300, 1, '小米', 120),
('联想笔记本', '商务办公首选,稳定可靠', 5999.00, 50, 2, '联想', 30),
('戴尔笔记本', '游戏性能出色,散热良好', 8999.00, 30, 2, '戴尔', 15);
INSERT INTO `app_order` (`order_no`, `user_id`, `product_id`, `quantity`, `price`, `amount`, `final_amount`, `status`, `created_time`) VALUES
('ORD202301150001', 1, 1, 1, 6999.00, 6999.00, 6999.00, 'paid', '2023-01-15 15:30:00'),
('ORD202301160001', 2, 2, 2, 4999.00, 9998.00, 9998.00, 'paid', '2023-01-16 10:20:00'),
('ORD202301170001', 3, 3, 1, 2999.00, 2999.00, 2999.00, 'completed', '2023-01-17 14:15:00'),
('ORD202301180001', 1, 4, 1, 5999.00, 5999.00, 5999.00, 'pending', '2023-01-18 16:45:00'),
('ORD202301190001', 4, 5, 1, 8999.00, 8999.00, 8999.00, 'cancelled', '2023-01-19 11:30:00');
INSERT INTO `app_order_detail` (`order_id`, `product_id`, `product_title`, `price`, `quantity`, `amount`) VALUES
(1, 1, '苹果手机', 6999.00, 1, 6999.00),
(2, 2, '华为手机', 4999.00, 2, 9998.00),
(3, 3, '小米手机', 2999.00, 1, 2999.00),
(4, 4, '联想笔记本', 5999.00, 1, 5999.00),
(5, 5, '戴尔笔记本', 8999.00, 1, 8999.00);
INSERT INTO `app_payment_log` (`user_id`, `order_id`, `type`, `amount`, `method`, `status`, `description`) VALUES
(1, 1, 'order_payment', 6999.00, 'balance', 'success', '订单支付'),
(2, 2, 'order_payment', 9998.00, 'alipay', 'success', '订单支付'),
(3, 3, 'order_payment', 2999.00, 'wechat', 'success', '订单支付'),
(2, NULL, 'recharge', 10000.00, 'alipay', 'success', '账户充值'),
(3, NULL, 'recharge', 5000.00, 'wechat', 'success', '账户充值');
-- 创建索引优化查询性能
CREATE INDEX idx_user_email_status ON app_user(email, status);
CREATE INDEX idx_order_user_status ON app_order(user_id, status);
CREATE INDEX idx_order_created_status ON app_order(created_time, status);
CREATE INDEX idx_product_category_status ON app_product(category_id, status);
-- 创建视图(可选)
CREATE OR REPLACE VIEW v_user_order_stats AS
SELECT
u.id as user_id,
u.name as user_name,
u.email,
u.level,
COUNT(o.id) as order_count,
COALESCE(SUM(o.final_amount), 0) as total_amount,
COALESCE(AVG(o.final_amount), 0) as avg_amount,
MAX(o.created_time) as last_order_time
FROM app_user u
LEFT JOIN app_order o ON u.id = o.user_id AND o.status IN ('paid', 'completed')
WHERE u.status = 1
GROUP BY u.id;
-- 存储过程示例(可选)
DELIMITER //
CREATE PROCEDURE GetUserOrderSummary(IN p_user_id BIGINT)
BEGIN
SELECT
u.name,
u.email,
u.level,
u.balance,
COUNT(o.id) as order_count,
COALESCE(SUM(CASE WHEN o.status = 'paid' THEN o.final_amount END), 0) as paid_amount,
COALESCE(SUM(CASE WHEN o.status = 'completed' THEN o.final_amount END), 0) as completed_amount
FROM app_user u
LEFT JOIN app_order o ON u.id = o.user_id
WHERE u.id = p_user_id AND u.status = 1
GROUP BY u.id;
END //
DELIMITER ;
-- 显示表结构信息
SELECT
TABLE_NAME as '表名',
TABLE_COMMENT as '表注释',
TABLE_ROWS as '预估行数',
ROUND(DATA_LENGTH/1024/1024, 2) as '数据大小(MB)'
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'app_%'
ORDER BY TABLE_NAME;
+31 -3
View File
@@ -90,10 +90,29 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
}
// 处理普通条件字段
// 空切片的 IN 条件应该生成永假条件(1=0),而不是跳过
if v != nil && reflect.ValueOf(v).Type().String() == "common.Slice" && len(v.(Slice)) == 0 {
// 检查是否是 NOT IN(带 [!] 后缀)- NOT IN 空数组永真,跳过即可
if !strings.HasSuffix(k, "[!]") {
// IN 空数组 -> 生成永假条件
if normalCondCount > 0 {
where += " AND "
}
where += "1=0 "
normalCondCount++
}
continue
}
if v != nil && strings.Contains(reflect.ValueOf(v).Type().String(), "[]") && len(ObjToSlice(v)) == 0 {
// 检查是否是 NOT IN(带 [!] 后缀)- NOT IN 空数组永真,跳过即可
if !strings.HasSuffix(k, "[!]") {
// IN 空数组 -> 生成永假条件
if normalCondCount > 0 {
where += " AND "
}
where += "1=0 "
normalCondCount++
}
continue
}
@@ -110,17 +129,22 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
}
// 添加 WHERE 关键字
if len(where) != 0 {
// 先去除首尾空格,检查是否有实际条件内容
trimmedWhere := strings.TrimSpace(where)
if len(trimmedWhere) != 0 {
hasWhere := true
for _, v := range vcond {
if strings.Index(where, v) == 0 {
if strings.Index(trimmedWhere, v) == 0 {
hasWhere = false
}
}
if hasWhere {
where = " WHERE " + where + " "
where = " WHERE " + trimmedWhere + " "
}
} else {
// 没有实际条件内容,重置 where
where = ""
}
// 处理特殊字符(按固定顺序:GROUP, HAVING, ORDER, LIMIT, OFFSET
@@ -322,6 +346,8 @@ func (that *HoTimeDB) handleDefaultCondition(k string, v interface{}, where stri
if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
vs := ObjToSlice(v)
if len(vs) == 0 {
// IN 空数组 -> 生成永假条件
where += "1=0 "
return where, res
}
@@ -352,6 +378,8 @@ func (that *HoTimeDB) handlePlainField(k string, v interface{}, where string, re
} else if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
vs := ObjToSlice(v)
if len(vs) == 0 {
// IN 空数组 -> 生成永假条件
where += "1=0 "
return where, res
}
+63 -120
View File
@@ -1,9 +1,7 @@
package main
import (
"encoding/json"
"fmt"
"os"
"time"
. "code.hoteas.com/golang/hotime"
@@ -11,33 +9,7 @@ import (
. "code.hoteas.com/golang/hotime/db"
)
// 调试日志文件路径
const debugLogPath = `d:\work\hotimev1\.cursor\debug.log`
// debugLog 写入调试日志
func debugLog(location, message string, data interface{}, hypothesisId string) {
// #region agent log
logEntry := Map{
"location": location,
"message": message,
"data": data,
"timestamp": time.Now().UnixMilli(),
"sessionId": "debug-session",
"runId": "hotimedb-test-run",
"hypothesisId": hypothesisId,
}
jsonBytes, _ := json.Marshal(logEntry)
f, err := os.OpenFile(debugLogPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err == nil {
f.WriteString(string(jsonBytes) + "\n")
f.Close()
}
// #endregion
}
func main() {
debugLog("main.go:35", "开始 HoTimeDB 全功能测试", nil, "START")
appIns := Init("config/config.json")
appIns.SetConnectListener(func(that *Context) (isFinished bool) {
return isFinished
@@ -49,7 +21,6 @@ func main() {
// 测试入口 - 运行所有测试
"all": func(that *Context) {
results := Map{}
debugLog("main.go:48", "开始所有测试", nil, "ALL_TESTS")
// 初始化测试表
initTestTables(that)
@@ -84,16 +55,13 @@ func main() {
// 10. 原生 SQL 测试
results["10_raw_sql"] = testRawSQL(that)
debugLog("main.go:80", "所有测试完成", results, "ALL_TESTS_DONE")
that.Display(0, results)
},
// 查询数据库表结构
"tables": func(that *Context) {
debugLog("main.go:tables", "查询数据库表结构", nil, "TABLES")
// 查询所有表
tables := that.Db.Query("SHOW TABLES")
debugLog("main.go:tables", "表列表", tables, "TABLES")
that.Display(0, Map{"tables": tables})
},
@@ -108,7 +76,6 @@ func main() {
columns := that.Db.Query("DESCRIBE " + tableName)
// 查询表数据(前10条)
data := that.Db.Select(tableName, Map{"LIMIT": 10})
debugLog("main.go:describe", "表结构", Map{"table": tableName, "columns": columns, "data": data}, "DESCRIBE")
that.Display(0, Map{"table": tableName, "columns": columns, "sample_data": data})
},
@@ -140,15 +107,9 @@ func initTestTables(that *Context) {
create_time DATETIME
)`)
// 检查 admin 表数据
adminCount := that.Db.Count("admin")
articleCount := that.Db.Count("article")
debugLog("main.go:init", "MySQL数据库初始化检查完成", Map{
"adminCount": adminCount,
"articleCount": articleCount,
"dbType": "MySQL",
}, "INIT")
// 检查 admin 表数据(确认表存在)
_ = that.Db.Count("admin")
_ = that.Db.Count("article")
}
// ==================== 1. 基础 CRUD 测试 ====================
@@ -156,8 +117,6 @@ func testBasicCRUD(that *Context) Map {
result := Map{"name": "基础CRUD测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:103", "开始基础 CRUD 测试 (MySQL)", nil, "H1_CRUD")
// 1.1 Insert 测试 - 使用 admin 表
insertTest := Map{"name": "Insert 插入测试 (admin表)"}
adminId := that.Db.Insert("admin", Map{
@@ -173,7 +132,6 @@ func testBasicCRUD(that *Context) Map {
insertTest["result"] = adminId > 0
insertTest["adminId"] = adminId
insertTest["lastQuery"] = that.Db.LastQuery
debugLog("main.go:118", "Insert 测试", Map{"adminId": adminId, "success": adminId > 0, "query": that.Db.LastQuery}, "H1_INSERT")
tests = append(tests, insertTest)
// 1.2 Get 测试
@@ -181,7 +139,6 @@ func testBasicCRUD(that *Context) Map {
admin := that.Db.Get("admin", "*", Map{"id": adminId})
getTest["result"] = admin != nil && admin.GetInt64("id") == adminId
getTest["admin"] = admin
debugLog("main.go:126", "Get 测试", Map{"admin": admin, "success": admin != nil}, "H1_GET")
tests = append(tests, getTest)
// 1.3 Select 测试 - 单条件
@@ -189,7 +146,6 @@ func testBasicCRUD(that *Context) Map {
admins1 := that.Db.Select("admin", "*", Map{"state": 1, "LIMIT": 5})
selectTest1["result"] = len(admins1) >= 0 // 可能表中没有数据
selectTest1["count"] = len(admins1)
debugLog("main.go:134", "Select 单条件测试", Map{"count": len(admins1)}, "H1_SELECT1")
tests = append(tests, selectTest1)
// 1.4 Select 测试 - 多条件(自动 AND)
@@ -203,7 +159,6 @@ func testBasicCRUD(that *Context) Map {
selectTest2["result"] = true // 只要不报错就算成功
selectTest2["count"] = len(admins2)
selectTest2["lastQuery"] = that.Db.LastQuery
debugLog("main.go:149", "Select 多条件自动AND测试", Map{"count": len(admins2), "query": that.Db.LastQuery}, "H1_SELECT2")
tests = append(tests, selectTest2)
// 1.5 Update 测试
@@ -214,7 +169,6 @@ func testBasicCRUD(that *Context) Map {
}, Map{"id": adminId})
updateTest["result"] = affected > 0
updateTest["affected"] = affected
debugLog("main.go:160", "Update 测试", Map{"affected": affected}, "H1_UPDATE")
tests = append(tests, updateTest)
// 1.6 Delete 测试 - 使用 test_batch 表
@@ -229,7 +183,6 @@ func testBasicCRUD(that *Context) Map {
deleteAffected := that.Db.Delete("test_batch", Map{"id": tempId})
deleteTest["result"] = deleteAffected > 0
deleteTest["affected"] = deleteAffected
debugLog("main.go:175", "Delete 测试", Map{"affected": deleteAffected}, "H1_DELETE")
tests = append(tests, deleteTest)
result["tests"] = tests
@@ -242,14 +195,11 @@ func testConditionSyntax(that *Context) Map {
result := Map{"name": "条件查询语法测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:188", "开始条件查询语法测试 (MySQL)", nil, "H2_CONDITION")
// 2.1 等于 (=) - 使用 article 表
test1 := Map{"name": "等于条件 (=)"}
articles1 := that.Db.Select("article", "id,title", Map{"state": 0, "LIMIT": 3})
test1["result"] = true
test1["count"] = len(articles1)
debugLog("main.go:195", "等于条件测试", Map{"count": len(articles1)}, "H2_EQUAL")
tests = append(tests, test1)
// 2.2 不等于 ([!])
@@ -258,7 +208,6 @@ func testConditionSyntax(that *Context) Map {
test2["result"] = true
test2["count"] = len(articles2)
test2["lastQuery"] = that.Db.LastQuery
debugLog("main.go:204", "不等于条件测试", Map{"count": len(articles2), "query": that.Db.LastQuery}, "H2_NOT_EQUAL")
tests = append(tests, test2)
// 2.3 大于 ([>]) 和 小于 ([<])
@@ -270,7 +219,6 @@ func testConditionSyntax(that *Context) Map {
})
test3["result"] = true
test3["count"] = len(articles3)
debugLog("main.go:216", "大于小于条件测试", Map{"count": len(articles3)}, "H2_GREATER_LESS")
tests = append(tests, test3)
// 2.4 大于等于 ([>=]) 和 小于等于 ([<=])
@@ -282,7 +230,6 @@ func testConditionSyntax(that *Context) Map {
})
test4["result"] = true
test4["count"] = len(articles4)
debugLog("main.go:228", "大于等于小于等于条件测试", Map{"count": len(articles4)}, "H2_GTE_LTE")
tests = append(tests, test4)
// 2.5 LIKE 模糊查询 ([~])
@@ -291,7 +238,6 @@ func testConditionSyntax(that *Context) Map {
test5["result"] = true
test5["count"] = len(articles5)
test5["lastQuery"] = that.Db.LastQuery
debugLog("main.go:237", "LIKE 模糊查询测试", Map{"count": len(articles5), "query": that.Db.LastQuery}, "H2_LIKE")
tests = append(tests, test5)
// 2.6 右模糊 ([~!])
@@ -299,7 +245,6 @@ func testConditionSyntax(that *Context) Map {
articles6 := that.Db.Select("admin", "id,name", Map{"name[~!]": "管理", "LIMIT": 3})
test6["result"] = true
test6["count"] = len(articles6)
debugLog("main.go:245", "右模糊查询测试", Map{"count": len(articles6)}, "H2_LIKE_RIGHT")
tests = append(tests, test6)
// 2.7 BETWEEN ([<>])
@@ -308,7 +253,6 @@ func testConditionSyntax(that *Context) Map {
test7["result"] = true
test7["count"] = len(articles7)
test7["lastQuery"] = that.Db.LastQuery
debugLog("main.go:254", "BETWEEN 区间查询测试", Map{"count": len(articles7), "query": that.Db.LastQuery}, "H2_BETWEEN")
tests = append(tests, test7)
// 2.8 NOT BETWEEN ([><])
@@ -316,7 +260,6 @@ func testConditionSyntax(that *Context) Map {
articles8 := that.Db.Select("article", "id,title,sort", Map{"sort[><]": Slice{-10, 0}, "LIMIT": 3})
test8["result"] = true
test8["count"] = len(articles8)
debugLog("main.go:262", "NOT BETWEEN 查询测试", Map{"count": len(articles8)}, "H2_NOT_BETWEEN")
tests = append(tests, test8)
// 2.9 IN 查询
@@ -325,7 +268,6 @@ func testConditionSyntax(that *Context) Map {
test9["result"] = true
test9["count"] = len(articles9)
test9["lastQuery"] = that.Db.LastQuery
debugLog("main.go:271", "IN 查询测试", Map{"count": len(articles9), "query": that.Db.LastQuery}, "H2_IN")
tests = append(tests, test9)
// 2.10 NOT IN ([!])
@@ -333,7 +275,6 @@ func testConditionSyntax(that *Context) Map {
articles10 := that.Db.Select("article", "id,title", Map{"id[!]": Slice{1, 2, 3}, "LIMIT": 5})
test10["result"] = true
test10["count"] = len(articles10)
debugLog("main.go:279", "NOT IN 查询测试", Map{"count": len(articles10)}, "H2_NOT_IN")
tests = append(tests, test10)
// 2.11 IS NULL
@@ -341,7 +282,6 @@ func testConditionSyntax(that *Context) Map {
articles11 := that.Db.Select("article", "id,title,img", Map{"img": nil, "LIMIT": 3})
test11["result"] = true
test11["count"] = len(articles11)
debugLog("main.go:287", "IS NULL 查询测试", Map{"count": len(articles11)}, "H2_IS_NULL")
tests = append(tests, test11)
// 2.12 IS NOT NULL ([!])
@@ -349,7 +289,6 @@ func testConditionSyntax(that *Context) Map {
articles12 := that.Db.Select("article", "id,title,create_time", Map{"create_time[!]": nil, "LIMIT": 3})
test12["result"] = true
test12["count"] = len(articles12)
debugLog("main.go:295", "IS NOT NULL 查询测试", Map{"count": len(articles12)}, "H2_IS_NOT_NULL")
tests = append(tests, test12)
// 2.13 直接 SQL ([##] 用于 SQL 片段)
@@ -361,7 +300,6 @@ func testConditionSyntax(that *Context) Map {
test13["result"] = true
test13["count"] = len(articles13)
test13["lastQuery"] = that.Db.LastQuery
debugLog("main.go:307", "直接 SQL 片段查询测试", Map{"count": len(articles13), "query": that.Db.LastQuery}, "H2_RAW_SQL")
tests = append(tests, test13)
// 2.14 显式 AND 条件
@@ -375,7 +313,6 @@ func testConditionSyntax(that *Context) Map {
})
test14["result"] = true
test14["count"] = len(articles14)
debugLog("main.go:321", "显式 AND 条件测试", Map{"count": len(articles14)}, "H2_EXPLICIT_AND")
tests = append(tests, test14)
// 2.15 OR 条件
@@ -389,7 +326,6 @@ func testConditionSyntax(that *Context) Map {
})
test15["result"] = true
test15["count"] = len(articles15)
debugLog("main.go:335", "OR 条件测试", Map{"count": len(articles15)}, "H2_OR")
tests = append(tests, test15)
// 2.16 嵌套 AND/OR 条件
@@ -407,7 +343,6 @@ func testConditionSyntax(that *Context) Map {
test16["result"] = true
test16["count"] = len(articles16)
test16["lastQuery"] = that.Db.LastQuery
debugLog("main.go:353", "嵌套 AND/OR 条件测试", Map{"count": len(articles16), "query": that.Db.LastQuery}, "H2_NESTED")
tests = append(tests, test16)
result["tests"] = tests
@@ -420,8 +355,6 @@ func testChainQuery(that *Context) Map {
result := Map{"name": "链式查询测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:366", "开始链式查询测试 (MySQL)", nil, "H3_CHAIN")
// 3.1 基本链式查询 - 使用 article 表
test1 := Map{"name": "基本链式查询 Table().Where().Select()"}
articles1 := that.Db.Table("article").
@@ -429,7 +362,6 @@ func testChainQuery(that *Context) Map {
Select("id,title,author")
test1["result"] = len(articles1) >= 0
test1["count"] = len(articles1)
debugLog("main.go:375", "基本链式查询测试", Map{"count": len(articles1)}, "H3_BASIC")
tests = append(tests, test1)
// 3.2 链式 And 条件
@@ -441,7 +373,6 @@ func testChainQuery(that *Context) Map {
Select("id,title,click_num")
test2["result"] = len(articles2) >= 0
test2["count"] = len(articles2)
debugLog("main.go:387", "链式 And 条件测试", Map{"count": len(articles2)}, "H3_AND")
tests = append(tests, test2)
// 3.3 链式 Or 条件
@@ -455,7 +386,6 @@ func testChainQuery(that *Context) Map {
Select("id,title,sort,click_num")
test3["result"] = len(articles3) >= 0
test3["count"] = len(articles3)
debugLog("main.go:401", "链式 Or 条件测试", Map{"count": len(articles3)}, "H3_OR")
tests = append(tests, test3)
// 3.4 链式 Order
@@ -467,7 +397,6 @@ func testChainQuery(that *Context) Map {
Select("id,title,create_time")
test4["result"] = len(articles4) >= 0
test4["count"] = len(articles4)
debugLog("main.go:413", "链式 Order 排序测试", Map{"count": len(articles4)}, "H3_ORDER")
tests = append(tests, test4)
// 3.5 链式 Limit
@@ -478,7 +407,6 @@ func testChainQuery(that *Context) Map {
Select("id,title")
test5["result"] = len(articles5) <= 3
test5["count"] = len(articles5)
debugLog("main.go:424", "链式 Limit 限制测试", Map{"count": len(articles5)}, "H3_LIMIT")
tests = append(tests, test5)
// 3.6 链式 Get 单条
@@ -488,7 +416,6 @@ func testChainQuery(that *Context) Map {
Get("id,title,author")
test6["result"] = article6 != nil || true // 允许为空
test6["article"] = article6
debugLog("main.go:434", "链式 Get 获取单条测试", Map{"article": article6}, "H3_GET")
tests = append(tests, test6)
// 3.7 链式 Count
@@ -498,7 +425,6 @@ func testChainQuery(that *Context) Map {
Count()
test7["result"] = count7 >= 0
test7["count"] = count7
debugLog("main.go:444", "链式 Count 统计测试", Map{"count": count7}, "H3_COUNT")
tests = append(tests, test7)
// 3.8 链式 Page 分页
@@ -509,7 +435,6 @@ func testChainQuery(that *Context) Map {
Select("id,title")
test8["result"] = len(articles8) <= 5
test8["count"] = len(articles8)
debugLog("main.go:455", "链式 Page 分页测试", Map{"count": len(articles8)}, "H3_PAGE")
tests = append(tests, test8)
// 3.9 链式 Group 分组
@@ -520,7 +445,6 @@ func testChainQuery(that *Context) Map {
Select("ctg_id, COUNT(*) as cnt")
test9["result"] = len(stats9) >= 0
test9["stats"] = stats9
debugLog("main.go:466", "链式 Group 分组测试", Map{"stats": stats9}, "H3_GROUP")
tests = append(tests, test9)
// 3.10 链式 Update
@@ -537,7 +461,6 @@ func testChainQuery(that *Context) Map {
test10["result"] = true
test10["note"] = "无可用测试数据"
}
debugLog("main.go:483", "链式 Update 更新测试", test10, "H3_UPDATE")
tests = append(tests, test10)
result["tests"] = tests
@@ -550,8 +473,6 @@ func testJoinQuery(that *Context) Map {
result := Map{"name": "JOIN查询测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:496", "开始 JOIN 查询测试 (MySQL)", nil, "H4_JOIN")
// 4.1 LEFT JOIN 链式 - article 关联 ctg
test1 := Map{"name": "LEFT JOIN 链式查询"}
articles1 := that.Db.Table("article").
@@ -562,7 +483,6 @@ func testJoinQuery(that *Context) Map {
test1["result"] = len(articles1) >= 0
test1["count"] = len(articles1)
test1["data"] = articles1
debugLog("main.go:508", "LEFT JOIN 链式查询测试", Map{"count": len(articles1)}, "H4_LEFT_JOIN")
tests = append(tests, test1)
// 4.2 传统 JOIN 语法
@@ -579,7 +499,6 @@ func testJoinQuery(that *Context) Map {
test2["result"] = len(articles2) >= 0
test2["count"] = len(articles2)
test2["lastQuery"] = that.Db.LastQuery
debugLog("main.go:525", "传统 JOIN 语法测试", Map{"count": len(articles2), "query": that.Db.LastQuery}, "H4_TRADITIONAL_JOIN")
tests = append(tests, test2)
// 4.3 多表 JOIN - article 关联 ctg 和 admin
@@ -593,7 +512,6 @@ func testJoinQuery(that *Context) Map {
test3["result"] = len(articles3) >= 0
test3["count"] = len(articles3)
test3["data"] = articles3
debugLog("main.go:539", "多表 JOIN 测试", Map{"count": len(articles3)}, "H4_MULTI_JOIN")
tests = append(tests, test3)
// 4.4 INNER JOIN
@@ -605,7 +523,6 @@ func testJoinQuery(that *Context) Map {
Select("article.id, article.title, ctg.name as ctg_name")
test4["result"] = len(articles4) >= 0
test4["count"] = len(articles4)
debugLog("main.go:551", "INNER JOIN 测试", Map{"count": len(articles4)}, "H4_INNER_JOIN")
tests = append(tests, test4)
result["tests"] = tests
@@ -618,14 +535,11 @@ func testAggregate(that *Context) Map {
result := Map{"name": "聚合函数测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:564", "开始聚合函数测试 (MySQL)", nil, "H5_AGGREGATE")
// 5.1 Count 总数
test1 := Map{"name": "Count 总数统计"}
count1 := that.Db.Count("article")
test1["result"] = count1 >= 0
test1["count"] = count1
debugLog("main.go:571", "Count 总数统计测试", Map{"count": count1}, "H5_COUNT")
tests = append(tests, test1)
// 5.2 Count 带条件
@@ -633,7 +547,6 @@ func testAggregate(that *Context) Map {
count2 := that.Db.Count("article", Map{"state": 0})
test2["result"] = count2 >= 0
test2["count"] = count2
debugLog("main.go:579", "Count 条件统计测试", Map{"count": count2}, "H5_COUNT_WHERE")
tests = append(tests, test2)
// 5.3 Sum 求和
@@ -641,7 +554,6 @@ func testAggregate(that *Context) Map {
sum3 := that.Db.Sum("article", "click_num", Map{"state": 0})
test3["result"] = sum3 >= 0
test3["sum"] = sum3
debugLog("main.go:587", "Sum 求和测试", Map{"sum": sum3}, "H5_SUM")
tests = append(tests, test3)
// 5.4 Avg 平均值
@@ -649,7 +561,6 @@ func testAggregate(that *Context) Map {
avg4 := that.Db.Avg("article", "click_num", Map{"state": 0})
test4["result"] = avg4 >= 0
test4["avg"] = avg4
debugLog("main.go:595", "Avg 平均值测试", Map{"avg": avg4}, "H5_AVG")
tests = append(tests, test4)
// 5.5 Max 最大值
@@ -657,7 +568,6 @@ func testAggregate(that *Context) Map {
max5 := that.Db.Max("article", "click_num", Map{"state": 0})
test5["result"] = max5 >= 0
test5["max"] = max5
debugLog("main.go:603", "Max 最大值测试", Map{"max": max5}, "H5_MAX")
tests = append(tests, test5)
// 5.6 Min 最小值
@@ -665,7 +575,6 @@ func testAggregate(that *Context) Map {
min6 := that.Db.Min("article", "sort", Map{"state": 0})
test6["result"] = true // sort 可能为 0
test6["min"] = min6
debugLog("main.go:611", "Min 最小值测试", Map{"min": min6}, "H5_MIN")
tests = append(tests, test6)
// 5.7 GROUP BY 分组统计
@@ -680,7 +589,6 @@ func testAggregate(that *Context) Map {
})
test7["result"] = len(stats7) >= 0
test7["stats"] = stats7
debugLog("main.go:625", "GROUP BY 分组统计测试", Map{"stats": stats7}, "H5_GROUP_BY")
tests = append(tests, test7)
result["tests"] = tests
@@ -693,8 +601,6 @@ func testPagination(that *Context) Map {
result := Map{"name": "分页查询测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:638", "开始分页查询测试 (MySQL)", nil, "H6_PAGINATION")
// 6.1 PageSelect 分页查询
test1 := Map{"name": "PageSelect 分页查询"}
articles1 := that.Db.Page(1, 5).PageSelect("article", "*", Map{
@@ -703,7 +609,6 @@ func testPagination(that *Context) Map {
})
test1["result"] = len(articles1) <= 5
test1["count"] = len(articles1)
debugLog("main.go:648", "PageSelect 分页查询测试", Map{"count": len(articles1)}, "H6_PAGE_SELECT")
tests = append(tests, test1)
// 6.2 第二页
@@ -714,7 +619,6 @@ func testPagination(that *Context) Map {
})
test2["result"] = len(articles2) <= 5
test2["count"] = len(articles2)
debugLog("main.go:659", "PageSelect 第二页测试", Map{"count": len(articles2)}, "H6_PAGE_2")
tests = append(tests, test2)
// 6.3 链式分页
@@ -726,7 +630,6 @@ func testPagination(that *Context) Map {
Select("id,title,author")
test3["result"] = len(articles3) <= 3
test3["count"] = len(articles3)
debugLog("main.go:671", "链式 Page 分页测试", Map{"count": len(articles3)}, "H6_CHAIN_PAGE")
tests = append(tests, test3)
// 6.4 Offset 偏移
@@ -739,7 +642,6 @@ func testPagination(that *Context) Map {
test4["result"] = len(articles4) <= 3
test4["count"] = len(articles4)
test4["lastQuery"] = that.Db.LastQuery
debugLog("main.go:684", "Offset 偏移查询测试", Map{"count": len(articles4), "query": that.Db.LastQuery}, "H6_OFFSET")
tests = append(tests, test4)
result["tests"] = tests
@@ -752,8 +654,6 @@ func testBatchInsert(that *Context) Map {
result := Map{"name": "批量插入测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:697", "开始批量插入测试 (MySQL)", nil, "H7_BATCH")
// 7.1 批量插入
test1 := Map{"name": "BatchInsert 批量插入"}
timestamp := time.Now().UnixNano()
@@ -765,7 +665,6 @@ func testBatchInsert(that *Context) Map {
test1["result"] = affected1 >= 0
test1["affected"] = affected1
test1["lastQuery"] = that.Db.LastQuery
debugLog("main.go:710", "BatchInsert 批量插入测试", Map{"affected": affected1, "query": that.Db.LastQuery}, "H7_BATCH_INSERT")
tests = append(tests, test1)
// 7.2 带 [#] 的批量插入
@@ -777,7 +676,6 @@ func testBatchInsert(that *Context) Map {
})
test2["result"] = affected2 >= 0
test2["affected"] = affected2
debugLog("main.go:722", "BatchInsert 带 [#] 标记测试", Map{"affected": affected2}, "H7_BATCH_RAW")
tests = append(tests, test2)
// 清理测试数据
@@ -794,8 +692,6 @@ func testUpsert(that *Context) Map {
result := Map{"name": "Upsert测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:739", "开始 Upsert 测试 (MySQL)", nil, "H8_UPSERT")
// 使用 admin 表测试 UpsertMySQL ON DUPLICATE KEY UPDATE
timestamp := time.Now().Unix()
testPhone := fmt.Sprintf("199%08d", timestamp%100000000)
@@ -819,7 +715,6 @@ func testUpsert(that *Context) Map {
test1["result"] = affected1 >= 0
test1["affected"] = affected1
test1["lastQuery"] = that.Db.LastQuery
debugLog("main.go:763", "Upsert 插入新记录测试", Map{"affected": affected1, "query": that.Db.LastQuery}, "H8_UPSERT_INSERT")
tests = append(tests, test1)
// 8.2 Upsert 更新已存在记录
@@ -840,7 +735,6 @@ func testUpsert(that *Context) Map {
)
test2["result"] = affected2 >= 0
test2["affected"] = affected2
debugLog("main.go:783", "Upsert 更新已存在记录测试", Map{"affected": affected2}, "H8_UPSERT_UPDATE")
tests = append(tests, test2)
// 验证更新结果
@@ -860,8 +754,6 @@ func testTransaction(that *Context) Map {
result := Map{"name": "事务测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:803", "开始事务测试 (MySQL)", nil, "H9_TRANSACTION")
// 9.1 事务成功提交
test1 := Map{"name": "事务成功提交"}
timestamp := time.Now().Unix()
@@ -875,7 +767,6 @@ func testTransaction(that *Context) Map {
"state": 1,
"create_time[#]": "NOW()",
})
debugLog("main.go:818", "事务内插入记录", Map{"recordId": recordId}, "H9_TX_INSERT")
return recordId != 0
})
@@ -884,7 +775,6 @@ func testTransaction(that *Context) Map {
// 验证数据是否存在
checkRecord := that.Db.Get("test_batch", "*", Map{"name": testName1})
test1["recordExists"] = checkRecord != nil
debugLog("main.go:831", "事务成功提交测试", Map{"success": success1, "recordExists": checkRecord != nil}, "H9_TX_SUCCESS")
tests = append(tests, test1)
// 9.2 事务回滚
@@ -893,13 +783,12 @@ func testTransaction(that *Context) Map {
success2 := that.Db.Action(func(tx HoTimeDB) bool {
// 插入记录
recordId := tx.Insert("test_batch", Map{
_ = tx.Insert("test_batch", Map{
"name": testName2,
"title": "事务回滚测试",
"state": 1,
"create_time[#]": "NOW()",
})
debugLog("main.go:846", "事务内插入(将回滚)", Map{"recordId": recordId}, "H9_TX_ROLLBACK_INSERT")
// 返回 false 触发回滚
return false
@@ -909,7 +798,6 @@ func testTransaction(that *Context) Map {
// 验证数据是否不存在(已回滚)
checkRecord2 := that.Db.Get("test_batch", "*", Map{"name": testName2})
test2["recordRolledBack"] = checkRecord2 == nil
debugLog("main.go:856", "事务回滚测试", Map{"success": success2, "rolledBack": checkRecord2 == nil}, "H9_TX_ROLLBACK")
tests = append(tests, test2)
// 清理测试数据
@@ -925,14 +813,11 @@ func testRawSQL(that *Context) Map {
result := Map{"name": "原生SQL测试", "tests": Slice{}}
tests := Slice{}
debugLog("main.go:872", "开始原生 SQL 测试 (MySQL)", nil, "H10_RAW_SQL")
// 10.1 Query 查询 - 使用真实的 article 表
test1 := Map{"name": "Query 原生查询"}
articles1 := that.Db.Query("SELECT id, title, author FROM `article` WHERE state = ? LIMIT ?", 0, 5)
test1["result"] = len(articles1) >= 0
test1["count"] = len(articles1)
debugLog("main.go:879", "Query 原生查询测试", Map{"count": len(articles1)}, "H10_QUERY")
tests = append(tests, test1)
// 10.2 Exec 执行 - 使用 article 表
@@ -953,9 +838,67 @@ func testRawSQL(that *Context) Map {
test2["result"] = true
test2["note"] = "无可用测试数据"
}
debugLog("main.go:899", "Exec 原生执行测试", test2, "H10_EXEC")
tests = append(tests, test2)
// ==================== IN/NOT IN 数组测试 ====================
// H1: IN (?) 配合非空数组能正确展开
test3 := Map{"name": "H1: IN (?) 非空数组展开"}
articles3 := that.Db.Query("SELECT id, title FROM `article` WHERE id IN (?) LIMIT 10", []int{1, 2, 3, 4, 5})
test3["result"] = len(articles3) >= 0
test3["count"] = len(articles3)
test3["lastQuery"] = that.Db.LastQuery
tests = append(tests, test3)
// H2: IN (?) 配合空数组替换为 1=0
test4 := Map{"name": "H2: IN (?) 空数组替换为1=0"}
articles4 := that.Db.Query("SELECT id, title FROM `article` WHERE id IN (?) LIMIT 10", []int{})
test4["result"] = len(articles4) == 0 // 空数组的IN应该返回0条
test4["count"] = len(articles4)
test4["lastQuery"] = that.Db.LastQuery
test4["expected"] = "count=0, SQL应包含1=0"
tests = append(tests, test4)
// H3: NOT IN (?) 配合空数组替换为 1=1
test5 := Map{"name": "H3: NOT IN (?) 空数组替换为1=1"}
articles5 := that.Db.Query("SELECT id, title FROM `article` WHERE id NOT IN (?) LIMIT 10", []int{})
test5["result"] = len(articles5) > 0 // NOT IN空数组应该返回记录
test5["count"] = len(articles5)
test5["lastQuery"] = that.Db.LastQuery
test5["expected"] = "count>0, SQL应包含1=1"
tests = append(tests, test5)
// H4: NOT IN (?) 配合非空数组正常展开
test6 := Map{"name": "H4: NOT IN (?) 非空数组展开"}
articles6 := that.Db.Query("SELECT id, title FROM `article` WHERE id NOT IN (?) LIMIT 10", []int{1, 2, 3})
test6["result"] = len(articles6) >= 0
test6["count"] = len(articles6)
test6["lastQuery"] = that.Db.LastQuery
tests = append(tests, test6)
// H5: 普通 ? 占位符保持原有行为
test7 := Map{"name": "H5: 普通?占位符不受影响"}
articles7 := that.Db.Query("SELECT id, title FROM `article` WHERE state = ? LIMIT ?", 0, 5)
test7["result"] = len(articles7) >= 0
test7["count"] = len(articles7)
test7["lastQuery"] = that.Db.LastQuery
tests = append(tests, test7)
// 额外测试: Select ORM方法的空数组处理
test8 := Map{"name": "ORM Select: IN空数组"}
articles8 := that.Db.Select("article", "id,title", Map{"id": []int{}, "LIMIT": 10})
test8["result"] = len(articles8) == 0
test8["count"] = len(articles8)
test8["lastQuery"] = that.Db.LastQuery
tests = append(tests, test8)
// 额外测试: Select ORM方法的NOT IN空数组处理
test9 := Map{"name": "ORM Select: NOT IN空数组"}
articles9 := that.Db.Select("article", "id,title", Map{"id[!]": []int{}, "LIMIT": 10})
test9["result"] = len(articles9) > 0 // NOT IN 空数组应返回记录
test9["count"] = len(articles9)
test9["lastQuery"] = that.Db.LastQuery
tests = append(tests, test9)
result["tests"] = tests
result["success"] = true
return result