2026-05-02 13:02:38 +08:00

52 lines
1.3 KiB
Go

package auth
import (
"context"
"database/sql"
"fmt"
"hyapp/pkg/appcode"
)
const firstDisplayUserID int64 = 163000
// AllocateDisplayUserID 从数据库序列分配当前 App 下的默认短号。
// 这里不用内存计数,避免服务重启后从 163000 重新发号导致连续冲突。
func (r *Repository) AllocateDisplayUserID(ctx context.Context, appCode string) (string, error) {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer tx.Rollback()
normalized := appcode.Normalize(appCode)
var next int64
err = tx.QueryRowContext(ctx, `
SELECT next_value
FROM display_user_id_sequences
WHERE app_code = ?
FOR UPDATE
`, normalized).Scan(&next)
if err == sql.ErrNoRows {
next = firstDisplayUserID
_, err = tx.ExecContext(ctx, `
INSERT INTO display_user_id_sequences (app_code, next_value, updated_at_ms)
VALUES (?, ?, 0)
`, normalized, next+1)
} else if err == nil {
_, err = tx.ExecContext(ctx, `
UPDATE display_user_id_sequences
SET next_value = ?, updated_at_ms = CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS UNSIGNED)
WHERE app_code = ?
`, next+1, normalized)
}
if err != nil {
return "", err
}
if err := tx.Commit(); err != nil {
return "", err
}
return fmt.Sprintf("%d", next), nil
}