user and score
All checks were successful
Auth & User Management Service CI / build-services (app/auth_service/Dockerfile, auth_service, auth_service) (push) Successful in 36s
Auth & User Management Service CI / build-services (app/douyin_ecpm_calculation_service/Dockerfile, douyin_ecpm_calculation_service, douyin_ecpm_calculation_service) (push) Successful in 34s
Auth & User Management Service CI / build-services (app/ranking_management/Dockerfile, ranking_management, ranking_management) (push) Successful in 36s
Auth & User Management Service CI / build-services (app/user_management/Dockerfile, user_manager, user_management) (push) Successful in 35s
Auth & User Management Service CI / start-services (push) Successful in 8s

This commit is contained in:
xiabin 2025-02-13 14:37:02 +08:00
parent 7e3620c2ce
commit c09ed81544
9 changed files with 86 additions and 290 deletions

View File

@ -14,7 +14,7 @@ const TableNameGameScore = "game_score"
type GameScore struct { type GameScore struct {
ID uint64 `gorm:"column:id;type:bigint unsigned;primaryKey;autoIncrement:true" json:"id"` ID uint64 `gorm:"column:id;type:bigint unsigned;primaryKey;autoIncrement:true" json:"id"`
AppAccount uint32 `gorm:"column:app_account;type:int unsigned;not null;uniqueIndex:rank_list,priority:1;comment:小游戏id" json:"app_account"` // 小游戏id AppAccount uint32 `gorm:"column:app_account;type:int unsigned;not null;uniqueIndex:rank_list,priority:1;comment:小游戏id" json:"app_account"` // 小游戏id
AppUserID uint64 `gorm:"column:app_user_id;type:bigint unsigned;not null;uniqueIndex:rank_list,priority:3;index:user_id,priority:1;comment:用户id" json:"app_user_id"` // 用户id UserID uint64 `gorm:"column:user_id;type:bigint unsigned;not null;uniqueIndex:rank_list,priority:3;index:user_id,priority:1;comment:用户id" json:"user_id"` // 用户id
Score uint32 `gorm:"column:score;type:int unsigned;not null;comment:得分" json:"score"` // 得分 Score uint32 `gorm:"column:score;type:int unsigned;not null;comment:得分" json:"score"` // 得分
T uint32 `gorm:"column:t;type:tinyint unsigned;not null;uniqueIndex:rank_list,priority:2;comment:得分类型(区分相同小游戏中的不同模式得分)" json:"t"` // 得分类型(区分相同小游戏中的不同模式得分) T uint32 `gorm:"column:t;type:tinyint unsigned;not null;uniqueIndex:rank_list,priority:2;comment:得分类型(区分相同小游戏中的不同模式得分)" json:"t"` // 得分类型(区分相同小游戏中的不同模式得分)
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;comment:更新时间" json:"updated_at"` // 更新时间 UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;comment:更新时间" json:"updated_at"` // 更新时间

View File

@ -6,7 +6,6 @@ package query
import ( import (
"context" "context"
"strings"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
@ -18,7 +17,6 @@ import (
"gorm.io/plugin/dbresolver" "gorm.io/plugin/dbresolver"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/gen/dao/model" "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/gen/dao/model"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/pkg/my_gorm/gen/querier"
) )
func newGameScore(db *gorm.DB, opts ...gen.DOOption) gameScore { func newGameScore(db *gorm.DB, opts ...gen.DOOption) gameScore {
@ -31,7 +29,7 @@ func newGameScore(db *gorm.DB, opts ...gen.DOOption) gameScore {
_gameScore.ALL = field.NewAsterisk(tableName) _gameScore.ALL = field.NewAsterisk(tableName)
_gameScore.ID = field.NewUint64(tableName, "id") _gameScore.ID = field.NewUint64(tableName, "id")
_gameScore.AppAccount = field.NewUint32(tableName, "app_account") _gameScore.AppAccount = field.NewUint32(tableName, "app_account")
_gameScore.AppUserID = field.NewUint64(tableName, "app_user_id") _gameScore.UserID = field.NewUint64(tableName, "user_id")
_gameScore.Score = field.NewUint32(tableName, "score") _gameScore.Score = field.NewUint32(tableName, "score")
_gameScore.T = field.NewUint32(tableName, "t") _gameScore.T = field.NewUint32(tableName, "t")
_gameScore.UpdatedAt = field.NewTime(tableName, "updated_at") _gameScore.UpdatedAt = field.NewTime(tableName, "updated_at")
@ -42,15 +40,15 @@ func newGameScore(db *gorm.DB, opts ...gen.DOOption) gameScore {
} }
type gameScore struct { type gameScore struct {
gameScoreDo gameScoreDo gameScoreDo
ALL field.Asterisk ALL field.Asterisk
ID field.Uint64 ID field.Uint64
AppAccount field.Uint32 AppAccount field.Uint32 // 小游戏id
AppUserID field.Uint64 UserID field.Uint64 // 用户id
Score field.Uint32 Score field.Uint32 // 得分
T field.Uint32 T field.Uint32 // 得分类型(区分相同小游戏中的不同模式得分)
UpdatedAt field.Time UpdatedAt field.Time // 更新时间
fieldMap map[string]field.Expr fieldMap map[string]field.Expr
} }
@ -69,7 +67,7 @@ func (g *gameScore) updateTableName(table string) *gameScore {
g.ALL = field.NewAsterisk(table) g.ALL = field.NewAsterisk(table)
g.ID = field.NewUint64(table, "id") g.ID = field.NewUint64(table, "id")
g.AppAccount = field.NewUint32(table, "app_account") g.AppAccount = field.NewUint32(table, "app_account")
g.AppUserID = field.NewUint64(table, "app_user_id") g.UserID = field.NewUint64(table, "user_id")
g.Score = field.NewUint32(table, "score") g.Score = field.NewUint32(table, "score")
g.T = field.NewUint32(table, "t") g.T = field.NewUint32(table, "t")
g.UpdatedAt = field.NewTime(table, "updated_at") g.UpdatedAt = field.NewTime(table, "updated_at")
@ -79,6 +77,16 @@ func (g *gameScore) updateTableName(table string) *gameScore {
return g return g
} }
func (g *gameScore) WithContext(ctx context.Context) *gameScoreDo {
return g.gameScoreDo.WithContext(ctx)
}
func (g gameScore) TableName() string { return g.gameScoreDo.TableName() }
func (g gameScore) Alias() string { return g.gameScoreDo.Alias() }
func (g gameScore) Columns(cols ...field.Expr) gen.Columns { return g.gameScoreDo.Columns(cols...) }
func (g *gameScore) GetFieldByName(fieldName string) (field.OrderExpr, bool) { func (g *gameScore) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := g.fieldMap[fieldName] _f, ok := g.fieldMap[fieldName]
if !ok || _f == nil { if !ok || _f == nil {
@ -92,7 +100,7 @@ func (g *gameScore) fillFieldMap() {
g.fieldMap = make(map[string]field.Expr, 6) g.fieldMap = make(map[string]field.Expr, 6)
g.fieldMap["id"] = g.ID g.fieldMap["id"] = g.ID
g.fieldMap["app_account"] = g.AppAccount g.fieldMap["app_account"] = g.AppAccount
g.fieldMap["app_user_id"] = g.AppUserID g.fieldMap["user_id"] = g.UserID
g.fieldMap["score"] = g.Score g.fieldMap["score"] = g.Score
g.fieldMap["t"] = g.T g.fieldMap["t"] = g.T
g.fieldMap["updated_at"] = g.UpdatedAt g.fieldMap["updated_at"] = g.UpdatedAt
@ -110,211 +118,95 @@ func (g gameScore) replaceDB(db *gorm.DB) gameScore {
type gameScoreDo struct{ gen.DO } type gameScoreDo struct{ gen.DO }
type IGameScoreDo interface { func (g gameScoreDo) Debug() *gameScoreDo {
gen.SubQuery
Debug() IGameScoreDo
WithContext(ctx context.Context) IGameScoreDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() IGameScoreDo
WriteDB() IGameScoreDo
As(alias string) gen.Dao
Session(config *gorm.Session) IGameScoreDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) IGameScoreDo
Not(conds ...gen.Condition) IGameScoreDo
Or(conds ...gen.Condition) IGameScoreDo
Select(conds ...field.Expr) IGameScoreDo
Where(conds ...gen.Condition) IGameScoreDo
Order(conds ...field.Expr) IGameScoreDo
Distinct(cols ...field.Expr) IGameScoreDo
Omit(cols ...field.Expr) IGameScoreDo
Join(table schema.Tabler, on ...field.Expr) IGameScoreDo
LeftJoin(table schema.Tabler, on ...field.Expr) IGameScoreDo
RightJoin(table schema.Tabler, on ...field.Expr) IGameScoreDo
Group(cols ...field.Expr) IGameScoreDo
Having(conds ...gen.Condition) IGameScoreDo
Limit(limit int) IGameScoreDo
Offset(offset int) IGameScoreDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) IGameScoreDo
Unscoped() IGameScoreDo
Create(values ...*model.GameScore) error
CreateInBatches(values []*model.GameScore, batchSize int) error
Save(values ...*model.GameScore) error
First() (*model.GameScore, error)
Take() (*model.GameScore, error)
Last() (*model.GameScore, error)
Find() ([]*model.GameScore, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.GameScore, err error)
FindInBatches(result *[]*model.GameScore, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.GameScore) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) IGameScoreDo
Assign(attrs ...field.AssignExpr) IGameScoreDo
Joins(fields ...field.RelationField) IGameScoreDo
Preload(fields ...field.RelationField) IGameScoreDo
FirstOrInit() (*model.GameScore, error)
FirstOrCreate() (*model.GameScore, error)
FindByPage(offset int, limit int) (result []*model.GameScore, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) IGameScoreDo
UnderlyingDB() *gorm.DB
schema.Tabler
GetUserRank(appId uint32, userId uint64, t uint32) (result querier.RankingData, err error)
FindDistinctRanking() (result []*model.GameScore, err error)
}
// SELECT
//
// app_user.nickname,
// app_user.avatar,
// gs.score,
// gs.app_user_id,
// gs.t_rank
// FROM
// (
// SELECT
// game_score.score,
// game_score.app_user_id,
// game_score.app_account,
// rank() OVER (ORDER BY game_score.score DESC) t_rank
// FROM
// game_score
// WHERE
// game_score.t = @t
// AND game_score.app_account = @appId
// ) AS gs
// LEFT JOIN app_user ON app_user.id = gs.app_user_id
// WHERE
// gs.app_user_id = @userId
// LIMIT 1;
func (g gameScoreDo) GetUserRank(appId uint32, userId uint64, t uint32) (result querier.RankingData, err error) {
var params []interface{}
var generateSQL strings.Builder
params = append(params, t)
params = append(params, appId)
params = append(params, userId)
generateSQL.WriteString("SELECT app_user.nickname, app_user.avatar, gs.score, gs.app_user_id, gs.t_rank FROM ( SELECT game_score.score, game_score.app_user_id, game_score.app_account, rank() OVER (ORDER BY game_score.score DESC) t_rank FROM game_score WHERE game_score.t = ? AND game_score.app_account = ? ) AS gs LEFT JOIN app_user ON app_user.id = gs.app_user_id WHERE gs.app_user_id = ? LIMIT 1; ")
var executeSQL *gorm.DB
executeSQL = g.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert
err = executeSQL.Error
return
}
// select DISTINCT app_account,t from game_score
func (g gameScoreDo) FindDistinctRanking() (result []*model.GameScore, err error) {
var generateSQL strings.Builder
generateSQL.WriteString("select DISTINCT app_account,t from game_score ")
var executeSQL *gorm.DB
executeSQL = g.UnderlyingDB().Raw(generateSQL.String()).Find(&result) // ignore_security_alert
err = executeSQL.Error
return
}
func (g gameScoreDo) Debug() IGameScoreDo {
return g.withDO(g.DO.Debug()) return g.withDO(g.DO.Debug())
} }
func (g gameScoreDo) WithContext(ctx context.Context) IGameScoreDo { func (g gameScoreDo) WithContext(ctx context.Context) *gameScoreDo {
return g.withDO(g.DO.WithContext(ctx)) return g.withDO(g.DO.WithContext(ctx))
} }
func (g gameScoreDo) ReadDB() IGameScoreDo { func (g gameScoreDo) ReadDB() *gameScoreDo {
return g.Clauses(dbresolver.Read) return g.Clauses(dbresolver.Read)
} }
func (g gameScoreDo) WriteDB() IGameScoreDo { func (g gameScoreDo) WriteDB() *gameScoreDo {
return g.Clauses(dbresolver.Write) return g.Clauses(dbresolver.Write)
} }
func (g gameScoreDo) Session(config *gorm.Session) IGameScoreDo { func (g gameScoreDo) Session(config *gorm.Session) *gameScoreDo {
return g.withDO(g.DO.Session(config)) return g.withDO(g.DO.Session(config))
} }
func (g gameScoreDo) Clauses(conds ...clause.Expression) IGameScoreDo { func (g gameScoreDo) Clauses(conds ...clause.Expression) *gameScoreDo {
return g.withDO(g.DO.Clauses(conds...)) return g.withDO(g.DO.Clauses(conds...))
} }
func (g gameScoreDo) Returning(value interface{}, columns ...string) IGameScoreDo { func (g gameScoreDo) Returning(value interface{}, columns ...string) *gameScoreDo {
return g.withDO(g.DO.Returning(value, columns...)) return g.withDO(g.DO.Returning(value, columns...))
} }
func (g gameScoreDo) Not(conds ...gen.Condition) IGameScoreDo { func (g gameScoreDo) Not(conds ...gen.Condition) *gameScoreDo {
return g.withDO(g.DO.Not(conds...)) return g.withDO(g.DO.Not(conds...))
} }
func (g gameScoreDo) Or(conds ...gen.Condition) IGameScoreDo { func (g gameScoreDo) Or(conds ...gen.Condition) *gameScoreDo {
return g.withDO(g.DO.Or(conds...)) return g.withDO(g.DO.Or(conds...))
} }
func (g gameScoreDo) Select(conds ...field.Expr) IGameScoreDo { func (g gameScoreDo) Select(conds ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.Select(conds...)) return g.withDO(g.DO.Select(conds...))
} }
func (g gameScoreDo) Where(conds ...gen.Condition) IGameScoreDo { func (g gameScoreDo) Where(conds ...gen.Condition) *gameScoreDo {
return g.withDO(g.DO.Where(conds...)) return g.withDO(g.DO.Where(conds...))
} }
func (g gameScoreDo) Order(conds ...field.Expr) IGameScoreDo { func (g gameScoreDo) Order(conds ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.Order(conds...)) return g.withDO(g.DO.Order(conds...))
} }
func (g gameScoreDo) Distinct(cols ...field.Expr) IGameScoreDo { func (g gameScoreDo) Distinct(cols ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.Distinct(cols...)) return g.withDO(g.DO.Distinct(cols...))
} }
func (g gameScoreDo) Omit(cols ...field.Expr) IGameScoreDo { func (g gameScoreDo) Omit(cols ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.Omit(cols...)) return g.withDO(g.DO.Omit(cols...))
} }
func (g gameScoreDo) Join(table schema.Tabler, on ...field.Expr) IGameScoreDo { func (g gameScoreDo) Join(table schema.Tabler, on ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.Join(table, on...)) return g.withDO(g.DO.Join(table, on...))
} }
func (g gameScoreDo) LeftJoin(table schema.Tabler, on ...field.Expr) IGameScoreDo { func (g gameScoreDo) LeftJoin(table schema.Tabler, on ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.LeftJoin(table, on...)) return g.withDO(g.DO.LeftJoin(table, on...))
} }
func (g gameScoreDo) RightJoin(table schema.Tabler, on ...field.Expr) IGameScoreDo { func (g gameScoreDo) RightJoin(table schema.Tabler, on ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.RightJoin(table, on...)) return g.withDO(g.DO.RightJoin(table, on...))
} }
func (g gameScoreDo) Group(cols ...field.Expr) IGameScoreDo { func (g gameScoreDo) Group(cols ...field.Expr) *gameScoreDo {
return g.withDO(g.DO.Group(cols...)) return g.withDO(g.DO.Group(cols...))
} }
func (g gameScoreDo) Having(conds ...gen.Condition) IGameScoreDo { func (g gameScoreDo) Having(conds ...gen.Condition) *gameScoreDo {
return g.withDO(g.DO.Having(conds...)) return g.withDO(g.DO.Having(conds...))
} }
func (g gameScoreDo) Limit(limit int) IGameScoreDo { func (g gameScoreDo) Limit(limit int) *gameScoreDo {
return g.withDO(g.DO.Limit(limit)) return g.withDO(g.DO.Limit(limit))
} }
func (g gameScoreDo) Offset(offset int) IGameScoreDo { func (g gameScoreDo) Offset(offset int) *gameScoreDo {
return g.withDO(g.DO.Offset(offset)) return g.withDO(g.DO.Offset(offset))
} }
func (g gameScoreDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IGameScoreDo { func (g gameScoreDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *gameScoreDo {
return g.withDO(g.DO.Scopes(funcs...)) return g.withDO(g.DO.Scopes(funcs...))
} }
func (g gameScoreDo) Unscoped() IGameScoreDo { func (g gameScoreDo) Unscoped() *gameScoreDo {
return g.withDO(g.DO.Unscoped()) return g.withDO(g.DO.Unscoped())
} }
@ -380,22 +272,22 @@ func (g gameScoreDo) FindInBatches(result *[]*model.GameScore, batchSize int, fc
return g.DO.FindInBatches(result, batchSize, fc) return g.DO.FindInBatches(result, batchSize, fc)
} }
func (g gameScoreDo) Attrs(attrs ...field.AssignExpr) IGameScoreDo { func (g gameScoreDo) Attrs(attrs ...field.AssignExpr) *gameScoreDo {
return g.withDO(g.DO.Attrs(attrs...)) return g.withDO(g.DO.Attrs(attrs...))
} }
func (g gameScoreDo) Assign(attrs ...field.AssignExpr) IGameScoreDo { func (g gameScoreDo) Assign(attrs ...field.AssignExpr) *gameScoreDo {
return g.withDO(g.DO.Assign(attrs...)) return g.withDO(g.DO.Assign(attrs...))
} }
func (g gameScoreDo) Joins(fields ...field.RelationField) IGameScoreDo { func (g gameScoreDo) Joins(fields ...field.RelationField) *gameScoreDo {
for _, _f := range fields { for _, _f := range fields {
g = *g.withDO(g.DO.Joins(_f)) g = *g.withDO(g.DO.Joins(_f))
} }
return &g return &g
} }
func (g gameScoreDo) Preload(fields ...field.RelationField) IGameScoreDo { func (g gameScoreDo) Preload(fields ...field.RelationField) *gameScoreDo {
for _, _f := range fields { for _, _f := range fields {
g = *g.withDO(g.DO.Preload(_f)) g = *g.withDO(g.DO.Preload(_f))
} }

View File

@ -7,7 +7,6 @@ package query
import ( import (
"context" "context"
"fmt" "fmt"
"strconv"
"testing" "testing"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/gen/dao/model" "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/gen/dao/model"
@ -144,33 +143,3 @@ func Test_gameScoreQuery(t *testing.T) {
t.Error("Not/Or/Clauses on table <game_score> fail:", err) t.Error("Not/Or/Clauses on table <game_score> fail:", err)
} }
} }
var GameScoreGetUserRankTestCase = []TestCase{}
func Test_gameScore_GetUserRank(t *testing.T) {
gameScore := newGameScore(_gen_test_db)
do := gameScore.WithContext(context.Background()).Debug()
for i, tt := range GameScoreGetUserRankTestCase {
t.Run("GetUserRank_"+strconv.Itoa(i), func(t *testing.T) {
res1, res2 := do.GetUserRank(tt.Input.Args[0].(uint32), tt.Input.Args[1].(uint64), tt.Input.Args[2].(uint32))
assert(t, "GetUserRank", res1, tt.Expectation.Ret[0])
assert(t, "GetUserRank", res2, tt.Expectation.Ret[1])
})
}
}
var GameScoreFindDistinctRankingTestCase = []TestCase{}
func Test_gameScore_FindDistinctRanking(t *testing.T) {
gameScore := newGameScore(_gen_test_db)
do := gameScore.WithContext(context.Background()).Debug()
for i, tt := range GameScoreFindDistinctRankingTestCase {
t.Run("FindDistinctRanking_"+strconv.Itoa(i), func(t *testing.T) {
res1, res2 := do.FindDistinctRanking()
assert(t, "FindDistinctRanking", res1, tt.Expectation.Ret[0])
assert(t, "FindDistinctRanking", res2, tt.Expectation.Ret[1])
})
}
}

View File

@ -15,16 +15,6 @@ import (
"gorm.io/plugin/dbresolver" "gorm.io/plugin/dbresolver"
) )
var (
Q = new(Query)
GameScore *gameScore
)
func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
*Q = *Use(db, opts...)
GameScore = &Q.GameScore
}
func Use(db *gorm.DB, opts ...gen.DOOption) *Query { func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
return &Query{ return &Query{
db: db, db: db,
@ -63,7 +53,7 @@ func (q *Query) ReplaceDB(db *gorm.DB) *Query {
} }
type queryCtx struct { type queryCtx struct {
GameScore IGameScoreDo GameScore *gameScoreDo
} }
func (q *Query) WithContext(ctx context.Context) *queryCtx { func (q *Query) WithContext(ctx context.Context) *queryCtx {

View File

@ -1,76 +0,0 @@
package main
import (
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/gen/dao/model"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/pkg/my_gorm/gen/querier"
"gorm.io/driver/mysql"
"gorm.io/gen"
"gorm.io/gorm"
)
func main() {
g := gen.NewGenerator(gen.Config{
OutPath: "./app/ranking_management/internal/gen/dao/query",
Mode: gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
WithUnitTest: true,
})
dsn := "root:youtu!0113@tcp(192.168.0.47:3306)/ecpm?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// gormdb, _ := gorm.Open(mysql.Open("root:@(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"))
g.UseDB(db) // reuse your gorm db
//g.ApplyBasic(model.AppAccount{}, model.AppUser{}, model.DouyinEcpmConfig{}, model.GameScore{})
// Generate Type Safe API with Dynamic SQL defined on Querier interface for `model.User` and `model.Company`
g.ApplyInterface(func(querier.GameScoreQuerier) {}, model.GameScore{})
g.ApplyBasic(model.GameScore{})
// Generate the code
g.Execute()
}
type GameScoreQuerier interface {
/*
SELECT
app_user.nickname,
app_user.avatar,
gs.score,
gs.app_user_id,
gs.t_rank
FROM
(
SELECT
game_score.score,
game_score.app_user_id,
game_score.app_account,
rank() OVER (ORDER BY game_score.score DESC) t_rank
FROM
game_score
WHERE
game_score.t = @t
AND game_score.app_account = @appId
) AS gs
LEFT JOIN app_user ON app_user.id = gs.app_user_id
WHERE
gs.app_user_id = @userId
LIMIT 1;
*/
GetUserRank(appId uint32, userId uint64, t uint32) (resp RankingData, err error)
//select DISTINCT app_account,t from game_score
FindDistinctRanking() (resp []*gen.T, err error)
}
type RankingData struct {
Nickname string `json:"nickname" db:"nickname"` // 昵称
Avatar string `json:"avatar" db:"avatar"` // 头像
Score uint32 `json:"score" db:"score"` // 得分
UserId uint64 `json:"userId" db:"app_user_id"` // 用户 ID
Rank uint32 `json:"rank" db:"t_rank"` // 排名
Self bool `json:"self" db:"-"` // 是否是自己
}

View File

@ -7,6 +7,7 @@ import (
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/svc" "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/internal/svc"
ranking_management2 "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/ranking_management" ranking_management2 "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/ranking_management/ranking_management"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/user_management" "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/user_management"
"github.com/redis/go-redis/v9"
"gorm.io/gorm" "gorm.io/gorm"
"strconv" "strconv"
@ -28,7 +29,10 @@ func NewGetRankingListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Ge
} }
func (l *GetRankingListLogic) GetRankingList(in *ranking_management2.GetRankingListRequest) (resp *ranking_management2.GetRankingListResponse, err error) { func (l *GetRankingListLogic) GetRankingList(in *ranking_management2.GetRankingListRequest) (resp *ranking_management2.GetRankingListResponse, err error) {
cacheData, err := l.svcCtx.RedisRanking.GetList(l.ctx, rankings.GetRankingsCacheKey(in.AppId, in.Type), 0, 99) resp = new(ranking_management2.GetRankingListResponse)
cacheKey := rankings.GetRankingsCacheKey(in.AppId, in.Type)
cacheData, err := l.svcCtx.RedisRanking.GetList(l.ctx, cacheKey, 0, 99)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -63,19 +67,32 @@ func (l *GetRankingListLogic) GetRankingList(in *ranking_management2.GetRankingL
} }
if !flag { if !flag {
tmp, err := l.svcCtx.Query.GameScore.GetUserRank(in.AppId, in.UserId, in.Type) rank, err := l.svcCtx.RedisRanking.GetRank(l.ctx, cacheKey, strconv.FormatUint(in.UserId, 10))
if err != nil {
//如果没有找到,则创建一个空的数据
if errors.Is(err, redis.Nil) {
resp.RankingData = append(resp.RankingData, new(ranking_management2.RankingList))
return resp, nil
}
return nil, err
}
score, err := l.svcCtx.RedisRanking.GetScore(l.ctx, cacheKey, strconv.FormatUint(in.UserId, 10))
if err != nil {
return nil, err
}
tmp, err := l.svcCtx.UserManagerClient.GetUserById(l.ctx, &user_management.UserId{UserId: in.UserId})
//tmp, err := l.svcCtx.Query.GameScore.GetUserRank(in.AppId, in.UserId, in.Type)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err return nil, err
} }
userRank = &ranking_management2.RankingList{ userRank = &ranking_management2.RankingList{
Nickname: tmp.Nickname, Nickname: tmp.Nickname,
Avatar: tmp.Avatar, Avatar: tmp.Avatar,
Score: tmp.Score, Score: uint32(score),
Rank: tmp.Rank, Rank: uint32(rank),
Self: tmp.Self, Self: true,
UserId: tmp.UserId, UserId: in.UserId,
} }
userRank.Self = true
} }
resp.RankingData = append(resp.RankingData, userRank) resp.RankingData = append(resp.RankingData, userRank)

View File

@ -35,7 +35,7 @@ func (l *SetUserGameScoreLogic) SetUserGameScore(in *ranking_management.SetUserG
oldScore, err := gs. oldScore, err := gs.
WithContext(l.ctx). WithContext(l.ctx).
Where( Where(
gs.AppUserID.Eq(in.UserId), gs.UserID.Eq(in.UserId),
gs.AppAccount.Eq(in.AppId), gs.AppAccount.Eq(in.AppId),
gs.T.Eq(in.Type), gs.T.Eq(in.Type),
). ).
@ -56,7 +56,7 @@ func (l *SetUserGameScoreLogic) SetUserGameScore(in *ranking_management.SetUserG
oldScore.Score = in.Score oldScore.Score = in.Score
oldScore.T = in.Type oldScore.T = in.Type
oldScore.AppUserID = in.UserId oldScore.UserID = in.UserId
oldScore.AppAccount = in.AppId oldScore.AppAccount = in.AppId
// 更新数据库 // 更新数据库

View File

@ -68,13 +68,13 @@ func (svc *ServiceContext) InitRankings(redisClient *redis.Client) {
//获取所有不同的排行榜 //获取所有不同的排行榜
gs := svc.Query.GameScore gs := svc.Query.GameScore
r, err := gs.FindDistinctRanking() r, err := gs.WithContext(context.TODO()).Select(gs.AppAccount, gs.T).Distinct().Find()
if err != nil { if err != nil {
panic(err) panic(err)
} }
//获取所有排行榜 //获取所有排行榜
for _, ranking := range r { for _, ranking := range r {
scores, err := gs.Where(gs.AppAccount.Eq(ranking.AppAccount), gs.T.Eq(ranking.T)).Find() scores, err := gs.WithContext(context.TODO()).Where(gs.AppAccount.Eq(ranking.AppAccount), gs.T.Eq(ranking.T)).Find()
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -83,7 +83,7 @@ func (svc *ServiceContext) InitRankings(redisClient *redis.Client) {
for _, score := range scores { for _, score := range scores {
data = append(data, redis.Z{ data = append(data, redis.Z{
Score: float64(uint64(score.Score)<<32 + uint64(score.UpdatedAt.Unix())), Score: float64(uint64(score.Score)<<32 + uint64(score.UpdatedAt.Unix())),
Member: score.AppUserID, Member: score.UserID,
}) })
} }
svc.RedisRanking.SetList(context.Background(), rankings.GetRankingsCacheKey(ranking.AppAccount, ranking.T), data...) svc.RedisRanking.SetList(context.Background(), rankings.GetRankingsCacheKey(ranking.AppAccount, ranking.T), data...)

View File

@ -3,6 +3,7 @@ package logic
import ( import (
"context" "context"
"errors" "errors"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/internal/gen/dao/model"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/internal/svc" "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/internal/svc"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/user_management" "gitea.youtukeji.com.cn/youtu/youtu_grpc/app/user_management/user_management"
@ -30,7 +31,10 @@ func (l *SetUserLogic) SetUser(in *user_management.SetUserRequest) (*user_manage
return nil, errors.New("参数错误") return nil, errors.New("参数错误")
} }
user := l.svcCtx.Query.User user := l.svcCtx.Query.User
update, err := user.WithContext(l.ctx).Where(user.ID.Eq(in.UserId)).Update(user.Avatar, user.Nickname) update, err := user.WithContext(l.ctx).Where(user.ID.Eq(in.UserId)).Updates(model.User{
Nickname: in.Nickname,
Avatar: in.Avatar,
})
if err != nil { if err != nil {
return nil, err return nil, err
} }