u
This commit is contained in:
1 parent
89aaef1d6b
commit
6d54a9e407
192 files changed
+971
-51708
No files matched your search
@@ -59,7 +59,6 @@ func handleThirdLogin(
|
||||
loginType int16,
|
||||
vo *types.LoginVO,
|
||||
) error {
|
||||
|
||||
dbClient := db.New()
|
||||
|
||||
user, err := getUserByOpenID(dbClient, c, openid, loginType)
|
||||
@@ -101,6 +100,29 @@ func handleThirdLogin(
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
familyMembers, err := dbClient.LoadData(
|
||||
c.Context(),
|
||||
"b_family_member",
|
||||
"user_id = ?",
|
||||
"",
|
||||
[]string{"family_id"},
|
||||
[]any{id},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if len(familyMembers) == 0 {
|
||||
vo.FamilyId = 0
|
||||
} else {
|
||||
familyMember := familyMembers[0]
|
||||
|
||||
familyId := toInt64(familyMember["family_id"])
|
||||
|
||||
vo.FamilyId = familyId
|
||||
}
|
||||
|
||||
// ========= 返回 =========
|
||||
vo.Token = token
|
||||
vo.UserId = id
|
||||
@@ -133,20 +155,20 @@ func registerUser(
|
||||
"id": userId,
|
||||
"nickname": nickname,
|
||||
"avatar": avatar,
|
||||
"created_at": "NOW()",
|
||||
"updated_at": "NOW()",
|
||||
"create_time": "NOW()",
|
||||
"update_time": "NOW()",
|
||||
"last_login_time": "NOW()",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Insert(c.Context(), "b_user_oauth", "id", map[string]any{
|
||||
"id": uniqueid.NextId(),
|
||||
"user_id": userId,
|
||||
"type": loginType,
|
||||
"openid": openid,
|
||||
"created_at": "NOW()",
|
||||
"updated_at": "NOW()",
|
||||
"id": uniqueid.NextId(),
|
||||
"user_id": userId,
|
||||
"type": loginType,
|
||||
"openid": openid,
|
||||
"create_time": "NOW()",
|
||||
"update_time": "NOW()",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -169,6 +191,7 @@ func registerUser(
|
||||
vo.UserId = userId
|
||||
vo.Nickname = nickname
|
||||
vo.Avatar = avatar
|
||||
vo.FamilyId = 0
|
||||
|
||||
return httpx.OK(c, vo)
|
||||
}
|
||||
|
||||
@@ -15,4 +15,5 @@ type LoginVO struct {
|
||||
UserId int64 `json:"userId"`
|
||||
Nickname string `json:"nickname"`
|
||||
Avatar string `json:"avatar"`
|
||||
FamilyId int64 `json:"family_id"`
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var auditExcludeTables = map[string]bool{
|
||||
"b_user": true,
|
||||
"b_user_oauth": true,
|
||||
}
|
||||
|
||||
func validateData(table string, keyField string, data map[string]any) (any, error) {
|
||||
if table == "" {
|
||||
return nil, fmt.Errorf("表名不能为空")
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("数据不能为空")
|
||||
}
|
||||
|
||||
if keyField == "" {
|
||||
return nil, fmt.Errorf("主键字段不能为空")
|
||||
}
|
||||
|
||||
val, ok := data[keyField]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("缺少主键字段: %s", keyField)
|
||||
}
|
||||
|
||||
if val == nil {
|
||||
return nil, fmt.Errorf("主键字段值不能为空")
|
||||
}
|
||||
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// 高效 placeholder 转换
|
||||
func convertPlaceholder(sql string) string {
|
||||
var sb strings.Builder
|
||||
sb.Grow(len(sql))
|
||||
|
||||
argIndex := 1
|
||||
|
||||
for i := 0; i < len(sql); i++ {
|
||||
if sql[i] == '?' {
|
||||
sb.WriteByte('$')
|
||||
sb.WriteString(strconv.Itoa(argIndex))
|
||||
argIndex++
|
||||
} else {
|
||||
sb.WriteByte(sql[i])
|
||||
}
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
@@ -6,96 +6,49 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (c *Client) Delete(
|
||||
ctx context.Context,
|
||||
table string,
|
||||
keyField string,
|
||||
data map[string]any,
|
||||
) error {
|
||||
if keyField == "" {
|
||||
return fmt.Errorf("keyField 不能为空")
|
||||
}
|
||||
|
||||
rawTable := table
|
||||
|
||||
keyVal, err := validateData(rawTable, keyField, data)
|
||||
func (c *Client) Delete(ctx context.Context, table, keyField string, data map[string]any) error {
|
||||
keyVal, err := validateData(table, keyField, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tableParts := strings.Split(table, ".")
|
||||
for i, p := range tableParts {
|
||||
tableParts[i] = `"` + p + `"`
|
||||
}
|
||||
table = strings.Join(tableParts, ".")
|
||||
|
||||
keyField = `"` + keyField + `"`
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
"DELETE FROM %s WHERE %s = $1",
|
||||
table,
|
||||
keyField,
|
||||
"DELETE FROM %s WHERE %s=$1",
|
||||
quoteTable(table),
|
||||
quoteCol(keyField),
|
||||
)
|
||||
|
||||
_, err = c.exec().Exec(ctx, sql, keyVal)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) BatchDelete(
|
||||
ctx context.Context,
|
||||
table string,
|
||||
keyField string,
|
||||
dataList []map[string]any,
|
||||
) error {
|
||||
|
||||
if table == "" {
|
||||
return fmt.Errorf("表名不能为空")
|
||||
func (c *Client) BatchDelete(ctx context.Context, table, keyField string, list []map[string]any) error {
|
||||
if len(list) == 0 {
|
||||
return fmt.Errorf("empty data")
|
||||
}
|
||||
|
||||
if keyField == "" {
|
||||
return fmt.Errorf("主键字段不能为空")
|
||||
}
|
||||
|
||||
if len(dataList) == 0 {
|
||||
return fmt.Errorf("数据不能为空")
|
||||
}
|
||||
|
||||
rawTable := table
|
||||
|
||||
tableParts := strings.Split(table, ".")
|
||||
for i, p := range tableParts {
|
||||
tableParts[i] = `"` + p + `"`
|
||||
}
|
||||
table = strings.Join(tableParts, ".")
|
||||
|
||||
keyFieldQuoted := `"` + keyField + `"`
|
||||
|
||||
var (
|
||||
placeholders []string
|
||||
args []any
|
||||
argIndex = 1
|
||||
args []any
|
||||
in []string
|
||||
i = 1
|
||||
)
|
||||
|
||||
for _, data := range dataList {
|
||||
keyVal, err := validateData(rawTable, keyField, data)
|
||||
for _, row := range list {
|
||||
v, err := validateData(table, keyField, row)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if keyVal == nil {
|
||||
return fmt.Errorf("主键字段值不能为空")
|
||||
}
|
||||
|
||||
placeholders = append(placeholders, fmt.Sprintf("$%d", argIndex))
|
||||
args = append(args, keyVal)
|
||||
argIndex++
|
||||
in = append(in, fmt.Sprintf("$%d", i))
|
||||
args = append(args, v)
|
||||
i++
|
||||
}
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
"DELETE FROM %s WHERE %s IN (%s)",
|
||||
table,
|
||||
keyFieldQuoted,
|
||||
strings.Join(placeholders, ", "),
|
||||
quoteTable(table),
|
||||
quoteCol(keyField),
|
||||
strings.Join(in, ", "),
|
||||
)
|
||||
|
||||
_, err := c.exec().Exec(ctx, sql, args...)
|
||||
|
||||
@@ -1,158 +1,99 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"allapp-go/internal/middleware"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 构建 INSERT SQL(单条)
|
||||
func buildInsertSQL(table string, data map[string]any) (string, []any) {
|
||||
var (
|
||||
columns []string
|
||||
placeholders []string
|
||||
args []any
|
||||
cols []string
|
||||
vals []string
|
||||
args []any
|
||||
i = 1
|
||||
)
|
||||
|
||||
// 处理 schema.table 的情况
|
||||
tableParts := strings.Split(table, ".")
|
||||
for i, p := range tableParts {
|
||||
tableParts[i] = `"` + p + `"`
|
||||
}
|
||||
table = strings.Join(tableParts, ".")
|
||||
|
||||
i := 1
|
||||
for col, val := range data {
|
||||
// 列名加引号
|
||||
columns = append(columns, `"`+col+`"`)
|
||||
|
||||
placeholders = append(placeholders, fmt.Sprintf("$%d", i))
|
||||
args = append(args, val)
|
||||
for k, v := range data {
|
||||
cols = append(cols, quoteCol(k))
|
||||
vals = append(vals, fmt.Sprintf("$%d", i))
|
||||
args = append(args, v)
|
||||
i++
|
||||
}
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
return fmt.Sprintf(
|
||||
"INSERT INTO %s (%s) VALUES (%s)",
|
||||
table,
|
||||
strings.Join(columns, ", "),
|
||||
strings.Join(placeholders, ", "),
|
||||
)
|
||||
|
||||
return sql, args
|
||||
quoteTable(table),
|
||||
strings.Join(cols, ", "),
|
||||
strings.Join(vals, ", "),
|
||||
), args
|
||||
}
|
||||
|
||||
func (c *Client) Insert(
|
||||
ctx context.Context,
|
||||
table string,
|
||||
keyField string,
|
||||
data map[string]any,
|
||||
) error {
|
||||
func (c *Client) Insert(ctx context.Context, table, keyField string, data map[string]any) error {
|
||||
if _, err := validateData(table, keyField, data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !auditExcludeTables[table] {
|
||||
now := time.Now()
|
||||
|
||||
delete(data, "create_time")
|
||||
delete(data, "update_time")
|
||||
delete(data, "create_by")
|
||||
delete(data, "update_by")
|
||||
|
||||
data["create_time"] = now
|
||||
data["update_time"] = now
|
||||
|
||||
userID, flag := middleware.GetUserID(ctx)
|
||||
|
||||
if flag {
|
||||
data["create_by"] = userID
|
||||
data["update_by"] = userID
|
||||
}
|
||||
}
|
||||
data = applyMetaFields(ctx, table, data, true)
|
||||
|
||||
sql, args := buildInsertSQL(table, data)
|
||||
|
||||
_, err := c.exec().Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) BatchInsert(
|
||||
ctx context.Context,
|
||||
table string,
|
||||
keyField string,
|
||||
dataList []map[string]any,
|
||||
) error {
|
||||
if len(dataList) == 0 {
|
||||
return fmt.Errorf("数据不能为空")
|
||||
func (c *Client) BatchInsert(ctx context.Context, table, keyField string, list []map[string]any) error {
|
||||
if len(list) == 0 {
|
||||
return fmt.Errorf("empty data")
|
||||
}
|
||||
|
||||
first := dataList[0]
|
||||
first := list[0]
|
||||
if _, err := validateData(table, keyField, first); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 👉 表名加引号(支持 schema)
|
||||
tableParts := strings.Split(table, ".")
|
||||
for i, p := range tableParts {
|
||||
tableParts[i] = `"` + p + `"`
|
||||
}
|
||||
table = strings.Join(tableParts, ".")
|
||||
tableSQL := quoteTable(table)
|
||||
|
||||
var columns []string
|
||||
for col := range first {
|
||||
columns = append(columns, col)
|
||||
}
|
||||
|
||||
sort.Strings(columns)
|
||||
|
||||
// 👉 列名加引号
|
||||
var quotedColumns []string
|
||||
for _, col := range columns {
|
||||
quotedColumns = append(quotedColumns, `"`+col+`"`)
|
||||
var cols []string
|
||||
for k := range first {
|
||||
cols = append(cols, k)
|
||||
}
|
||||
sort.Strings(cols)
|
||||
|
||||
var (
|
||||
valueStrings []string
|
||||
args []any
|
||||
argIndex = 1
|
||||
args []any
|
||||
values []string
|
||||
argIndex = 1
|
||||
)
|
||||
|
||||
for _, data := range dataList {
|
||||
if _, err := validateData(table, keyField, data); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range list {
|
||||
row = applyMetaFields(ctx, table, row, true)
|
||||
|
||||
if len(data) != len(columns) {
|
||||
return fmt.Errorf("批量插入失败:数据字段不一致")
|
||||
}
|
||||
|
||||
var placeholders []string
|
||||
|
||||
for _, col := range columns {
|
||||
val, ok := data[col]
|
||||
var place []string
|
||||
for _, col := range cols {
|
||||
v, ok := row[col]
|
||||
if !ok {
|
||||
return fmt.Errorf("缺少字段: %s", col)
|
||||
return fmt.Errorf("missing field: %s", col)
|
||||
}
|
||||
|
||||
placeholders = append(placeholders, fmt.Sprintf("$%d", argIndex))
|
||||
args = append(args, val)
|
||||
place = append(place, fmt.Sprintf("$%d", argIndex))
|
||||
args = append(args, v)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
valueStrings = append(
|
||||
valueStrings,
|
||||
fmt.Sprintf("(%s)", strings.Join(placeholders, ", ")),
|
||||
)
|
||||
values = append(values, fmt.Sprintf("(%s)", strings.Join(place, ",")))
|
||||
}
|
||||
|
||||
var quotedCols []string
|
||||
for _, c := range cols {
|
||||
quotedCols = append(quotedCols, quoteCol(c))
|
||||
}
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
"INSERT INTO %s (%s) VALUES %s",
|
||||
table,
|
||||
strings.Join(quotedColumns, ", "),
|
||||
strings.Join(valueStrings, ", "),
|
||||
tableSQL,
|
||||
strings.Join(quotedCols, ", "),
|
||||
strings.Join(values, ", "),
|
||||
)
|
||||
|
||||
_, err := c.exec().Exec(ctx, sql, args...)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"allapp-go/internal/middleware"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
var auditExcludeTables = map[string]bool{
|
||||
"b_user": true,
|
||||
"b_user_oauth": true,
|
||||
}
|
||||
|
||||
// 返回新 map(避免修改入参)
|
||||
func applyMetaFields(ctx context.Context, table string, data map[string]any, isInsert bool) map[string]any {
|
||||
if auditExcludeTables[table] {
|
||||
return data
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
newData := make(map[string]any, len(data)+2)
|
||||
|
||||
for k, v := range data {
|
||||
newData[k] = v
|
||||
}
|
||||
|
||||
if isInsert {
|
||||
newData["create_time"] = now
|
||||
newData["update_time"] = now
|
||||
} else {
|
||||
newData["update_time"] = now
|
||||
}
|
||||
|
||||
if userID, ok := middleware.GetUserID(ctx); ok {
|
||||
if isInsert {
|
||||
newData["create_by"] = userID
|
||||
}
|
||||
newData["update_by"] = userID
|
||||
}
|
||||
|
||||
return newData
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"allapp-go/pkg/logger"
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap"
|
||||
@@ -96,3 +97,23 @@ func (c *Client) query(ctx context.Context, sql string, args ...any) ([]map[stri
|
||||
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// 高效 placeholder 转换
|
||||
func convertPlaceholder(sql string) string {
|
||||
var sb strings.Builder
|
||||
sb.Grow(len(sql))
|
||||
|
||||
argIndex := 1
|
||||
|
||||
for i := 0; i < len(sql); i++ {
|
||||
if sql[i] == '?' {
|
||||
sb.WriteByte('$')
|
||||
sb.WriteString(strconv.Itoa(argIndex))
|
||||
argIndex++
|
||||
} else {
|
||||
sb.WriteByte(sql[i])
|
||||
}
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
@@ -1,141 +1,93 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"allapp-go/internal/middleware"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (c *Client) Update(
|
||||
ctx context.Context,
|
||||
table string,
|
||||
keyField string,
|
||||
data map[string]any,
|
||||
) error {
|
||||
func (c *Client) Update(ctx context.Context, table, keyField string, data map[string]any) error {
|
||||
keyVal, err := validateData(table, keyField, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !auditExcludeTables[table] {
|
||||
now := time.Now()
|
||||
data = applyMetaFields(ctx, table, data, false)
|
||||
|
||||
delete(data, "update_time")
|
||||
delete(data, "update_by")
|
||||
|
||||
data["update_time"] = now
|
||||
|
||||
userID, flag := middleware.GetUserID(ctx)
|
||||
if flag {
|
||||
data["update_by"] = userID
|
||||
}
|
||||
}
|
||||
|
||||
// 👉 表名加引号(支持 schema)
|
||||
tableParts := strings.Split(table, ".")
|
||||
for i, p := range tableParts {
|
||||
tableParts[i] = `"` + p + `"`
|
||||
}
|
||||
table = strings.Join(tableParts, ".")
|
||||
|
||||
// 👉 keyField 加引号
|
||||
keyField = `"` + keyField + `"`
|
||||
tableSQL := quoteTable(table)
|
||||
keySQL := quoteCol(keyField)
|
||||
|
||||
var (
|
||||
setClauses []string
|
||||
args []any
|
||||
i = 1
|
||||
set []string
|
||||
args []any
|
||||
i = 1
|
||||
)
|
||||
|
||||
for col, val := range data {
|
||||
if col == keyField {
|
||||
for k, v := range data {
|
||||
if k == keyField {
|
||||
continue
|
||||
}
|
||||
|
||||
// 👉 列名加引号
|
||||
colQuoted := `"` + col + `"`
|
||||
|
||||
setClauses = append(setClauses, fmt.Sprintf("%s=$%d", colQuoted, i))
|
||||
args = append(args, val)
|
||||
set = append(set, fmt.Sprintf("%s=$%d", quoteCol(k), i))
|
||||
args = append(args, v)
|
||||
i++
|
||||
}
|
||||
|
||||
where := fmt.Sprintf("%s=$%d", keyField, i)
|
||||
args = append(args, keyVal)
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
"UPDATE %s SET %s WHERE %s",
|
||||
table,
|
||||
strings.Join(setClauses, ", "),
|
||||
where,
|
||||
"UPDATE %s SET %s WHERE %s=$%d",
|
||||
tableSQL,
|
||||
strings.Join(set, ", "),
|
||||
keySQL,
|
||||
i,
|
||||
)
|
||||
|
||||
_, err = c.exec().Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) BatchUpdate(
|
||||
ctx context.Context,
|
||||
table string,
|
||||
keyField string,
|
||||
dataList []map[string]any,
|
||||
) error {
|
||||
|
||||
if len(dataList) == 0 {
|
||||
return fmt.Errorf("数据不能为空")
|
||||
func (c *Client) BatchUpdate(ctx context.Context, table, keyField string, list []map[string]any) error {
|
||||
if len(list) == 0 {
|
||||
return fmt.Errorf("empty data")
|
||||
}
|
||||
|
||||
first := dataList[0]
|
||||
first := list[0]
|
||||
if _, err := validateData(table, keyField, first); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 👉 表名加引号(支持 schema)
|
||||
tableParts := strings.Split(table, ".")
|
||||
for i, p := range tableParts {
|
||||
tableParts[i] = `"` + p + `"`
|
||||
}
|
||||
table = strings.Join(tableParts, ".")
|
||||
tableSQL := quoteTable(table)
|
||||
keySQL := quoteCol(keyField)
|
||||
|
||||
// 👉 keyField 加引号
|
||||
keyFieldQuoted := `"` + keyField + `"`
|
||||
|
||||
var columns []string
|
||||
for col := range first {
|
||||
if col != keyField {
|
||||
columns = append(columns, col)
|
||||
var cols []string
|
||||
for k := range first {
|
||||
if k != keyField {
|
||||
cols = append(cols, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(columns)
|
||||
sort.Strings(cols)
|
||||
|
||||
var (
|
||||
args []any
|
||||
argIndex = 1
|
||||
sets []string
|
||||
)
|
||||
|
||||
var setClauses []string
|
||||
for _, col := range cols {
|
||||
colSQL := quoteCol(col)
|
||||
|
||||
for _, col := range columns {
|
||||
colQuoted := `"` + col + `"`
|
||||
var caseSQL strings.Builder
|
||||
caseSQL.WriteString(fmt.Sprintf("%s = CASE %s ", colSQL, keySQL))
|
||||
|
||||
var caseBuilder strings.Builder
|
||||
caseBuilder.WriteString(fmt.Sprintf("%s = CASE %s ", colQuoted, keyFieldQuoted))
|
||||
for _, row := range list {
|
||||
row = applyMetaFields(ctx, table, row, false)
|
||||
|
||||
for _, data := range dataList {
|
||||
keyVal, err := validateData(table, keyField, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyVal, _ := row[keyField]
|
||||
val := row[col]
|
||||
|
||||
val, ok := data[col]
|
||||
if !ok {
|
||||
return fmt.Errorf("缺少字段: %s", col)
|
||||
}
|
||||
|
||||
caseBuilder.WriteString(fmt.Sprintf(
|
||||
caseSQL.WriteString(fmt.Sprintf(
|
||||
"WHEN $%d THEN $%d ",
|
||||
argIndex,
|
||||
argIndex+1,
|
||||
@@ -145,29 +97,23 @@ func (c *Client) BatchUpdate(
|
||||
argIndex += 2
|
||||
}
|
||||
|
||||
caseBuilder.WriteString("END")
|
||||
setClauses = append(setClauses, caseBuilder.String())
|
||||
caseSQL.WriteString("END")
|
||||
sets = append(sets, caseSQL.String())
|
||||
}
|
||||
|
||||
var wherePlaceholders []string
|
||||
|
||||
for _, data := range dataList {
|
||||
keyVal, ok := data[keyField]
|
||||
if !ok || keyVal == nil {
|
||||
return fmt.Errorf("缺少主键字段值: %s", keyField)
|
||||
}
|
||||
|
||||
wherePlaceholders = append(wherePlaceholders, fmt.Sprintf("$%d", argIndex))
|
||||
args = append(args, keyVal)
|
||||
var where []string
|
||||
for _, row := range list {
|
||||
where = append(where, fmt.Sprintf("$%d", argIndex))
|
||||
args = append(args, row[keyField])
|
||||
argIndex++
|
||||
}
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
"UPDATE %s SET %s WHERE %s IN (%s)",
|
||||
table,
|
||||
strings.Join(setClauses, ", "),
|
||||
keyFieldQuoted,
|
||||
strings.Join(wherePlaceholders, ", "),
|
||||
tableSQL,
|
||||
strings.Join(sets, ", "),
|
||||
keySQL,
|
||||
strings.Join(where, ", "),
|
||||
)
|
||||
|
||||
_, err := c.exec().Exec(ctx, sql, args...)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var identRe = regexp.MustCompile(`^[a-zA-Z0-9_]+$`)
|
||||
|
||||
// 安全标识符校验
|
||||
func safeIdent(name string) bool {
|
||||
return identRe.MatchString(name)
|
||||
}
|
||||
|
||||
// 表名引用(支持 schema)
|
||||
func quoteTable(table string) string {
|
||||
parts := strings.Split(table, ".")
|
||||
for i, p := range parts {
|
||||
if !safeIdent(p) {
|
||||
panic(fmt.Sprintf("invalid table: %s", p))
|
||||
}
|
||||
parts[i] = `"` + p + `"`
|
||||
}
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
// 字段引用
|
||||
func quoteCol(col string) string {
|
||||
if !safeIdent(col) {
|
||||
panic(fmt.Sprintf("invalid column: %s", col))
|
||||
}
|
||||
return `"` + col + `"`
|
||||
}
|
||||
|
||||
// 校验数据
|
||||
func validateData(table string, keyField string, data map[string]any) (any, error) {
|
||||
if table == "" {
|
||||
return nil, fmt.Errorf("表名不能为空")
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("数据不能为空")
|
||||
}
|
||||
|
||||
if keyField == "" {
|
||||
return nil, fmt.Errorf("主键字段不能为空")
|
||||
}
|
||||
|
||||
val, ok := data[keyField]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("缺少主键字段: %s", keyField)
|
||||
}
|
||||
|
||||
if val == nil {
|
||||
return nil, fmt.Errorf("主键字段值不能为空")
|
||||
}
|
||||
|
||||
return val, nil
|
||||
}
|
||||
Reference in new issue
Block a user