Compare commits
10 Commits
1e96ec3b25
...
e5831ea5b7
Author | SHA1 | Date | |
---|---|---|---|
e5831ea5b7 | |||
bc110382df | |||
150e241c4d | |||
9de52d82b0 | |||
f638652270 | |||
9cc97b5c06 | |||
7f7a881d46 | |||
cf601f9466 | |||
23a91824a0 | |||
5acaf1028b |
@ -2,10 +2,15 @@
|
||||
|
||||
```shell
|
||||
goctl api go -api .\game_open_api\app_user.api -dir .\game_open_api\ --style=go_zero
|
||||
goctl api go -api ./game_open_api/app_user.api -dir ./game_open_api --style=go_zero
|
||||
|
||||
goctl rpc protoc .\dw_server\dw_server.proto --go-grpc_out .\dw_server\ --go_out .\dw_server\ --zrpc_out .\dw_server\ -c -style go_zero
|
||||
|
||||
goctl model mysql datasource -c -dir .\game_open_api\model\ --url 'root:youtu!0113@tcp(127.0.0.1:3306)/ecpm' -t game_score -style go_zero
|
||||
|
||||
docker exec -i mysql mysqldump -uroot -p'youtu!0113' ecpm > ecpm_backup.sql
|
||||
|
||||
docker build -t youtu_server -f game_open_api/Dockerfile .
|
||||
|
||||
docker save youtu_server -o ./images.tar
|
||||
```
|
37
docker-compose-dev.yaml
Normal file
37
docker-compose-dev.yaml
Normal file
@ -0,0 +1,37 @@
|
||||
version: "3"
|
||||
services:
|
||||
mysql:
|
||||
image: mysql
|
||||
container_name: mysql
|
||||
restart: always
|
||||
command: [
|
||||
'--character-set-server=utf8mb4',
|
||||
'--collation-server=utf8mb4_general_ci',
|
||||
'--explicit_defaults_for_timestamp=true',
|
||||
'--lower_case_table_names=1'
|
||||
]
|
||||
ports:
|
||||
- "3306:3306"
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: youtu!0113
|
||||
MYSQL_INITDB_SKIP_TZINFO: "Asia/Shanghai"
|
||||
MYSQL_DATABASE: ecpm
|
||||
volumes:
|
||||
##初始化的脚本,初始化我们存放的init.sql文件
|
||||
- ./sql:/docker-entrypoint-initdb.d/
|
||||
healthcheck:
|
||||
test: [ "CMD", "mysqladmin", "ping", "-h", "localhost", "-uyoutu", "-pyoutu!0113" ]
|
||||
interval: 6s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
#network_mode: host
|
||||
redis:
|
||||
image: redis
|
||||
restart: always
|
||||
hostname: redis
|
||||
container_name: redis
|
||||
privileged: true
|
||||
ports:
|
||||
- "6379:6379"
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
@ -18,7 +18,7 @@ COPY . .
|
||||
RUN go build -ldflags="-s -w" -o /app/game_open_api ./game_open_api/game_open_api.go
|
||||
|
||||
|
||||
FROM scratch
|
||||
FROM alpine
|
||||
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai
|
||||
|
@ -19,4 +19,5 @@ Log:
|
||||
|
||||
DWCache:
|
||||
Host: redis:6379
|
||||
Password:
|
||||
IdleTimeout: 60
|
@ -19,5 +19,6 @@ Log:
|
||||
|
||||
DWCache:
|
||||
Host: 127.0.0.1:6379
|
||||
Password:
|
||||
IdleTimeout: 60
|
||||
EcpmLogPath: ./logs/ecpm.log
|
@ -3,8 +3,8 @@ syntax = "v1"
|
||||
import "common.api"
|
||||
|
||||
type SetUserGameScoreRequest {
|
||||
Score uint64 `json:"score"`
|
||||
Type uint64 `json:"type,default=0" form:"type,default=0"`
|
||||
Score uint32 `json:"score"`
|
||||
Type uint32 `json:"type,default=0"`
|
||||
}
|
||||
|
||||
type RankingData {
|
||||
@ -22,7 +22,7 @@ type RankingResponse {
|
||||
}
|
||||
|
||||
type RankingListRequest {
|
||||
Type uint64 `json:"type,default=0" form:"type,default=0"`
|
||||
Type uint32 `form:"type,default=0"`
|
||||
PageBase
|
||||
}
|
||||
|
||||
|
@ -20,6 +20,7 @@ type Config struct {
|
||||
|
||||
DWCache struct {
|
||||
Host string // 缓存服务器地址
|
||||
Password string // 缓存服务器密码
|
||||
IdleTimeout int
|
||||
} // 抖音微信缓存配置
|
||||
|
||||
|
@ -2,7 +2,8 @@ package app_user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
||||
@ -30,10 +31,18 @@ func (l *AppUserSetUserLogic) AppUserSetUser(req *types.SetAppUserRequest) (resp
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = l.svcCtx.AppUser.UpdateNicknameAvatar(l.ctx, &model.AppUser{
|
||||
Id: at.UserId,
|
||||
info, err := l.svcCtx.Query.AppUser.WithContext(l.ctx).Where(l.svcCtx.Query.AppUser.ID.Eq(at.UserId)).Updates(field.Attrs(&model.AppUser{
|
||||
ID: at.UserId,
|
||||
Nickname: req.Nickname,
|
||||
Avatar: req.Avatar,
|
||||
})
|
||||
return
|
||||
}))
|
||||
switch {
|
||||
case err != nil:
|
||||
return
|
||||
case info.Error != nil:
|
||||
err = info.Error
|
||||
return
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
@ -2,12 +2,10 @@ package douyin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"time"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
@ -55,36 +53,31 @@ func (l *DouyinCode2tokenLogic) DouyinCode2token(req *types.DouyinCode2TokenRequ
|
||||
return
|
||||
}
|
||||
|
||||
accountId, err := l.svcCtx.AppAccount.FindIdByAppId(l.ctx, req.AppId)
|
||||
account, err := l.svcCtx.Query.AppAccount.WithContext(l.ctx).Where(l.svcCtx.Query.AppAccount.AppID.Eq(req.AppId)).Take()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
aui := &model.AppUser{
|
||||
AppAccountId: accountId,
|
||||
Openid: res.Openid,
|
||||
Unionid: res.Unionid,
|
||||
AnonymousOpenid: res.AnonymousOpenid,
|
||||
AppAccountID: account.ID,
|
||||
Openid: res.Openid,
|
||||
Unionid: res.Unionid,
|
||||
}
|
||||
err = l.svcCtx.AppUser.FindOrCreate(l.ctx, aui)
|
||||
|
||||
aui, err = l.svcCtx.Query.AppUser.WithContext(l.ctx).Where(field.Attrs(&aui)).Assign(field.Attrs(model.AppUser{
|
||||
Nickname: svc.GetRandomUsername(),
|
||||
Avatar: "https://youtukeji.com.cn/candy/images/lollipop.png",
|
||||
})).FirstOrCreate()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
claims := make(jwt.MapClaims)
|
||||
claims["exp"] = time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire
|
||||
claims["iat"] = l.svcCtx.Config.Auth.AccessExpire
|
||||
|
||||
claims["payload"] = &svc.AccessToken{
|
||||
AppId: accountId,
|
||||
UserId: aui.Id,
|
||||
resp.Token, err = l.svcCtx.GenerateAccessToken(&svc.AccessToken{
|
||||
AppId: account.ID,
|
||||
UserId: aui.ID,
|
||||
AppIdStr: req.AppId,
|
||||
OpenId: res.Openid,
|
||||
}
|
||||
l.Logger.Debugf("payload: %+v", claims["payload"])
|
||||
})
|
||||
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
token.Claims = claims
|
||||
resp.Token, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
|
||||
return
|
||||
}
|
||||
|
@ -2,8 +2,10 @@ package game
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/logic/rankings"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
||||
"strconv"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
@ -32,37 +34,51 @@ func (l *RankingListLogic) RankingList(req *types.RankingListRequest) (resp *typ
|
||||
l.Logger.Debugf("at: %+v", at)
|
||||
l.Logger.Debugf("req: %+v", req)
|
||||
|
||||
resp.RankingData, err = l.svcCtx.GameScore.GetRankList(l.ctx, at.AppId, req.Type, req.PageBase)
|
||||
cacheData, err := l.svcCtx.RedisRanking.GetList(l.ctx, rankings.GetRankingsCacheKey(at.AppId, req.Type), 0, 99)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
flag bool
|
||||
userRank types.RankingData
|
||||
)
|
||||
for i := range resp.RankingData {
|
||||
if resp.RankingData[i].UserId == at.UserId {
|
||||
resp.RankingData[i].Self = true
|
||||
userRank = resp.RankingData[i]
|
||||
l.Logger.Debugf("userRank: %+v", userRank)
|
||||
resp.RankingData = append(resp.RankingData, userRank)
|
||||
flag = true
|
||||
break
|
||||
var flag bool
|
||||
|
||||
resp.RankingData = make([]types.RankingData, 0, len(cacheData))
|
||||
var userRank types.RankingData
|
||||
|
||||
for i, datum := range cacheData {
|
||||
userId, err := strconv.Atoi(datum.Member.(string))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
//查询用户数据,FindOne带缓存
|
||||
user, err := l.svcCtx.Query.AppUser.Where(l.svcCtx.Query.AppUser.ID.Eq(uint64(userId))).Take()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data := types.RankingData{
|
||||
Nickname: user.Nickname,
|
||||
Avatar: user.Avatar,
|
||||
Score: uint32(uint64(datum.Score) >> 32),
|
||||
Rank: uint32(i) + 1,
|
||||
Self: user.ID == at.UserId,
|
||||
}
|
||||
if user.ID == at.UserId {
|
||||
flag = true
|
||||
userRank = data
|
||||
}
|
||||
resp.RankingData = append(resp.RankingData, data)
|
||||
}
|
||||
|
||||
if !flag {
|
||||
userRank, err := l.svcCtx.GameScore.GetUserRank(l.ctx, at.AppId, at.UserId, req.Type)
|
||||
tmp, err := l.svcCtx.Query.GameScore.GetUserRank(at.AppId, at.UserId, req.Type)
|
||||
if err != nil {
|
||||
|
||||
return nil, err
|
||||
}
|
||||
l.Logger.Debugf("userRank: %+v", userRank)
|
||||
userRank = types.RankingData(tmp)
|
||||
userRank.Self = true
|
||||
resp.RankingData = append(resp.RankingData, userRank)
|
||||
}
|
||||
l.Logger.Debugf("resp: %+v", resp)
|
||||
resp.RankingData = append(resp.RankingData, userRank)
|
||||
|
||||
l.Logger.Debugf("userRank: %+v", userRank)
|
||||
l.Logger.Debugf("resp: %+v", resp)
|
||||
return
|
||||
}
|
||||
|
@ -3,11 +3,11 @@ package game
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/logic/rankings"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
@ -33,28 +33,43 @@ func (l *RankingSetScoreLogic) RankingSetScore(req *types.SetUserGameScoreReques
|
||||
return
|
||||
}
|
||||
|
||||
oldScore, err := l.svcCtx.GameScore.FindUserScore(l.ctx, at.AppId, at.UserId, req.Type)
|
||||
if err != nil && !errors.Is(err, sqlc.ErrNotFound) {
|
||||
gs := l.svcCtx.Query.GameScore
|
||||
|
||||
// 查询旧分数
|
||||
oldScore, err := gs.
|
||||
WithContext(l.ctx).
|
||||
Where(
|
||||
gs.AppUserID.Eq(at.UserId),
|
||||
gs.AppAccount.Eq(at.AppId),
|
||||
gs.T.Eq(req.Type),
|
||||
).
|
||||
Take()
|
||||
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return
|
||||
}
|
||||
|
||||
if oldScore != nil && req.Score <= oldScore.Score {
|
||||
// 判断是否需要更新(只保留最高分)
|
||||
if req.Score <= oldScore.Score {
|
||||
return
|
||||
}
|
||||
|
||||
if oldScore != nil {
|
||||
oldScore.Score = req.Score
|
||||
err = l.svcCtx.GameScore.UpdateScore(l.ctx, oldScore)
|
||||
} else {
|
||||
oldScore = &model.GameScore{
|
||||
AppUserId: at.UserId,
|
||||
AppAccount: at.AppId,
|
||||
Score: req.Score,
|
||||
}
|
||||
err = l.svcCtx.GameScore.CreateScore(l.ctx, oldScore)
|
||||
oldScore.Score = req.Score
|
||||
oldScore.T = req.Type
|
||||
oldScore.AppUserID = at.UserId
|
||||
oldScore.AppAccount = at.AppId
|
||||
|
||||
// 更新数据库
|
||||
err = gs.WithContext(l.ctx).Where(gs.ID.Eq(oldScore.ID)).Save(oldScore)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// 更新排行榜
|
||||
l.svcCtx.RedisRanking.SetList(l.ctx, rankings.GetRankingsCacheKey(at.AppId, req.Type), redis.Z{
|
||||
Member: at.UserId,
|
||||
Score: float64(uint64(req.Score)<<32 + uint64(oldScore.UpdatedAt.Unix())),
|
||||
})
|
||||
|
||||
l.Logger.Debugf("GameScore: %+v", oldScore)
|
||||
|
||||
return
|
||||
}
|
||||
|
45
game_open_api/internal/logic/rankings/ranking.go
Normal file
45
game_open_api/internal/logic/rankings/ranking.go
Normal file
@ -0,0 +1,45 @@
|
||||
package rankings
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Ranking 排行榜结构体
|
||||
type Ranking struct {
|
||||
c *redis.Client
|
||||
}
|
||||
|
||||
const EcpmRankingsListPrefix = "ecpm:rankings:"
|
||||
|
||||
// NewRanking 创建一个新的排行榜实例
|
||||
func NewRanking(c *redis.Client) *Ranking {
|
||||
return &Ranking{
|
||||
c: c,
|
||||
}
|
||||
}
|
||||
|
||||
func GetRankingsCacheKey(appId uint32, t uint32) string {
|
||||
return fmt.Sprintf("%sappId:%d:type:%d", EcpmRankingsListPrefix, appId, t)
|
||||
}
|
||||
|
||||
// SetList 向排行榜中添加成员及其分数
|
||||
func (r *Ranking) SetList(ctx context.Context, key string, data ...redis.Z) {
|
||||
r.c.ZAdd(ctx, key, data...)
|
||||
}
|
||||
|
||||
// GetList 获取排行榜,按照分数从高到低排序
|
||||
func (r *Ranking) GetList(ctx context.Context, key string, start, stop int64) (data []redis.Z, err error) {
|
||||
return r.c.ZRevRangeWithScores(ctx, key, start, stop).Result()
|
||||
}
|
||||
|
||||
// GetRank 获取指定成员在排行榜中的排名(排名从 0 开始,分数越高排名越靠前)
|
||||
func (r *Ranking) GetRank(ctx context.Context, key, member string) (rank int64, err error) {
|
||||
return r.c.ZRevRank(ctx, key, member).Result()
|
||||
}
|
||||
|
||||
// GetScore 获取指定成员在排行榜中的分数
|
||||
func (r *Ranking) GetScore(ctx context.Context, key, member string) (score float64, err error) {
|
||||
return r.c.ZScore(ctx, key, member).Result()
|
||||
}
|
@ -3,12 +3,10 @@ package wechat
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"time"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
@ -44,35 +42,31 @@ func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2TokenRe
|
||||
return
|
||||
}
|
||||
|
||||
accountId, err := l.svcCtx.AppAccount.FindIdByAppId(l.ctx, req.AppId)
|
||||
account, err := l.svcCtx.Query.AppAccount.WithContext(l.ctx).Where(l.svcCtx.Query.AppAccount.AppID.Eq(req.AppId)).Take()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
aui := &model.AppUser{
|
||||
AppAccountId: accountId,
|
||||
AppAccountID: account.ID,
|
||||
Openid: res.OpenID,
|
||||
Unionid: res.UnionID,
|
||||
}
|
||||
|
||||
err = l.svcCtx.AppUser.FindOrCreate(l.ctx, aui)
|
||||
aui, err = l.svcCtx.Query.AppUser.WithContext(l.ctx).Where(field.Attrs(&aui)).Assign(field.Attrs(model.AppUser{
|
||||
Nickname: svc.GetRandomUsername(),
|
||||
Avatar: "https://youtukeji.com.cn/candy/images/lollipop.png",
|
||||
})).FirstOrCreate()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
claims := make(jwt.MapClaims)
|
||||
claims["exp"] = time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire
|
||||
claims["iat"] = l.svcCtx.Config.Auth.AccessExpire
|
||||
|
||||
claims["payload"] = &svc.AccessToken{
|
||||
AppId: accountId,
|
||||
UserId: aui.Id,
|
||||
resp.Token, err = l.svcCtx.GenerateAccessToken(&svc.AccessToken{
|
||||
AppId: account.ID,
|
||||
UserId: aui.ID,
|
||||
AppIdStr: req.AppId,
|
||||
OpenId: res.OpenID,
|
||||
}
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
token.Claims = claims
|
||||
resp.Token, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
@ -5,51 +5,126 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/config"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/logic/rankings"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/query"
|
||||
redisCacher "gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/redis"
|
||||
helper "gitea.youtukeji.com.cn/youtu/openapi-helper"
|
||||
"github.com/go-gorm/caches/v4"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/redis/go-redis/v9"
|
||||
redisCache "github.com/silenceper/wechat/v2/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ServiceContext struct {
|
||||
Config config.Config
|
||||
AppUser model.AppUserModel
|
||||
GameScore model.GameScoreModel
|
||||
AppAccount model.AppAccountModel
|
||||
DouyinCli *helper.DouYinOpenApiClient
|
||||
WechatCli *helper.WechatApi
|
||||
ZapLogger *zap.Logger
|
||||
Config config.Config
|
||||
DouyinCli *helper.DouYinOpenApiClient
|
||||
WechatCli *helper.WechatApi
|
||||
ZapLogger *zap.Logger
|
||||
RedisRanking *rankings.Ranking
|
||||
Query *query.Query
|
||||
}
|
||||
|
||||
func NewServiceContext(c config.Config) *ServiceContext {
|
||||
//初始化redis client
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: c.DWCache.Host,
|
||||
Password: c.DWCache.Password, // 没有密码,默认值
|
||||
})
|
||||
|
||||
//初始化数据库
|
||||
db, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = db.Use(&caches.Caches{Conf: &caches.Config{
|
||||
Easer: true,
|
||||
Cacher: redisCacher.New(redisClient),
|
||||
}})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
svc := &ServiceContext{
|
||||
Config: c,
|
||||
AppUser: model.NewAppUserModel(sqlx.NewMysql(c.DB.DataSource), c.Cache),
|
||||
GameScore: model.NewGameScoreModel(sqlx.NewMysql(c.DB.DataSource), c.Cache),
|
||||
AppAccount: model.NewAppAccountModel(sqlx.NewMysql(c.DB.DataSource), c.Cache),
|
||||
Config: c,
|
||||
Query: query.Use(db),
|
||||
}
|
||||
|
||||
//初始化排行榜对象
|
||||
svc.InitRankings(redisClient)
|
||||
|
||||
//初始化小程序配置
|
||||
svc.InitDWClient(c)
|
||||
|
||||
//初始化一个zap日志对象用于写入ecpm日志
|
||||
svc.InitEcpmLog(c)
|
||||
return svc
|
||||
}
|
||||
|
||||
func (svc *ServiceContext) InitRankings(redisClient *redis.Client) {
|
||||
//初始化排行榜对象
|
||||
svc.RedisRanking = rankings.NewRanking(redisClient)
|
||||
|
||||
//获取所有不同的排行榜
|
||||
gs := svc.Query.GameScore
|
||||
r, err := gs.FindDistinctRanking()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
//获取所有排行榜
|
||||
for _, ranking := range r {
|
||||
scores, err := gs.Where(gs.AppAccount.Eq(ranking.AppAccount), gs.T.Eq(ranking.T)).Find()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
data := make([]redis.Z, 0, len(scores))
|
||||
|
||||
for _, score := range scores {
|
||||
data = append(data, redis.Z{
|
||||
Score: float64(uint64(score.Score)<<32 + uint64(score.UpdatedAt.Unix())),
|
||||
Member: score.AppUserID,
|
||||
})
|
||||
}
|
||||
svc.RedisRanking.SetList(context.Background(), rankings.GetRankingsCacheKey(ranking.AppAccount, ranking.T), data...)
|
||||
}
|
||||
}
|
||||
|
||||
func (svc *ServiceContext) InitDWClient(c config.Config) {
|
||||
dwCache := redisCache.NewRedis(context.Background(), &redisCache.RedisOpts{Host: c.DWCache.Host, IdleTimeout: c.DWCache.IdleTimeout})
|
||||
|
||||
svc.DouyinCli = helper.NewDouYinOpenApiClient()
|
||||
svc.WechatCli = helper.NewWechatOpenApiClient()
|
||||
result, err := svc.AppAccount.FindAll(context.Background())
|
||||
|
||||
//select `app_id`,`secret`,`ecpm_value`,`ecpm_view`,`type` from `app_account` left join douyin_ecpm_config on app_account.id = douyin_ecpm_config.app_account_id
|
||||
var result []struct {
|
||||
ID int32 `gorm:"column:id;type:int unsigned;primaryKey;autoIncrement:true" json:"id"`
|
||||
Type int32 `gorm:"column:type;type:tinyint unsigned;not null;comment:类型(0:抖音,1:微信)" json:"type"` // 类型(0:抖音,1:微信)
|
||||
AppID string `gorm:"column:app_id;type:char(20);not null;uniqueIndex:app_id,priority:1" json:"app_id"`
|
||||
Secret string `gorm:"column:secret;type:char(40);not null" json:"secret"`
|
||||
EcpmValue uint32 `gorm:"column:ecpm_value;type:int unsigned;not null;comment:值" json:"ecpm_value"` // 值
|
||||
EcpmView uint32 `gorm:"column:ecpm_view;type:int unsigned;not null;comment:浏览次数" json:"ecpm_view"` // 浏览次数
|
||||
}
|
||||
//查询小程序配置(抖音&微信)
|
||||
err := svc.Query.AppAccount.LeftJoin(svc.Query.DouyinEcpmConfig, svc.Query.AppAccount.ID.EqCol(svc.Query.DouyinEcpmConfig.AppAccountID)).Scan(&result)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
for _, v := range *result {
|
||||
//小程序配置
|
||||
for _, v := range result {
|
||||
if v.Type == 0 {
|
||||
svc.DouyinCli.NewAndStoreDouYinOpenApi(v.AppID, v.Secret, v.EcpmValue.V, v.EcpmView.V, dwCache)
|
||||
svc.DouyinCli.NewAndStoreDouYinOpenApi(v.AppID, v.Secret, v.EcpmValue, v.EcpmView, dwCache)
|
||||
} else {
|
||||
svc.WechatCli.NewAndStoreWechatOpenApi(v.AppID, v.Secret, dwCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//初始化一个zap日志对象用于写入ecpm日志
|
||||
func (svc *ServiceContext) InitEcpmLog(c config.Config) {
|
||||
svc.ZapLogger = zap.New(zapcore.NewCore(
|
||||
zapcore.NewJSONEncoder(zapcore.EncoderConfig{
|
||||
TimeKey: "ts",
|
||||
@ -74,12 +149,10 @@ func NewServiceContext(c config.Config) *ServiceContext {
|
||||
})),
|
||||
zapcore.InfoLevel,
|
||||
))
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
type AccessToken struct {
|
||||
AppId uint64 `json:"appId"`
|
||||
AppId uint32 `json:"appId"`
|
||||
UserId uint64 `json:"userId"`
|
||||
AppIdStr string `json:"appIdStr"`
|
||||
OpenId string `json:"openId"`
|
||||
@ -92,7 +165,7 @@ func UnmarshalAccessToken(d any) (ac AccessToken, err error) {
|
||||
return
|
||||
}
|
||||
appId, _ := m["appId"].(json.Number).Int64()
|
||||
ac.AppId = uint64(appId)
|
||||
ac.AppId = uint32(appId)
|
||||
userId, _ := m["userId"].(json.Number).Int64()
|
||||
ac.UserId = uint64(userId)
|
||||
ac.AppIdStr = m["appIdStr"].(string)
|
||||
@ -103,3 +176,40 @@ func UnmarshalAccessToken(d any) (ac AccessToken, err error) {
|
||||
func GetCtxToken(ctx context.Context) (ac AccessToken, err error) {
|
||||
return UnmarshalAccessToken(ctx.Value("payload"))
|
||||
}
|
||||
|
||||
// GenerateAccessToken 生成 JWT 认证的 token
|
||||
// 会从ServiceContext中获取配置信息
|
||||
func (svc *ServiceContext) GenerateAccessToken(at *AccessToken) (token string, err error) {
|
||||
claims := make(jwt.MapClaims)
|
||||
claims["exp"] = time.Now().Unix() + svc.Config.Auth.AccessExpire
|
||||
claims["iat"] = svc.Config.Auth.AccessExpire
|
||||
claims["payload"] = at
|
||||
|
||||
t := jwt.New(jwt.SigningMethodHS256)
|
||||
t.Claims = claims
|
||||
token, err = t.SignedString([]byte(svc.Config.Auth.AccessSecret))
|
||||
return
|
||||
}
|
||||
|
||||
var DefaultUsername = []string{
|
||||
"甜蜜糖果",
|
||||
"糖果爱好者",
|
||||
"软糖粉丝",
|
||||
"巧克力糖果控",
|
||||
"棒棒糖迷",
|
||||
"小熊软糖达人",
|
||||
"硬糖狂人",
|
||||
"焦糖糖果控",
|
||||
"水果糖行家",
|
||||
"棉花糖达人",
|
||||
}
|
||||
|
||||
// GetRandomUsername 随机获取一个糖果相关的用户名
|
||||
func GetRandomUsername() string {
|
||||
// 初始化随机数种子
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
// 生成一个 0 到列表长度减 1 之间的随机索引
|
||||
randomIndex := r.Intn(len(DefaultUsername))
|
||||
// 根据随机索引返回对应的用户名
|
||||
return DefaultUsername[randomIndex]
|
||||
}
|
||||
|
@ -34,7 +34,7 @@ type RankingData struct {
|
||||
}
|
||||
|
||||
type RankingListRequest struct {
|
||||
Type uint64 `json:"type,default=0" form:"type,default=0"`
|
||||
Type uint32 `form:"type,default=0"`
|
||||
PageBase
|
||||
}
|
||||
|
||||
@ -49,8 +49,8 @@ type SetAppUserRequest struct {
|
||||
}
|
||||
|
||||
type SetUserGameScoreRequest struct {
|
||||
Score uint64 `json:"score"`
|
||||
Type uint64 `json:"type,default=0" form:"type,default=0"`
|
||||
Score uint32 `json:"score"`
|
||||
Type uint32 `json:"type,default=0"`
|
||||
}
|
||||
|
||||
type UserId struct {
|
||||
|
@ -1,65 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
var _ AppAccountModel = (*customAppAccountModel)(nil)
|
||||
|
||||
type (
|
||||
// AppAccountModel is an interface to be customized, add more methods here,
|
||||
// and implement the added methods in customAppAccountModel.
|
||||
AppAccountModel interface {
|
||||
appAccountModel
|
||||
}
|
||||
|
||||
customAppAccountModel struct {
|
||||
*defaultAppAccountModel
|
||||
}
|
||||
|
||||
appAccountModel interface {
|
||||
Insert(ctx context.Context, data *AppAccount) (sql.Result, error)
|
||||
FindOne(ctx context.Context, id uint64) (*AppAccount, error)
|
||||
Update(ctx context.Context, data *AppAccount) error
|
||||
Delete(ctx context.Context, id uint64) error
|
||||
FindIdByAppId(ctx context.Context, appId string) (uint64, error)
|
||||
FindAll(ctx context.Context) (*[]*GameAppConfig, error)
|
||||
}
|
||||
)
|
||||
|
||||
// NewAppAccountModel returns a model for the database table.
|
||||
func NewAppAccountModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AppAccountModel {
|
||||
return &customAppAccountModel{
|
||||
defaultAppAccountModel: newAppAccountModel(conn, c, opts...),
|
||||
}
|
||||
}
|
||||
|
||||
type GameAppConfig struct {
|
||||
AppID string `db:"app_id"`
|
||||
Secret string `db:"secret"`
|
||||
EcpmValue sql.Null[uint32] `db:"ecpm_value"` // 值
|
||||
EcpmView sql.Null[uint32] `db:"ecpm_view"` // 浏览次数
|
||||
Type uint64 `db:"type"` // 类型(0:抖音,1:微信)
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) FindAll(ctx context.Context) (*[]*GameAppConfig, error) {
|
||||
ecpmAppAccountIdKey := fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, "all")
|
||||
var resp []*GameAppConfig
|
||||
err := m.QueryRowCtx(ctx, &resp, ecpmAppAccountIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := "select `app_id`,`secret`,`ecpm_value`,`ecpm_view`,`type` from `app_account` left join douyin_ecpm_config on app_account.id = douyin_ecpm_config.app_account_id"
|
||||
return conn.QueryRowsCtx(ctx, v, query)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return &resp, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
@ -1,124 +0,0 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
// versions:
|
||||
// goctl version: 1.7.5
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/stores/builder"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"github.com/zeromicro/go-zero/core/stringx"
|
||||
)
|
||||
|
||||
var (
|
||||
appAccountFieldNames = builder.RawFieldNames(&AppAccount{})
|
||||
appAccountRows = strings.Join(appAccountFieldNames, ",")
|
||||
appAccountRowsExpectAutoSet = strings.Join(stringx.Remove(appAccountFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
|
||||
appAccountRowsWithPlaceHolder = strings.Join(stringx.Remove(appAccountFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
|
||||
|
||||
cacheEcpmAppAccountIdPrefix = "cache:ecpm:appAccount:id:"
|
||||
)
|
||||
|
||||
type (
|
||||
defaultAppAccountModel struct {
|
||||
sqlc.CachedConn
|
||||
table string
|
||||
}
|
||||
|
||||
AppAccount struct {
|
||||
Id uint64 `db:"id"`
|
||||
Type uint64 `db:"type"` // 类型(0:抖音,1:微信)
|
||||
AppId string `db:"app_id"`
|
||||
Secret string `db:"secret"`
|
||||
Remark sql.NullString `db:"remark"` // 备注
|
||||
DeletedAt sql.NullString `db:"deleted_at"`
|
||||
}
|
||||
)
|
||||
|
||||
func newAppAccountModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultAppAccountModel {
|
||||
return &defaultAppAccountModel{
|
||||
CachedConn: sqlc.NewConn(conn, c, opts...),
|
||||
table: "`app_account`",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) Delete(ctx context.Context, id uint64) error {
|
||||
ecpmAppAccountIdKey := fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
|
||||
return conn.ExecCtx(ctx, query, id)
|
||||
}, ecpmAppAccountIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) FindOne(ctx context.Context, id uint64) (*AppAccount, error) {
|
||||
ecpmAppAccountIdKey := fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, id)
|
||||
var resp AppAccount
|
||||
err := m.QueryRowCtx(ctx, &resp, ecpmAppAccountIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appAccountRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, id)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return &resp, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) Insert(ctx context.Context, data *AppAccount) (sql.Result, error) {
|
||||
ecpmAppAccountIdKey := fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, data.Id)
|
||||
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, appAccountRowsExpectAutoSet)
|
||||
return conn.ExecCtx(ctx, query, data.Type, data.AppId, data.Secret, data.Remark, data.DeletedAt)
|
||||
}, ecpmAppAccountIdKey)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) Update(ctx context.Context, data *AppAccount) error {
|
||||
ecpmAppAccountIdKey := fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, data.Id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, appAccountRowsWithPlaceHolder)
|
||||
return conn.ExecCtx(ctx, query, data.Type, data.AppId, data.Secret, data.Remark, data.DeletedAt, data.Id)
|
||||
}, ecpmAppAccountIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) FindIdByAppId(ctx context.Context, appId string) (uint64, error) {
|
||||
ecpmAppAccountIdKey := fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, appId)
|
||||
var id uint64
|
||||
err := m.QueryRowCtx(ctx, &id, ecpmAppAccountIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := fmt.Sprintf("select id from %s where `app_id` = ? limit 1", m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, appId)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return id, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return 0, ErrNotFound
|
||||
default:
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) formatPrimary(primary any) string {
|
||||
return fmt.Sprintf("%s%v", cacheEcpmAppAccountIdPrefix, primary)
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appAccountRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, primary)
|
||||
}
|
||||
|
||||
func (m *defaultAppAccountModel) tableName() string {
|
||||
return m.table
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
var _ AppUserModel = (*customAppUserModel)(nil)
|
||||
|
||||
type (
|
||||
// AppUserModel is an interface to be customized, add more methods here,
|
||||
// and implement the added methods in customAppUserModel.
|
||||
AppUserModel interface {
|
||||
appUserModel
|
||||
FindOrCreate(ctx context.Context, data *AppUser) (err error)
|
||||
}
|
||||
|
||||
customAppUserModel struct {
|
||||
*defaultAppUserModel
|
||||
}
|
||||
)
|
||||
|
||||
const cacheEcpmAppUserPrefix = "cache:ecpm:appUser:"
|
||||
|
||||
// NewAppUserModel returns a model for the database table.
|
||||
func NewAppUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AppUserModel {
|
||||
return &customAppUserModel{
|
||||
defaultAppUserModel: newAppUserModel(conn, c, opts...),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *customAppUserModel) FindOrCreate(ctx context.Context, data *AppUser) (err error) {
|
||||
ecpmAppUserIdKey := fmt.Sprintf("%sappId:%d:openid:%s", cacheEcpmAppUserPrefix, data.AppAccountId, data.Openid)
|
||||
var resp AppUser
|
||||
err = m.QueryRowCtx(ctx, &resp, ecpmAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := "select * from app_user where `openid` = ? and `app_account_id`= ? limit 1"
|
||||
return conn.QueryRowCtx(ctx, v, query, data.Openid, data.AppAccountId)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
*data = resp
|
||||
return nil
|
||||
case sqlc.ErrNotFound:
|
||||
res, err := m.Insert(ctx, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data.Id = uint64(id)
|
||||
return nil
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
@ -1,125 +0,0 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
// versions:
|
||||
// goctl version: 1.7.5
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/stores/builder"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"github.com/zeromicro/go-zero/core/stringx"
|
||||
)
|
||||
|
||||
var (
|
||||
appUserFieldNames = builder.RawFieldNames(&AppUser{})
|
||||
appUserRows = strings.Join(appUserFieldNames, ",")
|
||||
appUserRowsExpectAutoSet = strings.Join(stringx.Remove(appUserFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
|
||||
appUserRowsWithPlaceHolder = strings.Join(stringx.Remove(appUserFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
|
||||
|
||||
cacheEcpmAppUserIdPrefix = "cache:ecpm:appUser:id:"
|
||||
)
|
||||
|
||||
type (
|
||||
appUserModel interface {
|
||||
Insert(ctx context.Context, data *AppUser) (sql.Result, error)
|
||||
FindOne(ctx context.Context, id uint64) (*AppUser, error)
|
||||
Update(ctx context.Context, data *AppUser) error
|
||||
Delete(ctx context.Context, id uint64) error
|
||||
UpdateNicknameAvatar(ctx context.Context, data *AppUser) error
|
||||
}
|
||||
|
||||
defaultAppUserModel struct {
|
||||
sqlc.CachedConn
|
||||
table string
|
||||
}
|
||||
|
||||
AppUser struct {
|
||||
Id uint64 `db:"id"`
|
||||
AppAccountId uint64 `db:"app_account_id"` // app_account表外键
|
||||
Openid string `db:"openid"`
|
||||
Unionid string `db:"unionid"`
|
||||
Nickname string `db:"nickname"` // 昵称
|
||||
Avatar string `db:"avatar"` // 头像
|
||||
AnonymousOpenid string `db:"anonymous_openid"` // 匿名openid
|
||||
}
|
||||
)
|
||||
|
||||
func newAppUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultAppUserModel {
|
||||
return &defaultAppUserModel{
|
||||
CachedConn: sqlc.NewConn(conn, c, opts...),
|
||||
table: "`app_user`",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) Delete(ctx context.Context, id uint64) error {
|
||||
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
|
||||
return conn.ExecCtx(ctx, query, id)
|
||||
}, ecpmAppUserIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) FindOne(ctx context.Context, id uint64) (*AppUser, error) {
|
||||
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, id)
|
||||
var resp AppUser
|
||||
err := m.QueryRowCtx(ctx, &resp, ecpmAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appUserRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, id)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return &resp, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) Insert(ctx context.Context, data *AppUser) (sql.Result, error) {
|
||||
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, data.Id)
|
||||
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, appUserRowsExpectAutoSet)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccountId, data.Openid, data.Unionid, data.Nickname, data.Avatar, data.AnonymousOpenid)
|
||||
}, ecpmAppUserIdKey)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) Update(ctx context.Context, data *AppUser) error {
|
||||
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, data.Id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, appUserRowsWithPlaceHolder)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccountId, data.Openid, data.Unionid, data.Nickname, data.Avatar, data.AnonymousOpenid, data.Id)
|
||||
}, ecpmAppUserIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) UpdateNicknameAvatar(ctx context.Context, data *AppUser) error {
|
||||
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, data.Id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, "`nickname`=?,`avatar`=?")
|
||||
return conn.ExecCtx(ctx, query, data.Nickname, data.Avatar, data.Id)
|
||||
}, ecpmAppUserIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) formatPrimary(primary any) string {
|
||||
return fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, primary)
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appUserRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, primary)
|
||||
}
|
||||
|
||||
func (m *defaultAppUserModel) tableName() string {
|
||||
return m.table
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
var _ DouyinEcpmConfigModel = (*customDouyinEcpmConfigModel)(nil)
|
||||
|
||||
type (
|
||||
// DouyinEcpmConfigModel is an interface to be customized, add more methods here,
|
||||
// and implement the added methods in customDouyinEcpmConfigModel.
|
||||
DouyinEcpmConfigModel interface {
|
||||
douyinEcpmConfigModel
|
||||
}
|
||||
|
||||
customDouyinEcpmConfigModel struct {
|
||||
*defaultDouyinEcpmConfigModel
|
||||
}
|
||||
)
|
||||
|
||||
// NewDouyinEcpmConfigModel returns a model for the database table.
|
||||
func NewDouyinEcpmConfigModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) DouyinEcpmConfigModel {
|
||||
return &customDouyinEcpmConfigModel{
|
||||
defaultDouyinEcpmConfigModel: newDouyinEcpmConfigModel(conn, c, opts...),
|
||||
}
|
||||
}
|
@ -1,112 +0,0 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
// versions:
|
||||
// goctl version: 1.7.5
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/stores/builder"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"github.com/zeromicro/go-zero/core/stringx"
|
||||
)
|
||||
|
||||
var (
|
||||
douyinEcpmConfigFieldNames = builder.RawFieldNames(&DouyinEcpmConfig{})
|
||||
douyinEcpmConfigRows = strings.Join(douyinEcpmConfigFieldNames, ",")
|
||||
douyinEcpmConfigRowsExpectAutoSet = strings.Join(stringx.Remove(douyinEcpmConfigFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
|
||||
douyinEcpmConfigRowsWithPlaceHolder = strings.Join(stringx.Remove(douyinEcpmConfigFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
|
||||
|
||||
cacheEcpmDouyinEcpmConfigIdPrefix = "cache:ecpm:douyinEcpmConfig:id:"
|
||||
)
|
||||
|
||||
type (
|
||||
douyinEcpmConfigModel interface {
|
||||
Insert(ctx context.Context, data *DouyinEcpmConfig) (sql.Result, error)
|
||||
FindOne(ctx context.Context, id uint64) (*DouyinEcpmConfig, error)
|
||||
Update(ctx context.Context, data *DouyinEcpmConfig) error
|
||||
Delete(ctx context.Context, id uint64) error
|
||||
}
|
||||
|
||||
defaultDouyinEcpmConfigModel struct {
|
||||
sqlc.CachedConn
|
||||
table string
|
||||
}
|
||||
|
||||
DouyinEcpmConfig struct {
|
||||
Id uint64 `db:"id"`
|
||||
AppAccountId uint64 `db:"app_account_id"`
|
||||
EcpmValue uint64 `db:"ecpm_value"` // 值
|
||||
EcpmView uint64 `db:"ecpm_view"` // 浏览次数
|
||||
}
|
||||
)
|
||||
|
||||
func newDouyinEcpmConfigModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultDouyinEcpmConfigModel {
|
||||
return &defaultDouyinEcpmConfigModel{
|
||||
CachedConn: sqlc.NewConn(conn, c, opts...),
|
||||
table: "`douyin_ecpm_config`",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) Delete(ctx context.Context, id uint64) error {
|
||||
ecpmDouyinEcpmConfigIdKey := fmt.Sprintf("%s%v", cacheEcpmDouyinEcpmConfigIdPrefix, id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
|
||||
return conn.ExecCtx(ctx, query, id)
|
||||
}, ecpmDouyinEcpmConfigIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) FindOne(ctx context.Context, id uint64) (*DouyinEcpmConfig, error) {
|
||||
ecpmDouyinEcpmConfigIdKey := fmt.Sprintf("%s%v", cacheEcpmDouyinEcpmConfigIdPrefix, id)
|
||||
var resp DouyinEcpmConfig
|
||||
err := m.QueryRowCtx(ctx, &resp, ecpmDouyinEcpmConfigIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", douyinEcpmConfigRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, id)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return &resp, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) Insert(ctx context.Context, data *DouyinEcpmConfig) (sql.Result, error) {
|
||||
ecpmDouyinEcpmConfigIdKey := fmt.Sprintf("%s%v", cacheEcpmDouyinEcpmConfigIdPrefix, data.Id)
|
||||
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?)", m.table, douyinEcpmConfigRowsExpectAutoSet)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccountId, data.EcpmValue, data.EcpmView)
|
||||
}, ecpmDouyinEcpmConfigIdKey)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) Update(ctx context.Context, data *DouyinEcpmConfig) error {
|
||||
ecpmDouyinEcpmConfigIdKey := fmt.Sprintf("%s%v", cacheEcpmDouyinEcpmConfigIdPrefix, data.Id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, douyinEcpmConfigRowsWithPlaceHolder)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccountId, data.EcpmValue, data.EcpmView, data.Id)
|
||||
}, ecpmDouyinEcpmConfigIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) formatPrimary(primary any) string {
|
||||
return fmt.Sprintf("%s%v", cacheEcpmDouyinEcpmConfigIdPrefix, primary)
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", douyinEcpmConfigRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, primary)
|
||||
}
|
||||
|
||||
func (m *defaultDouyinEcpmConfigModel) tableName() string {
|
||||
return m.table
|
||||
}
|
@ -1,195 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
var _ GameScoreModel = (*customGameScoreModel)(nil)
|
||||
|
||||
const (
|
||||
cacheEcpmGameScorePrefix = "cache:ecpm:gameScore:"
|
||||
)
|
||||
|
||||
type (
|
||||
// GameScoreModel is an interface to be customized, add more methods here,
|
||||
// and implement the added methods in customGameScoreModel.
|
||||
GameScoreModel interface {
|
||||
gameScoreModel
|
||||
|
||||
GetRankList(ctx context.Context, appId uint64, t uint64, page types.PageBase) ([]types.RankingData, error)
|
||||
GetUserRank(ctx context.Context, appId uint64, userId uint64, t uint64) (types.RankingData, error)
|
||||
FindUserScore(ctx context.Context, appId, userId, t uint64) (*GameScore, error)
|
||||
|
||||
UpdateScore(ctx context.Context, data *GameScore) error
|
||||
CreateScore(ctx context.Context, data *GameScore) error
|
||||
}
|
||||
|
||||
customGameScoreModel struct {
|
||||
*defaultGameScoreModel
|
||||
rankListKey []string
|
||||
mutex sync.Mutex
|
||||
}
|
||||
)
|
||||
|
||||
// NewGameScoreModel returns a model for the database table.
|
||||
func NewGameScoreModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) GameScoreModel {
|
||||
return &customGameScoreModel{
|
||||
defaultGameScoreModel: newGameScoreModel(conn, c, opts...),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *customGameScoreModel) pageCacheKey(page types.PageBase) string {
|
||||
return fmt.Sprintf(":page:%d:pageSize:%d", page.Page, page.PageSize)
|
||||
}
|
||||
|
||||
// rankListCacheKey 排行榜缓存key
|
||||
func (m *customGameScoreModel) rankListCacheKey(appId uint64, t uint64) string {
|
||||
return fmt.Sprintf("%s:rankList:appId:%d:t:%d", cacheEcpmGameScorePrefix, appId, t)
|
||||
}
|
||||
|
||||
// userScoreCacheKey 用户游戏分数缓存key
|
||||
func (m *customGameScoreModel) userScoreCacheKey(userId, appId, t uint64) string {
|
||||
return fmt.Sprintf("%suserId:%d:appId:%v:t:%d", cacheEcpmGameScorePrefix, userId, appId, t)
|
||||
}
|
||||
|
||||
// userRankCacheKey 用户游戏排名缓存key
|
||||
func (m *customGameScoreModel) userRankCacheKey(userId, appId, t uint64) string {
|
||||
return fmt.Sprintf("%srank:userId:%d:appId:%v:t:%d", cacheEcpmGameScorePrefix, userId, appId, t)
|
||||
}
|
||||
|
||||
// GetRankList 获取排行榜列表
|
||||
func (m *customGameScoreModel) GetRankList(ctx context.Context, appId uint64, t uint64, page types.PageBase) (resp []types.RankingData, err error) {
|
||||
cacheKey := m.rankListCacheKey(appId, t)
|
||||
err = m.QueryRowCtx(ctx, &resp, cacheKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := `
|
||||
SELECT
|
||||
game_score.score,
|
||||
app_user.nickname,
|
||||
app_user.avatar,
|
||||
game_score.app_user_id,
|
||||
rank() over (ORDER BY game_score.score DESC) t_rank
|
||||
FROM
|
||||
game_score
|
||||
JOIN app_user ON app_user.id = game_score.app_user_id
|
||||
WHERE
|
||||
game_score.app_account = ?
|
||||
AND game_score.t = ?
|
||||
LIMIT 20`
|
||||
return conn.QueryRowsPartialCtx(ctx, v, query, appId, t)
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
return resp, nil
|
||||
case errors.Is(err, sqlc.ErrNotFound):
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserRank 获取用户排名
|
||||
func (m *customGameScoreModel) GetUserRank(ctx context.Context, appId uint64, userId uint64, t uint64) (resp types.RankingData, err error) {
|
||||
var res []types.RankingData
|
||||
err = m.QueryRowCtx(ctx, &res, m.userRankCacheKey(userId, appId, t), func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := `
|
||||
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对分数进行降序排名
|
||||
rank() OVER (ORDER BY game_score.score DESC) t_rank
|
||||
FROM
|
||||
game_score
|
||||
-- 在子查询中先根据t = 0过滤数据
|
||||
WHERE
|
||||
game_score.t = ?
|
||||
-- 在子查询中根据app_account = 2过滤数据
|
||||
AND game_score.app_account = ?
|
||||
) AS gs
|
||||
-- 使用LEFT JOIN将子查询结果和app_user表进行连接
|
||||
LEFT JOIN app_user ON app_user.id = gs.app_user_id
|
||||
-- 在外部查询中根据app_user_id = 59过滤数据
|
||||
WHERE
|
||||
gs.app_user_id = ?
|
||||
LIMIT 1;
|
||||
`
|
||||
return conn.QueryRowsPartialCtx(ctx, v, query, t, appId, userId)
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
if len(res) == 1 {
|
||||
resp = res[0]
|
||||
}
|
||||
return resp, nil
|
||||
case errors.Is(err, sqlc.ErrNotFound):
|
||||
return resp, ErrNotFound
|
||||
default:
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
|
||||
// FindUserScore 查询用户游戏分数
|
||||
func (m *customGameScoreModel) FindUserScore(ctx context.Context, appId, userId, t uint64) (*GameScore, error) {
|
||||
var (
|
||||
resp GameScore
|
||||
err error
|
||||
)
|
||||
err = m.QueryRowCtx(ctx, &resp, m.userScoreCacheKey(userId, appId, t), func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := fmt.Sprintf("select %s from %s where app_account = ? and `app_user_id` = ? and t = ? limit 1", gameScoreRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, appId, userId, t)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return &resp, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateScore 更新游戏分数记录
|
||||
func (m *customGameScoreModel) UpdateScore(ctx context.Context, data *GameScore) error {
|
||||
cacheKeys := []string{
|
||||
m.rankListCacheKey(data.AppAccount, data.T), // 删除排行榜缓存
|
||||
m.userRankCacheKey(data.AppUserId, data.AppAccount, data.T), // 删除用户排行缓存
|
||||
m.userScoreCacheKey(data.AppUserId, data.AppAccount, data.T), // 删除用户分数缓存
|
||||
}
|
||||
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("update %s set `score` = ? where `id` = ?", m.table)
|
||||
return conn.ExecCtx(ctx, query, data.Score, data.Id)
|
||||
}, cacheKeys...)
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateScore 创建游戏分数记录
|
||||
func (m *customGameScoreModel) CreateScore(ctx context.Context, data *GameScore) error {
|
||||
cacheKeys := []string{
|
||||
m.rankListCacheKey(data.AppAccount, data.T), // 删除排行榜缓存
|
||||
m.userRankCacheKey(data.AppUserId, data.AppAccount, data.T), // 删除用户排行缓存
|
||||
m.userScoreCacheKey(data.AppUserId, data.AppAccount, data.T), // 删除用户分数缓存
|
||||
}
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?)", m.table, gameScoreRowsExpectAutoSet)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccount, data.AppUserId, data.Score, data.T)
|
||||
}, cacheKeys...)
|
||||
return err
|
||||
}
|
@ -1,113 +0,0 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
// versions:
|
||||
// goctl version: 1.7.5
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/stores/builder"
|
||||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"github.com/zeromicro/go-zero/core/stringx"
|
||||
)
|
||||
|
||||
var (
|
||||
gameScoreFieldNames = builder.RawFieldNames(&GameScore{})
|
||||
gameScoreRows = strings.Join(gameScoreFieldNames, ",")
|
||||
gameScoreRowsExpectAutoSet = strings.Join(stringx.Remove(gameScoreFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
|
||||
gameScoreRowsWithPlaceHolder = strings.Join(stringx.Remove(gameScoreFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
|
||||
|
||||
cacheEcpmGameScoreIdPrefix = "cache:ecpm:gameScore:id:"
|
||||
)
|
||||
|
||||
type (
|
||||
gameScoreModel interface {
|
||||
Insert(ctx context.Context, data *GameScore) (sql.Result, error)
|
||||
FindOne(ctx context.Context, id uint64) (*GameScore, error)
|
||||
Update(ctx context.Context, data *GameScore) error
|
||||
Delete(ctx context.Context, id uint64) error
|
||||
}
|
||||
|
||||
defaultGameScoreModel struct {
|
||||
sqlc.CachedConn
|
||||
table string
|
||||
}
|
||||
|
||||
GameScore struct {
|
||||
Id uint64 `db:"id"`
|
||||
AppAccount uint64 `db:"app_account"` // 小游戏id
|
||||
AppUserId uint64 `db:"app_user_id"` // 用户id
|
||||
Score uint64 `db:"score"` // 得分
|
||||
T uint64 `db:"t"` // 得分类型(区分相同小游戏中的不同模式得分)
|
||||
}
|
||||
)
|
||||
|
||||
func newGameScoreModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultGameScoreModel {
|
||||
return &defaultGameScoreModel{
|
||||
CachedConn: sqlc.NewConn(conn, c, opts...),
|
||||
table: "`game_score`",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) Delete(ctx context.Context, id uint64) error {
|
||||
ecpmGameScoreIdKey := fmt.Sprintf("%s%v", cacheEcpmGameScoreIdPrefix, id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
|
||||
return conn.ExecCtx(ctx, query, id)
|
||||
}, ecpmGameScoreIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) FindOne(ctx context.Context, id uint64) (*GameScore, error) {
|
||||
ecpmGameScoreIdKey := fmt.Sprintf("%s%v", cacheEcpmGameScoreIdPrefix, id)
|
||||
var resp GameScore
|
||||
err := m.QueryRowCtx(ctx, &resp, ecpmGameScoreIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", gameScoreRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, id)
|
||||
})
|
||||
switch err {
|
||||
case nil:
|
||||
return &resp, nil
|
||||
case sqlc.ErrNotFound:
|
||||
return nil, ErrNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) Insert(ctx context.Context, data *GameScore) (sql.Result, error) {
|
||||
ecpmGameScoreIdKey := fmt.Sprintf("%s%v", cacheEcpmGameScoreIdPrefix, data.Id)
|
||||
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?)", m.table, gameScoreRowsExpectAutoSet)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccount, data.AppUserId, data.Score, data.T)
|
||||
}, ecpmGameScoreIdKey)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) Update(ctx context.Context, data *GameScore) error {
|
||||
ecpmGameScoreIdKey := fmt.Sprintf("%s%v", cacheEcpmGameScoreIdPrefix, data.Id)
|
||||
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
|
||||
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, gameScoreRowsWithPlaceHolder)
|
||||
return conn.ExecCtx(ctx, query, data.AppAccount, data.AppUserId, data.Score, data.T, data.Id)
|
||||
}, ecpmGameScoreIdKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) formatPrimary(primary any) string {
|
||||
return fmt.Sprintf("%s%v", cacheEcpmGameScoreIdPrefix, primary)
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", gameScoreRows, m.table)
|
||||
return conn.QueryRowCtx(ctx, v, query, primary)
|
||||
}
|
||||
|
||||
func (m *defaultGameScoreModel) tableName() string {
|
||||
return m.table
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
package model
|
||||
|
||||
import "github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
|
||||
var ErrNotFound = sqlx.ErrNotFound
|
16
go.mod
16
go.mod
@ -4,11 +4,18 @@ go 1.23.5
|
||||
|
||||
require (
|
||||
gitea.youtukeji.com.cn/youtu/openapi-helper v0.0.3-2
|
||||
github.com/go-gorm/caches/v4 v4.0.5
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1
|
||||
github.com/redis/go-redis/v9 v9.7.0
|
||||
github.com/silenceper/wechat/v2 v2.1.7
|
||||
github.com/zeromicro/go-zero v1.7.6
|
||||
go.uber.org/zap v1.27.0
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gorm.io/driver/mysql v1.5.7
|
||||
gorm.io/driver/sqlite v1.4.3
|
||||
gorm.io/gen v0.3.26
|
||||
gorm.io/gorm v1.25.12
|
||||
gorm.io/plugin/dbresolver v1.5.3
|
||||
)
|
||||
|
||||
require (
|
||||
@ -27,9 +34,12 @@ require (
|
||||
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.15 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/openzipkin/zipkin-go v0.4.3 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
@ -38,7 +48,6 @@ require (
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.62.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/redis/go-redis/v9 v9.7.0 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
@ -60,12 +69,17 @@ require (
|
||||
go.uber.org/automaxprocs v1.6.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/crypto v0.32.0 // indirect
|
||||
golang.org/x/mod v0.17.0 // indirect
|
||||
golang.org/x/net v0.34.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.29.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250122153221-138b5a5a4fd4 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250122153221-138b5a5a4fd4 // indirect
|
||||
google.golang.org/grpc v1.69.4 // indirect
|
||||
google.golang.org/protobuf v1.36.3 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gorm.io/datatypes v1.1.1-0.20230130040222-c43177d3cf8c // indirect
|
||||
gorm.io/hints v1.1.0 // indirect
|
||||
)
|
||||
|
84
go.sum
84
go.sum
@ -2,8 +2,6 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
gitea.youtukeji.com.cn/youtu/openapi-helper v0.0.3-2 h1:MtJ1uQRb7QqKIsbqEVjWk+T/TGx5CoKEx93RsiMcVsY=
|
||||
gitea.youtukeji.com.cn/youtu/openapi-helper v0.0.3-2/go.mod h1:o3XiYjUmxptrwcYPbTwNc2SQSOeOj7qbQPdNNVU0H5w=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE=
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
|
||||
@ -42,6 +40,8 @@ github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7z
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/go-gorm/caches/v4 v4.0.5 h1:Sdj9vxbEM0sCmv5+s5o6GzoVMuraWF0bjJJvUU+7c1U=
|
||||
github.com/go-gorm/caches/v4 v4.0.5/go.mod h1:Ms8LnWVoW4GkTofpDzFH8OfDGNTjLxQDyxBmRN67Ujw=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
@ -49,11 +49,16 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
|
||||
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
@ -80,6 +85,28 @@ github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslC
|
||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8=
|
||||
github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
|
||||
github.com/jackc/pgconn v1.13.0 h1:3L1XMNV2Zvca/8BYhzcRFS70Lr0WlDg16Di6SFGAbys=
|
||||
github.com/jackc/pgconn v1.13.0/go.mod h1:AnowpAqO4CMIIJNZl2VJp+KrkAZciAkhEl0W0JIobpI=
|
||||
github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE=
|
||||
github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgproto3/v2 v2.3.1 h1:nwj7qwf0S+Q7ISFfBndqeLwSwxs+4DPsbRFjECT1Y4Y=
|
||||
github.com/jackc/pgproto3/v2 v2.3.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgtype v1.12.0 h1:Dlq8Qvcch7kiehm8wPGIW0W3KsCCHJnRacKW0UM8n5w=
|
||||
github.com/jackc/pgtype v1.12.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgx/v4 v4.17.2 h1:0Ut0rpeKwvIVbMQ1KbMBU4h6wxehBI535LK6Flheh8E=
|
||||
github.com/jackc/pgx/v4 v4.17.2/go.mod h1:lcxIZN44yMIrWI78a5CpucdD14hX0SBDbNRvjDBItsw=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@ -92,6 +119,11 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
|
||||
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE=
|
||||
github.com/microsoft/go-mssqldb v0.17.0/go.mod h1:OkoNGhGEs8EZqchVTtochlXruEhEOaO4S0d2sB5aeGQ=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
|
||||
@ -159,6 +191,7 @@ github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhso
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
@ -201,22 +234,34 @@ go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
|
||||
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
|
||||
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@ -232,19 +277,31 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@ -283,5 +340,28 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/datatypes v1.1.1-0.20230130040222-c43177d3cf8c h1:jWdr7cHgl8c/ua5vYbR2WhSp+NQmzhsj0xoY3foTzW8=
|
||||
gorm.io/datatypes v1.1.1-0.20230130040222-c43177d3cf8c/go.mod h1:SH2K9R+2RMjuX1CkCONrPwoe9JzVv2hkQvEu4bXGojE=
|
||||
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
|
||||
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||
gorm.io/driver/postgres v1.4.5 h1:mTeXTTtHAgnS9PgmhN2YeUbazYpLhUI1doLnw42XUZc=
|
||||
gorm.io/driver/postgres v1.4.5/go.mod h1:GKNQYSJ14qvWkvPwXljMGehpKrhlDNsqYRr5HnYGncg=
|
||||
gorm.io/driver/sqlite v1.1.6/go.mod h1:W8LmC/6UvVbHKah0+QOC7Ja66EaZXHwUTjgXY8YNWX8=
|
||||
gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
|
||||
gorm.io/driver/sqlite v1.4.3/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
|
||||
gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0=
|
||||
gorm.io/driver/sqlserver v1.4.1/go.mod h1:DJ4P+MeZbc5rvY58PnmN1Lnyvb5gw5NPzGshHDnJLig=
|
||||
gorm.io/gen v0.3.26 h1:sFf1j7vNStimPRRAtH4zz5NiHM+1dr6eA9aaRdplyhY=
|
||||
gorm.io/gen v0.3.26/go.mod h1:a5lq5y3w4g5LMxBcw0wnO6tYUCdNutWODq5LrIt75LE=
|
||||
gorm.io/gorm v1.21.15/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
gorm.io/gorm v1.22.2/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
gorm.io/gorm v1.24.0/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
gorm.io/hints v1.1.0 h1:Lp4z3rxREufSdxn4qmkK3TLDltrM10FLTHiuqwDPvXw=
|
||||
gorm.io/hints v1.1.0/go.mod h1:lKQ0JjySsPBj3uslFzY3JhYDtqEwzm+G1hv8rWujB6Y=
|
||||
gorm.io/plugin/dbresolver v1.5.3 h1:wFwINGZZmttuu9h7XpvbDHd8Lf9bb8GNzp/NpAMV2wU=
|
||||
gorm.io/plugin/dbresolver v1.5.3/go.mod h1:TSrVhaUg2DZAWP3PrHlDlITEJmNOkL0tFTjvTEsQ4XE=
|
||||
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 h1:pUdcCO1Lk/tbT5ztQWOBi5HBgbBP1J8+AsQnQCKsi8A=
|
||||
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
|
||||
|
26
gorm-gen/dao/model/app_account.gen.go
Normal file
26
gorm-gen/dao/model/app_account.gen.go
Normal file
@ -0,0 +1,26 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const TableNameAppAccount = "app_account"
|
||||
|
||||
// AppAccount mapped from table <app_account>
|
||||
type AppAccount struct {
|
||||
ID uint32 `gorm:"column:id;type:int unsigned;primaryKey;autoIncrement:true" json:"id"`
|
||||
Type uint32 `gorm:"column:type;type:tinyint unsigned;not null;comment:类型(0:抖音,1:微信)" json:"type"` // 类型(0:抖音,1:微信)
|
||||
AppID string `gorm:"column:app_id;type:char(20);not null;uniqueIndex:app_id,priority:1" json:"app_id"`
|
||||
Secret string `gorm:"column:secret;type:char(40);not null" json:"secret"`
|
||||
Remark *string `gorm:"column:remark;type:varchar(255);comment:备注" json:"remark"` // 备注
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:time" json:"deleted_at"`
|
||||
}
|
||||
|
||||
// TableName AppAccount's table name
|
||||
func (*AppAccount) TableName() string {
|
||||
return TableNameAppAccount
|
||||
}
|
29
gorm-gen/dao/model/app_user.gen.go
Normal file
29
gorm-gen/dao/model/app_user.gen.go
Normal file
@ -0,0 +1,29 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const TableNameAppUser = "app_user"
|
||||
|
||||
// AppUser mapped from table <app_user>
|
||||
type AppUser struct {
|
||||
ID uint64 `gorm:"column:id;type:bigint unsigned;primaryKey;autoIncrement:true;index:idx_app_user_id,priority:1" json:"id"`
|
||||
AppAccountID uint32 `gorm:"column:app_account_id;type:int unsigned;not null;uniqueIndex:app_account_id_open_id,priority:1;comment:app_account表外键" json:"app_account_id"` // app_account表外键
|
||||
Openid string `gorm:"column:openid;type:varchar(255);not null;uniqueIndex:app_account_id_open_id,priority:2" json:"openid"`
|
||||
Unionid string `gorm:"column:unionid;type:varchar(255);not null" json:"unionid"`
|
||||
Nickname string `gorm:"column:nickname;type:varchar(255);not null;comment:昵称" json:"nickname"` // 昵称
|
||||
Avatar string `gorm:"column:avatar;type:varchar(255);not null;comment:头像" json:"avatar"` // 头像
|
||||
AnonymousOpenid string `gorm:"column:anonymous_openid;type:varchar(255);not null;comment:匿名openid" json:"anonymous_openid"` // 匿名openid
|
||||
CreatedAt time.Time `gorm:"column:created_at;type:datetime;not null;default:CURRENT_TIMESTAMP;comment:创建时间" json:"created_at"` // 创建时间
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;type:datetime;not null;default:CURRENT_TIMESTAMP;comment:更新时间" json:"updated_at"` // 更新时间
|
||||
}
|
||||
|
||||
// TableName AppUser's table name
|
||||
func (*AppUser) TableName() string {
|
||||
return TableNameAppUser
|
||||
}
|
20
gorm-gen/dao/model/douyin_ecpm_config.gen.go
Normal file
20
gorm-gen/dao/model/douyin_ecpm_config.gen.go
Normal file
@ -0,0 +1,20 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package model
|
||||
|
||||
const TableNameDouyinEcpmConfig = "douyin_ecpm_config"
|
||||
|
||||
// DouyinEcpmConfig mapped from table <douyin_ecpm_config>
|
||||
type DouyinEcpmConfig struct {
|
||||
ID uint32 `gorm:"column:id;type:int unsigned;primaryKey;autoIncrement:true" json:"id"`
|
||||
AppAccountID uint32 `gorm:"column:app_account_id;type:int unsigned;not null;index:app_account_id,priority:1" json:"app_account_id"`
|
||||
EcpmValue uint32 `gorm:"column:ecpm_value;type:int unsigned;not null;comment:值" json:"ecpm_value"` // 值
|
||||
EcpmView uint32 `gorm:"column:ecpm_view;type:int unsigned;not null;comment:浏览次数" json:"ecpm_view"` // 浏览次数
|
||||
}
|
||||
|
||||
// TableName DouyinEcpmConfig's table name
|
||||
func (*DouyinEcpmConfig) TableName() string {
|
||||
return TableNameDouyinEcpmConfig
|
||||
}
|
26
gorm-gen/dao/model/game_score.gen.go
Normal file
26
gorm-gen/dao/model/game_score.gen.go
Normal file
@ -0,0 +1,26 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const TableNameGameScore = "game_score"
|
||||
|
||||
// GameScore mapped from table <game_score>
|
||||
type GameScore struct {
|
||||
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
|
||||
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
|
||||
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"` // 得分类型(区分相同小游戏中的不同模式得分)
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;comment:更新时间" json:"updated_at"` // 更新时间
|
||||
}
|
||||
|
||||
// TableName GameScore's table name
|
||||
func (*GameScore) TableName() string {
|
||||
return TableNameGameScore
|
||||
}
|
417
gorm-gen/dao/query/app_account.gen.go
Normal file
417
gorm-gen/dao/query/app_account.gen.go
Normal file
@ -0,0 +1,417 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
)
|
||||
|
||||
func newAppAccount(db *gorm.DB, opts ...gen.DOOption) appAccount {
|
||||
_appAccount := appAccount{}
|
||||
|
||||
_appAccount.appAccountDo.UseDB(db, opts...)
|
||||
_appAccount.appAccountDo.UseModel(&model.AppAccount{})
|
||||
|
||||
tableName := _appAccount.appAccountDo.TableName()
|
||||
_appAccount.ALL = field.NewAsterisk(tableName)
|
||||
_appAccount.ID = field.NewUint32(tableName, "id")
|
||||
_appAccount.Type = field.NewUint32(tableName, "type")
|
||||
_appAccount.AppID = field.NewString(tableName, "app_id")
|
||||
_appAccount.Secret = field.NewString(tableName, "secret")
|
||||
_appAccount.Remark = field.NewString(tableName, "remark")
|
||||
_appAccount.DeletedAt = field.NewField(tableName, "deleted_at")
|
||||
|
||||
_appAccount.fillFieldMap()
|
||||
|
||||
return _appAccount
|
||||
}
|
||||
|
||||
type appAccount struct {
|
||||
appAccountDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Uint32
|
||||
Type field.Uint32
|
||||
AppID field.String
|
||||
Secret field.String
|
||||
Remark field.String
|
||||
DeletedAt field.Field
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (a appAccount) Table(newTableName string) *appAccount {
|
||||
a.appAccountDo.UseTable(newTableName)
|
||||
return a.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (a appAccount) As(alias string) *appAccount {
|
||||
a.appAccountDo.DO = *(a.appAccountDo.As(alias).(*gen.DO))
|
||||
return a.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (a *appAccount) updateTableName(table string) *appAccount {
|
||||
a.ALL = field.NewAsterisk(table)
|
||||
a.ID = field.NewUint32(table, "id")
|
||||
a.Type = field.NewUint32(table, "type")
|
||||
a.AppID = field.NewString(table, "app_id")
|
||||
a.Secret = field.NewString(table, "secret")
|
||||
a.Remark = field.NewString(table, "remark")
|
||||
a.DeletedAt = field.NewField(table, "deleted_at")
|
||||
|
||||
a.fillFieldMap()
|
||||
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *appAccount) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := a.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (a *appAccount) fillFieldMap() {
|
||||
a.fieldMap = make(map[string]field.Expr, 6)
|
||||
a.fieldMap["id"] = a.ID
|
||||
a.fieldMap["type"] = a.Type
|
||||
a.fieldMap["app_id"] = a.AppID
|
||||
a.fieldMap["secret"] = a.Secret
|
||||
a.fieldMap["remark"] = a.Remark
|
||||
a.fieldMap["deleted_at"] = a.DeletedAt
|
||||
}
|
||||
|
||||
func (a appAccount) clone(db *gorm.DB) appAccount {
|
||||
a.appAccountDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return a
|
||||
}
|
||||
|
||||
func (a appAccount) replaceDB(db *gorm.DB) appAccount {
|
||||
a.appAccountDo.ReplaceDB(db)
|
||||
return a
|
||||
}
|
||||
|
||||
type appAccountDo struct{ gen.DO }
|
||||
|
||||
type IAppAccountDo interface {
|
||||
gen.SubQuery
|
||||
Debug() IAppAccountDo
|
||||
WithContext(ctx context.Context) IAppAccountDo
|
||||
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
|
||||
ReplaceDB(db *gorm.DB)
|
||||
ReadDB() IAppAccountDo
|
||||
WriteDB() IAppAccountDo
|
||||
As(alias string) gen.Dao
|
||||
Session(config *gorm.Session) IAppAccountDo
|
||||
Columns(cols ...field.Expr) gen.Columns
|
||||
Clauses(conds ...clause.Expression) IAppAccountDo
|
||||
Not(conds ...gen.Condition) IAppAccountDo
|
||||
Or(conds ...gen.Condition) IAppAccountDo
|
||||
Select(conds ...field.Expr) IAppAccountDo
|
||||
Where(conds ...gen.Condition) IAppAccountDo
|
||||
Order(conds ...field.Expr) IAppAccountDo
|
||||
Distinct(cols ...field.Expr) IAppAccountDo
|
||||
Omit(cols ...field.Expr) IAppAccountDo
|
||||
Join(table schema.Tabler, on ...field.Expr) IAppAccountDo
|
||||
LeftJoin(table schema.Tabler, on ...field.Expr) IAppAccountDo
|
||||
RightJoin(table schema.Tabler, on ...field.Expr) IAppAccountDo
|
||||
Group(cols ...field.Expr) IAppAccountDo
|
||||
Having(conds ...gen.Condition) IAppAccountDo
|
||||
Limit(limit int) IAppAccountDo
|
||||
Offset(offset int) IAppAccountDo
|
||||
Count() (count int64, err error)
|
||||
Scopes(funcs ...func(gen.Dao) gen.Dao) IAppAccountDo
|
||||
Unscoped() IAppAccountDo
|
||||
Create(values ...*model.AppAccount) error
|
||||
CreateInBatches(values []*model.AppAccount, batchSize int) error
|
||||
Save(values ...*model.AppAccount) error
|
||||
First() (*model.AppAccount, error)
|
||||
Take() (*model.AppAccount, error)
|
||||
Last() (*model.AppAccount, error)
|
||||
Find() ([]*model.AppAccount, error)
|
||||
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.AppAccount, err error)
|
||||
FindInBatches(result *[]*model.AppAccount, batchSize int, fc func(tx gen.Dao, batch int) error) error
|
||||
Pluck(column field.Expr, dest interface{}) error
|
||||
Delete(...*model.AppAccount) (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) IAppAccountDo
|
||||
Assign(attrs ...field.AssignExpr) IAppAccountDo
|
||||
Joins(fields ...field.RelationField) IAppAccountDo
|
||||
Preload(fields ...field.RelationField) IAppAccountDo
|
||||
FirstOrInit() (*model.AppAccount, error)
|
||||
FirstOrCreate() (*model.AppAccount, error)
|
||||
FindByPage(offset int, limit int) (result []*model.AppAccount, 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) IAppAccountDo
|
||||
UnderlyingDB() *gorm.DB
|
||||
schema.Tabler
|
||||
|
||||
GetAppConfig() (result []*model.AppAccount, err error)
|
||||
}
|
||||
|
||||
// GetAppConfig 获取所有小游戏配置
|
||||
//
|
||||
// select `app_id`,`secret`,`ecpm_value`,`ecpm_view`,`type` from `app_account` left join douyin_ecpm_config on app_account.id = douyin_ecpm_config.app_account_id
|
||||
func (a appAccountDo) GetAppConfig() (result []*model.AppAccount, err error) {
|
||||
var generateSQL strings.Builder
|
||||
generateSQL.WriteString("select `app_id`,`secret`,`ecpm_value`,`ecpm_view`,`type` from `app_account` left join douyin_ecpm_config on app_account.id = douyin_ecpm_config.app_account_id ")
|
||||
|
||||
var executeSQL *gorm.DB
|
||||
executeSQL = a.UnderlyingDB().Raw(generateSQL.String()).Find(&result) // ignore_security_alert
|
||||
err = executeSQL.Error
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (a appAccountDo) Debug() IAppAccountDo {
|
||||
return a.withDO(a.DO.Debug())
|
||||
}
|
||||
|
||||
func (a appAccountDo) WithContext(ctx context.Context) IAppAccountDo {
|
||||
return a.withDO(a.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (a appAccountDo) ReadDB() IAppAccountDo {
|
||||
return a.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (a appAccountDo) WriteDB() IAppAccountDo {
|
||||
return a.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (a appAccountDo) Session(config *gorm.Session) IAppAccountDo {
|
||||
return a.withDO(a.DO.Session(config))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Clauses(conds ...clause.Expression) IAppAccountDo {
|
||||
return a.withDO(a.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Returning(value interface{}, columns ...string) IAppAccountDo {
|
||||
return a.withDO(a.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Not(conds ...gen.Condition) IAppAccountDo {
|
||||
return a.withDO(a.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Or(conds ...gen.Condition) IAppAccountDo {
|
||||
return a.withDO(a.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Select(conds ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Where(conds ...gen.Condition) IAppAccountDo {
|
||||
return a.withDO(a.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Order(conds ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Distinct(cols ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Omit(cols ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Join(table schema.Tabler, on ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) LeftJoin(table schema.Tabler, on ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) RightJoin(table schema.Tabler, on ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Group(cols ...field.Expr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Having(conds ...gen.Condition) IAppAccountDo {
|
||||
return a.withDO(a.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Limit(limit int) IAppAccountDo {
|
||||
return a.withDO(a.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Offset(offset int) IAppAccountDo {
|
||||
return a.withDO(a.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IAppAccountDo {
|
||||
return a.withDO(a.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Unscoped() IAppAccountDo {
|
||||
return a.withDO(a.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (a appAccountDo) Create(values ...*model.AppAccount) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return a.DO.Create(values)
|
||||
}
|
||||
|
||||
func (a appAccountDo) CreateInBatches(values []*model.AppAccount, batchSize int) error {
|
||||
return a.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (a appAccountDo) Save(values ...*model.AppAccount) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return a.DO.Save(values)
|
||||
}
|
||||
|
||||
func (a appAccountDo) First() (*model.AppAccount, error) {
|
||||
if result, err := a.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppAccount), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appAccountDo) Take() (*model.AppAccount, error) {
|
||||
if result, err := a.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppAccount), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appAccountDo) Last() (*model.AppAccount, error) {
|
||||
if result, err := a.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppAccount), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appAccountDo) Find() ([]*model.AppAccount, error) {
|
||||
result, err := a.DO.Find()
|
||||
return result.([]*model.AppAccount), err
|
||||
}
|
||||
|
||||
func (a appAccountDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.AppAccount, err error) {
|
||||
buf := make([]*model.AppAccount, 0, batchSize)
|
||||
err = a.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (a appAccountDo) FindInBatches(result *[]*model.AppAccount, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return a.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (a appAccountDo) Attrs(attrs ...field.AssignExpr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Assign(attrs ...field.AssignExpr) IAppAccountDo {
|
||||
return a.withDO(a.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (a appAccountDo) Joins(fields ...field.RelationField) IAppAccountDo {
|
||||
for _, _f := range fields {
|
||||
a = *a.withDO(a.DO.Joins(_f))
|
||||
}
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a appAccountDo) Preload(fields ...field.RelationField) IAppAccountDo {
|
||||
for _, _f := range fields {
|
||||
a = *a.withDO(a.DO.Preload(_f))
|
||||
}
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a appAccountDo) FirstOrInit() (*model.AppAccount, error) {
|
||||
if result, err := a.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppAccount), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appAccountDo) FirstOrCreate() (*model.AppAccount, error) {
|
||||
if result, err := a.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppAccount), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appAccountDo) FindByPage(offset int, limit int) (result []*model.AppAccount, count int64, err error) {
|
||||
result, err = a.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = a.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (a appAccountDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = a.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = a.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (a appAccountDo) Scan(result interface{}) (err error) {
|
||||
return a.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (a appAccountDo) Delete(models ...*model.AppAccount) (result gen.ResultInfo, err error) {
|
||||
return a.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (a *appAccountDo) withDO(do gen.Dao) *appAccountDo {
|
||||
a.DO = *do.(*gen.DO)
|
||||
return a
|
||||
}
|
145
gorm-gen/dao/query/app_account.gen_test.go
Normal file
145
gorm-gen/dao/query/app_account.gen_test.go
Normal file
@ -0,0 +1,145 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func init() {
|
||||
InitializeDB()
|
||||
err := _gen_test_db.AutoMigrate(&model.AppAccount{})
|
||||
if err != nil {
|
||||
fmt.Printf("Error: AutoMigrate(&model.AppAccount{}) fail: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_appAccountQuery(t *testing.T) {
|
||||
appAccount := newAppAccount(_gen_test_db)
|
||||
appAccount = *appAccount.As(appAccount.TableName())
|
||||
_do := appAccount.WithContext(context.Background()).Debug()
|
||||
|
||||
primaryKey := field.NewString(appAccount.TableName(), clause.PrimaryKey)
|
||||
_, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete()
|
||||
if err != nil {
|
||||
t.Error("clean table <app_account> fail:", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, ok := appAccount.GetFieldByName("")
|
||||
if ok {
|
||||
t.Error("GetFieldByName(\"\") from appAccount success")
|
||||
}
|
||||
|
||||
err = _do.Create(&model.AppAccount{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Save(&model.AppAccount{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.CreateInBatches([]*model.AppAccount{{}, {}}, 10)
|
||||
if err != nil {
|
||||
t.Error("create item in table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(appAccount.ALL).Take()
|
||||
if err != nil {
|
||||
t.Error("Take() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.First()
|
||||
if err != nil {
|
||||
t.Error("First() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Last()
|
||||
if err != nil {
|
||||
t.Error("First() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatch() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.AppAccount{}, 10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatches() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(appAccount.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find()
|
||||
if err != nil {
|
||||
t.Error("Find() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Distinct(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("select Distinct() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(appAccount.ALL).Omit(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("Omit() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Group(primaryKey).Find()
|
||||
if err != nil {
|
||||
t.Error("Group() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find()
|
||||
if err != nil {
|
||||
t.Error("Scopes() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, _, err = _do.FindByPage(0, 1)
|
||||
if err != nil {
|
||||
t.Error("FindByPage() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.ScanByPage(&model.AppAccount{}, 0, 1)
|
||||
if err != nil {
|
||||
t.Error("ScanByPage() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit()
|
||||
if err != nil {
|
||||
t.Error("FirstOrInit() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate()
|
||||
if err != nil {
|
||||
t.Error("FirstOrCreate() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
var _a _another
|
||||
var _aPK = field.NewString(_a.TableName(), "id")
|
||||
|
||||
err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("Join() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("LeftJoin() on table <app_account> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Not().Or().Clauses().Take()
|
||||
if err != nil {
|
||||
t.Error("Not/Or/Clauses on table <app_account> fail:", err)
|
||||
}
|
||||
}
|
412
gorm-gen/dao/query/app_user.gen.go
Normal file
412
gorm-gen/dao/query/app_user.gen.go
Normal file
@ -0,0 +1,412 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
)
|
||||
|
||||
func newAppUser(db *gorm.DB, opts ...gen.DOOption) appUser {
|
||||
_appUser := appUser{}
|
||||
|
||||
_appUser.appUserDo.UseDB(db, opts...)
|
||||
_appUser.appUserDo.UseModel(&model.AppUser{})
|
||||
|
||||
tableName := _appUser.appUserDo.TableName()
|
||||
_appUser.ALL = field.NewAsterisk(tableName)
|
||||
_appUser.ID = field.NewUint64(tableName, "id")
|
||||
_appUser.AppAccountID = field.NewUint32(tableName, "app_account_id")
|
||||
_appUser.Openid = field.NewString(tableName, "openid")
|
||||
_appUser.Unionid = field.NewString(tableName, "unionid")
|
||||
_appUser.Nickname = field.NewString(tableName, "nickname")
|
||||
_appUser.Avatar = field.NewString(tableName, "avatar")
|
||||
_appUser.AnonymousOpenid = field.NewString(tableName, "anonymous_openid")
|
||||
_appUser.CreatedAt = field.NewTime(tableName, "created_at")
|
||||
_appUser.UpdatedAt = field.NewTime(tableName, "updated_at")
|
||||
|
||||
_appUser.fillFieldMap()
|
||||
|
||||
return _appUser
|
||||
}
|
||||
|
||||
type appUser struct {
|
||||
appUserDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Uint64
|
||||
AppAccountID field.Uint32
|
||||
Openid field.String
|
||||
Unionid field.String
|
||||
Nickname field.String
|
||||
Avatar field.String
|
||||
AnonymousOpenid field.String
|
||||
CreatedAt field.Time
|
||||
UpdatedAt field.Time
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (a appUser) Table(newTableName string) *appUser {
|
||||
a.appUserDo.UseTable(newTableName)
|
||||
return a.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (a appUser) As(alias string) *appUser {
|
||||
a.appUserDo.DO = *(a.appUserDo.As(alias).(*gen.DO))
|
||||
return a.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (a *appUser) updateTableName(table string) *appUser {
|
||||
a.ALL = field.NewAsterisk(table)
|
||||
a.ID = field.NewUint64(table, "id")
|
||||
a.AppAccountID = field.NewUint32(table, "app_account_id")
|
||||
a.Openid = field.NewString(table, "openid")
|
||||
a.Unionid = field.NewString(table, "unionid")
|
||||
a.Nickname = field.NewString(table, "nickname")
|
||||
a.Avatar = field.NewString(table, "avatar")
|
||||
a.AnonymousOpenid = field.NewString(table, "anonymous_openid")
|
||||
a.CreatedAt = field.NewTime(table, "created_at")
|
||||
a.UpdatedAt = field.NewTime(table, "updated_at")
|
||||
|
||||
a.fillFieldMap()
|
||||
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *appUser) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := a.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (a *appUser) fillFieldMap() {
|
||||
a.fieldMap = make(map[string]field.Expr, 9)
|
||||
a.fieldMap["id"] = a.ID
|
||||
a.fieldMap["app_account_id"] = a.AppAccountID
|
||||
a.fieldMap["openid"] = a.Openid
|
||||
a.fieldMap["unionid"] = a.Unionid
|
||||
a.fieldMap["nickname"] = a.Nickname
|
||||
a.fieldMap["avatar"] = a.Avatar
|
||||
a.fieldMap["anonymous_openid"] = a.AnonymousOpenid
|
||||
a.fieldMap["created_at"] = a.CreatedAt
|
||||
a.fieldMap["updated_at"] = a.UpdatedAt
|
||||
}
|
||||
|
||||
func (a appUser) clone(db *gorm.DB) appUser {
|
||||
a.appUserDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return a
|
||||
}
|
||||
|
||||
func (a appUser) replaceDB(db *gorm.DB) appUser {
|
||||
a.appUserDo.ReplaceDB(db)
|
||||
return a
|
||||
}
|
||||
|
||||
type appUserDo struct{ gen.DO }
|
||||
|
||||
type IAppUserDo interface {
|
||||
gen.SubQuery
|
||||
Debug() IAppUserDo
|
||||
WithContext(ctx context.Context) IAppUserDo
|
||||
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
|
||||
ReplaceDB(db *gorm.DB)
|
||||
ReadDB() IAppUserDo
|
||||
WriteDB() IAppUserDo
|
||||
As(alias string) gen.Dao
|
||||
Session(config *gorm.Session) IAppUserDo
|
||||
Columns(cols ...field.Expr) gen.Columns
|
||||
Clauses(conds ...clause.Expression) IAppUserDo
|
||||
Not(conds ...gen.Condition) IAppUserDo
|
||||
Or(conds ...gen.Condition) IAppUserDo
|
||||
Select(conds ...field.Expr) IAppUserDo
|
||||
Where(conds ...gen.Condition) IAppUserDo
|
||||
Order(conds ...field.Expr) IAppUserDo
|
||||
Distinct(cols ...field.Expr) IAppUserDo
|
||||
Omit(cols ...field.Expr) IAppUserDo
|
||||
Join(table schema.Tabler, on ...field.Expr) IAppUserDo
|
||||
LeftJoin(table schema.Tabler, on ...field.Expr) IAppUserDo
|
||||
RightJoin(table schema.Tabler, on ...field.Expr) IAppUserDo
|
||||
Group(cols ...field.Expr) IAppUserDo
|
||||
Having(conds ...gen.Condition) IAppUserDo
|
||||
Limit(limit int) IAppUserDo
|
||||
Offset(offset int) IAppUserDo
|
||||
Count() (count int64, err error)
|
||||
Scopes(funcs ...func(gen.Dao) gen.Dao) IAppUserDo
|
||||
Unscoped() IAppUserDo
|
||||
Create(values ...*model.AppUser) error
|
||||
CreateInBatches(values []*model.AppUser, batchSize int) error
|
||||
Save(values ...*model.AppUser) error
|
||||
First() (*model.AppUser, error)
|
||||
Take() (*model.AppUser, error)
|
||||
Last() (*model.AppUser, error)
|
||||
Find() ([]*model.AppUser, error)
|
||||
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.AppUser, err error)
|
||||
FindInBatches(result *[]*model.AppUser, batchSize int, fc func(tx gen.Dao, batch int) error) error
|
||||
Pluck(column field.Expr, dest interface{}) error
|
||||
Delete(...*model.AppUser) (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) IAppUserDo
|
||||
Assign(attrs ...field.AssignExpr) IAppUserDo
|
||||
Joins(fields ...field.RelationField) IAppUserDo
|
||||
Preload(fields ...field.RelationField) IAppUserDo
|
||||
FirstOrInit() (*model.AppUser, error)
|
||||
FirstOrCreate() (*model.AppUser, error)
|
||||
FindByPage(offset int, limit int) (result []*model.AppUser, 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) IAppUserDo
|
||||
UnderlyingDB() *gorm.DB
|
||||
schema.Tabler
|
||||
}
|
||||
|
||||
func (a appUserDo) Debug() IAppUserDo {
|
||||
return a.withDO(a.DO.Debug())
|
||||
}
|
||||
|
||||
func (a appUserDo) WithContext(ctx context.Context) IAppUserDo {
|
||||
return a.withDO(a.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (a appUserDo) ReadDB() IAppUserDo {
|
||||
return a.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (a appUserDo) WriteDB() IAppUserDo {
|
||||
return a.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (a appUserDo) Session(config *gorm.Session) IAppUserDo {
|
||||
return a.withDO(a.DO.Session(config))
|
||||
}
|
||||
|
||||
func (a appUserDo) Clauses(conds ...clause.Expression) IAppUserDo {
|
||||
return a.withDO(a.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Returning(value interface{}, columns ...string) IAppUserDo {
|
||||
return a.withDO(a.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Not(conds ...gen.Condition) IAppUserDo {
|
||||
return a.withDO(a.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Or(conds ...gen.Condition) IAppUserDo {
|
||||
return a.withDO(a.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Select(conds ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Where(conds ...gen.Condition) IAppUserDo {
|
||||
return a.withDO(a.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Order(conds ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Distinct(cols ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Omit(cols ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Join(table schema.Tabler, on ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (a appUserDo) LeftJoin(table schema.Tabler, on ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (a appUserDo) RightJoin(table schema.Tabler, on ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Group(cols ...field.Expr) IAppUserDo {
|
||||
return a.withDO(a.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Having(conds ...gen.Condition) IAppUserDo {
|
||||
return a.withDO(a.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Limit(limit int) IAppUserDo {
|
||||
return a.withDO(a.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (a appUserDo) Offset(offset int) IAppUserDo {
|
||||
return a.withDO(a.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (a appUserDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IAppUserDo {
|
||||
return a.withDO(a.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Unscoped() IAppUserDo {
|
||||
return a.withDO(a.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (a appUserDo) Create(values ...*model.AppUser) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return a.DO.Create(values)
|
||||
}
|
||||
|
||||
func (a appUserDo) CreateInBatches(values []*model.AppUser, batchSize int) error {
|
||||
return a.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (a appUserDo) Save(values ...*model.AppUser) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return a.DO.Save(values)
|
||||
}
|
||||
|
||||
func (a appUserDo) First() (*model.AppUser, error) {
|
||||
if result, err := a.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appUserDo) Take() (*model.AppUser, error) {
|
||||
if result, err := a.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appUserDo) Last() (*model.AppUser, error) {
|
||||
if result, err := a.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appUserDo) Find() ([]*model.AppUser, error) {
|
||||
result, err := a.DO.Find()
|
||||
return result.([]*model.AppUser), err
|
||||
}
|
||||
|
||||
func (a appUserDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.AppUser, err error) {
|
||||
buf := make([]*model.AppUser, 0, batchSize)
|
||||
err = a.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (a appUserDo) FindInBatches(result *[]*model.AppUser, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return a.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (a appUserDo) Attrs(attrs ...field.AssignExpr) IAppUserDo {
|
||||
return a.withDO(a.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Assign(attrs ...field.AssignExpr) IAppUserDo {
|
||||
return a.withDO(a.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (a appUserDo) Joins(fields ...field.RelationField) IAppUserDo {
|
||||
for _, _f := range fields {
|
||||
a = *a.withDO(a.DO.Joins(_f))
|
||||
}
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a appUserDo) Preload(fields ...field.RelationField) IAppUserDo {
|
||||
for _, _f := range fields {
|
||||
a = *a.withDO(a.DO.Preload(_f))
|
||||
}
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a appUserDo) FirstOrInit() (*model.AppUser, error) {
|
||||
if result, err := a.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appUserDo) FirstOrCreate() (*model.AppUser, error) {
|
||||
if result, err := a.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.AppUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a appUserDo) FindByPage(offset int, limit int) (result []*model.AppUser, count int64, err error) {
|
||||
result, err = a.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = a.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (a appUserDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = a.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = a.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (a appUserDo) Scan(result interface{}) (err error) {
|
||||
return a.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (a appUserDo) Delete(models ...*model.AppUser) (result gen.ResultInfo, err error) {
|
||||
return a.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (a *appUserDo) withDO(do gen.Dao) *appUserDo {
|
||||
a.DO = *do.(*gen.DO)
|
||||
return a
|
||||
}
|
145
gorm-gen/dao/query/app_user.gen_test.go
Normal file
145
gorm-gen/dao/query/app_user.gen_test.go
Normal file
@ -0,0 +1,145 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func init() {
|
||||
InitializeDB()
|
||||
err := _gen_test_db.AutoMigrate(&model.AppUser{})
|
||||
if err != nil {
|
||||
fmt.Printf("Error: AutoMigrate(&model.AppUser{}) fail: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_appUserQuery(t *testing.T) {
|
||||
appUser := newAppUser(_gen_test_db)
|
||||
appUser = *appUser.As(appUser.TableName())
|
||||
_do := appUser.WithContext(context.Background()).Debug()
|
||||
|
||||
primaryKey := field.NewString(appUser.TableName(), clause.PrimaryKey)
|
||||
_, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete()
|
||||
if err != nil {
|
||||
t.Error("clean table <app_user> fail:", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, ok := appUser.GetFieldByName("")
|
||||
if ok {
|
||||
t.Error("GetFieldByName(\"\") from appUser success")
|
||||
}
|
||||
|
||||
err = _do.Create(&model.AppUser{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Save(&model.AppUser{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.CreateInBatches([]*model.AppUser{{}, {}}, 10)
|
||||
if err != nil {
|
||||
t.Error("create item in table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(appUser.ALL).Take()
|
||||
if err != nil {
|
||||
t.Error("Take() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.First()
|
||||
if err != nil {
|
||||
t.Error("First() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Last()
|
||||
if err != nil {
|
||||
t.Error("First() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatch() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.AppUser{}, 10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatches() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(appUser.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find()
|
||||
if err != nil {
|
||||
t.Error("Find() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Distinct(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("select Distinct() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(appUser.ALL).Omit(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("Omit() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Group(primaryKey).Find()
|
||||
if err != nil {
|
||||
t.Error("Group() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find()
|
||||
if err != nil {
|
||||
t.Error("Scopes() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, _, err = _do.FindByPage(0, 1)
|
||||
if err != nil {
|
||||
t.Error("FindByPage() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.ScanByPage(&model.AppUser{}, 0, 1)
|
||||
if err != nil {
|
||||
t.Error("ScanByPage() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit()
|
||||
if err != nil {
|
||||
t.Error("FirstOrInit() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate()
|
||||
if err != nil {
|
||||
t.Error("FirstOrCreate() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
var _a _another
|
||||
var _aPK = field.NewString(_a.TableName(), "id")
|
||||
|
||||
err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("Join() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("LeftJoin() on table <app_user> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Not().Or().Clauses().Take()
|
||||
if err != nil {
|
||||
t.Error("Not/Or/Clauses on table <app_user> fail:", err)
|
||||
}
|
||||
}
|
392
gorm-gen/dao/query/douyin_ecpm_config.gen.go
Normal file
392
gorm-gen/dao/query/douyin_ecpm_config.gen.go
Normal file
@ -0,0 +1,392 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
)
|
||||
|
||||
func newDouyinEcpmConfig(db *gorm.DB, opts ...gen.DOOption) douyinEcpmConfig {
|
||||
_douyinEcpmConfig := douyinEcpmConfig{}
|
||||
|
||||
_douyinEcpmConfig.douyinEcpmConfigDo.UseDB(db, opts...)
|
||||
_douyinEcpmConfig.douyinEcpmConfigDo.UseModel(&model.DouyinEcpmConfig{})
|
||||
|
||||
tableName := _douyinEcpmConfig.douyinEcpmConfigDo.TableName()
|
||||
_douyinEcpmConfig.ALL = field.NewAsterisk(tableName)
|
||||
_douyinEcpmConfig.ID = field.NewUint32(tableName, "id")
|
||||
_douyinEcpmConfig.AppAccountID = field.NewUint32(tableName, "app_account_id")
|
||||
_douyinEcpmConfig.EcpmValue = field.NewUint32(tableName, "ecpm_value")
|
||||
_douyinEcpmConfig.EcpmView = field.NewUint32(tableName, "ecpm_view")
|
||||
|
||||
_douyinEcpmConfig.fillFieldMap()
|
||||
|
||||
return _douyinEcpmConfig
|
||||
}
|
||||
|
||||
type douyinEcpmConfig struct {
|
||||
douyinEcpmConfigDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Uint32
|
||||
AppAccountID field.Uint32
|
||||
EcpmValue field.Uint32
|
||||
EcpmView field.Uint32
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfig) Table(newTableName string) *douyinEcpmConfig {
|
||||
d.douyinEcpmConfigDo.UseTable(newTableName)
|
||||
return d.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfig) As(alias string) *douyinEcpmConfig {
|
||||
d.douyinEcpmConfigDo.DO = *(d.douyinEcpmConfigDo.As(alias).(*gen.DO))
|
||||
return d.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (d *douyinEcpmConfig) updateTableName(table string) *douyinEcpmConfig {
|
||||
d.ALL = field.NewAsterisk(table)
|
||||
d.ID = field.NewUint32(table, "id")
|
||||
d.AppAccountID = field.NewUint32(table, "app_account_id")
|
||||
d.EcpmValue = field.NewUint32(table, "ecpm_value")
|
||||
d.EcpmView = field.NewUint32(table, "ecpm_view")
|
||||
|
||||
d.fillFieldMap()
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *douyinEcpmConfig) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := d.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (d *douyinEcpmConfig) fillFieldMap() {
|
||||
d.fieldMap = make(map[string]field.Expr, 4)
|
||||
d.fieldMap["id"] = d.ID
|
||||
d.fieldMap["app_account_id"] = d.AppAccountID
|
||||
d.fieldMap["ecpm_value"] = d.EcpmValue
|
||||
d.fieldMap["ecpm_view"] = d.EcpmView
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfig) clone(db *gorm.DB) douyinEcpmConfig {
|
||||
d.douyinEcpmConfigDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return d
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfig) replaceDB(db *gorm.DB) douyinEcpmConfig {
|
||||
d.douyinEcpmConfigDo.ReplaceDB(db)
|
||||
return d
|
||||
}
|
||||
|
||||
type douyinEcpmConfigDo struct{ gen.DO }
|
||||
|
||||
type IDouyinEcpmConfigDo interface {
|
||||
gen.SubQuery
|
||||
Debug() IDouyinEcpmConfigDo
|
||||
WithContext(ctx context.Context) IDouyinEcpmConfigDo
|
||||
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
|
||||
ReplaceDB(db *gorm.DB)
|
||||
ReadDB() IDouyinEcpmConfigDo
|
||||
WriteDB() IDouyinEcpmConfigDo
|
||||
As(alias string) gen.Dao
|
||||
Session(config *gorm.Session) IDouyinEcpmConfigDo
|
||||
Columns(cols ...field.Expr) gen.Columns
|
||||
Clauses(conds ...clause.Expression) IDouyinEcpmConfigDo
|
||||
Not(conds ...gen.Condition) IDouyinEcpmConfigDo
|
||||
Or(conds ...gen.Condition) IDouyinEcpmConfigDo
|
||||
Select(conds ...field.Expr) IDouyinEcpmConfigDo
|
||||
Where(conds ...gen.Condition) IDouyinEcpmConfigDo
|
||||
Order(conds ...field.Expr) IDouyinEcpmConfigDo
|
||||
Distinct(cols ...field.Expr) IDouyinEcpmConfigDo
|
||||
Omit(cols ...field.Expr) IDouyinEcpmConfigDo
|
||||
Join(table schema.Tabler, on ...field.Expr) IDouyinEcpmConfigDo
|
||||
LeftJoin(table schema.Tabler, on ...field.Expr) IDouyinEcpmConfigDo
|
||||
RightJoin(table schema.Tabler, on ...field.Expr) IDouyinEcpmConfigDo
|
||||
Group(cols ...field.Expr) IDouyinEcpmConfigDo
|
||||
Having(conds ...gen.Condition) IDouyinEcpmConfigDo
|
||||
Limit(limit int) IDouyinEcpmConfigDo
|
||||
Offset(offset int) IDouyinEcpmConfigDo
|
||||
Count() (count int64, err error)
|
||||
Scopes(funcs ...func(gen.Dao) gen.Dao) IDouyinEcpmConfigDo
|
||||
Unscoped() IDouyinEcpmConfigDo
|
||||
Create(values ...*model.DouyinEcpmConfig) error
|
||||
CreateInBatches(values []*model.DouyinEcpmConfig, batchSize int) error
|
||||
Save(values ...*model.DouyinEcpmConfig) error
|
||||
First() (*model.DouyinEcpmConfig, error)
|
||||
Take() (*model.DouyinEcpmConfig, error)
|
||||
Last() (*model.DouyinEcpmConfig, error)
|
||||
Find() ([]*model.DouyinEcpmConfig, error)
|
||||
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.DouyinEcpmConfig, err error)
|
||||
FindInBatches(result *[]*model.DouyinEcpmConfig, batchSize int, fc func(tx gen.Dao, batch int) error) error
|
||||
Pluck(column field.Expr, dest interface{}) error
|
||||
Delete(...*model.DouyinEcpmConfig) (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) IDouyinEcpmConfigDo
|
||||
Assign(attrs ...field.AssignExpr) IDouyinEcpmConfigDo
|
||||
Joins(fields ...field.RelationField) IDouyinEcpmConfigDo
|
||||
Preload(fields ...field.RelationField) IDouyinEcpmConfigDo
|
||||
FirstOrInit() (*model.DouyinEcpmConfig, error)
|
||||
FirstOrCreate() (*model.DouyinEcpmConfig, error)
|
||||
FindByPage(offset int, limit int) (result []*model.DouyinEcpmConfig, 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) IDouyinEcpmConfigDo
|
||||
UnderlyingDB() *gorm.DB
|
||||
schema.Tabler
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Debug() IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Debug())
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) WithContext(ctx context.Context) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) ReadDB() IDouyinEcpmConfigDo {
|
||||
return d.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) WriteDB() IDouyinEcpmConfigDo {
|
||||
return d.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Session(config *gorm.Session) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Session(config))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Clauses(conds ...clause.Expression) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Returning(value interface{}, columns ...string) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Not(conds ...gen.Condition) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Or(conds ...gen.Condition) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Select(conds ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Where(conds ...gen.Condition) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Order(conds ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Distinct(cols ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Omit(cols ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Join(table schema.Tabler, on ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) LeftJoin(table schema.Tabler, on ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) RightJoin(table schema.Tabler, on ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Group(cols ...field.Expr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Having(conds ...gen.Condition) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Limit(limit int) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Offset(offset int) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Unscoped() IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Create(values ...*model.DouyinEcpmConfig) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return d.DO.Create(values)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) CreateInBatches(values []*model.DouyinEcpmConfig, batchSize int) error {
|
||||
return d.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (d douyinEcpmConfigDo) Save(values ...*model.DouyinEcpmConfig) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return d.DO.Save(values)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) First() (*model.DouyinEcpmConfig, error) {
|
||||
if result, err := d.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.DouyinEcpmConfig), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Take() (*model.DouyinEcpmConfig, error) {
|
||||
if result, err := d.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.DouyinEcpmConfig), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Last() (*model.DouyinEcpmConfig, error) {
|
||||
if result, err := d.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.DouyinEcpmConfig), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Find() ([]*model.DouyinEcpmConfig, error) {
|
||||
result, err := d.DO.Find()
|
||||
return result.([]*model.DouyinEcpmConfig), err
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.DouyinEcpmConfig, err error) {
|
||||
buf := make([]*model.DouyinEcpmConfig, 0, batchSize)
|
||||
err = d.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) FindInBatches(result *[]*model.DouyinEcpmConfig, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return d.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Attrs(attrs ...field.AssignExpr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Assign(attrs ...field.AssignExpr) IDouyinEcpmConfigDo {
|
||||
return d.withDO(d.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Joins(fields ...field.RelationField) IDouyinEcpmConfigDo {
|
||||
for _, _f := range fields {
|
||||
d = *d.withDO(d.DO.Joins(_f))
|
||||
}
|
||||
return &d
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Preload(fields ...field.RelationField) IDouyinEcpmConfigDo {
|
||||
for _, _f := range fields {
|
||||
d = *d.withDO(d.DO.Preload(_f))
|
||||
}
|
||||
return &d
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) FirstOrInit() (*model.DouyinEcpmConfig, error) {
|
||||
if result, err := d.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.DouyinEcpmConfig), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) FirstOrCreate() (*model.DouyinEcpmConfig, error) {
|
||||
if result, err := d.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.DouyinEcpmConfig), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) FindByPage(offset int, limit int) (result []*model.DouyinEcpmConfig, count int64, err error) {
|
||||
result, err = d.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = d.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = d.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = d.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Scan(result interface{}) (err error) {
|
||||
return d.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (d douyinEcpmConfigDo) Delete(models ...*model.DouyinEcpmConfig) (result gen.ResultInfo, err error) {
|
||||
return d.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (d *douyinEcpmConfigDo) withDO(do gen.Dao) *douyinEcpmConfigDo {
|
||||
d.DO = *do.(*gen.DO)
|
||||
return d
|
||||
}
|
145
gorm-gen/dao/query/douyin_ecpm_config.gen_test.go
Normal file
145
gorm-gen/dao/query/douyin_ecpm_config.gen_test.go
Normal file
@ -0,0 +1,145 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func init() {
|
||||
InitializeDB()
|
||||
err := _gen_test_db.AutoMigrate(&model.DouyinEcpmConfig{})
|
||||
if err != nil {
|
||||
fmt.Printf("Error: AutoMigrate(&model.DouyinEcpmConfig{}) fail: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_douyinEcpmConfigQuery(t *testing.T) {
|
||||
douyinEcpmConfig := newDouyinEcpmConfig(_gen_test_db)
|
||||
douyinEcpmConfig = *douyinEcpmConfig.As(douyinEcpmConfig.TableName())
|
||||
_do := douyinEcpmConfig.WithContext(context.Background()).Debug()
|
||||
|
||||
primaryKey := field.NewString(douyinEcpmConfig.TableName(), clause.PrimaryKey)
|
||||
_, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete()
|
||||
if err != nil {
|
||||
t.Error("clean table <douyin_ecpm_config> fail:", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, ok := douyinEcpmConfig.GetFieldByName("")
|
||||
if ok {
|
||||
t.Error("GetFieldByName(\"\") from douyinEcpmConfig success")
|
||||
}
|
||||
|
||||
err = _do.Create(&model.DouyinEcpmConfig{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Save(&model.DouyinEcpmConfig{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.CreateInBatches([]*model.DouyinEcpmConfig{{}, {}}, 10)
|
||||
if err != nil {
|
||||
t.Error("create item in table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(douyinEcpmConfig.ALL).Take()
|
||||
if err != nil {
|
||||
t.Error("Take() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.First()
|
||||
if err != nil {
|
||||
t.Error("First() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Last()
|
||||
if err != nil {
|
||||
t.Error("First() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatch() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.DouyinEcpmConfig{}, 10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatches() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(douyinEcpmConfig.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find()
|
||||
if err != nil {
|
||||
t.Error("Find() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Distinct(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("select Distinct() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(douyinEcpmConfig.ALL).Omit(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("Omit() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Group(primaryKey).Find()
|
||||
if err != nil {
|
||||
t.Error("Group() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find()
|
||||
if err != nil {
|
||||
t.Error("Scopes() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, _, err = _do.FindByPage(0, 1)
|
||||
if err != nil {
|
||||
t.Error("FindByPage() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.ScanByPage(&model.DouyinEcpmConfig{}, 0, 1)
|
||||
if err != nil {
|
||||
t.Error("ScanByPage() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit()
|
||||
if err != nil {
|
||||
t.Error("FirstOrInit() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate()
|
||||
if err != nil {
|
||||
t.Error("FirstOrCreate() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
var _a _another
|
||||
var _aPK = field.NewString(_a.TableName(), "id")
|
||||
|
||||
err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("Join() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("LeftJoin() on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Not().Or().Clauses().Take()
|
||||
if err != nil {
|
||||
t.Error("Not/Or/Clauses on table <douyin_ecpm_config> fail:", err)
|
||||
}
|
||||
}
|
457
gorm-gen/dao/query/game_score.gen.go
Normal file
457
gorm-gen/dao/query/game_score.gen.go
Normal file
@ -0,0 +1,457 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/querier"
|
||||
)
|
||||
|
||||
func newGameScore(db *gorm.DB, opts ...gen.DOOption) gameScore {
|
||||
_gameScore := gameScore{}
|
||||
|
||||
_gameScore.gameScoreDo.UseDB(db, opts...)
|
||||
_gameScore.gameScoreDo.UseModel(&model.GameScore{})
|
||||
|
||||
tableName := _gameScore.gameScoreDo.TableName()
|
||||
_gameScore.ALL = field.NewAsterisk(tableName)
|
||||
_gameScore.ID = field.NewUint64(tableName, "id")
|
||||
_gameScore.AppAccount = field.NewUint32(tableName, "app_account")
|
||||
_gameScore.AppUserID = field.NewUint64(tableName, "app_user_id")
|
||||
_gameScore.Score = field.NewUint32(tableName, "score")
|
||||
_gameScore.T = field.NewUint32(tableName, "t")
|
||||
_gameScore.UpdatedAt = field.NewTime(tableName, "updated_at")
|
||||
|
||||
_gameScore.fillFieldMap()
|
||||
|
||||
return _gameScore
|
||||
}
|
||||
|
||||
type gameScore struct {
|
||||
gameScoreDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Uint64
|
||||
AppAccount field.Uint32
|
||||
AppUserID field.Uint64
|
||||
Score field.Uint32
|
||||
T field.Uint32
|
||||
UpdatedAt field.Time
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (g gameScore) Table(newTableName string) *gameScore {
|
||||
g.gameScoreDo.UseTable(newTableName)
|
||||
return g.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (g gameScore) As(alias string) *gameScore {
|
||||
g.gameScoreDo.DO = *(g.gameScoreDo.As(alias).(*gen.DO))
|
||||
return g.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (g *gameScore) updateTableName(table string) *gameScore {
|
||||
g.ALL = field.NewAsterisk(table)
|
||||
g.ID = field.NewUint64(table, "id")
|
||||
g.AppAccount = field.NewUint32(table, "app_account")
|
||||
g.AppUserID = field.NewUint64(table, "app_user_id")
|
||||
g.Score = field.NewUint32(table, "score")
|
||||
g.T = field.NewUint32(table, "t")
|
||||
g.UpdatedAt = field.NewTime(table, "updated_at")
|
||||
|
||||
g.fillFieldMap()
|
||||
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *gameScore) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := g.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (g *gameScore) fillFieldMap() {
|
||||
g.fieldMap = make(map[string]field.Expr, 6)
|
||||
g.fieldMap["id"] = g.ID
|
||||
g.fieldMap["app_account"] = g.AppAccount
|
||||
g.fieldMap["app_user_id"] = g.AppUserID
|
||||
g.fieldMap["score"] = g.Score
|
||||
g.fieldMap["t"] = g.T
|
||||
g.fieldMap["updated_at"] = g.UpdatedAt
|
||||
}
|
||||
|
||||
func (g gameScore) clone(db *gorm.DB) gameScore {
|
||||
g.gameScoreDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return g
|
||||
}
|
||||
|
||||
func (g gameScore) replaceDB(db *gorm.DB) gameScore {
|
||||
g.gameScoreDo.ReplaceDB(db)
|
||||
return g
|
||||
}
|
||||
|
||||
type gameScoreDo struct{ gen.DO }
|
||||
|
||||
type IGameScoreDo interface {
|
||||
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())
|
||||
}
|
||||
|
||||
func (g gameScoreDo) WithContext(ctx context.Context) IGameScoreDo {
|
||||
return g.withDO(g.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) ReadDB() IGameScoreDo {
|
||||
return g.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (g gameScoreDo) WriteDB() IGameScoreDo {
|
||||
return g.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Session(config *gorm.Session) IGameScoreDo {
|
||||
return g.withDO(g.DO.Session(config))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Clauses(conds ...clause.Expression) IGameScoreDo {
|
||||
return g.withDO(g.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Returning(value interface{}, columns ...string) IGameScoreDo {
|
||||
return g.withDO(g.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Not(conds ...gen.Condition) IGameScoreDo {
|
||||
return g.withDO(g.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Or(conds ...gen.Condition) IGameScoreDo {
|
||||
return g.withDO(g.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Select(conds ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Where(conds ...gen.Condition) IGameScoreDo {
|
||||
return g.withDO(g.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Order(conds ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Distinct(cols ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Omit(cols ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Join(table schema.Tabler, on ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) LeftJoin(table schema.Tabler, on ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) RightJoin(table schema.Tabler, on ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Group(cols ...field.Expr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Having(conds ...gen.Condition) IGameScoreDo {
|
||||
return g.withDO(g.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Limit(limit int) IGameScoreDo {
|
||||
return g.withDO(g.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Offset(offset int) IGameScoreDo {
|
||||
return g.withDO(g.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IGameScoreDo {
|
||||
return g.withDO(g.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Unscoped() IGameScoreDo {
|
||||
return g.withDO(g.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Create(values ...*model.GameScore) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return g.DO.Create(values)
|
||||
}
|
||||
|
||||
func (g gameScoreDo) CreateInBatches(values []*model.GameScore, batchSize int) error {
|
||||
return g.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (g gameScoreDo) Save(values ...*model.GameScore) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return g.DO.Save(values)
|
||||
}
|
||||
|
||||
func (g gameScoreDo) First() (*model.GameScore, error) {
|
||||
if result, err := g.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.GameScore), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Take() (*model.GameScore, error) {
|
||||
if result, err := g.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.GameScore), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Last() (*model.GameScore, error) {
|
||||
if result, err := g.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.GameScore), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Find() ([]*model.GameScore, error) {
|
||||
result, err := g.DO.Find()
|
||||
return result.([]*model.GameScore), err
|
||||
}
|
||||
|
||||
func (g gameScoreDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.GameScore, err error) {
|
||||
buf := make([]*model.GameScore, 0, batchSize)
|
||||
err = g.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (g gameScoreDo) FindInBatches(result *[]*model.GameScore, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return g.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Attrs(attrs ...field.AssignExpr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Assign(attrs ...field.AssignExpr) IGameScoreDo {
|
||||
return g.withDO(g.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Joins(fields ...field.RelationField) IGameScoreDo {
|
||||
for _, _f := range fields {
|
||||
g = *g.withDO(g.DO.Joins(_f))
|
||||
}
|
||||
return &g
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Preload(fields ...field.RelationField) IGameScoreDo {
|
||||
for _, _f := range fields {
|
||||
g = *g.withDO(g.DO.Preload(_f))
|
||||
}
|
||||
return &g
|
||||
}
|
||||
|
||||
func (g gameScoreDo) FirstOrInit() (*model.GameScore, error) {
|
||||
if result, err := g.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.GameScore), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g gameScoreDo) FirstOrCreate() (*model.GameScore, error) {
|
||||
if result, err := g.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.GameScore), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g gameScoreDo) FindByPage(offset int, limit int) (result []*model.GameScore, count int64, err error) {
|
||||
result, err = g.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = g.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (g gameScoreDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = g.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = g.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Scan(result interface{}) (err error) {
|
||||
return g.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (g gameScoreDo) Delete(models ...*model.GameScore) (result gen.ResultInfo, err error) {
|
||||
return g.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (g *gameScoreDo) withDO(do gen.Dao) *gameScoreDo {
|
||||
g.DO = *do.(*gen.DO)
|
||||
return g
|
||||
}
|
145
gorm-gen/dao/query/game_score.gen_test.go
Normal file
145
gorm-gen/dao/query/game_score.gen_test.go
Normal file
@ -0,0 +1,145 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func init() {
|
||||
InitializeDB()
|
||||
err := _gen_test_db.AutoMigrate(&model.GameScore{})
|
||||
if err != nil {
|
||||
fmt.Printf("Error: AutoMigrate(&model.GameScore{}) fail: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_gameScoreQuery(t *testing.T) {
|
||||
gameScore := newGameScore(_gen_test_db)
|
||||
gameScore = *gameScore.As(gameScore.TableName())
|
||||
_do := gameScore.WithContext(context.Background()).Debug()
|
||||
|
||||
primaryKey := field.NewString(gameScore.TableName(), clause.PrimaryKey)
|
||||
_, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete()
|
||||
if err != nil {
|
||||
t.Error("clean table <game_score> fail:", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, ok := gameScore.GetFieldByName("")
|
||||
if ok {
|
||||
t.Error("GetFieldByName(\"\") from gameScore success")
|
||||
}
|
||||
|
||||
err = _do.Create(&model.GameScore{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Save(&model.GameScore{})
|
||||
if err != nil {
|
||||
t.Error("create item in table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.CreateInBatches([]*model.GameScore{{}, {}}, 10)
|
||||
if err != nil {
|
||||
t.Error("create item in table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(gameScore.ALL).Take()
|
||||
if err != nil {
|
||||
t.Error("Take() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.First()
|
||||
if err != nil {
|
||||
t.Error("First() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Last()
|
||||
if err != nil {
|
||||
t.Error("First() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatch() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.GameScore{}, 10, func(tx gen.Dao, batch int) error { return nil })
|
||||
if err != nil {
|
||||
t.Error("FindInBatches() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(gameScore.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find()
|
||||
if err != nil {
|
||||
t.Error("Find() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Distinct(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("select Distinct() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Select(gameScore.ALL).Omit(primaryKey).Take()
|
||||
if err != nil {
|
||||
t.Error("Omit() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Group(primaryKey).Find()
|
||||
if err != nil {
|
||||
t.Error("Group() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find()
|
||||
if err != nil {
|
||||
t.Error("Scopes() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, _, err = _do.FindByPage(0, 1)
|
||||
if err != nil {
|
||||
t.Error("FindByPage() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.ScanByPage(&model.GameScore{}, 0, 1)
|
||||
if err != nil {
|
||||
t.Error("ScanByPage() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit()
|
||||
if err != nil {
|
||||
t.Error("FirstOrInit() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate()
|
||||
if err != nil {
|
||||
t.Error("FirstOrCreate() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
var _a _another
|
||||
var _aPK = field.NewString(_a.TableName(), "id")
|
||||
|
||||
err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("Join() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
|
||||
if err != nil {
|
||||
t.Error("LeftJoin() on table <game_score> fail:", err)
|
||||
}
|
||||
|
||||
_, err = _do.Not().Or().Clauses().Take()
|
||||
if err != nil {
|
||||
t.Error("Not/Or/Clauses on table <game_score> fail:", err)
|
||||
}
|
||||
}
|
127
gorm-gen/dao/query/gen.go
Normal file
127
gorm-gen/dao/query/gen.go
Normal file
@ -0,0 +1,127 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"gorm.io/gen"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
)
|
||||
|
||||
var (
|
||||
Q = new(Query)
|
||||
AppAccount *appAccount
|
||||
AppUser *appUser
|
||||
DouyinEcpmConfig *douyinEcpmConfig
|
||||
GameScore *gameScore
|
||||
)
|
||||
|
||||
func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
|
||||
*Q = *Use(db, opts...)
|
||||
AppAccount = &Q.AppAccount
|
||||
AppUser = &Q.AppUser
|
||||
DouyinEcpmConfig = &Q.DouyinEcpmConfig
|
||||
GameScore = &Q.GameScore
|
||||
}
|
||||
|
||||
func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
|
||||
return &Query{
|
||||
db: db,
|
||||
AppAccount: newAppAccount(db, opts...),
|
||||
AppUser: newAppUser(db, opts...),
|
||||
DouyinEcpmConfig: newDouyinEcpmConfig(db, opts...),
|
||||
GameScore: newGameScore(db, opts...),
|
||||
}
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
db *gorm.DB
|
||||
|
||||
AppAccount appAccount
|
||||
AppUser appUser
|
||||
DouyinEcpmConfig douyinEcpmConfig
|
||||
GameScore gameScore
|
||||
}
|
||||
|
||||
func (q *Query) Available() bool { return q.db != nil }
|
||||
|
||||
func (q *Query) clone(db *gorm.DB) *Query {
|
||||
return &Query{
|
||||
db: db,
|
||||
AppAccount: q.AppAccount.clone(db),
|
||||
AppUser: q.AppUser.clone(db),
|
||||
DouyinEcpmConfig: q.DouyinEcpmConfig.clone(db),
|
||||
GameScore: q.GameScore.clone(db),
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Query) ReadDB() *Query {
|
||||
return q.ReplaceDB(q.db.Clauses(dbresolver.Read))
|
||||
}
|
||||
|
||||
func (q *Query) WriteDB() *Query {
|
||||
return q.ReplaceDB(q.db.Clauses(dbresolver.Write))
|
||||
}
|
||||
|
||||
func (q *Query) ReplaceDB(db *gorm.DB) *Query {
|
||||
return &Query{
|
||||
db: db,
|
||||
AppAccount: q.AppAccount.replaceDB(db),
|
||||
AppUser: q.AppUser.replaceDB(db),
|
||||
DouyinEcpmConfig: q.DouyinEcpmConfig.replaceDB(db),
|
||||
GameScore: q.GameScore.replaceDB(db),
|
||||
}
|
||||
}
|
||||
|
||||
type queryCtx struct {
|
||||
AppAccount IAppAccountDo
|
||||
AppUser IAppUserDo
|
||||
DouyinEcpmConfig IDouyinEcpmConfigDo
|
||||
GameScore IGameScoreDo
|
||||
}
|
||||
|
||||
func (q *Query) WithContext(ctx context.Context) *queryCtx {
|
||||
return &queryCtx{
|
||||
AppAccount: q.AppAccount.WithContext(ctx),
|
||||
AppUser: q.AppUser.WithContext(ctx),
|
||||
DouyinEcpmConfig: q.DouyinEcpmConfig.WithContext(ctx),
|
||||
GameScore: q.GameScore.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error {
|
||||
return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...)
|
||||
}
|
||||
|
||||
func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx {
|
||||
tx := q.db.Begin(opts...)
|
||||
return &QueryTx{Query: q.clone(tx), Error: tx.Error}
|
||||
}
|
||||
|
||||
type QueryTx struct {
|
||||
*Query
|
||||
Error error
|
||||
}
|
||||
|
||||
func (q *QueryTx) Commit() error {
|
||||
return q.db.Commit().Error
|
||||
}
|
||||
|
||||
func (q *QueryTx) Rollback() error {
|
||||
return q.db.Rollback().Error
|
||||
}
|
||||
|
||||
func (q *QueryTx) SavePoint(name string) error {
|
||||
return q.db.SavePoint(name).Error
|
||||
}
|
||||
|
||||
func (q *QueryTx) RollbackTo(name string) error {
|
||||
return q.db.RollbackTo(name).Error
|
||||
}
|
121
gorm-gen/dao/query/gen_test.go
Normal file
121
gorm-gen/dao/query/gen_test.go
Normal file
@ -0,0 +1,121 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Input struct {
|
||||
Args []interface{}
|
||||
}
|
||||
|
||||
type Expectation struct {
|
||||
Ret []interface{}
|
||||
}
|
||||
|
||||
type TestCase struct {
|
||||
Input
|
||||
Expectation
|
||||
}
|
||||
|
||||
const _gen_test_db_name = "gen_test.db"
|
||||
|
||||
var _gen_test_db *gorm.DB
|
||||
var _gen_test_once sync.Once
|
||||
|
||||
func init() {
|
||||
InitializeDB()
|
||||
_gen_test_db.AutoMigrate(&_another{})
|
||||
}
|
||||
|
||||
func InitializeDB() {
|
||||
_gen_test_once.Do(func() {
|
||||
var err error
|
||||
_gen_test_db, err = gorm.Open(sqlite.Open(_gen_test_db_name), &gorm.Config{})
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("open sqlite %q fail: %w", _gen_test_db_name, err))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func assert(t *testing.T, methodName string, res, exp interface{}) {
|
||||
if !reflect.DeepEqual(res, exp) {
|
||||
t.Errorf("%v() gotResult = %v, want %v", methodName, res, exp)
|
||||
}
|
||||
}
|
||||
|
||||
type _another struct {
|
||||
ID uint64 `gorm:"primaryKey"`
|
||||
}
|
||||
|
||||
func (*_another) TableName() string { return "another_for_unit_test" }
|
||||
|
||||
func Test_Available(t *testing.T) {
|
||||
if !Use(_gen_test_db).Available() {
|
||||
t.Errorf("query.Available() == false")
|
||||
}
|
||||
}
|
||||
|
||||
func Test_WithContext(t *testing.T) {
|
||||
query := Use(_gen_test_db)
|
||||
if !query.Available() {
|
||||
t.Errorf("query Use(_gen_test_db) fail: query.Available() == false")
|
||||
}
|
||||
|
||||
type Content string
|
||||
var key, value Content = "gen_tag", "unit_test"
|
||||
qCtx := query.WithContext(context.WithValue(context.Background(), key, value))
|
||||
|
||||
for _, ctx := range []context.Context{
|
||||
qCtx.AppAccount.UnderlyingDB().Statement.Context,
|
||||
qCtx.AppUser.UnderlyingDB().Statement.Context,
|
||||
qCtx.DouyinEcpmConfig.UnderlyingDB().Statement.Context,
|
||||
qCtx.GameScore.UnderlyingDB().Statement.Context,
|
||||
} {
|
||||
if v := ctx.Value(key); v != value {
|
||||
t.Errorf("get value from context fail, expect %q, got %q", value, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Transaction(t *testing.T) {
|
||||
query := Use(_gen_test_db)
|
||||
if !query.Available() {
|
||||
t.Errorf("query Use(_gen_test_db) fail: query.Available() == false")
|
||||
}
|
||||
|
||||
err := query.Transaction(func(tx *Query) error { return nil })
|
||||
if err != nil {
|
||||
t.Errorf("query.Transaction execute fail: %s", err)
|
||||
}
|
||||
|
||||
tx := query.Begin()
|
||||
|
||||
err = tx.SavePoint("point")
|
||||
if err != nil {
|
||||
t.Errorf("query tx SavePoint fail: %s", err)
|
||||
}
|
||||
err = tx.RollbackTo("point")
|
||||
if err != nil {
|
||||
t.Errorf("query tx RollbackTo fail: %s", err)
|
||||
}
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
t.Errorf("query tx Commit fail: %s", err)
|
||||
}
|
||||
|
||||
err = query.Begin().Rollback()
|
||||
if err != nil {
|
||||
t.Errorf("query tx Rollback fail: %s", err)
|
||||
}
|
||||
}
|
17
gorm-gen/gen.yaml
Normal file
17
gorm-gen/gen.yaml
Normal file
@ -0,0 +1,17 @@
|
||||
version: "0.1"
|
||||
database:
|
||||
dsn : "root:youtu!0113@tcp(localhost:3306)/ecpm?charset=utf8&parseTime=True&loc=Local"
|
||||
db : "mysql"
|
||||
tables :
|
||||
- "app_account"
|
||||
- "app_user"
|
||||
- "douyin_ecpm_config"
|
||||
- "game_score"
|
||||
outPath : "./dao/query"
|
||||
outFile : ""
|
||||
withUnitTest : true
|
||||
modelPkgName : "model"
|
||||
fieldNullable : true
|
||||
fieldWithIndexTag : true
|
||||
fieldWithTypeTag : true
|
||||
fieldSignable : true
|
96
gorm-gen/gen_model.go
Normal file
96
gorm-gen/gen_model.go
Normal file
@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/model"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/dao/query"
|
||||
"gitea.youtukeji.com.cn/xiabin/youtu_server/gorm-gen/querier"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gorm"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AppAccountQuerier
|
||||
|
||||
var DefaultUsername = []string{
|
||||
"甜蜜糖果",
|
||||
"糖果爱好者",
|
||||
"软糖粉丝",
|
||||
"巧克力糖果控",
|
||||
"棒棒糖迷",
|
||||
"小熊软糖达人",
|
||||
"硬糖狂人",
|
||||
"焦糖糖果控",
|
||||
"水果糖行家",
|
||||
"棉花糖达人",
|
||||
}
|
||||
|
||||
// GetRandomUsername 随机获取一个糖果相关的用户名
|
||||
func GetRandomUsername() string {
|
||||
// 初始化随机数种子
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
// 生成一个 0 到列表长度减 1 之间的随机索引
|
||||
randomIndex := r.Intn(len(DefaultUsername))
|
||||
// 根据随机索引返回对应的用户名
|
||||
return DefaultUsername[randomIndex]
|
||||
}
|
||||
|
||||
func main() {
|
||||
g := gen.NewGenerator(gen.Config{
|
||||
OutPath: "./dao/query",
|
||||
Mode: gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
|
||||
})
|
||||
dsn := "root:youtu!0113@tcp(localhost: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.AppAccountQuerier) {}, model.AppAccount{})
|
||||
|
||||
g.ApplyInterface(func(querier.GameScoreQuerier) {}, model.GameScore{})
|
||||
|
||||
g.ApplyBasic(model.AppUser{}, model.DouyinEcpmConfig{})
|
||||
|
||||
// Generate the code
|
||||
g.Execute()
|
||||
|
||||
}
|
||||
|
||||
func DataGen(db *gorm.DB) {
|
||||
//生成20条用户及分数数据
|
||||
|
||||
u := query.Use(db).AppUser
|
||||
user, err := u.WithContext(context.Background()).Where(u.Openid.Like("test_openid%")).Find()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
//生成20条游戏得分数据
|
||||
var score []*model.GameScore
|
||||
for i := 0; i < 20; i++ {
|
||||
score = append(score, &model.GameScore{
|
||||
AppAccount: 3,
|
||||
AppUserID: user[i].ID,
|
||||
Score: uint32(Abs(rand.New(rand.NewSource(time.Now().UnixNano())).Intn(1000))),
|
||||
T: 1,
|
||||
})
|
||||
}
|
||||
|
||||
err = query.Use(db).GameScore.WithContext(context.Background()).CreateInBatches(score, len(score))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Abs(x int) int {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
54
gorm-gen/querier/querier.go
Normal file
54
gorm-gen/querier/querier.go
Normal file
@ -0,0 +1,54 @@
|
||||
package querier
|
||||
|
||||
import (
|
||||
"gorm.io/gen"
|
||||
)
|
||||
|
||||
type AppAccountQuerier interface {
|
||||
//GetAppConfig 获取所有小游戏配置
|
||||
//
|
||||
//select `app_id`,`secret`,`ecpm_value`,`ecpm_view`,`type` from `app_account` left join douyin_ecpm_config on app_account.id = douyin_ecpm_config.app_account_id
|
||||
GetAppConfig() ([]*gen.T, error)
|
||||
}
|
||||
|
||||
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:"-"` // 是否是自己
|
||||
}
|
73
gorm-gen/redis/cacher.go
Normal file
73
gorm-gen/redis/cacher.go
Normal file
@ -0,0 +1,73 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/go-gorm/caches/v4"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Cacher struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
func New(rdb *redis.Client) *Cacher {
|
||||
return &Cacher{rdb: rdb}
|
||||
}
|
||||
|
||||
func (c *Cacher) Get(ctx context.Context, key string, q *caches.Query[any]) (*caches.Query[any], error) {
|
||||
res, err := c.rdb.Get(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := q.Unmarshal([]byte(res)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return q, nil
|
||||
}
|
||||
|
||||
func (c *Cacher) Store(ctx context.Context, key string, val *caches.Query[any]) error {
|
||||
res, err := val.Marshal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.rdb.Set(ctx, key, res, 300*time.Second) // Set proper cache time
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Cacher) Invalidate(ctx context.Context) error {
|
||||
var (
|
||||
cursor uint64
|
||||
keys []string
|
||||
)
|
||||
for {
|
||||
var (
|
||||
k []string
|
||||
err error
|
||||
)
|
||||
k, cursor, err = c.rdb.Scan(ctx, cursor, fmt.Sprintf("%s*", caches.IdentifierPrefix), 0).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keys = append(keys, k...)
|
||||
if cursor == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(keys) > 0 {
|
||||
if _, err := c.rdb.Del(ctx, keys...).Result(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
149
sql/ecpm_backup.sql
Normal file
149
sql/ecpm_backup.sql
Normal file
File diff suppressed because one or more lines are too long
Loading…
x
Reference in New Issue
Block a user