From 6cc14479c5ac19b75c4d6101485b0383704b2c45 Mon Sep 17 00:00:00 2001 From: zetaloop Date: Fri, 24 Apr 2026 08:16:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20community=20RPC=20=E4=BB=8E=E5=86=85?= =?UTF-8?q?=E5=AD=98=E5=AD=98=E5=82=A8=E8=BF=81=E7=A7=BB=E5=88=B0=20ent=20?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/logic/addCommentLikesLogic.go | 42 +- .../rpc/internal/logic/addCommentsLogic.go | 42 +- .../rpc/internal/logic/addPostLikesLogic.go | 43 +- .../rpc/internal/logic/addPostsLogic.go | 53 +- .../internal/logic/delCommentLikesLogic.go | 47 +- .../rpc/internal/logic/delCommentsLogic.go | 33 +- .../rpc/internal/logic/delPostLikesLogic.go | 47 +- .../rpc/internal/logic/delPostsLogic.go | 20 +- .../logic/getCommentLikesByIdLogic.go | 17 +- .../internal/logic/getCommentsByIdLogic.go | 14 +- .../internal/logic/getPostLikesByIdLogic.go | 17 +- .../rpc/internal/logic/getPostsByIdLogic.go | 17 +- app/community/rpc/internal/logic/helpers.go | 91 +- .../internal/logic/searchCommentLikesLogic.go | 41 +- .../rpc/internal/logic/searchCommentsLogic.go | 64 +- .../internal/logic/searchPostLikesLogic.go | 41 +- .../rpc/internal/logic/searchPostsLogic.go | 87 +- .../internal/logic/updateCommentLikesLogic.go | 24 +- .../rpc/internal/logic/updateCommentsLogic.go | 32 +- .../internal/logic/updatePostLikesLogic.go | 26 +- .../rpc/internal/logic/updatePostsLogic.go | 92 +- app/community/rpc/internal/models/client.go | 770 ++++ .../rpc/internal/models/commentlikes.go | 126 + .../models/commentlikes/commentlikes.go | 70 + .../rpc/internal/models/commentlikes/where.go | 205 ++ .../internal/models/commentlikes_create.go | 240 ++ .../internal/models/commentlikes_delete.go | 88 + .../rpc/internal/models/commentlikes_query.go | 527 +++ .../internal/models/commentlikes_update.go | 283 ++ app/community/rpc/internal/models/comments.go | 164 + .../rpc/internal/models/comments/comments.go | 96 + .../rpc/internal/models/comments/where.go | 385 ++ .../rpc/internal/models/comments_create.go | 293 ++ .../rpc/internal/models/comments_delete.go | 88 + .../rpc/internal/models/comments_query.go | 527 +++ .../rpc/internal/models/comments_update.go | 442 +++ app/community/rpc/internal/models/ent.go | 614 ++++ .../rpc/internal/models/enttest/enttest.go | 85 + app/community/rpc/internal/models/generate.go | 3 + .../rpc/internal/models/hook/hook.go | 234 ++ .../rpc/internal/models/migrate/migrate.go | 64 + .../rpc/internal/models/migrate/schema.go | 155 + app/community/rpc/internal/models/mutation.go | 3160 +++++++++++++++++ .../rpc/internal/models/postlikes.go | 126 + .../internal/models/postlikes/postlikes.go | 70 + .../rpc/internal/models/postlikes/where.go | 205 ++ .../rpc/internal/models/postlikes_create.go | 240 ++ .../rpc/internal/models/postlikes_delete.go | 88 + .../rpc/internal/models/postlikes_query.go | 527 +++ .../rpc/internal/models/postlikes_update.go | 283 ++ app/community/rpc/internal/models/posts.go | 263 ++ .../rpc/internal/models/posts/posts.go | 174 + .../rpc/internal/models/posts/where.go | 826 +++++ .../rpc/internal/models/posts_create.go | 470 +++ .../rpc/internal/models/posts_delete.go | 88 + .../rpc/internal/models/posts_query.go | 527 +++ .../rpc/internal/models/posts_update.go | 901 +++++ .../internal/models/predicate/predicate.go | 19 + app/community/rpc/internal/models/runtime.go | 74 + .../rpc/internal/models/runtime/runtime.go | 10 + .../internal/models/schema/commentlikes.go | 30 + .../rpc/internal/models/schema/comments.go | 36 + .../rpc/internal/models/schema/postlikes.go | 30 + .../rpc/internal/models/schema/posts.go | 53 + app/community/rpc/internal/models/tx.go | 219 ++ .../rpc/internal/svc/serviceContext.go | 49 +- app/community/rpc/internal/svc/store.go | 40 - go.mod | 20 +- go.sum | 20 +- 69 files changed, 14396 insertions(+), 501 deletions(-) create mode 100644 app/community/rpc/internal/models/client.go create mode 100644 app/community/rpc/internal/models/commentlikes.go create mode 100644 app/community/rpc/internal/models/commentlikes/commentlikes.go create mode 100644 app/community/rpc/internal/models/commentlikes/where.go create mode 100644 app/community/rpc/internal/models/commentlikes_create.go create mode 100644 app/community/rpc/internal/models/commentlikes_delete.go create mode 100644 app/community/rpc/internal/models/commentlikes_query.go create mode 100644 app/community/rpc/internal/models/commentlikes_update.go create mode 100644 app/community/rpc/internal/models/comments.go create mode 100644 app/community/rpc/internal/models/comments/comments.go create mode 100644 app/community/rpc/internal/models/comments/where.go create mode 100644 app/community/rpc/internal/models/comments_create.go create mode 100644 app/community/rpc/internal/models/comments_delete.go create mode 100644 app/community/rpc/internal/models/comments_query.go create mode 100644 app/community/rpc/internal/models/comments_update.go create mode 100644 app/community/rpc/internal/models/ent.go create mode 100644 app/community/rpc/internal/models/enttest/enttest.go create mode 100644 app/community/rpc/internal/models/generate.go create mode 100644 app/community/rpc/internal/models/hook/hook.go create mode 100644 app/community/rpc/internal/models/migrate/migrate.go create mode 100644 app/community/rpc/internal/models/migrate/schema.go create mode 100644 app/community/rpc/internal/models/mutation.go create mode 100644 app/community/rpc/internal/models/postlikes.go create mode 100644 app/community/rpc/internal/models/postlikes/postlikes.go create mode 100644 app/community/rpc/internal/models/postlikes/where.go create mode 100644 app/community/rpc/internal/models/postlikes_create.go create mode 100644 app/community/rpc/internal/models/postlikes_delete.go create mode 100644 app/community/rpc/internal/models/postlikes_query.go create mode 100644 app/community/rpc/internal/models/postlikes_update.go create mode 100644 app/community/rpc/internal/models/posts.go create mode 100644 app/community/rpc/internal/models/posts/posts.go create mode 100644 app/community/rpc/internal/models/posts/where.go create mode 100644 app/community/rpc/internal/models/posts_create.go create mode 100644 app/community/rpc/internal/models/posts_delete.go create mode 100644 app/community/rpc/internal/models/posts_query.go create mode 100644 app/community/rpc/internal/models/posts_update.go create mode 100644 app/community/rpc/internal/models/predicate/predicate.go create mode 100644 app/community/rpc/internal/models/runtime.go create mode 100644 app/community/rpc/internal/models/runtime/runtime.go create mode 100644 app/community/rpc/internal/models/schema/commentlikes.go create mode 100644 app/community/rpc/internal/models/schema/comments.go create mode 100644 app/community/rpc/internal/models/schema/postlikes.go create mode 100644 app/community/rpc/internal/models/schema/posts.go create mode 100644 app/community/rpc/internal/models/tx.go delete mode 100644 app/community/rpc/internal/svc/store.go diff --git a/app/community/rpc/internal/logic/addCommentLikesLogic.go b/app/community/rpc/internal/logic/addCommentLikesLogic.go index 81e088d..caba298 100644 --- a/app/community/rpc/internal/logic/addCommentLikesLogic.go +++ b/app/community/rpc/internal/logic/addCommentLikesLogic.go @@ -4,8 +4,11 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/comments" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" "github.com/zeromicro/go-zero/core/logx" ) @@ -30,26 +33,39 @@ func (l *AddCommentLikesLogic) AddCommentLikes(in *pb.AddCommentLikesReq) (*pb.A return nil, errors.New("commentId and userId are required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - comment, ok := store.Comments[in.GetCommentId()] - if !ok || comment.GetDeletedAt() > 0 { + exists, err := l.svcCtx.CommunityModelRO.Comments.Query(). + Where(comments.IDEQ(in.GetCommentId()), comments.DeletedAtIsNil()). + Exist(l.ctx) + if err != nil || !exists { return nil, errors.New("comment not found") } - key := commentLikeKey(in.GetCommentId(), in.GetUserId()) - if _, exists := store.CommentLikes[key]; exists { + dup, _ := l.svcCtx.CommunityModelRO.CommentLikes.Query(). + Where(commentlikes.CommentIDEQ(in.GetCommentId()), commentlikes.UserIDEQ(in.GetUserId())). + Exist(l.ctx) + if dup { return &pb.AddCommentLikesResp{}, nil } - store.CommentLikes[key] = &pb.CommentLikes{ - CommentId: in.GetCommentId(), - UserId: in.GetUserId(), - CreatedAt: nowUnix(in.GetCreatedAt()), + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create comment like id failed") } - comment.LikeCount++ + + _, err = l.svcCtx.CommunityModelRW.CommentLikes.Create(). + SetID(idResp.Id). + SetCommentID(in.GetCommentId()). + SetUserID(in.GetUserId()). + Save(l.ctx) + if err != nil { + logx.Errorf("addCommentLikes err: %v", err) + return nil, errors.New("add comment like failed") + } + + l.svcCtx.CommunityModelRW.Comments.Update(). + Where(comments.IDEQ(in.GetCommentId())). + AddLikeCount(1). + Exec(l.ctx) return &pb.AddCommentLikesResp{}, nil } diff --git a/app/community/rpc/internal/logic/addCommentsLogic.go b/app/community/rpc/internal/logic/addCommentsLogic.go index 8283bbe..d1db4c2 100644 --- a/app/community/rpc/internal/logic/addCommentsLogic.go +++ b/app/community/rpc/internal/logic/addCommentsLogic.go @@ -4,8 +4,10 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" "github.com/zeromicro/go-zero/core/logx" ) @@ -36,27 +38,33 @@ func (l *AddCommentsLogic) AddComments(in *pb.AddCommentsReq) (*pb.AddCommentsRe return nil, errors.New("content is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - post, ok := store.Posts[in.GetPostId()] - if !ok || post.GetDeletedAt() > 0 { + exists, err := l.svcCtx.CommunityModelRO.Posts.Query(). + Where(posts.IDEQ(in.GetPostId()), posts.DeletedAtIsNil()). + Exist(l.ctx) + if err != nil || !exists { return nil, errors.New("post not found") } - now := nowUnix(in.GetCreatedAt()) - comment := &pb.Comments{ - Id: store.NextComment(), - PostId: in.GetPostId(), - AuthorId: in.GetAuthorId(), - Content: in.GetContent(), - LikeCount: 0, - CreatedAt: now, + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create comment id failed") } - store.Comments[comment.Id] = comment - post.CommentCount++ - post.UpdatedAt = now + + _, err = l.svcCtx.CommunityModelRW.Comments.Create(). + SetID(idResp.Id). + SetPostID(in.GetPostId()). + SetAuthorID(in.GetAuthorId()). + SetContent(in.GetContent()). + Save(l.ctx) + if err != nil { + logx.Errorf("addComments err: %v", err) + return nil, errors.New("add comment failed") + } + + l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(in.GetPostId())). + AddCommentCount(1). + Exec(l.ctx) return &pb.AddCommentsResp{}, nil } diff --git a/app/community/rpc/internal/logic/addPostLikesLogic.go b/app/community/rpc/internal/logic/addPostLikesLogic.go index 82a35ff..08044fe 100644 --- a/app/community/rpc/internal/logic/addPostLikesLogic.go +++ b/app/community/rpc/internal/logic/addPostLikesLogic.go @@ -4,8 +4,11 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" "github.com/zeromicro/go-zero/core/logx" ) @@ -26,31 +29,43 @@ func NewAddPostLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddP // -----------------------postLikes----------------------- func (l *AddPostLikesLogic) AddPostLikes(in *pb.AddPostLikesReq) (*pb.AddPostLikesResp, error) { - // todo: add your logic here and delete this line if in.GetPostId() <= 0 || in.GetUserId() <= 0 { return nil, errors.New("postId and userId are required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - post, ok := store.Posts[in.GetPostId()] - if !ok || post.GetDeletedAt() > 0 { + exists, err := l.svcCtx.CommunityModelRO.Posts.Query(). + Where(posts.IDEQ(in.GetPostId()), posts.DeletedAtIsNil()). + Exist(l.ctx) + if err != nil || !exists { return nil, errors.New("post not found") } - key := postLikeKey(in.GetPostId(), in.GetUserId()) - if _, exists := store.PostLikes[key]; exists { + dup, _ := l.svcCtx.CommunityModelRO.PostLikes.Query(). + Where(postlikes.PostIDEQ(in.GetPostId()), postlikes.UserIDEQ(in.GetUserId())). + Exist(l.ctx) + if dup { return &pb.AddPostLikesResp{}, nil } - store.PostLikes[key] = &pb.PostLikes{ - PostId: in.GetPostId(), - UserId: in.GetUserId(), - CreatedAt: nowUnix(in.GetCreatedAt()), + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create post like id failed") } - post.LikeCount++ + + _, err = l.svcCtx.CommunityModelRW.PostLikes.Create(). + SetID(idResp.Id). + SetPostID(in.GetPostId()). + SetUserID(in.GetUserId()). + Save(l.ctx) + if err != nil { + logx.Errorf("addPostLikes err: %v", err) + return nil, errors.New("add post like failed") + } + + l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(in.GetPostId())). + AddLikeCount(1). + Exec(l.ctx) return &pb.AddPostLikesResp{}, nil } diff --git a/app/community/rpc/internal/logic/addPostsLogic.go b/app/community/rpc/internal/logic/addPostsLogic.go index 87f1742..b8d9ab6 100644 --- a/app/community/rpc/internal/logic/addPostsLogic.go +++ b/app/community/rpc/internal/logic/addPostsLogic.go @@ -6,6 +6,7 @@ import ( "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" "github.com/zeromicro/go-zero/core/logx" ) @@ -36,32 +37,38 @@ func (l *AddPostsLogic) AddPosts(in *pb.AddPostsReq) (*pb.AddPostsResp, error) { return nil, errors.New("content is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create post id failed") + } - now := nowUnix(in.GetCreatedAt()) - post := &pb.Posts{ - Id: store.NextPost(), - AuthorId: in.GetAuthorId(), - AuthorRole: in.GetAuthorRole(), - Title: in.GetTitle(), - Content: in.GetContent(), - Images: append([]string(nil), in.GetImages()...), - Tags: append([]string(nil), in.GetTags()...), - LinkedOrderId: in.GetLinkedOrderId(), - QuotedPostId: in.GetQuotedPostId(), - LikeCount: 0, - CommentCount: 0, - Pinned: in.GetPinned(), - SearchText: in.GetTitle() + " " + in.GetContent(), - CreatedAt: now, - UpdatedAt: now, + authorRole := in.GetAuthorRole() + if authorRole == "" { + authorRole = "consumer" } - if post.AuthorRole == "" { - post.AuthorRole = "consumer" + + creator := l.svcCtx.CommunityModelRW.Posts.Create(). + SetID(idResp.Id). + SetAuthorID(in.GetAuthorId()). + SetAuthorRole(authorRole). + SetTitle(in.GetTitle()). + SetContent(in.GetContent()). + SetImages(toTextArray(in.GetImages())). + SetTags(toTextArray(in.GetTags())). + SetPinned(in.GetPinned()) + + if in.GetLinkedOrderId() != 0 { + creator = creator.SetLinkedOrderID(in.GetLinkedOrderId()) + } + if in.GetQuotedPostId() != 0 { + creator = creator.SetQuotedPostID(in.GetQuotedPostId()) + } + + _, err = creator.Save(l.ctx) + if err != nil { + logx.Errorf("addPosts err: %v", err) + return nil, errors.New("add post failed") } - store.Posts[post.Id] = post return &pb.AddPostsResp{}, nil } diff --git a/app/community/rpc/internal/logic/delCommentLikesLogic.go b/app/community/rpc/internal/logic/delCommentLikesLogic.go index 1ecf61e..4dd82fc 100644 --- a/app/community/rpc/internal/logic/delCommentLikesLogic.go +++ b/app/community/rpc/internal/logic/delCommentLikesLogic.go @@ -4,6 +4,8 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/comments" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,36 +31,33 @@ func (l *DelCommentLikesLogic) DelCommentLikes(in *pb.DelCommentLikesReq) (*pb.D return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - if in.UserId != nil && in.GetUserId() > 0 { - key := commentLikeKey(in.GetId(), in.GetUserId()) - if _, ok := store.CommentLikes[key]; ok { - delete(store.CommentLikes, key) - if comment, ok := store.Comments[in.GetId()]; ok && comment.LikeCount > 0 { - comment.LikeCount-- - } + n, err := l.svcCtx.CommunityModelRW.CommentLikes.Delete(). + Where(commentlikes.CommentIDEQ(in.GetId()), commentlikes.UserIDEQ(in.GetUserId())). + Exec(l.ctx) + if err != nil { + logx.Errorf("delCommentLikes err: %v", err) + } + if n > 0 { + l.svcCtx.CommunityModelRW.Comments.Update(). + Where(comments.IDEQ(in.GetId()), comments.LikeCountGT(0)). + AddLikeCount(-1). + Exec(l.ctx) } return &pb.DelCommentLikesResp{}, nil } - removed := int64(0) - for key, like := range store.CommentLikes { - if like.GetCommentId() == in.GetId() { - delete(store.CommentLikes, key) - removed++ - } + n, err := l.svcCtx.CommunityModelRW.CommentLikes.Delete(). + Where(commentlikes.CommentIDEQ(in.GetId())). + Exec(l.ctx) + if err != nil { + logx.Errorf("delCommentLikes err: %v", err) } - if removed > 0 { - if comment, ok := store.Comments[in.GetId()]; ok { - if comment.LikeCount >= removed { - comment.LikeCount -= removed - } else { - comment.LikeCount = 0 - } - } + if n > 0 { + l.svcCtx.CommunityModelRW.Comments.Update(). + Where(comments.IDEQ(in.GetId()), comments.LikeCountGTE(n)). + AddLikeCount(-n). + Exec(l.ctx) } return &pb.DelCommentLikesResp{}, nil diff --git a/app/community/rpc/internal/logic/delCommentsLogic.go b/app/community/rpc/internal/logic/delCommentsLogic.go index 297a15e..1d38bd1 100644 --- a/app/community/rpc/internal/logic/delCommentsLogic.go +++ b/app/community/rpc/internal/logic/delCommentsLogic.go @@ -3,7 +3,10 @@ package logic import ( "context" "errors" + "time" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,22 +32,26 @@ func (l *DelCommentsLogic) DelComments(in *pb.DelCommentsReq) (*pb.DelCommentsRe return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - comment, ok := store.Comments[in.GetId()] - if !ok { + comment, err := l.svcCtx.CommunityModelRO.Comments.Query(). + Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil()). + First(l.ctx) + if err != nil { return &pb.DelCommentsResp{}, nil } - if comment.GetDeletedAt() == 0 { - now := nowUnix(0) - comment.DeletedAt = now - if post, ok := store.Posts[comment.GetPostId()]; ok && post.GetDeletedAt() == 0 && post.CommentCount > 0 { - post.CommentCount-- - post.UpdatedAt = now - } + + now := time.Now() + _, err = l.svcCtx.CommunityModelRW.Comments.Update(). + Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil()). + SetDeletedAt(now). + Save(l.ctx) + if err != nil { + logx.Errorf("delComments err: %v", err) } + l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(comment.PostID), posts.DeletedAtIsNil(), posts.CommentCountGT(0)). + AddCommentCount(-1). + Exec(l.ctx) + return &pb.DelCommentsResp{}, nil } diff --git a/app/community/rpc/internal/logic/delPostLikesLogic.go b/app/community/rpc/internal/logic/delPostLikesLogic.go index 8b0e5ce..8ee34d6 100644 --- a/app/community/rpc/internal/logic/delPostLikesLogic.go +++ b/app/community/rpc/internal/logic/delPostLikesLogic.go @@ -4,6 +4,8 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,36 +31,33 @@ func (l *DelPostLikesLogic) DelPostLikes(in *pb.DelPostLikesReq) (*pb.DelPostLik return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - if in.UserId != nil && in.GetUserId() > 0 { - key := postLikeKey(in.GetId(), in.GetUserId()) - if _, ok := store.PostLikes[key]; ok { - delete(store.PostLikes, key) - if post, ok := store.Posts[in.GetId()]; ok && post.LikeCount > 0 { - post.LikeCount-- - } + n, err := l.svcCtx.CommunityModelRW.PostLikes.Delete(). + Where(postlikes.PostIDEQ(in.GetId()), postlikes.UserIDEQ(in.GetUserId())). + Exec(l.ctx) + if err != nil { + logx.Errorf("delPostLikes err: %v", err) + } + if n > 0 { + l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(in.GetId()), posts.LikeCountGT(0)). + AddLikeCount(-1). + Exec(l.ctx) } return &pb.DelPostLikesResp{}, nil } - removed := int64(0) - for key, like := range store.PostLikes { - if like.GetPostId() == in.GetId() { - delete(store.PostLikes, key) - removed++ - } + n, err := l.svcCtx.CommunityModelRW.PostLikes.Delete(). + Where(postlikes.PostIDEQ(in.GetId())). + Exec(l.ctx) + if err != nil { + logx.Errorf("delPostLikes err: %v", err) } - if removed > 0 { - if post, ok := store.Posts[in.GetId()]; ok { - if post.LikeCount >= removed { - post.LikeCount -= removed - } else { - post.LikeCount = 0 - } - } + if n > 0 { + l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(in.GetId()), posts.LikeCountGTE(n)). + AddLikeCount(-n). + Exec(l.ctx) } return &pb.DelPostLikesResp{}, nil diff --git a/app/community/rpc/internal/logic/delPostsLogic.go b/app/community/rpc/internal/logic/delPostsLogic.go index 15588c7..5fd7108 100644 --- a/app/community/rpc/internal/logic/delPostsLogic.go +++ b/app/community/rpc/internal/logic/delPostsLogic.go @@ -3,7 +3,9 @@ package logic import ( "context" "errors" + "time" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,17 +31,15 @@ func (l *DelPostsLogic) DelPosts(in *pb.DelPostsReq) (*pb.DelPostsResp, error) { return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - post, ok := store.Posts[in.GetId()] - if !ok { - return &pb.DelPostsResp{}, nil + now := time.Now() + _, err := l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(in.GetId()), posts.DeletedAtIsNil()). + SetDeletedAt(now). + SetUpdatedAt(now). + Save(l.ctx) + if err != nil { + logx.Errorf("delPosts err: %v", err) } - now := nowUnix(0) - post.DeletedAt = now - post.UpdatedAt = now return &pb.DelPostsResp{}, nil } diff --git a/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go b/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go index 2366250..7fd534d 100644 --- a/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go +++ b/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/commentlikes" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,16 +30,12 @@ func (l *GetCommentLikesByIdLogic) GetCommentLikesById(in *pb.GetCommentLikesByI return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() - - for _, like := range store.CommentLikes { - if like.GetCommentId() == in.GetId() { - cp := *like - return &pb.GetCommentLikesByIdResp{CommentLikes: &cp}, nil - } + like, err := l.svcCtx.CommunityModelRO.CommentLikes.Query(). + Where(commentlikes.CommentIDEQ(in.GetId())). + First(l.ctx) + if err != nil { + return nil, errors.New("comment like not found") } - return nil, errors.New("comment like not found") + return &pb.GetCommentLikesByIdResp{CommentLikes: entCommentLikeToPb(like)}, nil } diff --git a/app/community/rpc/internal/logic/getCommentsByIdLogic.go b/app/community/rpc/internal/logic/getCommentsByIdLogic.go index c840c1d..d79fb23 100644 --- a/app/community/rpc/internal/logic/getCommentsByIdLogic.go +++ b/app/community/rpc/internal/logic/getCommentsByIdLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/comments" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,15 +30,12 @@ func (l *GetCommentsByIdLogic) GetCommentsById(in *pb.GetCommentsByIdReq) (*pb.G return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() - - comment, ok := store.Comments[in.GetId()] - if !ok || comment.GetDeletedAt() > 0 { + comment, err := l.svcCtx.CommunityModelRO.Comments.Query(). + Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil()). + First(l.ctx) + if err != nil { return nil, errors.New("comment not found") } - out := *comment - return &pb.GetCommentsByIdResp{Comments: &out}, nil + return &pb.GetCommentsByIdResp{Comments: entCommentToPb(comment)}, nil } diff --git a/app/community/rpc/internal/logic/getPostLikesByIdLogic.go b/app/community/rpc/internal/logic/getPostLikesByIdLogic.go index a5cf988..6ea48fd 100644 --- a/app/community/rpc/internal/logic/getPostLikesByIdLogic.go +++ b/app/community/rpc/internal/logic/getPostLikesByIdLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/postlikes" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,16 +30,12 @@ func (l *GetPostLikesByIdLogic) GetPostLikesById(in *pb.GetPostLikesByIdReq) (*p return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() - - for _, like := range store.PostLikes { - if like.GetPostId() == in.GetId() { - cp := *like - return &pb.GetPostLikesByIdResp{PostLikes: &cp}, nil - } + like, err := l.svcCtx.CommunityModelRO.PostLikes.Query(). + Where(postlikes.PostIDEQ(in.GetId())). + First(l.ctx) + if err != nil { + return nil, errors.New("post like not found") } - return nil, errors.New("post like not found") + return &pb.GetPostLikesByIdResp{PostLikes: entPostLikeToPb(like)}, nil } diff --git a/app/community/rpc/internal/logic/getPostsByIdLogic.go b/app/community/rpc/internal/logic/getPostsByIdLogic.go index 95a818a..7e16b80 100644 --- a/app/community/rpc/internal/logic/getPostsByIdLogic.go +++ b/app/community/rpc/internal/logic/getPostsByIdLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,18 +30,12 @@ func (l *GetPostsByIdLogic) GetPostsById(in *pb.GetPostsByIdReq) (*pb.GetPostsBy return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() - - post, ok := store.Posts[in.GetId()] - if !ok || post.GetDeletedAt() > 0 { + post, err := l.svcCtx.CommunityModelRO.Posts.Query(). + Where(posts.IDEQ(in.GetId()), posts.DeletedAtIsNil()). + First(l.ctx) + if err != nil { return nil, errors.New("post not found") } - out := *post - out.Images = append([]string(nil), post.Images...) - out.Tags = append([]string(nil), post.Tags...) - - return &pb.GetPostsByIdResp{Posts: &out}, nil + return &pb.GetPostsByIdResp{Posts: entPostToPb(post)}, nil } diff --git a/app/community/rpc/internal/logic/helpers.go b/app/community/rpc/internal/logic/helpers.go index 32dd62f..d134634 100644 --- a/app/community/rpc/internal/logic/helpers.go +++ b/app/community/rpc/internal/logic/helpers.go @@ -1,45 +1,78 @@ package logic import ( - "sort" - "strconv" - "time" - + "juwan-backend/app/community/rpc/internal/models" "juwan-backend/app/community/rpc/pb" + "juwan-backend/pkg/types" + + "github.com/jackc/pgx/v5/pgtype" ) -func nowUnix(in int64) int64 { - if in > 0 { - return in +func toTextArray(s []string) types.TextArray { + if len(s) == 0 { + return types.TextArray{Valid: true} + } + return types.TextArray{ + Elements: s, + Dims: []pgtype.ArrayDimension{{Length: int32(len(s)), LowerBound: 1}}, + Valid: true, } - return time.Now().Unix() } -func postLikeKey(postID, userID int64) string { - return strconv.FormatInt(postID, 10) + ":" + strconv.FormatInt(userID, 10) +func entPostToPb(p *models.Posts) *pb.Posts { + out := &pb.Posts{ + Id: p.ID, + AuthorId: p.AuthorID, + AuthorRole: p.AuthorRole, + Title: p.Title, + Content: p.Content, + Images: p.Images.Elements, + Tags: p.Tags.Elements, + LikeCount: int64(p.LikeCount), + CommentCount: int64(p.CommentCount), + Pinned: p.Pinned, + CreatedAt: p.CreatedAt.Unix(), + UpdatedAt: p.UpdatedAt.Unix(), + } + if p.LinkedOrderID != nil { + out.LinkedOrderId = *p.LinkedOrderID + } + if p.QuotedPostID != nil { + out.QuotedPostId = *p.QuotedPostID + } + if p.DeletedAt != nil { + out.DeletedAt = p.DeletedAt.Unix() + } + return out } -func commentLikeKey(commentID, userID int64) string { - return strconv.FormatInt(commentID, 10) + ":" + strconv.FormatInt(userID, 10) +func entCommentToPb(c *models.Comments) *pb.Comments { + out := &pb.Comments{ + Id: c.ID, + PostId: c.PostID, + AuthorId: c.AuthorID, + Content: c.Content, + LikeCount: int64(c.LikeCount), + CreatedAt: c.CreatedAt.Unix(), + } + if c.DeletedAt != nil { + out.DeletedAt = c.DeletedAt.Unix() + } + return out } -func sortPostsDesc(posts []*pb.Posts) { - sort.Slice(posts, func(i, j int) bool { - if posts[i].Pinned != posts[j].Pinned { - return posts[i].Pinned - } - if posts[i].CreatedAt == posts[j].CreatedAt { - return posts[i].Id > posts[j].Id - } - return posts[i].CreatedAt > posts[j].CreatedAt - }) +func entPostLikeToPb(l *models.PostLikes) *pb.PostLikes { + return &pb.PostLikes{ + PostId: l.PostID, + UserId: l.UserID, + CreatedAt: l.CreatedAt.Unix(), + } } -func sortCommentsAsc(comments []*pb.Comments) { - sort.Slice(comments, func(i, j int) bool { - if comments[i].CreatedAt == comments[j].CreatedAt { - return comments[i].Id < comments[j].Id - } - return comments[i].CreatedAt < comments[j].CreatedAt - }) +func entCommentLikeToPb(l *models.CommentLikes) *pb.CommentLikes { + return &pb.CommentLikes{ + CommentId: l.CommentID, + UserId: l.UserID, + CreatedAt: l.CreatedAt.Unix(), + } } diff --git a/app/community/rpc/internal/logic/searchCommentLikesLogic.go b/app/community/rpc/internal/logic/searchCommentLikesLogic.go index e5a4a67..eed4444 100644 --- a/app/community/rpc/internal/logic/searchCommentLikesLogic.go +++ b/app/community/rpc/internal/logic/searchCommentLikesLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/commentlikes" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -37,29 +38,27 @@ func (l *SearchCommentLikesLogic) SearchCommentLikes(in *pb.SearchCommentLikesRe offset = 0 } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() - - filtered := make([]*pb.CommentLikes, 0, len(store.CommentLikes)) - for _, like := range store.CommentLikes { - if in.GetCommentId() > 0 && like.GetCommentId() != in.GetCommentId() { - continue - } - if in.GetUserId() > 0 && like.GetUserId() != in.GetUserId() { - continue - } - cp := *like - filtered = append(filtered, &cp) + query := l.svcCtx.CommunityModelRO.CommentLikes.Query() + if in.GetCommentId() > 0 { + query = query.Where(commentlikes.CommentIDEQ(in.GetCommentId())) + } + if in.GetUserId() > 0 { + query = query.Where(commentlikes.UserIDEQ(in.GetUserId())) } - if offset >= int64(len(filtered)) { - return &pb.SearchCommentLikesResp{CommentLikes: []*pb.CommentLikes{}}, nil - } - end := offset + limit - if end > int64(len(filtered)) { - end = int64(len(filtered)) + list, err := query. + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchCommentLikes err: %v", err) + return nil, errors.New("search comment likes failed") } - return &pb.SearchCommentLikesResp{CommentLikes: filtered[offset:end]}, nil + out := make([]*pb.CommentLikes, len(list)) + for i, like := range list { + out[i] = entCommentLikeToPb(like) + } + + return &pb.SearchCommentLikesResp{CommentLikes: out}, nil } diff --git a/app/community/rpc/internal/logic/searchCommentsLogic.go b/app/community/rpc/internal/logic/searchCommentsLogic.go index da6adf4..cb91106 100644 --- a/app/community/rpc/internal/logic/searchCommentsLogic.go +++ b/app/community/rpc/internal/logic/searchCommentsLogic.go @@ -3,11 +3,12 @@ package logic import ( "context" "errors" - "strings" + "juwan-backend/app/community/rpc/internal/models/comments" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" + "entgo.io/ent/dialect/sql" "github.com/zeromicro/go-zero/core/logx" ) @@ -38,43 +39,36 @@ func (l *SearchCommentsLogic) SearchComments(in *pb.SearchCommentsReq) (*pb.Sear offset = 0 } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() + query := l.svcCtx.CommunityModelRO.Comments.Query(). + Where(comments.DeletedAtIsNil()) - filtered := make([]*pb.Comments, 0, len(store.Comments)) - for _, c := range store.Comments { - if c.GetDeletedAt() > 0 { - continue - } - if in.GetId() > 0 && c.GetId() != in.GetId() { - continue - } - if in.GetPostId() > 0 && c.GetPostId() != in.GetPostId() { - continue - } - if in.GetAuthorId() > 0 && c.GetAuthorId() != in.GetAuthorId() { - continue - } - if in.Content != nil && !strings.Contains(strings.ToLower(c.GetContent()), strings.ToLower(in.GetContent())) { - continue - } - if in.LikeCount != nil && c.GetLikeCount() != in.GetLikeCount() { - continue - } - cc := *c - filtered = append(filtered, &cc) + if in.GetId() > 0 { + query = query.Where(comments.IDEQ(in.GetId())) + } + if in.GetPostId() > 0 { + query = query.Where(comments.PostIDEQ(in.GetPostId())) + } + if in.GetAuthorId() > 0 { + query = query.Where(comments.AuthorIDEQ(in.GetAuthorId())) + } + if in.Content != nil { + query = query.Where(comments.ContentContainsFold(in.GetContent())) } - sortCommentsAsc(filtered) - - if offset >= int64(len(filtered)) { - return &pb.SearchCommentsResp{Comments: []*pb.Comments{}}, nil - } - end := offset + limit - if end > int64(len(filtered)) { - end = int64(len(filtered)) + list, err := query. + Order(comments.ByCreatedAt(sql.OrderAsc()), comments.ByID(sql.OrderAsc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchComments err: %v", err) + return nil, errors.New("search comments failed") } - return &pb.SearchCommentsResp{Comments: filtered[offset:end]}, nil + out := make([]*pb.Comments, len(list)) + for i, c := range list { + out[i] = entCommentToPb(c) + } + + return &pb.SearchCommentsResp{Comments: out}, nil } diff --git a/app/community/rpc/internal/logic/searchPostLikesLogic.go b/app/community/rpc/internal/logic/searchPostLikesLogic.go index cffdcfe..46da283 100644 --- a/app/community/rpc/internal/logic/searchPostLikesLogic.go +++ b/app/community/rpc/internal/logic/searchPostLikesLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/postlikes" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -37,29 +38,27 @@ func (l *SearchPostLikesLogic) SearchPostLikes(in *pb.SearchPostLikesReq) (*pb.S offset = 0 } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() - - filtered := make([]*pb.PostLikes, 0, len(store.PostLikes)) - for _, like := range store.PostLikes { - if in.PostId != nil && like.GetPostId() != in.GetPostId() { - continue - } - if in.UserId != nil && like.GetUserId() != in.GetUserId() { - continue - } - cp := *like - filtered = append(filtered, &cp) + query := l.svcCtx.CommunityModelRO.PostLikes.Query() + if in.PostId != nil { + query = query.Where(postlikes.PostIDEQ(in.GetPostId())) + } + if in.UserId != nil { + query = query.Where(postlikes.UserIDEQ(in.GetUserId())) } - if offset >= int64(len(filtered)) { - return &pb.SearchPostLikesResp{PostLikes: []*pb.PostLikes{}}, nil - } - end := offset + limit - if end > int64(len(filtered)) { - end = int64(len(filtered)) + list, err := query. + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchPostLikes err: %v", err) + return nil, errors.New("search post likes failed") } - return &pb.SearchPostLikesResp{PostLikes: filtered[offset:end]}, nil + out := make([]*pb.PostLikes, len(list)) + for i, like := range list { + out[i] = entPostLikeToPb(like) + } + + return &pb.SearchPostLikesResp{PostLikes: out}, nil } diff --git a/app/community/rpc/internal/logic/searchPostsLogic.go b/app/community/rpc/internal/logic/searchPostsLogic.go index 0ded0a7..669ae83 100644 --- a/app/community/rpc/internal/logic/searchPostsLogic.go +++ b/app/community/rpc/internal/logic/searchPostsLogic.go @@ -3,11 +3,12 @@ package logic import ( "context" "errors" - "strings" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" + "entgo.io/ent/dialect/sql" "github.com/zeromicro/go-zero/core/logx" ) @@ -38,63 +39,39 @@ func (l *SearchPostsLogic) SearchPosts(in *pb.SearchPostsReq) (*pb.SearchPostsRe offset = 0 } - store := l.svcCtx.Store - store.Mu.RLock() - defer store.Mu.RUnlock() + query := l.svcCtx.CommunityModelRO.Posts.Query(). + Where(posts.DeletedAtIsNil()) - filtered := make([]*pb.Posts, 0, len(store.Posts)) - for _, p := range store.Posts { - if p.GetDeletedAt() > 0 { - continue - } - if in.GetId() > 0 && p.GetId() != in.GetId() { - continue - } - if in.AuthorId != nil && p.GetAuthorId() != in.GetAuthorId() { - continue - } - if in.AuthorRole != nil && p.GetAuthorRole() != in.GetAuthorRole() { - continue - } - if in.Title != nil && !strings.Contains(strings.ToLower(p.GetTitle()), strings.ToLower(in.GetTitle())) { - continue - } - if in.Content != nil && !strings.Contains(strings.ToLower(p.GetContent()), strings.ToLower(in.GetContent())) { - continue - } - if len(in.GetTags()) > 0 { - match := false - for _, t := range in.GetTags() { - for _, pt := range p.GetTags() { - if t == pt { - match = true - break - } - } - if match { - break - } - } - if !match { - continue - } - } - - cp := *p - cp.Images = append([]string(nil), p.Images...) - cp.Tags = append([]string(nil), p.Tags...) - filtered = append(filtered, &cp) + if in.GetId() > 0 { + query = query.Where(posts.IDEQ(in.GetId())) + } + if in.AuthorId != nil { + query = query.Where(posts.AuthorIDEQ(in.GetAuthorId())) + } + if in.AuthorRole != nil { + query = query.Where(posts.AuthorRole(in.GetAuthorRole())) + } + if in.Title != nil { + query = query.Where(posts.TitleContainsFold(in.GetTitle())) + } + if in.Content != nil { + query = query.Where(posts.ContentContainsFold(in.GetContent())) } - sortPostsDesc(filtered) - - if offset >= int64(len(filtered)) { - return &pb.SearchPostsResp{Posts: []*pb.Posts{}}, nil - } - end := offset + limit - if end > int64(len(filtered)) { - end = int64(len(filtered)) + list, err := query. + Order(posts.ByPinned(sql.OrderDesc()), posts.ByCreatedAt(sql.OrderDesc()), posts.ByID(sql.OrderDesc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchPosts err: %v", err) + return nil, errors.New("search posts failed") } - return &pb.SearchPostsResp{Posts: filtered[offset:end]}, nil + out := make([]*pb.Posts, len(list)) + for i, p := range list { + out[i] = entPostToPb(p) + } + + return &pb.SearchPostsResp{Posts: out}, nil } diff --git a/app/community/rpc/internal/logic/updateCommentLikesLogic.go b/app/community/rpc/internal/logic/updateCommentLikesLogic.go index 30c8571..331e1c8 100644 --- a/app/community/rpc/internal/logic/updateCommentLikesLogic.go +++ b/app/community/rpc/internal/logic/updateCommentLikesLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/commentlikes" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,18 +30,19 @@ func (l *UpdateCommentLikesLogic) UpdateCommentLikes(in *pb.UpdateCommentLikesRe return nil, errors.New("commentId and userId are required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - if _, ok := store.Comments[in.GetCommentId()]; !ok { - return nil, errors.New("comment not found") + _, err := l.svcCtx.CommunityModelRO.CommentLikes.Query(). + Where(commentlikes.CommentIDEQ(in.GetCommentId()), commentlikes.UserIDEQ(in.GetUserId())). + First(l.ctx) + if err != nil { + return nil, errors.New("comment like not found") } - key := commentLikeKey(in.GetCommentId(), in.GetUserId()) - store.CommentLikes[key] = &pb.CommentLikes{ - CommentId: in.GetCommentId(), - UserId: in.GetUserId(), - CreatedAt: nowUnix(in.GetCreatedAt()), + + _, err = l.svcCtx.CommunityModelRW.CommentLikes.Update(). + Where(commentlikes.CommentIDEQ(in.GetCommentId()), commentlikes.UserIDEQ(in.GetUserId())). + Save(l.ctx) + if err != nil { + logx.Errorf("updateCommentLikes err: %v", err) + return nil, errors.New("update comment like failed") } return &pb.UpdateCommentLikesResp{}, nil diff --git a/app/community/rpc/internal/logic/updateCommentsLogic.go b/app/community/rpc/internal/logic/updateCommentsLogic.go index a82fa5b..95e8db5 100644 --- a/app/community/rpc/internal/logic/updateCommentsLogic.go +++ b/app/community/rpc/internal/logic/updateCommentsLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/comments" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,32 +30,23 @@ func (l *UpdateCommentsLogic) UpdateComments(in *pb.UpdateCommentsReq) (*pb.Upda return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() + updater := l.svcCtx.CommunityModelRW.Comments.Update(). + Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil()) - comment, ok := store.Comments[in.GetId()] - if !ok || comment.GetDeletedAt() > 0 { - return nil, errors.New("comment not found") - } - - if in.GetPostId() > 0 { - comment.PostId = in.GetPostId() - } - if in.GetAuthorId() > 0 { - comment.AuthorId = in.GetAuthorId() - } if in.GetContent() != "" { - comment.Content = in.GetContent() + updater = updater.SetContent(in.GetContent()) } if in.GetLikeCount() > 0 { - comment.LikeCount = in.GetLikeCount() + updater = updater.SetLikeCount(int(in.GetLikeCount())) } - if in.GetDeletedAt() > 0 { - comment.DeletedAt = in.GetDeletedAt() + + n, err := updater.Save(l.ctx) + if err != nil { + logx.Errorf("updateComments err: %v", err) + return nil, errors.New("update comment failed") } - if in.GetCreatedAt() > 0 { - comment.CreatedAt = in.GetCreatedAt() + if n == 0 { + return nil, errors.New("comment not found") } return &pb.UpdateCommentsResp{}, nil diff --git a/app/community/rpc/internal/logic/updatePostLikesLogic.go b/app/community/rpc/internal/logic/updatePostLikesLogic.go index 998d806..b545b72 100644 --- a/app/community/rpc/internal/logic/updatePostLikesLogic.go +++ b/app/community/rpc/internal/logic/updatePostLikesLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/postlikes" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -28,21 +29,20 @@ func (l *UpdatePostLikesLogic) UpdatePostLikes(in *pb.UpdatePostLikesReq) (*pb.U if in.PostId == nil || in.UserId == nil { return nil, errors.New("postId and userId are required") } - postID := in.GetPostId() - userID := in.GetUserId() - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() - - if _, ok := store.Posts[postID]; !ok { - return nil, errors.New("post not found") + _, err := l.svcCtx.CommunityModelRO.PostLikes.Query(). + Where(postlikes.PostIDEQ(in.GetPostId()), postlikes.UserIDEQ(in.GetUserId())). + First(l.ctx) + if err != nil { + return nil, errors.New("post like not found") } - key := postLikeKey(postID, userID) - store.PostLikes[key] = &pb.PostLikes{ - PostId: postID, - UserId: userID, - CreatedAt: nowUnix(in.GetCreatedAt()), + + _, err = l.svcCtx.CommunityModelRW.PostLikes.Update(). + Where(postlikes.PostIDEQ(in.GetPostId()), postlikes.UserIDEQ(in.GetUserId())). + Save(l.ctx) + if err != nil { + logx.Errorf("updatePostLikes err: %v", err) + return nil, errors.New("update post like failed") } return &pb.UpdatePostLikesResp{}, nil diff --git a/app/community/rpc/internal/logic/updatePostsLogic.go b/app/community/rpc/internal/logic/updatePostsLogic.go index 2506670..d8152bc 100644 --- a/app/community/rpc/internal/logic/updatePostsLogic.go +++ b/app/community/rpc/internal/logic/updatePostsLogic.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "juwan-backend/app/community/rpc/internal/models/posts" "juwan-backend/app/community/rpc/internal/svc" "juwan-backend/app/community/rpc/pb" @@ -29,58 +30,51 @@ func (l *UpdatePostsLogic) UpdatePosts(in *pb.UpdatePostsReq) (*pb.UpdatePostsRe return nil, errors.New("id is required") } - store := l.svcCtx.Store - store.Mu.Lock() - defer store.Mu.Unlock() + updater := l.svcCtx.CommunityModelRW.Posts.Update(). + Where(posts.IDEQ(in.GetId()), posts.DeletedAtIsNil()) - post, ok := store.Posts[in.GetId()] - if !ok || post.GetDeletedAt() > 0 { + if in.AuthorId != nil { + updater = updater.SetAuthorID(in.GetAuthorId()) + } + if in.AuthorRole != nil { + updater = updater.SetAuthorRole(in.GetAuthorRole()) + } + if in.Title != nil { + updater = updater.SetTitle(in.GetTitle()) + } + if in.Content != nil { + updater = updater.SetContent(in.GetContent()) + } + if len(in.Images) > 0 { + updater = updater.SetImages(toTextArray(in.GetImages())) + } + if len(in.Tags) > 0 { + updater = updater.SetTags(toTextArray(in.GetTags())) + } + if in.LinkedOrderId != nil { + updater = updater.SetLinkedOrderID(in.GetLinkedOrderId()) + } + if in.QuotedPostId != nil { + updater = updater.SetQuotedPostID(in.GetQuotedPostId()) + } + if in.LikeCount != nil { + updater = updater.SetLikeCount(int(in.GetLikeCount())) + } + if in.CommentCount != nil { + updater = updater.SetCommentCount(int(in.GetCommentCount())) + } + if in.Pinned != nil { + updater = updater.SetPinned(in.GetPinned()) + } + + n, err := updater.Save(l.ctx) + if err != nil { + logx.Errorf("updatePosts err: %v", err) + return nil, errors.New("update post failed") + } + if n == 0 { return nil, errors.New("post not found") } - if in.AuthorId != nil { - post.AuthorId = in.GetAuthorId() - } - if in.AuthorRole != nil { - post.AuthorRole = in.GetAuthorRole() - } - if in.Title != nil { - post.Title = in.GetTitle() - } - if in.Content != nil { - post.Content = in.GetContent() - } - if len(in.Images) > 0 { - post.Images = append([]string(nil), in.GetImages()...) - } - if len(in.Tags) > 0 { - post.Tags = append([]string(nil), in.GetTags()...) - } - if in.LinkedOrderId != nil { - post.LinkedOrderId = in.GetLinkedOrderId() - } - if in.QuotedPostId != nil { - post.QuotedPostId = in.GetQuotedPostId() - } - if in.LikeCount != nil { - post.LikeCount = in.GetLikeCount() - } - if in.CommentCount != nil { - post.CommentCount = in.GetCommentCount() - } - if in.Pinned != nil { - post.Pinned = in.GetPinned() - } - if in.SearchText != nil { - post.SearchText = in.GetSearchText() - } - if in.DeletedAt != nil { - post.DeletedAt = in.GetDeletedAt() - } - if in.CreatedAt != nil { - post.CreatedAt = in.GetCreatedAt() - } - post.UpdatedAt = nowUnix(in.GetUpdatedAt()) - return &pb.UpdatePostsResp{}, nil } diff --git a/app/community/rpc/internal/models/client.go b/app/community/rpc/internal/models/client.go new file mode 100644 index 0000000..0566578 --- /dev/null +++ b/app/community/rpc/internal/models/client.go @@ -0,0 +1,770 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "juwan-backend/app/community/rpc/internal/models/migrate" + + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/posts" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // CommentLikes is the client for interacting with the CommentLikes builders. + CommentLikes *CommentLikesClient + // Comments is the client for interacting with the Comments builders. + Comments *CommentsClient + // PostLikes is the client for interacting with the PostLikes builders. + PostLikes *PostLikesClient + // Posts is the client for interacting with the Posts builders. + Posts *PostsClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.CommentLikes = NewCommentLikesClient(c.config) + c.Comments = NewCommentsClient(c.config) + c.PostLikes = NewPostLikesClient(c.config) + c.Posts = NewPostsClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("models: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + CommentLikes: NewCommentLikesClient(cfg), + Comments: NewCommentsClient(cfg), + PostLikes: NewPostLikesClient(cfg), + Posts: NewPostsClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + CommentLikes: NewCommentLikesClient(cfg), + Comments: NewCommentsClient(cfg), + PostLikes: NewPostLikesClient(cfg), + Posts: NewPostsClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// CommentLikes. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.CommentLikes.Use(hooks...) + c.Comments.Use(hooks...) + c.PostLikes.Use(hooks...) + c.Posts.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.CommentLikes.Intercept(interceptors...) + c.Comments.Intercept(interceptors...) + c.PostLikes.Intercept(interceptors...) + c.Posts.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *CommentLikesMutation: + return c.CommentLikes.mutate(ctx, m) + case *CommentsMutation: + return c.Comments.mutate(ctx, m) + case *PostLikesMutation: + return c.PostLikes.mutate(ctx, m) + case *PostsMutation: + return c.Posts.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// CommentLikesClient is a client for the CommentLikes schema. +type CommentLikesClient struct { + config +} + +// NewCommentLikesClient returns a client for the CommentLikes from the given config. +func NewCommentLikesClient(c config) *CommentLikesClient { + return &CommentLikesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `commentlikes.Hooks(f(g(h())))`. +func (c *CommentLikesClient) Use(hooks ...Hook) { + c.hooks.CommentLikes = append(c.hooks.CommentLikes, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `commentlikes.Intercept(f(g(h())))`. +func (c *CommentLikesClient) Intercept(interceptors ...Interceptor) { + c.inters.CommentLikes = append(c.inters.CommentLikes, interceptors...) +} + +// Create returns a builder for creating a CommentLikes entity. +func (c *CommentLikesClient) Create() *CommentLikesCreate { + mutation := newCommentLikesMutation(c.config, OpCreate) + return &CommentLikesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CommentLikes entities. +func (c *CommentLikesClient) CreateBulk(builders ...*CommentLikesCreate) *CommentLikesCreateBulk { + return &CommentLikesCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *CommentLikesClient) MapCreateBulk(slice any, setFunc func(*CommentLikesCreate, int)) *CommentLikesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CommentLikesCreateBulk{err: fmt.Errorf("calling to CommentLikesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CommentLikesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CommentLikesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CommentLikes. +func (c *CommentLikesClient) Update() *CommentLikesUpdate { + mutation := newCommentLikesMutation(c.config, OpUpdate) + return &CommentLikesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CommentLikesClient) UpdateOne(_m *CommentLikes) *CommentLikesUpdateOne { + mutation := newCommentLikesMutation(c.config, OpUpdateOne, withCommentLikes(_m)) + return &CommentLikesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CommentLikesClient) UpdateOneID(id int64) *CommentLikesUpdateOne { + mutation := newCommentLikesMutation(c.config, OpUpdateOne, withCommentLikesID(id)) + return &CommentLikesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CommentLikes. +func (c *CommentLikesClient) Delete() *CommentLikesDelete { + mutation := newCommentLikesMutation(c.config, OpDelete) + return &CommentLikesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CommentLikesClient) DeleteOne(_m *CommentLikes) *CommentLikesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CommentLikesClient) DeleteOneID(id int64) *CommentLikesDeleteOne { + builder := c.Delete().Where(commentlikes.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CommentLikesDeleteOne{builder} +} + +// Query returns a query builder for CommentLikes. +func (c *CommentLikesClient) Query() *CommentLikesQuery { + return &CommentLikesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCommentLikes}, + inters: c.Interceptors(), + } +} + +// Get returns a CommentLikes entity by its id. +func (c *CommentLikesClient) Get(ctx context.Context, id int64) (*CommentLikes, error) { + return c.Query().Where(commentlikes.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CommentLikesClient) GetX(ctx context.Context, id int64) *CommentLikes { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *CommentLikesClient) Hooks() []Hook { + return c.hooks.CommentLikes +} + +// Interceptors returns the client interceptors. +func (c *CommentLikesClient) Interceptors() []Interceptor { + return c.inters.CommentLikes +} + +func (c *CommentLikesClient) mutate(ctx context.Context, m *CommentLikesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CommentLikesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CommentLikesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CommentLikesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CommentLikesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown CommentLikes mutation op: %q", m.Op()) + } +} + +// CommentsClient is a client for the Comments schema. +type CommentsClient struct { + config +} + +// NewCommentsClient returns a client for the Comments from the given config. +func NewCommentsClient(c config) *CommentsClient { + return &CommentsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `comments.Hooks(f(g(h())))`. +func (c *CommentsClient) Use(hooks ...Hook) { + c.hooks.Comments = append(c.hooks.Comments, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `comments.Intercept(f(g(h())))`. +func (c *CommentsClient) Intercept(interceptors ...Interceptor) { + c.inters.Comments = append(c.inters.Comments, interceptors...) +} + +// Create returns a builder for creating a Comments entity. +func (c *CommentsClient) Create() *CommentsCreate { + mutation := newCommentsMutation(c.config, OpCreate) + return &CommentsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Comments entities. +func (c *CommentsClient) CreateBulk(builders ...*CommentsCreate) *CommentsCreateBulk { + return &CommentsCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *CommentsClient) MapCreateBulk(slice any, setFunc func(*CommentsCreate, int)) *CommentsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CommentsCreateBulk{err: fmt.Errorf("calling to CommentsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CommentsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CommentsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Comments. +func (c *CommentsClient) Update() *CommentsUpdate { + mutation := newCommentsMutation(c.config, OpUpdate) + return &CommentsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CommentsClient) UpdateOne(_m *Comments) *CommentsUpdateOne { + mutation := newCommentsMutation(c.config, OpUpdateOne, withComments(_m)) + return &CommentsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CommentsClient) UpdateOneID(id int64) *CommentsUpdateOne { + mutation := newCommentsMutation(c.config, OpUpdateOne, withCommentsID(id)) + return &CommentsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Comments. +func (c *CommentsClient) Delete() *CommentsDelete { + mutation := newCommentsMutation(c.config, OpDelete) + return &CommentsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CommentsClient) DeleteOne(_m *Comments) *CommentsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CommentsClient) DeleteOneID(id int64) *CommentsDeleteOne { + builder := c.Delete().Where(comments.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CommentsDeleteOne{builder} +} + +// Query returns a query builder for Comments. +func (c *CommentsClient) Query() *CommentsQuery { + return &CommentsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeComments}, + inters: c.Interceptors(), + } +} + +// Get returns a Comments entity by its id. +func (c *CommentsClient) Get(ctx context.Context, id int64) (*Comments, error) { + return c.Query().Where(comments.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CommentsClient) GetX(ctx context.Context, id int64) *Comments { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *CommentsClient) Hooks() []Hook { + return c.hooks.Comments +} + +// Interceptors returns the client interceptors. +func (c *CommentsClient) Interceptors() []Interceptor { + return c.inters.Comments +} + +func (c *CommentsClient) mutate(ctx context.Context, m *CommentsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CommentsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CommentsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CommentsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CommentsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Comments mutation op: %q", m.Op()) + } +} + +// PostLikesClient is a client for the PostLikes schema. +type PostLikesClient struct { + config +} + +// NewPostLikesClient returns a client for the PostLikes from the given config. +func NewPostLikesClient(c config) *PostLikesClient { + return &PostLikesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `postlikes.Hooks(f(g(h())))`. +func (c *PostLikesClient) Use(hooks ...Hook) { + c.hooks.PostLikes = append(c.hooks.PostLikes, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `postlikes.Intercept(f(g(h())))`. +func (c *PostLikesClient) Intercept(interceptors ...Interceptor) { + c.inters.PostLikes = append(c.inters.PostLikes, interceptors...) +} + +// Create returns a builder for creating a PostLikes entity. +func (c *PostLikesClient) Create() *PostLikesCreate { + mutation := newPostLikesMutation(c.config, OpCreate) + return &PostLikesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of PostLikes entities. +func (c *PostLikesClient) CreateBulk(builders ...*PostLikesCreate) *PostLikesCreateBulk { + return &PostLikesCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *PostLikesClient) MapCreateBulk(slice any, setFunc func(*PostLikesCreate, int)) *PostLikesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &PostLikesCreateBulk{err: fmt.Errorf("calling to PostLikesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*PostLikesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &PostLikesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for PostLikes. +func (c *PostLikesClient) Update() *PostLikesUpdate { + mutation := newPostLikesMutation(c.config, OpUpdate) + return &PostLikesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PostLikesClient) UpdateOne(_m *PostLikes) *PostLikesUpdateOne { + mutation := newPostLikesMutation(c.config, OpUpdateOne, withPostLikes(_m)) + return &PostLikesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PostLikesClient) UpdateOneID(id int64) *PostLikesUpdateOne { + mutation := newPostLikesMutation(c.config, OpUpdateOne, withPostLikesID(id)) + return &PostLikesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for PostLikes. +func (c *PostLikesClient) Delete() *PostLikesDelete { + mutation := newPostLikesMutation(c.config, OpDelete) + return &PostLikesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *PostLikesClient) DeleteOne(_m *PostLikes) *PostLikesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *PostLikesClient) DeleteOneID(id int64) *PostLikesDeleteOne { + builder := c.Delete().Where(postlikes.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PostLikesDeleteOne{builder} +} + +// Query returns a query builder for PostLikes. +func (c *PostLikesClient) Query() *PostLikesQuery { + return &PostLikesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypePostLikes}, + inters: c.Interceptors(), + } +} + +// Get returns a PostLikes entity by its id. +func (c *PostLikesClient) Get(ctx context.Context, id int64) (*PostLikes, error) { + return c.Query().Where(postlikes.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PostLikesClient) GetX(ctx context.Context, id int64) *PostLikes { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *PostLikesClient) Hooks() []Hook { + return c.hooks.PostLikes +} + +// Interceptors returns the client interceptors. +func (c *PostLikesClient) Interceptors() []Interceptor { + return c.inters.PostLikes +} + +func (c *PostLikesClient) mutate(ctx context.Context, m *PostLikesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&PostLikesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&PostLikesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&PostLikesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&PostLikesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown PostLikes mutation op: %q", m.Op()) + } +} + +// PostsClient is a client for the Posts schema. +type PostsClient struct { + config +} + +// NewPostsClient returns a client for the Posts from the given config. +func NewPostsClient(c config) *PostsClient { + return &PostsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `posts.Hooks(f(g(h())))`. +func (c *PostsClient) Use(hooks ...Hook) { + c.hooks.Posts = append(c.hooks.Posts, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `posts.Intercept(f(g(h())))`. +func (c *PostsClient) Intercept(interceptors ...Interceptor) { + c.inters.Posts = append(c.inters.Posts, interceptors...) +} + +// Create returns a builder for creating a Posts entity. +func (c *PostsClient) Create() *PostsCreate { + mutation := newPostsMutation(c.config, OpCreate) + return &PostsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Posts entities. +func (c *PostsClient) CreateBulk(builders ...*PostsCreate) *PostsCreateBulk { + return &PostsCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *PostsClient) MapCreateBulk(slice any, setFunc func(*PostsCreate, int)) *PostsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &PostsCreateBulk{err: fmt.Errorf("calling to PostsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*PostsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &PostsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Posts. +func (c *PostsClient) Update() *PostsUpdate { + mutation := newPostsMutation(c.config, OpUpdate) + return &PostsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PostsClient) UpdateOne(_m *Posts) *PostsUpdateOne { + mutation := newPostsMutation(c.config, OpUpdateOne, withPosts(_m)) + return &PostsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PostsClient) UpdateOneID(id int64) *PostsUpdateOne { + mutation := newPostsMutation(c.config, OpUpdateOne, withPostsID(id)) + return &PostsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Posts. +func (c *PostsClient) Delete() *PostsDelete { + mutation := newPostsMutation(c.config, OpDelete) + return &PostsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *PostsClient) DeleteOne(_m *Posts) *PostsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *PostsClient) DeleteOneID(id int64) *PostsDeleteOne { + builder := c.Delete().Where(posts.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PostsDeleteOne{builder} +} + +// Query returns a query builder for Posts. +func (c *PostsClient) Query() *PostsQuery { + return &PostsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypePosts}, + inters: c.Interceptors(), + } +} + +// Get returns a Posts entity by its id. +func (c *PostsClient) Get(ctx context.Context, id int64) (*Posts, error) { + return c.Query().Where(posts.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PostsClient) GetX(ctx context.Context, id int64) *Posts { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *PostsClient) Hooks() []Hook { + return c.hooks.Posts +} + +// Interceptors returns the client interceptors. +func (c *PostsClient) Interceptors() []Interceptor { + return c.inters.Posts +} + +func (c *PostsClient) mutate(ctx context.Context, m *PostsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&PostsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&PostsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&PostsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&PostsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Posts mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + CommentLikes, Comments, PostLikes, Posts []ent.Hook + } + inters struct { + CommentLikes, Comments, PostLikes, Posts []ent.Interceptor + } +) diff --git a/app/community/rpc/internal/models/commentlikes.go b/app/community/rpc/internal/models/commentlikes.go new file mode 100644 index 0000000..de87173 --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes.go @@ -0,0 +1,126 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// CommentLikes is the model entity for the CommentLikes schema. +type CommentLikes struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // CommentID holds the value of the "comment_id" field. + CommentID int64 `json:"comment_id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CommentLikes) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case commentlikes.FieldID, commentlikes.FieldCommentID, commentlikes.FieldUserID: + values[i] = new(sql.NullInt64) + case commentlikes.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the CommentLikes fields. +func (_m *CommentLikes) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case commentlikes.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case commentlikes.FieldCommentID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field comment_id", values[i]) + } else if value.Valid { + _m.CommentID = value.Int64 + } + case commentlikes.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = value.Int64 + } + case commentlikes.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the CommentLikes. +// This includes values selected through modifiers, order, etc. +func (_m *CommentLikes) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this CommentLikes. +// Note that you need to call CommentLikes.Unwrap() before calling this method if this CommentLikes +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *CommentLikes) Update() *CommentLikesUpdateOne { + return NewCommentLikesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the CommentLikes entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *CommentLikes) Unwrap() *CommentLikes { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: CommentLikes is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *CommentLikes) String() string { + var builder strings.Builder + builder.WriteString("CommentLikes(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("comment_id=") + builder.WriteString(fmt.Sprintf("%v", _m.CommentID)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// CommentLikesSlice is a parsable slice of CommentLikes. +type CommentLikesSlice []*CommentLikes diff --git a/app/community/rpc/internal/models/commentlikes/commentlikes.go b/app/community/rpc/internal/models/commentlikes/commentlikes.go new file mode 100644 index 0000000..489a924 --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes/commentlikes.go @@ -0,0 +1,70 @@ +// Code generated by ent, DO NOT EDIT. + +package commentlikes + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the commentlikes type in the database. + Label = "comment_likes" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCommentID holds the string denoting the comment_id field in the database. + FieldCommentID = "comment_id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the commentlikes in the database. + Table = "comment_likes" +) + +// Columns holds all SQL columns for commentlikes fields. +var Columns = []string{ + FieldID, + FieldCommentID, + FieldUserID, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the CommentLikes queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByCommentID orders the results by the comment_id field. +func ByCommentID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCommentID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} diff --git a/app/community/rpc/internal/models/commentlikes/where.go b/app/community/rpc/internal/models/commentlikes/where.go new file mode 100644 index 0000000..b964cc5 --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes/where.go @@ -0,0 +1,205 @@ +// Code generated by ent, DO NOT EDIT. + +package commentlikes + +import ( + "juwan-backend/app/community/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLTE(FieldID, id)) +} + +// CommentID applies equality check predicate on the "comment_id" field. It's identical to CommentIDEQ. +func CommentID(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldCommentID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldUserID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CommentIDEQ applies the EQ predicate on the "comment_id" field. +func CommentIDEQ(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldCommentID, v)) +} + +// CommentIDNEQ applies the NEQ predicate on the "comment_id" field. +func CommentIDNEQ(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNEQ(FieldCommentID, v)) +} + +// CommentIDIn applies the In predicate on the "comment_id" field. +func CommentIDIn(vs ...int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldIn(FieldCommentID, vs...)) +} + +// CommentIDNotIn applies the NotIn predicate on the "comment_id" field. +func CommentIDNotIn(vs ...int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNotIn(FieldCommentID, vs...)) +} + +// CommentIDGT applies the GT predicate on the "comment_id" field. +func CommentIDGT(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGT(FieldCommentID, v)) +} + +// CommentIDGTE applies the GTE predicate on the "comment_id" field. +func CommentIDGTE(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGTE(FieldCommentID, v)) +} + +// CommentIDLT applies the LT predicate on the "comment_id" field. +func CommentIDLT(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLT(FieldCommentID, v)) +} + +// CommentIDLTE applies the LTE predicate on the "comment_id" field. +func CommentIDLTE(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLTE(FieldCommentID, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int64) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLTE(FieldUserID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.CommentLikes { + return predicate.CommentLikes(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.CommentLikes) predicate.CommentLikes { + return predicate.CommentLikes(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CommentLikes) predicate.CommentLikes { + return predicate.CommentLikes(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CommentLikes) predicate.CommentLikes { + return predicate.CommentLikes(sql.NotPredicates(p)) +} diff --git a/app/community/rpc/internal/models/commentlikes_create.go b/app/community/rpc/internal/models/commentlikes_create.go new file mode 100644 index 0000000..c510b8e --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes_create.go @@ -0,0 +1,240 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentLikesCreate is the builder for creating a CommentLikes entity. +type CommentLikesCreate struct { + config + mutation *CommentLikesMutation + hooks []Hook +} + +// SetCommentID sets the "comment_id" field. +func (_c *CommentLikesCreate) SetCommentID(v int64) *CommentLikesCreate { + _c.mutation.SetCommentID(v) + return _c +} + +// SetUserID sets the "user_id" field. +func (_c *CommentLikesCreate) SetUserID(v int64) *CommentLikesCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CommentLikesCreate) SetCreatedAt(v time.Time) *CommentLikesCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CommentLikesCreate) SetNillableCreatedAt(v *time.Time) *CommentLikesCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *CommentLikesCreate) SetID(v int64) *CommentLikesCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the CommentLikesMutation object of the builder. +func (_c *CommentLikesCreate) Mutation() *CommentLikesMutation { + return _c.mutation +} + +// Save creates the CommentLikes in the database. +func (_c *CommentLikesCreate) Save(ctx context.Context) (*CommentLikes, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CommentLikesCreate) SaveX(ctx context.Context) *CommentLikes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CommentLikesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CommentLikesCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *CommentLikesCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := commentlikes.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CommentLikesCreate) check() error { + if _, ok := _c.mutation.CommentID(); !ok { + return &ValidationError{Name: "comment_id", err: errors.New(`models: missing required field "CommentLikes.comment_id"`)} + } + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "CommentLikes.user_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "CommentLikes.created_at"`)} + } + return nil +} + +func (_c *CommentLikesCreate) sqlSave(ctx context.Context) (*CommentLikes, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CommentLikesCreate) createSpec() (*CommentLikes, *sqlgraph.CreateSpec) { + var ( + _node = &CommentLikes{config: _c.config} + _spec = sqlgraph.NewCreateSpec(commentlikes.Table, sqlgraph.NewFieldSpec(commentlikes.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.CommentID(); ok { + _spec.SetField(commentlikes.FieldCommentID, field.TypeInt64, value) + _node.CommentID = value + } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(commentlikes.FieldUserID, field.TypeInt64, value) + _node.UserID = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(commentlikes.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// CommentLikesCreateBulk is the builder for creating many CommentLikes entities in bulk. +type CommentLikesCreateBulk struct { + config + err error + builders []*CommentLikesCreate +} + +// Save creates the CommentLikes entities in the database. +func (_c *CommentLikesCreateBulk) Save(ctx context.Context) ([]*CommentLikes, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*CommentLikes, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentLikesMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *CommentLikesCreateBulk) SaveX(ctx context.Context) []*CommentLikes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CommentLikesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CommentLikesCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/commentlikes_delete.go b/app/community/rpc/internal/models/commentlikes_delete.go new file mode 100644 index 0000000..c7d26c4 --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentLikesDelete is the builder for deleting a CommentLikes entity. +type CommentLikesDelete struct { + config + hooks []Hook + mutation *CommentLikesMutation +} + +// Where appends a list predicates to the CommentLikesDelete builder. +func (_d *CommentLikesDelete) Where(ps ...predicate.CommentLikes) *CommentLikesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CommentLikesDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CommentLikesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CommentLikesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(commentlikes.Table, sqlgraph.NewFieldSpec(commentlikes.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// CommentLikesDeleteOne is the builder for deleting a single CommentLikes entity. +type CommentLikesDeleteOne struct { + _d *CommentLikesDelete +} + +// Where appends a list predicates to the CommentLikesDelete builder. +func (_d *CommentLikesDeleteOne) Where(ps ...predicate.CommentLikes) *CommentLikesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CommentLikesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{commentlikes.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CommentLikesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/commentlikes_query.go b/app/community/rpc/internal/models/commentlikes_query.go new file mode 100644 index 0000000..6e65df0 --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentLikesQuery is the builder for querying CommentLikes entities. +type CommentLikesQuery struct { + config + ctx *QueryContext + order []commentlikes.OrderOption + inters []Interceptor + predicates []predicate.CommentLikes + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the CommentLikesQuery builder. +func (_q *CommentLikesQuery) Where(ps ...predicate.CommentLikes) *CommentLikesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CommentLikesQuery) Limit(limit int) *CommentLikesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CommentLikesQuery) Offset(offset int) *CommentLikesQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *CommentLikesQuery) Unique(unique bool) *CommentLikesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CommentLikesQuery) Order(o ...commentlikes.OrderOption) *CommentLikesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first CommentLikes entity from the query. +// Returns a *NotFoundError when no CommentLikes was found. +func (_q *CommentLikesQuery) First(ctx context.Context) (*CommentLikes, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{commentlikes.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CommentLikesQuery) FirstX(ctx context.Context) *CommentLikes { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CommentLikes ID from the query. +// Returns a *NotFoundError when no CommentLikes ID was found. +func (_q *CommentLikesQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{commentlikes.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CommentLikesQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CommentLikes entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CommentLikes entity is found. +// Returns a *NotFoundError when no CommentLikes entities are found. +func (_q *CommentLikesQuery) Only(ctx context.Context) (*CommentLikes, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{commentlikes.Label} + default: + return nil, &NotSingularError{commentlikes.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CommentLikesQuery) OnlyX(ctx context.Context) *CommentLikes { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CommentLikes ID in the query. +// Returns a *NotSingularError when more than one CommentLikes ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CommentLikesQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{commentlikes.Label} + default: + err = &NotSingularError{commentlikes.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CommentLikesQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of CommentLikesSlice. +func (_q *CommentLikesQuery) All(ctx context.Context) ([]*CommentLikes, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CommentLikes, *CommentLikesQuery]() + return withInterceptors[[]*CommentLikes](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CommentLikesQuery) AllX(ctx context.Context) []*CommentLikes { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CommentLikes IDs. +func (_q *CommentLikesQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(commentlikes.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CommentLikesQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *CommentLikesQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*CommentLikesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CommentLikesQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *CommentLikesQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *CommentLikesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CommentLikesQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *CommentLikesQuery) Clone() *CommentLikesQuery { + if _q == nil { + return nil + } + return &CommentLikesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]commentlikes.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.CommentLikes{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CommentID int64 `json:"comment_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.CommentLikes.Query(). +// GroupBy(commentlikes.FieldCommentID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *CommentLikesQuery) GroupBy(field string, fields ...string) *CommentLikesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CommentLikesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = commentlikes.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// CommentID int64 `json:"comment_id,omitempty"` +// } +// +// client.CommentLikes.Query(). +// Select(commentlikes.FieldCommentID). +// Scan(ctx, &v) +func (_q *CommentLikesQuery) Select(fields ...string) *CommentLikesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CommentLikesSelect{CommentLikesQuery: _q} + sbuild.label = commentlikes.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CommentLikesSelect configured with the given aggregations. +func (_q *CommentLikesQuery) Aggregate(fns ...AggregateFunc) *CommentLikesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CommentLikesQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !commentlikes.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *CommentLikesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CommentLikes, error) { + var ( + nodes = []*CommentLikes{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CommentLikes).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CommentLikes{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *CommentLikesQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *CommentLikesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(commentlikes.Table, commentlikes.Columns, sqlgraph.NewFieldSpec(commentlikes.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, commentlikes.FieldID) + for i := range fields { + if fields[i] != commentlikes.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *CommentLikesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(commentlikes.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = commentlikes.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// CommentLikesGroupBy is the group-by builder for CommentLikes entities. +type CommentLikesGroupBy struct { + selector + build *CommentLikesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CommentLikesGroupBy) Aggregate(fns ...AggregateFunc) *CommentLikesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CommentLikesGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CommentLikesQuery, *CommentLikesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CommentLikesGroupBy) sqlScan(ctx context.Context, root *CommentLikesQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// CommentLikesSelect is the builder for selecting fields of CommentLikes entities. +type CommentLikesSelect struct { + *CommentLikesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CommentLikesSelect) Aggregate(fns ...AggregateFunc) *CommentLikesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CommentLikesSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CommentLikesQuery, *CommentLikesSelect](ctx, _s.CommentLikesQuery, _s, _s.inters, v) +} + +func (_s *CommentLikesSelect) sqlScan(ctx context.Context, root *CommentLikesQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/community/rpc/internal/models/commentlikes_update.go b/app/community/rpc/internal/models/commentlikes_update.go new file mode 100644 index 0000000..a6ef996 --- /dev/null +++ b/app/community/rpc/internal/models/commentlikes_update.go @@ -0,0 +1,283 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentLikesUpdate is the builder for updating CommentLikes entities. +type CommentLikesUpdate struct { + config + hooks []Hook + mutation *CommentLikesMutation +} + +// Where appends a list predicates to the CommentLikesUpdate builder. +func (_u *CommentLikesUpdate) Where(ps ...predicate.CommentLikes) *CommentLikesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetCommentID sets the "comment_id" field. +func (_u *CommentLikesUpdate) SetCommentID(v int64) *CommentLikesUpdate { + _u.mutation.ResetCommentID() + _u.mutation.SetCommentID(v) + return _u +} + +// SetNillableCommentID sets the "comment_id" field if the given value is not nil. +func (_u *CommentLikesUpdate) SetNillableCommentID(v *int64) *CommentLikesUpdate { + if v != nil { + _u.SetCommentID(*v) + } + return _u +} + +// AddCommentID adds value to the "comment_id" field. +func (_u *CommentLikesUpdate) AddCommentID(v int64) *CommentLikesUpdate { + _u.mutation.AddCommentID(v) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *CommentLikesUpdate) SetUserID(v int64) *CommentLikesUpdate { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *CommentLikesUpdate) SetNillableUserID(v *int64) *CommentLikesUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *CommentLikesUpdate) AddUserID(v int64) *CommentLikesUpdate { + _u.mutation.AddUserID(v) + return _u +} + +// Mutation returns the CommentLikesMutation object of the builder. +func (_u *CommentLikesUpdate) Mutation() *CommentLikesMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CommentLikesUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CommentLikesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CommentLikesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CommentLikesUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *CommentLikesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(commentlikes.Table, commentlikes.Columns, sqlgraph.NewFieldSpec(commentlikes.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.CommentID(); ok { + _spec.SetField(commentlikes.FieldCommentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedCommentID(); ok { + _spec.AddField(commentlikes.FieldCommentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(commentlikes.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(commentlikes.FieldUserID, field.TypeInt64, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{commentlikes.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CommentLikesUpdateOne is the builder for updating a single CommentLikes entity. +type CommentLikesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CommentLikesMutation +} + +// SetCommentID sets the "comment_id" field. +func (_u *CommentLikesUpdateOne) SetCommentID(v int64) *CommentLikesUpdateOne { + _u.mutation.ResetCommentID() + _u.mutation.SetCommentID(v) + return _u +} + +// SetNillableCommentID sets the "comment_id" field if the given value is not nil. +func (_u *CommentLikesUpdateOne) SetNillableCommentID(v *int64) *CommentLikesUpdateOne { + if v != nil { + _u.SetCommentID(*v) + } + return _u +} + +// AddCommentID adds value to the "comment_id" field. +func (_u *CommentLikesUpdateOne) AddCommentID(v int64) *CommentLikesUpdateOne { + _u.mutation.AddCommentID(v) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *CommentLikesUpdateOne) SetUserID(v int64) *CommentLikesUpdateOne { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *CommentLikesUpdateOne) SetNillableUserID(v *int64) *CommentLikesUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *CommentLikesUpdateOne) AddUserID(v int64) *CommentLikesUpdateOne { + _u.mutation.AddUserID(v) + return _u +} + +// Mutation returns the CommentLikesMutation object of the builder. +func (_u *CommentLikesUpdateOne) Mutation() *CommentLikesMutation { + return _u.mutation +} + +// Where appends a list predicates to the CommentLikesUpdate builder. +func (_u *CommentLikesUpdateOne) Where(ps ...predicate.CommentLikes) *CommentLikesUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *CommentLikesUpdateOne) Select(field string, fields ...string) *CommentLikesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated CommentLikes entity. +func (_u *CommentLikesUpdateOne) Save(ctx context.Context) (*CommentLikes, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CommentLikesUpdateOne) SaveX(ctx context.Context) *CommentLikes { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CommentLikesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CommentLikesUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *CommentLikesUpdateOne) sqlSave(ctx context.Context) (_node *CommentLikes, err error) { + _spec := sqlgraph.NewUpdateSpec(commentlikes.Table, commentlikes.Columns, sqlgraph.NewFieldSpec(commentlikes.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "CommentLikes.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, commentlikes.FieldID) + for _, f := range fields { + if !commentlikes.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != commentlikes.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.CommentID(); ok { + _spec.SetField(commentlikes.FieldCommentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedCommentID(); ok { + _spec.AddField(commentlikes.FieldCommentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(commentlikes.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(commentlikes.FieldUserID, field.TypeInt64, value) + } + _node = &CommentLikes{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{commentlikes.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/community/rpc/internal/models/comments.go b/app/community/rpc/internal/models/comments.go new file mode 100644 index 0000000..a78a5ac --- /dev/null +++ b/app/community/rpc/internal/models/comments.go @@ -0,0 +1,164 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/community/rpc/internal/models/comments" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Comments is the model entity for the Comments schema. +type Comments struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // PostID holds the value of the "post_id" field. + PostID int64 `json:"post_id,omitempty"` + // AuthorID holds the value of the "author_id" field. + AuthorID int64 `json:"author_id,omitempty"` + // Content holds the value of the "content" field. + Content string `json:"content,omitempty"` + // LikeCount holds the value of the "like_count" field. + LikeCount int `json:"like_count,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Comments) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case comments.FieldID, comments.FieldPostID, comments.FieldAuthorID, comments.FieldLikeCount: + values[i] = new(sql.NullInt64) + case comments.FieldContent: + values[i] = new(sql.NullString) + case comments.FieldCreatedAt, comments.FieldDeletedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Comments fields. +func (_m *Comments) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case comments.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case comments.FieldPostID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field post_id", values[i]) + } else if value.Valid { + _m.PostID = value.Int64 + } + case comments.FieldAuthorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field author_id", values[i]) + } else if value.Valid { + _m.AuthorID = value.Int64 + } + case comments.FieldContent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content", values[i]) + } else if value.Valid { + _m.Content = value.String + } + case comments.FieldLikeCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field like_count", values[i]) + } else if value.Valid { + _m.LikeCount = int(value.Int64) + } + case comments.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case comments.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = new(time.Time) + *_m.DeletedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Comments. +// This includes values selected through modifiers, order, etc. +func (_m *Comments) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Comments. +// Note that you need to call Comments.Unwrap() before calling this method if this Comments +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Comments) Update() *CommentsUpdateOne { + return NewCommentsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Comments entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Comments) Unwrap() *Comments { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Comments is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Comments) String() string { + var builder strings.Builder + builder.WriteString("Comments(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("post_id=") + builder.WriteString(fmt.Sprintf("%v", _m.PostID)) + builder.WriteString(", ") + builder.WriteString("author_id=") + builder.WriteString(fmt.Sprintf("%v", _m.AuthorID)) + builder.WriteString(", ") + builder.WriteString("content=") + builder.WriteString(_m.Content) + builder.WriteString(", ") + builder.WriteString("like_count=") + builder.WriteString(fmt.Sprintf("%v", _m.LikeCount)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// CommentsSlice is a parsable slice of Comments. +type CommentsSlice []*Comments diff --git a/app/community/rpc/internal/models/comments/comments.go b/app/community/rpc/internal/models/comments/comments.go new file mode 100644 index 0000000..f2a9187 --- /dev/null +++ b/app/community/rpc/internal/models/comments/comments.go @@ -0,0 +1,96 @@ +// Code generated by ent, DO NOT EDIT. + +package comments + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the comments type in the database. + Label = "comments" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPostID holds the string denoting the post_id field in the database. + FieldPostID = "post_id" + // FieldAuthorID holds the string denoting the author_id field in the database. + FieldAuthorID = "author_id" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + // FieldLikeCount holds the string denoting the like_count field in the database. + FieldLikeCount = "like_count" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // Table holds the table name of the comments in the database. + Table = "comments" +) + +// Columns holds all SQL columns for comments fields. +var Columns = []string{ + FieldID, + FieldPostID, + FieldAuthorID, + FieldContent, + FieldLikeCount, + FieldCreatedAt, + FieldDeletedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultLikeCount holds the default value on creation for the "like_count" field. + DefaultLikeCount int + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Comments queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByPostID orders the results by the post_id field. +func ByPostID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPostID, opts...).ToFunc() +} + +// ByAuthorID orders the results by the author_id field. +func ByAuthorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorID, opts...).ToFunc() +} + +// ByContent orders the results by the content field. +func ByContent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContent, opts...).ToFunc() +} + +// ByLikeCount orders the results by the like_count field. +func ByLikeCount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLikeCount, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} diff --git a/app/community/rpc/internal/models/comments/where.go b/app/community/rpc/internal/models/comments/where.go new file mode 100644 index 0000000..ef932bd --- /dev/null +++ b/app/community/rpc/internal/models/comments/where.go @@ -0,0 +1,385 @@ +// Code generated by ent, DO NOT EDIT. + +package comments + +import ( + "juwan-backend/app/community/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldID, id)) +} + +// PostID applies equality check predicate on the "post_id" field. It's identical to PostIDEQ. +func PostID(v int64) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldPostID, v)) +} + +// AuthorID applies equality check predicate on the "author_id" field. It's identical to AuthorIDEQ. +func AuthorID(v int64) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldAuthorID, v)) +} + +// Content applies equality check predicate on the "content" field. It's identical to ContentEQ. +func Content(v string) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldContent, v)) +} + +// LikeCount applies equality check predicate on the "like_count" field. It's identical to LikeCountEQ. +func LikeCount(v int) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldLikeCount, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldCreatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldDeletedAt, v)) +} + +// PostIDEQ applies the EQ predicate on the "post_id" field. +func PostIDEQ(v int64) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldPostID, v)) +} + +// PostIDNEQ applies the NEQ predicate on the "post_id" field. +func PostIDNEQ(v int64) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldPostID, v)) +} + +// PostIDIn applies the In predicate on the "post_id" field. +func PostIDIn(vs ...int64) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldPostID, vs...)) +} + +// PostIDNotIn applies the NotIn predicate on the "post_id" field. +func PostIDNotIn(vs ...int64) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldPostID, vs...)) +} + +// PostIDGT applies the GT predicate on the "post_id" field. +func PostIDGT(v int64) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldPostID, v)) +} + +// PostIDGTE applies the GTE predicate on the "post_id" field. +func PostIDGTE(v int64) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldPostID, v)) +} + +// PostIDLT applies the LT predicate on the "post_id" field. +func PostIDLT(v int64) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldPostID, v)) +} + +// PostIDLTE applies the LTE predicate on the "post_id" field. +func PostIDLTE(v int64) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldPostID, v)) +} + +// AuthorIDEQ applies the EQ predicate on the "author_id" field. +func AuthorIDEQ(v int64) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldAuthorID, v)) +} + +// AuthorIDNEQ applies the NEQ predicate on the "author_id" field. +func AuthorIDNEQ(v int64) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldAuthorID, v)) +} + +// AuthorIDIn applies the In predicate on the "author_id" field. +func AuthorIDIn(vs ...int64) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldAuthorID, vs...)) +} + +// AuthorIDNotIn applies the NotIn predicate on the "author_id" field. +func AuthorIDNotIn(vs ...int64) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldAuthorID, vs...)) +} + +// AuthorIDGT applies the GT predicate on the "author_id" field. +func AuthorIDGT(v int64) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldAuthorID, v)) +} + +// AuthorIDGTE applies the GTE predicate on the "author_id" field. +func AuthorIDGTE(v int64) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldAuthorID, v)) +} + +// AuthorIDLT applies the LT predicate on the "author_id" field. +func AuthorIDLT(v int64) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldAuthorID, v)) +} + +// AuthorIDLTE applies the LTE predicate on the "author_id" field. +func AuthorIDLTE(v int64) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldAuthorID, v)) +} + +// ContentEQ applies the EQ predicate on the "content" field. +func ContentEQ(v string) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldContent, v)) +} + +// ContentNEQ applies the NEQ predicate on the "content" field. +func ContentNEQ(v string) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldContent, v)) +} + +// ContentIn applies the In predicate on the "content" field. +func ContentIn(vs ...string) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldContent, vs...)) +} + +// ContentNotIn applies the NotIn predicate on the "content" field. +func ContentNotIn(vs ...string) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldContent, vs...)) +} + +// ContentGT applies the GT predicate on the "content" field. +func ContentGT(v string) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldContent, v)) +} + +// ContentGTE applies the GTE predicate on the "content" field. +func ContentGTE(v string) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldContent, v)) +} + +// ContentLT applies the LT predicate on the "content" field. +func ContentLT(v string) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldContent, v)) +} + +// ContentLTE applies the LTE predicate on the "content" field. +func ContentLTE(v string) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldContent, v)) +} + +// ContentContains applies the Contains predicate on the "content" field. +func ContentContains(v string) predicate.Comments { + return predicate.Comments(sql.FieldContains(FieldContent, v)) +} + +// ContentHasPrefix applies the HasPrefix predicate on the "content" field. +func ContentHasPrefix(v string) predicate.Comments { + return predicate.Comments(sql.FieldHasPrefix(FieldContent, v)) +} + +// ContentHasSuffix applies the HasSuffix predicate on the "content" field. +func ContentHasSuffix(v string) predicate.Comments { + return predicate.Comments(sql.FieldHasSuffix(FieldContent, v)) +} + +// ContentEqualFold applies the EqualFold predicate on the "content" field. +func ContentEqualFold(v string) predicate.Comments { + return predicate.Comments(sql.FieldEqualFold(FieldContent, v)) +} + +// ContentContainsFold applies the ContainsFold predicate on the "content" field. +func ContentContainsFold(v string) predicate.Comments { + return predicate.Comments(sql.FieldContainsFold(FieldContent, v)) +} + +// LikeCountEQ applies the EQ predicate on the "like_count" field. +func LikeCountEQ(v int) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldLikeCount, v)) +} + +// LikeCountNEQ applies the NEQ predicate on the "like_count" field. +func LikeCountNEQ(v int) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldLikeCount, v)) +} + +// LikeCountIn applies the In predicate on the "like_count" field. +func LikeCountIn(vs ...int) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldLikeCount, vs...)) +} + +// LikeCountNotIn applies the NotIn predicate on the "like_count" field. +func LikeCountNotIn(vs ...int) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldLikeCount, vs...)) +} + +// LikeCountGT applies the GT predicate on the "like_count" field. +func LikeCountGT(v int) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldLikeCount, v)) +} + +// LikeCountGTE applies the GTE predicate on the "like_count" field. +func LikeCountGTE(v int) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldLikeCount, v)) +} + +// LikeCountLT applies the LT predicate on the "like_count" field. +func LikeCountLT(v int) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldLikeCount, v)) +} + +// LikeCountLTE applies the LTE predicate on the "like_count" field. +func LikeCountLTE(v int) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldLikeCount, v)) +} + +// LikeCountIsNil applies the IsNil predicate on the "like_count" field. +func LikeCountIsNil() predicate.Comments { + return predicate.Comments(sql.FieldIsNull(FieldLikeCount)) +} + +// LikeCountNotNil applies the NotNil predicate on the "like_count" field. +func LikeCountNotNil() predicate.Comments { + return predicate.Comments(sql.FieldNotNull(FieldLikeCount)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldCreatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Comments { + return predicate.Comments(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Comments { + return predicate.Comments(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Comments { + return predicate.Comments(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Comments { + return predicate.Comments(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Comments { + return predicate.Comments(sql.FieldNotNull(FieldDeletedAt)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Comments) predicate.Comments { + return predicate.Comments(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Comments) predicate.Comments { + return predicate.Comments(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Comments) predicate.Comments { + return predicate.Comments(sql.NotPredicates(p)) +} diff --git a/app/community/rpc/internal/models/comments_create.go b/app/community/rpc/internal/models/comments_create.go new file mode 100644 index 0000000..85cf1d6 --- /dev/null +++ b/app/community/rpc/internal/models/comments_create.go @@ -0,0 +1,293 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/comments" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentsCreate is the builder for creating a Comments entity. +type CommentsCreate struct { + config + mutation *CommentsMutation + hooks []Hook +} + +// SetPostID sets the "post_id" field. +func (_c *CommentsCreate) SetPostID(v int64) *CommentsCreate { + _c.mutation.SetPostID(v) + return _c +} + +// SetAuthorID sets the "author_id" field. +func (_c *CommentsCreate) SetAuthorID(v int64) *CommentsCreate { + _c.mutation.SetAuthorID(v) + return _c +} + +// SetContent sets the "content" field. +func (_c *CommentsCreate) SetContent(v string) *CommentsCreate { + _c.mutation.SetContent(v) + return _c +} + +// SetLikeCount sets the "like_count" field. +func (_c *CommentsCreate) SetLikeCount(v int) *CommentsCreate { + _c.mutation.SetLikeCount(v) + return _c +} + +// SetNillableLikeCount sets the "like_count" field if the given value is not nil. +func (_c *CommentsCreate) SetNillableLikeCount(v *int) *CommentsCreate { + if v != nil { + _c.SetLikeCount(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CommentsCreate) SetCreatedAt(v time.Time) *CommentsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CommentsCreate) SetNillableCreatedAt(v *time.Time) *CommentsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *CommentsCreate) SetDeletedAt(v time.Time) *CommentsCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *CommentsCreate) SetNillableDeletedAt(v *time.Time) *CommentsCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *CommentsCreate) SetID(v int64) *CommentsCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the CommentsMutation object of the builder. +func (_c *CommentsCreate) Mutation() *CommentsMutation { + return _c.mutation +} + +// Save creates the Comments in the database. +func (_c *CommentsCreate) Save(ctx context.Context) (*Comments, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CommentsCreate) SaveX(ctx context.Context) *Comments { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CommentsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CommentsCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *CommentsCreate) defaults() { + if _, ok := _c.mutation.LikeCount(); !ok { + v := comments.DefaultLikeCount + _c.mutation.SetLikeCount(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := comments.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CommentsCreate) check() error { + if _, ok := _c.mutation.PostID(); !ok { + return &ValidationError{Name: "post_id", err: errors.New(`models: missing required field "Comments.post_id"`)} + } + if _, ok := _c.mutation.AuthorID(); !ok { + return &ValidationError{Name: "author_id", err: errors.New(`models: missing required field "Comments.author_id"`)} + } + if _, ok := _c.mutation.Content(); !ok { + return &ValidationError{Name: "content", err: errors.New(`models: missing required field "Comments.content"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Comments.created_at"`)} + } + return nil +} + +func (_c *CommentsCreate) sqlSave(ctx context.Context) (*Comments, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CommentsCreate) createSpec() (*Comments, *sqlgraph.CreateSpec) { + var ( + _node = &Comments{config: _c.config} + _spec = sqlgraph.NewCreateSpec(comments.Table, sqlgraph.NewFieldSpec(comments.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.PostID(); ok { + _spec.SetField(comments.FieldPostID, field.TypeInt64, value) + _node.PostID = value + } + if value, ok := _c.mutation.AuthorID(); ok { + _spec.SetField(comments.FieldAuthorID, field.TypeInt64, value) + _node.AuthorID = value + } + if value, ok := _c.mutation.Content(); ok { + _spec.SetField(comments.FieldContent, field.TypeString, value) + _node.Content = value + } + if value, ok := _c.mutation.LikeCount(); ok { + _spec.SetField(comments.FieldLikeCount, field.TypeInt, value) + _node.LikeCount = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(comments.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(comments.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + return _node, _spec +} + +// CommentsCreateBulk is the builder for creating many Comments entities in bulk. +type CommentsCreateBulk struct { + config + err error + builders []*CommentsCreate +} + +// Save creates the Comments entities in the database. +func (_c *CommentsCreateBulk) Save(ctx context.Context) ([]*Comments, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Comments, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentsMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *CommentsCreateBulk) SaveX(ctx context.Context) []*Comments { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CommentsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CommentsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/comments_delete.go b/app/community/rpc/internal/models/comments_delete.go new file mode 100644 index 0000000..69eefca --- /dev/null +++ b/app/community/rpc/internal/models/comments_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentsDelete is the builder for deleting a Comments entity. +type CommentsDelete struct { + config + hooks []Hook + mutation *CommentsMutation +} + +// Where appends a list predicates to the CommentsDelete builder. +func (_d *CommentsDelete) Where(ps ...predicate.Comments) *CommentsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CommentsDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CommentsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CommentsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(comments.Table, sqlgraph.NewFieldSpec(comments.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// CommentsDeleteOne is the builder for deleting a single Comments entity. +type CommentsDeleteOne struct { + _d *CommentsDelete +} + +// Where appends a list predicates to the CommentsDelete builder. +func (_d *CommentsDeleteOne) Where(ps ...predicate.Comments) *CommentsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CommentsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{comments.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CommentsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/comments_query.go b/app/community/rpc/internal/models/comments_query.go new file mode 100644 index 0000000..96f0c7c --- /dev/null +++ b/app/community/rpc/internal/models/comments_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentsQuery is the builder for querying Comments entities. +type CommentsQuery struct { + config + ctx *QueryContext + order []comments.OrderOption + inters []Interceptor + predicates []predicate.Comments + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the CommentsQuery builder. +func (_q *CommentsQuery) Where(ps ...predicate.Comments) *CommentsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CommentsQuery) Limit(limit int) *CommentsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CommentsQuery) Offset(offset int) *CommentsQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *CommentsQuery) Unique(unique bool) *CommentsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CommentsQuery) Order(o ...comments.OrderOption) *CommentsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Comments entity from the query. +// Returns a *NotFoundError when no Comments was found. +func (_q *CommentsQuery) First(ctx context.Context) (*Comments, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{comments.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CommentsQuery) FirstX(ctx context.Context) *Comments { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Comments ID from the query. +// Returns a *NotFoundError when no Comments ID was found. +func (_q *CommentsQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{comments.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CommentsQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Comments entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Comments entity is found. +// Returns a *NotFoundError when no Comments entities are found. +func (_q *CommentsQuery) Only(ctx context.Context) (*Comments, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{comments.Label} + default: + return nil, &NotSingularError{comments.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CommentsQuery) OnlyX(ctx context.Context) *Comments { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Comments ID in the query. +// Returns a *NotSingularError when more than one Comments ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CommentsQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{comments.Label} + default: + err = &NotSingularError{comments.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CommentsQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of CommentsSlice. +func (_q *CommentsQuery) All(ctx context.Context) ([]*Comments, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Comments, *CommentsQuery]() + return withInterceptors[[]*Comments](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CommentsQuery) AllX(ctx context.Context) []*Comments { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Comments IDs. +func (_q *CommentsQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(comments.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CommentsQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *CommentsQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*CommentsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CommentsQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *CommentsQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *CommentsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CommentsQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *CommentsQuery) Clone() *CommentsQuery { + if _q == nil { + return nil + } + return &CommentsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]comments.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Comments{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// PostID int64 `json:"post_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Comments.Query(). +// GroupBy(comments.FieldPostID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *CommentsQuery) GroupBy(field string, fields ...string) *CommentsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CommentsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = comments.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// PostID int64 `json:"post_id,omitempty"` +// } +// +// client.Comments.Query(). +// Select(comments.FieldPostID). +// Scan(ctx, &v) +func (_q *CommentsQuery) Select(fields ...string) *CommentsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CommentsSelect{CommentsQuery: _q} + sbuild.label = comments.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CommentsSelect configured with the given aggregations. +func (_q *CommentsQuery) Aggregate(fns ...AggregateFunc) *CommentsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CommentsQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !comments.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *CommentsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Comments, error) { + var ( + nodes = []*Comments{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Comments).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Comments{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *CommentsQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *CommentsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(comments.Table, comments.Columns, sqlgraph.NewFieldSpec(comments.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, comments.FieldID) + for i := range fields { + if fields[i] != comments.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *CommentsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(comments.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = comments.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// CommentsGroupBy is the group-by builder for Comments entities. +type CommentsGroupBy struct { + selector + build *CommentsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CommentsGroupBy) Aggregate(fns ...AggregateFunc) *CommentsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CommentsGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CommentsQuery, *CommentsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CommentsGroupBy) sqlScan(ctx context.Context, root *CommentsQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// CommentsSelect is the builder for selecting fields of Comments entities. +type CommentsSelect struct { + *CommentsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CommentsSelect) Aggregate(fns ...AggregateFunc) *CommentsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CommentsSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CommentsQuery, *CommentsSelect](ctx, _s.CommentsQuery, _s, _s.inters, v) +} + +func (_s *CommentsSelect) sqlScan(ctx context.Context, root *CommentsQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/community/rpc/internal/models/comments_update.go b/app/community/rpc/internal/models/comments_update.go new file mode 100644 index 0000000..909ec75 --- /dev/null +++ b/app/community/rpc/internal/models/comments_update.go @@ -0,0 +1,442 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CommentsUpdate is the builder for updating Comments entities. +type CommentsUpdate struct { + config + hooks []Hook + mutation *CommentsMutation +} + +// Where appends a list predicates to the CommentsUpdate builder. +func (_u *CommentsUpdate) Where(ps ...predicate.Comments) *CommentsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetPostID sets the "post_id" field. +func (_u *CommentsUpdate) SetPostID(v int64) *CommentsUpdate { + _u.mutation.ResetPostID() + _u.mutation.SetPostID(v) + return _u +} + +// SetNillablePostID sets the "post_id" field if the given value is not nil. +func (_u *CommentsUpdate) SetNillablePostID(v *int64) *CommentsUpdate { + if v != nil { + _u.SetPostID(*v) + } + return _u +} + +// AddPostID adds value to the "post_id" field. +func (_u *CommentsUpdate) AddPostID(v int64) *CommentsUpdate { + _u.mutation.AddPostID(v) + return _u +} + +// SetAuthorID sets the "author_id" field. +func (_u *CommentsUpdate) SetAuthorID(v int64) *CommentsUpdate { + _u.mutation.ResetAuthorID() + _u.mutation.SetAuthorID(v) + return _u +} + +// SetNillableAuthorID sets the "author_id" field if the given value is not nil. +func (_u *CommentsUpdate) SetNillableAuthorID(v *int64) *CommentsUpdate { + if v != nil { + _u.SetAuthorID(*v) + } + return _u +} + +// AddAuthorID adds value to the "author_id" field. +func (_u *CommentsUpdate) AddAuthorID(v int64) *CommentsUpdate { + _u.mutation.AddAuthorID(v) + return _u +} + +// SetContent sets the "content" field. +func (_u *CommentsUpdate) SetContent(v string) *CommentsUpdate { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *CommentsUpdate) SetNillableContent(v *string) *CommentsUpdate { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetLikeCount sets the "like_count" field. +func (_u *CommentsUpdate) SetLikeCount(v int) *CommentsUpdate { + _u.mutation.ResetLikeCount() + _u.mutation.SetLikeCount(v) + return _u +} + +// SetNillableLikeCount sets the "like_count" field if the given value is not nil. +func (_u *CommentsUpdate) SetNillableLikeCount(v *int) *CommentsUpdate { + if v != nil { + _u.SetLikeCount(*v) + } + return _u +} + +// AddLikeCount adds value to the "like_count" field. +func (_u *CommentsUpdate) AddLikeCount(v int) *CommentsUpdate { + _u.mutation.AddLikeCount(v) + return _u +} + +// ClearLikeCount clears the value of the "like_count" field. +func (_u *CommentsUpdate) ClearLikeCount() *CommentsUpdate { + _u.mutation.ClearLikeCount() + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CommentsUpdate) SetDeletedAt(v time.Time) *CommentsUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CommentsUpdate) SetNillableDeletedAt(v *time.Time) *CommentsUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CommentsUpdate) ClearDeletedAt() *CommentsUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the CommentsMutation object of the builder. +func (_u *CommentsUpdate) Mutation() *CommentsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CommentsUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CommentsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CommentsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CommentsUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *CommentsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(comments.Table, comments.Columns, sqlgraph.NewFieldSpec(comments.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.PostID(); ok { + _spec.SetField(comments.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPostID(); ok { + _spec.AddField(comments.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AuthorID(); ok { + _spec.SetField(comments.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedAuthorID(); ok { + _spec.AddField(comments.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(comments.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.LikeCount(); ok { + _spec.SetField(comments.FieldLikeCount, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedLikeCount(); ok { + _spec.AddField(comments.FieldLikeCount, field.TypeInt, value) + } + if _u.mutation.LikeCountCleared() { + _spec.ClearField(comments.FieldLikeCount, field.TypeInt) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(comments.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(comments.FieldDeletedAt, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{comments.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CommentsUpdateOne is the builder for updating a single Comments entity. +type CommentsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CommentsMutation +} + +// SetPostID sets the "post_id" field. +func (_u *CommentsUpdateOne) SetPostID(v int64) *CommentsUpdateOne { + _u.mutation.ResetPostID() + _u.mutation.SetPostID(v) + return _u +} + +// SetNillablePostID sets the "post_id" field if the given value is not nil. +func (_u *CommentsUpdateOne) SetNillablePostID(v *int64) *CommentsUpdateOne { + if v != nil { + _u.SetPostID(*v) + } + return _u +} + +// AddPostID adds value to the "post_id" field. +func (_u *CommentsUpdateOne) AddPostID(v int64) *CommentsUpdateOne { + _u.mutation.AddPostID(v) + return _u +} + +// SetAuthorID sets the "author_id" field. +func (_u *CommentsUpdateOne) SetAuthorID(v int64) *CommentsUpdateOne { + _u.mutation.ResetAuthorID() + _u.mutation.SetAuthorID(v) + return _u +} + +// SetNillableAuthorID sets the "author_id" field if the given value is not nil. +func (_u *CommentsUpdateOne) SetNillableAuthorID(v *int64) *CommentsUpdateOne { + if v != nil { + _u.SetAuthorID(*v) + } + return _u +} + +// AddAuthorID adds value to the "author_id" field. +func (_u *CommentsUpdateOne) AddAuthorID(v int64) *CommentsUpdateOne { + _u.mutation.AddAuthorID(v) + return _u +} + +// SetContent sets the "content" field. +func (_u *CommentsUpdateOne) SetContent(v string) *CommentsUpdateOne { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *CommentsUpdateOne) SetNillableContent(v *string) *CommentsUpdateOne { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetLikeCount sets the "like_count" field. +func (_u *CommentsUpdateOne) SetLikeCount(v int) *CommentsUpdateOne { + _u.mutation.ResetLikeCount() + _u.mutation.SetLikeCount(v) + return _u +} + +// SetNillableLikeCount sets the "like_count" field if the given value is not nil. +func (_u *CommentsUpdateOne) SetNillableLikeCount(v *int) *CommentsUpdateOne { + if v != nil { + _u.SetLikeCount(*v) + } + return _u +} + +// AddLikeCount adds value to the "like_count" field. +func (_u *CommentsUpdateOne) AddLikeCount(v int) *CommentsUpdateOne { + _u.mutation.AddLikeCount(v) + return _u +} + +// ClearLikeCount clears the value of the "like_count" field. +func (_u *CommentsUpdateOne) ClearLikeCount() *CommentsUpdateOne { + _u.mutation.ClearLikeCount() + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CommentsUpdateOne) SetDeletedAt(v time.Time) *CommentsUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CommentsUpdateOne) SetNillableDeletedAt(v *time.Time) *CommentsUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CommentsUpdateOne) ClearDeletedAt() *CommentsUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the CommentsMutation object of the builder. +func (_u *CommentsUpdateOne) Mutation() *CommentsMutation { + return _u.mutation +} + +// Where appends a list predicates to the CommentsUpdate builder. +func (_u *CommentsUpdateOne) Where(ps ...predicate.Comments) *CommentsUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *CommentsUpdateOne) Select(field string, fields ...string) *CommentsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Comments entity. +func (_u *CommentsUpdateOne) Save(ctx context.Context) (*Comments, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CommentsUpdateOne) SaveX(ctx context.Context) *Comments { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CommentsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CommentsUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *CommentsUpdateOne) sqlSave(ctx context.Context) (_node *Comments, err error) { + _spec := sqlgraph.NewUpdateSpec(comments.Table, comments.Columns, sqlgraph.NewFieldSpec(comments.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Comments.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, comments.FieldID) + for _, f := range fields { + if !comments.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != comments.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.PostID(); ok { + _spec.SetField(comments.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPostID(); ok { + _spec.AddField(comments.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AuthorID(); ok { + _spec.SetField(comments.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedAuthorID(); ok { + _spec.AddField(comments.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(comments.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.LikeCount(); ok { + _spec.SetField(comments.FieldLikeCount, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedLikeCount(); ok { + _spec.AddField(comments.FieldLikeCount, field.TypeInt, value) + } + if _u.mutation.LikeCountCleared() { + _spec.ClearField(comments.FieldLikeCount, field.TypeInt) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(comments.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(comments.FieldDeletedAt, field.TypeTime) + } + _node = &Comments{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{comments.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/community/rpc/internal/models/ent.go b/app/community/rpc/internal/models/ent.go new file mode 100644 index 0000000..f96231e --- /dev/null +++ b/app/community/rpc/internal/models/ent.go @@ -0,0 +1,614 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/posts" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + commentlikes.Table: commentlikes.ValidColumn, + comments.Table: comments.ValidColumn, + postlikes.Table: postlikes.ValidColumn, + posts.Table: posts.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "models: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "models: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "models: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "models: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/app/community/rpc/internal/models/enttest/enttest.go b/app/community/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..7422616 --- /dev/null +++ b/app/community/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/community/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/community/rpc/internal/models/runtime" + + "juwan-backend/app/community/rpc/internal/models/migrate" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []models.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...models.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls models.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client { + o := newOptions(opts) + c, err := models.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls models.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *models.Client { + o := newOptions(opts) + c := models.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *models.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/app/community/rpc/internal/models/generate.go b/app/community/rpc/internal/models/generate.go new file mode 100644 index 0000000..d441aca --- /dev/null +++ b/app/community/rpc/internal/models/generate.go @@ -0,0 +1,3 @@ +package models + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/app/community/rpc/internal/models/hook/hook.go b/app/community/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..719f0fe --- /dev/null +++ b/app/community/rpc/internal/models/hook/hook.go @@ -0,0 +1,234 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "juwan-backend/app/community/rpc/internal/models" +) + +// The CommentLikesFunc type is an adapter to allow the use of ordinary +// function as CommentLikes mutator. +type CommentLikesFunc func(context.Context, *models.CommentLikesMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f CommentLikesFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.CommentLikesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.CommentLikesMutation", m) +} + +// The CommentsFunc type is an adapter to allow the use of ordinary +// function as Comments mutator. +type CommentsFunc func(context.Context, *models.CommentsMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f CommentsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.CommentsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.CommentsMutation", m) +} + +// The PostLikesFunc type is an adapter to allow the use of ordinary +// function as PostLikes mutator. +type PostLikesFunc func(context.Context, *models.PostLikesMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f PostLikesFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.PostLikesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.PostLikesMutation", m) +} + +// The PostsFunc type is an adapter to allow the use of ordinary +// function as Posts mutator. +type PostsFunc func(context.Context, *models.PostsMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f PostsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.PostsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.PostsMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, models.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op models.Op) Condition { + return func(_ context.Context, m models.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk models.Hook, cond Condition) models.Hook { + return func(next models.Mutator) models.Mutator { + return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, models.Delete|models.Create) +func On(hk models.Hook, op models.Op) models.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, models.Update|models.UpdateOne) +func Unless(hk models.Hook, op models.Op) models.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) models.Hook { + return func(models.Mutator) models.Mutator { + return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []models.Hook { +// return []models.Hook{ +// Reject(models.Delete|models.Update), +// } +// } +func Reject(op models.Op) models.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []models.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...models.Hook) Chain { + return Chain{append([]models.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() models.Hook { + return func(mutator models.Mutator) models.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...models.Hook) Chain { + newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/app/community/rpc/internal/models/migrate/migrate.go b/app/community/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/community/rpc/internal/models/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/app/community/rpc/internal/models/migrate/schema.go b/app/community/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..7cf06af --- /dev/null +++ b/app/community/rpc/internal/models/migrate/schema.go @@ -0,0 +1,155 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // CommentLikesColumns holds the columns for the "comment_likes" table. + CommentLikesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "comment_id", Type: field.TypeInt64}, + {Name: "user_id", Type: field.TypeInt64}, + {Name: "created_at", Type: field.TypeTime}, + } + // CommentLikesTable holds the schema information for the "comment_likes" table. + CommentLikesTable = &schema.Table{ + Name: "comment_likes", + Columns: CommentLikesColumns, + PrimaryKey: []*schema.Column{CommentLikesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "commentlikes_comment_id_user_id", + Unique: true, + Columns: []*schema.Column{CommentLikesColumns[1], CommentLikesColumns[2]}, + }, + { + Name: "commentlikes_user_id_comment_id", + Unique: false, + Columns: []*schema.Column{CommentLikesColumns[2], CommentLikesColumns[1]}, + }, + { + Name: "commentlikes_user_id_created_at", + Unique: false, + Columns: []*schema.Column{CommentLikesColumns[2], CommentLikesColumns[3]}, + }, + }, + } + // CommentsColumns holds the columns for the "comments" table. + CommentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "post_id", Type: field.TypeInt64}, + {Name: "author_id", Type: field.TypeInt64}, + {Name: "content", Type: field.TypeString}, + {Name: "like_count", Type: field.TypeInt, Nullable: true, Default: 0}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + } + // CommentsTable holds the schema information for the "comments" table. + CommentsTable = &schema.Table{ + Name: "comments", + Columns: CommentsColumns, + PrimaryKey: []*schema.Column{CommentsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "comments_post_id_created_at", + Unique: false, + Columns: []*schema.Column{CommentsColumns[1], CommentsColumns[5]}, + }, + { + Name: "comments_author_id_created_at", + Unique: false, + Columns: []*schema.Column{CommentsColumns[2], CommentsColumns[5]}, + }, + }, + } + // PostLikesColumns holds the columns for the "post_likes" table. + PostLikesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "post_id", Type: field.TypeInt64}, + {Name: "user_id", Type: field.TypeInt64}, + {Name: "created_at", Type: field.TypeTime}, + } + // PostLikesTable holds the schema information for the "post_likes" table. + PostLikesTable = &schema.Table{ + Name: "post_likes", + Columns: PostLikesColumns, + PrimaryKey: []*schema.Column{PostLikesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "postlikes_post_id_user_id", + Unique: true, + Columns: []*schema.Column{PostLikesColumns[1], PostLikesColumns[2]}, + }, + { + Name: "postlikes_user_id_post_id", + Unique: false, + Columns: []*schema.Column{PostLikesColumns[2], PostLikesColumns[1]}, + }, + { + Name: "postlikes_user_id_created_at", + Unique: false, + Columns: []*schema.Column{PostLikesColumns[2], PostLikesColumns[3]}, + }, + }, + } + // PostsColumns holds the columns for the "posts" table. + PostsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "author_id", Type: field.TypeInt64}, + {Name: "author_role", Type: field.TypeString, Size: 20, Default: "consumer"}, + {Name: "title", Type: field.TypeString, Size: 500}, + {Name: "content", Type: field.TypeString}, + {Name: "images", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "tags", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "linked_order_id", Type: field.TypeInt64, Nullable: true}, + {Name: "quoted_post_id", Type: field.TypeInt64, Nullable: true}, + {Name: "like_count", Type: field.TypeInt, Nullable: true, Default: 0}, + {Name: "comment_count", Type: field.TypeInt, Nullable: true, Default: 0}, + {Name: "pinned", Type: field.TypeBool, Nullable: true, Default: false}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + } + // PostsTable holds the schema information for the "posts" table. + PostsTable = &schema.Table{ + Name: "posts", + Columns: PostsColumns, + PrimaryKey: []*schema.Column{PostsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "posts_author_id_created_at", + Unique: false, + Columns: []*schema.Column{PostsColumns[1], PostsColumns[12]}, + }, + { + Name: "posts_created_at", + Unique: false, + Columns: []*schema.Column{PostsColumns[12]}, + }, + { + Name: "posts_linked_order_id", + Unique: false, + Columns: []*schema.Column{PostsColumns[7]}, + }, + { + Name: "posts_quoted_post_id", + Unique: false, + Columns: []*schema.Column{PostsColumns[8]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + CommentLikesTable, + CommentsTable, + PostLikesTable, + PostsTable, + } +) + +func init() { +} diff --git a/app/community/rpc/internal/models/mutation.go b/app/community/rpc/internal/models/mutation.go new file mode 100644 index 0000000..eb98198 --- /dev/null +++ b/app/community/rpc/internal/models/mutation.go @@ -0,0 +1,3160 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/app/community/rpc/internal/models/predicate" + "juwan-backend/pkg/types" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeCommentLikes = "CommentLikes" + TypeComments = "Comments" + TypePostLikes = "PostLikes" + TypePosts = "Posts" +) + +// CommentLikesMutation represents an operation that mutates the CommentLikes nodes in the graph. +type CommentLikesMutation struct { + config + op Op + typ string + id *int64 + comment_id *int64 + addcomment_id *int64 + user_id *int64 + adduser_id *int64 + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*CommentLikes, error) + predicates []predicate.CommentLikes +} + +var _ ent.Mutation = (*CommentLikesMutation)(nil) + +// commentlikesOption allows management of the mutation configuration using functional options. +type commentlikesOption func(*CommentLikesMutation) + +// newCommentLikesMutation creates new mutation for the CommentLikes entity. +func newCommentLikesMutation(c config, op Op, opts ...commentlikesOption) *CommentLikesMutation { + m := &CommentLikesMutation{ + config: c, + op: op, + typ: TypeCommentLikes, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCommentLikesID sets the ID field of the mutation. +func withCommentLikesID(id int64) commentlikesOption { + return func(m *CommentLikesMutation) { + var ( + err error + once sync.Once + value *CommentLikes + ) + m.oldValue = func(ctx context.Context) (*CommentLikes, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CommentLikes.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCommentLikes sets the old CommentLikes of the mutation. +func withCommentLikes(node *CommentLikes) commentlikesOption { + return func(m *CommentLikesMutation) { + m.oldValue = func(context.Context) (*CommentLikes, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m CommentLikesMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m CommentLikesMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of CommentLikes entities. +func (m *CommentLikesMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *CommentLikesMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *CommentLikesMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().CommentLikes.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCommentID sets the "comment_id" field. +func (m *CommentLikesMutation) SetCommentID(i int64) { + m.comment_id = &i + m.addcomment_id = nil +} + +// CommentID returns the value of the "comment_id" field in the mutation. +func (m *CommentLikesMutation) CommentID() (r int64, exists bool) { + v := m.comment_id + if v == nil { + return + } + return *v, true +} + +// OldCommentID returns the old "comment_id" field's value of the CommentLikes entity. +// If the CommentLikes object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentLikesMutation) OldCommentID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCommentID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCommentID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCommentID: %w", err) + } + return oldValue.CommentID, nil +} + +// AddCommentID adds i to the "comment_id" field. +func (m *CommentLikesMutation) AddCommentID(i int64) { + if m.addcomment_id != nil { + *m.addcomment_id += i + } else { + m.addcomment_id = &i + } +} + +// AddedCommentID returns the value that was added to the "comment_id" field in this mutation. +func (m *CommentLikesMutation) AddedCommentID() (r int64, exists bool) { + v := m.addcomment_id + if v == nil { + return + } + return *v, true +} + +// ResetCommentID resets all changes to the "comment_id" field. +func (m *CommentLikesMutation) ResetCommentID() { + m.comment_id = nil + m.addcomment_id = nil +} + +// SetUserID sets the "user_id" field. +func (m *CommentLikesMutation) SetUserID(i int64) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *CommentLikesMutation) UserID() (r int64, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the CommentLikes entity. +// If the CommentLikes object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentLikesMutation) OldUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// AddUserID adds i to the "user_id" field. +func (m *CommentLikesMutation) AddUserID(i int64) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *CommentLikesMutation) AddedUserID() (r int64, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *CommentLikesMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *CommentLikesMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CommentLikesMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the CommentLikes entity. +// If the CommentLikes object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentLikesMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *CommentLikesMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the CommentLikesMutation builder. +func (m *CommentLikesMutation) Where(ps ...predicate.CommentLikes) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CommentLikesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CommentLikesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CommentLikes, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CommentLikesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CommentLikesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CommentLikes). +func (m *CommentLikesMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *CommentLikesMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.comment_id != nil { + fields = append(fields, commentlikes.FieldCommentID) + } + if m.user_id != nil { + fields = append(fields, commentlikes.FieldUserID) + } + if m.created_at != nil { + fields = append(fields, commentlikes.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *CommentLikesMutation) Field(name string) (ent.Value, bool) { + switch name { + case commentlikes.FieldCommentID: + return m.CommentID() + case commentlikes.FieldUserID: + return m.UserID() + case commentlikes.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *CommentLikesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case commentlikes.FieldCommentID: + return m.OldCommentID(ctx) + case commentlikes.FieldUserID: + return m.OldUserID(ctx) + case commentlikes.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown CommentLikes field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *CommentLikesMutation) SetField(name string, value ent.Value) error { + switch name { + case commentlikes.FieldCommentID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCommentID(v) + return nil + case commentlikes.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case commentlikes.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown CommentLikes field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CommentLikesMutation) AddedFields() []string { + var fields []string + if m.addcomment_id != nil { + fields = append(fields, commentlikes.FieldCommentID) + } + if m.adduser_id != nil { + fields = append(fields, commentlikes.FieldUserID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *CommentLikesMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case commentlikes.FieldCommentID: + return m.AddedCommentID() + case commentlikes.FieldUserID: + return m.AddedUserID() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *CommentLikesMutation) AddField(name string, value ent.Value) error { + switch name { + case commentlikes.FieldCommentID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCommentID(v) + return nil + case commentlikes.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + } + return fmt.Errorf("unknown CommentLikes numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CommentLikesMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CommentLikesMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *CommentLikesMutation) ClearField(name string) error { + return fmt.Errorf("unknown CommentLikes nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *CommentLikesMutation) ResetField(name string) error { + switch name { + case commentlikes.FieldCommentID: + m.ResetCommentID() + return nil + case commentlikes.FieldUserID: + m.ResetUserID() + return nil + case commentlikes.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown CommentLikes field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CommentLikesMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CommentLikesMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CommentLikesMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CommentLikesMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CommentLikesMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CommentLikesMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *CommentLikesMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown CommentLikes unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *CommentLikesMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown CommentLikes edge %s", name) +} + +// CommentsMutation represents an operation that mutates the Comments nodes in the graph. +type CommentsMutation struct { + config + op Op + typ string + id *int64 + post_id *int64 + addpost_id *int64 + author_id *int64 + addauthor_id *int64 + content *string + like_count *int + addlike_count *int + created_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Comments, error) + predicates []predicate.Comments +} + +var _ ent.Mutation = (*CommentsMutation)(nil) + +// commentsOption allows management of the mutation configuration using functional options. +type commentsOption func(*CommentsMutation) + +// newCommentsMutation creates new mutation for the Comments entity. +func newCommentsMutation(c config, op Op, opts ...commentsOption) *CommentsMutation { + m := &CommentsMutation{ + config: c, + op: op, + typ: TypeComments, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCommentsID sets the ID field of the mutation. +func withCommentsID(id int64) commentsOption { + return func(m *CommentsMutation) { + var ( + err error + once sync.Once + value *Comments + ) + m.oldValue = func(ctx context.Context) (*Comments, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Comments.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withComments sets the old Comments of the mutation. +func withComments(node *Comments) commentsOption { + return func(m *CommentsMutation) { + m.oldValue = func(context.Context) (*Comments, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m CommentsMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m CommentsMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Comments entities. +func (m *CommentsMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *CommentsMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *CommentsMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Comments.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetPostID sets the "post_id" field. +func (m *CommentsMutation) SetPostID(i int64) { + m.post_id = &i + m.addpost_id = nil +} + +// PostID returns the value of the "post_id" field in the mutation. +func (m *CommentsMutation) PostID() (r int64, exists bool) { + v := m.post_id + if v == nil { + return + } + return *v, true +} + +// OldPostID returns the old "post_id" field's value of the Comments entity. +// If the Comments object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentsMutation) OldPostID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPostID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPostID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPostID: %w", err) + } + return oldValue.PostID, nil +} + +// AddPostID adds i to the "post_id" field. +func (m *CommentsMutation) AddPostID(i int64) { + if m.addpost_id != nil { + *m.addpost_id += i + } else { + m.addpost_id = &i + } +} + +// AddedPostID returns the value that was added to the "post_id" field in this mutation. +func (m *CommentsMutation) AddedPostID() (r int64, exists bool) { + v := m.addpost_id + if v == nil { + return + } + return *v, true +} + +// ResetPostID resets all changes to the "post_id" field. +func (m *CommentsMutation) ResetPostID() { + m.post_id = nil + m.addpost_id = nil +} + +// SetAuthorID sets the "author_id" field. +func (m *CommentsMutation) SetAuthorID(i int64) { + m.author_id = &i + m.addauthor_id = nil +} + +// AuthorID returns the value of the "author_id" field in the mutation. +func (m *CommentsMutation) AuthorID() (r int64, exists bool) { + v := m.author_id + if v == nil { + return + } + return *v, true +} + +// OldAuthorID returns the old "author_id" field's value of the Comments entity. +// If the Comments object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentsMutation) OldAuthorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorID: %w", err) + } + return oldValue.AuthorID, nil +} + +// AddAuthorID adds i to the "author_id" field. +func (m *CommentsMutation) AddAuthorID(i int64) { + if m.addauthor_id != nil { + *m.addauthor_id += i + } else { + m.addauthor_id = &i + } +} + +// AddedAuthorID returns the value that was added to the "author_id" field in this mutation. +func (m *CommentsMutation) AddedAuthorID() (r int64, exists bool) { + v := m.addauthor_id + if v == nil { + return + } + return *v, true +} + +// ResetAuthorID resets all changes to the "author_id" field. +func (m *CommentsMutation) ResetAuthorID() { + m.author_id = nil + m.addauthor_id = nil +} + +// SetContent sets the "content" field. +func (m *CommentsMutation) SetContent(s string) { + m.content = &s +} + +// Content returns the value of the "content" field in the mutation. +func (m *CommentsMutation) Content() (r string, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the Comments entity. +// If the Comments object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentsMutation) OldContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ResetContent resets all changes to the "content" field. +func (m *CommentsMutation) ResetContent() { + m.content = nil +} + +// SetLikeCount sets the "like_count" field. +func (m *CommentsMutation) SetLikeCount(i int) { + m.like_count = &i + m.addlike_count = nil +} + +// LikeCount returns the value of the "like_count" field in the mutation. +func (m *CommentsMutation) LikeCount() (r int, exists bool) { + v := m.like_count + if v == nil { + return + } + return *v, true +} + +// OldLikeCount returns the old "like_count" field's value of the Comments entity. +// If the Comments object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentsMutation) OldLikeCount(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLikeCount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLikeCount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLikeCount: %w", err) + } + return oldValue.LikeCount, nil +} + +// AddLikeCount adds i to the "like_count" field. +func (m *CommentsMutation) AddLikeCount(i int) { + if m.addlike_count != nil { + *m.addlike_count += i + } else { + m.addlike_count = &i + } +} + +// AddedLikeCount returns the value that was added to the "like_count" field in this mutation. +func (m *CommentsMutation) AddedLikeCount() (r int, exists bool) { + v := m.addlike_count + if v == nil { + return + } + return *v, true +} + +// ClearLikeCount clears the value of the "like_count" field. +func (m *CommentsMutation) ClearLikeCount() { + m.like_count = nil + m.addlike_count = nil + m.clearedFields[comments.FieldLikeCount] = struct{}{} +} + +// LikeCountCleared returns if the "like_count" field was cleared in this mutation. +func (m *CommentsMutation) LikeCountCleared() bool { + _, ok := m.clearedFields[comments.FieldLikeCount] + return ok +} + +// ResetLikeCount resets all changes to the "like_count" field. +func (m *CommentsMutation) ResetLikeCount() { + m.like_count = nil + m.addlike_count = nil + delete(m.clearedFields, comments.FieldLikeCount) +} + +// SetCreatedAt sets the "created_at" field. +func (m *CommentsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CommentsMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the Comments entity. +// If the Comments object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentsMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *CommentsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *CommentsMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *CommentsMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the Comments entity. +// If the Comments object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CommentsMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *CommentsMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[comments.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *CommentsMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[comments.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *CommentsMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, comments.FieldDeletedAt) +} + +// Where appends a list predicates to the CommentsMutation builder. +func (m *CommentsMutation) Where(ps ...predicate.Comments) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CommentsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CommentsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Comments, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CommentsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CommentsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Comments). +func (m *CommentsMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *CommentsMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.post_id != nil { + fields = append(fields, comments.FieldPostID) + } + if m.author_id != nil { + fields = append(fields, comments.FieldAuthorID) + } + if m.content != nil { + fields = append(fields, comments.FieldContent) + } + if m.like_count != nil { + fields = append(fields, comments.FieldLikeCount) + } + if m.created_at != nil { + fields = append(fields, comments.FieldCreatedAt) + } + if m.deleted_at != nil { + fields = append(fields, comments.FieldDeletedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *CommentsMutation) Field(name string) (ent.Value, bool) { + switch name { + case comments.FieldPostID: + return m.PostID() + case comments.FieldAuthorID: + return m.AuthorID() + case comments.FieldContent: + return m.Content() + case comments.FieldLikeCount: + return m.LikeCount() + case comments.FieldCreatedAt: + return m.CreatedAt() + case comments.FieldDeletedAt: + return m.DeletedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *CommentsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case comments.FieldPostID: + return m.OldPostID(ctx) + case comments.FieldAuthorID: + return m.OldAuthorID(ctx) + case comments.FieldContent: + return m.OldContent(ctx) + case comments.FieldLikeCount: + return m.OldLikeCount(ctx) + case comments.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case comments.FieldDeletedAt: + return m.OldDeletedAt(ctx) + } + return nil, fmt.Errorf("unknown Comments field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *CommentsMutation) SetField(name string, value ent.Value) error { + switch name { + case comments.FieldPostID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPostID(v) + return nil + case comments.FieldAuthorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorID(v) + return nil + case comments.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + case comments.FieldLikeCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLikeCount(v) + return nil + case comments.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case comments.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + } + return fmt.Errorf("unknown Comments field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CommentsMutation) AddedFields() []string { + var fields []string + if m.addpost_id != nil { + fields = append(fields, comments.FieldPostID) + } + if m.addauthor_id != nil { + fields = append(fields, comments.FieldAuthorID) + } + if m.addlike_count != nil { + fields = append(fields, comments.FieldLikeCount) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *CommentsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case comments.FieldPostID: + return m.AddedPostID() + case comments.FieldAuthorID: + return m.AddedAuthorID() + case comments.FieldLikeCount: + return m.AddedLikeCount() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *CommentsMutation) AddField(name string, value ent.Value) error { + switch name { + case comments.FieldPostID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPostID(v) + return nil + case comments.FieldAuthorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAuthorID(v) + return nil + case comments.FieldLikeCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddLikeCount(v) + return nil + } + return fmt.Errorf("unknown Comments numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CommentsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(comments.FieldLikeCount) { + fields = append(fields, comments.FieldLikeCount) + } + if m.FieldCleared(comments.FieldDeletedAt) { + fields = append(fields, comments.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CommentsMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *CommentsMutation) ClearField(name string) error { + switch name { + case comments.FieldLikeCount: + m.ClearLikeCount() + return nil + case comments.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown Comments nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *CommentsMutation) ResetField(name string) error { + switch name { + case comments.FieldPostID: + m.ResetPostID() + return nil + case comments.FieldAuthorID: + m.ResetAuthorID() + return nil + case comments.FieldContent: + m.ResetContent() + return nil + case comments.FieldLikeCount: + m.ResetLikeCount() + return nil + case comments.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case comments.FieldDeletedAt: + m.ResetDeletedAt() + return nil + } + return fmt.Errorf("unknown Comments field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CommentsMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CommentsMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CommentsMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CommentsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CommentsMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CommentsMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *CommentsMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Comments unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *CommentsMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Comments edge %s", name) +} + +// PostLikesMutation represents an operation that mutates the PostLikes nodes in the graph. +type PostLikesMutation struct { + config + op Op + typ string + id *int64 + post_id *int64 + addpost_id *int64 + user_id *int64 + adduser_id *int64 + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*PostLikes, error) + predicates []predicate.PostLikes +} + +var _ ent.Mutation = (*PostLikesMutation)(nil) + +// postlikesOption allows management of the mutation configuration using functional options. +type postlikesOption func(*PostLikesMutation) + +// newPostLikesMutation creates new mutation for the PostLikes entity. +func newPostLikesMutation(c config, op Op, opts ...postlikesOption) *PostLikesMutation { + m := &PostLikesMutation{ + config: c, + op: op, + typ: TypePostLikes, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPostLikesID sets the ID field of the mutation. +func withPostLikesID(id int64) postlikesOption { + return func(m *PostLikesMutation) { + var ( + err error + once sync.Once + value *PostLikes + ) + m.oldValue = func(ctx context.Context) (*PostLikes, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().PostLikes.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPostLikes sets the old PostLikes of the mutation. +func withPostLikes(node *PostLikes) postlikesOption { + return func(m *PostLikesMutation) { + m.oldValue = func(context.Context) (*PostLikes, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m PostLikesMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m PostLikesMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of PostLikes entities. +func (m *PostLikesMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *PostLikesMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *PostLikesMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().PostLikes.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetPostID sets the "post_id" field. +func (m *PostLikesMutation) SetPostID(i int64) { + m.post_id = &i + m.addpost_id = nil +} + +// PostID returns the value of the "post_id" field in the mutation. +func (m *PostLikesMutation) PostID() (r int64, exists bool) { + v := m.post_id + if v == nil { + return + } + return *v, true +} + +// OldPostID returns the old "post_id" field's value of the PostLikes entity. +// If the PostLikes object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostLikesMutation) OldPostID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPostID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPostID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPostID: %w", err) + } + return oldValue.PostID, nil +} + +// AddPostID adds i to the "post_id" field. +func (m *PostLikesMutation) AddPostID(i int64) { + if m.addpost_id != nil { + *m.addpost_id += i + } else { + m.addpost_id = &i + } +} + +// AddedPostID returns the value that was added to the "post_id" field in this mutation. +func (m *PostLikesMutation) AddedPostID() (r int64, exists bool) { + v := m.addpost_id + if v == nil { + return + } + return *v, true +} + +// ResetPostID resets all changes to the "post_id" field. +func (m *PostLikesMutation) ResetPostID() { + m.post_id = nil + m.addpost_id = nil +} + +// SetUserID sets the "user_id" field. +func (m *PostLikesMutation) SetUserID(i int64) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *PostLikesMutation) UserID() (r int64, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the PostLikes entity. +// If the PostLikes object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostLikesMutation) OldUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// AddUserID adds i to the "user_id" field. +func (m *PostLikesMutation) AddUserID(i int64) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *PostLikesMutation) AddedUserID() (r int64, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *PostLikesMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *PostLikesMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PostLikesMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the PostLikes entity. +// If the PostLikes object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostLikesMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *PostLikesMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the PostLikesMutation builder. +func (m *PostLikesMutation) Where(ps ...predicate.PostLikes) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the PostLikesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *PostLikesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.PostLikes, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *PostLikesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *PostLikesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (PostLikes). +func (m *PostLikesMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *PostLikesMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.post_id != nil { + fields = append(fields, postlikes.FieldPostID) + } + if m.user_id != nil { + fields = append(fields, postlikes.FieldUserID) + } + if m.created_at != nil { + fields = append(fields, postlikes.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *PostLikesMutation) Field(name string) (ent.Value, bool) { + switch name { + case postlikes.FieldPostID: + return m.PostID() + case postlikes.FieldUserID: + return m.UserID() + case postlikes.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *PostLikesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case postlikes.FieldPostID: + return m.OldPostID(ctx) + case postlikes.FieldUserID: + return m.OldUserID(ctx) + case postlikes.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown PostLikes field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *PostLikesMutation) SetField(name string, value ent.Value) error { + switch name { + case postlikes.FieldPostID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPostID(v) + return nil + case postlikes.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case postlikes.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown PostLikes field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PostLikesMutation) AddedFields() []string { + var fields []string + if m.addpost_id != nil { + fields = append(fields, postlikes.FieldPostID) + } + if m.adduser_id != nil { + fields = append(fields, postlikes.FieldUserID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *PostLikesMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case postlikes.FieldPostID: + return m.AddedPostID() + case postlikes.FieldUserID: + return m.AddedUserID() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *PostLikesMutation) AddField(name string, value ent.Value) error { + switch name { + case postlikes.FieldPostID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPostID(v) + return nil + case postlikes.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + } + return fmt.Errorf("unknown PostLikes numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PostLikesMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PostLikesMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *PostLikesMutation) ClearField(name string) error { + return fmt.Errorf("unknown PostLikes nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *PostLikesMutation) ResetField(name string) error { + switch name { + case postlikes.FieldPostID: + m.ResetPostID() + return nil + case postlikes.FieldUserID: + m.ResetUserID() + return nil + case postlikes.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown PostLikes field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PostLikesMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PostLikesMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PostLikesMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PostLikesMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PostLikesMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PostLikesMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *PostLikesMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown PostLikes unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *PostLikesMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown PostLikes edge %s", name) +} + +// PostsMutation represents an operation that mutates the Posts nodes in the graph. +type PostsMutation struct { + config + op Op + typ string + id *int64 + author_id *int64 + addauthor_id *int64 + author_role *string + title *string + content *string + images *types.TextArray + tags *types.TextArray + linked_order_id *int64 + addlinked_order_id *int64 + quoted_post_id *int64 + addquoted_post_id *int64 + like_count *int + addlike_count *int + comment_count *int + addcomment_count *int + pinned *bool + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Posts, error) + predicates []predicate.Posts +} + +var _ ent.Mutation = (*PostsMutation)(nil) + +// postsOption allows management of the mutation configuration using functional options. +type postsOption func(*PostsMutation) + +// newPostsMutation creates new mutation for the Posts entity. +func newPostsMutation(c config, op Op, opts ...postsOption) *PostsMutation { + m := &PostsMutation{ + config: c, + op: op, + typ: TypePosts, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPostsID sets the ID field of the mutation. +func withPostsID(id int64) postsOption { + return func(m *PostsMutation) { + var ( + err error + once sync.Once + value *Posts + ) + m.oldValue = func(ctx context.Context) (*Posts, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Posts.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPosts sets the old Posts of the mutation. +func withPosts(node *Posts) postsOption { + return func(m *PostsMutation) { + m.oldValue = func(context.Context) (*Posts, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m PostsMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m PostsMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Posts entities. +func (m *PostsMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *PostsMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *PostsMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Posts.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetAuthorID sets the "author_id" field. +func (m *PostsMutation) SetAuthorID(i int64) { + m.author_id = &i + m.addauthor_id = nil +} + +// AuthorID returns the value of the "author_id" field in the mutation. +func (m *PostsMutation) AuthorID() (r int64, exists bool) { + v := m.author_id + if v == nil { + return + } + return *v, true +} + +// OldAuthorID returns the old "author_id" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldAuthorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorID: %w", err) + } + return oldValue.AuthorID, nil +} + +// AddAuthorID adds i to the "author_id" field. +func (m *PostsMutation) AddAuthorID(i int64) { + if m.addauthor_id != nil { + *m.addauthor_id += i + } else { + m.addauthor_id = &i + } +} + +// AddedAuthorID returns the value that was added to the "author_id" field in this mutation. +func (m *PostsMutation) AddedAuthorID() (r int64, exists bool) { + v := m.addauthor_id + if v == nil { + return + } + return *v, true +} + +// ResetAuthorID resets all changes to the "author_id" field. +func (m *PostsMutation) ResetAuthorID() { + m.author_id = nil + m.addauthor_id = nil +} + +// SetAuthorRole sets the "author_role" field. +func (m *PostsMutation) SetAuthorRole(s string) { + m.author_role = &s +} + +// AuthorRole returns the value of the "author_role" field in the mutation. +func (m *PostsMutation) AuthorRole() (r string, exists bool) { + v := m.author_role + if v == nil { + return + } + return *v, true +} + +// OldAuthorRole returns the old "author_role" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldAuthorRole(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorRole is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorRole requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorRole: %w", err) + } + return oldValue.AuthorRole, nil +} + +// ResetAuthorRole resets all changes to the "author_role" field. +func (m *PostsMutation) ResetAuthorRole() { + m.author_role = nil +} + +// SetTitle sets the "title" field. +func (m *PostsMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *PostsMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *PostsMutation) ResetTitle() { + m.title = nil +} + +// SetContent sets the "content" field. +func (m *PostsMutation) SetContent(s string) { + m.content = &s +} + +// Content returns the value of the "content" field in the mutation. +func (m *PostsMutation) Content() (r string, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ResetContent resets all changes to the "content" field. +func (m *PostsMutation) ResetContent() { + m.content = nil +} + +// SetImages sets the "images" field. +func (m *PostsMutation) SetImages(ta types.TextArray) { + m.images = &ta +} + +// Images returns the value of the "images" field in the mutation. +func (m *PostsMutation) Images() (r types.TextArray, exists bool) { + v := m.images + if v == nil { + return + } + return *v, true +} + +// OldImages returns the old "images" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldImages(ctx context.Context) (v types.TextArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldImages is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldImages requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImages: %w", err) + } + return oldValue.Images, nil +} + +// ClearImages clears the value of the "images" field. +func (m *PostsMutation) ClearImages() { + m.images = nil + m.clearedFields[posts.FieldImages] = struct{}{} +} + +// ImagesCleared returns if the "images" field was cleared in this mutation. +func (m *PostsMutation) ImagesCleared() bool { + _, ok := m.clearedFields[posts.FieldImages] + return ok +} + +// ResetImages resets all changes to the "images" field. +func (m *PostsMutation) ResetImages() { + m.images = nil + delete(m.clearedFields, posts.FieldImages) +} + +// SetTags sets the "tags" field. +func (m *PostsMutation) SetTags(ta types.TextArray) { + m.tags = &ta +} + +// Tags returns the value of the "tags" field in the mutation. +func (m *PostsMutation) Tags() (r types.TextArray, exists bool) { + v := m.tags + if v == nil { + return + } + return *v, true +} + +// OldTags returns the old "tags" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldTags(ctx context.Context) (v types.TextArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTags is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTags requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTags: %w", err) + } + return oldValue.Tags, nil +} + +// ClearTags clears the value of the "tags" field. +func (m *PostsMutation) ClearTags() { + m.tags = nil + m.clearedFields[posts.FieldTags] = struct{}{} +} + +// TagsCleared returns if the "tags" field was cleared in this mutation. +func (m *PostsMutation) TagsCleared() bool { + _, ok := m.clearedFields[posts.FieldTags] + return ok +} + +// ResetTags resets all changes to the "tags" field. +func (m *PostsMutation) ResetTags() { + m.tags = nil + delete(m.clearedFields, posts.FieldTags) +} + +// SetLinkedOrderID sets the "linked_order_id" field. +func (m *PostsMutation) SetLinkedOrderID(i int64) { + m.linked_order_id = &i + m.addlinked_order_id = nil +} + +// LinkedOrderID returns the value of the "linked_order_id" field in the mutation. +func (m *PostsMutation) LinkedOrderID() (r int64, exists bool) { + v := m.linked_order_id + if v == nil { + return + } + return *v, true +} + +// OldLinkedOrderID returns the old "linked_order_id" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldLinkedOrderID(ctx context.Context) (v *int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLinkedOrderID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLinkedOrderID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLinkedOrderID: %w", err) + } + return oldValue.LinkedOrderID, nil +} + +// AddLinkedOrderID adds i to the "linked_order_id" field. +func (m *PostsMutation) AddLinkedOrderID(i int64) { + if m.addlinked_order_id != nil { + *m.addlinked_order_id += i + } else { + m.addlinked_order_id = &i + } +} + +// AddedLinkedOrderID returns the value that was added to the "linked_order_id" field in this mutation. +func (m *PostsMutation) AddedLinkedOrderID() (r int64, exists bool) { + v := m.addlinked_order_id + if v == nil { + return + } + return *v, true +} + +// ClearLinkedOrderID clears the value of the "linked_order_id" field. +func (m *PostsMutation) ClearLinkedOrderID() { + m.linked_order_id = nil + m.addlinked_order_id = nil + m.clearedFields[posts.FieldLinkedOrderID] = struct{}{} +} + +// LinkedOrderIDCleared returns if the "linked_order_id" field was cleared in this mutation. +func (m *PostsMutation) LinkedOrderIDCleared() bool { + _, ok := m.clearedFields[posts.FieldLinkedOrderID] + return ok +} + +// ResetLinkedOrderID resets all changes to the "linked_order_id" field. +func (m *PostsMutation) ResetLinkedOrderID() { + m.linked_order_id = nil + m.addlinked_order_id = nil + delete(m.clearedFields, posts.FieldLinkedOrderID) +} + +// SetQuotedPostID sets the "quoted_post_id" field. +func (m *PostsMutation) SetQuotedPostID(i int64) { + m.quoted_post_id = &i + m.addquoted_post_id = nil +} + +// QuotedPostID returns the value of the "quoted_post_id" field in the mutation. +func (m *PostsMutation) QuotedPostID() (r int64, exists bool) { + v := m.quoted_post_id + if v == nil { + return + } + return *v, true +} + +// OldQuotedPostID returns the old "quoted_post_id" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldQuotedPostID(ctx context.Context) (v *int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuotedPostID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuotedPostID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuotedPostID: %w", err) + } + return oldValue.QuotedPostID, nil +} + +// AddQuotedPostID adds i to the "quoted_post_id" field. +func (m *PostsMutation) AddQuotedPostID(i int64) { + if m.addquoted_post_id != nil { + *m.addquoted_post_id += i + } else { + m.addquoted_post_id = &i + } +} + +// AddedQuotedPostID returns the value that was added to the "quoted_post_id" field in this mutation. +func (m *PostsMutation) AddedQuotedPostID() (r int64, exists bool) { + v := m.addquoted_post_id + if v == nil { + return + } + return *v, true +} + +// ClearQuotedPostID clears the value of the "quoted_post_id" field. +func (m *PostsMutation) ClearQuotedPostID() { + m.quoted_post_id = nil + m.addquoted_post_id = nil + m.clearedFields[posts.FieldQuotedPostID] = struct{}{} +} + +// QuotedPostIDCleared returns if the "quoted_post_id" field was cleared in this mutation. +func (m *PostsMutation) QuotedPostIDCleared() bool { + _, ok := m.clearedFields[posts.FieldQuotedPostID] + return ok +} + +// ResetQuotedPostID resets all changes to the "quoted_post_id" field. +func (m *PostsMutation) ResetQuotedPostID() { + m.quoted_post_id = nil + m.addquoted_post_id = nil + delete(m.clearedFields, posts.FieldQuotedPostID) +} + +// SetLikeCount sets the "like_count" field. +func (m *PostsMutation) SetLikeCount(i int) { + m.like_count = &i + m.addlike_count = nil +} + +// LikeCount returns the value of the "like_count" field in the mutation. +func (m *PostsMutation) LikeCount() (r int, exists bool) { + v := m.like_count + if v == nil { + return + } + return *v, true +} + +// OldLikeCount returns the old "like_count" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldLikeCount(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLikeCount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLikeCount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLikeCount: %w", err) + } + return oldValue.LikeCount, nil +} + +// AddLikeCount adds i to the "like_count" field. +func (m *PostsMutation) AddLikeCount(i int) { + if m.addlike_count != nil { + *m.addlike_count += i + } else { + m.addlike_count = &i + } +} + +// AddedLikeCount returns the value that was added to the "like_count" field in this mutation. +func (m *PostsMutation) AddedLikeCount() (r int, exists bool) { + v := m.addlike_count + if v == nil { + return + } + return *v, true +} + +// ClearLikeCount clears the value of the "like_count" field. +func (m *PostsMutation) ClearLikeCount() { + m.like_count = nil + m.addlike_count = nil + m.clearedFields[posts.FieldLikeCount] = struct{}{} +} + +// LikeCountCleared returns if the "like_count" field was cleared in this mutation. +func (m *PostsMutation) LikeCountCleared() bool { + _, ok := m.clearedFields[posts.FieldLikeCount] + return ok +} + +// ResetLikeCount resets all changes to the "like_count" field. +func (m *PostsMutation) ResetLikeCount() { + m.like_count = nil + m.addlike_count = nil + delete(m.clearedFields, posts.FieldLikeCount) +} + +// SetCommentCount sets the "comment_count" field. +func (m *PostsMutation) SetCommentCount(i int) { + m.comment_count = &i + m.addcomment_count = nil +} + +// CommentCount returns the value of the "comment_count" field in the mutation. +func (m *PostsMutation) CommentCount() (r int, exists bool) { + v := m.comment_count + if v == nil { + return + } + return *v, true +} + +// OldCommentCount returns the old "comment_count" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldCommentCount(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCommentCount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCommentCount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCommentCount: %w", err) + } + return oldValue.CommentCount, nil +} + +// AddCommentCount adds i to the "comment_count" field. +func (m *PostsMutation) AddCommentCount(i int) { + if m.addcomment_count != nil { + *m.addcomment_count += i + } else { + m.addcomment_count = &i + } +} + +// AddedCommentCount returns the value that was added to the "comment_count" field in this mutation. +func (m *PostsMutation) AddedCommentCount() (r int, exists bool) { + v := m.addcomment_count + if v == nil { + return + } + return *v, true +} + +// ClearCommentCount clears the value of the "comment_count" field. +func (m *PostsMutation) ClearCommentCount() { + m.comment_count = nil + m.addcomment_count = nil + m.clearedFields[posts.FieldCommentCount] = struct{}{} +} + +// CommentCountCleared returns if the "comment_count" field was cleared in this mutation. +func (m *PostsMutation) CommentCountCleared() bool { + _, ok := m.clearedFields[posts.FieldCommentCount] + return ok +} + +// ResetCommentCount resets all changes to the "comment_count" field. +func (m *PostsMutation) ResetCommentCount() { + m.comment_count = nil + m.addcomment_count = nil + delete(m.clearedFields, posts.FieldCommentCount) +} + +// SetPinned sets the "pinned" field. +func (m *PostsMutation) SetPinned(b bool) { + m.pinned = &b +} + +// Pinned returns the value of the "pinned" field in the mutation. +func (m *PostsMutation) Pinned() (r bool, exists bool) { + v := m.pinned + if v == nil { + return + } + return *v, true +} + +// OldPinned returns the old "pinned" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldPinned(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPinned is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPinned requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPinned: %w", err) + } + return oldValue.Pinned, nil +} + +// ClearPinned clears the value of the "pinned" field. +func (m *PostsMutation) ClearPinned() { + m.pinned = nil + m.clearedFields[posts.FieldPinned] = struct{}{} +} + +// PinnedCleared returns if the "pinned" field was cleared in this mutation. +func (m *PostsMutation) PinnedCleared() bool { + _, ok := m.clearedFields[posts.FieldPinned] + return ok +} + +// ResetPinned resets all changes to the "pinned" field. +func (m *PostsMutation) ResetPinned() { + m.pinned = nil + delete(m.clearedFields, posts.FieldPinned) +} + +// SetCreatedAt sets the "created_at" field. +func (m *PostsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PostsMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *PostsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *PostsMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *PostsMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *PostsMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *PostsMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *PostsMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the Posts entity. +// If the Posts object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PostsMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *PostsMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[posts.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *PostsMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[posts.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *PostsMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, posts.FieldDeletedAt) +} + +// Where appends a list predicates to the PostsMutation builder. +func (m *PostsMutation) Where(ps ...predicate.Posts) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the PostsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *PostsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Posts, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *PostsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *PostsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Posts). +func (m *PostsMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *PostsMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.author_id != nil { + fields = append(fields, posts.FieldAuthorID) + } + if m.author_role != nil { + fields = append(fields, posts.FieldAuthorRole) + } + if m.title != nil { + fields = append(fields, posts.FieldTitle) + } + if m.content != nil { + fields = append(fields, posts.FieldContent) + } + if m.images != nil { + fields = append(fields, posts.FieldImages) + } + if m.tags != nil { + fields = append(fields, posts.FieldTags) + } + if m.linked_order_id != nil { + fields = append(fields, posts.FieldLinkedOrderID) + } + if m.quoted_post_id != nil { + fields = append(fields, posts.FieldQuotedPostID) + } + if m.like_count != nil { + fields = append(fields, posts.FieldLikeCount) + } + if m.comment_count != nil { + fields = append(fields, posts.FieldCommentCount) + } + if m.pinned != nil { + fields = append(fields, posts.FieldPinned) + } + if m.created_at != nil { + fields = append(fields, posts.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, posts.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, posts.FieldDeletedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *PostsMutation) Field(name string) (ent.Value, bool) { + switch name { + case posts.FieldAuthorID: + return m.AuthorID() + case posts.FieldAuthorRole: + return m.AuthorRole() + case posts.FieldTitle: + return m.Title() + case posts.FieldContent: + return m.Content() + case posts.FieldImages: + return m.Images() + case posts.FieldTags: + return m.Tags() + case posts.FieldLinkedOrderID: + return m.LinkedOrderID() + case posts.FieldQuotedPostID: + return m.QuotedPostID() + case posts.FieldLikeCount: + return m.LikeCount() + case posts.FieldCommentCount: + return m.CommentCount() + case posts.FieldPinned: + return m.Pinned() + case posts.FieldCreatedAt: + return m.CreatedAt() + case posts.FieldUpdatedAt: + return m.UpdatedAt() + case posts.FieldDeletedAt: + return m.DeletedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *PostsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case posts.FieldAuthorID: + return m.OldAuthorID(ctx) + case posts.FieldAuthorRole: + return m.OldAuthorRole(ctx) + case posts.FieldTitle: + return m.OldTitle(ctx) + case posts.FieldContent: + return m.OldContent(ctx) + case posts.FieldImages: + return m.OldImages(ctx) + case posts.FieldTags: + return m.OldTags(ctx) + case posts.FieldLinkedOrderID: + return m.OldLinkedOrderID(ctx) + case posts.FieldQuotedPostID: + return m.OldQuotedPostID(ctx) + case posts.FieldLikeCount: + return m.OldLikeCount(ctx) + case posts.FieldCommentCount: + return m.OldCommentCount(ctx) + case posts.FieldPinned: + return m.OldPinned(ctx) + case posts.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case posts.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case posts.FieldDeletedAt: + return m.OldDeletedAt(ctx) + } + return nil, fmt.Errorf("unknown Posts field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *PostsMutation) SetField(name string, value ent.Value) error { + switch name { + case posts.FieldAuthorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorID(v) + return nil + case posts.FieldAuthorRole: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorRole(v) + return nil + case posts.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case posts.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + case posts.FieldImages: + v, ok := value.(types.TextArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImages(v) + return nil + case posts.FieldTags: + v, ok := value.(types.TextArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTags(v) + return nil + case posts.FieldLinkedOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLinkedOrderID(v) + return nil + case posts.FieldQuotedPostID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuotedPostID(v) + return nil + case posts.FieldLikeCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLikeCount(v) + return nil + case posts.FieldCommentCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCommentCount(v) + return nil + case posts.FieldPinned: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPinned(v) + return nil + case posts.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case posts.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case posts.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + } + return fmt.Errorf("unknown Posts field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PostsMutation) AddedFields() []string { + var fields []string + if m.addauthor_id != nil { + fields = append(fields, posts.FieldAuthorID) + } + if m.addlinked_order_id != nil { + fields = append(fields, posts.FieldLinkedOrderID) + } + if m.addquoted_post_id != nil { + fields = append(fields, posts.FieldQuotedPostID) + } + if m.addlike_count != nil { + fields = append(fields, posts.FieldLikeCount) + } + if m.addcomment_count != nil { + fields = append(fields, posts.FieldCommentCount) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *PostsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case posts.FieldAuthorID: + return m.AddedAuthorID() + case posts.FieldLinkedOrderID: + return m.AddedLinkedOrderID() + case posts.FieldQuotedPostID: + return m.AddedQuotedPostID() + case posts.FieldLikeCount: + return m.AddedLikeCount() + case posts.FieldCommentCount: + return m.AddedCommentCount() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *PostsMutation) AddField(name string, value ent.Value) error { + switch name { + case posts.FieldAuthorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAuthorID(v) + return nil + case posts.FieldLinkedOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddLinkedOrderID(v) + return nil + case posts.FieldQuotedPostID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddQuotedPostID(v) + return nil + case posts.FieldLikeCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddLikeCount(v) + return nil + case posts.FieldCommentCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCommentCount(v) + return nil + } + return fmt.Errorf("unknown Posts numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PostsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(posts.FieldImages) { + fields = append(fields, posts.FieldImages) + } + if m.FieldCleared(posts.FieldTags) { + fields = append(fields, posts.FieldTags) + } + if m.FieldCleared(posts.FieldLinkedOrderID) { + fields = append(fields, posts.FieldLinkedOrderID) + } + if m.FieldCleared(posts.FieldQuotedPostID) { + fields = append(fields, posts.FieldQuotedPostID) + } + if m.FieldCleared(posts.FieldLikeCount) { + fields = append(fields, posts.FieldLikeCount) + } + if m.FieldCleared(posts.FieldCommentCount) { + fields = append(fields, posts.FieldCommentCount) + } + if m.FieldCleared(posts.FieldPinned) { + fields = append(fields, posts.FieldPinned) + } + if m.FieldCleared(posts.FieldDeletedAt) { + fields = append(fields, posts.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PostsMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *PostsMutation) ClearField(name string) error { + switch name { + case posts.FieldImages: + m.ClearImages() + return nil + case posts.FieldTags: + m.ClearTags() + return nil + case posts.FieldLinkedOrderID: + m.ClearLinkedOrderID() + return nil + case posts.FieldQuotedPostID: + m.ClearQuotedPostID() + return nil + case posts.FieldLikeCount: + m.ClearLikeCount() + return nil + case posts.FieldCommentCount: + m.ClearCommentCount() + return nil + case posts.FieldPinned: + m.ClearPinned() + return nil + case posts.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown Posts nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *PostsMutation) ResetField(name string) error { + switch name { + case posts.FieldAuthorID: + m.ResetAuthorID() + return nil + case posts.FieldAuthorRole: + m.ResetAuthorRole() + return nil + case posts.FieldTitle: + m.ResetTitle() + return nil + case posts.FieldContent: + m.ResetContent() + return nil + case posts.FieldImages: + m.ResetImages() + return nil + case posts.FieldTags: + m.ResetTags() + return nil + case posts.FieldLinkedOrderID: + m.ResetLinkedOrderID() + return nil + case posts.FieldQuotedPostID: + m.ResetQuotedPostID() + return nil + case posts.FieldLikeCount: + m.ResetLikeCount() + return nil + case posts.FieldCommentCount: + m.ResetCommentCount() + return nil + case posts.FieldPinned: + m.ResetPinned() + return nil + case posts.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case posts.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case posts.FieldDeletedAt: + m.ResetDeletedAt() + return nil + } + return fmt.Errorf("unknown Posts field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PostsMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PostsMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PostsMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PostsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PostsMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PostsMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *PostsMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Posts unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *PostsMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Posts edge %s", name) +} diff --git a/app/community/rpc/internal/models/postlikes.go b/app/community/rpc/internal/models/postlikes.go new file mode 100644 index 0000000..01c7f15 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes.go @@ -0,0 +1,126 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// PostLikes is the model entity for the PostLikes schema. +type PostLikes struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // PostID holds the value of the "post_id" field. + PostID int64 `json:"post_id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*PostLikes) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case postlikes.FieldID, postlikes.FieldPostID, postlikes.FieldUserID: + values[i] = new(sql.NullInt64) + case postlikes.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the PostLikes fields. +func (_m *PostLikes) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case postlikes.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case postlikes.FieldPostID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field post_id", values[i]) + } else if value.Valid { + _m.PostID = value.Int64 + } + case postlikes.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = value.Int64 + } + case postlikes.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the PostLikes. +// This includes values selected through modifiers, order, etc. +func (_m *PostLikes) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this PostLikes. +// Note that you need to call PostLikes.Unwrap() before calling this method if this PostLikes +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *PostLikes) Update() *PostLikesUpdateOne { + return NewPostLikesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the PostLikes entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *PostLikes) Unwrap() *PostLikes { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: PostLikes is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *PostLikes) String() string { + var builder strings.Builder + builder.WriteString("PostLikes(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("post_id=") + builder.WriteString(fmt.Sprintf("%v", _m.PostID)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// PostLikesSlice is a parsable slice of PostLikes. +type PostLikesSlice []*PostLikes diff --git a/app/community/rpc/internal/models/postlikes/postlikes.go b/app/community/rpc/internal/models/postlikes/postlikes.go new file mode 100644 index 0000000..81d0374 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes/postlikes.go @@ -0,0 +1,70 @@ +// Code generated by ent, DO NOT EDIT. + +package postlikes + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the postlikes type in the database. + Label = "post_likes" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPostID holds the string denoting the post_id field in the database. + FieldPostID = "post_id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the postlikes in the database. + Table = "post_likes" +) + +// Columns holds all SQL columns for postlikes fields. +var Columns = []string{ + FieldID, + FieldPostID, + FieldUserID, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the PostLikes queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByPostID orders the results by the post_id field. +func ByPostID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPostID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} diff --git a/app/community/rpc/internal/models/postlikes/where.go b/app/community/rpc/internal/models/postlikes/where.go new file mode 100644 index 0000000..e3b07a9 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes/where.go @@ -0,0 +1,205 @@ +// Code generated by ent, DO NOT EDIT. + +package postlikes + +import ( + "juwan-backend/app/community/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLTE(FieldID, id)) +} + +// PostID applies equality check predicate on the "post_id" field. It's identical to PostIDEQ. +func PostID(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldPostID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldUserID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldCreatedAt, v)) +} + +// PostIDEQ applies the EQ predicate on the "post_id" field. +func PostIDEQ(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldPostID, v)) +} + +// PostIDNEQ applies the NEQ predicate on the "post_id" field. +func PostIDNEQ(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNEQ(FieldPostID, v)) +} + +// PostIDIn applies the In predicate on the "post_id" field. +func PostIDIn(vs ...int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldIn(FieldPostID, vs...)) +} + +// PostIDNotIn applies the NotIn predicate on the "post_id" field. +func PostIDNotIn(vs ...int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNotIn(FieldPostID, vs...)) +} + +// PostIDGT applies the GT predicate on the "post_id" field. +func PostIDGT(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGT(FieldPostID, v)) +} + +// PostIDGTE applies the GTE predicate on the "post_id" field. +func PostIDGTE(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGTE(FieldPostID, v)) +} + +// PostIDLT applies the LT predicate on the "post_id" field. +func PostIDLT(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLT(FieldPostID, v)) +} + +// PostIDLTE applies the LTE predicate on the "post_id" field. +func PostIDLTE(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLTE(FieldPostID, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int64) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLTE(FieldUserID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.PostLikes { + return predicate.PostLikes(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.PostLikes) predicate.PostLikes { + return predicate.PostLikes(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.PostLikes) predicate.PostLikes { + return predicate.PostLikes(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.PostLikes) predicate.PostLikes { + return predicate.PostLikes(sql.NotPredicates(p)) +} diff --git a/app/community/rpc/internal/models/postlikes_create.go b/app/community/rpc/internal/models/postlikes_create.go new file mode 100644 index 0000000..7b05e97 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes_create.go @@ -0,0 +1,240 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostLikesCreate is the builder for creating a PostLikes entity. +type PostLikesCreate struct { + config + mutation *PostLikesMutation + hooks []Hook +} + +// SetPostID sets the "post_id" field. +func (_c *PostLikesCreate) SetPostID(v int64) *PostLikesCreate { + _c.mutation.SetPostID(v) + return _c +} + +// SetUserID sets the "user_id" field. +func (_c *PostLikesCreate) SetUserID(v int64) *PostLikesCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *PostLikesCreate) SetCreatedAt(v time.Time) *PostLikesCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *PostLikesCreate) SetNillableCreatedAt(v *time.Time) *PostLikesCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *PostLikesCreate) SetID(v int64) *PostLikesCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the PostLikesMutation object of the builder. +func (_c *PostLikesCreate) Mutation() *PostLikesMutation { + return _c.mutation +} + +// Save creates the PostLikes in the database. +func (_c *PostLikesCreate) Save(ctx context.Context) (*PostLikes, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *PostLikesCreate) SaveX(ctx context.Context) *PostLikes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *PostLikesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *PostLikesCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *PostLikesCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := postlikes.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *PostLikesCreate) check() error { + if _, ok := _c.mutation.PostID(); !ok { + return &ValidationError{Name: "post_id", err: errors.New(`models: missing required field "PostLikes.post_id"`)} + } + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "PostLikes.user_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "PostLikes.created_at"`)} + } + return nil +} + +func (_c *PostLikesCreate) sqlSave(ctx context.Context) (*PostLikes, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *PostLikesCreate) createSpec() (*PostLikes, *sqlgraph.CreateSpec) { + var ( + _node = &PostLikes{config: _c.config} + _spec = sqlgraph.NewCreateSpec(postlikes.Table, sqlgraph.NewFieldSpec(postlikes.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.PostID(); ok { + _spec.SetField(postlikes.FieldPostID, field.TypeInt64, value) + _node.PostID = value + } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(postlikes.FieldUserID, field.TypeInt64, value) + _node.UserID = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(postlikes.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// PostLikesCreateBulk is the builder for creating many PostLikes entities in bulk. +type PostLikesCreateBulk struct { + config + err error + builders []*PostLikesCreate +} + +// Save creates the PostLikes entities in the database. +func (_c *PostLikesCreateBulk) Save(ctx context.Context) ([]*PostLikes, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*PostLikes, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PostLikesMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *PostLikesCreateBulk) SaveX(ctx context.Context) []*PostLikes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *PostLikesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *PostLikesCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/postlikes_delete.go b/app/community/rpc/internal/models/postlikes_delete.go new file mode 100644 index 0000000..c5c2054 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostLikesDelete is the builder for deleting a PostLikes entity. +type PostLikesDelete struct { + config + hooks []Hook + mutation *PostLikesMutation +} + +// Where appends a list predicates to the PostLikesDelete builder. +func (_d *PostLikesDelete) Where(ps ...predicate.PostLikes) *PostLikesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *PostLikesDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *PostLikesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *PostLikesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(postlikes.Table, sqlgraph.NewFieldSpec(postlikes.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// PostLikesDeleteOne is the builder for deleting a single PostLikes entity. +type PostLikesDeleteOne struct { + _d *PostLikesDelete +} + +// Where appends a list predicates to the PostLikesDelete builder. +func (_d *PostLikesDeleteOne) Where(ps ...predicate.PostLikes) *PostLikesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *PostLikesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{postlikes.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *PostLikesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/postlikes_query.go b/app/community/rpc/internal/models/postlikes_query.go new file mode 100644 index 0000000..4304c70 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostLikesQuery is the builder for querying PostLikes entities. +type PostLikesQuery struct { + config + ctx *QueryContext + order []postlikes.OrderOption + inters []Interceptor + predicates []predicate.PostLikes + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the PostLikesQuery builder. +func (_q *PostLikesQuery) Where(ps ...predicate.PostLikes) *PostLikesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *PostLikesQuery) Limit(limit int) *PostLikesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *PostLikesQuery) Offset(offset int) *PostLikesQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *PostLikesQuery) Unique(unique bool) *PostLikesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *PostLikesQuery) Order(o ...postlikes.OrderOption) *PostLikesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first PostLikes entity from the query. +// Returns a *NotFoundError when no PostLikes was found. +func (_q *PostLikesQuery) First(ctx context.Context) (*PostLikes, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{postlikes.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *PostLikesQuery) FirstX(ctx context.Context) *PostLikes { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first PostLikes ID from the query. +// Returns a *NotFoundError when no PostLikes ID was found. +func (_q *PostLikesQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{postlikes.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *PostLikesQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single PostLikes entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one PostLikes entity is found. +// Returns a *NotFoundError when no PostLikes entities are found. +func (_q *PostLikesQuery) Only(ctx context.Context) (*PostLikes, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{postlikes.Label} + default: + return nil, &NotSingularError{postlikes.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *PostLikesQuery) OnlyX(ctx context.Context) *PostLikes { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only PostLikes ID in the query. +// Returns a *NotSingularError when more than one PostLikes ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *PostLikesQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{postlikes.Label} + default: + err = &NotSingularError{postlikes.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *PostLikesQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of PostLikesSlice. +func (_q *PostLikesQuery) All(ctx context.Context) ([]*PostLikes, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*PostLikes, *PostLikesQuery]() + return withInterceptors[[]*PostLikes](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *PostLikesQuery) AllX(ctx context.Context) []*PostLikes { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of PostLikes IDs. +func (_q *PostLikesQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(postlikes.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *PostLikesQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *PostLikesQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*PostLikesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *PostLikesQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *PostLikesQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *PostLikesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the PostLikesQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *PostLikesQuery) Clone() *PostLikesQuery { + if _q == nil { + return nil + } + return &PostLikesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]postlikes.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.PostLikes{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// PostID int64 `json:"post_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.PostLikes.Query(). +// GroupBy(postlikes.FieldPostID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *PostLikesQuery) GroupBy(field string, fields ...string) *PostLikesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &PostLikesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = postlikes.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// PostID int64 `json:"post_id,omitempty"` +// } +// +// client.PostLikes.Query(). +// Select(postlikes.FieldPostID). +// Scan(ctx, &v) +func (_q *PostLikesQuery) Select(fields ...string) *PostLikesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &PostLikesSelect{PostLikesQuery: _q} + sbuild.label = postlikes.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a PostLikesSelect configured with the given aggregations. +func (_q *PostLikesQuery) Aggregate(fns ...AggregateFunc) *PostLikesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *PostLikesQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !postlikes.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *PostLikesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PostLikes, error) { + var ( + nodes = []*PostLikes{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*PostLikes).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &PostLikes{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *PostLikesQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *PostLikesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(postlikes.Table, postlikes.Columns, sqlgraph.NewFieldSpec(postlikes.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, postlikes.FieldID) + for i := range fields { + if fields[i] != postlikes.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *PostLikesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(postlikes.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = postlikes.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// PostLikesGroupBy is the group-by builder for PostLikes entities. +type PostLikesGroupBy struct { + selector + build *PostLikesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *PostLikesGroupBy) Aggregate(fns ...AggregateFunc) *PostLikesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *PostLikesGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*PostLikesQuery, *PostLikesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *PostLikesGroupBy) sqlScan(ctx context.Context, root *PostLikesQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// PostLikesSelect is the builder for selecting fields of PostLikes entities. +type PostLikesSelect struct { + *PostLikesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *PostLikesSelect) Aggregate(fns ...AggregateFunc) *PostLikesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *PostLikesSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*PostLikesQuery, *PostLikesSelect](ctx, _s.PostLikesQuery, _s, _s.inters, v) +} + +func (_s *PostLikesSelect) sqlScan(ctx context.Context, root *PostLikesQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/community/rpc/internal/models/postlikes_update.go b/app/community/rpc/internal/models/postlikes_update.go new file mode 100644 index 0000000..81bac53 --- /dev/null +++ b/app/community/rpc/internal/models/postlikes_update.go @@ -0,0 +1,283 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostLikesUpdate is the builder for updating PostLikes entities. +type PostLikesUpdate struct { + config + hooks []Hook + mutation *PostLikesMutation +} + +// Where appends a list predicates to the PostLikesUpdate builder. +func (_u *PostLikesUpdate) Where(ps ...predicate.PostLikes) *PostLikesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetPostID sets the "post_id" field. +func (_u *PostLikesUpdate) SetPostID(v int64) *PostLikesUpdate { + _u.mutation.ResetPostID() + _u.mutation.SetPostID(v) + return _u +} + +// SetNillablePostID sets the "post_id" field if the given value is not nil. +func (_u *PostLikesUpdate) SetNillablePostID(v *int64) *PostLikesUpdate { + if v != nil { + _u.SetPostID(*v) + } + return _u +} + +// AddPostID adds value to the "post_id" field. +func (_u *PostLikesUpdate) AddPostID(v int64) *PostLikesUpdate { + _u.mutation.AddPostID(v) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *PostLikesUpdate) SetUserID(v int64) *PostLikesUpdate { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *PostLikesUpdate) SetNillableUserID(v *int64) *PostLikesUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *PostLikesUpdate) AddUserID(v int64) *PostLikesUpdate { + _u.mutation.AddUserID(v) + return _u +} + +// Mutation returns the PostLikesMutation object of the builder. +func (_u *PostLikesUpdate) Mutation() *PostLikesMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *PostLikesUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *PostLikesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *PostLikesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *PostLikesUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *PostLikesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(postlikes.Table, postlikes.Columns, sqlgraph.NewFieldSpec(postlikes.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.PostID(); ok { + _spec.SetField(postlikes.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPostID(); ok { + _spec.AddField(postlikes.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(postlikes.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(postlikes.FieldUserID, field.TypeInt64, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{postlikes.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// PostLikesUpdateOne is the builder for updating a single PostLikes entity. +type PostLikesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *PostLikesMutation +} + +// SetPostID sets the "post_id" field. +func (_u *PostLikesUpdateOne) SetPostID(v int64) *PostLikesUpdateOne { + _u.mutation.ResetPostID() + _u.mutation.SetPostID(v) + return _u +} + +// SetNillablePostID sets the "post_id" field if the given value is not nil. +func (_u *PostLikesUpdateOne) SetNillablePostID(v *int64) *PostLikesUpdateOne { + if v != nil { + _u.SetPostID(*v) + } + return _u +} + +// AddPostID adds value to the "post_id" field. +func (_u *PostLikesUpdateOne) AddPostID(v int64) *PostLikesUpdateOne { + _u.mutation.AddPostID(v) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *PostLikesUpdateOne) SetUserID(v int64) *PostLikesUpdateOne { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *PostLikesUpdateOne) SetNillableUserID(v *int64) *PostLikesUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *PostLikesUpdateOne) AddUserID(v int64) *PostLikesUpdateOne { + _u.mutation.AddUserID(v) + return _u +} + +// Mutation returns the PostLikesMutation object of the builder. +func (_u *PostLikesUpdateOne) Mutation() *PostLikesMutation { + return _u.mutation +} + +// Where appends a list predicates to the PostLikesUpdate builder. +func (_u *PostLikesUpdateOne) Where(ps ...predicate.PostLikes) *PostLikesUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *PostLikesUpdateOne) Select(field string, fields ...string) *PostLikesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated PostLikes entity. +func (_u *PostLikesUpdateOne) Save(ctx context.Context) (*PostLikes, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *PostLikesUpdateOne) SaveX(ctx context.Context) *PostLikes { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *PostLikesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *PostLikesUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *PostLikesUpdateOne) sqlSave(ctx context.Context) (_node *PostLikes, err error) { + _spec := sqlgraph.NewUpdateSpec(postlikes.Table, postlikes.Columns, sqlgraph.NewFieldSpec(postlikes.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "PostLikes.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, postlikes.FieldID) + for _, f := range fields { + if !postlikes.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != postlikes.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.PostID(); ok { + _spec.SetField(postlikes.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPostID(); ok { + _spec.AddField(postlikes.FieldPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(postlikes.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(postlikes.FieldUserID, field.TypeInt64, value) + } + _node = &PostLikes{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{postlikes.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/community/rpc/internal/models/posts.go b/app/community/rpc/internal/models/posts.go new file mode 100644 index 0000000..76b345b --- /dev/null +++ b/app/community/rpc/internal/models/posts.go @@ -0,0 +1,263 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/pkg/types" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Posts is the model entity for the Posts schema. +type Posts struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // AuthorID holds the value of the "author_id" field. + AuthorID int64 `json:"author_id,omitempty"` + // AuthorRole holds the value of the "author_role" field. + AuthorRole string `json:"author_role,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // Content holds the value of the "content" field. + Content string `json:"content,omitempty"` + // Images holds the value of the "images" field. + Images types.TextArray `json:"images,omitempty"` + // Tags holds the value of the "tags" field. + Tags types.TextArray `json:"tags,omitempty"` + // LinkedOrderID holds the value of the "linked_order_id" field. + LinkedOrderID *int64 `json:"linked_order_id,omitempty"` + // QuotedPostID holds the value of the "quoted_post_id" field. + QuotedPostID *int64 `json:"quoted_post_id,omitempty"` + // LikeCount holds the value of the "like_count" field. + LikeCount int `json:"like_count,omitempty"` + // CommentCount holds the value of the "comment_count" field. + CommentCount int `json:"comment_count,omitempty"` + // Pinned holds the value of the "pinned" field. + Pinned bool `json:"pinned,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Posts) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case posts.FieldPinned: + values[i] = new(sql.NullBool) + case posts.FieldID, posts.FieldAuthorID, posts.FieldLinkedOrderID, posts.FieldQuotedPostID, posts.FieldLikeCount, posts.FieldCommentCount: + values[i] = new(sql.NullInt64) + case posts.FieldAuthorRole, posts.FieldTitle, posts.FieldContent: + values[i] = new(sql.NullString) + case posts.FieldCreatedAt, posts.FieldUpdatedAt, posts.FieldDeletedAt: + values[i] = new(sql.NullTime) + case posts.FieldImages, posts.FieldTags: + values[i] = new(types.TextArray) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Posts fields. +func (_m *Posts) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case posts.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case posts.FieldAuthorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field author_id", values[i]) + } else if value.Valid { + _m.AuthorID = value.Int64 + } + case posts.FieldAuthorRole: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field author_role", values[i]) + } else if value.Valid { + _m.AuthorRole = value.String + } + case posts.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + _m.Title = value.String + } + case posts.FieldContent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content", values[i]) + } else if value.Valid { + _m.Content = value.String + } + case posts.FieldImages: + if value, ok := values[i].(*types.TextArray); !ok { + return fmt.Errorf("unexpected type %T for field images", values[i]) + } else if value != nil { + _m.Images = *value + } + case posts.FieldTags: + if value, ok := values[i].(*types.TextArray); !ok { + return fmt.Errorf("unexpected type %T for field tags", values[i]) + } else if value != nil { + _m.Tags = *value + } + case posts.FieldLinkedOrderID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field linked_order_id", values[i]) + } else if value.Valid { + _m.LinkedOrderID = new(int64) + *_m.LinkedOrderID = value.Int64 + } + case posts.FieldQuotedPostID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field quoted_post_id", values[i]) + } else if value.Valid { + _m.QuotedPostID = new(int64) + *_m.QuotedPostID = value.Int64 + } + case posts.FieldLikeCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field like_count", values[i]) + } else if value.Valid { + _m.LikeCount = int(value.Int64) + } + case posts.FieldCommentCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field comment_count", values[i]) + } else if value.Valid { + _m.CommentCount = int(value.Int64) + } + case posts.FieldPinned: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field pinned", values[i]) + } else if value.Valid { + _m.Pinned = value.Bool + } + case posts.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case posts.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case posts.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = new(time.Time) + *_m.DeletedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Posts. +// This includes values selected through modifiers, order, etc. +func (_m *Posts) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Posts. +// Note that you need to call Posts.Unwrap() before calling this method if this Posts +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Posts) Update() *PostsUpdateOne { + return NewPostsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Posts entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Posts) Unwrap() *Posts { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Posts is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Posts) String() string { + var builder strings.Builder + builder.WriteString("Posts(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("author_id=") + builder.WriteString(fmt.Sprintf("%v", _m.AuthorID)) + builder.WriteString(", ") + builder.WriteString("author_role=") + builder.WriteString(_m.AuthorRole) + builder.WriteString(", ") + builder.WriteString("title=") + builder.WriteString(_m.Title) + builder.WriteString(", ") + builder.WriteString("content=") + builder.WriteString(_m.Content) + builder.WriteString(", ") + builder.WriteString("images=") + builder.WriteString(fmt.Sprintf("%v", _m.Images)) + builder.WriteString(", ") + builder.WriteString("tags=") + builder.WriteString(fmt.Sprintf("%v", _m.Tags)) + builder.WriteString(", ") + if v := _m.LinkedOrderID; v != nil { + builder.WriteString("linked_order_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.QuotedPostID; v != nil { + builder.WriteString("quoted_post_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("like_count=") + builder.WriteString(fmt.Sprintf("%v", _m.LikeCount)) + builder.WriteString(", ") + builder.WriteString("comment_count=") + builder.WriteString(fmt.Sprintf("%v", _m.CommentCount)) + builder.WriteString(", ") + builder.WriteString("pinned=") + builder.WriteString(fmt.Sprintf("%v", _m.Pinned)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// PostsSlice is a parsable slice of Posts. +type PostsSlice []*Posts diff --git a/app/community/rpc/internal/models/posts/posts.go b/app/community/rpc/internal/models/posts/posts.go new file mode 100644 index 0000000..00e63e7 --- /dev/null +++ b/app/community/rpc/internal/models/posts/posts.go @@ -0,0 +1,174 @@ +// Code generated by ent, DO NOT EDIT. + +package posts + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the posts type in the database. + Label = "posts" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldAuthorID holds the string denoting the author_id field in the database. + FieldAuthorID = "author_id" + // FieldAuthorRole holds the string denoting the author_role field in the database. + FieldAuthorRole = "author_role" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + // FieldImages holds the string denoting the images field in the database. + FieldImages = "images" + // FieldTags holds the string denoting the tags field in the database. + FieldTags = "tags" + // FieldLinkedOrderID holds the string denoting the linked_order_id field in the database. + FieldLinkedOrderID = "linked_order_id" + // FieldQuotedPostID holds the string denoting the quoted_post_id field in the database. + FieldQuotedPostID = "quoted_post_id" + // FieldLikeCount holds the string denoting the like_count field in the database. + FieldLikeCount = "like_count" + // FieldCommentCount holds the string denoting the comment_count field in the database. + FieldCommentCount = "comment_count" + // FieldPinned holds the string denoting the pinned field in the database. + FieldPinned = "pinned" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // Table holds the table name of the posts in the database. + Table = "posts" +) + +// Columns holds all SQL columns for posts fields. +var Columns = []string{ + FieldID, + FieldAuthorID, + FieldAuthorRole, + FieldTitle, + FieldContent, + FieldImages, + FieldTags, + FieldLinkedOrderID, + FieldQuotedPostID, + FieldLikeCount, + FieldCommentCount, + FieldPinned, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultAuthorRole holds the default value on creation for the "author_role" field. + DefaultAuthorRole string + // AuthorRoleValidator is a validator for the "author_role" field. It is called by the builders before save. + AuthorRoleValidator func(string) error + // TitleValidator is a validator for the "title" field. It is called by the builders before save. + TitleValidator func(string) error + // DefaultLikeCount holds the default value on creation for the "like_count" field. + DefaultLikeCount int + // DefaultCommentCount holds the default value on creation for the "comment_count" field. + DefaultCommentCount int + // DefaultPinned holds the default value on creation for the "pinned" field. + DefaultPinned bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Posts queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByAuthorID orders the results by the author_id field. +func ByAuthorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorID, opts...).ToFunc() +} + +// ByAuthorRole orders the results by the author_role field. +func ByAuthorRole(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorRole, opts...).ToFunc() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByContent orders the results by the content field. +func ByContent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContent, opts...).ToFunc() +} + +// ByImages orders the results by the images field. +func ByImages(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldImages, opts...).ToFunc() +} + +// ByTags orders the results by the tags field. +func ByTags(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTags, opts...).ToFunc() +} + +// ByLinkedOrderID orders the results by the linked_order_id field. +func ByLinkedOrderID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLinkedOrderID, opts...).ToFunc() +} + +// ByQuotedPostID orders the results by the quoted_post_id field. +func ByQuotedPostID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQuotedPostID, opts...).ToFunc() +} + +// ByLikeCount orders the results by the like_count field. +func ByLikeCount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLikeCount, opts...).ToFunc() +} + +// ByCommentCount orders the results by the comment_count field. +func ByCommentCount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCommentCount, opts...).ToFunc() +} + +// ByPinned orders the results by the pinned field. +func ByPinned(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPinned, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} diff --git a/app/community/rpc/internal/models/posts/where.go b/app/community/rpc/internal/models/posts/where.go new file mode 100644 index 0000000..c0164d6 --- /dev/null +++ b/app/community/rpc/internal/models/posts/where.go @@ -0,0 +1,826 @@ +// Code generated by ent, DO NOT EDIT. + +package posts + +import ( + "juwan-backend/app/community/rpc/internal/models/predicate" + "juwan-backend/pkg/types" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldID, id)) +} + +// AuthorID applies equality check predicate on the "author_id" field. It's identical to AuthorIDEQ. +func AuthorID(v int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldAuthorID, v)) +} + +// AuthorRole applies equality check predicate on the "author_role" field. It's identical to AuthorRoleEQ. +func AuthorRole(v string) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldAuthorRole, v)) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldTitle, v)) +} + +// Content applies equality check predicate on the "content" field. It's identical to ContentEQ. +func Content(v string) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldContent, v)) +} + +// Images applies equality check predicate on the "images" field. It's identical to ImagesEQ. +func Images(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldImages, v)) +} + +// Tags applies equality check predicate on the "tags" field. It's identical to TagsEQ. +func Tags(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldTags, v)) +} + +// LinkedOrderID applies equality check predicate on the "linked_order_id" field. It's identical to LinkedOrderIDEQ. +func LinkedOrderID(v int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldLinkedOrderID, v)) +} + +// QuotedPostID applies equality check predicate on the "quoted_post_id" field. It's identical to QuotedPostIDEQ. +func QuotedPostID(v int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldQuotedPostID, v)) +} + +// LikeCount applies equality check predicate on the "like_count" field. It's identical to LikeCountEQ. +func LikeCount(v int) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldLikeCount, v)) +} + +// CommentCount applies equality check predicate on the "comment_count" field. It's identical to CommentCountEQ. +func CommentCount(v int) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldCommentCount, v)) +} + +// Pinned applies equality check predicate on the "pinned" field. It's identical to PinnedEQ. +func Pinned(v bool) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldPinned, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldDeletedAt, v)) +} + +// AuthorIDEQ applies the EQ predicate on the "author_id" field. +func AuthorIDEQ(v int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldAuthorID, v)) +} + +// AuthorIDNEQ applies the NEQ predicate on the "author_id" field. +func AuthorIDNEQ(v int64) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldAuthorID, v)) +} + +// AuthorIDIn applies the In predicate on the "author_id" field. +func AuthorIDIn(vs ...int64) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldAuthorID, vs...)) +} + +// AuthorIDNotIn applies the NotIn predicate on the "author_id" field. +func AuthorIDNotIn(vs ...int64) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldAuthorID, vs...)) +} + +// AuthorIDGT applies the GT predicate on the "author_id" field. +func AuthorIDGT(v int64) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldAuthorID, v)) +} + +// AuthorIDGTE applies the GTE predicate on the "author_id" field. +func AuthorIDGTE(v int64) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldAuthorID, v)) +} + +// AuthorIDLT applies the LT predicate on the "author_id" field. +func AuthorIDLT(v int64) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldAuthorID, v)) +} + +// AuthorIDLTE applies the LTE predicate on the "author_id" field. +func AuthorIDLTE(v int64) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldAuthorID, v)) +} + +// AuthorRoleEQ applies the EQ predicate on the "author_role" field. +func AuthorRoleEQ(v string) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldAuthorRole, v)) +} + +// AuthorRoleNEQ applies the NEQ predicate on the "author_role" field. +func AuthorRoleNEQ(v string) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldAuthorRole, v)) +} + +// AuthorRoleIn applies the In predicate on the "author_role" field. +func AuthorRoleIn(vs ...string) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldAuthorRole, vs...)) +} + +// AuthorRoleNotIn applies the NotIn predicate on the "author_role" field. +func AuthorRoleNotIn(vs ...string) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldAuthorRole, vs...)) +} + +// AuthorRoleGT applies the GT predicate on the "author_role" field. +func AuthorRoleGT(v string) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldAuthorRole, v)) +} + +// AuthorRoleGTE applies the GTE predicate on the "author_role" field. +func AuthorRoleGTE(v string) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldAuthorRole, v)) +} + +// AuthorRoleLT applies the LT predicate on the "author_role" field. +func AuthorRoleLT(v string) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldAuthorRole, v)) +} + +// AuthorRoleLTE applies the LTE predicate on the "author_role" field. +func AuthorRoleLTE(v string) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldAuthorRole, v)) +} + +// AuthorRoleContains applies the Contains predicate on the "author_role" field. +func AuthorRoleContains(v string) predicate.Posts { + return predicate.Posts(sql.FieldContains(FieldAuthorRole, v)) +} + +// AuthorRoleHasPrefix applies the HasPrefix predicate on the "author_role" field. +func AuthorRoleHasPrefix(v string) predicate.Posts { + return predicate.Posts(sql.FieldHasPrefix(FieldAuthorRole, v)) +} + +// AuthorRoleHasSuffix applies the HasSuffix predicate on the "author_role" field. +func AuthorRoleHasSuffix(v string) predicate.Posts { + return predicate.Posts(sql.FieldHasSuffix(FieldAuthorRole, v)) +} + +// AuthorRoleEqualFold applies the EqualFold predicate on the "author_role" field. +func AuthorRoleEqualFold(v string) predicate.Posts { + return predicate.Posts(sql.FieldEqualFold(FieldAuthorRole, v)) +} + +// AuthorRoleContainsFold applies the ContainsFold predicate on the "author_role" field. +func AuthorRoleContainsFold(v string) predicate.Posts { + return predicate.Posts(sql.FieldContainsFold(FieldAuthorRole, v)) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldTitle, v)) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldTitle, v)) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldTitle, vs...)) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldTitle, vs...)) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldTitle, v)) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldTitle, v)) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldTitle, v)) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldTitle, v)) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Posts { + return predicate.Posts(sql.FieldContains(FieldTitle, v)) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Posts { + return predicate.Posts(sql.FieldHasPrefix(FieldTitle, v)) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Posts { + return predicate.Posts(sql.FieldHasSuffix(FieldTitle, v)) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Posts { + return predicate.Posts(sql.FieldEqualFold(FieldTitle, v)) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Posts { + return predicate.Posts(sql.FieldContainsFold(FieldTitle, v)) +} + +// ContentEQ applies the EQ predicate on the "content" field. +func ContentEQ(v string) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldContent, v)) +} + +// ContentNEQ applies the NEQ predicate on the "content" field. +func ContentNEQ(v string) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldContent, v)) +} + +// ContentIn applies the In predicate on the "content" field. +func ContentIn(vs ...string) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldContent, vs...)) +} + +// ContentNotIn applies the NotIn predicate on the "content" field. +func ContentNotIn(vs ...string) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldContent, vs...)) +} + +// ContentGT applies the GT predicate on the "content" field. +func ContentGT(v string) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldContent, v)) +} + +// ContentGTE applies the GTE predicate on the "content" field. +func ContentGTE(v string) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldContent, v)) +} + +// ContentLT applies the LT predicate on the "content" field. +func ContentLT(v string) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldContent, v)) +} + +// ContentLTE applies the LTE predicate on the "content" field. +func ContentLTE(v string) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldContent, v)) +} + +// ContentContains applies the Contains predicate on the "content" field. +func ContentContains(v string) predicate.Posts { + return predicate.Posts(sql.FieldContains(FieldContent, v)) +} + +// ContentHasPrefix applies the HasPrefix predicate on the "content" field. +func ContentHasPrefix(v string) predicate.Posts { + return predicate.Posts(sql.FieldHasPrefix(FieldContent, v)) +} + +// ContentHasSuffix applies the HasSuffix predicate on the "content" field. +func ContentHasSuffix(v string) predicate.Posts { + return predicate.Posts(sql.FieldHasSuffix(FieldContent, v)) +} + +// ContentEqualFold applies the EqualFold predicate on the "content" field. +func ContentEqualFold(v string) predicate.Posts { + return predicate.Posts(sql.FieldEqualFold(FieldContent, v)) +} + +// ContentContainsFold applies the ContainsFold predicate on the "content" field. +func ContentContainsFold(v string) predicate.Posts { + return predicate.Posts(sql.FieldContainsFold(FieldContent, v)) +} + +// ImagesEQ applies the EQ predicate on the "images" field. +func ImagesEQ(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldImages, v)) +} + +// ImagesNEQ applies the NEQ predicate on the "images" field. +func ImagesNEQ(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldImages, v)) +} + +// ImagesIn applies the In predicate on the "images" field. +func ImagesIn(vs ...types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldImages, vs...)) +} + +// ImagesNotIn applies the NotIn predicate on the "images" field. +func ImagesNotIn(vs ...types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldImages, vs...)) +} + +// ImagesGT applies the GT predicate on the "images" field. +func ImagesGT(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldImages, v)) +} + +// ImagesGTE applies the GTE predicate on the "images" field. +func ImagesGTE(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldImages, v)) +} + +// ImagesLT applies the LT predicate on the "images" field. +func ImagesLT(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldImages, v)) +} + +// ImagesLTE applies the LTE predicate on the "images" field. +func ImagesLTE(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldImages, v)) +} + +// ImagesIsNil applies the IsNil predicate on the "images" field. +func ImagesIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldImages)) +} + +// ImagesNotNil applies the NotNil predicate on the "images" field. +func ImagesNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldImages)) +} + +// TagsEQ applies the EQ predicate on the "tags" field. +func TagsEQ(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldTags, v)) +} + +// TagsNEQ applies the NEQ predicate on the "tags" field. +func TagsNEQ(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldTags, v)) +} + +// TagsIn applies the In predicate on the "tags" field. +func TagsIn(vs ...types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldTags, vs...)) +} + +// TagsNotIn applies the NotIn predicate on the "tags" field. +func TagsNotIn(vs ...types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldTags, vs...)) +} + +// TagsGT applies the GT predicate on the "tags" field. +func TagsGT(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldTags, v)) +} + +// TagsGTE applies the GTE predicate on the "tags" field. +func TagsGTE(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldTags, v)) +} + +// TagsLT applies the LT predicate on the "tags" field. +func TagsLT(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldTags, v)) +} + +// TagsLTE applies the LTE predicate on the "tags" field. +func TagsLTE(v types.TextArray) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldTags, v)) +} + +// TagsIsNil applies the IsNil predicate on the "tags" field. +func TagsIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldTags)) +} + +// TagsNotNil applies the NotNil predicate on the "tags" field. +func TagsNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldTags)) +} + +// LinkedOrderIDEQ applies the EQ predicate on the "linked_order_id" field. +func LinkedOrderIDEQ(v int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldLinkedOrderID, v)) +} + +// LinkedOrderIDNEQ applies the NEQ predicate on the "linked_order_id" field. +func LinkedOrderIDNEQ(v int64) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldLinkedOrderID, v)) +} + +// LinkedOrderIDIn applies the In predicate on the "linked_order_id" field. +func LinkedOrderIDIn(vs ...int64) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldLinkedOrderID, vs...)) +} + +// LinkedOrderIDNotIn applies the NotIn predicate on the "linked_order_id" field. +func LinkedOrderIDNotIn(vs ...int64) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldLinkedOrderID, vs...)) +} + +// LinkedOrderIDGT applies the GT predicate on the "linked_order_id" field. +func LinkedOrderIDGT(v int64) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldLinkedOrderID, v)) +} + +// LinkedOrderIDGTE applies the GTE predicate on the "linked_order_id" field. +func LinkedOrderIDGTE(v int64) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldLinkedOrderID, v)) +} + +// LinkedOrderIDLT applies the LT predicate on the "linked_order_id" field. +func LinkedOrderIDLT(v int64) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldLinkedOrderID, v)) +} + +// LinkedOrderIDLTE applies the LTE predicate on the "linked_order_id" field. +func LinkedOrderIDLTE(v int64) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldLinkedOrderID, v)) +} + +// LinkedOrderIDIsNil applies the IsNil predicate on the "linked_order_id" field. +func LinkedOrderIDIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldLinkedOrderID)) +} + +// LinkedOrderIDNotNil applies the NotNil predicate on the "linked_order_id" field. +func LinkedOrderIDNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldLinkedOrderID)) +} + +// QuotedPostIDEQ applies the EQ predicate on the "quoted_post_id" field. +func QuotedPostIDEQ(v int64) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldQuotedPostID, v)) +} + +// QuotedPostIDNEQ applies the NEQ predicate on the "quoted_post_id" field. +func QuotedPostIDNEQ(v int64) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldQuotedPostID, v)) +} + +// QuotedPostIDIn applies the In predicate on the "quoted_post_id" field. +func QuotedPostIDIn(vs ...int64) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldQuotedPostID, vs...)) +} + +// QuotedPostIDNotIn applies the NotIn predicate on the "quoted_post_id" field. +func QuotedPostIDNotIn(vs ...int64) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldQuotedPostID, vs...)) +} + +// QuotedPostIDGT applies the GT predicate on the "quoted_post_id" field. +func QuotedPostIDGT(v int64) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldQuotedPostID, v)) +} + +// QuotedPostIDGTE applies the GTE predicate on the "quoted_post_id" field. +func QuotedPostIDGTE(v int64) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldQuotedPostID, v)) +} + +// QuotedPostIDLT applies the LT predicate on the "quoted_post_id" field. +func QuotedPostIDLT(v int64) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldQuotedPostID, v)) +} + +// QuotedPostIDLTE applies the LTE predicate on the "quoted_post_id" field. +func QuotedPostIDLTE(v int64) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldQuotedPostID, v)) +} + +// QuotedPostIDIsNil applies the IsNil predicate on the "quoted_post_id" field. +func QuotedPostIDIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldQuotedPostID)) +} + +// QuotedPostIDNotNil applies the NotNil predicate on the "quoted_post_id" field. +func QuotedPostIDNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldQuotedPostID)) +} + +// LikeCountEQ applies the EQ predicate on the "like_count" field. +func LikeCountEQ(v int) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldLikeCount, v)) +} + +// LikeCountNEQ applies the NEQ predicate on the "like_count" field. +func LikeCountNEQ(v int) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldLikeCount, v)) +} + +// LikeCountIn applies the In predicate on the "like_count" field. +func LikeCountIn(vs ...int) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldLikeCount, vs...)) +} + +// LikeCountNotIn applies the NotIn predicate on the "like_count" field. +func LikeCountNotIn(vs ...int) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldLikeCount, vs...)) +} + +// LikeCountGT applies the GT predicate on the "like_count" field. +func LikeCountGT(v int) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldLikeCount, v)) +} + +// LikeCountGTE applies the GTE predicate on the "like_count" field. +func LikeCountGTE(v int) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldLikeCount, v)) +} + +// LikeCountLT applies the LT predicate on the "like_count" field. +func LikeCountLT(v int) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldLikeCount, v)) +} + +// LikeCountLTE applies the LTE predicate on the "like_count" field. +func LikeCountLTE(v int) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldLikeCount, v)) +} + +// LikeCountIsNil applies the IsNil predicate on the "like_count" field. +func LikeCountIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldLikeCount)) +} + +// LikeCountNotNil applies the NotNil predicate on the "like_count" field. +func LikeCountNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldLikeCount)) +} + +// CommentCountEQ applies the EQ predicate on the "comment_count" field. +func CommentCountEQ(v int) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldCommentCount, v)) +} + +// CommentCountNEQ applies the NEQ predicate on the "comment_count" field. +func CommentCountNEQ(v int) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldCommentCount, v)) +} + +// CommentCountIn applies the In predicate on the "comment_count" field. +func CommentCountIn(vs ...int) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldCommentCount, vs...)) +} + +// CommentCountNotIn applies the NotIn predicate on the "comment_count" field. +func CommentCountNotIn(vs ...int) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldCommentCount, vs...)) +} + +// CommentCountGT applies the GT predicate on the "comment_count" field. +func CommentCountGT(v int) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldCommentCount, v)) +} + +// CommentCountGTE applies the GTE predicate on the "comment_count" field. +func CommentCountGTE(v int) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldCommentCount, v)) +} + +// CommentCountLT applies the LT predicate on the "comment_count" field. +func CommentCountLT(v int) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldCommentCount, v)) +} + +// CommentCountLTE applies the LTE predicate on the "comment_count" field. +func CommentCountLTE(v int) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldCommentCount, v)) +} + +// CommentCountIsNil applies the IsNil predicate on the "comment_count" field. +func CommentCountIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldCommentCount)) +} + +// CommentCountNotNil applies the NotNil predicate on the "comment_count" field. +func CommentCountNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldCommentCount)) +} + +// PinnedEQ applies the EQ predicate on the "pinned" field. +func PinnedEQ(v bool) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldPinned, v)) +} + +// PinnedNEQ applies the NEQ predicate on the "pinned" field. +func PinnedNEQ(v bool) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldPinned, v)) +} + +// PinnedIsNil applies the IsNil predicate on the "pinned" field. +func PinnedIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldPinned)) +} + +// PinnedNotNil applies the NotNil predicate on the "pinned" field. +func PinnedNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldPinned)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Posts { + return predicate.Posts(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Posts { + return predicate.Posts(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Posts { + return predicate.Posts(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Posts { + return predicate.Posts(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Posts { + return predicate.Posts(sql.FieldNotNull(FieldDeletedAt)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Posts) predicate.Posts { + return predicate.Posts(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Posts) predicate.Posts { + return predicate.Posts(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Posts) predicate.Posts { + return predicate.Posts(sql.NotPredicates(p)) +} diff --git a/app/community/rpc/internal/models/posts_create.go b/app/community/rpc/internal/models/posts_create.go new file mode 100644 index 0000000..6d340c8 --- /dev/null +++ b/app/community/rpc/internal/models/posts_create.go @@ -0,0 +1,470 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/pkg/types" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostsCreate is the builder for creating a Posts entity. +type PostsCreate struct { + config + mutation *PostsMutation + hooks []Hook +} + +// SetAuthorID sets the "author_id" field. +func (_c *PostsCreate) SetAuthorID(v int64) *PostsCreate { + _c.mutation.SetAuthorID(v) + return _c +} + +// SetAuthorRole sets the "author_role" field. +func (_c *PostsCreate) SetAuthorRole(v string) *PostsCreate { + _c.mutation.SetAuthorRole(v) + return _c +} + +// SetNillableAuthorRole sets the "author_role" field if the given value is not nil. +func (_c *PostsCreate) SetNillableAuthorRole(v *string) *PostsCreate { + if v != nil { + _c.SetAuthorRole(*v) + } + return _c +} + +// SetTitle sets the "title" field. +func (_c *PostsCreate) SetTitle(v string) *PostsCreate { + _c.mutation.SetTitle(v) + return _c +} + +// SetContent sets the "content" field. +func (_c *PostsCreate) SetContent(v string) *PostsCreate { + _c.mutation.SetContent(v) + return _c +} + +// SetImages sets the "images" field. +func (_c *PostsCreate) SetImages(v types.TextArray) *PostsCreate { + _c.mutation.SetImages(v) + return _c +} + +// SetNillableImages sets the "images" field if the given value is not nil. +func (_c *PostsCreate) SetNillableImages(v *types.TextArray) *PostsCreate { + if v != nil { + _c.SetImages(*v) + } + return _c +} + +// SetTags sets the "tags" field. +func (_c *PostsCreate) SetTags(v types.TextArray) *PostsCreate { + _c.mutation.SetTags(v) + return _c +} + +// SetNillableTags sets the "tags" field if the given value is not nil. +func (_c *PostsCreate) SetNillableTags(v *types.TextArray) *PostsCreate { + if v != nil { + _c.SetTags(*v) + } + return _c +} + +// SetLinkedOrderID sets the "linked_order_id" field. +func (_c *PostsCreate) SetLinkedOrderID(v int64) *PostsCreate { + _c.mutation.SetLinkedOrderID(v) + return _c +} + +// SetNillableLinkedOrderID sets the "linked_order_id" field if the given value is not nil. +func (_c *PostsCreate) SetNillableLinkedOrderID(v *int64) *PostsCreate { + if v != nil { + _c.SetLinkedOrderID(*v) + } + return _c +} + +// SetQuotedPostID sets the "quoted_post_id" field. +func (_c *PostsCreate) SetQuotedPostID(v int64) *PostsCreate { + _c.mutation.SetQuotedPostID(v) + return _c +} + +// SetNillableQuotedPostID sets the "quoted_post_id" field if the given value is not nil. +func (_c *PostsCreate) SetNillableQuotedPostID(v *int64) *PostsCreate { + if v != nil { + _c.SetQuotedPostID(*v) + } + return _c +} + +// SetLikeCount sets the "like_count" field. +func (_c *PostsCreate) SetLikeCount(v int) *PostsCreate { + _c.mutation.SetLikeCount(v) + return _c +} + +// SetNillableLikeCount sets the "like_count" field if the given value is not nil. +func (_c *PostsCreate) SetNillableLikeCount(v *int) *PostsCreate { + if v != nil { + _c.SetLikeCount(*v) + } + return _c +} + +// SetCommentCount sets the "comment_count" field. +func (_c *PostsCreate) SetCommentCount(v int) *PostsCreate { + _c.mutation.SetCommentCount(v) + return _c +} + +// SetNillableCommentCount sets the "comment_count" field if the given value is not nil. +func (_c *PostsCreate) SetNillableCommentCount(v *int) *PostsCreate { + if v != nil { + _c.SetCommentCount(*v) + } + return _c +} + +// SetPinned sets the "pinned" field. +func (_c *PostsCreate) SetPinned(v bool) *PostsCreate { + _c.mutation.SetPinned(v) + return _c +} + +// SetNillablePinned sets the "pinned" field if the given value is not nil. +func (_c *PostsCreate) SetNillablePinned(v *bool) *PostsCreate { + if v != nil { + _c.SetPinned(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *PostsCreate) SetCreatedAt(v time.Time) *PostsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *PostsCreate) SetNillableCreatedAt(v *time.Time) *PostsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *PostsCreate) SetUpdatedAt(v time.Time) *PostsCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *PostsCreate) SetNillableUpdatedAt(v *time.Time) *PostsCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *PostsCreate) SetDeletedAt(v time.Time) *PostsCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *PostsCreate) SetNillableDeletedAt(v *time.Time) *PostsCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *PostsCreate) SetID(v int64) *PostsCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the PostsMutation object of the builder. +func (_c *PostsCreate) Mutation() *PostsMutation { + return _c.mutation +} + +// Save creates the Posts in the database. +func (_c *PostsCreate) Save(ctx context.Context) (*Posts, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *PostsCreate) SaveX(ctx context.Context) *Posts { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *PostsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *PostsCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *PostsCreate) defaults() { + if _, ok := _c.mutation.AuthorRole(); !ok { + v := posts.DefaultAuthorRole + _c.mutation.SetAuthorRole(v) + } + if _, ok := _c.mutation.LikeCount(); !ok { + v := posts.DefaultLikeCount + _c.mutation.SetLikeCount(v) + } + if _, ok := _c.mutation.CommentCount(); !ok { + v := posts.DefaultCommentCount + _c.mutation.SetCommentCount(v) + } + if _, ok := _c.mutation.Pinned(); !ok { + v := posts.DefaultPinned + _c.mutation.SetPinned(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := posts.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := posts.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *PostsCreate) check() error { + if _, ok := _c.mutation.AuthorID(); !ok { + return &ValidationError{Name: "author_id", err: errors.New(`models: missing required field "Posts.author_id"`)} + } + if _, ok := _c.mutation.AuthorRole(); !ok { + return &ValidationError{Name: "author_role", err: errors.New(`models: missing required field "Posts.author_role"`)} + } + if v, ok := _c.mutation.AuthorRole(); ok { + if err := posts.AuthorRoleValidator(v); err != nil { + return &ValidationError{Name: "author_role", err: fmt.Errorf(`models: validator failed for field "Posts.author_role": %w`, err)} + } + } + if _, ok := _c.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`models: missing required field "Posts.title"`)} + } + if v, ok := _c.mutation.Title(); ok { + if err := posts.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`models: validator failed for field "Posts.title": %w`, err)} + } + } + if _, ok := _c.mutation.Content(); !ok { + return &ValidationError{Name: "content", err: errors.New(`models: missing required field "Posts.content"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Posts.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Posts.updated_at"`)} + } + return nil +} + +func (_c *PostsCreate) sqlSave(ctx context.Context) (*Posts, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *PostsCreate) createSpec() (*Posts, *sqlgraph.CreateSpec) { + var ( + _node = &Posts{config: _c.config} + _spec = sqlgraph.NewCreateSpec(posts.Table, sqlgraph.NewFieldSpec(posts.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.AuthorID(); ok { + _spec.SetField(posts.FieldAuthorID, field.TypeInt64, value) + _node.AuthorID = value + } + if value, ok := _c.mutation.AuthorRole(); ok { + _spec.SetField(posts.FieldAuthorRole, field.TypeString, value) + _node.AuthorRole = value + } + if value, ok := _c.mutation.Title(); ok { + _spec.SetField(posts.FieldTitle, field.TypeString, value) + _node.Title = value + } + if value, ok := _c.mutation.Content(); ok { + _spec.SetField(posts.FieldContent, field.TypeString, value) + _node.Content = value + } + if value, ok := _c.mutation.Images(); ok { + _spec.SetField(posts.FieldImages, field.TypeOther, value) + _node.Images = value + } + if value, ok := _c.mutation.Tags(); ok { + _spec.SetField(posts.FieldTags, field.TypeOther, value) + _node.Tags = value + } + if value, ok := _c.mutation.LinkedOrderID(); ok { + _spec.SetField(posts.FieldLinkedOrderID, field.TypeInt64, value) + _node.LinkedOrderID = &value + } + if value, ok := _c.mutation.QuotedPostID(); ok { + _spec.SetField(posts.FieldQuotedPostID, field.TypeInt64, value) + _node.QuotedPostID = &value + } + if value, ok := _c.mutation.LikeCount(); ok { + _spec.SetField(posts.FieldLikeCount, field.TypeInt, value) + _node.LikeCount = value + } + if value, ok := _c.mutation.CommentCount(); ok { + _spec.SetField(posts.FieldCommentCount, field.TypeInt, value) + _node.CommentCount = value + } + if value, ok := _c.mutation.Pinned(); ok { + _spec.SetField(posts.FieldPinned, field.TypeBool, value) + _node.Pinned = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(posts.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(posts.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(posts.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + return _node, _spec +} + +// PostsCreateBulk is the builder for creating many Posts entities in bulk. +type PostsCreateBulk struct { + config + err error + builders []*PostsCreate +} + +// Save creates the Posts entities in the database. +func (_c *PostsCreateBulk) Save(ctx context.Context) ([]*Posts, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Posts, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PostsMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *PostsCreateBulk) SaveX(ctx context.Context) []*Posts { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *PostsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *PostsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/posts_delete.go b/app/community/rpc/internal/models/posts_delete.go new file mode 100644 index 0000000..2cff3ce --- /dev/null +++ b/app/community/rpc/internal/models/posts_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/app/community/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostsDelete is the builder for deleting a Posts entity. +type PostsDelete struct { + config + hooks []Hook + mutation *PostsMutation +} + +// Where appends a list predicates to the PostsDelete builder. +func (_d *PostsDelete) Where(ps ...predicate.Posts) *PostsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *PostsDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *PostsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *PostsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(posts.Table, sqlgraph.NewFieldSpec(posts.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// PostsDeleteOne is the builder for deleting a single Posts entity. +type PostsDeleteOne struct { + _d *PostsDelete +} + +// Where appends a list predicates to the PostsDelete builder. +func (_d *PostsDeleteOne) Where(ps ...predicate.Posts) *PostsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *PostsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{posts.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *PostsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/community/rpc/internal/models/posts_query.go b/app/community/rpc/internal/models/posts_query.go new file mode 100644 index 0000000..e8297ac --- /dev/null +++ b/app/community/rpc/internal/models/posts_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/app/community/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostsQuery is the builder for querying Posts entities. +type PostsQuery struct { + config + ctx *QueryContext + order []posts.OrderOption + inters []Interceptor + predicates []predicate.Posts + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the PostsQuery builder. +func (_q *PostsQuery) Where(ps ...predicate.Posts) *PostsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *PostsQuery) Limit(limit int) *PostsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *PostsQuery) Offset(offset int) *PostsQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *PostsQuery) Unique(unique bool) *PostsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *PostsQuery) Order(o ...posts.OrderOption) *PostsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Posts entity from the query. +// Returns a *NotFoundError when no Posts was found. +func (_q *PostsQuery) First(ctx context.Context) (*Posts, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{posts.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *PostsQuery) FirstX(ctx context.Context) *Posts { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Posts ID from the query. +// Returns a *NotFoundError when no Posts ID was found. +func (_q *PostsQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{posts.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *PostsQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Posts entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Posts entity is found. +// Returns a *NotFoundError when no Posts entities are found. +func (_q *PostsQuery) Only(ctx context.Context) (*Posts, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{posts.Label} + default: + return nil, &NotSingularError{posts.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *PostsQuery) OnlyX(ctx context.Context) *Posts { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Posts ID in the query. +// Returns a *NotSingularError when more than one Posts ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *PostsQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{posts.Label} + default: + err = &NotSingularError{posts.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *PostsQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of PostsSlice. +func (_q *PostsQuery) All(ctx context.Context) ([]*Posts, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Posts, *PostsQuery]() + return withInterceptors[[]*Posts](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *PostsQuery) AllX(ctx context.Context) []*Posts { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Posts IDs. +func (_q *PostsQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(posts.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *PostsQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *PostsQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*PostsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *PostsQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *PostsQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *PostsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the PostsQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *PostsQuery) Clone() *PostsQuery { + if _q == nil { + return nil + } + return &PostsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]posts.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Posts{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// AuthorID int64 `json:"author_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Posts.Query(). +// GroupBy(posts.FieldAuthorID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *PostsQuery) GroupBy(field string, fields ...string) *PostsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &PostsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = posts.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// AuthorID int64 `json:"author_id,omitempty"` +// } +// +// client.Posts.Query(). +// Select(posts.FieldAuthorID). +// Scan(ctx, &v) +func (_q *PostsQuery) Select(fields ...string) *PostsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &PostsSelect{PostsQuery: _q} + sbuild.label = posts.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a PostsSelect configured with the given aggregations. +func (_q *PostsQuery) Aggregate(fns ...AggregateFunc) *PostsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *PostsQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !posts.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *PostsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Posts, error) { + var ( + nodes = []*Posts{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Posts).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Posts{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *PostsQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *PostsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(posts.Table, posts.Columns, sqlgraph.NewFieldSpec(posts.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, posts.FieldID) + for i := range fields { + if fields[i] != posts.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *PostsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(posts.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = posts.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// PostsGroupBy is the group-by builder for Posts entities. +type PostsGroupBy struct { + selector + build *PostsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *PostsGroupBy) Aggregate(fns ...AggregateFunc) *PostsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *PostsGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*PostsQuery, *PostsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *PostsGroupBy) sqlScan(ctx context.Context, root *PostsQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// PostsSelect is the builder for selecting fields of Posts entities. +type PostsSelect struct { + *PostsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *PostsSelect) Aggregate(fns ...AggregateFunc) *PostsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *PostsSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*PostsQuery, *PostsSelect](ctx, _s.PostsQuery, _s, _s.inters, v) +} + +func (_s *PostsSelect) sqlScan(ctx context.Context, root *PostsQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/community/rpc/internal/models/posts_update.go b/app/community/rpc/internal/models/posts_update.go new file mode 100644 index 0000000..22d5a69 --- /dev/null +++ b/app/community/rpc/internal/models/posts_update.go @@ -0,0 +1,901 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/app/community/rpc/internal/models/predicate" + "juwan-backend/pkg/types" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PostsUpdate is the builder for updating Posts entities. +type PostsUpdate struct { + config + hooks []Hook + mutation *PostsMutation +} + +// Where appends a list predicates to the PostsUpdate builder. +func (_u *PostsUpdate) Where(ps ...predicate.Posts) *PostsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAuthorID sets the "author_id" field. +func (_u *PostsUpdate) SetAuthorID(v int64) *PostsUpdate { + _u.mutation.ResetAuthorID() + _u.mutation.SetAuthorID(v) + return _u +} + +// SetNillableAuthorID sets the "author_id" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableAuthorID(v *int64) *PostsUpdate { + if v != nil { + _u.SetAuthorID(*v) + } + return _u +} + +// AddAuthorID adds value to the "author_id" field. +func (_u *PostsUpdate) AddAuthorID(v int64) *PostsUpdate { + _u.mutation.AddAuthorID(v) + return _u +} + +// SetAuthorRole sets the "author_role" field. +func (_u *PostsUpdate) SetAuthorRole(v string) *PostsUpdate { + _u.mutation.SetAuthorRole(v) + return _u +} + +// SetNillableAuthorRole sets the "author_role" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableAuthorRole(v *string) *PostsUpdate { + if v != nil { + _u.SetAuthorRole(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *PostsUpdate) SetTitle(v string) *PostsUpdate { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableTitle(v *string) *PostsUpdate { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetContent sets the "content" field. +func (_u *PostsUpdate) SetContent(v string) *PostsUpdate { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableContent(v *string) *PostsUpdate { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetImages sets the "images" field. +func (_u *PostsUpdate) SetImages(v types.TextArray) *PostsUpdate { + _u.mutation.SetImages(v) + return _u +} + +// SetNillableImages sets the "images" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableImages(v *types.TextArray) *PostsUpdate { + if v != nil { + _u.SetImages(*v) + } + return _u +} + +// ClearImages clears the value of the "images" field. +func (_u *PostsUpdate) ClearImages() *PostsUpdate { + _u.mutation.ClearImages() + return _u +} + +// SetTags sets the "tags" field. +func (_u *PostsUpdate) SetTags(v types.TextArray) *PostsUpdate { + _u.mutation.SetTags(v) + return _u +} + +// SetNillableTags sets the "tags" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableTags(v *types.TextArray) *PostsUpdate { + if v != nil { + _u.SetTags(*v) + } + return _u +} + +// ClearTags clears the value of the "tags" field. +func (_u *PostsUpdate) ClearTags() *PostsUpdate { + _u.mutation.ClearTags() + return _u +} + +// SetLinkedOrderID sets the "linked_order_id" field. +func (_u *PostsUpdate) SetLinkedOrderID(v int64) *PostsUpdate { + _u.mutation.ResetLinkedOrderID() + _u.mutation.SetLinkedOrderID(v) + return _u +} + +// SetNillableLinkedOrderID sets the "linked_order_id" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableLinkedOrderID(v *int64) *PostsUpdate { + if v != nil { + _u.SetLinkedOrderID(*v) + } + return _u +} + +// AddLinkedOrderID adds value to the "linked_order_id" field. +func (_u *PostsUpdate) AddLinkedOrderID(v int64) *PostsUpdate { + _u.mutation.AddLinkedOrderID(v) + return _u +} + +// ClearLinkedOrderID clears the value of the "linked_order_id" field. +func (_u *PostsUpdate) ClearLinkedOrderID() *PostsUpdate { + _u.mutation.ClearLinkedOrderID() + return _u +} + +// SetQuotedPostID sets the "quoted_post_id" field. +func (_u *PostsUpdate) SetQuotedPostID(v int64) *PostsUpdate { + _u.mutation.ResetQuotedPostID() + _u.mutation.SetQuotedPostID(v) + return _u +} + +// SetNillableQuotedPostID sets the "quoted_post_id" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableQuotedPostID(v *int64) *PostsUpdate { + if v != nil { + _u.SetQuotedPostID(*v) + } + return _u +} + +// AddQuotedPostID adds value to the "quoted_post_id" field. +func (_u *PostsUpdate) AddQuotedPostID(v int64) *PostsUpdate { + _u.mutation.AddQuotedPostID(v) + return _u +} + +// ClearQuotedPostID clears the value of the "quoted_post_id" field. +func (_u *PostsUpdate) ClearQuotedPostID() *PostsUpdate { + _u.mutation.ClearQuotedPostID() + return _u +} + +// SetLikeCount sets the "like_count" field. +func (_u *PostsUpdate) SetLikeCount(v int) *PostsUpdate { + _u.mutation.ResetLikeCount() + _u.mutation.SetLikeCount(v) + return _u +} + +// SetNillableLikeCount sets the "like_count" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableLikeCount(v *int) *PostsUpdate { + if v != nil { + _u.SetLikeCount(*v) + } + return _u +} + +// AddLikeCount adds value to the "like_count" field. +func (_u *PostsUpdate) AddLikeCount(v int) *PostsUpdate { + _u.mutation.AddLikeCount(v) + return _u +} + +// ClearLikeCount clears the value of the "like_count" field. +func (_u *PostsUpdate) ClearLikeCount() *PostsUpdate { + _u.mutation.ClearLikeCount() + return _u +} + +// SetCommentCount sets the "comment_count" field. +func (_u *PostsUpdate) SetCommentCount(v int) *PostsUpdate { + _u.mutation.ResetCommentCount() + _u.mutation.SetCommentCount(v) + return _u +} + +// SetNillableCommentCount sets the "comment_count" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableCommentCount(v *int) *PostsUpdate { + if v != nil { + _u.SetCommentCount(*v) + } + return _u +} + +// AddCommentCount adds value to the "comment_count" field. +func (_u *PostsUpdate) AddCommentCount(v int) *PostsUpdate { + _u.mutation.AddCommentCount(v) + return _u +} + +// ClearCommentCount clears the value of the "comment_count" field. +func (_u *PostsUpdate) ClearCommentCount() *PostsUpdate { + _u.mutation.ClearCommentCount() + return _u +} + +// SetPinned sets the "pinned" field. +func (_u *PostsUpdate) SetPinned(v bool) *PostsUpdate { + _u.mutation.SetPinned(v) + return _u +} + +// SetNillablePinned sets the "pinned" field if the given value is not nil. +func (_u *PostsUpdate) SetNillablePinned(v *bool) *PostsUpdate { + if v != nil { + _u.SetPinned(*v) + } + return _u +} + +// ClearPinned clears the value of the "pinned" field. +func (_u *PostsUpdate) ClearPinned() *PostsUpdate { + _u.mutation.ClearPinned() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *PostsUpdate) SetUpdatedAt(v time.Time) *PostsUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *PostsUpdate) SetDeletedAt(v time.Time) *PostsUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *PostsUpdate) SetNillableDeletedAt(v *time.Time) *PostsUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *PostsUpdate) ClearDeletedAt() *PostsUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the PostsMutation object of the builder. +func (_u *PostsUpdate) Mutation() *PostsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *PostsUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *PostsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *PostsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *PostsUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *PostsUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := posts.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *PostsUpdate) check() error { + if v, ok := _u.mutation.AuthorRole(); ok { + if err := posts.AuthorRoleValidator(v); err != nil { + return &ValidationError{Name: "author_role", err: fmt.Errorf(`models: validator failed for field "Posts.author_role": %w`, err)} + } + } + if v, ok := _u.mutation.Title(); ok { + if err := posts.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`models: validator failed for field "Posts.title": %w`, err)} + } + } + return nil +} + +func (_u *PostsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(posts.Table, posts.Columns, sqlgraph.NewFieldSpec(posts.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.AuthorID(); ok { + _spec.SetField(posts.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedAuthorID(); ok { + _spec.AddField(posts.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AuthorRole(); ok { + _spec.SetField(posts.FieldAuthorRole, field.TypeString, value) + } + if value, ok := _u.mutation.Title(); ok { + _spec.SetField(posts.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(posts.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.Images(); ok { + _spec.SetField(posts.FieldImages, field.TypeOther, value) + } + if _u.mutation.ImagesCleared() { + _spec.ClearField(posts.FieldImages, field.TypeOther) + } + if value, ok := _u.mutation.Tags(); ok { + _spec.SetField(posts.FieldTags, field.TypeOther, value) + } + if _u.mutation.TagsCleared() { + _spec.ClearField(posts.FieldTags, field.TypeOther) + } + if value, ok := _u.mutation.LinkedOrderID(); ok { + _spec.SetField(posts.FieldLinkedOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedLinkedOrderID(); ok { + _spec.AddField(posts.FieldLinkedOrderID, field.TypeInt64, value) + } + if _u.mutation.LinkedOrderIDCleared() { + _spec.ClearField(posts.FieldLinkedOrderID, field.TypeInt64) + } + if value, ok := _u.mutation.QuotedPostID(); ok { + _spec.SetField(posts.FieldQuotedPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedQuotedPostID(); ok { + _spec.AddField(posts.FieldQuotedPostID, field.TypeInt64, value) + } + if _u.mutation.QuotedPostIDCleared() { + _spec.ClearField(posts.FieldQuotedPostID, field.TypeInt64) + } + if value, ok := _u.mutation.LikeCount(); ok { + _spec.SetField(posts.FieldLikeCount, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedLikeCount(); ok { + _spec.AddField(posts.FieldLikeCount, field.TypeInt, value) + } + if _u.mutation.LikeCountCleared() { + _spec.ClearField(posts.FieldLikeCount, field.TypeInt) + } + if value, ok := _u.mutation.CommentCount(); ok { + _spec.SetField(posts.FieldCommentCount, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCommentCount(); ok { + _spec.AddField(posts.FieldCommentCount, field.TypeInt, value) + } + if _u.mutation.CommentCountCleared() { + _spec.ClearField(posts.FieldCommentCount, field.TypeInt) + } + if value, ok := _u.mutation.Pinned(); ok { + _spec.SetField(posts.FieldPinned, field.TypeBool, value) + } + if _u.mutation.PinnedCleared() { + _spec.ClearField(posts.FieldPinned, field.TypeBool) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(posts.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(posts.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(posts.FieldDeletedAt, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{posts.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// PostsUpdateOne is the builder for updating a single Posts entity. +type PostsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *PostsMutation +} + +// SetAuthorID sets the "author_id" field. +func (_u *PostsUpdateOne) SetAuthorID(v int64) *PostsUpdateOne { + _u.mutation.ResetAuthorID() + _u.mutation.SetAuthorID(v) + return _u +} + +// SetNillableAuthorID sets the "author_id" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableAuthorID(v *int64) *PostsUpdateOne { + if v != nil { + _u.SetAuthorID(*v) + } + return _u +} + +// AddAuthorID adds value to the "author_id" field. +func (_u *PostsUpdateOne) AddAuthorID(v int64) *PostsUpdateOne { + _u.mutation.AddAuthorID(v) + return _u +} + +// SetAuthorRole sets the "author_role" field. +func (_u *PostsUpdateOne) SetAuthorRole(v string) *PostsUpdateOne { + _u.mutation.SetAuthorRole(v) + return _u +} + +// SetNillableAuthorRole sets the "author_role" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableAuthorRole(v *string) *PostsUpdateOne { + if v != nil { + _u.SetAuthorRole(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *PostsUpdateOne) SetTitle(v string) *PostsUpdateOne { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableTitle(v *string) *PostsUpdateOne { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetContent sets the "content" field. +func (_u *PostsUpdateOne) SetContent(v string) *PostsUpdateOne { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableContent(v *string) *PostsUpdateOne { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetImages sets the "images" field. +func (_u *PostsUpdateOne) SetImages(v types.TextArray) *PostsUpdateOne { + _u.mutation.SetImages(v) + return _u +} + +// SetNillableImages sets the "images" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableImages(v *types.TextArray) *PostsUpdateOne { + if v != nil { + _u.SetImages(*v) + } + return _u +} + +// ClearImages clears the value of the "images" field. +func (_u *PostsUpdateOne) ClearImages() *PostsUpdateOne { + _u.mutation.ClearImages() + return _u +} + +// SetTags sets the "tags" field. +func (_u *PostsUpdateOne) SetTags(v types.TextArray) *PostsUpdateOne { + _u.mutation.SetTags(v) + return _u +} + +// SetNillableTags sets the "tags" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableTags(v *types.TextArray) *PostsUpdateOne { + if v != nil { + _u.SetTags(*v) + } + return _u +} + +// ClearTags clears the value of the "tags" field. +func (_u *PostsUpdateOne) ClearTags() *PostsUpdateOne { + _u.mutation.ClearTags() + return _u +} + +// SetLinkedOrderID sets the "linked_order_id" field. +func (_u *PostsUpdateOne) SetLinkedOrderID(v int64) *PostsUpdateOne { + _u.mutation.ResetLinkedOrderID() + _u.mutation.SetLinkedOrderID(v) + return _u +} + +// SetNillableLinkedOrderID sets the "linked_order_id" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableLinkedOrderID(v *int64) *PostsUpdateOne { + if v != nil { + _u.SetLinkedOrderID(*v) + } + return _u +} + +// AddLinkedOrderID adds value to the "linked_order_id" field. +func (_u *PostsUpdateOne) AddLinkedOrderID(v int64) *PostsUpdateOne { + _u.mutation.AddLinkedOrderID(v) + return _u +} + +// ClearLinkedOrderID clears the value of the "linked_order_id" field. +func (_u *PostsUpdateOne) ClearLinkedOrderID() *PostsUpdateOne { + _u.mutation.ClearLinkedOrderID() + return _u +} + +// SetQuotedPostID sets the "quoted_post_id" field. +func (_u *PostsUpdateOne) SetQuotedPostID(v int64) *PostsUpdateOne { + _u.mutation.ResetQuotedPostID() + _u.mutation.SetQuotedPostID(v) + return _u +} + +// SetNillableQuotedPostID sets the "quoted_post_id" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableQuotedPostID(v *int64) *PostsUpdateOne { + if v != nil { + _u.SetQuotedPostID(*v) + } + return _u +} + +// AddQuotedPostID adds value to the "quoted_post_id" field. +func (_u *PostsUpdateOne) AddQuotedPostID(v int64) *PostsUpdateOne { + _u.mutation.AddQuotedPostID(v) + return _u +} + +// ClearQuotedPostID clears the value of the "quoted_post_id" field. +func (_u *PostsUpdateOne) ClearQuotedPostID() *PostsUpdateOne { + _u.mutation.ClearQuotedPostID() + return _u +} + +// SetLikeCount sets the "like_count" field. +func (_u *PostsUpdateOne) SetLikeCount(v int) *PostsUpdateOne { + _u.mutation.ResetLikeCount() + _u.mutation.SetLikeCount(v) + return _u +} + +// SetNillableLikeCount sets the "like_count" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableLikeCount(v *int) *PostsUpdateOne { + if v != nil { + _u.SetLikeCount(*v) + } + return _u +} + +// AddLikeCount adds value to the "like_count" field. +func (_u *PostsUpdateOne) AddLikeCount(v int) *PostsUpdateOne { + _u.mutation.AddLikeCount(v) + return _u +} + +// ClearLikeCount clears the value of the "like_count" field. +func (_u *PostsUpdateOne) ClearLikeCount() *PostsUpdateOne { + _u.mutation.ClearLikeCount() + return _u +} + +// SetCommentCount sets the "comment_count" field. +func (_u *PostsUpdateOne) SetCommentCount(v int) *PostsUpdateOne { + _u.mutation.ResetCommentCount() + _u.mutation.SetCommentCount(v) + return _u +} + +// SetNillableCommentCount sets the "comment_count" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableCommentCount(v *int) *PostsUpdateOne { + if v != nil { + _u.SetCommentCount(*v) + } + return _u +} + +// AddCommentCount adds value to the "comment_count" field. +func (_u *PostsUpdateOne) AddCommentCount(v int) *PostsUpdateOne { + _u.mutation.AddCommentCount(v) + return _u +} + +// ClearCommentCount clears the value of the "comment_count" field. +func (_u *PostsUpdateOne) ClearCommentCount() *PostsUpdateOne { + _u.mutation.ClearCommentCount() + return _u +} + +// SetPinned sets the "pinned" field. +func (_u *PostsUpdateOne) SetPinned(v bool) *PostsUpdateOne { + _u.mutation.SetPinned(v) + return _u +} + +// SetNillablePinned sets the "pinned" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillablePinned(v *bool) *PostsUpdateOne { + if v != nil { + _u.SetPinned(*v) + } + return _u +} + +// ClearPinned clears the value of the "pinned" field. +func (_u *PostsUpdateOne) ClearPinned() *PostsUpdateOne { + _u.mutation.ClearPinned() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *PostsUpdateOne) SetUpdatedAt(v time.Time) *PostsUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *PostsUpdateOne) SetDeletedAt(v time.Time) *PostsUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *PostsUpdateOne) SetNillableDeletedAt(v *time.Time) *PostsUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *PostsUpdateOne) ClearDeletedAt() *PostsUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the PostsMutation object of the builder. +func (_u *PostsUpdateOne) Mutation() *PostsMutation { + return _u.mutation +} + +// Where appends a list predicates to the PostsUpdate builder. +func (_u *PostsUpdateOne) Where(ps ...predicate.Posts) *PostsUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *PostsUpdateOne) Select(field string, fields ...string) *PostsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Posts entity. +func (_u *PostsUpdateOne) Save(ctx context.Context) (*Posts, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *PostsUpdateOne) SaveX(ctx context.Context) *Posts { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *PostsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *PostsUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *PostsUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := posts.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *PostsUpdateOne) check() error { + if v, ok := _u.mutation.AuthorRole(); ok { + if err := posts.AuthorRoleValidator(v); err != nil { + return &ValidationError{Name: "author_role", err: fmt.Errorf(`models: validator failed for field "Posts.author_role": %w`, err)} + } + } + if v, ok := _u.mutation.Title(); ok { + if err := posts.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`models: validator failed for field "Posts.title": %w`, err)} + } + } + return nil +} + +func (_u *PostsUpdateOne) sqlSave(ctx context.Context) (_node *Posts, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(posts.Table, posts.Columns, sqlgraph.NewFieldSpec(posts.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Posts.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, posts.FieldID) + for _, f := range fields { + if !posts.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != posts.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.AuthorID(); ok { + _spec.SetField(posts.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedAuthorID(); ok { + _spec.AddField(posts.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AuthorRole(); ok { + _spec.SetField(posts.FieldAuthorRole, field.TypeString, value) + } + if value, ok := _u.mutation.Title(); ok { + _spec.SetField(posts.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(posts.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.Images(); ok { + _spec.SetField(posts.FieldImages, field.TypeOther, value) + } + if _u.mutation.ImagesCleared() { + _spec.ClearField(posts.FieldImages, field.TypeOther) + } + if value, ok := _u.mutation.Tags(); ok { + _spec.SetField(posts.FieldTags, field.TypeOther, value) + } + if _u.mutation.TagsCleared() { + _spec.ClearField(posts.FieldTags, field.TypeOther) + } + if value, ok := _u.mutation.LinkedOrderID(); ok { + _spec.SetField(posts.FieldLinkedOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedLinkedOrderID(); ok { + _spec.AddField(posts.FieldLinkedOrderID, field.TypeInt64, value) + } + if _u.mutation.LinkedOrderIDCleared() { + _spec.ClearField(posts.FieldLinkedOrderID, field.TypeInt64) + } + if value, ok := _u.mutation.QuotedPostID(); ok { + _spec.SetField(posts.FieldQuotedPostID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedQuotedPostID(); ok { + _spec.AddField(posts.FieldQuotedPostID, field.TypeInt64, value) + } + if _u.mutation.QuotedPostIDCleared() { + _spec.ClearField(posts.FieldQuotedPostID, field.TypeInt64) + } + if value, ok := _u.mutation.LikeCount(); ok { + _spec.SetField(posts.FieldLikeCount, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedLikeCount(); ok { + _spec.AddField(posts.FieldLikeCount, field.TypeInt, value) + } + if _u.mutation.LikeCountCleared() { + _spec.ClearField(posts.FieldLikeCount, field.TypeInt) + } + if value, ok := _u.mutation.CommentCount(); ok { + _spec.SetField(posts.FieldCommentCount, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCommentCount(); ok { + _spec.AddField(posts.FieldCommentCount, field.TypeInt, value) + } + if _u.mutation.CommentCountCleared() { + _spec.ClearField(posts.FieldCommentCount, field.TypeInt) + } + if value, ok := _u.mutation.Pinned(); ok { + _spec.SetField(posts.FieldPinned, field.TypeBool, value) + } + if _u.mutation.PinnedCleared() { + _spec.ClearField(posts.FieldPinned, field.TypeBool) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(posts.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(posts.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(posts.FieldDeletedAt, field.TypeTime) + } + _node = &Posts{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{posts.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/community/rpc/internal/models/predicate/predicate.go b/app/community/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..269e937 --- /dev/null +++ b/app/community/rpc/internal/models/predicate/predicate.go @@ -0,0 +1,19 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// CommentLikes is the predicate function for commentlikes builders. +type CommentLikes func(*sql.Selector) + +// Comments is the predicate function for comments builders. +type Comments func(*sql.Selector) + +// PostLikes is the predicate function for postlikes builders. +type PostLikes func(*sql.Selector) + +// Posts is the predicate function for posts builders. +type Posts func(*sql.Selector) diff --git a/app/community/rpc/internal/models/runtime.go b/app/community/rpc/internal/models/runtime.go new file mode 100644 index 0000000..73586e4 --- /dev/null +++ b/app/community/rpc/internal/models/runtime.go @@ -0,0 +1,74 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/community/rpc/internal/models/commentlikes" + "juwan-backend/app/community/rpc/internal/models/comments" + "juwan-backend/app/community/rpc/internal/models/postlikes" + "juwan-backend/app/community/rpc/internal/models/posts" + "juwan-backend/app/community/rpc/internal/models/schema" + "time" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + commentlikesFields := schema.CommentLikes{}.Fields() + _ = commentlikesFields + // commentlikesDescCreatedAt is the schema descriptor for created_at field. + commentlikesDescCreatedAt := commentlikesFields[3].Descriptor() + // commentlikes.DefaultCreatedAt holds the default value on creation for the created_at field. + commentlikes.DefaultCreatedAt = commentlikesDescCreatedAt.Default.(func() time.Time) + commentsFields := schema.Comments{}.Fields() + _ = commentsFields + // commentsDescLikeCount is the schema descriptor for like_count field. + commentsDescLikeCount := commentsFields[4].Descriptor() + // comments.DefaultLikeCount holds the default value on creation for the like_count field. + comments.DefaultLikeCount = commentsDescLikeCount.Default.(int) + // commentsDescCreatedAt is the schema descriptor for created_at field. + commentsDescCreatedAt := commentsFields[5].Descriptor() + // comments.DefaultCreatedAt holds the default value on creation for the created_at field. + comments.DefaultCreatedAt = commentsDescCreatedAt.Default.(func() time.Time) + postlikesFields := schema.PostLikes{}.Fields() + _ = postlikesFields + // postlikesDescCreatedAt is the schema descriptor for created_at field. + postlikesDescCreatedAt := postlikesFields[3].Descriptor() + // postlikes.DefaultCreatedAt holds the default value on creation for the created_at field. + postlikes.DefaultCreatedAt = postlikesDescCreatedAt.Default.(func() time.Time) + postsFields := schema.Posts{}.Fields() + _ = postsFields + // postsDescAuthorRole is the schema descriptor for author_role field. + postsDescAuthorRole := postsFields[2].Descriptor() + // posts.DefaultAuthorRole holds the default value on creation for the author_role field. + posts.DefaultAuthorRole = postsDescAuthorRole.Default.(string) + // posts.AuthorRoleValidator is a validator for the "author_role" field. It is called by the builders before save. + posts.AuthorRoleValidator = postsDescAuthorRole.Validators[0].(func(string) error) + // postsDescTitle is the schema descriptor for title field. + postsDescTitle := postsFields[3].Descriptor() + // posts.TitleValidator is a validator for the "title" field. It is called by the builders before save. + posts.TitleValidator = postsDescTitle.Validators[0].(func(string) error) + // postsDescLikeCount is the schema descriptor for like_count field. + postsDescLikeCount := postsFields[9].Descriptor() + // posts.DefaultLikeCount holds the default value on creation for the like_count field. + posts.DefaultLikeCount = postsDescLikeCount.Default.(int) + // postsDescCommentCount is the schema descriptor for comment_count field. + postsDescCommentCount := postsFields[10].Descriptor() + // posts.DefaultCommentCount holds the default value on creation for the comment_count field. + posts.DefaultCommentCount = postsDescCommentCount.Default.(int) + // postsDescPinned is the schema descriptor for pinned field. + postsDescPinned := postsFields[11].Descriptor() + // posts.DefaultPinned holds the default value on creation for the pinned field. + posts.DefaultPinned = postsDescPinned.Default.(bool) + // postsDescCreatedAt is the schema descriptor for created_at field. + postsDescCreatedAt := postsFields[12].Descriptor() + // posts.DefaultCreatedAt holds the default value on creation for the created_at field. + posts.DefaultCreatedAt = postsDescCreatedAt.Default.(func() time.Time) + // postsDescUpdatedAt is the schema descriptor for updated_at field. + postsDescUpdatedAt := postsFields[13].Descriptor() + // posts.DefaultUpdatedAt holds the default value on creation for the updated_at field. + posts.DefaultUpdatedAt = postsDescUpdatedAt.Default.(func() time.Time) + // posts.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + posts.UpdateDefaultUpdatedAt = postsDescUpdatedAt.UpdateDefault.(func() time.Time) +} diff --git a/app/community/rpc/internal/models/runtime/runtime.go b/app/community/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..e4061c7 --- /dev/null +++ b/app/community/rpc/internal/models/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in juwan-backend/app/community/rpc/internal/models/runtime.go + +const ( + Version = "v0.14.5" // Version of ent codegen. + Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. +) diff --git a/app/community/rpc/internal/models/schema/commentlikes.go b/app/community/rpc/internal/models/schema/commentlikes.go new file mode 100644 index 0000000..346212f --- /dev/null +++ b/app/community/rpc/internal/models/schema/commentlikes.go @@ -0,0 +1,30 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type CommentLikes struct { + ent.Schema +} + +func (CommentLikes) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Immutable().Unique(), + field.Int64("comment_id"), + field.Int64("user_id"), + field.Time("created_at").Default(time.Now).Immutable(), + } +} + +func (CommentLikes) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("comment_id", "user_id").Unique(), + index.Fields("user_id", "comment_id"), + index.Fields("user_id", "created_at"), + } +} diff --git a/app/community/rpc/internal/models/schema/comments.go b/app/community/rpc/internal/models/schema/comments.go new file mode 100644 index 0000000..35fe448 --- /dev/null +++ b/app/community/rpc/internal/models/schema/comments.go @@ -0,0 +1,36 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type Comments struct { + ent.Schema +} + +func (Comments) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("post_id"), + field.Int64("author_id"), + field.String("content"), + field.Int("like_count").Optional().Default(0), + field.Time("created_at").Default(time.Now).Immutable(), + field.Time("deleted_at").Optional().Nillable(), + } +} + +func (Comments) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("post_id", "created_at"), + index.Fields("author_id", "created_at"), + } +} + +func (Comments) Edges() []ent.Edge { + return nil +} diff --git a/app/community/rpc/internal/models/schema/postlikes.go b/app/community/rpc/internal/models/schema/postlikes.go new file mode 100644 index 0000000..e9a3823 --- /dev/null +++ b/app/community/rpc/internal/models/schema/postlikes.go @@ -0,0 +1,30 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type PostLikes struct { + ent.Schema +} + +func (PostLikes) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Immutable().Unique(), + field.Int64("post_id"), + field.Int64("user_id"), + field.Time("created_at").Default(time.Now).Immutable(), + } +} + +func (PostLikes) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("post_id", "user_id").Unique(), + index.Fields("user_id", "post_id"), + index.Fields("user_id", "created_at"), + } +} diff --git a/app/community/rpc/internal/models/schema/posts.go b/app/community/rpc/internal/models/schema/posts.go new file mode 100644 index 0000000..ca6af10 --- /dev/null +++ b/app/community/rpc/internal/models/schema/posts.go @@ -0,0 +1,53 @@ +package schema + +import ( + "time" + + "juwan-backend/pkg/types" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type Posts struct { + ent.Schema +} + +func (Posts) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("author_id"), + field.String("author_role").MaxLen(20).Default("consumer"), + field.String("title").MaxLen(500), + field.String("content"), + field.Other("images", types.TextArray{}). + SchemaType(map[string]string{dialect.Postgres: "text[]"}). + Optional(), + field.Other("tags", types.TextArray{}). + SchemaType(map[string]string{dialect.Postgres: "text[]"}). + Optional(), + field.Int64("linked_order_id").Optional().Nillable(), + field.Int64("quoted_post_id").Optional().Nillable(), + field.Int("like_count").Optional().Default(0), + field.Int("comment_count").Optional().Default(0), + field.Bool("pinned").Optional().Default(false), + field.Time("created_at").Default(time.Now).Immutable(), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + field.Time("deleted_at").Optional().Nillable(), + } +} + +func (Posts) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("author_id", "created_at"), + index.Fields("created_at"), + index.Fields("linked_order_id"), + index.Fields("quoted_post_id"), + } +} + +func (Posts) Edges() []ent.Edge { + return nil +} diff --git a/app/community/rpc/internal/models/tx.go b/app/community/rpc/internal/models/tx.go new file mode 100644 index 0000000..6fc97c8 --- /dev/null +++ b/app/community/rpc/internal/models/tx.go @@ -0,0 +1,219 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // CommentLikes is the client for interacting with the CommentLikes builders. + CommentLikes *CommentLikesClient + // Comments is the client for interacting with the Comments builders. + Comments *CommentsClient + // PostLikes is the client for interacting with the PostLikes builders. + PostLikes *PostLikesClient + // Posts is the client for interacting with the Posts builders. + Posts *PostsClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.CommentLikes = NewCommentLikesClient(tx.config) + tx.Comments = NewCommentsClient(tx.config) + tx.PostLikes = NewPostLikesClient(tx.config) + tx.Posts = NewPostsClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: CommentLikes.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/app/community/rpc/internal/svc/serviceContext.go b/app/community/rpc/internal/svc/serviceContext.go index 33089dc..368d3e1 100644 --- a/app/community/rpc/internal/svc/serviceContext.go +++ b/app/community/rpc/internal/svc/serviceContext.go @@ -1,15 +1,54 @@ package svc -import "juwan-backend/app/community/rpc/internal/config" +import ( + stdsql "database/sql" + "juwan-backend/app/community/rpc/internal/config" + "juwan-backend/app/community/rpc/internal/models" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" + "time" + + "ariga.io/entcache" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" + + _ "github.com/jackc/pgx/v5/stdlib" +) type ServiceContext struct { - Config config.Config - Store *CommunityStore + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + CommunityModelRW *models.Client + CommunityModelRO *models.Client } func NewServiceContext(c config.Config) *ServiceContext { + rawRW, err := stdsql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + rawRO, err := stdsql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + RWConn := sql.OpenDB(dialect.Postgres, rawRW) + ROConn := sql.OpenDB(dialect.Postgres, rawRO) + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + logx.Errorf("failed to connect to Redis cluster: %v", err) + panic(err) + } + + RWDrv := entcache.NewDriver(RWConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) + RODrv := entcache.NewDriver(ROConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) return &ServiceContext{ - Config: c, - Store: NewCommunityStore(), + Config: c, + CommunityModelRW: models.NewClient(models.Driver(RWDrv)), + CommunityModelRO: models.NewClient(models.Driver(RODrv)), + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), } } diff --git a/app/community/rpc/internal/svc/store.go b/app/community/rpc/internal/svc/store.go deleted file mode 100644 index 56e545b..0000000 --- a/app/community/rpc/internal/svc/store.go +++ /dev/null @@ -1,40 +0,0 @@ -package svc - -import ( - "sync" - - "juwan-backend/app/community/rpc/pb" -) - -type CommunityStore struct { - Mu sync.RWMutex - - nextPostID int64 - nextCommentID int64 - - Posts map[int64]*pb.Posts - Comments map[int64]*pb.Comments - PostLikes map[string]*pb.PostLikes - CommentLikes map[string]*pb.CommentLikes -} - -func NewCommunityStore() *CommunityStore { - return &CommunityStore{ - nextPostID: 1000, - nextCommentID: 1000, - Posts: make(map[int64]*pb.Posts), - Comments: make(map[int64]*pb.Comments), - PostLikes: make(map[string]*pb.PostLikes), - CommentLikes: make(map[string]*pb.CommentLikes), - } -} - -func (s *CommunityStore) NextPost() int64 { - s.nextPostID++ - return s.nextPostID -} - -func (s *CommunityStore) NextComment() int64 { - s.nextCommentID++ - return s.nextCommentID -} diff --git a/go.mod b/go.mod index 6ba6e61..b7fd0d2 100644 --- a/go.mod +++ b/go.mod @@ -3,30 +3,34 @@ module juwan-backend go 1.25.1 require ( + ariga.io/entcache v0.1.0 entgo.io/ent v0.14.5 + github.com/aws/aws-sdk-go-v2 v1.41.2 + github.com/aws/aws-sdk-go-v2/config v1.32.10 + github.com/aws/aws-sdk-go-v2/credentials v1.19.10 + github.com/aws/aws-sdk-go-v2/service/s3 v1.96.2 github.com/envoyproxy/go-control-plane/envoy v1.36.0 github.com/golang-jwt/jwt/v4 v4.5.2 github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.8.0 + github.com/jinzhu/copier v0.4.0 github.com/lib/pq v1.11.2 github.com/redis/go-redis/v9 v9.17.3 + github.com/shopspring/decimal v1.4.0 github.com/zeromicro/go-queue v1.2.2 github.com/zeromicro/go-zero v1.10.0 golang.org/x/crypto v0.46.0 google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 google.golang.org/grpc v1.79.1 google.golang.org/protobuf v1.36.11 + k8s.io/apimachinery v0.29.4 ) require ( ariga.io/atlas v0.32.1-0.20250325101103-175b25e1c1b9 // indirect - ariga.io/entcache v0.1.0 // indirect - filippo.io/edwards25519 v1.1.1 // indirect github.com/agext/levenshtein v1.2.3 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect - github.com/aws/aws-sdk-go-v2 v1.41.2 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.5 // indirect - github.com/aws/aws-sdk-go-v2/config v1.32.10 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.19.10 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18 // indirect @@ -36,7 +40,6 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.10 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.18 // indirect - github.com/aws/aws-sdk-go-v2/service/s3 v1.96.2 // indirect github.com/aws/aws-sdk-go-v2/service/signin v1.0.6 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.30.11 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.15 // indirect @@ -61,7 +64,6 @@ require ( github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.22.4 // indirect github.com/go-redis/redis/v8 v8.11.3 // indirect - github.com/go-sql-driver/mysql v1.9.3 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.4 // indirect @@ -74,9 +76,7 @@ require ( github.com/hashicorp/hcl/v2 v2.18.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.8.0 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - github.com/jinzhu/copier v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.18.0 // indirect @@ -97,7 +97,6 @@ require ( github.com/prometheus/common v0.66.1 // indirect github.com/prometheus/procfs v0.16.1 // indirect github.com/segmentio/kafka-go v0.4.47 // indirect - github.com/shopspring/decimal v1.4.0 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/zclconf/go-cty v1.14.4 // indirect github.com/zclconf/go-cty-yaml v1.1.0 // indirect @@ -134,7 +133,6 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/api v0.29.3 // indirect - k8s.io/apimachinery v0.29.4 // indirect k8s.io/client-go v0.29.3 // indirect k8s.io/klog/v2 v2.110.1 // indirect k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect diff --git a/go.sum b/go.sum index 5c27214..3ac27aa 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,6 @@ ariga.io/entcache v0.1.0 h1:nfJXzjB5CEvAK6SmjupHREMJrKLakeqU5tG3s4TO6JA= ariga.io/entcache v0.1.0/go.mod h1:3Z1Sql5bcqPA1YV/jvMlZyh9T+ntSFOclaASAm1TiKQ= entgo.io/ent v0.14.5 h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4= entgo.io/ent v0.14.5/go.mod h1:zTzLmWtPvGpmSwtkaayM2cm5m819NdM7z7tYPq3vN0U= -filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw= -filippo.io/edwards25519 v1.1.1/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= @@ -88,6 +86,7 @@ github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9 github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -106,8 +105,8 @@ github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogB github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-redis/redis/v8 v8.11.3 h1:GCjoYp8c+yQTJfc0n69iwSiHjvuAdruxl7elnZCxgt8= github.com/go-redis/redis/v8 v8.11.3/go.mod h1:xNJ9xDG09FsIPwh3bWdk+0oDWHbtF9rPN0F/oD9XeKc= -github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= -github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= +github.com/go-redis/redismock/v8 v8.0.6 h1:rtuijPgGynsRB2Y7KDACm09WvjHWS4RaG44Nm7rcj4Y= +github.com/go-redis/redismock/v8 v8.0.6/go.mod h1:sDIF73OVsmaKzYe/1FJXGiCQ4+oHYbzjpaL9Vor0sS4= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= @@ -159,8 +158,6 @@ github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplb github.com/hashicorp/hcl/v2 v2.18.1 h1:6nxnOJFku1EuSawSD81fuviYUV8DxFr3fp2dUi3ZYSo= github.com/hashicorp/hcl/v2 v2.18.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -198,8 +195,6 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= -github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM= github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= @@ -214,11 +209,11 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= -github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4= github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= @@ -252,8 +247,6 @@ github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzM github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4= github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/segmentio/kafka-go v0.4.47 h1:IqziR4pA3vrZq7YdRxaT3w1/5fvIH5qpCwstUanQQB0= @@ -264,8 +257,6 @@ github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -461,6 +452,7 @@ gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY= gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaDva0= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=