fix(db): 真实容器验证 Postgres/MySQL 方言修复
Docker 起 mysql:8 / postgres:16 实跑迁移+核心 CRUD,发现并修复三处阻断问题: - pgx 不支持 ? 占位符:新增 pgx_compat driver 包裹 pgx stdlib,把 ? 重写为 $N (internal/db/pgx_compat.go),driverPgx 指向它;全仓库 ? 写法零改动。 - pgx 对 BOOLEAN 严格按 bool 读写,与 int/boolToInt 写法不兼容:Postgres migration 的 BOOLEAN 列改 INTEGER 0/1,与 SQLite/MySQL 对齐 (00001/00004/00008)。 - pgx 不支持 Result.LastInsertId:新增 insertReturningID helper,Postgres 走 INSERT ... RETURNING id,SQLite/MySQL 走 LastInsertId (Cards/Keywords/ Notifications/Automation 的 INSERT 路径)。 附带 MySQL 部署加固:parseDBURL 自动补 multiStatements=true(缺失会静默只执行 首条迁移语句);base_url TEXT→VARCHAR(512)(strict mode 拒绝 TEXT+DEFAULT)。 新增 cmd/dbverify 三库迁移+核心 CRUD 烟囱测试工具。 验证:SQLite/MySQL/Postgres 三库 9 步 CRUD 全通过;go test ./... 与 go vet 通过。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
1 parent
fb83aacb8b
commit
62705c524d
13 files changed
+449
-62
No files matched your search
+34
-3
@@ -1,6 +1,10 @@
|
||||
package db
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DialectUpsert 生成 UPSERT 子句,处理三种数据库的语法差异。
|
||||
//
|
||||
@@ -23,8 +27,10 @@ func DialectUpsert(d Dialect, conflictCols []string, updateAssignments map[strin
|
||||
for _, col := range keys {
|
||||
expr := updateAssignments[col]
|
||||
if d == DialectMySQL {
|
||||
if strings.HasPrefix(expr, "EXCLUDED.") {
|
||||
field := strings.TrimPrefix(expr, "EXCLUDED.")
|
||||
// EXCLUDED.col / excluded.col → VALUES(col)(大小写不敏感)
|
||||
upper := strings.ToUpper(expr)
|
||||
if strings.HasPrefix(upper, "EXCLUDED.") {
|
||||
field := expr[len("EXCLUDED."):] // 保留原大小写
|
||||
expr = "VALUES(" + field + ")"
|
||||
}
|
||||
}
|
||||
@@ -90,3 +96,28 @@ func sortStrings(s []string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DBTX 是 *sql.DB 与 *sql.Tx 共有的最小执行接口,供 insertReturningID 复用。
|
||||
type DBTX interface {
|
||||
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
// insertReturningID 执行 INSERT 并返回自增主键 id。
|
||||
// Postgres 的 pgx driver 不支持 Result.LastInsertId(Postgres 无该概念),
|
||||
// 改用 `INSERT ... RETURNING id` + QueryRow.Scan;SQLite/MySQL 走 res.LastInsertId()。
|
||||
// query 必须是可安全追加 ` RETURNING id` 的单条 INSERT(无尾随分号/ON CONFLICT 亦可)。
|
||||
func insertReturningID(ctx context.Context, exec DBTX, dialect Dialect, query string, args ...any) (int64, error) {
|
||||
if dialect == DialectPostgres {
|
||||
var id int64
|
||||
if err := exec.QueryRowContext(ctx, query+" RETURNING id", args...).Scan(&id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
res, err := exec.ExecContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
Reference in new issue
Block a user