Compare commits

...

10 Commits

Author SHA1 Message Date
Rogee
4bddcfef9c feat: update
Some checks failed
build quyun abc / Build (push) Failing after 1m13s
2025-05-28 19:47:42 +08:00
Rogee
1a9dd1d30d feat: update 2025-05-28 19:40:50 +08:00
Rogee
fa87d18276 feat: update 2025-05-28 19:38:47 +08:00
Rogee
0a8f6f9a1b feat: update slice expr 2025-05-26 14:31:41 +08:00
Rogee
d634e0175b feat: fix issues 2025-05-26 12:25:55 +08:00
Rogee
51ed5685dc feat: update toolchain 2025-05-26 10:53:26 +08:00
Rogee
f28bc7226f feat: update func 2025-05-23 23:50:26 +08:00
Rogee
1166a5c949 feat: update 2025-05-23 23:42:27 +08:00
Rogee
409a2e8304 feat: update 2025-05-23 21:43:49 +08:00
Rogee
f13ef4388e feat: update 2025-05-23 21:39:01 +08:00
41 changed files with 1213 additions and 879 deletions

View File

@@ -19,8 +19,7 @@ type medias struct {
// @Bind pagination query
// @Bind query query
func (ctl *medias) List(ctx fiber.Ctx, pagination *requests.Pagination, query *ListQuery) (*requests.Pager, error) {
cond := model.MediasModel.BuildConditionWithKey(query.Keyword)
return model.MediasModel.List(ctx.Context(), pagination, cond)
return model.MediasModel().List(ctx.Context(), pagination, model.MediasModel().Like(query.Keyword))
}
// Show media
@@ -28,7 +27,7 @@ func (ctl *medias) List(ctx fiber.Ctx, pagination *requests.Pagination, query *L
// @Router /admin/medias/:id [get]
// @Bind id path
func (ctl *medias) Show(ctx fiber.Ctx, id int64) error {
media, err := model.MediasModel.GetByID(ctx.Context(), id)
media, err := model.MediasModel().GetByID(ctx.Context(), id)
if err != nil {
return ctx.SendString("Media not found")
}
@@ -46,7 +45,7 @@ func (ctl *medias) Show(ctx fiber.Ctx, id int64) error {
// @Router /admin/medias/:id [delete]
// @Bind id path
func (ctl *medias) Delete(ctx fiber.Ctx, id int64) error {
media, err := model.MediasModel.GetByID(ctx.Context(), id)
media, err := model.MediasModel().GetByID(ctx.Context(), id)
if err != nil {
return ctx.SendString("Media not found")
}
@@ -55,7 +54,7 @@ func (ctl *medias) Delete(ctx fiber.Ctx, id int64) error {
return err
}
if err := model.MediasModel.Delete(ctx.Context(), id); err != nil {
if err := media.Delete(ctx.Context()); err != nil {
return err
}
return ctx.SendStatus(fiber.StatusNoContent)

View File

@@ -28,25 +28,25 @@ type orders struct {
// @Bind pagination query
// @Bind query query
func (ctl *orders) List(ctx fiber.Ctx, pagination *requests.Pagination, query *OrderListQuery) (*requests.Pager, error) {
cond := model.OrdersModel.BuildConditionWithKey(query.OrderNumber, query.UserID)
return model.OrdersModel.List(ctx.Context(), pagination, cond)
cond := model.OrdersModel().BuildConditionWithKey(query.OrderNumber, query.UserID)
return model.OrdersModel().List(ctx.Context(), pagination, cond)
}
// Refund
// @Router /admin/orders/:id/refund [post]
// @Bind id path
func (ctl *orders) Refund(ctx fiber.Ctx, id int64) error {
order, err := model.OrdersModel.GetByID(ctx.Context(), id)
order, err := model.OrdersModel().GetByID(ctx.Context(), id)
if err != nil {
return err
}
user, err := model.UsersModel.GetByID(ctx.Context(), order.UserID)
user, err := model.UsersModel().GetByID(ctx.Context(), order.UserID)
if err != nil {
return err
}
post, err := model.PostsModel.GetByID(ctx.Context(), order.PostID)
post, err := model.PostsModel().GetByID(ctx.Context(), order.PostID)
if err != nil {
return err
}
@@ -61,7 +61,7 @@ func (ctl *orders) Refund(ctx fiber.Ctx, id int64) error {
}
order.Status = fields.OrderStatusRefundSuccess
if err := model.OrdersModel.Update(ctx.Context(), order); err != nil {
if err := order.Update(ctx.Context()); err != nil {
return errors.Wrap(err, "update order failed")
}
@@ -87,7 +87,7 @@ func (ctl *orders) Refund(ctx fiber.Ctx, id int64) error {
order.RefundTransactionID = resp.RefundId
order.Status = fields.OrderStatusRefundProcessing
if err := model.OrdersModel.Update(ctx.Context(), order); err != nil {
if err := order.Update(ctx.Context()); err != nil {
return err
}

View File

@@ -3,7 +3,6 @@ package admin
import (
"quyun/app/model"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/fields"
"github.com/gofiber/fiber/v3"
@@ -23,12 +22,12 @@ type posts struct{}
// @Bind pagination query
// @Bind query query
func (ctl *posts) List(ctx fiber.Ctx, pagination *requests.Pagination, query *ListQuery) (*requests.Pager, error) {
conds := []conds.Cond{
conds := []model.Cond{
// conds.Post_NotDeleted(),
// conds.Post_Status(fields.PostStatusPublished),
conds.Post_Like(query.Keyword),
model.PostsModel().CondLike(query.Keyword),
}
pager, err := model.PostsModel.List(ctx.Context(), pagination, conds...)
pager, err := model.PostsModel().List(ctx.Context(), pagination, conds...)
if err != nil {
return nil, err
}
@@ -37,7 +36,7 @@ func (ctl *posts) List(ctx fiber.Ctx, pagination *requests.Pagination, query *Li
return item.ID
})
if len(postIds) > 0 {
postCntMap, err := model.PostsModel.BoughtStatistics(ctx.Context(), postIds)
postCntMap, err := model.PostsModel().BoughtStatistics(ctx.Context(), postIds)
if err != nil {
return pager, err
}
@@ -85,7 +84,7 @@ func (ctl *posts) Create(ctx fiber.Ctx, form *PostForm) error {
}
if form.Medias != nil {
medias, err := model.MediasModel.GetByIds(ctx.Context(), form.Medias)
medias, err := model.MediasModel().GetByIds(ctx.Context(), form.Medias)
if err != nil {
return err
}
@@ -111,7 +110,7 @@ func (ctl *posts) Create(ctx fiber.Ctx, form *PostForm) error {
// @Bind id path
// @Bind form body
func (ctl *posts) Update(ctx fiber.Ctx, id int64, form *PostForm) error {
post, err := model.PostsModel.GetByID(ctx.Context(), id)
post, err := model.PostsModel().GetByID(ctx.Context(), id)
if err != nil {
return err
}
@@ -125,7 +124,7 @@ func (ctl *posts) Update(ctx fiber.Ctx, id int64, form *PostForm) error {
post.Tags = fields.Json[[]string]{}
if form.Medias != nil {
medias, err := model.MediasModel.GetByIds(ctx.Context(), form.Medias)
medias, err := model.MediasModel().GetByIds(ctx.Context(), form.Medias)
if err != nil {
return err
}
@@ -150,7 +149,7 @@ func (ctl *posts) Update(ctx fiber.Ctx, id int64, form *PostForm) error {
// @Router /admin/posts/:id [delete]
// @Bind id path
func (ctl *posts) Delete(ctx fiber.Ctx, id int64) error {
post, err := model.PostsModel.GetByID(ctx.Context(), id)
post, err := model.PostsModel().GetByID(ctx.Context(), id)
if err != nil {
return err
}
@@ -158,7 +157,7 @@ func (ctl *posts) Delete(ctx fiber.Ctx, id int64) error {
return fiber.ErrNotFound
}
if err := post.Delete(ctx.Context()); err != nil {
if err := post.ForceDelete(ctx.Context()); err != nil {
return err
}
return nil
@@ -175,12 +174,12 @@ type PostItem struct {
// @Router /admin/posts/:id [get]
// @Bind id path
func (ctl *posts) Show(ctx fiber.Ctx, id int64) (*PostItem, error) {
post, err := model.PostsModel.GetByID(ctx.Context(), id)
post, err := model.PostsModel().GetByID(ctx.Context(), id)
if err != nil {
return nil, err
}
medias, err := model.MediasModel.GetByIds(ctx.Context(), lo.Map(post.Assets.Data, func(asset fields.MediaAsset, _ int) int64 {
medias, err := model.MediasModel().GetByIds(ctx.Context(), lo.Map(post.Assets.Data, func(asset fields.MediaAsset, _ int) int64 {
return asset.Media
}))
if err != nil {
@@ -198,12 +197,12 @@ func (ctl *posts) Show(ctx fiber.Ctx, id int64) (*PostItem, error) {
// @Bind id path
// @Bind userId path
func (ctl *posts) SendTo(ctx fiber.Ctx, id, userId int64) error {
post, err := model.PostsModel.GetByID(ctx.Context(), id)
post, err := model.PostsModel().GetByID(ctx.Context(), id)
if err != nil {
return err
}
user, err := model.UsersModel.GetByID(ctx.Context(), userId)
user, err := model.UsersModel().GetByID(ctx.Context(), userId)
if err != nil {
return err
}

View File

@@ -29,31 +29,31 @@ func (s *statistics) statistics(ctx fiber.Ctx) (*StatisticsResponse, error) {
var err error
statistics.PostDraft, err = model.PostsModel.Count(ctx.Context(), table.Posts.Status.EQ(Int(int64(fields.PostStatusDraft))))
statistics.PostDraft, err = model.PostsModel().Count(ctx.Context(), model.ExprCond(table.Posts.Status.EQ(Int(int64(fields.PostStatusDraft)))))
if err != nil {
return nil, err
}
statistics.PostPublished, err = model.PostsModel.Count(ctx.Context(), table.Posts.Status.EQ(Int(int64(fields.PostStatusPublished))))
statistics.PostPublished, err = model.PostsModel().Count(ctx.Context(), model.ExprCond(table.Posts.Status.EQ(Int(int64(fields.PostStatusPublished)))))
if err != nil {
return nil, err
}
statistics.Media, err = model.MediasModel.Count(ctx.Context())
statistics.Media, err = model.MediasModel().Count(ctx.Context())
if err != nil {
return nil, err
}
statistics.Order, err = model.OrdersModel.Count(ctx.Context(), table.Orders.Status.EQ(Int(int64(fields.OrderStatusCompleted))))
statistics.Order, err = model.OrdersModel().Count(ctx.Context(), model.ExprCond(table.Orders.Status.EQ(Int(int64(fields.OrderStatusCompleted)))))
if err != nil {
return nil, err
}
statistics.User, err = model.UsersModel.Count(ctx.Context(), BoolExp(Bool(true)))
statistics.User, err = model.UsersModel().Count(ctx.Context())
if err != nil {
return nil, err
}
statistics.Amount, err = model.OrdersModel.SumAmount(ctx.Context())
statistics.Amount, err = model.OrdersModel().SumAmount(ctx.Context())
if err != nil {
return nil, err
}

View File

@@ -38,7 +38,7 @@ type PreCheckResp struct {
// @Bind ext path
// @Bind mime query
func (up *uploads) PreUploadCheck(ctx fiber.Ctx, md5, ext, mime string) (*PreCheckResp, error) {
_, err := model.MediasModel.GetByHash(ctx.Context(), md5)
_, err := model.MediasModel().GetByHash(ctx.Context(), md5)
if err != nil && errors.Is(err, qrm.ErrNoRows) {
preSign, err := up.oss.PreSignUpload(ctx.Context(), fmt.Sprintf("%s.%s", md5, ext), mime)
if err != nil {
@@ -63,7 +63,7 @@ type PostUploadedForm struct {
// @Router /admin/uploads/post-uploaded-action [post]
// @Bind body body
func (up *uploads) PostUploadedAction(ctx fiber.Ctx, body *PostUploadedForm) error {
m, err := model.MediasModel.GetByHash(ctx.Context(), body.Md5)
m, err := model.MediasModel().GetByHash(ctx.Context(), body.Md5)
if err != nil && !errors.Is(err, qrm.ErrNoRows) {
return err
}
@@ -75,7 +75,7 @@ func (up *uploads) PostUploadedAction(ctx fiber.Ctx, body *PostUploadedForm) err
Hash: body.Md5,
Path: filepath.Join(UPLOAD_PATH, body.Md5+filepath.Ext(body.OriginalName)),
}
if err := model.MediasModel.Create(ctx.Context(), m); err != nil {
if err := m.Create(ctx.Context()); err != nil {
return err
}

View File

@@ -20,8 +20,8 @@ type users struct{}
// @Bind pagination query
// @Bind query query
func (ctl *users) List(ctx fiber.Ctx, pagination *requests.Pagination, query *UserListQuery) (*requests.Pager, error) {
cond := model.UsersModel.BuildConditionWithKey(query.Keyword)
return model.UsersModel.List(ctx.Context(), pagination, cond)
cond := model.UsersModel().BuildConditionWithKey(query.Keyword)
return model.UsersModel().List(ctx.Context(), pagination, cond)
}
// Show user
@@ -29,7 +29,7 @@ func (ctl *users) List(ctx fiber.Ctx, pagination *requests.Pagination, query *Us
// @Router /admin/users/:id [get]
// @Bind id path
func (ctl *users) Show(ctx fiber.Ctx, id int64) (*model.Users, error) {
return model.UsersModel.GetByID(ctx.Context(), id)
return model.UsersModel().GetByID(ctx.Context(), id)
}
// Articles show user bought articles
@@ -38,7 +38,7 @@ func (ctl *users) Show(ctx fiber.Ctx, id int64) (*model.Users, error) {
// @Bind id path
// @Bind pagination query
func (ctl *users) Articles(ctx fiber.Ctx, id int64, pagination *requests.Pagination) (*requests.Pager, error) {
return model.PostsModel.Bought(ctx.Context(), id, pagination)
return model.PostsModel().Bought(ctx.Context(), id, pagination)
}
type UserBalance struct {
@@ -51,7 +51,7 @@ type UserBalance struct {
// @Bind id path
// @Bind balance body
func (ctl *users) Balance(ctx fiber.Ctx, id int64, balance *UserBalance) error {
user, err := model.UsersModel.GetByID(ctx.Context(), id)
user, err := model.UsersModel().GetByID(ctx.Context(), id)
if err != nil {
return err
}

View File

@@ -89,7 +89,7 @@ func (ctl *auth) Login(ctx fiber.Ctx, code, state, redirect string) error {
Scope: token.Scope,
}),
}
user, err := model.UsersModel.GetUserByOpenIDOrCreate(ctx.Context(), token.GetOpenID(), userModel)
user, err := model.UsersModel().GetUserByOpenIDOrCreate(ctx.Context(), token.GetOpenID(), userModel)
if err != nil {
return errors.Wrap(err, "failed to get user by openid")
}

View File

@@ -8,7 +8,6 @@ import (
"quyun/app/jobs"
"quyun/app/model"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/fields"
"quyun/providers/ali"
"quyun/providers/job"
@@ -39,13 +38,13 @@ type posts struct {
// @Bind query query
// @Bind user local
func (ctl *posts) List(ctx fiber.Ctx, pagination *requests.Pagination, query *ListQuery, user *model.Users) (*requests.Pager, error) {
conds := []conds.Cond{
conds.Post_NotDeleted(),
conds.Post_Status(fields.PostStatusPublished),
conds.Post_Like(query.Keyword),
conds := []model.Cond{
model.PostsModel().CondNotDeleted(),
model.PostsModel().CondStatus(fields.PostStatusPublished),
model.PostsModel().CondLike(query.Keyword),
}
pager, err := model.PostsModel.List(ctx.Context(), pagination, conds...)
pager, err := model.PostsModel().List(ctx.Context(), pagination, conds...)
if err != nil {
log.WithError(err).Errorf("post list err: %v", err)
return nil, err
@@ -59,7 +58,7 @@ func (ctl *posts) List(ctx fiber.Ctx, pagination *requests.Pagination, query *Li
}
items := lo.FilterMap(pager.Items.([]model.Posts), func(item model.Posts, _ int) (PostItem, bool) {
medias, err := model.PostsModel.GetMediaByIds(ctx.Context(), item.HeadImages.Data)
medias, err := model.PostsModel().GetMediaByIds(ctx.Context(), item.HeadImages.Data)
if err != nil {
log.Errorf("GetMediaByIds err: %v", err)
return PostItem{}, false
@@ -118,7 +117,7 @@ type PostItem struct {
func (ctl *posts) Show(ctx fiber.Ctx, id int64, user *model.Users) (*PostItem, error) {
log.Infof("Fetching post with ID: %d", id)
post, err := model.PostsModel.GetByID(ctx.Context(), id, conds.Post_NotDeleted(), conds.Post_Status(fields.PostStatusPublished))
post, err := model.PostsModel().GetByID(ctx.Context(), id, model.PostsModel().CondNotDeleted(), model.PostsModel().CondStatus(fields.PostStatusPublished))
if err != nil {
log.WithError(err).Errorf("GetByID err: %v", err)
return nil, err
@@ -129,7 +128,7 @@ func (ctl *posts) Show(ctx fiber.Ctx, id int64, user *model.Users) (*PostItem, e
return nil, err
}
medias, err := model.PostsModel.GetMediaByIds(ctx.Context(), post.HeadImages.Data)
medias, err := model.PostsModel().GetMediaByIds(ctx.Context(), post.HeadImages.Data)
if err != nil {
return nil, err
}
@@ -179,7 +178,7 @@ func (ctl *posts) Play(ctx fiber.Ctx, id int64, user *model.Users) (*PlayUrl, er
}
log.Infof("Fetching play URL for post ID: %d", id)
post, err := model.PostsModel.GetByID(ctx.Context(), id)
post, err := model.PostsModel().GetByID(ctx.Context(), id)
if err != nil {
log.WithError(err).Errorf("GetByID err: %v", err)
return nil, err
@@ -188,7 +187,7 @@ func (ctl *posts) Play(ctx fiber.Ctx, id int64, user *model.Users) (*PlayUrl, er
for _, asset := range post.Assets.Data {
if asset.Type == "video/mp4" && asset.Metas != nil && asset.Metas.Short == preview {
media, err := model.MediasModel.GetByID(ctx.Context(), asset.Media)
media, err := model.MediasModel().GetByID(ctx.Context(), asset.Media)
if err != nil {
log.WithError(err).Errorf("medias GetByID err: %v", err)
return nil, err
@@ -217,12 +216,13 @@ func (ctl *posts) Play(ctx fiber.Ctx, id int64, user *model.Users) (*PlayUrl, er
func (ctl *posts) Mine(ctx fiber.Ctx, pagination *requests.Pagination, query *ListQuery, user *model.Users) (*requests.Pager, error) {
log.Infof("Fetching posts for user with pagination: %+v and keyword: %v", pagination, query.Keyword)
conds := []conds.Cond{
conds.Post_NotDeleted(),
conds.Post_Status(fields.PostStatusPublished),
conds.Post_Like(query.Keyword),
conds := []model.Cond{
model.PostsModel().CondNotDeleted(),
model.PostsModel().CondStatus(fields.PostStatusPublished),
model.PostsModel().CondLike(query.Keyword),
}
pager, err := model.UsersModel.PostList(ctx.Context(), user.ID, pagination, conds...)
pager, err := model.UsersModel().PostList(ctx.Context(), user.ID, pagination, conds...)
if err != nil {
log.WithError(err).Errorf("post list err: %v", err)
return nil, err
@@ -231,7 +231,7 @@ func (ctl *posts) Mine(ctx fiber.Ctx, pagination *requests.Pagination, query *Li
postIds := lo.Map(pager.Items.([]model.Posts), func(item model.Posts, _ int) int64 { return item.ID })
if len(postIds) > 0 {
items := lo.FilterMap(pager.Items.([]model.Posts), func(item model.Posts, _ int) (PostItem, bool) {
medias, err := model.PostsModel.GetMediaByIds(ctx.Context(), item.HeadImages.Data)
medias, err := model.PostsModel().GetMediaByIds(ctx.Context(), item.HeadImages.Data)
if err != nil {
log.Errorf("GetMediaByIds err: %v", err)
return PostItem{}, false
@@ -279,20 +279,20 @@ func (ctl *posts) Buy(ctx fiber.Ctx, id int64, user *model.Users) (*wechat.JSAPI
return nil, errors.New("已经购买过了")
}
post, err := model.PostsModel.GetByID(ctx.Context(), id)
post, err := model.PostsModel().GetByID(ctx.Context(), id)
if err != nil {
return nil, errors.Wrapf(err, " failed to get post: %d", id)
}
payPrice := post.Price * int64(post.Discount) / 100
// payPrice := post.PayPrice()
order, err := model.OrdersModel.Create(ctx.Context(), user.ID, post.ID)
order, err := model.OrdersModel().CreateFromUserPostID(ctx.Context(), user.ID, post.ID)
if err != nil {
return nil, errors.Wrap(err, "订单创建失败")
}
if user.Balance >= payPrice {
if err := model.OrdersModel.SetMeta(ctx.Context(), order.ID, func(om fields.OrderMeta) fields.OrderMeta {
om.CostBalance = payPrice
if user.Balance >= post.PayPrice() {
if err := order.SetMeta(ctx.Context(), func(om fields.OrderMeta) fields.OrderMeta {
om.CostBalance = post.PayPrice()
return om
}); err != nil {
return nil, errors.Wrap(err, "订单创建失败")
@@ -308,8 +308,8 @@ func (ctl *posts) Buy(ctx fiber.Ctx, id int64, user *model.Users) (*wechat.JSAPI
}, nil
}
payPrice = payPrice - user.Balance
if err := model.OrdersModel.SetMeta(ctx.Context(), order.ID, func(om fields.OrderMeta) fields.OrderMeta {
payPrice := post.PayPrice() - user.Balance
if err := order.SetMeta(ctx.Context(), func(om fields.OrderMeta) fields.OrderMeta {
om.CostBalance = user.Balance
return om
}); err != nil {

View File

@@ -45,7 +45,7 @@ func (w *BalancePayNotifyWorker) Work(ctx context.Context, job *Job[BalancePayNo
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
order, err := model.OrdersModel.GetByOrderNo(context.Background(), job.Args.OrderNo)
order, err := model.OrdersModel().GetByOrderNo(context.Background(), job.Args.OrderNo)
if err != nil {
log.Errorf("GetByOrderNo error:%v", err)
return err
@@ -56,7 +56,7 @@ func (w *BalancePayNotifyWorker) Work(ctx context.Context, job *Job[BalancePayNo
return JobCancel(fmt.Errorf("Order already paid, currently status: %d", order.Status))
}
user, err := model.UsersModel.GetByID(context.Background(), order.UserID)
user, err := model.UsersModel().GetByID(context.Background(), order.UserID)
if err != nil {
log.Errorf("GetByID error:%v", err)
return errors.Wrap(err, "get user error")
@@ -93,7 +93,7 @@ func (w *BalancePayNotifyWorker) Work(ctx context.Context, job *Job[BalancePayNo
return errors.Wrap(err, "BuyPosts error")
}
if err := model.OrdersModel.Update(context.Background(), order); err != nil {
if err := order.Update(context.Background()); err != nil {
log.Errorf("Update order error:%v", err)
return errors.Wrap(err, "Update order error")
}

View File

@@ -55,7 +55,7 @@ func (w *DownloadFromAliOSSWorker) Work(ctx context.Context, job *Job[DownloadFr
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
media, err := model.MediasModel.GetByHash(ctx, job.Args.MediaHash)
media, err := model.MediasModel().GetByHash(ctx, job.Args.MediaHash)
if err != nil {
log.Errorf("Error getting media by ID: %v", err)
return JobCancel(err)

View File

@@ -56,13 +56,13 @@ func (w *PublishDraftPostsWorker) Work(ctx context.Context, job *Job[PublishDraf
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
media, err := model.MediasModel.GetByHash(ctx, job.Args.MediaHash)
media, err := model.MediasModel().GetByHash(ctx, job.Args.MediaHash)
if err != nil {
log.Errorf("Error getting media by ID: %v", err)
return JobCancel(err)
}
relationMedias, err := model.MediasModel.GetRelations(ctx, media.Hash)
relationMedias, err := model.MediasModel().GetRelations(ctx, media.Hash)
if err != nil {
log.Errorf("Error getting relation medias: %v", err)
return JobCancel(err)

View File

@@ -54,7 +54,7 @@ func (w *VideoCutWorker) Work(ctx context.Context, job *Job[VideoCut]) error {
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
media, err := model.MediasModel.GetByHash(ctx, job.Args.MediaHash)
media, err := model.MediasModel().GetByHash(ctx, job.Args.MediaHash)
if err != nil {
log.Errorf("Error getting media by ID: %v", err)
return JobCancel(err)
@@ -81,7 +81,7 @@ func (w *VideoCutWorker) Work(ctx context.Context, job *Job[VideoCut]) error {
Short: false,
Duration: duration,
}
if err := model.MediasModel.UpdateMetas(ctx, media.ID, metas); err != nil {
if err := model.MediasModel().UpdateMetas(ctx, media.ID, metas); err != nil {
log.Errorf("Error updating media metas: %v", err)
return errors.Wrap(err, "update media metas")
}

View File

@@ -57,7 +57,7 @@ func (w *VideoExtractHeadImageWorker) Work(ctx context.Context, job *Job[VideoEx
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
media, err := model.MediasModel.GetByHash(ctx, job.Args.MediaHash)
media, err := model.MediasModel().GetByHash(ctx, job.Args.MediaHash)
if err != nil {
log.Errorf("Error getting media by ID: %v", err)
return JobCancel(err)
@@ -89,7 +89,6 @@ func (w *VideoExtractHeadImageWorker) Work(ctx context.Context, job *Job[VideoEx
// create a new media record for the image
imageMedia := &model.Medias{
CreatedAt: time.Now(),
Name: name,
MimeType: "image/jpeg",
Size: fileSize,
@@ -110,7 +109,7 @@ func (w *VideoExtractHeadImageWorker) Work(ctx context.Context, job *Job[VideoEx
log.Errorf("Error removing original file: %v", err)
}
if err := model.MediasModel.Create(ctx, imageMedia); err != nil {
if err := imageMedia.Create(ctx); err != nil {
log.Errorf("Error creating media record: %v", err)
return errors.Wrap(err, "failed to create media record")
}

View File

@@ -57,7 +57,7 @@ func (w *VideoStoreShortWorker) Work(ctx context.Context, job *Job[VideoStoreSho
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
media, err := model.MediasModel.GetByHash(ctx, job.Args.MediaHash)
media, err := model.MediasModel().GetByHash(ctx, job.Args.MediaHash)
if err != nil {
log.Errorf("Error getting media by ID: %v", err)
return JobCancel(err)
@@ -91,8 +91,7 @@ func (w *VideoStoreShortWorker) Work(ctx context.Context, job *Job[VideoStoreSho
// save to db and relate to master
mediaModel := &model.Medias{
CreatedAt: time.Now(),
Name: "[试听]" + media.Name,
Name: "[试听] " + media.Name,
MimeType: media.MimeType,
Size: fileSize,
Path: filePath,
@@ -112,7 +111,7 @@ func (w *VideoStoreShortWorker) Work(ctx context.Context, job *Job[VideoStoreSho
}
log.Infof("pending create media record %s", job.Args.FilePath)
if err := model.MediasModel.Create(ctx, mediaModel); err != nil {
if err := mediaModel.Create(ctx); err != nil {
log.Errorf("Error saving media record: %v data: %+v", err, mediaModel)
return err
}

View File

@@ -53,7 +53,7 @@ func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNoti
return JobCancel(errors.New("TradeState is not SUCCESS"))
}
order, err := model.OrdersModel.GetByOrderNo(context.Background(), notify.OutTradeNo)
order, err := model.OrdersModel().GetByOrderNo(context.Background(), notify.OutTradeNo)
if err != nil {
log.Errorf("GetByOrderNo error:%v", err)
return err
@@ -64,7 +64,7 @@ func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNoti
return JobCancel(fmt.Errorf("Order already paid, currently status: %d", order.Status))
}
user, err := model.UsersModel.GetByID(context.Background(), order.UserID)
user, err := model.UsersModel().GetByID(context.Background(), order.UserID)
if err != nil {
return errors.Wrapf(err, "get user by id(%d) failed", order.UserID)
}
@@ -103,7 +103,7 @@ func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNoti
return errors.Wrap(err, "BuyPosts error")
}
if err := model.OrdersModel.Update(context.Background(), order); err != nil {
if err := order.Update(context.Background()); err != nil {
log.Errorf("Update order error:%v", err)
return errors.Wrap(err, "Update order error")
}

View File

@@ -47,13 +47,13 @@ func (w *WechatRefundNotifyWorker) Work(ctx context.Context, job *Job[WechatRefu
notify := job.Args.Notify
order, err := model.OrdersModel.GetByOrderNo(context.Background(), notify.OutTradeNo)
order, err := model.OrdersModel().GetByOrderNo(context.Background(), notify.OutTradeNo)
if err != nil {
log.Errorf("GetByOrderNo error:%v", err)
return err
}
user, err := model.UsersModel.GetByID(context.Background(), order.UserID)
user, err := model.UsersModel().GetByID(context.Background(), order.UserID)
if err != nil {
log.Errorf("GetByID error:%v", err)
return err
@@ -88,7 +88,7 @@ func (w *WechatRefundNotifyWorker) Work(ctx context.Context, job *Job[WechatRefu
}
}
if err := model.OrdersModel.Update(context.Background(), order); err != nil {
if err := order.Update(context.Background()); err != nil {
log.Errorf("Update order error:%v", err)
return errors.Wrap(err, "Update order error")
}

View File

@@ -26,7 +26,7 @@ func (f *Middlewares) Auth(ctx fiber.Ctx) error {
}
if f.app.IsDevMode() && false {
user, err := model.UsersModel.GetByID(ctx.Context(), 1)
user, err := model.UsersModel().GetByID(ctx.Context(), 1)
if err != nil {
return ctx.Send([]byte("User not found"))
}
@@ -66,7 +66,7 @@ func (f *Middlewares) Auth(ctx fiber.Ctx) error {
return ctx.Redirect().To(fullUrl)
}
user, err := model.UsersModel.GetByID(ctx.Context(), jwt.UserID)
user, err := model.UsersModel().GetByID(ctx.Context(), jwt.UserID)
if err != nil {
// remove cookie
ctx.ClearCookie("token")

View File

@@ -0,0 +1,137 @@
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
package model
import (
"context"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"time"
)
// conds
func (m *Medias) CondID(id int64) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblMedias.ID.EQ(Int(id)))
}
}
// funcs
func (m *Medias) log() *log.Entry {
return log.WithField("model", "Medias")
}
func (m *Medias) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
stmt := tblMedias.INSERT(tblMedias.MutableColumns).MODEL(m).RETURNING(tblMedias.AllColumns)
m.log().WithField("func", "Create").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Medias item: %v", err)
return err
}
m.log().WithField("func", "Create").Infof("Medias item created successfully")
return nil
}
func (m *Medias) BatchCreate(ctx context.Context, models []*Medias) error {
stmt := tblMedias.INSERT(tblMedias.MutableColumns).MODELS(models)
m.log().WithField("func", "BatchCreate").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Medias item: %v", err)
return err
}
m.log().WithField("func", "BatchCreate").Infof("Medias items created successfully")
return nil
}
func (m *Medias) Delete(ctx context.Context) error {
stmt := tblMedias.DELETE().WHERE(tblMedias.ID.EQ(Int(m.ID)))
m.log().WithField("func", "Delete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Delete").Errorf("error deleting Medias item: %v", err)
return err
}
m.log().WithField("func", "Delete").Infof("Medias item deleted successfully")
return nil
}
// BatchDelete
func (m *Medias) BatchDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblMedias.DELETE().WHERE(tblMedias.ID.IN(condIds...))
m.log().WithField("func", "BatchDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "BatchDelete").Errorf("error deleting Medias items: %v", err)
return err
}
m.log().WithField("func", "BatchDelete").WithField("ids", ids).Infof("Medias items deleted successfully")
return nil
}
func (m *Medias) Update(ctx context.Context) error {
stmt := tblMedias.UPDATE(tblMediasUpdateMutableColumns).MODEL(m).WHERE(tblMedias.ID.EQ(Int(m.ID))).RETURNING(tblMedias.AllColumns)
m.log().WithField("func", "Update").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Update").Errorf("error updating Medias item: %v", err)
return err
}
m.log().WithField("func", "Update").Infof("Medias item updated successfully")
return nil
}
// GetByCond
func (m *Medias) GetByCond(ctx context.Context, conds ...Cond) (*Medias, error) {
cond := CondTrue(conds...)
stmt := tblMedias.SELECT(tblMedias.AllColumns).WHERE(cond)
m.log().WithField("func", "GetByCond").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "GetByCond").Errorf("error getting Medias item by ID: %v", err)
return nil, err
}
m.log().WithField("func", "GetByCond").Infof("Medias item retrieved successfully")
return m, nil
}
// GetByID
func (m *Medias) GetByID(ctx context.Context, id int64, conds ...Cond) (*Medias, error) {
return m.GetByCond(ctx, CondJoin(m.CondID(id), conds...)...)
}
// Count
func (m *Medias) Count(ctx context.Context, conds ...Cond) (int64, error) {
cond := CondTrue(conds...)
stmt := tblMedias.SELECT(COUNT(tblMedias.ID).AS("count")).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting Medias items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -2,26 +2,21 @@ package model
import (
"context"
"time"
"quyun/app/requests"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Medias) log() *log.Entry {
return log.WithField("model", "MediasModel")
}
func (m *Medias) BuildConditionWithKey(key *string) BoolExpression {
tbl := table.Medias
cond := Bool(true)
var tblMediasUpdateMutableColumns = tblMedias.MutableColumns.Except(
tblMedias.CreatedAt,
)
func (m *Medias) Like(key *string) Cond {
return func(cond BoolExpression) BoolExpression {
tbl := tblMedias
if key == nil || *key == "" {
return cond
}
@@ -31,34 +26,16 @@ func (m *Medias) BuildConditionWithKey(key *string) BoolExpression {
)
return cond
}
}
// countByCond
func (m *Medias) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Medias
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting media items: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
func (m *Medias) List(ctx context.Context, pagination *requests.Pagination, expr BoolExpression) (*requests.Pager, error) {
func (m *Medias) List(ctx context.Context, pagination *requests.Pagination, conds ...Cond) (*requests.Pager, error) {
pagination.Format()
tbl := table.Medias
tbl := tblMedias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(expr).
WHERE(CondTrue(conds...)).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
@@ -71,7 +48,7 @@ func (m *Medias) List(ctx context.Context, pagination *requests.Pagination, expr
return nil, err
}
count, err := m.countByCondition(ctx, expr)
count, err := m.Count(ctx, conds...)
if err != nil {
m.log().Errorf("error getting media count: %v", err)
return nil, err
@@ -84,47 +61,16 @@ func (m *Medias) List(ctx context.Context, pagination *requests.Pagination, expr
}, nil
}
func (m *Medias) BatchCreate(ctx context.Context, models []*Medias) error {
stmt := table.Medias.INSERT(table.Medias.MutableColumns).MODELS(models)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error creating media item: %v", err)
return err
}
m.log().Infof("media item created successfully")
return nil
}
func (m *Medias) Create(ctx context.Context, medias *Medias) error {
medias.CreatedAt = time.Now()
stmt := table.Medias.INSERT(table.Medias.MutableColumns).MODEL(medias).RETURNING(table.Medias.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, medias); err != nil {
m.log().Errorf("error creating media item: %v", err)
return err
}
m.log().Infof("media item created successfully")
return nil
}
// GetByIds
func (m *Medias) GetByIds(ctx context.Context, ids []int64) ([]*Medias, error) {
if len(ids) == 0 {
return nil, nil
}
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
tbl := table.Medias
tbl := tblMedias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(tbl.ID.IN(condIds...))
WHERE(tbl.ID.IN(IntExprSlice(ids)...))
m.log().Infof("sql: %s", stmt.DebugSql())
var medias []Medias
@@ -141,10 +87,9 @@ func (m *Medias) GetByIds(ctx context.Context, ids []int64) ([]*Medias, error) {
// GetByHash
func (m *Medias) GetByHash(ctx context.Context, hash string) (*Medias, error) {
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(tbl.Hash.EQ(String(hash)))
stmt := tblMedias.
SELECT(tblMedias.AllColumns).
WHERE(tblMedias.Hash.EQ(String(hash)))
m.log().Infof("sql: %s", stmt.DebugSql())
var media Medias
@@ -157,68 +102,14 @@ func (m *Medias) GetByHash(ctx context.Context, hash string) (*Medias, error) {
return &media, nil
}
// Update
func (m *Medias) Update(ctx context.Context, hash string, model *Medias) error {
tbl := table.Medias
stmt := tbl.
UPDATE(tbl.MutableColumns.Except(tbl.CreatedAt)).
MODEL(model).
WHERE(table.Medias.Hash.EQ(String(hash)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("hash", hash).Errorf("error updating media item: %v", err)
return err
}
m.log().Infof("media item updated successfully")
return nil
}
// GetByID
func (m *Medias) GetByID(ctx context.Context, id int64) (*Medias, error) {
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
var media Medias
if err := stmt.QueryContext(ctx, db, &media); err != nil {
m.log().Errorf("error querying media item by ID: %v", err)
return nil, err
}
return &media, nil
}
// Delete
func (m *Medias) Delete(ctx context.Context, id int64) error {
tbl := table.Medias
stmt := tbl.
DELETE().
WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting media item: %v", err)
return err
}
m.log().Infof("media item deleted successfully")
return nil
}
// UpdateMetas
func (m *Medias) UpdateMetas(ctx context.Context, id int64, metas fields.MediaMetas) error {
meta := fields.ToJson(metas)
tbl := table.Medias
stmt := tbl.
UPDATE(tbl.Metas).
stmt := tblMedias.
UPDATE(tblMedias.Metas).
SET(meta).
WHERE(tbl.ID.EQ(Int64(id)))
WHERE(tblMedias.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
@@ -232,9 +123,8 @@ func (m *Medias) UpdateMetas(ctx context.Context, id int64, metas fields.MediaMe
// GetRelationMedias
func (m *Medias) GetRelations(ctx context.Context, hash string) ([]*Medias, error) {
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
stmt := tblMedias.
SELECT(tblMedias.AllColumns).
WHERE(
RawBool("metas->>'parent_hash' = ?", RawArgs{"?": hash}),
)
@@ -250,21 +140,3 @@ func (m *Medias) GetRelations(ctx context.Context, hash string) ([]*Medias, erro
return &media
}), nil
}
// Count
func (m *Medias) Count(ctx context.Context) (int64, error) {
tbl := table.Medias
stmt := tbl.SELECT(COUNT(tbl.ID).AS("count"))
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting media items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -11,7 +11,6 @@ import (
"quyun/app/requests"
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
@@ -43,16 +42,16 @@ func Test_Medias(t *testing.T) {
func (s *MediasTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
database.Truncate(context.Background(), db, tblMedias.TableName())
})
}
func (s *MediasTestSuite) Test_countByCondition() {
Convey("countByCondition", s.T(), func() {
Convey("no cond", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
database.Truncate(context.Background(), db, tblMedias.TableName())
cnt, err := MediasModel.countByCondition(context.Background(), nil)
cnt, err := MediasModel().Count(context.Background())
Convey("should not return an error", func() {
So(err, ShouldBeNil)
})
@@ -68,7 +67,7 @@ func (s *MediasTestSuite) Test_countByCondition() {
func (s *MediasTestSuite) Test_BatchCreate() {
Convey("Create", s.T(), func() {
Convey("valid media", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
database.Truncate(context.Background(), db, tblMedias.TableName())
models := []*Medias{
{
@@ -110,7 +109,7 @@ func (s *MediasTestSuite) Test_BatchCreate() {
count := 10
for i := 0; i < count; i++ {
err := MediasModel.BatchCreate(context.Background(), models)
err := MediasModel().BatchCreate(context.Background(), models)
Convey("Create should not return an error: "+fmt.Sprintf("%d", i), func() {
So(err, ShouldBeNil)
})
@@ -122,7 +121,7 @@ func (s *MediasTestSuite) Test_BatchCreate() {
func (s *MediasTestSuite) Test_Create() {
Convey("Create", s.T(), func() {
Convey("valid media", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
database.Truncate(context.Background(), db, tblMedias.TableName())
model := &Medias{
Name: "test",
@@ -132,12 +131,12 @@ func (s *MediasTestSuite) Test_Create() {
Path: "path/to/media.pdf",
}
err := MediasModel.Create(context.Background(), model)
err := model.Create(context.Background())
Convey("Create should not return an error", func() {
So(err, ShouldBeNil)
})
cnt, err := MediasModel.countByCondition(context.Background(), nil)
cnt, err := MediasModel().Count(context.Background())
Convey("Count should not return an error", func() {
So(err, ShouldBeNil)
})
@@ -154,7 +153,7 @@ func (s *MediasTestSuite) Test_Create() {
func (s *MediasTestSuite) Test_Page() {
Convey("Create", s.T(), func() {
Convey("Insert Items", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
database.Truncate(context.Background(), db, tblMedias.TableName())
for i := 0; i < 20; i++ {
model := &Medias{
@@ -165,31 +164,31 @@ func (s *MediasTestSuite) Test_Page() {
Path: "path/to/media.pdf",
}
err := MediasModel.Create(context.Background(), model)
err := model.Create(context.Background())
So(err, ShouldBeNil)
}
cnt, err := MediasModel.countByCondition(context.Background(), nil)
cnt, err := MediasModel().Count(context.Background())
So(err, ShouldBeNil)
So(cnt, ShouldEqual, 20)
})
Convey("Page", func() {
Convey("page 1", func() {
pager, err := MediasModel.List(context.Background(), &requests.Pagination{Page: 1, Limit: 10}, nil)
pager, err := MediasModel().List(context.Background(), &requests.Pagination{Page: 1, Limit: 10}, nil)
So(err, ShouldBeNil)
So(pager.Total, ShouldEqual, 20)
So(pager.Items, ShouldHaveLength, 10)
})
Convey("page 2", func() {
pager, err := MediasModel.List(context.Background(), &requests.Pagination{Page: 2, Limit: 10}, nil)
pager, err := MediasModel().List(context.Background(), &requests.Pagination{Page: 2, Limit: 10}, nil)
So(err, ShouldBeNil)
So(pager.Total, ShouldEqual, 20)
So(pager.Items, ShouldHaveLength, 10)
})
Convey("page 3", func() {
pager, err := MediasModel.List(context.Background(), &requests.Pagination{Page: 3, Limit: 10}, nil)
pager, err := MediasModel().List(context.Background(), &requests.Pagination{Page: 3, Limit: 10}, nil)
So(err, ShouldBeNil)
So(pager.Total, ShouldEqual, 20)
So(pager.Items, ShouldBeEmpty)
@@ -208,7 +207,7 @@ func (s *MediasTestSuite) Test_CreateGetID() {
Path: "path/to/media.pdf",
}
err := MediasModel.Create(context.Background(), model)
err := model.Create(context.Background())
So(err, ShouldBeNil)
So(model.ID, ShouldNotBeEmpty)
@@ -219,7 +218,7 @@ func (s *MediasTestSuite) Test_CreateGetID() {
func (s *MediasTestSuite) Test_GetRelations() {
Convey("GetByHash", s.T(), func() {
hash := "ce4cd071128cef282cf315dda75bdab4"
media, err := MediasModel.GetRelations(context.Background(), hash)
media, err := MediasModel().GetRelations(context.Background(), hash)
So(err, ShouldBeNil)
So(media, ShouldNotBeNil)

View File

@@ -1,19 +0,0 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"time"
)
type Migrations struct {
ID int32 `sql:"primary_key" json:"id"`
VersionID int64 `json:"version_id"`
IsApplied bool `json:"is_applied"`
Tstamp time.Time `json:"tstamp"`
}

View File

@@ -0,0 +1,139 @@
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
package model
import (
"context"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"time"
)
// conds
func (m *Orders) CondID(id int64) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblOrders.ID.EQ(Int(id)))
}
}
// funcs
func (m *Orders) log() *log.Entry {
return log.WithField("model", "Orders")
}
func (m *Orders) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
stmt := tblOrders.INSERT(tblOrders.MutableColumns).MODEL(m).RETURNING(tblOrders.AllColumns)
m.log().WithField("func", "Create").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Orders item: %v", err)
return err
}
m.log().WithField("func", "Create").Infof("Orders item created successfully")
return nil
}
func (m *Orders) BatchCreate(ctx context.Context, models []*Orders) error {
stmt := tblOrders.INSERT(tblOrders.MutableColumns).MODELS(models)
m.log().WithField("func", "BatchCreate").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Orders item: %v", err)
return err
}
m.log().WithField("func", "BatchCreate").Infof("Orders items created successfully")
return nil
}
func (m *Orders) Delete(ctx context.Context) error {
stmt := tblOrders.DELETE().WHERE(tblOrders.ID.EQ(Int(m.ID)))
m.log().WithField("func", "Delete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Delete").Errorf("error deleting Orders item: %v", err)
return err
}
m.log().WithField("func", "Delete").Infof("Orders item deleted successfully")
return nil
}
// BatchDelete
func (m *Orders) BatchDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblOrders.DELETE().WHERE(tblOrders.ID.IN(condIds...))
m.log().WithField("func", "BatchDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "BatchDelete").Errorf("error deleting Orders items: %v", err)
return err
}
m.log().WithField("func", "BatchDelete").WithField("ids", ids).Infof("Orders items deleted successfully")
return nil
}
func (m *Orders) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
stmt := tblOrders.UPDATE(tblOrdersUpdateMutableColumns).MODEL(m).WHERE(tblOrders.ID.EQ(Int(m.ID))).RETURNING(tblOrders.AllColumns)
m.log().WithField("func", "Update").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Update").Errorf("error updating Orders item: %v", err)
return err
}
m.log().WithField("func", "Update").Infof("Orders item updated successfully")
return nil
}
// GetByCond
func (m *Orders) GetByCond(ctx context.Context, conds ...Cond) (*Orders, error) {
cond := CondTrue(conds...)
stmt := tblOrders.SELECT(tblOrders.AllColumns).WHERE(cond)
m.log().WithField("func", "GetByCond").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "GetByCond").Errorf("error getting Orders item by ID: %v", err)
return nil, err
}
m.log().WithField("func", "GetByCond").Infof("Orders item retrieved successfully")
return m, nil
}
// GetByID
func (m *Orders) GetByID(ctx context.Context, id int64, conds ...Cond) (*Orders, error) {
return m.GetByCond(ctx, CondJoin(m.CondID(id), conds...)...)
}
// Count
func (m *Orders) Count(ctx context.Context, conds ...Cond) (int64, error) {
cond := CondTrue(conds...)
stmt := tblOrders.SELECT(COUNT(tblOrders.ID).AS("count")).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting Orders items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -2,47 +2,28 @@ package model
import (
"context"
"fmt"
"time"
"quyun/app/requests"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/pkg/errors"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Orders) log() *log.Entry {
return log.WithField("model", "OrdersModel")
}
// GetByID returns an order by ID
func (m *Orders) GetByID(ctx context.Context, id int64) (*Orders, error) {
tbl := table.Orders
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var order Orders
err := stmt.QueryContext(ctx, db, &order)
if err != nil {
m.log().Errorf("error querying order by ID: %v", err)
return nil, err
}
return &order, nil
}
var tblOrdersUpdateMutableColumns = tblOrders.MutableColumns.Except(
tblOrders.OrderNo,
tblOrders.Price,
tblOrders.Discount,
tblOrders.SubOrderNo,
tblOrders.PostID,
tblOrders.UserID,
)
// BuildConditionWithKey builds the WHERE clause for order queries
func (m *Orders) BuildConditionWithKey(orderNumber *string, userID *int64) BoolExpression {
tbl := table.Orders
tbl := tblOrders
cond := Bool(true)
@@ -67,7 +48,7 @@ func (m *Orders) countByCondition(ctx context.Context, expr BoolExpression) (int
Cnt int64
}
tbl := table.Orders
tbl := tblOrders
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
@@ -81,10 +62,14 @@ func (m *Orders) countByCondition(ctx context.Context, expr BoolExpression) (int
}
// List returns a paginated list of orders
func (m *Orders) List(ctx context.Context, pagination *requests.Pagination, cond BoolExpression) (*requests.Pager, error) {
func (m *Orders) List(
ctx context.Context,
pagination *requests.Pagination,
cond BoolExpression,
) (*requests.Pager, error) {
pagination.Format()
tbl := table.Orders
tbl := tblOrders
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(cond).
@@ -99,15 +84,13 @@ func (m *Orders) List(ctx context.Context, pagination *requests.Pagination, cond
return nil, err
}
postsMap, err := PostsModel.GetPostsMapByIDs(ctx, lo.Map(orders, func(order Orders, _ int) int64 {
return order.PostID
}))
postsMap, err := PostsModel().GetPostsMapByIDs(ctx, lo.Map(orders, func(order Orders, _ int) int64 { return order.PostID }))
if err != nil {
m.log().Errorf("error getting posts map: %v", err)
return nil, err
}
userMap, err := UsersModel.GetUsersMapByIDs(ctx, lo.Map(orders, func(order Orders, _ int) int64 {
userMap, err := UsersModel().GetUsersMapByIDs(ctx, lo.Map(orders, func(order Orders, _ int) int64 {
return order.UserID
}))
if err != nil {
@@ -150,8 +133,8 @@ func (m *Orders) List(ctx context.Context, pagination *requests.Pagination, cond
}
// Create creates a new order
func (o *Orders) Create(ctx context.Context, userId, postId int64) (*Orders, error) {
post, err := PostsModel.GetByID(ctx, postId)
func (o *Orders) CreateFromUserPostID(ctx context.Context, userId, postId int64) (*Orders, error) {
post, err := PostsModel().GetByID(ctx, postId)
if err != nil {
return nil, errors.Wrap(err, "failed to get post")
}
@@ -160,7 +143,7 @@ func (o *Orders) Create(ctx context.Context, userId, postId int64) (*Orders, err
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
m.Status = fields.OrderStatusPending
m.OrderNo = fmt.Sprintf("%s", time.Now().Format("20060102150405"))
m.OrderNo = time.Now().Format("20060102150405")
m.SubOrderNo = m.OrderNo
m.UserID = userId
m.PostID = postId
@@ -168,80 +151,56 @@ func (o *Orders) Create(ctx context.Context, userId, postId int64) (*Orders, err
m.Price = post.Price
m.Discount = post.Discount
tbl := table.Orders
tbl := tblOrders
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(m).RETURNING(tbl.AllColumns)
o.log().Infof("sql: %s", stmt.DebugSql())
var order Orders
if err := stmt.QueryContext(ctx, db, &order); err != nil {
if err := stmt.QueryContext(ctx, db, o); err != nil {
o.log().Errorf("error creating order: %v", err)
return nil, err
}
return &order, nil
return o, nil
}
func (m *Orders) SetMeta(ctx context.Context, id int64, metaFunc func(fields.OrderMeta) fields.OrderMeta) error {
order, err := m.GetByID(ctx, id)
if err != nil {
return errors.Wrap(err, "failed to get order")
}
tbl := table.Orders
func (m *Orders) SetMeta(ctx context.Context, metaFunc func(fields.OrderMeta) fields.OrderMeta) error {
tbl := tblOrders
stmt := tbl.
UPDATE(tbl.Meta).
SET(fields.ToJson(metaFunc(order.Meta.Data))).
SET(fields.ToJson(metaFunc(m.Meta.Data))).
WHERE(
tbl.ID.EQ(Int64(id)),
)
tbl.ID.EQ(Int64(m.ID)),
).
RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().Errorf("error set order meta: %v", err)
return err
}
return nil
}
// DeleteByID soft deletes an order by ID
func (m *Orders) SetStatus(ctx context.Context, orderNo string, status fields.OrderStatus) error {
tbl := table.Orders
func (m *Orders) SetStatus(ctx context.Context, status fields.OrderStatus) error {
tbl := tblOrders
stmt := tbl.
UPDATE(tbl.Status).
SET(status).
WHERE(
tbl.OrderNo.EQ(String(orderNo)),
)
tbl.ID.EQ(Int64(m.ID)),
).
RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().Errorf("error set order status: %v", err)
return err
}
return nil
}
// Count
func (m *Orders) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Orders
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var cnt struct {
Cnt int64
}
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting orders: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// SumAmount
func (m *Orders) SumAmount(ctx context.Context) (int64, error) {
tbl := table.Orders
tbl := tblOrders
stmt := SELECT(SUM(tbl.Price).AS("cnt")).FROM(tbl).WHERE(
tbl.Status.EQ(Int(int64(fields.OrderStatusCompleted))),
)
@@ -262,7 +221,7 @@ func (m *Orders) SumAmount(ctx context.Context) (int64, error) {
// GetByOrderNo
func (m *Orders) GetByOrderNo(ctx context.Context, orderNo string) (*Orders, error) {
tbl := table.Orders
tbl := tblOrders
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
@@ -280,14 +239,14 @@ func (m *Orders) GetByOrderNo(ctx context.Context, orderNo string) (*Orders, err
return &order, nil
}
// SetTranscationID
func (m *Orders) SetTranscationID(ctx context.Context, id int64, transactionID string) error {
tbl := table.Orders
// SetTransactionID
func (m *Orders) SetTransactionID(ctx context.Context, transactionID string) error {
tbl := tblOrders
stmt := tbl.
UPDATE(tbl.TransactionID).
SET(String(transactionID)).
WHERE(
tbl.ID.EQ(Int64(id)),
tbl.ID.EQ(Int64(m.ID)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
@@ -297,30 +256,3 @@ func (m *Orders) SetTranscationID(ctx context.Context, id int64, transactionID s
}
return nil
}
// Update
func (m *Orders) Update(ctx context.Context, order *Orders) error {
tbl := table.Orders
stmt := tbl.
UPDATE(
tbl.MutableColumns.Except(
tbl.OrderNo,
tbl.Price,
tbl.Discount,
tbl.SubOrderNo,
tbl.PostID,
tbl.UserID,
),
).
MODEL(order).
WHERE(
tbl.ID.EQ(Int64(order.ID)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating order: %v", err)
return err
}
return nil
}

View File

@@ -6,7 +6,6 @@ import (
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
@@ -38,6 +37,6 @@ func Test_Orders(t *testing.T) {
func (s *OrdersTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Orders.TableName())
database.Truncate(context.Background(), db, tblOrders.TableName())
})
}

View File

@@ -0,0 +1,180 @@
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
package model
import (
"context"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"time"
)
// conds
func (m *Posts) CondNotDeleted() Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblPosts.DeletedAt.IS_NULL())
}
}
func (m *Posts) CondDeleted() Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblPosts.DeletedAt.IS_NOT_NULL())
}
}
func (m *Posts) CondID(id int64) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblPosts.ID.EQ(Int(id)))
}
}
// funcs
func (m *Posts) log() *log.Entry {
return log.WithField("model", "Posts")
}
func (m *Posts) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
stmt := tblPosts.INSERT(tblPosts.MutableColumns).MODEL(m).RETURNING(tblPosts.AllColumns)
m.log().WithField("func", "Create").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Posts item: %v", err)
return err
}
m.log().WithField("func", "Create").Infof("Posts item created successfully")
return nil
}
func (m *Posts) BatchCreate(ctx context.Context, models []*Posts) error {
stmt := tblPosts.INSERT(tblPosts.MutableColumns).MODELS(models)
m.log().WithField("func", "BatchCreate").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Posts item: %v", err)
return err
}
m.log().WithField("func", "BatchCreate").Infof("Posts items created successfully")
return nil
}
func (m *Posts) Delete(ctx context.Context) error {
stmt := tblPosts.UPDATE().SET(tblPosts.DeletedAt.SET(TimestampT(time.Now()))).WHERE(tblPosts.ID.EQ(Int(m.ID)))
m.log().WithField("func", "SoftDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "SoftDelete").Errorf("error soft deleting Posts item: %v", err)
return err
}
m.log().WithField("func", "SoftDelete").Infof("Posts item soft deleted successfully")
return nil
}
// BatchDelete
func (m *Posts) BatchDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblPosts.UPDATE().SET(tblPosts.DeletedAt.SET(TimestampT(time.Now()))).WHERE(tblPosts.ID.IN(condIds...))
m.log().WithField("func", "BatchSoftDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "BatchSoftDelete").Errorf("error soft deleting Posts items: %v", err)
return err
}
m.log().WithField("func", "BatchSoftDelete").WithField("ids", ids).Infof("Posts items soft deleted successfully")
return nil
}
func (m *Posts) ForceDelete(ctx context.Context) error {
stmt := tblPosts.DELETE().WHERE(tblPosts.ID.EQ(Int(m.ID)))
m.log().WithField("func", "Delete").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Delete").Errorf("error deleting Posts item: %v", err)
return err
}
m.log().WithField("func", "Delete").Infof("Posts item deleted successfully")
return nil
}
func (m *Posts) BatchForceDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblPosts.DELETE().WHERE(tblPosts.ID.IN(condIds...))
m.log().WithField("func", "BatchDelete").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "BatchForceDelete").Errorf("error deleting Posts items: %v", err)
return err
}
m.log().WithField("func", "BatchForceDelete").WithField("ids", ids).Infof("Posts items deleted successfully")
return nil
}
func (m *Posts) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
stmt := tblPosts.UPDATE(tblPostsUpdateMutableColumns).MODEL(m).WHERE(tblPosts.ID.EQ(Int(m.ID))).RETURNING(tblPosts.AllColumns)
m.log().WithField("func", "Update").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Update").Errorf("error updating Posts item: %v", err)
return err
}
m.log().WithField("func", "Update").Infof("Posts item updated successfully")
return nil
}
// GetByCond
func (m *Posts) GetByCond(ctx context.Context, conds ...Cond) (*Posts, error) {
cond := CondTrue(conds...)
stmt := tblPosts.SELECT(tblPosts.AllColumns).WHERE(cond)
m.log().WithField("func", "GetByCond").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "GetByCond").Errorf("error getting Posts item by ID: %v", err)
return nil, err
}
m.log().WithField("func", "GetByCond").Infof("Posts item retrieved successfully")
return m, nil
}
// GetByID
func (m *Posts) GetByID(ctx context.Context, id int64, conds ...Cond) (*Posts, error) {
return m.GetByCond(ctx, CondJoin(m.CondID(id), conds...)...)
}
// Count
func (m *Posts) Count(ctx context.Context, conds ...Cond) (int64, error) {
cond := CondTrue(conds...)
stmt := tblPosts.SELECT(COUNT(tblPosts.ID).AS("count")).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting Posts items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -5,125 +5,71 @@ import (
"time"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/table"
"quyun/database/fields"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Posts) log() *log.Entry {
return log.WithField("model", "PostsModel")
var tblPostsUpdateMutableColumns = tblPosts.MutableColumns.Except(
tblPosts.CreatedAt,
tblPosts.DeletedAt,
tblPosts.Views,
tblPosts.Likes,
)
func (m *Posts) CondStatus(s fields.PostStatus) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblPosts.Status.EQ(Int(int64(s))))
}
}
func (m *Posts) CondLike(key *string) Cond {
return func(cond BoolExpression) BoolExpression {
tbl := tblPosts
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Title.LIKE(String("%" + *key + "%")).
OR(
tbl.Content.LIKE(String("%" + *key + "%")),
).
OR(
tbl.Description.LIKE(String("%" + *key + "%")),
),
)
return cond
}
}
func (m *Posts) IncrViewCount(ctx context.Context) error {
tbl := table.Posts
tbl := tblPosts
stmt := tbl.UPDATE(tbl.Views).SET(tbl.Views.ADD(Int64(1))).WHERE(tbl.ID.EQ(Int64(m.ID)))
stmt := tbl.UPDATE(tbl.Views).
SET(tbl.Views.ADD(Int64(1))).
WHERE(tbl.ID.EQ(Int64(m.ID))).
RETURNING(tblPosts.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
var post Posts
err := stmt.QueryContext(ctx, db, &post)
if err != nil {
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().Errorf("error updating post view count: %v", err)
return err
}
return nil
}
// GetByID
func (m *Posts) GetByID(ctx context.Context, id int64, cond ...conds.Cond) (*Posts, error) {
tbl := table.Posts
var combinedCond BoolExpression = tbl.ID.EQ(Int64(id))
for _, c := range cond {
combinedCond = c(combinedCond)
}
stmt := tbl.SELECT(tbl.AllColumns).WHERE(combinedCond)
m.log().Infof("sql: %s", stmt.DebugSql())
var post Posts
err := stmt.QueryContext(ctx, db, &post)
if err != nil {
m.log().Errorf("error getting post: %v", err)
return nil, err
}
return &post, nil
}
// Create
func (m *Posts) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
tbl := table.Posts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(m).RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().Errorf("error creating post: %v", err)
return err
}
return nil
}
// Update
func (m *Posts) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
tbl := table.Posts
stmt := tbl.
UPDATE(
tbl.MutableColumns.Except(
tbl.CreatedAt,
tbl.DeletedAt,
tbl.Views,
tbl.Likes,
),
).
MODEL(m).
WHERE(tbl.ID.EQ(Int64(m.ID)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating post: %v", err)
return err
}
return nil
}
// countByCond
func (m *Posts) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Posts
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting post items: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
func (m *Posts) List(ctx context.Context, pagination *requests.Pagination, cond ...conds.Cond) (*requests.Pager, error) {
func (m *Posts) List(ctx context.Context, pagination *requests.Pagination, conds ...Cond) (*requests.Pager, error) {
pagination.Format()
combinedCond := table.Posts.DeletedAt.IS_NULL()
for _, c := range cond {
combinedCond = c(combinedCond)
}
cond := CondJoin(m.CondNotDeleted(), conds...)
tbl := table.Posts
tbl := tblPosts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(combinedCond).
WHERE(CondTrue(cond...)).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
@@ -136,7 +82,7 @@ func (m *Posts) List(ctx context.Context, pagination *requests.Pagination, cond
return nil, err
}
count, err := m.countByCondition(ctx, combinedCond)
count, err := m.Count(ctx, CondJoin(m.CondNotDeleted(), conds...)...)
if err != nil {
m.log().Errorf("error getting post count: %v", err)
return nil, err
@@ -149,28 +95,10 @@ func (m *Posts) List(ctx context.Context, pagination *requests.Pagination, cond
}, nil
}
// DeleteByID soft delete item
func (m *Posts) Delete(ctx context.Context) error {
tbl := table.Posts
stmt := tbl.
UPDATE(tbl.DeletedAt).
SET(TimestampT(time.Now())).
WHERE(
tbl.ID.EQ(Int64(m.ID)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting post: %v", err)
return err
}
return nil
}
// SendTo
func (m *Posts) SendTo(ctx context.Context, userId int64) error {
// add record to user_posts
tbl := table.UserPosts
tbl := tblUserPosts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(UserPosts{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
@@ -188,7 +116,7 @@ func (m *Posts) SendTo(ctx context.Context, userId int64) error {
// PostBoughtStatistics 获取指定文件 ID 的购买次数
func (m *Posts) BoughtStatistics(ctx context.Context, postIds []int64) (map[int64]int64, error) {
tbl := table.UserPosts
tbl := tblUserPosts
// select count(user_id), post_id from user_posts up where post_id in (1, 2,3,4,5,6,7,8,9,10) group by post_id
stmt := tbl.
@@ -197,7 +125,7 @@ func (m *Posts) BoughtStatistics(ctx context.Context, postIds []int64) (map[int6
tbl.PostID.AS("post_id"),
).
WHERE(
tbl.PostID.IN(lo.Map(postIds, func(id int64, _ int) Expression { return Int64(id) })...),
tbl.PostID.IN(IntExprSlice(postIds)...),
).
GROUP_BY(
tbl.PostID,
@@ -228,15 +156,15 @@ func (m *Posts) Bought(ctx context.Context, userId int64, pagination *requests.P
pagination.Format()
// select up.price,up.created_at,p.* from user_posts up left join posts p on up.post_id = p.id where up.user_id =1
tbl := table.UserPosts
tbl := tblUserPosts
stmt := tbl.
SELECT(
tbl.Price.AS("price"),
tbl.CreatedAt.AS("bought_at"),
table.Posts.Title.AS("title"),
tblPosts.Title.AS("title"),
).
FROM(
tbl.INNER_JOIN(table.Posts, table.Posts.ID.EQ(tbl.PostID)),
tbl.INNER_JOIN(tblPosts, tblPosts.ID.EQ(tbl.PostID)),
).
WHERE(
tbl.UserID.EQ(Int64(userId)),
@@ -286,11 +214,11 @@ func (m *Posts) GetPostsMapByIDs(ctx context.Context, ids []int64) (map[int64]Po
return nil, nil
}
tbl := table.Posts
tbl := tblPosts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
tbl.ID.IN(IntExprSlice(ids)...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
@@ -313,11 +241,11 @@ func (m *Posts) GetMediaByIds(ctx context.Context, ids []int64) ([]Medias, error
return nil, nil
}
tbl := table.Medias
tbl := tblMedias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
tbl.ID.IN(IntExprSlice(ids)...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
@@ -332,20 +260,6 @@ func (m *Posts) GetMediaByIds(ctx context.Context, ids []int64) ([]Medias, error
return medias, nil
}
// Count
func (m *Posts) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Posts
stmt := tbl.
SELECT(COUNT(tbl.ID).AS("count")).
WHERE(cond)
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting posts: %v", err)
return 0, err
}
return count.Count, nil
func (m *Posts) PayPrice() int64 {
return m.Price * int64(m.Discount) / 100
}

View File

@@ -7,7 +7,6 @@ import (
"quyun/app/service/testx"
"quyun/database"
"quyun/database/fields"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
@@ -39,14 +38,14 @@ func Test_Posts(t *testing.T) {
func (s *PostsTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Posts.TableName())
database.Truncate(context.Background(), db, tblPosts.TableName())
})
}
// Test_Create
func (s *PostsTestSuite) Test_Create() {
Convey("Test_Create", s.T(), func() {
// database.Truncate(context.Background(), db, table.Posts.TableName())
// database.Truncate(context.Background(), db, tblPosts.TableName())
post := &Posts{
Title: "Test Post",
@@ -65,3 +64,18 @@ func (s *PostsTestSuite) Test_Create() {
So(post.UpdatedAt, ShouldNotBeZeroValue)
})
}
func (s *PostsTestSuite) Test_IncrView() {
Convey("Test_IncrView", s.T(), func() {
// database.Truncate(context.Background(), db, tblPosts.TableName())
post, err := PostsModel().GetByID(context.Background(), 1)
So(err, ShouldBeNil)
oldViews := post.Views
So(post, ShouldNotBeNil)
err = post.IncrViewCount(context.Background())
So(err, ShouldBeNil)
So(post.Views, ShouldBeGreaterThan, oldViews)
})
}

View File

@@ -7,67 +7,90 @@ import (
"context"
"database/sql"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
"go.ipao.vip/atom"
"go.ipao.vip/atom/container"
"go.ipao.vip/atom/contracts"
"go.ipao.vip/atom/opt"
"golang.org/x/exp/constraints"
)
var db *sql.DB
var MediasModel *Medias
var OrdersModel *Orders
var PostsModel *Posts
var UsersModel *Users
type Cond func(BoolExpression) BoolExpression
func Transaction(ctx context.Context) (*sql.Tx, error) {
return db.Begin()
func ExprCond(expr BoolExpression) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(expr)
}
}
func DB() *sql.DB {
return db
func CondTrue(conds ...Cond) BoolExpression {
cond := BoolExp(Bool(true))
for _, c := range conds {
cond = c(cond)
}
return cond
}
func CondJoin(cond Cond, conds ...Cond) []Cond {
return append([]Cond{cond}, conds...)
}
// converts
func IntExprSlice[T constraints.Integer](slice []T) []Expression {
if len(slice) == 0 {
return nil
}
return lo.Map(slice, func(item T, _ int) Expression {
switch any(item).(type) {
case int8:
return Int8(int8(item))
case int16:
return Int16(int16(item))
case int32:
return Int32(int32(item))
case int64:
return Int64(int64(item))
case uint8:
return Uint8(uint8(item))
case uint16:
return Uint16(uint16(item))
case uint32:
return Uint32(uint32(item))
case uint64:
return Uint64(uint64(item))
default:
return nil
}
})
}
// tables
var tblMedias = table.Medias
var tblOrders = table.Orders
var tblPosts = table.Posts
var tblUserPosts = table.UserPosts
var tblUsers = table.Users
// models
var db *sql.DB
func MediasModel() *Medias { return &Medias{} }
func OrdersModel() *Orders { return &Orders{} }
func PostsModel() *Posts { return &Posts{} }
func UserPostsModel() *UserPosts { return &UserPosts{} }
func UsersModel() *Users { return &Users{} }
func Transaction(ctx context.Context) (*sql.Tx, error) { return db.Begin() }
func DB() *sql.DB { return db }
func Provide(opts ...opt.Option) error {
if err := container.Container.Provide(func() (*Medias, error) {
obj := &Medias{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*Orders, error) {
obj := &Orders{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*Posts, error) {
obj := &Posts{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*Users, error) {
obj := &Users{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func(
_db *sql.DB,
medias *Medias,
orders *Orders,
posts *Posts,
users *Users,
) (contracts.Initial, error) {
if err := container.Container.Provide(func(_db *sql.DB) (contracts.Initial, error) {
db = _db
MediasModel = medias
OrdersModel = orders
PostsModel = posts
UsersModel = users
return nil, nil
}, atom.GroupInitial); err != nil {
return err

View File

@@ -0,0 +1,139 @@
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
package model
import (
"context"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"time"
)
// conds
func (m *UserPosts) CondID(id int64) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblUserPosts.ID.EQ(Int(id)))
}
}
// funcs
func (m *UserPosts) log() *log.Entry {
return log.WithField("model", "UserPosts")
}
func (m *UserPosts) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
stmt := tblUserPosts.INSERT(tblUserPosts.MutableColumns).MODEL(m).RETURNING(tblUserPosts.AllColumns)
m.log().WithField("func", "Create").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Create").Errorf("error creating UserPosts item: %v", err)
return err
}
m.log().WithField("func", "Create").Infof("UserPosts item created successfully")
return nil
}
func (m *UserPosts) BatchCreate(ctx context.Context, models []*UserPosts) error {
stmt := tblUserPosts.INSERT(tblUserPosts.MutableColumns).MODELS(models)
m.log().WithField("func", "BatchCreate").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Create").Errorf("error creating UserPosts item: %v", err)
return err
}
m.log().WithField("func", "BatchCreate").Infof("UserPosts items created successfully")
return nil
}
func (m *UserPosts) Delete(ctx context.Context) error {
stmt := tblUserPosts.DELETE().WHERE(tblUserPosts.ID.EQ(Int(m.ID)))
m.log().WithField("func", "Delete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Delete").Errorf("error deleting UserPosts item: %v", err)
return err
}
m.log().WithField("func", "Delete").Infof("UserPosts item deleted successfully")
return nil
}
// BatchDelete
func (m *UserPosts) BatchDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblUserPosts.DELETE().WHERE(tblUserPosts.ID.IN(condIds...))
m.log().WithField("func", "BatchDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "BatchDelete").Errorf("error deleting UserPosts items: %v", err)
return err
}
m.log().WithField("func", "BatchDelete").WithField("ids", ids).Infof("UserPosts items deleted successfully")
return nil
}
func (m *UserPosts) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
stmt := tblUserPosts.UPDATE(tblUserPostsUpdateMutableColumns).MODEL(m).WHERE(tblUserPosts.ID.EQ(Int(m.ID))).RETURNING(tblUserPosts.AllColumns)
m.log().WithField("func", "Update").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Update").Errorf("error updating UserPosts item: %v", err)
return err
}
m.log().WithField("func", "Update").Infof("UserPosts item updated successfully")
return nil
}
// GetByCond
func (m *UserPosts) GetByCond(ctx context.Context, conds ...Cond) (*UserPosts, error) {
cond := CondTrue(conds...)
stmt := tblUserPosts.SELECT(tblUserPosts.AllColumns).WHERE(cond)
m.log().WithField("func", "GetByCond").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "GetByCond").Errorf("error getting UserPosts item by ID: %v", err)
return nil, err
}
m.log().WithField("func", "GetByCond").Infof("UserPosts item retrieved successfully")
return m, nil
}
// GetByID
func (m *UserPosts) GetByID(ctx context.Context, id int64, conds ...Cond) (*UserPosts, error) {
return m.GetByCond(ctx, CondJoin(m.CondID(id), conds...)...)
}
// Count
func (m *UserPosts) Count(ctx context.Context, conds ...Cond) (int64, error) {
cond := CondTrue(conds...)
stmt := tblUserPosts.SELECT(COUNT(tblUserPosts.ID).AS("count")).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting UserPosts items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -0,0 +1,10 @@
package model
import (
"quyun/database/table"
)
var tblUserPostsUpdateMutableColumns = tblUserPosts.MutableColumns.Except(
table.UserPosts.CreatedAt,
table.UserPosts.UpdatedAt,
)

View File

@@ -0,0 +1,43 @@
package model
import (
"context"
"testing"
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
// . "github.com/go-jet/jet/v2/postgres"
"github.com/stretchr/testify/suite"
"go.uber.org/dig"
)
type UserPostsInjectParams struct {
dig.In
Initials []contracts.Initial `group:"initials"`
}
type UserPostsTestSuite struct {
suite.Suite
UserPostsInjectParams
}
func Test_UserPosts(t *testing.T) {
providers := testx.Default().With(Provide)
testx.Serve(providers, t, func(params UserPostsInjectParams) {
suite.Run(t, &UserPostsTestSuite{
UserPostsInjectParams: params,
})
})
}
func (s *UserPostsTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.UserPosts.TableName())
})
}

View File

@@ -0,0 +1,180 @@
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
package model
import (
"context"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"time"
)
// conds
func (m *Users) CondNotDeleted() Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblUsers.DeletedAt.IS_NULL())
}
}
func (m *Users) CondDeleted() Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblUsers.DeletedAt.IS_NOT_NULL())
}
}
func (m *Users) CondID(id int64) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(tblUsers.ID.EQ(Int(id)))
}
}
// funcs
func (m *Users) log() *log.Entry {
return log.WithField("model", "Users")
}
func (m *Users) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
stmt := tblUsers.INSERT(tblUsers.MutableColumns).MODEL(m).RETURNING(tblUsers.AllColumns)
m.log().WithField("func", "Create").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Users item: %v", err)
return err
}
m.log().WithField("func", "Create").Infof("Users item created successfully")
return nil
}
func (m *Users) BatchCreate(ctx context.Context, models []*Users) error {
stmt := tblUsers.INSERT(tblUsers.MutableColumns).MODELS(models)
m.log().WithField("func", "BatchCreate").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Create").Errorf("error creating Users item: %v", err)
return err
}
m.log().WithField("func", "BatchCreate").Infof("Users items created successfully")
return nil
}
func (m *Users) Delete(ctx context.Context) error {
stmt := tblUsers.UPDATE().SET(tblUsers.DeletedAt.SET(TimestampT(time.Now()))).WHERE(tblUsers.ID.EQ(Int(m.ID)))
m.log().WithField("func", "SoftDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "SoftDelete").Errorf("error soft deleting Users item: %v", err)
return err
}
m.log().WithField("func", "SoftDelete").Infof("Users item soft deleted successfully")
return nil
}
// BatchDelete
func (m *Users) BatchDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblUsers.UPDATE().SET(tblUsers.DeletedAt.SET(TimestampT(time.Now()))).WHERE(tblUsers.ID.IN(condIds...))
m.log().WithField("func", "BatchSoftDelete").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "BatchSoftDelete").Errorf("error soft deleting Users items: %v", err)
return err
}
m.log().WithField("func", "BatchSoftDelete").WithField("ids", ids).Infof("Users items soft deleted successfully")
return nil
}
func (m *Users) ForceDelete(ctx context.Context) error {
stmt := tblUsers.DELETE().WHERE(tblUsers.ID.EQ(Int(m.ID)))
m.log().WithField("func", "Delete").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "Delete").Errorf("error deleting Users item: %v", err)
return err
}
m.log().WithField("func", "Delete").Infof("Users item deleted successfully")
return nil
}
func (m *Users) BatchForceDelete(ctx context.Context, ids []int64) error {
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
stmt := tblUsers.DELETE().WHERE(tblUsers.ID.IN(condIds...))
m.log().WithField("func", "BatchDelete").Info(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("func", "BatchForceDelete").Errorf("error deleting Users items: %v", err)
return err
}
m.log().WithField("func", "BatchForceDelete").WithField("ids", ids).Infof("Users items deleted successfully")
return nil
}
func (m *Users) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
stmt := tblUsers.UPDATE(tblUsersUpdateMutableColumns).MODEL(m).WHERE(tblUsers.ID.EQ(Int(m.ID))).RETURNING(tblUsers.AllColumns)
m.log().WithField("func", "Update").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Update").Errorf("error updating Users item: %v", err)
return err
}
m.log().WithField("func", "Update").Infof("Users item updated successfully")
return nil
}
// GetByCond
func (m *Users) GetByCond(ctx context.Context, conds ...Cond) (*Users, error) {
cond := CondTrue(conds...)
stmt := tblUsers.SELECT(tblUsers.AllColumns).WHERE(cond)
m.log().WithField("func", "GetByCond").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "GetByCond").Errorf("error getting Users item by ID: %v", err)
return nil, err
}
m.log().WithField("func", "GetByCond").Infof("Users item retrieved successfully")
return m, nil
}
// GetByID
func (m *Users) GetByID(ctx context.Context, id int64, conds ...Cond) (*Users, error) {
return m.GetByCond(ctx, CondJoin(m.CondID(id), conds...)...)
}
// Count
func (m *Users) Count(ctx context.Context, conds ...Cond) (int64, error) {
cond := CondTrue(conds...)
stmt := tblUsers.SELECT(COUNT(tblUsers.ID).AS("count")).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting Users items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -5,44 +5,24 @@ import (
"time"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/pkg/errors"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Users) log() *log.Entry {
return log.WithField("model", "UsersModel")
}
// GetByID
func (m *Users) GetByID(ctx context.Context, id int64) (*Users, error) {
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var user Users
if err := stmt.QueryContext(ctx, db, &user); err != nil {
m.log().Errorf("error querying user by ID(%d), err: %v", id, err)
return nil, err
}
return &user, nil
}
var tblUsersUpdateMutableColumns = tblUsers.MutableColumns.Except(
tblUsers.OpenID,
tblUsers.Balance,
tblUsers.CreatedAt,
tblUsers.DeletedAt,
)
// BuildConditionWithKey builds the WHERE clause for user queries
func (m *Users) BuildConditionWithKey(key *string) BoolExpression {
tbl := table.Users
tbl := tblUsers
cond := tbl.DeletedAt.IS_NULL()
@@ -63,7 +43,7 @@ func (m *Users) countByCondition(ctx context.Context, expr BoolExpression) (int6
Cnt int64
}
tbl := table.Users
tbl := tblUsers
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
@@ -77,10 +57,14 @@ func (m *Users) countByCondition(ctx context.Context, expr BoolExpression) (int6
}
// List returns a paginated list of users
func (m *Users) List(ctx context.Context, pagination *requests.Pagination, cond BoolExpression) (*requests.Pager, error) {
func (m *Users) List(
ctx context.Context,
pagination *requests.Pagination,
cond BoolExpression,
) (*requests.Pager, error) {
pagination.Format()
tbl := table.Users
tbl := tblUsers
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(cond).
@@ -109,81 +93,20 @@ func (m *Users) List(ctx context.Context, pagination *requests.Pagination, cond
}, nil
}
// Create creates a new user
func (m *Users) Create(ctx context.Context) (*Users, error) {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
tbl := table.Users
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(m).RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
var createdUser Users
err := stmt.QueryContext(ctx, db, &createdUser)
if err != nil {
m.log().Errorf("error creating user: %v", err)
return nil, err
}
return &createdUser, nil
}
// Update updates an existing user
func (m *Users) Update(ctx context.Context) (*Users, error) {
m.UpdatedAt = time.Now()
tbl := table.Users
stmt := tbl.
UPDATE(
tbl.MutableColumns.Except(
tbl.OpenID,
tbl.Balance,
tbl.CreatedAt,
tbl.DeletedAt,
),
).
MODEL(m).
WHERE(tbl.ID.EQ(Int64(m.ID))).
RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
var user Users
if err := stmt.QueryContext(ctx, db, &user); err != nil {
m.log().Errorf("error updating user: %v", err)
return nil, err
}
return &user, nil
}
// DeleteByID soft deletes a user by ID
func (m *Users) DeleteByID(ctx context.Context, id int64) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.DeletedAt).
SET(TimestampT(time.Now())).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting user: %v", err)
return err
}
return nil
}
// PostList returns a paginated list of posts for a user
func (m *Users) PostList(ctx context.Context, userId int64, pagination *requests.Pagination, conds ...conds.Cond) (*requests.Pager, error) {
func (m *Users) PostList(
ctx context.Context,
userId int64,
pagination *requests.Pagination,
conds ...Cond,
) (*requests.Pager, error) {
pagination.Format()
tblUserPosts := table.UserPosts
tblUserPosts := tblUserPosts
combineConds := tblUserPosts.UserID.EQ(Int64(userId))
for _, c := range conds {
combineConds = c(combineConds)
}
cond := CondJoin(ExprCond(tblUserPosts.UserID.EQ(Int64(userId))), conds...)
tbl := table.Posts
tbl := tblPosts
stmt := SELECT(tbl.AllColumns).
FROM(tbl.
RIGHT_JOIN(
@@ -191,7 +114,7 @@ func (m *Users) PostList(ctx context.Context, userId int64, pagination *requests
tblUserPosts.PostID.EQ(tbl.ID),
),
).
WHERE(combineConds).
WHERE(CondTrue(cond...)).
ORDER_BY(tblUserPosts.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
@@ -233,7 +156,7 @@ func (m *Users) PostList(ctx context.Context, userId int64, pagination *requests
// GetUserIDByOpenID
func (m *Users) GetUserByOpenID(ctx context.Context, openID string) (*Users, error) {
tbl := table.Users
tbl := tblUsers
stmt := tbl.
SELECT(tbl.AllColumns).
@@ -256,8 +179,7 @@ func (m *Users) GetUserByOpenIDOrCreate(ctx context.Context, openID string, user
user, err := m.GetUserByOpenID(ctx, openID)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
user, err = userModel.Create(ctx)
if err != nil {
if err = userModel.Create(ctx); err != nil {
return nil, errors.Wrap(err, "failed to create user")
}
} else {
@@ -271,8 +193,7 @@ func (m *Users) GetUserByOpenIDOrCreate(ctx context.Context, openID string, user
user.Metas = userModel.Metas
user.AuthToken = userModel.AuthToken
user, err = user.Update(ctx)
if err != nil {
if err := user.Update(ctx); err != nil {
return nil, errors.Wrap(err, "failed to update user")
}
}
@@ -285,11 +206,11 @@ func (m *Users) GetUsersMapByIDs(ctx context.Context, ids []int64) (map[int64]Us
return nil, nil
}
tbl := table.Users
tbl := tblUsers
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
tbl.ID.IN(IntExprSlice(ids)...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
@@ -307,10 +228,10 @@ func (m *Users) GetUsersMapByIDs(ctx context.Context, ids []int64) (map[int64]Us
}
func (m *Users) BatchCheckHasBought(ctx context.Context, postIDs []int64) (map[int64]bool, error) {
tbl := table.UserPosts
tbl := tblUserPosts
stmt := tbl.SELECT(tbl.PostID.AS("post_id")).WHERE(
tbl.UserID.EQ(Int64(m.ID)).AND(
tbl.PostID.IN(lo.Map(postIDs, func(id int64, _ int) Expression { return Int64(id) })...),
tbl.PostID.IN(IntExprSlice(postIDs)...),
),
)
@@ -331,7 +252,7 @@ func (m *Users) BatchCheckHasBought(ctx context.Context, postIDs []int64) (map[i
// HasBought
func (m *Users) HasBought(ctx context.Context, postID int64) (bool, error) {
tbl := table.UserPosts
tbl := tblUserPosts
stmt := tbl.
SELECT(tbl.ID).
WHERE(
@@ -354,30 +275,9 @@ func (m *Users) HasBought(ctx context.Context, postID int64) (bool, error) {
return userPost.ID > 0, nil
}
// Count
func (m *Users) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Users
stmt := tbl.
SELECT(COUNT(tbl.ID).AS("cnt")).
WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var cnt struct {
Cnt int64
}
if err := stmt.QueryContext(ctx, db, &cnt); err != nil {
m.log().Errorf("error counting users: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// SetUsername
func (m *Users) SetUsername(ctx context.Context, username string) error {
tbl := table.Users
tbl := tblUsers
stmt := tbl.
UPDATE(tbl.Username).
SET(String(username)).
@@ -395,7 +295,7 @@ func (m *Users) SetUsername(ctx context.Context, username string) error {
// UpdateUserToken
func (m *Users) UpdateUserToken(ctx context.Context, token fields.UserAuthToken) error {
tbl := table.Users
tbl := tblUsers
stmt := tbl.
UPDATE(tbl.AuthToken).
SET(fields.ToJson(token)).
@@ -413,7 +313,7 @@ func (m *Users) UpdateUserToken(ctx context.Context, token fields.UserAuthToken)
// BuyPosts
func (m *Users) BuyPosts(ctx context.Context, postID, price int64) error {
tbl := table.UserPosts
tbl := tblUserPosts
stmt := tbl.
INSERT(tbl.MutableColumns).
MODEL(&UserPosts{
@@ -434,7 +334,7 @@ func (m *Users) BuyPosts(ctx context.Context, postID, price int64) error {
}
func (m *Users) RevokePosts(ctx context.Context, postID int64) error {
tbl := table.UserPosts
tbl := tblUserPosts
stmt := tbl.
DELETE().
WHERE(
@@ -453,7 +353,7 @@ func (m *Users) RevokePosts(ctx context.Context, postID int64) error {
// SetBalance
func (m *Users) SetBalance(ctx context.Context, balance int64) error {
tbl := table.Users
tbl := tblUsers
stmt := tbl.
UPDATE(tbl.Balance).
SET(Int64(balance)).
@@ -471,7 +371,7 @@ func (m *Users) SetBalance(ctx context.Context, balance int64) error {
// AddBalance adds the given amount to the user's balance
func (m *Users) AddBalance(ctx context.Context, amount int64) error {
tbl := table.Users
tbl := tblUsers
stmt := tbl.
UPDATE(tbl.Balance).
SET(tbl.Balance.ADD(Int64(amount))).

View File

@@ -51,9 +51,26 @@ func (s *UsersTestSuite) Test_Create() {
Balance: 1000,
}
u, err := user.Create(context.TODO())
err := user.Create(context.TODO())
So(err, ShouldBeNil)
So(u, ShouldNotBeNil)
So(u.ID, ShouldNotBeZeroValue)
So(user, ShouldNotBeNil)
So(user.ID, ShouldNotBeZeroValue)
})
}
func (s *UsersTestSuite) Test_Update() {
Convey("Test_Update", s.T(), func() {
user, err := UsersModel().GetByID(context.Background(), 1001)
So(err, ShouldBeNil)
So(user, ShouldNotBeNil)
user.Username = "TestUpdate"
err = user.Update(context.TODO())
So(err, ShouldBeNil)
updatedUser, err := UsersModel().GetByID(context.Background(), user.ID)
So(err, ShouldBeNil)
So(updatedUser, ShouldNotBeNil)
So(updatedUser.Username, ShouldEqual, "TestUpdate")
})
}

View File

@@ -1,11 +0,0 @@
package conds
import (
. "github.com/go-jet/jet/v2/postgres"
)
type Cond func(BoolExpression) BoolExpression
func Default() BoolExpression {
return BoolExp(Bool(true))
}

View File

@@ -1,41 +0,0 @@
package conds
import (
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
)
func Post_NotDeleted() Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(table.Posts.DeletedAt.IS_NULL())
}
}
func Post_Status(s fields.PostStatus) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(table.Posts.Status.EQ(Int(int64(s))))
}
}
func Post_Like(key *string) Cond {
return func(cond BoolExpression) BoolExpression {
tbl := table.Posts
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Title.LIKE(String("%" + *key + "%")).
OR(
tbl.Content.LIKE(String("%" + *key + "%")),
).
OR(
tbl.Description.LIKE(String("%" + *key + "%")),
),
)
return cond
}
}

View File

@@ -1,84 +0,0 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Migrations = newMigrationsTable("public", "migrations", "")
type migrationsTable struct {
postgres.Table
// Columns
ID postgres.ColumnInteger
VersionID postgres.ColumnInteger
IsApplied postgres.ColumnBool
Tstamp postgres.ColumnTimestamp
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
}
type MigrationsTable struct {
migrationsTable
EXCLUDED migrationsTable
}
// AS creates new MigrationsTable with assigned alias
func (a MigrationsTable) AS(alias string) *MigrationsTable {
return newMigrationsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new MigrationsTable with assigned schema name
func (a MigrationsTable) FromSchema(schemaName string) *MigrationsTable {
return newMigrationsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new MigrationsTable with assigned table prefix
func (a MigrationsTable) WithPrefix(prefix string) *MigrationsTable {
return newMigrationsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new MigrationsTable with assigned table suffix
func (a MigrationsTable) WithSuffix(suffix string) *MigrationsTable {
return newMigrationsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newMigrationsTable(schemaName, tableName, alias string) *MigrationsTable {
return &MigrationsTable{
migrationsTable: newMigrationsTableImpl(schemaName, tableName, alias),
EXCLUDED: newMigrationsTableImpl("", "excluded", ""),
}
}
func newMigrationsTableImpl(schemaName, tableName, alias string) migrationsTable {
var (
IDColumn = postgres.IntegerColumn("id")
VersionIDColumn = postgres.IntegerColumn("version_id")
IsAppliedColumn = postgres.BoolColumn("is_applied")
TstampColumn = postgres.TimestampColumn("tstamp")
allColumns = postgres.ColumnList{IDColumn, VersionIDColumn, IsAppliedColumn, TstampColumn}
mutableColumns = postgres.ColumnList{VersionIDColumn, IsAppliedColumn, TstampColumn}
)
return migrationsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
ID: IDColumn,
VersionID: VersionIDColumn,
IsApplied: IsAppliedColumn,
Tstamp: TstampColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
}
}

View File

@@ -11,7 +11,6 @@ package table
// this method only once at the beginning of the program.
func UseSchema(schema string) {
Medias = Medias.FromSchema(schema)
Migrations = Migrations.FromSchema(schema)
Orders = Orders.FromSchema(schema)
Posts = Posts.FromSchema(schema)
UserPosts = UserPosts.FromSchema(schema)

View File

@@ -6,9 +6,9 @@ ignores:
- river_client_queue
- river_job_state
- river_queue
- migrations
model:
- migrations
- user_posts
types:
# users: # table name
# meta: UserMeta

View File

@@ -198,8 +198,6 @@ github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJV
github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
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=
@@ -256,8 +254,6 @@ github.com/riverqueue/river/rivertype v0.15.0 h1:+TXRnvQv1ulV24uQnsuZmbb3yJdmbpi
github.com/riverqueue/river/rivertype v0.15.0/go.mod h1:4vpt5ZSdZ35mFbRAV4oXgeRdH3Mq5h1pUzQTvaGfCUA=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogeecn/fabfile v1.6.0 h1:i0+Koa8yp3lsgEM8opcnya85cEohpGeGpm21xEekBmQ=
github.com/rogeecn/fabfile v1.6.0/go.mod h1:EPwX7TtVcIWSLJkJAqxSzYjM/aV1Q0wymcaXqnMgzas=
github.com/rogeecn/fabfile v1.7.0 h1:qtwkqaBsJjWrggbvznbd0HGyJ0ebBTOBE893JvD5Tng=
github.com/rogeecn/fabfile v1.7.0/go.mod h1:EPwX7TtVcIWSLJkJAqxSzYjM/aV1Q0wymcaXqnMgzas=
github.com/rogeecn/swag v1.0.1 h1:s1yxLgopqO1m8sqGjVmt6ocMBRubMPIh2JtIPG4xjQE=

View File

@@ -447,7 +447,7 @@ const loadHeadImagePreviews = async () => {
<Column field="fileSize" header="文件大小">
<template #body="{ data }">
{{ formatFileSize(data.file_size) }}
{{ formatFileSize(data.size) }}
</template>
</Column>