阶段十:完成 Go DB 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:01:13 +08:00
1 parent c47271ae9c
commit 668a4ed3f3
46 files changed
+3030 -19464

No files matched your search

+150 -28
View File
@@ -21,11 +21,14 @@ type KeywordRow struct {
ImageURL string
}
// UpdateByID 更新ByID。
func (k *Keywords) UpdateByID(ctx context.Context, row KeywordRow) error {
// kwType 保存kw类型,供当前处理流程使用
kwType := row.Type
if kwType == "" {
kwType = "text"
}
// res、err 保存res、err,供当前处理流程使用
res, err := k.DB.ExecContext(ctx, `UPDATE keywords
SET keyword=?,reply=?,item_id=?,type=?,image_url=?
WHERE id=? AND cookie_id=?`,
@@ -33,18 +36,22 @@ func (k *Keywords) UpdateByID(ctx context.Context, row KeywordRow) error {
if err != nil {
return err
}
if affected, err := res.RowsAffected(); err == nil && affected == 0 {
if // affected、err 保存affected、err,供当前处理流程使用
affected, err := res.RowsAffected(); err == nil && affected == 0 {
return ErrNotFound
}
return nil
}
// DeleteByID 删除ByID。
func (k *Keywords) DeleteByID(ctx context.Context, cookieID string, id int64) error {
// res、err 保存res、err,供当前处理流程使用
res, err := k.DB.ExecContext(ctx, `DELETE FROM keywords WHERE id=? AND cookie_id=?`, id, cookieID)
if err != nil {
return err
}
if affected, err := res.RowsAffected(); err == nil && affected == 0 {
if // affected、err 保存affected、err,供当前处理流程使用
affected, err := res.RowsAffected(); err == nil && affected == 0 {
return ErrNotFound
}
return nil
@@ -52,6 +59,7 @@ func (k *Keywords) DeleteByID(ctx context.Context, cookieID string, id int64) er
// AllRows 取某账号所有关键字(含 id)。
func (k *Keywords) AllRows(ctx context.Context, cookieID string) ([]KeywordRow, error) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := k.DB.QueryContext(ctx,
`SELECT id, keyword, reply, COALESCE(item_id,''), COALESCE(type,'text'), COALESCE(image_url,'')
FROM keywords WHERE cookie_id=? ORDER BY id`, cookieID)
@@ -59,10 +67,13 @@ func (k *Keywords) AllRows(ctx context.Context, cookieID string) ([]KeywordRow,
return nil, err
}
defer rows.Close()
// out 保存out,供当前处理流程使用
var out []KeywordRow
for rows.Next() {
// r 保存r,供当前处理流程使用
var r KeywordRow
if err := rows.Scan(&r.ID, &r.Keyword, &r.Reply, &r.ItemID, &r.Type, &r.ImageURL); err != nil {
if // err 保存err,供当前处理流程使用
err := rows.Scan(&r.ID, &r.Keyword, &r.Reply, &r.ItemID, &r.Type, &r.ImageURL); err != nil {
return nil, err
}
r.CookieID = cookieID
@@ -83,20 +94,25 @@ func (k *Keywords) Add(ctx context.Context, cookieID, keyword, reply, itemID, kw
// ReplaceForCookie 覆盖某账号的全部关键词。
func (k *Keywords) ReplaceForCookie(ctx context.Context, cookieID string, rows []KeywordRow) error {
// tx、err 保存tx、err,供当前处理流程使用
tx, err := k.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `DELETE FROM keywords WHERE cookie_id=?`, cookieID); err != nil {
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, `DELETE FROM keywords WHERE cookie_id=?`, cookieID); err != nil {
return err
}
// row 表示当前遍历过程中的row
for _, row := range rows {
// kwType 保存kw类型,供当前处理流程使用
kwType := row.Type
if kwType == "" {
kwType = "text"
}
if _, err := tx.ExecContext(ctx,
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx,
`INSERT INTO keywords (cookie_id, keyword, reply, item_id, type, image_url) VALUES (?,?,?,?,?,?)`,
cookieID, row.Keyword, row.Reply, nullable(row.ItemID), kwType, nullable(row.ImageURL)); err != nil {
return err
@@ -107,16 +123,20 @@ func (k *Keywords) ReplaceForCookie(ctx context.Context, cookieID string, rows [
// DeleteByIndex 按索引(0-based,按 id 顺序)删除某账号的一个关键字。
func (k *Keywords) DeleteByIndex(ctx context.Context, cookieID string, index int) error {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := k.DB.QueryContext(ctx,
`SELECT id FROM keywords WHERE cookie_id=? ORDER BY id`, cookieID)
if err != nil {
return err
}
defer rows.Close()
// ids 保存ids,供当前处理流程使用
var ids []int64
for rows.Next() {
// id 保存标识,供当前处理流程使用
var id int64
if err := rows.Scan(&id); err != nil {
if // err 保存err,供当前处理流程使用
err := rows.Scan(&id); err != nil {
return err
}
ids = append(ids, id)
@@ -134,6 +154,7 @@ func (k *Keywords) DeleteByIndex(ctx context.Context, cookieID string, index int
// Set 设置指定商品回复。
func (i *ItemReplies) Set(ctx context.Context, cookieID, itemID, content string) error {
// tx、err 保存tx、err,供当前处理流程使用
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return err
@@ -143,7 +164,8 @@ func (i *ItemReplies) Set(ctx context.Context, cookieID, itemID, content string)
if _, err := tx.ExecContext(ctx, `DELETE FROM item_replay WHERE cookie_id=? AND item_id=?`, cookieID, itemID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx,
`INSERT INTO item_replay (item_id, cookie_id, reply_content, updated_at)
VALUES (?,?,?,CURRENT_TIMESTAMP)`, itemID, cookieID, content); err != nil {
return err
@@ -153,6 +175,7 @@ func (i *ItemReplies) Set(ctx context.Context, cookieID, itemID, content string)
// Delete 删除指定商品回复。
func (i *ItemReplies) Delete(ctx context.Context, cookieID, itemID string) error {
// err 保存err,供当前处理流程使用
_, err := i.DB.ExecContext(ctx,
`DELETE FROM item_replay WHERE cookie_id=? AND item_id=?`, cookieID, itemID)
return err
@@ -160,16 +183,20 @@ func (i *ItemReplies) Delete(ctx context.Context, cookieID, itemID string) error
// AllForUser 取某账号所有指定商品回复。
func (i *ItemReplies) AllForUser(ctx context.Context, cookieID string) ([]ItemReply, error) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := i.DB.QueryContext(ctx,
`SELECT item_id, cookie_id, reply_content FROM item_replay WHERE cookie_id=?`, cookieID)
if err != nil {
return nil, err
}
defer rows.Close()
// out 保存out,供当前处理流程使用
var out []ItemReply
for rows.Next() {
// r 保存r,供当前处理流程使用
var r ItemReply
if err := rows.Scan(&r.ItemID, &r.CookieID, &r.ReplyContent); err != nil {
if // err 保存err,供当前处理流程使用
err := rows.Scan(&r.ItemID, &r.CookieID, &r.ReplyContent); err != nil {
return nil, err
}
out = append(out, r)
@@ -192,6 +219,7 @@ type NotificationChannelRow struct {
// AllChannelsForUser 取某用户全部通知渠道。
func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([]NotificationChannelRow, error) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := n.DB.QueryContext(ctx,
`SELECT id, name, type, config, COALESCE(event_types,''), enabled, COALESCE(user_id,1) FROM notification_channels
WHERE user_id=? ORDER BY id DESC`, userID)
@@ -199,11 +227,15 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
return nil, err
}
defer rows.Close()
// out 保存out,供当前处理流程使用
var out []NotificationChannelRow
for rows.Next() {
// c 保存c,供当前处理流程使用
var c NotificationChannelRow
// enabled 保存启用状态,供当前处理流程使用
var enabled int
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
if // err 保存err,供当前处理流程使用
err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
return nil, err
}
c.Config, err = n.codec.decrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
@@ -218,6 +250,7 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
// CreateChannel 创建通知渠道。
func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChannelRow) (int64, error) {
// config、err 保存config、err,供当前处理流程使用
config, err := n.codec.encrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
if err != nil {
return 0, err
@@ -230,10 +263,12 @@ func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChanne
// UpdateChannel 更新通知渠道。
func (n *Notifications) UpdateChannel(ctx context.Context, c *NotificationChannelRow) error {
if c.UserID == 0 {
if err := n.DB.QueryRowContext(ctx, `SELECT COALESCE(user_id,1) FROM notification_channels WHERE id=?`, c.ID).Scan(&c.UserID); err != nil {
if // err 保存err,供当前处理流程使用
err := n.DB.QueryRowContext(ctx, `SELECT COALESCE(user_id,1) FROM notification_channels WHERE id=?`, c.ID).Scan(&c.UserID); err != nil {
return err
}
}
// config、err 保存config、err,供当前处理流程使用
config, err := n.codec.encrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
if err != nil {
return err
@@ -246,18 +281,23 @@ func (n *Notifications) UpdateChannel(ctx context.Context, c *NotificationChanne
// GetChannelRowForUser 按用户取单个通知渠道。未找到返回 nil。
func (n *Notifications) GetChannelRowForUser(ctx context.Context, id, userID int64) (*NotificationChannelRow, error) {
// row 保存row,供当前处理流程使用
row := n.DB.QueryRowContext(ctx,
`SELECT id, name, type, config, COALESCE(event_types,''), enabled, COALESCE(user_id,1)
FROM notification_channels WHERE id=? AND user_id=?`, id, userID)
// c 保存c,供当前处理流程使用
var c NotificationChannelRow
// enabled 保存启用状态,供当前处理流程使用
var enabled int
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
if // err 保存err,供当前处理流程使用
err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
c.Enabled = enabled != 0
// config、err 保存config、err,供当前处理流程使用
config, err := n.codec.decrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
if err != nil {
return nil, err
@@ -268,10 +308,12 @@ func (n *Notifications) GetChannelRowForUser(ctx context.Context, id, userID int
// UpdateChannelForUser 更新指定用户拥有的通知渠道。
func (n *Notifications) UpdateChannelForUser(ctx context.Context, c *NotificationChannelRow, userID int64) error {
// config、err 保存config、err,供当前处理流程使用
config, err := n.codec.encrypt("notification-config", strconv.FormatInt(userID, 10), c.Config)
if err != nil {
return err
}
// res、err 保存res、err,供当前处理流程使用
res, err := n.DB.ExecContext(ctx,
`UPDATE notification_channels
SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP
@@ -280,6 +322,7 @@ func (n *Notifications) UpdateChannelForUser(ctx context.Context, c *Notificatio
if err != nil {
return err
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := res.RowsAffected()
if err == nil && rows == 0 {
return ErrNotFound
@@ -289,16 +332,19 @@ func (n *Notifications) UpdateChannelForUser(ctx context.Context, c *Notificatio
// DeleteChannel 删除通知渠道。
func (n *Notifications) DeleteChannel(ctx context.Context, id int64) error {
// err 保存err,供当前处理流程使用
_, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=?`, id)
return err
}
// DeleteChannelForUser 删除指定用户拥有的通知渠道。
func (n *Notifications) DeleteChannelForUser(ctx context.Context, id, userID int64) error {
// res、err 保存res、err,供当前处理流程使用
res, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=? AND user_id=?`, id, userID)
if err != nil {
return err
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := res.RowsAffected()
if err == nil && rows == 0 {
return ErrNotFound
@@ -308,16 +354,21 @@ func (n *Notifications) DeleteChannelForUser(ctx context.Context, id, userID int
// GetChannel 按 ID 取单个通知渠道(含 config)。未找到返回 nil。
func (n *Notifications) GetChannel(ctx context.Context, id int64) (*NotificationChannel, error) {
// row 保存row,供当前处理流程使用
row := n.DB.QueryRowContext(ctx,
`SELECT id, name, type, config, COALESCE(event_types,''), COALESCE(user_id,1) FROM notification_channels WHERE id=?`, id)
// c 保存c,供当前处理流程使用
var c NotificationChannel
// userID 保存用户ID,供当前处理流程使用
var userID int64
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &userID); err != nil {
if // err 保存err,供当前处理流程使用
err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &userID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
// config、err 保存config、err,供当前处理流程使用
config, err := n.codec.decrypt("notification-config", strconv.FormatInt(userID, 10), c.Config)
if err != nil {
return nil, err
@@ -328,6 +379,7 @@ func (n *Notifications) GetChannel(ctx context.Context, id int64) (*Notification
// AccountBindings 取某账号已绑定的通知渠道 ID 列表。
func (n *Notifications) AccountBindings(ctx context.Context, cookieID string) ([]int64, error) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := n.DB.QueryContext(ctx,
`SELECT mn.channel_id
FROM message_notifications mn
@@ -338,10 +390,13 @@ func (n *Notifications) AccountBindings(ctx context.Context, cookieID string) ([
return nil, err
}
defer rows.Close()
// out 保存out,供当前处理流程使用
var out []int64
for rows.Next() {
// id 保存标识,供当前处理流程使用
var id int64
if err := rows.Scan(&id); err != nil {
if // err 保存err,供当前处理流程使用
err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
@@ -351,21 +406,27 @@ func (n *Notifications) AccountBindings(ctx context.Context, cookieID string) ([
// SetBindings 设置某账号的通知渠道绑定(覆盖式)。
func (n *Notifications) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
// tx、err 保存tx、err,供当前处理流程使用
tx, err := n.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// userID 保存用户ID,供当前处理流程使用
var userID int64
if err := tx.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&userID); err != nil {
if // err 保存err,供当前处理流程使用
err := tx.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&userID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
}
// channelID 表示当前遍历过程中的渠道ID
for _, channelID := range channelIDs {
// exists 保存exists,供当前处理流程使用
var exists bool
if err := tx.QueryRowContext(ctx,
if // err 保存err,供当前处理流程使用
err := tx.QueryRowContext(ctx,
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
channelID, userID).Scan(&exists); err != nil {
return err
@@ -374,11 +435,14 @@ func (n *Notifications) SetBindings(ctx context.Context, cookieID string, channe
return ErrForbidden
}
}
if _, err := tx.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=?`, cookieID); err != nil {
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=?`, cookieID); err != nil {
return err
}
// cid 表示当前遍历过程中的cid
for _, cid := range channelIDs {
if _, err := tx.ExecContext(ctx,
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx,
`INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES (?,?,1)`,
cookieID, cid); err != nil {
return err
@@ -398,8 +462,11 @@ type SystemSettings struct {
// Get 取单项设置。
func (s *SystemSettings) Get(ctx context.Context, key string) (string, error) {
// v 保存v,供当前处理流程使用
var v string
// keyCol 保存keyCol,供当前处理流程使用
keyCol := dialectQuote(s.Dialect, "key")
// err 保存err,供当前处理流程使用
err := s.DB.QueryRowContext(ctx, `SELECT value FROM system_settings WHERE `+keyCol+`=?`, key).Scan(&v)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
@@ -415,16 +482,21 @@ func (s *SystemSettings) Get(ctx context.Context, key string) (string, error) {
// All 取全部设置(key→value)。
func (s *SystemSettings) All(ctx context.Context) (map[string]string, error) {
// keyCol 保存keyCol,供当前处理流程使用
keyCol := dialectQuote(s.Dialect, "key")
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.DB.QueryContext(ctx, `SELECT `+keyCol+`, value FROM system_settings`)
if err != nil {
return nil, err
}
defer rows.Close()
// m 保存m,供当前处理流程使用
m := make(map[string]string)
for rows.Next() {
// k、v 保存k、v,供当前处理流程使用
var k, v string
if err := rows.Scan(&k, &v); err != nil {
if // err 保存err,供当前处理流程使用
err := rows.Scan(&k, &v); err != nil {
return nil, err
}
if isSensitiveSettingKey(k) {
@@ -441,13 +513,16 @@ func (s *SystemSettings) All(ctx context.Context) (map[string]string, error) {
// Set 设置单项。
func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
if isSensitiveSettingKey(key) {
// encrypted、err 保存encrypted、err,供当前处理流程使用
encrypted, err := s.codec.encrypt("system-setting", key, value)
if err != nil {
return err
}
value = encrypted
}
// keyCol 保存keyCol,供当前处理流程使用
keyCol := dialectQuote(s.Dialect, "key")
// err 保存err,供当前处理流程使用
_, err := s.DB.ExecContext(ctx,
`INSERT INTO system_settings (`+keyCol+`, value, updated_at) VALUES (?,?,CURRENT_TIMESTAMP)`+
dialectUpsert(s.Dialect, []string{keyCol}, map[string]string{
@@ -460,25 +535,31 @@ func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
// SetMany 在单个事务中原子保存多项设置。
func (s *SystemSettings) SetMany(ctx context.Context, values map[string]string) error {
// tx、err 保存tx、err,供当前处理流程使用
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// keyCol 保存keyCol,供当前处理流程使用
keyCol := dialectQuote(s.Dialect, "key")
// query 保存查询,供当前处理流程使用
query := `INSERT INTO system_settings (` + keyCol + `, value, updated_at) VALUES (?,?,CURRENT_TIMESTAMP)` +
dialectUpsert(s.Dialect, []string{keyCol}, map[string]string{
"value": "EXCLUDED.value", "updated_at": "CURRENT_TIMESTAMP",
})
// key、value 表示当前遍历过程中的key、value
for key, value := range values {
if isSensitiveSettingKey(key) {
// encrypted、err 保存encrypted、err,供当前处理流程使用
encrypted, err := s.codec.encrypt("system-setting", key, value)
if err != nil {
return err
}
value = encrypted
}
if _, err := tx.ExecContext(ctx, query, key, value); err != nil {
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, query, key, value); err != nil {
return err
}
}
@@ -492,13 +573,17 @@ var PublicSystemKeys = map[string]bool{
// Public 取公开设置子集。
func (s *SystemSettings) Public(ctx context.Context) (map[string]string, error) {
// all、err 保存all、err,供当前处理流程使用
all, err := s.All(ctx)
if err != nil {
return nil, err
}
// out 保存out,供当前处理流程使用
out := make(map[string]string)
// k 表示当前遍历过程中的k
for k := range PublicSystemKeys {
if v, ok := all[k]; ok {
if // v、ok 保存v、ok,供当前处理流程使用
v, ok := all[k]; ok {
out[k] = v
}
}
@@ -529,6 +614,7 @@ type ItemSyncResult struct {
// AllForCookie 取某账号全部商品。
func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := i.DB.QueryContext(ctx,
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
@@ -538,11 +624,15 @@ func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRo
return nil, err
}
defer rows.Close()
// out 保存out,供当前处理流程使用
var out []ItemInfoRow
for rows.Next() {
// r 保存r,供当前处理流程使用
var r ItemInfoRow
// isMulti、multiQty 保存isMulti、multiQty,供当前处理流程使用
var isMulti, multiQty int
if err := rows.Scan(&r.ID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.ItemDescription,
if // err 保存err,供当前处理流程使用
err := rows.Scan(&r.ID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.ItemDescription,
&r.ItemCategory, &r.ItemPrice, &r.ItemDetail, &isMulti, &multiQty); err != nil {
return nil, err
}
@@ -555,6 +645,7 @@ func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRo
// Upsert 插入或更新商品信息。
func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error {
// err 保存err,供当前处理流程使用
_, err := i.DB.ExecContext(ctx,
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery, updated_at)
@@ -581,6 +672,7 @@ func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error {
return i.upsertBasic(ctx, i.DB, r)
}
// UpsertBasicTx 负责UpsertBasicTx相关处理。
func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) error {
return i.upsertBasic(ctx, tx, r)
}
@@ -590,41 +682,51 @@ func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) e
// 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段
// (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内
// 完成,只有在全部远端商品写入成功后,才会逻辑删除本次全集中不存在的本地商品及其商品级自动化规则。
// SyncFromRemote 同步FromRemote。
func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) {
cookieID = strings.TrimSpace(cookieID)
if cookieID == "" {
return ItemSyncResult{}, errors.New("cookie_id 不能为空")
}
// remoteIDs 保存remoteIDs,供当前处理流程使用
remoteIDs := make(map[string]struct{}, len(rows))
// validRows 保存有效Rows,供当前处理流程使用
validRows := make([]ItemInfoRow, 0, len(rows))
// row 表示当前遍历过程中的row
for _, row := range rows {
row.CookieID = cookieID
row.ItemID = strings.TrimSpace(row.ItemID)
if row.ItemID == "" {
continue
}
if _, exists := remoteIDs[row.ItemID]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := remoteIDs[row.ItemID]; exists {
continue
}
remoteIDs[row.ItemID] = struct{}{}
validRows = append(validRows, row)
}
// tx、err 保存tx、err,供当前处理流程使用
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return ItemSyncResult{}, err
}
// rollback 保存rollback,供当前处理流程使用
rollback := func(err error) (ItemSyncResult, error) {
_ = tx.Rollback()
return ItemSyncResult{}, err
}
// index 表示当前遍历过程中的index
for index := range validRows {
if err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
if // err 保存err,供当前处理流程使用
err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
return rollback(err)
}
if validRows[index].IsMultiSpec {
if _, err := tx.ExecContext(ctx,
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=? WHERE cookie_id=? AND item_id=?`,
boolToInt(true), cookieID, validRows[index].ItemID); err != nil {
return rollback(err)
@@ -632,51 +734,65 @@ func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []Item
}
}
// args 保存args,供当前处理流程使用
args := make([]any, 0, len(remoteIDs)+1)
args = append(args, cookieID)
// deleteQuery 保存delete查询,供当前处理流程使用
deleteQuery := `UPDATE item_info SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND deleted_at IS NULL`
if len(remoteIDs) > 0 {
// placeholders 保存placeholders,供当前处理流程使用
placeholders := make([]string, 0, len(remoteIDs))
// itemID 表示当前遍历过程中的商品ID
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
args = append(args, itemID)
}
deleteQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
// deletedResult、err 保存deletedResult、err,供当前处理流程使用
deletedResult, err := tx.ExecContext(ctx, deleteQuery, args...)
if err != nil {
return rollback(err)
}
// deleted、err 保存deleted、err,供当前处理流程使用
deleted, err := deletedResult.RowsAffected()
if err != nil {
return rollback(err)
}
// ruleArgs 保存规则Args,供当前处理流程使用
ruleArgs := make([]any, 0, len(remoteIDs)+1)
ruleArgs = append(ruleArgs, cookieID)
// ruleQuery 保存规则查询,供当前处理流程使用
ruleQuery := `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id<>'' AND deleted_at IS NULL`
if len(remoteIDs) > 0 {
// placeholders 保存placeholders,供当前处理流程使用
placeholders := make([]string, 0, len(remoteIDs))
// itemID 表示当前遍历过程中的商品ID
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
ruleArgs = append(ruleArgs, itemID)
}
ruleQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
if _, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil {
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil {
return rollback(err)
}
if err := tx.Commit(); err != nil {
if // err 保存err,供当前处理流程使用
err := tx.Commit(); err != nil {
return ItemSyncResult{}, err
}
return ItemSyncResult{Saved: len(validRows), Deleted: int(deleted)}, nil
}
// upsertBasic 负责upsertBasic相关处理。
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
// conflictClause 保存conflictClause,供当前处理流程使用
var conflictClause string
switch i.Dialect {
case DialectMySQL:
@@ -698,6 +814,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
deleted_at=NULL,
updated_at=CURRENT_TIMESTAMP`
}
// err 保存err,供当前处理流程使用
_, err := execer.ExecContext(ctx,
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
item_category, item_price, item_detail, updated_at)
@@ -709,17 +826,20 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
// Delete 逻辑删除商品及其商品级自动化规则,保留历史数据以便审计和恢复。
func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error {
// tx、err 保存tx、err,供当前处理流程使用
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `UPDATE item_info
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, `UPDATE item_info
SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE automation_rules
if // err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
return err
@@ -729,6 +849,7 @@ func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error {
// SetMultiSpec 设置多规格开关。
func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error {
// err 保存err,供当前处理流程使用
_, err := i.DB.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
boolToInt(on), cookieID, itemID)
@@ -737,6 +858,7 @@ func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bo
// SetMultiQuantity 设置多数量发货开关。
func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error {
// err 保存err,供当前处理流程使用
_, err := i.DB.ExecContext(ctx,
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
boolToInt(on), cookieID, itemID)