From ad5237102835eb07f3afbd919ff0c12cfdbaa56e Mon Sep 17 00:00:00 2001 From: Rogee Date: Mon, 29 Dec 2025 09:30:49 +0800 Subject: [PATCH] feat: implement new structure --- backend/app/commands/http/http.go | 6 +- backend/app/http/provider.go | 13 + backend/app/http/v1/auth.go | 41 + backend/app/http/v1/common.go | 34 + backend/app/http/v1/content.go | 115 +++ backend/app/http/v1/creator.go | 225 +++++ backend/app/http/v1/dto/auth.go | 36 + backend/app/http/v1/dto/common.go | 9 + backend/app/http/v1/dto/content.go | 84 ++ backend/app/http/v1/dto/creator.go | 77 ++ backend/app/http/v1/dto/order.go | 23 + backend/app/http/v1/dto/super.go | 202 +++++ backend/app/http/v1/dto/tenant.go | 19 + backend/app/http/v1/dto/user.go | 62 ++ backend/app/http/v1/provider.gen.go | 100 +++ backend/app/http/v1/routes.gen.go | 394 +++++++++ backend/app/http/v1/routes.manual.go | 9 + backend/app/http/v1/super.go | 308 +++++++ backend/app/http/v1/tenant.go | 56 ++ backend/app/http/v1/transaction.go | 58 ++ backend/app/http/v1/user.go | 227 +++++ backend/app/http/web/dto/auth.go | 28 - backend/app/http/web/dto/me.go | 51 -- backend/app/http/web/dto/password_reset.go | 45 - backend/app/http/web/dto/tenant_apply.go | 33 - backend/app/http/web/provider.gen.go | 9 - backend/app/services/common.go | 15 + backend/app/services/content.go | 63 ++ backend/app/services/creator.go | 66 ++ backend/app/services/order.go | 31 + backend/app/services/provider.gen.go | 90 ++ backend/app/services/services.gen.go | 49 ++ backend/app/services/super.go | 91 ++ backend/app/services/tenant.go | 22 + backend/app/services/user.go | 35 + backend/app/services/wallet.go | 18 + .../20251227120000_add_api_support.sql | 298 +++++++ backend/database/models/comments.gen.go | 66 ++ backend/database/models/comments.query.gen.go | 510 +++++++++++ backend/database/models/content_access.gen.go | 20 +- .../models/content_access.query.gen.go | 22 +- backend/database/models/content_assets.gen.go | 20 +- .../models/content_assets.query.gen.go | 22 +- backend/database/models/content_prices.gen.go | 26 +- .../models/content_prices.query.gen.go | 32 +- backend/database/models/contents.gen.go | 36 +- backend/database/models/contents.query.gen.go | 74 +- backend/database/models/media_assets.gen.go | 30 +- .../database/models/media_assets.query.gen.go | 54 +- backend/database/models/notifications.gen.go | 62 ++ .../models/notifications.query.gen.go | 489 +++++++++++ backend/database/models/order_items.gen.go | 24 +- .../database/models/order_items.query.gen.go | 205 +---- backend/database/models/orders.gen.go | 40 +- backend/database/models/orders.query.gen.go | 141 +-- .../database/models/payout_accounts.gen.go | 63 ++ .../models/payout_accounts.query.gen.go | 493 +++++++++++ backend/database/models/query.gen.go | 40 + backend/database/models/tenant_invites.gen.go | 28 +- .../models/tenant_invites.query.gen.go | 30 +- .../models/tenant_join_requests.gen.go | 22 +- .../models/tenant_join_requests.query.gen.go | 24 +- backend/database/models/tenant_ledgers.gen.go | 37 +- .../models/tenant_ledgers.query.gen.go | 143 +-- backend/database/models/tenant_users.gen.go | 16 +- .../database/models/tenant_users.query.gen.go | 6 +- backend/database/models/tenants.gen.go | 23 +- backend/database/models/tenants.query.gen.go | 99 +-- .../models/user_comment_actions.gen.go | 59 ++ .../models/user_comment_actions.query.gen.go | 477 ++++++++++ .../models/user_content_actions.gen.go | 59 ++ .../models/user_content_actions.query.gen.go | 477 ++++++++++ backend/database/models/users.gen.go | 37 +- backend/database/models/users.query.gen.go | 269 ++---- backend/pkg/consts/api_enums.gen.go | 824 ++++++++++++++++++ backend/pkg/consts/api_enums.go | 127 +++ models/comments.gen.go | 66 ++ models/comments.query.gen.go | 510 +++++++++++ models/content_access.gen.go | 63 ++ .../models => models}/content_access.go | 0 models/content_access.query.gen.go | 493 +++++++++++ models/content_assets.gen.go | 63 ++ models/content_assets.query.gen.go | 493 +++++++++++ models/content_prices.gen.go | 66 ++ models/content_prices.query.gen.go | 505 +++++++++++ models/contents.gen.go | 76 ++ models/contents.query.gen.go | 546 ++++++++++++ models/media_assets.gen.go | 73 ++ models/media_assets.query.gen.go | 526 +++++++++++ models/notifications.gen.go | 62 ++ models/notifications.query.gen.go | 489 +++++++++++ models/order_items.gen.go | 61 ++ models/order_items.query.gen.go | 497 +++++++++++ models/orders.gen.go | 69 ++ models/orders.query.gen.go | 527 +++++++++++ models/payout_accounts.gen.go | 63 ++ models/payout_accounts.query.gen.go | 493 +++++++++++ models/query.gen.go | 239 +++++ models/tenant_invites.gen.go | 67 ++ models/tenant_invites.query.gen.go | 509 +++++++++++ models/tenant_join_requests.gen.go | 64 ++ models/tenant_join_requests.query.gen.go | 497 +++++++++++ models/tenant_ledgers.gen.go | 71 ++ models/tenant_ledgers.query.gen.go | 525 +++++++++++ models/tenant_users.gen.go | 60 ++ models/tenant_users.query.gen.go | 485 +++++++++++ models/tenants.gen.go | 61 ++ .../database/models => models}/tenants.go | 0 models/tenants.query.gen.go | 495 +++++++++++ models/user_comment_actions.gen.go | 59 ++ models/user_comment_actions.query.gen.go | 477 ++++++++++ models/user_content_actions.gen.go | 59 ++ models/user_content_actions.query.gen.go | 477 ++++++++++ models/users.gen.go | 78 ++ {backend/database/models => models}/users.go | 8 +- models/users.query.gen.go | 552 ++++++++++++ 116 files changed, 17579 insertions(+), 1213 deletions(-) create mode 100644 backend/app/http/provider.go create mode 100644 backend/app/http/v1/auth.go create mode 100644 backend/app/http/v1/common.go create mode 100644 backend/app/http/v1/content.go create mode 100644 backend/app/http/v1/creator.go create mode 100644 backend/app/http/v1/dto/auth.go create mode 100644 backend/app/http/v1/dto/common.go create mode 100644 backend/app/http/v1/dto/content.go create mode 100644 backend/app/http/v1/dto/creator.go create mode 100644 backend/app/http/v1/dto/order.go create mode 100644 backend/app/http/v1/dto/super.go create mode 100644 backend/app/http/v1/dto/tenant.go create mode 100644 backend/app/http/v1/dto/user.go create mode 100755 backend/app/http/v1/provider.gen.go create mode 100644 backend/app/http/v1/routes.gen.go create mode 100644 backend/app/http/v1/routes.manual.go create mode 100644 backend/app/http/v1/super.go create mode 100644 backend/app/http/v1/tenant.go create mode 100644 backend/app/http/v1/transaction.go create mode 100644 backend/app/http/v1/user.go delete mode 100644 backend/app/http/web/dto/auth.go delete mode 100644 backend/app/http/web/dto/me.go delete mode 100644 backend/app/http/web/dto/password_reset.go delete mode 100644 backend/app/http/web/dto/tenant_apply.go delete mode 100755 backend/app/http/web/provider.gen.go create mode 100644 backend/app/services/common.go create mode 100644 backend/app/services/content.go create mode 100644 backend/app/services/creator.go create mode 100644 backend/app/services/order.go create mode 100644 backend/app/services/services.gen.go create mode 100644 backend/app/services/super.go create mode 100644 backend/app/services/tenant.go create mode 100644 backend/app/services/user.go create mode 100644 backend/app/services/wallet.go create mode 100644 backend/database/migrations/20251227120000_add_api_support.sql create mode 100644 backend/database/models/comments.gen.go create mode 100644 backend/database/models/comments.query.gen.go create mode 100644 backend/database/models/notifications.gen.go create mode 100644 backend/database/models/notifications.query.gen.go create mode 100644 backend/database/models/payout_accounts.gen.go create mode 100644 backend/database/models/payout_accounts.query.gen.go create mode 100644 backend/database/models/user_comment_actions.gen.go create mode 100644 backend/database/models/user_comment_actions.query.gen.go create mode 100644 backend/database/models/user_content_actions.gen.go create mode 100644 backend/database/models/user_content_actions.query.gen.go create mode 100644 backend/pkg/consts/api_enums.gen.go create mode 100644 backend/pkg/consts/api_enums.go create mode 100644 models/comments.gen.go create mode 100644 models/comments.query.gen.go create mode 100644 models/content_access.gen.go rename {backend/database/models => models}/content_access.go (100%) create mode 100644 models/content_access.query.gen.go create mode 100644 models/content_assets.gen.go create mode 100644 models/content_assets.query.gen.go create mode 100644 models/content_prices.gen.go create mode 100644 models/content_prices.query.gen.go create mode 100644 models/contents.gen.go create mode 100644 models/contents.query.gen.go create mode 100644 models/media_assets.gen.go create mode 100644 models/media_assets.query.gen.go create mode 100644 models/notifications.gen.go create mode 100644 models/notifications.query.gen.go create mode 100644 models/order_items.gen.go create mode 100644 models/order_items.query.gen.go create mode 100644 models/orders.gen.go create mode 100644 models/orders.query.gen.go create mode 100644 models/payout_accounts.gen.go create mode 100644 models/payout_accounts.query.gen.go create mode 100644 models/query.gen.go create mode 100644 models/tenant_invites.gen.go create mode 100644 models/tenant_invites.query.gen.go create mode 100644 models/tenant_join_requests.gen.go create mode 100644 models/tenant_join_requests.query.gen.go create mode 100644 models/tenant_ledgers.gen.go create mode 100644 models/tenant_ledgers.query.gen.go create mode 100644 models/tenant_users.gen.go create mode 100644 models/tenant_users.query.gen.go create mode 100644 models/tenants.gen.go rename {backend/database/models => models}/tenants.go (100%) create mode 100644 models/tenants.query.gen.go create mode 100644 models/user_comment_actions.gen.go create mode 100644 models/user_comment_actions.query.gen.go create mode 100644 models/user_content_actions.gen.go create mode 100644 models/user_content_actions.query.gen.go create mode 100644 models/users.gen.go rename {backend/database/models => models}/users.go (57%) create mode 100644 models/users.query.gen.go diff --git a/backend/app/commands/http/http.go b/backend/app/commands/http/http.go index 9403727..9987da4 100644 --- a/backend/app/commands/http/http.go +++ b/backend/app/commands/http/http.go @@ -6,7 +6,7 @@ import ( "quyun/v2/app/commands" "quyun/v2/app/errorx" - "quyun/v2/app/http/web" + appHttp "quyun/v2/app/http" "quyun/v2/app/jobs" "quyun/v2/app/middlewares" "quyun/v2/app/services" @@ -46,11 +46,13 @@ func Command() atom.Option { atom.RunE(Serve), atom.Providers( defaultProviders(). + WithProviders( + appHttp.Providers(), + ). With( jobs.Provide, services.Provide, middlewares.Provide, - web.Provide, ), ), ) diff --git a/backend/app/http/provider.go b/backend/app/http/provider.go new file mode 100644 index 0000000..a916f5d --- /dev/null +++ b/backend/app/http/provider.go @@ -0,0 +1,13 @@ +package http + +import ( + v1 "quyun/v2/app/http/v1" + + "go.ipao.vip/atom/container" +) + +func Providers() container.Providers { + return container.Providers{ + {Provider: v1.Provide}, + } +} diff --git a/backend/app/http/v1/auth.go b/backend/app/http/v1/auth.go new file mode 100644 index 0000000..0835acf --- /dev/null +++ b/backend/app/http/v1/auth.go @@ -0,0 +1,41 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Auth struct{} + +// SendOTP sends an OTP to the provided phone number. +// +// @Router /v1/auth/otp [post] +// @Summary Send OTP +// @Description Send OTP to phone number +// @Tags Auth +// @Accept json +// @Produce json +// @Param form body dto.SendOTPForm true "Phone number" +// @Success 200 {object} string "OTP sent" +// @Bind form body +func (a *Auth) SendOTP(ctx fiber.Ctx, form *dto.SendOTPForm) error { + return services.User.SendOTP(ctx.Context(), form.Phone) +} + +// Login logs in or registers a user with OTP. +// +// @Router /v1/auth/login [post] +// @Summary Login or Register with OTP +// @Description Login or register user using phone number and OTP +// @Tags Auth +// @Accept json +// @Produce json +// @Param form body dto.LoginForm true "Login form" +// @Success 200 {object} dto.LoginResponse +// @Bind form body +func (a *Auth) Login(ctx fiber.Ctx, form *dto.LoginForm) (*dto.LoginResponse, error) { + return services.User.LoginWithOTP(ctx.Context(), form.Phone, form.OTP) +} diff --git a/backend/app/http/v1/common.go b/backend/app/http/v1/common.go new file mode 100644 index 0000000..c293afc --- /dev/null +++ b/backend/app/http/v1/common.go @@ -0,0 +1,34 @@ +package v1 + +import ( + "mime/multipart" + + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Common struct{} + +// Upload file +// +// @Router /v1/upload [post] +// @Summary Upload file +// @Description Upload file +// @Tags Common +// @Accept multipart/form-data +// @Produce json +// @Param file formData file true "File" +// @Param type formData string false "Type enum(image, video, audio)" +// @Success 200 {object} dto.UploadResult +// @Bind file file +// @Bind typeArg body key(type) +func (c *Common) Upload(ctx fiber.Ctx, file *multipart.FileHeader, typeArg *string) (*dto.UploadResult, error) { + val := "" + if typeArg != nil { + val = *typeArg + } + return services.Common.Upload(ctx.Context(), file, val) +} diff --git a/backend/app/http/v1/content.go b/backend/app/http/v1/content.go new file mode 100644 index 0000000..4d8aecf --- /dev/null +++ b/backend/app/http/v1/content.go @@ -0,0 +1,115 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Content struct{} + +// List contents (Explore / Search) +// +// @Router /v1/contents [get] +// @Summary List contents +// @Description List contents with filtering and pagination +// @Tags Content +// @Accept json +// @Produce json +// @Param keyword query string false "Search keyword" +// @Param genre query string false "Genre" +// @Param tenantId query string false "Filter by creator" +// @Param sort query string false "Sort order" Enums(latest, hot, price_asc) +// @Param page query int false "Page number" +// @Success 200 {object} dto.ContentListResponse +// @Bind keyword query +// @Bind genre query +// @Bind tenantId query +// @Bind sort query +// @Bind page query +func (c *Content) List( + ctx fiber.Ctx, + keyword, genre, tenantId, sort string, + page int, +) (*dto.ContentListResponse, error) { + return services.Content.List(ctx.Context(), keyword, genre, tenantId, sort, page) +} + +// Get content detail +// +// @Router /v1/contents/:id [get] +// @Summary Get content detail +// @Description Get content detail by ID +// @Tags Content +// @Accept json +// @Produce json +// @Param id path string true "Content ID" +// @Success 200 {object} dto.ContentDetail +// @Bind id path +func (c *Content) Get(ctx fiber.Ctx, id string) (*dto.ContentDetail, error) { + return services.Content.Get(ctx.Context(), id) +} + +// Get comments for a content +// +// @Router /v1/contents/:id/comments [get] +// @Summary Get comments +// @Description Get comments for a content +// @Tags Content +// @Accept json +// @Produce json +// @Param id path string true "Content ID" +// @Param page query int false "Page number" +// @Success 200 {object} dto.CommentListResponse +// @Bind id path +// @Bind page query +func (c *Content) ListComments(ctx fiber.Ctx, id string, page int) (*dto.CommentListResponse, error) { + return services.Content.ListComments(ctx.Context(), id, page) +} + +// Post a comment +// +// @Router /v1/contents/:id/comments [post] +// @Summary Post comment +// @Description Post a comment to a content +// @Tags Content +// @Accept json +// @Produce json +// @Param id path string true "Content ID" +// @Param form body dto.CommentCreateForm true "Comment form" +// @Success 200 {string} string "Comment created" +// @Bind id path +// @Bind form body +func (c *Content) CreateComment(ctx fiber.Ctx, id string, form *dto.CommentCreateForm) error { + return services.Content.CreateComment(ctx.Context(), id, form) +} + +// Like a comment +// +// @Router /v1/comments/:id/like [post] +// @Summary Like comment +// @Description Like a comment +// @Tags Content +// @Accept json +// @Produce json +// @Param id path string true "Comment ID" +// @Success 200 {string} string "Liked" +// @Bind id path +func (c *Content) LikeComment(ctx fiber.Ctx, id string) error { + return services.Content.LikeComment(ctx.Context(), id) +} + +// List curated topics +// +// @Router /v1/topics [get] +// @Summary List topics +// @Description List curated topics +// @Tags Content +// @Accept json +// @Produce json +// @Success 200 {array} dto.Topic +func (c *Content) ListTopics(ctx fiber.Ctx) ([]dto.Topic, error) { + return services.Content.ListTopics(ctx.Context()) +} diff --git a/backend/app/http/v1/creator.go b/backend/app/http/v1/creator.go new file mode 100644 index 0000000..bfab366 --- /dev/null +++ b/backend/app/http/v1/creator.go @@ -0,0 +1,225 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Creator struct{} + +// Apply to become a creator +// +// @Router /v1/creator/apply [post] +// @Summary Apply creator +// @Description Apply to become a creator +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param form body dto.ApplyForm true "Apply form" +// @Success 200 {string} string "Application submitted" +// @Bind form body +func (c *Creator) Apply(ctx fiber.Ctx, form *dto.ApplyForm) error { + return services.Creator.Apply(ctx.Context(), form) +} + +// Get creator dashboard stats +// +// @Router /v1/creator/dashboard [get] +// @Summary Dashboard stats +// @Description Get creator dashboard stats +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Success 200 {object} dto.DashboardStats +func (c *Creator) Dashboard(ctx fiber.Ctx) (*dto.DashboardStats, error) { + return services.Creator.Dashboard(ctx.Context()) +} + +// List creator contents +// +// @Router /v1/creator/contents [get] +// @Summary List contents +// @Description List creator contents +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param status query string false "Status" +// @Param genre query string false "Genre" +// @Param keyword query string false "Keyword" +// @Success 200 {array} dto.ContentItem +// @Bind status query +// @Bind genre query +// @Bind keyword query +func (c *Creator) ListContents(ctx fiber.Ctx, status, genre, keyword string) ([]dto.ContentItem, error) { + return services.Creator.ListContents(ctx.Context(), status, genre, keyword) +} + +// Create/Publish content +// +// @Router /v1/creator/contents [post] +// @Summary Create content +// @Description Create/Publish content +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param form body dto.ContentCreateForm true "Content form" +// @Success 200 {string} string "Created" +// @Bind form body +func (c *Creator) CreateContent(ctx fiber.Ctx, form *dto.ContentCreateForm) error { + return services.Creator.CreateContent(ctx.Context(), form) +} + +// Update content +// +// @Router /v1/creator/contents/:id [put] +// @Summary Update content +// @Description Update content +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param id path string true "Content ID" +// @Param form body dto.ContentUpdateForm true "Update form" +// @Success 200 {string} string "Updated" +// @Bind id path +// @Bind form body +func (c *Creator) UpdateContent(ctx fiber.Ctx, id string, form *dto.ContentUpdateForm) error { + return services.Creator.UpdateContent(ctx.Context(), id, form) +} + +// Delete content +// +// @Router /v1/creator/contents/:id [delete] +// @Summary Delete content +// @Description Delete content +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param id path string true "Content ID" +// @Success 200 {string} string "Deleted" +// @Bind id path +func (c *Creator) DeleteContent(ctx fiber.Ctx, id string) error { + return services.Creator.DeleteContent(ctx.Context(), id) +} + +// List sales orders +// +// @Router /v1/creator/orders [get] +// @Summary List sales orders +// @Description List sales orders +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param status query string false "Status" +// @Param keyword query string false "Keyword" +// @Success 200 {array} dto.Order +// @Bind status query +// @Bind keyword query +func (c *Creator) ListOrders(ctx fiber.Ctx, status, keyword string) ([]dto.Order, error) { + return services.Creator.ListOrders(ctx.Context(), status, keyword) +} + +// Process refund +// +// @Router /v1/creator/orders/:id/refund [post] +// @Summary Process refund +// @Description Process refund +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param id path string true "Order ID" +// @Param form body dto.RefundForm true "Refund form" +// @Success 200 {string} string "Processed" +// @Bind id path +// @Bind form body +func (c *Creator) Refund(ctx fiber.Ctx, id string, form *dto.RefundForm) error { + return services.Creator.ProcessRefund(ctx.Context(), id, form) +} + +// Get channel settings +// +// @Router /v1/creator/settings [get] +// @Summary Get settings +// @Description Get channel settings +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Success 200 {object} dto.Settings +func (c *Creator) GetSettings(ctx fiber.Ctx) (*dto.Settings, error) { + return services.Creator.GetSettings(ctx.Context()) +} + +// Update channel settings +// +// @Router /v1/creator/settings [put] +// @Summary Update settings +// @Description Update channel settings +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param form body dto.Settings true "Settings form" +// @Success 200 {string} string "Updated" +// @Bind form body +func (c *Creator) UpdateSettings(ctx fiber.Ctx, form *dto.Settings) error { + return services.Creator.UpdateSettings(ctx.Context(), form) +} + +// List payout accounts +// +// @Router /v1/creator/payout-accounts [get] +// @Summary List payout accounts +// @Description List payout accounts +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Success 200 {array} dto.PayoutAccount +func (c *Creator) ListPayoutAccounts(ctx fiber.Ctx) ([]dto.PayoutAccount, error) { + return services.Creator.ListPayoutAccounts(ctx.Context()) +} + +// Add payout account +// +// @Router /v1/creator/payout-accounts [post] +// @Summary Add payout account +// @Description Add payout account +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param form body dto.PayoutAccount true "Account form" +// @Success 200 {string} string "Added" +// @Bind form body +func (c *Creator) AddPayoutAccount(ctx fiber.Ctx, form *dto.PayoutAccount) error { + return services.Creator.AddPayoutAccount(ctx.Context(), form) +} + +// Remove payout account +// +// @Router /v1/creator/payout-accounts [delete] +// @Summary Remove payout account +// @Description Remove payout account +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param id query string true "Account ID" +// @Success 200 {string} string "Removed" +// @Bind id query +func (c *Creator) RemovePayoutAccount(ctx fiber.Ctx, id string) error { + return services.Creator.RemovePayoutAccount(ctx.Context(), id) +} + +// Request withdrawal +// +// @Router /v1/creator/withdraw [post] +// @Summary Request withdrawal +// @Description Request withdrawal +// @Tags CreatorCenter +// @Accept json +// @Produce json +// @Param form body dto.WithdrawForm true "Withdraw form" +// @Success 200 {string} string "Withdrawal requested" +// @Bind form body +func (c *Creator) Withdraw(ctx fiber.Ctx, form *dto.WithdrawForm) error { + return services.Creator.Withdraw(ctx.Context(), form) +} diff --git a/backend/app/http/v1/dto/auth.go b/backend/app/http/v1/dto/auth.go new file mode 100644 index 0000000..bf9fe53 --- /dev/null +++ b/backend/app/http/v1/dto/auth.go @@ -0,0 +1,36 @@ +package dto + +import "quyun/v2/pkg/consts" + +type SendOTPForm struct { + Phone string `json:"phone"` +} + +type LoginForm struct { + Phone string `json:"phone"` + OTP string `json:"otp"` +} + +type LoginResponse struct { + Token string `json:"token"` + User *User `json:"user"` +} + +type User struct { + ID string `json:"id"` + Phone string `json:"phone"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Gender consts.Gender `json:"gender"` + Bio string `json:"bio"` + Birthday string `json:"birthday"` // YYYY-MM-DD + Location *Location `json:"location"` + Balance float64 `json:"balance"` + Points int64 `json:"points"` + IsRealNameVerified bool `json:"isRealNameVerified"` +} + +type Location struct { + Province string `json:"province"` + City string `json:"city"` +} diff --git a/backend/app/http/v1/dto/common.go b/backend/app/http/v1/dto/common.go new file mode 100644 index 0000000..be435e7 --- /dev/null +++ b/backend/app/http/v1/dto/common.go @@ -0,0 +1,9 @@ +package dto + +type UploadResult struct { + ID string `json:"id"` + URL string `json:"url"` + Filename string `json:"filename"` + Size int64 `json:"size"` + MimeType string `json:"mimeType"` +} diff --git a/backend/app/http/v1/dto/content.go b/backend/app/http/v1/dto/content.go new file mode 100644 index 0000000..575c97d --- /dev/null +++ b/backend/app/http/v1/dto/content.go @@ -0,0 +1,84 @@ +package dto + +import "quyun/v2/app/requests" + +type ContentItem struct { + ID string `json:"id"` + Title string `json:"title"` + Cover string `json:"cover"` + Genre string `json:"genre"` + Type string `json:"type"` // video, audio, article + Price float64 `json:"price"` + AuthorID string `json:"authorId"` + AuthorName string `json:"authorName"` + AuthorAvatar string `json:"authorAvatar"` + Views int `json:"views"` + Likes int `json:"likes"` + IsPurchased bool `json:"isPurchased"` +} + +type ContentDetail struct { + ContentItem + Description string `json:"description"` + Body string `json:"body"` + MediaUrls []MediaURL `json:"mediaUrls"` + Meta Meta `json:"meta"` + IsLiked bool `json:"isLiked"` + IsFavorited bool `json:"isFavorited"` +} + +type MediaURL struct { + Type string `json:"type"` + URL string `json:"url"` + Duration int `json:"duration"` +} + +type Meta struct { + Role string `json:"role"` + Key string `json:"key"` + Beat string `json:"beat"` +} + +type Comment struct { + ID string `json:"id"` + Content string `json:"content"` + UserID string `json:"userId"` + UserNickname string `json:"userNickname"` + UserAvatar string `json:"userAvatar"` + CreateTime string `json:"createTime"` + Likes int `json:"likes"` + IsLiked bool `json:"isLiked"` + ReplyTo string `json:"replyTo"` +} + +type CommentListResponse struct { + Data []Comment `json:"data"` + Pagination requests.Pagination `json:"pagination"` +} + +type CommentCreateForm struct { + Content string `json:"content"` + ReplyTo string `json:"replyTo"` +} + +type ContentListResponse struct { + Data []ContentItem `json:"data"` + Pagination requests.Pagination `json:"pagination"` +} + +type Topic struct { + ID string `json:"id"` + Title string `json:"title"` + Cover string `json:"cover"` + Tag string `json:"tag"` + Count int `json:"count"` +} + +type ContentPrice struct { + Currency string `json:"currency"` + PriceAmount float64 `json:"priceAmount"` + DiscountType string `json:"discountType"` + DiscountValue float64 `json:"discountValue"` + DiscountStartAt string `json:"discountStartAt"` + DiscountEndAt string `json:"discountEndAt"` +} diff --git a/backend/app/http/v1/dto/creator.go b/backend/app/http/v1/dto/creator.go new file mode 100644 index 0000000..f1dd736 --- /dev/null +++ b/backend/app/http/v1/dto/creator.go @@ -0,0 +1,77 @@ +package dto + +type ApplyForm struct { + Name string `json:"name"` + Bio string `json:"bio"` + Avatar string `json:"avatar"` +} + +type DashboardStats struct { + TotalFollowers IntStatItem `json:"totalFollowers"` + TotalRevenue FloatStatItem `json:"totalRevenue"` + PendingRefunds int `json:"pendingRefunds"` + NewMessages int `json:"newMessages"` +} + +type IntStatItem struct { + Value int `json:"value"` + Trend float64 `json:"trend"` +} + +type FloatStatItem struct { + Value float64 `json:"value"` + Trend float64 `json:"trend"` +} + +type ContentCreateForm struct { + Title string `json:"title"` + Genre string `json:"genre"` + Price float64 `json:"price"` + MediaIDs []string `json:"mediaIds"` +} + +type ContentUpdateForm struct { + Title string `json:"title"` + Genre string `json:"genre"` + Price float64 `json:"price"` + MediaIDs []string `json:"mediaIds"` +} + +type RefundForm struct { + Action string `json:"action"` // accept, reject + Reason string `json:"reason"` +} + +type Settings struct { + Name string `json:"name"` + Bio string `json:"bio"` + Avatar string `json:"avatar"` + Cover string `json:"cover"` + Description string `json:"description"` +} + +type PayoutAccount struct { + ID string `json:"id"` + Type string `json:"type"` // bank, alipay + Name string `json:"name"` + Account string `json:"account"` + Realname string `json:"realname"` +} + +type WithdrawForm struct { + Amount float64 `json:"amount"` + Method string `json:"method"` // wallet, external + AccountID string `json:"accountId"` +} + +// Re-export or Wrap +// Since ContentItem and Order are in the same package 'dto', +// we don't need type aliases unless we want to rename them. +// If creator.go uses them, it can use dto.ContentItem directly. +// But creator.go is in `v1` (package v1) and imports `dto`. +// So it uses `dto.ContentItem`. +// So we don't need aliases here if the original types are in this package. + +// However, if the originals were in `content/dto` and `user/dto` and we moved them to `v1/dto` (this package), +// then we just have them defined in `content.go` (dto) and `user.go` (dto). +// So aliases are not needed if they are in the same package. \ No newline at end of file diff --git a/backend/app/http/v1/dto/order.go b/backend/app/http/v1/dto/order.go new file mode 100644 index 0000000..adc4e67 --- /dev/null +++ b/backend/app/http/v1/dto/order.go @@ -0,0 +1,23 @@ +package dto + +type OrderCreateForm struct { + ContentID string `json:"contentId"` + Sku string `json:"sku"` + Quantity int `json:"quantity"` +} + +type OrderCreateResponse struct { + OrderID string `json:"orderId"` +} + +type OrderPayForm struct { + Method string `json:"method"` // wechat, alipay, balance +} + +type OrderPayResponse struct { + PayParams string `json:"payParams"` +} + +type OrderStatusResponse struct { + Status string `json:"status"` // unpaid, paid, completed +} diff --git a/backend/app/http/v1/dto/super.go b/backend/app/http/v1/dto/super.go new file mode 100644 index 0000000..6b1dc53 --- /dev/null +++ b/backend/app/http/v1/dto/super.go @@ -0,0 +1,202 @@ +package dto + +import ( + "quyun/v2/pkg/consts" +) + +// SuperUserLite 用于平台用户列表的轻量级用户信息 +type SuperUserLite struct { + ID int64 `json:"id"` + Username string `json:"username"` + Roles []consts.Role `json:"roles"` + Status consts.UserStatus `json:"status"` + StatusDescription string `json:"status_description"` + VerifiedAt string `json:"verified_at"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type UserItem struct { + SuperUserLite + Balance int64 `json:"balance"` + BalanceFrozen int64 `json:"balance_frozen"` + OwnedTenantCount int64 `json:"owned_tenant_count"` + JoinedTenantCount int64 `json:"joined_tenant_count"` +} + +type UserStatistics struct { + Status consts.UserStatus `json:"status"` + StatusDescription string `json:"status_description"` + Count int64 `json:"count"` +} + +type UserStatusUpdateForm struct { + Status consts.UserStatus `json:"status" validate:"required"` +} + +type UserRolesUpdateForm struct { + Roles []consts.Role `json:"roles" validate:"required,min=1"` +} + +type UserTenantItem struct { + TenantID int64 `json:"tenant_id"` + TenantStatus consts.TenantStatus `json:"tenant_status"` + TenantStatusDescription string `json:"tenant_status_description"` + Name string `json:"name"` + Code string `json:"code"` + Owner *TenantOwnerUserLite `json:"owner"` + Role []consts.TenantUserRole `json:"role"` + MemberStatus consts.UserStatus `json:"member_status"` + MemberStatusDescription string `json:"member_status_description"` + JoinedAt string `json:"joined_at"` + ExpiredAt string `json:"expired_at"` +} + +// Tenant Related +type TenantCreateForm struct { + Name string `json:"name" validate:"required,max=128"` + Code string `json:"code" validate:"required,max=64"` + AdminUserID int64 `json:"admin_user_id" validate:"required"` + Duration int `json:"duration" validate:"required,oneof=7 30 90 180 365"` +} + +type TenantItem struct { + ID int64 `json:"id"` + UUID string `json:"uuid"` + Code string `json:"code"` + Name string `json:"name"` + Status consts.TenantStatus `json:"status"` + StatusDescription string `json:"status_description"` + Config []int `json:"config"` // Replace with actual config struct if needed + Owner *TenantOwnerUserLite `json:"owner"` + AdminUsers []*TenantAdminUserLite `json:"admin_users"` + UserCount int64 `json:"user_count"` + IncomeAmountPaidSum int64 `json:"income_amount_paid_sum"` + ExpiredAt string `json:"expired_at"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + UserID int64 `json:"user_id"` + Users []*SuperUserLite `json:"users"` +} + +type TenantOwnerUserLite struct { + ID int64 `json:"id"` + Username string `json:"username"` +} + +type TenantAdminUserLite struct { + ID int64 `json:"id"` + Username string `json:"username"` +} + +type TenantExpireUpdateForm struct { + Duration int `json:"duration" validate:"required,oneof=7 30 90 180 365"` +} + +type TenantStatusUpdateForm struct { + Status consts.TenantStatus `json:"status" validate:"required"` +} + +type SuperTenantContentItem struct { + Content *ContentItem `json:"content"` + StatusDescription string `json:"status_description"` + VisibilityDescription string `json:"visibility_description"` + Tenant *SuperContentTenantLite `json:"tenant"` + Owner *SuperUserLite `json:"owner"` + Price *ContentPrice `json:"price"` // Reuse or define specific price struct +} + +type SuperContentTenantLite struct { + ID int64 `json:"id"` + Code string `json:"code"` + Name string `json:"name"` +} + +type SuperTenantContentStatusUpdateForm struct { + Status consts.ContentStatus `json:"status" validate:"required,oneof=unpublished blocked"` +} + +type SuperTenantUserItem struct { + User *SuperUserLite `json:"user"` + TenantUser *TenantUser `json:"tenant_user"` +} + +type TenantUser struct { + ID int64 `json:"id"` + TenantID int64 `json:"tenant_id"` + UserID int64 `json:"user_id"` + Role []consts.TenantUserRole `json:"role"` + Status consts.UserStatus `json:"status"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +// Order Related +type SuperOrderItem struct { + ID int64 `json:"id"` + Type consts.OrderType `json:"type"` + Status consts.OrderStatus `json:"status"` + StatusDescription string `json:"status_description"` + Currency consts.Currency `json:"currency"` + AmountOriginal int64 `json:"amount_original"` + AmountDiscount int64 `json:"amount_discount"` + AmountPaid int64 `json:"amount_paid"` + Tenant *OrderTenantLite `json:"tenant"` + Buyer *OrderBuyerLite `json:"buyer"` + PaidAt string `json:"paid_at"` + RefundedAt string `json:"refunded_at"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type OrderTenantLite struct { + ID int64 `json:"id"` + Code string `json:"code"` + Name string `json:"name"` +} + +type OrderBuyerLite struct { + ID int64 `json:"id"` + Username string `json:"username"` +} + +type OrderStatisticsResponse struct { + TotalCount int64 `json:"total_count"` + TotalAmountPaidSum int64 `json:"total_amount_paid_sum"` + ByStatus []OrderStatisticsRow `json:"by_status"` +} + +type OrderStatisticsRow struct { + Status consts.OrderStatus `json:"status"` + StatusDescription string `json:"status_description"` + Count int64 `json:"count"` + AmountPaidSum int64 `json:"amount_paid_sum"` +} + +type SuperOrderDetail struct { + Order *SuperOrderItem `json:"order"` // Using SuperOrderItem as base, extend if needed + Tenant *OrderTenantLite `json:"tenant"` + Buyer *OrderBuyerLite `json:"buyer"` +} + +type SuperOrderRefundForm struct { + Force bool `json:"force"` + Reason string `json:"reason"` + IdempotencyKey string `json:"idempotency_key"` +} + +// AdminContentItem for super admin view +type AdminContentItem struct { + Content *ContentItem `json:"content"` + Owner *AdminContentOwnerLite `json:"owner"` + Price *ContentPrice `json:"price"` + StatusDescription string `json:"status_description"` + VisibilityDescription string `json:"visibility_description"` +} + +type AdminContentOwnerLite struct { + ID int64 `json:"id"` + Username string `json:"username"` + Roles []consts.Role `json:"roles"` + Status consts.UserStatus `json:"status"` +} diff --git a/backend/app/http/v1/dto/tenant.go b/backend/app/http/v1/dto/tenant.go new file mode 100644 index 0000000..5b8c70f --- /dev/null +++ b/backend/app/http/v1/dto/tenant.go @@ -0,0 +1,19 @@ +package dto + +type TenantProfile struct { + ID string `json:"id"` + Name string `json:"name"` + Avatar string `json:"avatar"` + Cover string `json:"cover"` + Bio string `json:"bio"` + Description string `json:"description"` + CertType string `json:"certType"` // personal, enterprise + Stats Stats `json:"stats"` + IsFollowing bool `json:"isFollowing"` +} + +type Stats struct { + Followers int `json:"followers"` + Contents int `json:"contents"` + Likes int `json:"likes"` +} diff --git a/backend/app/http/v1/dto/user.go b/backend/app/http/v1/dto/user.go new file mode 100644 index 0000000..ac2632e --- /dev/null +++ b/backend/app/http/v1/dto/user.go @@ -0,0 +1,62 @@ +package dto + +import "quyun/v2/pkg/consts" + +type UserUpdate struct { + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Gender consts.Gender `json:"gender"` + Bio string `json:"bio"` + Birthday string `json:"birthday"` + Location *Location `json:"location"` +} + +type RealNameForm struct { + Realname string `json:"realname"` + IDCard string `json:"idCard"` +} + +type WalletResponse struct { + Balance float64 `json:"balance"` + Transactions []Transaction `json:"transactions"` +} + +type Transaction struct { + ID string `json:"id"` + Title string `json:"title"` + Amount float64 `json:"amount"` + Type string `json:"type"` // income, expense + Date string `json:"date"` +} + +type RechargeForm struct { + Amount float64 `json:"amount"` + Method string `json:"method"` // wechat, alipay +} + +type RechargeResponse struct { + PayParams string `json:"payParams"` + OrderID string `json:"orderId"` +} + +type Order struct { + ID string `json:"id"` + CreateTime string `json:"createTime"` + PayTime string `json:"payTime"` + Status string `json:"status"` + Amount float64 `json:"amount"` + Quantity int `json:"quantity"` + Items []ContentItem `json:"items"` + TenantID string `json:"tenantId"` + TenantName string `json:"tenantName"` + IsVirtual bool `json:"isVirtual"` +} + +type Notification struct { + ID string `json:"id"` + Type string `json:"type"` + Title string `json:"title"` + Content string `json:"content"` + Read bool `json:"read"` + Time string `json:"time"` +} \ No newline at end of file diff --git a/backend/app/http/v1/provider.gen.go b/backend/app/http/v1/provider.gen.go new file mode 100755 index 0000000..28c3f49 --- /dev/null +++ b/backend/app/http/v1/provider.gen.go @@ -0,0 +1,100 @@ +package v1 + +import ( + "quyun/v2/app/middlewares" + + "go.ipao.vip/atom" + "go.ipao.vip/atom/container" + "go.ipao.vip/atom/contracts" + "go.ipao.vip/atom/opt" +) + +func Provide(opts ...opt.Option) error { + if err := container.Container.Provide(func() (*Auth, error) { + obj := &Auth{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*Common, error) { + obj := &Common{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*Content, error) { + obj := &Content{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*Creator, error) { + obj := &Creator{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func( + auth *Auth, + common *Common, + content *Content, + creator *Creator, + middlewares *middlewares.Middlewares, + super *Super, + tenant *Tenant, + transaction *Transaction, + user *User, + ) (contracts.HttpRoute, error) { + obj := &Routes{ + auth: auth, + common: common, + content: content, + creator: creator, + middlewares: middlewares, + super: super, + tenant: tenant, + transaction: transaction, + user: user, + } + if err := obj.Prepare(); err != nil { + return nil, err + } + + return obj, nil + }, atom.GroupRoutes); err != nil { + return err + } + if err := container.Container.Provide(func() (*Super, error) { + obj := &Super{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*Tenant, error) { + obj := &Tenant{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*Transaction, error) { + obj := &Transaction{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*User, error) { + obj := &User{} + + return obj, nil + }); err != nil { + return err + } + return nil +} diff --git a/backend/app/http/v1/routes.gen.go b/backend/app/http/v1/routes.gen.go new file mode 100644 index 0000000..360f9c6 --- /dev/null +++ b/backend/app/http/v1/routes.gen.go @@ -0,0 +1,394 @@ +// Code generated by atomctl. DO NOT EDIT. + +// Package v1 provides HTTP route definitions and registration +// for the quyun/v2 application. +package v1 + +import ( + "mime/multipart" + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/middlewares" + + "github.com/gofiber/fiber/v3" + log "github.com/sirupsen/logrus" + _ "go.ipao.vip/atom" + _ "go.ipao.vip/atom/contracts" + . "go.ipao.vip/atom/fen" +) + +// Routes implements the HttpRoute contract and provides route registration +// for all controllers in the v1 module. +// +// @provider contracts.HttpRoute atom.GroupRoutes +type Routes struct { + log *log.Entry `inject:"false"` + middlewares *middlewares.Middlewares + // Controller instances + auth *Auth + common *Common + content *Content + creator *Creator + super *Super + tenant *Tenant + transaction *Transaction + user *User +} + +// Prepare initializes the routes provider with logging configuration. +func (r *Routes) Prepare() error { + r.log = log.WithField("module", "routes.v1") + r.log.Info("Initializing routes module") + return nil +} + +// Name returns the unique identifier for this routes provider. +func (r *Routes) Name() string { + return "v1" +} + +// Register registers all HTTP routes with the provided fiber router. +// Each route is registered with its corresponding controller action and parameter bindings. +func (r *Routes) Register(router fiber.Router) { + // Register routes for controller: Auth + r.log.Debugf("Registering route: Post /v1/auth/login -> auth.Login") + router.Post("/v1/auth/login"[len(r.Path()):], DataFunc1( + r.auth.Login, + Body[dto.LoginForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/auth/otp -> auth.SendOTP") + router.Post("/v1/auth/otp"[len(r.Path()):], Func1( + r.auth.SendOTP, + Body[dto.SendOTPForm]("form"), + )) + // Register routes for controller: Common + r.log.Debugf("Registering route: Post /v1/upload -> common.Upload") + router.Post("/v1/upload"[len(r.Path()):], DataFunc2( + r.common.Upload, + File[multipart.FileHeader]("file"), + Body[string]("type"), + )) + // Register routes for controller: Content + r.log.Debugf("Registering route: Get /v1/contents -> content.List") + router.Get("/v1/contents"[len(r.Path()):], DataFunc5( + r.content.List, + QueryParam[string]("keyword"), + QueryParam[string]("genre"), + QueryParam[string]("tenantId"), + QueryParam[string]("sort"), + QueryParam[int]("page"), + )) + r.log.Debugf("Registering route: Get /v1/contents/:id -> content.Get") + router.Get("/v1/contents/:id"[len(r.Path()):], DataFunc1( + r.content.Get, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Get /v1/contents/:id/comments -> content.ListComments") + router.Get("/v1/contents/:id/comments"[len(r.Path()):], DataFunc2( + r.content.ListComments, + PathParam[string]("id"), + QueryParam[int]("page"), + )) + r.log.Debugf("Registering route: Get /v1/topics -> content.ListTopics") + router.Get("/v1/topics"[len(r.Path()):], DataFunc0( + r.content.ListTopics, + )) + r.log.Debugf("Registering route: Post /v1/comments/:id/like -> content.LikeComment") + router.Post("/v1/comments/:id/like"[len(r.Path()):], Func1( + r.content.LikeComment, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Post /v1/contents/:id/comments -> content.CreateComment") + router.Post("/v1/contents/:id/comments"[len(r.Path()):], Func2( + r.content.CreateComment, + PathParam[string]("id"), + Body[dto.CommentCreateForm]("form"), + )) + // Register routes for controller: Creator + r.log.Debugf("Registering route: Delete /v1/creator/contents/:id -> creator.DeleteContent") + router.Delete("/v1/creator/contents/:id"[len(r.Path()):], Func1( + r.creator.DeleteContent, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Delete /v1/creator/payout-accounts -> creator.RemovePayoutAccount") + router.Delete("/v1/creator/payout-accounts"[len(r.Path()):], Func1( + r.creator.RemovePayoutAccount, + QueryParam[string]("id"), + )) + r.log.Debugf("Registering route: Get /v1/creator/contents -> creator.ListContents") + router.Get("/v1/creator/contents"[len(r.Path()):], DataFunc3( + r.creator.ListContents, + QueryParam[string]("status"), + QueryParam[string]("genre"), + QueryParam[string]("keyword"), + )) + r.log.Debugf("Registering route: Get /v1/creator/dashboard -> creator.Dashboard") + router.Get("/v1/creator/dashboard"[len(r.Path()):], DataFunc0( + r.creator.Dashboard, + )) + r.log.Debugf("Registering route: Get /v1/creator/orders -> creator.ListOrders") + router.Get("/v1/creator/orders"[len(r.Path()):], DataFunc2( + r.creator.ListOrders, + QueryParam[string]("status"), + QueryParam[string]("keyword"), + )) + r.log.Debugf("Registering route: Get /v1/creator/payout-accounts -> creator.ListPayoutAccounts") + router.Get("/v1/creator/payout-accounts"[len(r.Path()):], DataFunc0( + r.creator.ListPayoutAccounts, + )) + r.log.Debugf("Registering route: Get /v1/creator/settings -> creator.GetSettings") + router.Get("/v1/creator/settings"[len(r.Path()):], DataFunc0( + r.creator.GetSettings, + )) + r.log.Debugf("Registering route: Post /v1/creator/apply -> creator.Apply") + router.Post("/v1/creator/apply"[len(r.Path()):], Func1( + r.creator.Apply, + Body[dto.ApplyForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/creator/contents -> creator.CreateContent") + router.Post("/v1/creator/contents"[len(r.Path()):], Func1( + r.creator.CreateContent, + Body[dto.ContentCreateForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/creator/orders/:id/refund -> creator.Refund") + router.Post("/v1/creator/orders/:id/refund"[len(r.Path()):], Func2( + r.creator.Refund, + PathParam[string]("id"), + Body[dto.RefundForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/creator/payout-accounts -> creator.AddPayoutAccount") + router.Post("/v1/creator/payout-accounts"[len(r.Path()):], Func1( + r.creator.AddPayoutAccount, + Body[dto.PayoutAccount]("form"), + )) + r.log.Debugf("Registering route: Post /v1/creator/withdraw -> creator.Withdraw") + router.Post("/v1/creator/withdraw"[len(r.Path()):], Func1( + r.creator.Withdraw, + Body[dto.WithdrawForm]("form"), + )) + r.log.Debugf("Registering route: Put /v1/creator/contents/:id -> creator.UpdateContent") + router.Put("/v1/creator/contents/:id"[len(r.Path()):], Func2( + r.creator.UpdateContent, + PathParam[string]("id"), + Body[dto.ContentUpdateForm]("form"), + )) + r.log.Debugf("Registering route: Put /v1/creator/settings -> creator.UpdateSettings") + router.Put("/v1/creator/settings"[len(r.Path()):], Func1( + r.creator.UpdateSettings, + Body[dto.Settings]("form"), + )) + // Register routes for controller: Super + r.log.Debugf("Registering route: Get /v1/auth/token -> super.CheckToken") + router.Get("/v1/auth/token"[len(r.Path()):], DataFunc0( + r.super.CheckToken, + )) + r.log.Debugf("Registering route: Get /v1/contents -> super.ListContents") + router.Get("/v1/contents"[len(r.Path()):], DataFunc2( + r.super.ListContents, + QueryParam[int]("page"), + QueryParam[int]("limit"), + )) + r.log.Debugf("Registering route: Get /v1/orders -> super.ListOrders") + router.Get("/v1/orders"[len(r.Path()):], DataFunc2( + r.super.ListOrders, + QueryParam[int]("page"), + QueryParam[int]("limit"), + )) + r.log.Debugf("Registering route: Get /v1/orders/:id -> super.GetOrder") + router.Get("/v1/orders/:id"[len(r.Path()):], DataFunc1( + r.super.GetOrder, + PathParam[int64]("id"), + )) + r.log.Debugf("Registering route: Get /v1/orders/statistics -> super.OrderStatistics") + router.Get("/v1/orders/statistics"[len(r.Path()):], DataFunc0( + r.super.OrderStatistics, + )) + r.log.Debugf("Registering route: Get /v1/tenants -> super.ListTenants") + router.Get("/v1/tenants"[len(r.Path()):], DataFunc3( + r.super.ListTenants, + QueryParam[int]("page"), + QueryParam[int]("limit"), + QueryParam[string]("name"), + )) + r.log.Debugf("Registering route: Get /v1/tenants/:id -> super.GetTenant") + router.Get("/v1/tenants/:id"[len(r.Path()):], DataFunc1( + r.super.GetTenant, + PathParam[int64]("id"), + )) + r.log.Debugf("Registering route: Get /v1/tenants/statuses -> super.TenantStatuses") + router.Get("/v1/tenants/statuses"[len(r.Path()):], DataFunc0( + r.super.TenantStatuses, + )) + r.log.Debugf("Registering route: Get /v1/users -> super.ListUsers") + router.Get("/v1/users"[len(r.Path()):], DataFunc3( + r.super.ListUsers, + QueryParam[int]("page"), + QueryParam[int]("limit"), + QueryParam[string]("username"), + )) + r.log.Debugf("Registering route: Get /v1/users/:id -> super.GetUser") + router.Get("/v1/users/:id"[len(r.Path()):], DataFunc1( + r.super.GetUser, + PathParam[int64]("id"), + )) + r.log.Debugf("Registering route: Get /v1/users/statistics -> super.UserStatistics") + router.Get("/v1/users/statistics"[len(r.Path()):], DataFunc0( + r.super.UserStatistics, + )) + r.log.Debugf("Registering route: Get /v1/users/statuses -> super.UserStatuses") + router.Get("/v1/users/statuses"[len(r.Path()):], DataFunc0( + r.super.UserStatuses, + )) + r.log.Debugf("Registering route: Patch /v1/tenants/:id -> super.UpdateTenantExpire") + router.Patch("/v1/tenants/:id"[len(r.Path()):], Func2( + r.super.UpdateTenantExpire, + PathParam[int64]("id"), + Body[dto.TenantExpireUpdateForm]("form"), + )) + r.log.Debugf("Registering route: Patch /v1/tenants/:id/status -> super.UpdateTenantStatus") + router.Patch("/v1/tenants/:id/status"[len(r.Path()):], Func2( + r.super.UpdateTenantStatus, + PathParam[int64]("id"), + Body[dto.TenantStatusUpdateForm]("form"), + )) + r.log.Debugf("Registering route: Patch /v1/tenants/:tenantID/contents/:contentID/status -> super.UpdateContentStatus") + router.Patch("/v1/tenants/:tenantID/contents/:contentID/status"[len(r.Path()):], Func3( + r.super.UpdateContentStatus, + PathParam[int64]("tenantID"), + PathParam[int64]("contentID"), + Body[dto.SuperTenantContentStatusUpdateForm]("form"), + )) + r.log.Debugf("Registering route: Patch /v1/users/:id/roles -> super.UpdateUserRoles") + router.Patch("/v1/users/:id/roles"[len(r.Path()):], Func2( + r.super.UpdateUserRoles, + PathParam[int64]("id"), + Body[dto.UserRolesUpdateForm]("form"), + )) + r.log.Debugf("Registering route: Patch /v1/users/:id/status -> super.UpdateUserStatus") + router.Patch("/v1/users/:id/status"[len(r.Path()):], Func2( + r.super.UpdateUserStatus, + PathParam[int64]("id"), + Body[dto.UserStatusUpdateForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/auth/login -> super.Login") + router.Post("/v1/auth/login"[len(r.Path()):], DataFunc1( + r.super.Login, + Body[dto.LoginForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/orders/:id/refund -> super.RefundOrder") + router.Post("/v1/orders/:id/refund"[len(r.Path()):], Func2( + r.super.RefundOrder, + PathParam[int64]("id"), + Body[dto.SuperOrderRefundForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/tenants -> super.CreateTenant") + router.Post("/v1/tenants"[len(r.Path()):], Func1( + r.super.CreateTenant, + Body[dto.TenantCreateForm]("form"), + )) + // Register routes for controller: Tenant + r.log.Debugf("Registering route: Delete /v1/tenants/:id/follow -> tenant.Unfollow") + router.Delete("/v1/tenants/:id/follow"[len(r.Path()):], Func1( + r.tenant.Unfollow, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Get /v1/tenants/:id -> tenant.Get") + router.Get("/v1/tenants/:id"[len(r.Path()):], DataFunc1( + r.tenant.Get, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Post /v1/tenants/:id/follow -> tenant.Follow") + router.Post("/v1/tenants/:id/follow"[len(r.Path()):], Func1( + r.tenant.Follow, + PathParam[string]("id"), + )) + // Register routes for controller: Transaction + r.log.Debugf("Registering route: Get /v1/orders/:id/status -> transaction.Status") + router.Get("/v1/orders/:id/status"[len(r.Path()):], DataFunc1( + r.transaction.Status, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Post /v1/orders -> transaction.Create") + router.Post("/v1/orders"[len(r.Path()):], DataFunc1( + r.transaction.Create, + Body[dto.OrderCreateForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/orders/:id/pay -> transaction.Pay") + router.Post("/v1/orders/:id/pay"[len(r.Path()):], DataFunc2( + r.transaction.Pay, + PathParam[string]("id"), + Body[dto.OrderPayForm]("form"), + )) + // Register routes for controller: User + r.log.Debugf("Registering route: Delete /v1/me/favorites/:contentId -> user.RemoveFavorite") + router.Delete("/v1/me/favorites/:contentId"[len(r.Path()):], Func1( + r.user.RemoveFavorite, + PathParam[string]("contentId"), + )) + r.log.Debugf("Registering route: Delete /v1/me/likes/:contentId -> user.RemoveLike") + router.Delete("/v1/me/likes/:contentId"[len(r.Path()):], Func1( + r.user.RemoveLike, + PathParam[string]("contentId"), + )) + r.log.Debugf("Registering route: Get /v1/me -> user.Me") + router.Get("/v1/me"[len(r.Path()):], DataFunc0( + r.user.Me, + )) + r.log.Debugf("Registering route: Get /v1/me/favorites -> user.Favorites") + router.Get("/v1/me/favorites"[len(r.Path()):], DataFunc0( + r.user.Favorites, + )) + r.log.Debugf("Registering route: Get /v1/me/library -> user.Library") + router.Get("/v1/me/library"[len(r.Path()):], DataFunc0( + r.user.Library, + )) + r.log.Debugf("Registering route: Get /v1/me/likes -> user.Likes") + router.Get("/v1/me/likes"[len(r.Path()):], DataFunc0( + r.user.Likes, + )) + r.log.Debugf("Registering route: Get /v1/me/notifications -> user.Notifications") + router.Get("/v1/me/notifications"[len(r.Path()):], DataFunc1( + r.user.Notifications, + QueryParam[string]("type"), + )) + r.log.Debugf("Registering route: Get /v1/me/orders -> user.ListOrders") + router.Get("/v1/me/orders"[len(r.Path()):], DataFunc1( + r.user.ListOrders, + QueryParam[string]("status"), + )) + r.log.Debugf("Registering route: Get /v1/me/orders/:id -> user.GetOrder") + router.Get("/v1/me/orders/:id"[len(r.Path()):], DataFunc1( + r.user.GetOrder, + PathParam[string]("id"), + )) + r.log.Debugf("Registering route: Get /v1/me/wallet -> user.Wallet") + router.Get("/v1/me/wallet"[len(r.Path()):], DataFunc0( + r.user.Wallet, + )) + r.log.Debugf("Registering route: Post /v1/me/favorites -> user.AddFavorite") + router.Post("/v1/me/favorites"[len(r.Path()):], Func1( + r.user.AddFavorite, + QueryParam[string]("contentId"), + )) + r.log.Debugf("Registering route: Post /v1/me/likes -> user.AddLike") + router.Post("/v1/me/likes"[len(r.Path()):], Func1( + r.user.AddLike, + QueryParam[string]("contentId"), + )) + r.log.Debugf("Registering route: Post /v1/me/realname -> user.RealName") + router.Post("/v1/me/realname"[len(r.Path()):], Func1( + r.user.RealName, + Body[dto.RealNameForm]("form"), + )) + r.log.Debugf("Registering route: Post /v1/me/wallet/recharge -> user.Recharge") + router.Post("/v1/me/wallet/recharge"[len(r.Path()):], DataFunc1( + r.user.Recharge, + Body[dto.RechargeForm]("form"), + )) + r.log.Debugf("Registering route: Put /v1/me -> user.Update") + router.Put("/v1/me"[len(r.Path()):], Func1( + r.user.Update, + Body[dto.UserUpdate]("form"), + )) + + r.log.Info("Successfully registered all routes") +} diff --git a/backend/app/http/v1/routes.manual.go b/backend/app/http/v1/routes.manual.go new file mode 100644 index 0000000..4802231 --- /dev/null +++ b/backend/app/http/v1/routes.manual.go @@ -0,0 +1,9 @@ +package v1 + +func (r *Routes) Path() string { + return "/v1" +} + +func (r *Routes) Middlewares() []any { + return []any{} +} diff --git a/backend/app/http/v1/super.go b/backend/app/http/v1/super.go new file mode 100644 index 0000000..c41f574 --- /dev/null +++ b/backend/app/http/v1/super.go @@ -0,0 +1,308 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/requests" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Super struct{} + +// Login +// +// @Router /v1/auth/login [post] +// @Summary Login +// @Tags Super +// @Accept json +// @Produce json +// @Param form body dto.LoginForm true "Login form" +// @Success 200 {object} dto.LoginResponse +// @Bind form body +func (s *Super) Login(ctx fiber.Ctx, form *dto.LoginForm) (*dto.LoginResponse, error) { + return services.Super.Login(ctx.Context(), form) +} + +// Check Token +// +// @Router /v1/auth/token [get] +// @Summary Check Token +// @Tags Super +// @Accept json +// @Produce json +// @Success 200 {object} dto.LoginResponse +func (s *Super) CheckToken(ctx fiber.Ctx) (*dto.LoginResponse, error) { + return services.Super.CheckToken(ctx.Context()) +} + +// List Users +// +// @Router /v1/users [get] +// @Summary User list +// @Tags Super +// @Accept json +// @Produce json +// @Param page query int false "Page" +// @Param limit query int false "Limit" +// @Param username query string false "Username" +// @Success 200 {object} requests.Pager{items=[]dto.UserItem} +// @Bind page query +// @Bind limit query +// @Bind username query +func (s *Super) ListUsers(ctx fiber.Ctx, page, limit int, username string) (*requests.Pager, error) { + return services.Super.ListUsers(ctx.Context(), page, limit, username) +} + +// Get User +// +// @Router /v1/users/:id [get] +// @Summary Get User +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Success 200 {object} dto.UserItem +// @Bind id path +func (s *Super) GetUser(ctx fiber.Ctx, id int64) (*dto.UserItem, error) { + return services.Super.GetUser(ctx.Context(), id) +} + +// Update User Status +// +// @Router /v1/users/:id/status [patch] +// @Summary Update user status +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Param form body dto.UserStatusUpdateForm true "Form" +// @Success 200 +// @Bind id path +// @Bind form body +func (s *Super) UpdateUserStatus(ctx fiber.Ctx, id int64, form *dto.UserStatusUpdateForm) error { + return services.Super.UpdateUserStatus(ctx.Context(), id, form) +} + +// Update User Roles +// +// @Router /v1/users/:id/roles [patch] +// @Summary Update user roles +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Param form body dto.UserRolesUpdateForm true "Form" +// @Success 200 +// @Bind id path +// @Bind form body +func (s *Super) UpdateUserRoles(ctx fiber.Ctx, id int64, form *dto.UserRolesUpdateForm) error { + return services.Super.UpdateUserRoles(ctx.Context(), id, form) +} + +// List Tenants +// +// @Router /v1/tenants [get] +// @Summary Tenant list +// @Tags Super +// @Accept json +// @Produce json +// @Param page query int false "Page" +// @Param limit query int false "Limit" +// @Param name query string false "Name" +// @Success 200 {object} requests.Pager{items=[]dto.TenantItem} +// @Bind page query +// @Bind limit query +// @Bind name query +func (s *Super) ListTenants(ctx fiber.Ctx, page, limit int, name string) (*requests.Pager, error) { + return services.Super.ListTenants(ctx.Context(), page, limit, name) +} + +// Create Tenant +// +// @Router /v1/tenants [post] +// @Summary Create Tenant +// @Tags Super +// @Accept json +// @Produce json +// @Param form body dto.TenantCreateForm true "Form" +// @Success 200 +// @Bind form body +func (s *Super) CreateTenant(ctx fiber.Ctx, form *dto.TenantCreateForm) error { + return services.Super.CreateTenant(ctx.Context(), form) +} + +// Get Tenant +// +// @Router /v1/tenants/:id [get] +// @Summary Get Tenant +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Success 200 {object} dto.TenantItem +// @Bind id path +func (s *Super) GetTenant(ctx fiber.Ctx, id int64) (*dto.TenantItem, error) { + return services.Super.GetTenant(ctx.Context(), id) +} + +// Update Tenant Status +// +// @Router /v1/tenants/:id/status [patch] +// @Summary Update Tenant Status +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Param form body dto.TenantStatusUpdateForm true "Form" +// @Success 200 +// @Bind id path +// @Bind form body +func (s *Super) UpdateTenantStatus(ctx fiber.Ctx, id int64, form *dto.TenantStatusUpdateForm) error { + return services.Super.UpdateTenantStatus(ctx.Context(), id, form) +} + +// Update Tenant Expire +// +// @Router /v1/tenants/:id [patch] +// @Summary Update Tenant Expire +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Param form body dto.TenantExpireUpdateForm true "Form" +// @Success 200 +// @Bind id path +// @Bind form body +func (s *Super) UpdateTenantExpire(ctx fiber.Ctx, id int64, form *dto.TenantExpireUpdateForm) error { + return services.Super.UpdateTenantExpire(ctx.Context(), id, form) +} + +// List Contents +// +// @Router /v1/contents [get] +// @Summary Content list +// @Tags Super +// @Accept json +// @Produce json +// @Param page query int false "Page" +// @Param limit query int false "Limit" +// @Success 200 {object} requests.Pager{items=[]dto.SuperTenantContentItem} +// @Bind page query +// @Bind limit query +func (s *Super) ListContents(ctx fiber.Ctx, page, limit int) (*requests.Pager, error) { + return services.Super.ListContents(ctx.Context(), page, limit) +} + +// Update Content Status +// +// @Router /v1/tenants/:tenantID/contents/:contentID/status [patch] +// @Summary Update Content Status +// @Tags Super +// @Accept json +// @Produce json +// @Param tenantID path int64 true "TenantID" +// @Param contentID path int64 true "ContentID" +// @Param form body dto.SuperTenantContentStatusUpdateForm true "Form" +// @Success 200 +// @Bind tenantID path +// @Bind contentID path +// @Bind form body +func (s *Super) UpdateContentStatus(ctx fiber.Ctx, tenantID, contentID int64, form *dto.SuperTenantContentStatusUpdateForm) error { + return services.Super.UpdateContentStatus(ctx.Context(), tenantID, contentID, form) +} + +// List Orders +// +// @Router /v1/orders [get] +// @Summary Order list +// @Tags Super +// @Accept json +// @Produce json +// @Param page query int false "Page" +// @Param limit query int false "Limit" +// @Success 200 {object} requests.Pager{items=[]dto.SuperOrderItem} +// @Bind page query +// @Bind limit query +func (s *Super) ListOrders(ctx fiber.Ctx, page, limit int) (*requests.Pager, error) { + return services.Super.ListOrders(ctx.Context(), page, limit) +} + +// Get Order +// +// @Router /v1/orders/:id [get] +// @Summary Get Order +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Success 200 {object} dto.SuperOrderDetail +// @Bind id path +func (s *Super) GetOrder(ctx fiber.Ctx, id int64) (*dto.SuperOrderDetail, error) { + return services.Super.GetOrder(ctx.Context(), id) +} + +// Refund Order +// +// @Router /v1/orders/:id/refund [post] +// @Summary Refund Order +// @Tags Super +// @Accept json +// @Produce json +// @Param id path int64 true "ID" +// @Param form body dto.SuperOrderRefundForm true "Form" +// @Success 200 +// @Bind id path +// @Bind form body +func (s *Super) RefundOrder(ctx fiber.Ctx, id int64, form *dto.SuperOrderRefundForm) error { + return services.Super.RefundOrder(ctx.Context(), id, form) +} + +// Order Statistics +// +// @Router /v1/orders/statistics [get] +// @Summary Order Statistics +// @Tags Super +// @Accept json +// @Produce json +// @Success 200 {object} dto.OrderStatisticsResponse +func (s *Super) OrderStatistics(ctx fiber.Ctx) (*dto.OrderStatisticsResponse, error) { + return services.Super.OrderStatistics(ctx.Context()) +} + +// User Statistics +// +// @Router /v1/users/statistics [get] +// @Summary User Statistics +// @Tags Super +// @Accept json +// @Produce json +// @Success 200 {array} dto.UserStatistics +func (s *Super) UserStatistics(ctx fiber.Ctx) ([]dto.UserStatistics, error) { + return services.Super.UserStatistics(ctx.Context()) +} + +// User Statuses +// +// @Router /v1/users/statuses [get] +// @Summary User Statuses Enum +// @Tags Super +// @Accept json +// @Produce json +// @Success 200 {array} requests.KV +func (s *Super) UserStatuses(ctx fiber.Ctx) ([]requests.KV, error) { + return services.Super.UserStatuses(ctx.Context()) +} + +// Tenant Statuses +// +// @Router /v1/tenants/statuses [get] +// @Summary Tenant Statuses Enum +// @Tags Super +// @Accept json +// @Produce json +// @Success 200 {array} requests.KV +func (s *Super) TenantStatuses(ctx fiber.Ctx) ([]requests.KV, error) { + return services.Super.TenantStatuses(ctx.Context()) +} diff --git a/backend/app/http/v1/tenant.go b/backend/app/http/v1/tenant.go new file mode 100644 index 0000000..1146272 --- /dev/null +++ b/backend/app/http/v1/tenant.go @@ -0,0 +1,56 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Tenant struct{} + +// Get tenant public profile +// +// @Router /v1/tenants/:id [get] +// @Summary Get tenant profile +// @Description Get tenant public profile +// @Tags TenantPublic +// @Accept json +// @Produce json +// @Param id path string true "Tenant ID" +// @Success 200 {object} dto.TenantProfile +// @Bind id path +func (t *Tenant) Get(ctx fiber.Ctx, id string) (*dto.TenantProfile, error) { + return services.Tenant.GetPublicProfile(ctx.Context(), id) +} + +// Follow a tenant +// +// @Router /v1/tenants/:id/follow [post] +// @Summary Follow tenant +// @Description Follow a tenant +// @Tags TenantPublic +// @Accept json +// @Produce json +// @Param id path string true "Tenant ID" +// @Success 200 {string} string "Followed" +// @Bind id path +func (t *Tenant) Follow(ctx fiber.Ctx, id string) error { + return services.Tenant.Follow(ctx.Context(), id) +} + +// Unfollow a tenant +// +// @Router /v1/tenants/:id/follow [delete] +// @Summary Unfollow tenant +// @Description Unfollow a tenant +// @Tags TenantPublic +// @Accept json +// @Produce json +// @Param id path string true "Tenant ID" +// @Success 200 {string} string "Unfollowed" +// @Bind id path +func (t *Tenant) Unfollow(ctx fiber.Ctx, id string) error { + return services.Tenant.Unfollow(ctx.Context(), id) +} diff --git a/backend/app/http/v1/transaction.go b/backend/app/http/v1/transaction.go new file mode 100644 index 0000000..6fffd7f --- /dev/null +++ b/backend/app/http/v1/transaction.go @@ -0,0 +1,58 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type Transaction struct{} + +// Create Order +// +// @Router /v1/orders [post] +// @Summary Create Order +// @Description Create Order +// @Tags Transaction +// @Accept json +// @Produce json +// @Param form body dto.OrderCreateForm true "Create form" +// @Success 200 {object} dto.OrderCreateResponse +// @Bind form body +func (t *Transaction) Create(ctx fiber.Ctx, form *dto.OrderCreateForm) (*dto.OrderCreateResponse, error) { + return services.Order.Create(ctx.Context(), form) +} + +// Pay for order +// +// @Router /v1/orders/:id/pay [post] +// @Summary Pay for order +// @Description Pay for order +// @Tags Transaction +// @Accept json +// @Produce json +// @Param id path string true "Order ID" +// @Param form body dto.OrderPayForm true "Pay form" +// @Success 200 {object} dto.OrderPayResponse +// @Bind id path +// @Bind form body +func (t *Transaction) Pay(ctx fiber.Ctx, id string, form *dto.OrderPayForm) (*dto.OrderPayResponse, error) { + return services.Order.Pay(ctx.Context(), id, form) +} + +// Check order payment status +// +// @Router /v1/orders/:id/status [get] +// @Summary Check order status +// @Description Check order payment status +// @Tags Transaction +// @Accept json +// @Produce json +// @Param id path string true "Order ID" +// @Success 200 {object} dto.OrderStatusResponse +// @Bind id path +func (t *Transaction) Status(ctx fiber.Ctx, id string) (*dto.OrderStatusResponse, error) { + return services.Order.Status(ctx.Context(), id) +} diff --git a/backend/app/http/v1/user.go b/backend/app/http/v1/user.go new file mode 100644 index 0000000..b1176e1 --- /dev/null +++ b/backend/app/http/v1/user.go @@ -0,0 +1,227 @@ +package v1 + +import ( + "quyun/v2/app/http/v1/dto" + auth_dto "quyun/v2/app/http/v1/dto" + "quyun/v2/app/services" + + "github.com/gofiber/fiber/v3" +) + +// @provider +type User struct{} + +// Get current user profile +// +// @Router /v1/me [get] +// @Summary Get user profile +// @Description Get current user profile +// @Tags UserCenter +// @Accept json +// @Produce json +// @Success 200 {object} auth_dto.User +func (u *User) Me(ctx fiber.Ctx) (*auth_dto.User, error) { + return services.User.Me(ctx.Context()) +} + +// Update user profile +// +// @Router /v1/me [put] +// @Summary Update user profile +// @Description Update user profile +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param form body dto.UserUpdate true "Update form" +// @Success 200 {string} string "Updated" +// @Bind form body +func (u *User) Update(ctx fiber.Ctx, form *dto.UserUpdate) error { + return services.User.Update(ctx.Context(), form) +} + +// Submit real-name authentication +// +// @Router /v1/me/realname [post] +// @Summary Realname auth +// @Description Submit real-name authentication +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param form body dto.RealNameForm true "Realname form" +// @Success 200 {string} string "Submitted" +// @Bind form body +func (u *User) RealName(ctx fiber.Ctx, form *dto.RealNameForm) error { + return services.User.RealName(ctx.Context(), form) +} + +// Get wallet balance and transactions +// +// @Router /v1/me/wallet [get] +// @Summary Get wallet +// @Description Get wallet balance and transactions +// @Tags UserCenter +// @Accept json +// @Produce json +// @Success 200 {object} dto.WalletResponse +func (u *User) Wallet(ctx fiber.Ctx) (*dto.WalletResponse, error) { + return services.Wallet.GetWallet(ctx.Context()) +} + +// Recharge wallet +// +// @Router /v1/me/wallet/recharge [post] +// @Summary Recharge wallet +// @Description Recharge wallet +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param form body dto.RechargeForm true "Recharge form" +// @Success 200 {object} dto.RechargeResponse +// @Bind form body +func (u *User) Recharge(ctx fiber.Ctx, form *dto.RechargeForm) (*dto.RechargeResponse, error) { + return services.Wallet.Recharge(ctx.Context(), form) +} + +// List user orders +// +// @Router /v1/me/orders [get] +// @Summary List orders +// @Description List user orders +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param status query string false "Status enum(all, unpaid, completed, refund)" +// @Success 200 {array} dto.Order +// @Bind status query +func (u *User) ListOrders(ctx fiber.Ctx, status string) ([]dto.Order, error) { + return services.Order.ListUserOrders(ctx.Context(), status) +} + +// Get user order detail +// +// @Router /v1/me/orders/:id [get] +// @Summary Get order detail +// @Description Get user order detail +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param id path string true "Order ID" +// @Success 200 {object} dto.Order +// @Bind id path +func (u *User) GetOrder(ctx fiber.Ctx, id string) (*dto.Order, error) { + return services.Order.GetUserOrder(ctx.Context(), id) +} + +// Get purchased content +// +// @Router /v1/me/library [get] +// @Summary Get library +// @Description Get purchased content +// @Tags UserCenter +// @Accept json +// @Produce json +// @Success 200 {array} dto.ContentItem +func (u *User) Library(ctx fiber.Ctx) ([]dto.ContentItem, error) { + return services.Content.GetLibrary(ctx.Context()) +} + +// Get favorites +// +// @Router /v1/me/favorites [get] +// @Summary Get favorites +// @Description Get favorites +// @Tags UserCenter +// @Accept json +// @Produce json +// @Success 200 {array} dto.ContentItem +func (u *User) Favorites(ctx fiber.Ctx) ([]dto.ContentItem, error) { + return services.Content.GetFavorites(ctx.Context()) +} + +// Add to favorites +// +// @Router /v1/me/favorites [post] +// @Summary Add favorite +// @Description Add to favorites +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param contentId query string true "Content ID" +// @Success 200 {string} string "Added" +// @Bind contentId query +func (u *User) AddFavorite(ctx fiber.Ctx, contentId string) error { + return services.Content.AddFavorite(ctx.Context(), contentId) +} + +// Remove from favorites +// +// @Router /v1/me/favorites/:contentId [delete] +// @Summary Remove favorite +// @Description Remove from favorites +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param contentId path string true "Content ID" +// @Success 200 {string} string "Removed" +// @Bind contentId path +func (u *User) RemoveFavorite(ctx fiber.Ctx, contentId string) error { + return services.Content.RemoveFavorite(ctx.Context(), contentId) +} + +// Get liked contents +// +// @Router /v1/me/likes [get] +// @Summary Get likes +// @Description Get liked contents +// @Tags UserCenter +// @Accept json +// @Produce json +// @Success 200 {array} dto.ContentItem +func (u *User) Likes(ctx fiber.Ctx) ([]dto.ContentItem, error) { + return services.Content.GetLikes(ctx.Context()) +} + +// Like content +// +// @Router /v1/me/likes [post] +// @Summary Like content +// @Description Like content +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param contentId query string true "Content ID" +// @Success 200 {string} string "Liked" +// @Bind contentId query +func (u *User) AddLike(ctx fiber.Ctx, contentId string) error { + return services.Content.AddLike(ctx.Context(), contentId) +} + +// Unlike content +// +// @Router /v1/me/likes/:contentId [delete] +// @Summary Unlike content +// @Description Unlike content +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param contentId path string true "Content ID" +// @Success 200 {string} string "Unliked" +// @Bind contentId path +func (u *User) RemoveLike(ctx fiber.Ctx, contentId string) error { + return services.Content.RemoveLike(ctx.Context(), contentId) +} + +// Get notifications +// +// @Router /v1/me/notifications [get] +// @Summary Get notifications +// @Description Get notifications +// @Tags UserCenter +// @Accept json +// @Produce json +// @Param type query string false "Type enum(all, system, order, audit, interaction)" +// @Success 200 {array} dto.Notification +// @Bind typeArg query key(type) +func (u *User) Notifications(ctx fiber.Ctx, typeArg string) ([]dto.Notification, error) { + return services.User.GetNotifications(ctx.Context(), typeArg) +} diff --git a/backend/app/http/web/dto/auth.go b/backend/app/http/web/dto/auth.go deleted file mode 100644 index 6085554..0000000 --- a/backend/app/http/web/dto/auth.go +++ /dev/null @@ -1,28 +0,0 @@ -package dto - -// LoginForm 平台侧用户登录表单(用于获取 JWT 访问凭证)。 -// 注意:此登录是“用户身份”登录(非超级管理员),用于进入租户管理后台前的身份校验与租户列表查询。 -type LoginForm struct { - // Username 用户名;必须与数据库 users.username 精确匹配。 - Username string `json:"username,omitempty"` - // Password 明文密码;后端会与 users.password 的 bcrypt hash 做比对。 - Password string `json:"password,omitempty"` -} - -// RegisterForm 平台侧用户注册表单(用于创建用户并获取 JWT 访问凭证)。 -type RegisterForm struct { - // Username 用户名;需全局唯一(users.username);建议仅允许字母/数字/下划线,且长度在合理范围内。 - Username string `json:"username,omitempty"` - // Password 明文密码;后端会在创建用户时自动加密(bcrypt)。 - Password string `json:"password,omitempty"` - // ConfirmPassword 确认密码;必须与 Password 一致,避免误输入导致无法登录。 - ConfirmPassword string `json:"confirmPassword,omitempty"` - // VerifyCode 验证码(预留字段);当前版本仅透传/占位,不做后端校验。 - VerifyCode string `json:"verifyCode,omitempty"` -} - -// LoginResponse 登录响应。 -type LoginResponse struct { - // Token JWT 访问令牌;前端应以 `Authorization: Bearer ` 方式携带。 - Token string `json:"token"` -} diff --git a/backend/app/http/web/dto/me.go b/backend/app/http/web/dto/me.go deleted file mode 100644 index bb8d895..0000000 --- a/backend/app/http/web/dto/me.go +++ /dev/null @@ -1,51 +0,0 @@ -package dto - -import ( - "time" - - "quyun/v2/pkg/consts" - - "go.ipao.vip/gen/types" -) - -// MeResponse 当前登录用户信息(脱敏)。 -type MeResponse struct { - // ID 用户ID(全局唯一)。 - ID int64 `json:"id"` - // Username 用户名。 - Username string `json:"username"` - // Roles 用户全局角色数组(如 user/super_admin 等)。 - Roles types.Array[consts.Role] `json:"roles"` - // Status 用户状态(active/verified/banned 等)。 - Status consts.UserStatus `json:"status"` - // StatusDescription 用户状态描述(便于前端展示)。 - StatusDescription string `json:"status_description"` - // CreatedAt 用户创建时间。 - CreatedAt time.Time `json:"created_at"` - // UpdatedAt 用户更新时间。 - UpdatedAt time.Time `json:"updated_at"` -} - -// MyTenantItem 当前用户可进入的租户条目(用于“选择租户进入后台”页面)。 -type MyTenantItem struct { - // TenantID 租户ID(数值型主键)。 - TenantID int64 `json:"tenant_id"` - // TenantCode 租户Code(路由使用:/t/:tenantCode/...)。 - TenantCode string `json:"tenant_code"` - // TenantName 租户名称。 - TenantName string `json:"tenant_name"` - // TenantStatus 租户状态(pending/verified/expired 等)。 - TenantStatus consts.TenantStatus `json:"tenant_status"` - // TenantStatusDescription 租户状态描述(便于前端展示)。 - TenantStatusDescription string `json:"tenant_status_description"` - - // IsOwner 是否为租户Owner(tenants.user_id == 当前用户)。 - // 说明:Owner 通常也在 tenant_users 里具备 tenant_admin 角色,但此字段更直观。 - IsOwner bool `json:"is_owner"` - // MemberRoles 当前用户在该租户下的角色(tenant_admin/member 等)。 - MemberRoles types.Array[consts.TenantUserRole] `json:"member_roles"` - // MemberStatus 当前用户在该租户下的成员状态。 - MemberStatus consts.UserStatus `json:"member_status"` - // JoinedAt 加入租户时间(tenant_users.created_at)。 - JoinedAt time.Time `json:"joined_at"` -} diff --git a/backend/app/http/web/dto/password_reset.go b/backend/app/http/web/dto/password_reset.go deleted file mode 100644 index 1c0a7e0..0000000 --- a/backend/app/http/web/dto/password_reset.go +++ /dev/null @@ -1,45 +0,0 @@ -package dto - -// PasswordResetSendSMSForm 找回密码:发送短信验证码表单。 -type PasswordResetSendSMSForm struct { - // Phone 手机号;当前版本将其作为用户名使用(users.username)。 - Phone string `json:"phone,omitempty"` -} - -// PasswordResetSendSMSResponse 找回密码:发送短信验证码响应。 -type PasswordResetSendSMSResponse struct { - // NextSendSeconds 下次可发送剩余秒数(用于前端 60s 倒计时)。 - NextSendSeconds int `json:"nextSendSeconds"` - // Code 验证码(预留:当前用于前端弹窗展示;正式接入短信后应移除/仅在开发环境返回)。 - Code string `json:"code,omitempty"` -} - -// PasswordResetVerifyForm 找回密码:验证码校验表单。 -type PasswordResetVerifyForm struct { - // Phone 手机号。 - Phone string `json:"phone,omitempty"` - // Code 短信验证码。 - Code string `json:"code,omitempty"` -} - -// PasswordResetVerifyResponse 找回密码:验证码校验响应。 -type PasswordResetVerifyResponse struct { - // ResetToken 重置令牌;验证码校验通过后,用该令牌提交新密码。 - ResetToken string `json:"resetToken"` -} - -// PasswordResetForm 找回密码:重置密码表单。 -type PasswordResetForm struct { - // ResetToken 重置令牌;由验证码校验接口返回。 - ResetToken string `json:"resetToken,omitempty"` - // Password 新密码(明文)。 - Password string `json:"password,omitempty"` - // ConfirmPassword 确认新密码;必须与 Password 一致。 - ConfirmPassword string `json:"confirmPassword,omitempty"` -} - -// PasswordResetResponse 找回密码:重置密码响应。 -type PasswordResetResponse struct { - // Ok 是否成功。 - Ok bool `json:"ok"` -} diff --git a/backend/app/http/web/dto/tenant_apply.go b/backend/app/http/web/dto/tenant_apply.go deleted file mode 100644 index ab1b872..0000000 --- a/backend/app/http/web/dto/tenant_apply.go +++ /dev/null @@ -1,33 +0,0 @@ -package dto - -import ( - "time" - - "quyun/v2/pkg/consts" -) - -// TenantApplyForm 申请创作者(创建租户申请)表单。 -type TenantApplyForm struct { - // Code 租户 ID(用于 URL/系统标识);全局唯一(tenants.code,忽略大小写)。 - Code string `json:"code,omitempty"` - // Name 租户名称(展示用)。 - Name string `json:"name,omitempty"` -} - -// TenantApplicationResponse 当前用户的租户申请信息(申请创作者)。 -type TenantApplicationResponse struct { - // HasApplication 是否已提交过申请(或已成为创作者)。 - HasApplication bool `json:"hasApplication"` - // TenantID 租户ID。 - TenantID int64 `json:"tenantId,omitempty"` - // TenantCode 租户 Code。 - TenantCode string `json:"tenantCode,omitempty"` - // TenantName 租户名称。 - TenantName string `json:"tenantName,omitempty"` - // Status 租户状态(pending_verify/verified/banned)。 - Status consts.TenantStatus `json:"status,omitempty"` - // StatusDescription 状态描述(便于前端展示)。 - StatusDescription string `json:"statusDescription,omitempty"` - // CreatedAt 申请创建时间(租户记录创建时间)。 - CreatedAt time.Time `json:"createdAt,omitempty"` -} diff --git a/backend/app/http/web/provider.gen.go b/backend/app/http/web/provider.gen.go deleted file mode 100755 index 72f2948..0000000 --- a/backend/app/http/web/provider.gen.go +++ /dev/null @@ -1,9 +0,0 @@ -package web - -import ( - "go.ipao.vip/atom/opt" -) - -func Provide(opts ...opt.Option) error { - return nil -} diff --git a/backend/app/services/common.go b/backend/app/services/common.go new file mode 100644 index 0000000..3ae390e --- /dev/null +++ b/backend/app/services/common.go @@ -0,0 +1,15 @@ +package services + +import ( + "context" + "mime/multipart" + + common_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type common struct{} + +func (s *common) Upload(ctx context.Context, file *multipart.FileHeader, typeArg string) (*common_dto.UploadResult, error) { + return &common_dto.UploadResult{}, nil +} diff --git a/backend/app/services/content.go b/backend/app/services/content.go new file mode 100644 index 0000000..15fda72 --- /dev/null +++ b/backend/app/services/content.go @@ -0,0 +1,63 @@ +package services + +import ( + "context" + + content_dto "quyun/v2/app/http/v1/dto" + user_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type content struct{} + +func (s *content) List(ctx context.Context, keyword, genre, tenantId, sort string, page int) (*content_dto.ContentListResponse, error) { + return &content_dto.ContentListResponse{}, nil +} + +func (s *content) Get(ctx context.Context, id string) (*content_dto.ContentDetail, error) { + return &content_dto.ContentDetail{}, nil +} + +func (s *content) ListComments(ctx context.Context, id string, page int) (*content_dto.CommentListResponse, error) { + return &content_dto.CommentListResponse{}, nil +} + +func (s *content) CreateComment(ctx context.Context, id string, form *content_dto.CommentCreateForm) error { + return nil +} + +func (s *content) LikeComment(ctx context.Context, id string) error { + return nil +} + +func (s *content) GetLibrary(ctx context.Context) ([]user_dto.ContentItem, error) { + return []user_dto.ContentItem{}, nil +} + +func (s *content) GetFavorites(ctx context.Context) ([]user_dto.ContentItem, error) { + return []user_dto.ContentItem{}, nil +} + +func (s *content) AddFavorite(ctx context.Context, contentId string) error { + return nil +} + +func (s *content) RemoveFavorite(ctx context.Context, contentId string) error { + return nil +} + +func (s *content) GetLikes(ctx context.Context) ([]user_dto.ContentItem, error) { + return []user_dto.ContentItem{}, nil +} + +func (s *content) AddLike(ctx context.Context, contentId string) error { + return nil +} + +func (s *content) RemoveLike(ctx context.Context, contentId string) error { + return nil +} + +func (s *content) ListTopics(ctx context.Context) ([]content_dto.Topic, error) { + return []content_dto.Topic{}, nil +} diff --git a/backend/app/services/creator.go b/backend/app/services/creator.go new file mode 100644 index 0000000..f655b2f --- /dev/null +++ b/backend/app/services/creator.go @@ -0,0 +1,66 @@ +package services + +import ( + "context" + + creator_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type creator struct{} + +func (s *creator) Apply(ctx context.Context, form *creator_dto.ApplyForm) error { + return nil +} + +func (s *creator) Dashboard(ctx context.Context) (*creator_dto.DashboardStats, error) { + return &creator_dto.DashboardStats{}, nil +} + +func (s *creator) ListContents(ctx context.Context, status, genre, keyword string) ([]creator_dto.ContentItem, error) { + return []creator_dto.ContentItem{}, nil +} + +func (s *creator) CreateContent(ctx context.Context, form *creator_dto.ContentCreateForm) error { + return nil +} + +func (s *creator) UpdateContent(ctx context.Context, id string, form *creator_dto.ContentUpdateForm) error { + return nil +} + +func (s *creator) DeleteContent(ctx context.Context, id string) error { + return nil +} + +func (s *creator) ListOrders(ctx context.Context, status, keyword string) ([]creator_dto.Order, error) { + return []creator_dto.Order{}, nil +} + +func (s *creator) ProcessRefund(ctx context.Context, id string, form *creator_dto.RefundForm) error { + return nil +} + +func (s *creator) GetSettings(ctx context.Context) (*creator_dto.Settings, error) { + return &creator_dto.Settings{}, nil +} + +func (s *creator) UpdateSettings(ctx context.Context, form *creator_dto.Settings) error { + return nil +} + +func (s *creator) ListPayoutAccounts(ctx context.Context) ([]creator_dto.PayoutAccount, error) { + return []creator_dto.PayoutAccount{}, nil +} + +func (s *creator) AddPayoutAccount(ctx context.Context, form *creator_dto.PayoutAccount) error { + return nil +} + +func (s *creator) RemovePayoutAccount(ctx context.Context, id string) error { + return nil +} + +func (s *creator) Withdraw(ctx context.Context, form *creator_dto.WithdrawForm) error { + return nil +} diff --git a/backend/app/services/order.go b/backend/app/services/order.go new file mode 100644 index 0000000..bfd985b --- /dev/null +++ b/backend/app/services/order.go @@ -0,0 +1,31 @@ +package services + +import ( + "context" + + transaction_dto "quyun/v2/app/http/v1/dto" + user_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type order struct{} + +func (s *order) ListUserOrders(ctx context.Context, status string) ([]user_dto.Order, error) { + return []user_dto.Order{}, nil +} + +func (s *order) GetUserOrder(ctx context.Context, id string) (*user_dto.Order, error) { + return &user_dto.Order{}, nil +} + +func (s *order) Create(ctx context.Context, form *transaction_dto.OrderCreateForm) (*transaction_dto.OrderCreateResponse, error) { + return &transaction_dto.OrderCreateResponse{}, nil +} + +func (s *order) Pay(ctx context.Context, id string, form *transaction_dto.OrderPayForm) (*transaction_dto.OrderPayResponse, error) { + return &transaction_dto.OrderPayResponse{}, nil +} + +func (s *order) Status(ctx context.Context, id string) (*transaction_dto.OrderStatusResponse, error) { + return &transaction_dto.OrderStatusResponse{}, nil +} diff --git a/backend/app/services/provider.gen.go b/backend/app/services/provider.gen.go index f3328aa..54a4c8a 100755 --- a/backend/app/services/provider.gen.go +++ b/backend/app/services/provider.gen.go @@ -1,9 +1,99 @@ package services import ( + "go.ipao.vip/atom" + "go.ipao.vip/atom/container" + "go.ipao.vip/atom/contracts" "go.ipao.vip/atom/opt" + "gorm.io/gorm" ) func Provide(opts ...opt.Option) error { + if err := container.Container.Provide(func() (*common, error) { + obj := &common{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*content, error) { + obj := &content{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*creator, error) { + obj := &creator{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*order, error) { + obj := &order{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func( + common *common, + content *content, + creator *creator, + db *gorm.DB, + order *order, + super *super, + tenant *tenant, + user *user, + wallet *wallet, + ) (contracts.Initial, error) { + obj := &services{ + common: common, + content: content, + creator: creator, + db: db, + order: order, + super: super, + tenant: tenant, + user: user, + wallet: wallet, + } + if err := obj.Prepare(); err != nil { + return nil, err + } + + return obj, nil + }, atom.GroupInitial); err != nil { + return err + } + if err := container.Container.Provide(func() (*super, error) { + obj := &super{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*tenant, error) { + obj := &tenant{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*user, error) { + obj := &user{} + + return obj, nil + }); err != nil { + return err + } + if err := container.Container.Provide(func() (*wallet, error) { + obj := &wallet{} + + return obj, nil + }); err != nil { + return err + } return nil } diff --git a/backend/app/services/services.gen.go b/backend/app/services/services.gen.go new file mode 100644 index 0000000..30c4868 --- /dev/null +++ b/backend/app/services/services.gen.go @@ -0,0 +1,49 @@ +package services + +import ( + "gorm.io/gorm" +) + +var _db *gorm.DB + +// exported CamelCase Services +var ( + Common *common + Content *content + Creator *creator + Order *order + Super *super + Tenant *tenant + User *user + Wallet *wallet +) + +// @provider(model) +type services struct { + db *gorm.DB + // define Services + common *common + content *content + creator *creator + order *order + super *super + tenant *tenant + user *user + wallet *wallet +} + +func (svc *services) Prepare() error { + _db = svc.db + + // set exported Services here + Common = svc.common + Content = svc.content + Creator = svc.creator + Order = svc.order + Super = svc.super + Tenant = svc.tenant + User = svc.user + Wallet = svc.wallet + + return nil +} diff --git a/backend/app/services/super.go b/backend/app/services/super.go new file mode 100644 index 0000000..7b38ec3 --- /dev/null +++ b/backend/app/services/super.go @@ -0,0 +1,91 @@ +package services + +import ( + "context" + + super_dto "quyun/v2/app/http/v1/dto" + "quyun/v2/app/requests" +) + +// @provider +type super struct{} + +func (s *super) Login(ctx context.Context, form *super_dto.LoginForm) (*super_dto.LoginResponse, error) { + return &super_dto.LoginResponse{}, nil +} + +func (s *super) CheckToken(ctx context.Context) (*super_dto.LoginResponse, error) { + return &super_dto.LoginResponse{}, nil +} + +func (s *super) ListUsers(ctx context.Context, page, limit int, username string) (*requests.Pager, error) { + return &requests.Pager{}, nil +} + +func (s *super) GetUser(ctx context.Context, id int64) (*super_dto.UserItem, error) { + return &super_dto.UserItem{}, nil +} + +func (s *super) UpdateUserStatus(ctx context.Context, id int64, form *super_dto.UserStatusUpdateForm) error { + return nil +} + +func (s *super) UpdateUserRoles(ctx context.Context, id int64, form *super_dto.UserRolesUpdateForm) error { + return nil +} + +func (s *super) ListTenants(ctx context.Context, page, limit int, name string) (*requests.Pager, error) { + return &requests.Pager{}, nil +} + +func (s *super) CreateTenant(ctx context.Context, form *super_dto.TenantCreateForm) error { + return nil +} + +func (s *super) GetTenant(ctx context.Context, id int64) (*super_dto.TenantItem, error) { + return &super_dto.TenantItem{}, nil +} + +func (s *super) UpdateTenantStatus(ctx context.Context, id int64, form *super_dto.TenantStatusUpdateForm) error { + return nil +} + +func (s *super) UpdateTenantExpire(ctx context.Context, id int64, form *super_dto.TenantExpireUpdateForm) error { + return nil +} + +func (s *super) ListContents(ctx context.Context, page, limit int) (*requests.Pager, error) { + return &requests.Pager{}, nil +} + +func (s *super) UpdateContentStatus(ctx context.Context, tenantID, contentID int64, form *super_dto.SuperTenantContentStatusUpdateForm) error { + return nil +} + +func (s *super) ListOrders(ctx context.Context, page, limit int) (*requests.Pager, error) { + return &requests.Pager{}, nil +} + +func (s *super) GetOrder(ctx context.Context, id int64) (*super_dto.SuperOrderDetail, error) { + return &super_dto.SuperOrderDetail{}, nil +} + +func (s *super) RefundOrder(ctx context.Context, id int64, form *super_dto.SuperOrderRefundForm) error { + return nil +} + +func (s *super) OrderStatistics(ctx context.Context) (*super_dto.OrderStatisticsResponse, error) { + return &super_dto.OrderStatisticsResponse{}, nil +} + +func (s *super) UserStatistics(ctx context.Context) ([]super_dto.UserStatistics, error) { + return []super_dto.UserStatistics{}, nil +} + +func (s *super) UserStatuses(ctx context.Context) ([]requests.KV, error) { + return []requests.KV{}, nil +} + +func (s *super) TenantStatuses(ctx context.Context) ([]requests.KV, error) { + return []requests.KV{}, nil +} diff --git a/backend/app/services/tenant.go b/backend/app/services/tenant.go new file mode 100644 index 0000000..a093924 --- /dev/null +++ b/backend/app/services/tenant.go @@ -0,0 +1,22 @@ +package services + +import ( + "context" + + tenant_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type tenant struct{} + +func (s *tenant) GetPublicProfile(ctx context.Context, id string) (*tenant_dto.TenantProfile, error) { + return &tenant_dto.TenantProfile{}, nil +} + +func (s *tenant) Follow(ctx context.Context, id string) error { + return nil +} + +func (s *tenant) Unfollow(ctx context.Context, id string) error { + return nil +} diff --git a/backend/app/services/user.go b/backend/app/services/user.go new file mode 100644 index 0000000..ae6cbc6 --- /dev/null +++ b/backend/app/services/user.go @@ -0,0 +1,35 @@ +package services + +import ( + "context" + + auth_dto "quyun/v2/app/http/v1/dto" + user_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type user struct{} + +func (s *user) SendOTP(ctx context.Context, phone string) error { + return nil +} + +func (s *user) LoginWithOTP(ctx context.Context, phone, otp string) (*auth_dto.LoginResponse, error) { + return &auth_dto.LoginResponse{}, nil +} + +func (s *user) Me(ctx context.Context) (*auth_dto.User, error) { + return &auth_dto.User{}, nil +} + +func (s *user) Update(ctx context.Context, form *user_dto.UserUpdate) error { + return nil +} + +func (s *user) RealName(ctx context.Context, form *user_dto.RealNameForm) error { + return nil +} + +func (s *user) GetNotifications(ctx context.Context, typeArg string) ([]user_dto.Notification, error) { + return []user_dto.Notification{}, nil +} diff --git a/backend/app/services/wallet.go b/backend/app/services/wallet.go new file mode 100644 index 0000000..2070d86 --- /dev/null +++ b/backend/app/services/wallet.go @@ -0,0 +1,18 @@ +package services + +import ( + "context" + + user_dto "quyun/v2/app/http/v1/dto" +) + +// @provider +type wallet struct{} + +func (s *wallet) GetWallet(ctx context.Context) (*user_dto.WalletResponse, error) { + return &user_dto.WalletResponse{}, nil +} + +func (s *wallet) Recharge(ctx context.Context, form *user_dto.RechargeForm) (*user_dto.RechargeResponse, error) { + return &user_dto.RechargeResponse{}, nil +} diff --git a/backend/database/migrations/20251227120000_add_api_support.sql b/backend/database/migrations/20251227120000_add_api_support.sql new file mode 100644 index 0000000..7fab69b --- /dev/null +++ b/backend/database/migrations/20251227120000_add_api_support.sql @@ -0,0 +1,298 @@ +-- +goose Up +-- Users +CREATE TABLE IF NOT EXISTS users ( + id BIGSERIAL PRIMARY KEY, + username VARCHAR(255) NOT NULL UNIQUE, + password VARCHAR(255) NOT NULL, + roles TEXT[] DEFAULT '{user}', + status VARCHAR(50) DEFAULT 'active', + metas JSONB DEFAULT '{}', + balance BIGINT DEFAULT 0, + balance_frozen BIGINT DEFAULT 0, + verified_at TIMESTAMP WITH TIME ZONE, + + -- New fields + nickname VARCHAR(255) DEFAULT '', + avatar VARCHAR(512) DEFAULT '', + gender VARCHAR(32) DEFAULT 'secret', + bio VARCHAR(512) DEFAULT '', + birthday DATE, + location JSONB DEFAULT '{}', + points BIGINT DEFAULT 0, + phone VARCHAR(32) DEFAULT '', + is_real_name_verified BOOLEAN DEFAULT FALSE, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + deleted_at TIMESTAMP WITH TIME ZONE +); + +-- Tenants +CREATE TABLE IF NOT EXISTS tenants ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + code VARCHAR(64) NOT NULL UNIQUE, + uuid UUID NOT NULL, + name VARCHAR(128) NOT NULL, + status VARCHAR(64) NOT NULL, + config JSONB DEFAULT '{}', + expired_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_tenants_user_id ON tenants(user_id); + +-- TenantUsers +CREATE TABLE IF NOT EXISTS tenant_users ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + role TEXT[] DEFAULT '{member}', + status VARCHAR(50) DEFAULT 'verified', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + UNIQUE(tenant_id, user_id) +); + +-- Contents +CREATE TABLE IF NOT EXISTS contents ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + title VARCHAR(255) NOT NULL, + description TEXT NOT NULL, + status VARCHAR(32) DEFAULT 'draft', + visibility VARCHAR(32) DEFAULT 'tenant_only', + preview_seconds INT DEFAULT 60, + preview_downloadable BOOLEAN DEFAULT FALSE, + published_at TIMESTAMP WITH TIME ZONE, + summary VARCHAR(256) DEFAULT '', + tags JSONB DEFAULT '[]', + + -- New fields + body TEXT DEFAULT '', + genre VARCHAR(64) DEFAULT '', + views INT DEFAULT 0, + likes INT DEFAULT 0, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + deleted_at TIMESTAMP WITH TIME ZONE +); +CREATE INDEX IF NOT EXISTS idx_contents_tenant_id ON contents(tenant_id); + +-- MediaAssets +CREATE TABLE IF NOT EXISTS media_assets ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + type VARCHAR(32) DEFAULT 'video', + status VARCHAR(32) DEFAULT 'uploaded', + provider VARCHAR(64) NOT NULL, + bucket VARCHAR(128) NOT NULL, + object_key VARCHAR(512) NOT NULL, + meta JSONB DEFAULT '{}', + variant VARCHAR(32) DEFAULT 'main', + source_asset_id BIGINT DEFAULT 0, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + deleted_at TIMESTAMP WITH TIME ZONE +); + +-- ContentAssets +CREATE TABLE IF NOT EXISTS content_assets ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content_id BIGINT NOT NULL, + asset_id BIGINT NOT NULL, + role VARCHAR(32) DEFAULT 'main', + sort INT DEFAULT 0, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- ContentPrices +CREATE TABLE IF NOT EXISTS content_prices ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content_id BIGINT NOT NULL, + currency VARCHAR(16) DEFAULT 'CNY', + price_amount BIGINT NOT NULL, + discount_type VARCHAR(16) DEFAULT 'none', + discount_value BIGINT DEFAULT 0, + discount_start_at TIMESTAMP WITH TIME ZONE, + discount_end_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + UNIQUE(tenant_id, content_id) +); + +-- ContentAccess +CREATE TABLE IF NOT EXISTS content_access ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content_id BIGINT NOT NULL, + order_id BIGINT DEFAULT 0, + status VARCHAR(16) DEFAULT 'active', + revoked_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + UNIQUE(tenant_id, user_id, content_id) +); + +-- Orders +CREATE TABLE IF NOT EXISTS orders ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + type VARCHAR(32) DEFAULT 'content_purchase', + status VARCHAR(32) DEFAULT 'created', + currency VARCHAR(16) DEFAULT 'CNY', + amount_original BIGINT NOT NULL, + amount_discount BIGINT NOT NULL, + amount_paid BIGINT NOT NULL, + snapshot JSONB DEFAULT '{}', + idempotency_key VARCHAR(128) NOT NULL, + paid_at TIMESTAMP WITH TIME ZONE, + refunded_at TIMESTAMP WITH TIME ZONE, + refund_forced BOOLEAN DEFAULT FALSE, + refund_operator_user_id BIGINT DEFAULT 0, + refund_reason VARCHAR(255) DEFAULT '', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- OrderItems +CREATE TABLE IF NOT EXISTS order_items ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + order_id BIGINT NOT NULL, + content_id BIGINT NOT NULL, + content_user_id BIGINT NOT NULL, + amount_paid BIGINT NOT NULL, + snapshot JSONB DEFAULT '{}', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- TenantLedgers +CREATE TABLE IF NOT EXISTS tenant_ledgers ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + order_id BIGINT DEFAULT 0, + type VARCHAR(32) NOT NULL, + amount BIGINT NOT NULL, + balance_before BIGINT NOT NULL, + balance_after BIGINT NOT NULL, + frozen_before BIGINT NOT NULL, + frozen_after BIGINT NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + remark VARCHAR(255) NOT NULL, + operator_user_id BIGINT DEFAULT 0, + biz_ref_type VARCHAR(32) DEFAULT '', + biz_ref_id BIGINT DEFAULT 0, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- TenantInvites +CREATE TABLE IF NOT EXISTS tenant_invites ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + code VARCHAR(64) NOT NULL, + status VARCHAR(32) DEFAULT 'active', + max_uses INT NOT NULL, + used_count INT DEFAULT 0, + expires_at TIMESTAMP WITH TIME ZONE, + disabled_at TIMESTAMP WITH TIME ZONE, + disabled_operator_user_id BIGINT DEFAULT 0, + remark VARCHAR(255) DEFAULT '', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- TenantJoinRequests +CREATE TABLE IF NOT EXISTS tenant_join_requests ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + status VARCHAR(32) DEFAULT 'pending', + reason VARCHAR(255) NOT NULL, + decided_at TIMESTAMP WITH TIME ZONE, + decided_operator_user_id BIGINT DEFAULT 0, + decided_reason VARCHAR(255) DEFAULT '', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Comments +CREATE TABLE IF NOT EXISTS comments ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content_id BIGINT NOT NULL, + reply_to BIGINT DEFAULT 0, + content TEXT NOT NULL, + likes INT DEFAULT 0, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + deleted_at TIMESTAMP WITH TIME ZONE +); +CREATE INDEX IF NOT EXISTS idx_comments_content_id ON comments(content_id); +CREATE INDEX IF NOT EXISTS idx_comments_user_id ON comments(user_id); + +-- User Content Actions (Like, Favorite) +CREATE TABLE IF NOT EXISTS user_content_actions ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + content_id BIGINT NOT NULL, + type VARCHAR(32) NOT NULL, -- like, favorite + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + UNIQUE(user_id, content_id, type) +); + +-- User Comment Actions (Like) +CREATE TABLE IF NOT EXISTS user_comment_actions ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + comment_id BIGINT NOT NULL, + type VARCHAR(32) NOT NULL, -- like + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + UNIQUE(user_id, comment_id, type) +); + +-- Payout Accounts +CREATE TABLE IF NOT EXISTS payout_accounts ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, -- Associated with a creator tenant + user_id BIGINT NOT NULL, -- Creator user + type VARCHAR(32) NOT NULL, -- bank, alipay + name VARCHAR(128) NOT NULL, + account VARCHAR(128) NOT NULL, + realname VARCHAR(128) NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_payout_accounts_tenant_id ON payout_accounts(tenant_id); + +-- Notifications +CREATE TABLE IF NOT EXISTS notifications ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + tenant_id BIGINT DEFAULT 0, -- Optional source tenant + type VARCHAR(32) NOT NULL, -- system, order, audit, interaction + title VARCHAR(255) NOT NULL, + content TEXT NOT NULL, + is_read BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id); + +-- +goose Down +-- Revert logic omitted for dev speed in this context \ No newline at end of file diff --git a/backend/database/models/comments.gen.go b/backend/database/models/comments.gen.go new file mode 100644 index 0000000..50736e7 --- /dev/null +++ b/backend/database/models/comments.gen.go @@ -0,0 +1,66 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "gorm.io/gorm" +) + +const TableNameComment = "comments" + +// Comment mapped from table +type Comment struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + ReplyTo int64 `gorm:"column:reply_to;type:bigint" json:"reply_to"` + Content string `gorm:"column:content;type:text;not null" json:"content"` + Likes int32 `gorm:"column:likes;type:integer" json:"likes"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Comment) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Comment) Save(ctx context.Context) error { return Q.Comment.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *Comment) Create(ctx context.Context) error { return Q.Comment.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *Comment) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Comment) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).Unscoped().Delete(m) +} + +// Restore sets deleted_at to NULL for this model's primary key using the default DB. +func (m *Comment) Restore(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).RestoreByID(m.ID) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Comment) Reload(ctx context.Context) error { + fresh, err := Q.Comment.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/comments.query.gen.go b/backend/database/models/comments.query.gen.go new file mode 100644 index 0000000..3eaa50f --- /dev/null +++ b/backend/database/models/comments.query.gen.go @@ -0,0 +1,510 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newComment(db *gorm.DB, opts ...gen.DOOption) commentQuery { + _commentQuery := commentQuery{} + + _commentQuery.commentQueryDo.UseDB(db, opts...) + _commentQuery.commentQueryDo.UseModel(&Comment{}) + + tableName := _commentQuery.commentQueryDo.TableName() + _commentQuery.ALL = field.NewAsterisk(tableName) + _commentQuery.ID = field.NewInt64(tableName, "id") + _commentQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _commentQuery.UserID = field.NewInt64(tableName, "user_id") + _commentQuery.ContentID = field.NewInt64(tableName, "content_id") + _commentQuery.ReplyTo = field.NewInt64(tableName, "reply_to") + _commentQuery.Content = field.NewString(tableName, "content") + _commentQuery.Likes = field.NewInt32(tableName, "likes") + _commentQuery.CreatedAt = field.NewTime(tableName, "created_at") + _commentQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _commentQuery.DeletedAt = field.NewField(tableName, "deleted_at") + + _commentQuery.fillFieldMap() + + return _commentQuery +} + +type commentQuery struct { + commentQueryDo commentQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + ReplyTo field.Int64 + Content field.String + Likes field.Int32 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + + fieldMap map[string]field.Expr +} + +func (c commentQuery) Table(newTableName string) *commentQuery { + c.commentQueryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c commentQuery) As(alias string) *commentQuery { + c.commentQueryDo.DO = *(c.commentQueryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *commentQuery) updateTableName(table string) *commentQuery { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.TenantID = field.NewInt64(table, "tenant_id") + c.UserID = field.NewInt64(table, "user_id") + c.ContentID = field.NewInt64(table, "content_id") + c.ReplyTo = field.NewInt64(table, "reply_to") + c.Content = field.NewString(table, "content") + c.Likes = field.NewInt32(table, "likes") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + + c.fillFieldMap() + + return c +} + +func (c *commentQuery) QueryContext(ctx context.Context) (*commentQuery, *commentQueryDo) { + return c, c.commentQueryDo.WithContext(ctx) +} + +func (c *commentQuery) WithContext(ctx context.Context) *commentQueryDo { + return c.commentQueryDo.WithContext(ctx) +} + +func (c commentQuery) TableName() string { return c.commentQueryDo.TableName() } + +func (c commentQuery) Alias() string { return c.commentQueryDo.Alias() } + +func (c commentQuery) Columns(cols ...field.Expr) gen.Columns { + return c.commentQueryDo.Columns(cols...) +} + +func (c *commentQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *commentQuery) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 10) + c.fieldMap["id"] = c.ID + c.fieldMap["tenant_id"] = c.TenantID + c.fieldMap["user_id"] = c.UserID + c.fieldMap["content_id"] = c.ContentID + c.fieldMap["reply_to"] = c.ReplyTo + c.fieldMap["content"] = c.Content + c.fieldMap["likes"] = c.Likes + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt +} + +func (c commentQuery) clone(db *gorm.DB) commentQuery { + c.commentQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c commentQuery) replaceDB(db *gorm.DB) commentQuery { + c.commentQueryDo.ReplaceDB(db) + return c +} + +type commentQueryDo struct{ gen.DO } + +func (c commentQueryDo) Debug() *commentQueryDo { + return c.withDO(c.DO.Debug()) +} + +func (c commentQueryDo) WithContext(ctx context.Context) *commentQueryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c commentQueryDo) ReadDB() *commentQueryDo { + return c.Clauses(dbresolver.Read) +} + +func (c commentQueryDo) WriteDB() *commentQueryDo { + return c.Clauses(dbresolver.Write) +} + +func (c commentQueryDo) Session(config *gorm.Session) *commentQueryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c commentQueryDo) Clauses(conds ...clause.Expression) *commentQueryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c commentQueryDo) Returning(value interface{}, columns ...string) *commentQueryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c commentQueryDo) Not(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c commentQueryDo) Or(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c commentQueryDo) Select(conds ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c commentQueryDo) Where(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c commentQueryDo) Order(conds ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c commentQueryDo) Distinct(cols ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c commentQueryDo) Omit(cols ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c commentQueryDo) Join(table schema.Tabler, on ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c commentQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c commentQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c commentQueryDo) Group(cols ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c commentQueryDo) Having(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c commentQueryDo) Limit(limit int) *commentQueryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c commentQueryDo) Offset(offset int) *commentQueryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c commentQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *commentQueryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c commentQueryDo) Unscoped() *commentQueryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c commentQueryDo) Create(values ...*Comment) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c commentQueryDo) CreateInBatches(values []*Comment, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c commentQueryDo) Save(values ...*Comment) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c commentQueryDo) First() (*Comment, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) Take() (*Comment, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) Last() (*Comment, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) Find() ([]*Comment, error) { + result, err := c.DO.Find() + return result.([]*Comment), err +} + +func (c commentQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Comment, err error) { + buf := make([]*Comment, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c commentQueryDo) FindInBatches(result *[]*Comment, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c commentQueryDo) Attrs(attrs ...field.AssignExpr) *commentQueryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c commentQueryDo) Assign(attrs ...field.AssignExpr) *commentQueryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c commentQueryDo) Joins(fields ...field.RelationField) *commentQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c commentQueryDo) Preload(fields ...field.RelationField) *commentQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c commentQueryDo) FirstOrInit() (*Comment, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) FirstOrCreate() (*Comment, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) FindByPage(offset int, limit int) (result []*Comment, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c commentQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c commentQueryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c commentQueryDo) Delete(models ...*Comment) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (c commentQueryDo) ForceDelete() (gen.ResultInfo, error) { + return c.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (c commentQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (c commentQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (c commentQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (c commentQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (c commentQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (c commentQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (c commentQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := c.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (c commentQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := c.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (c commentQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(c.TableName(), "id") + if err := c.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (c commentQueryDo) GetByID(id int64) (*Comment, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (c commentQueryDo) GetByIDs(ids ...int64) ([]*Comment, error) { + if len(ids) == 0 { + return []*Comment{}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (c commentQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (c commentQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Delete() +} + +// RestoreWhere sets deleted_at to NULL for rows matching current scope + conds. +func (c commentQueryDo) RestoreWhere(conds ...gen.Condition) (gen.ResultInfo, error) { + col := field.NewField(c.TableName(), "deleted_at") + return c.Unscoped().Where(conds...).UpdateColumn(col, nil) +} + +// RestoreByID sets deleted_at to NULL for the given primary key. +func (c commentQueryDo) RestoreByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + col := field.NewField(c.TableName(), "deleted_at") + return c.Unscoped().Where(pk.Eq(id)).UpdateColumn(col, nil) +} + +func (c *commentQueryDo) withDO(do gen.Dao) *commentQueryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/backend/database/models/content_access.gen.go b/backend/database/models/content_access.gen.go index fc5339b..3a3555b 100644 --- a/backend/database/models/content_access.gen.go +++ b/backend/database/models/content_access.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" ) @@ -17,15 +15,15 @@ const TableNameContentAccess = "content_access" // ContentAccess mapped from table type ContentAccess struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离;与内容、用户归属一致" json:"tenant_id"` // 租户ID:多租户隔离;与内容、用户归属一致 - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:权益所属用户;用于访问校验" json:"user_id"` // 用户ID:权益所属用户;用于访问校验 - ContentID int64 `gorm:"column:content_id;type:bigint;not null;comment:内容ID:权益对应内容;唯一约束 (tenant_id, user_id, content_id)" json:"content_id"` // 内容ID:权益对应内容;唯一约束 (tenant_id, user_id, content_id) - OrderID int64 `gorm:"column:order_id;type:bigint;comment:订单ID:产生该权益的订单;可为空(例如后台补发/迁移)" json:"order_id"` // 订单ID:产生该权益的订单;可为空(例如后台补发/迁移) - Status consts.ContentAccessStatus `gorm:"column:status;type:character varying(16);not null;default:active;comment:权益状态:active/revoked/expired;revoked 表示立即失效(例如退款/违规)" json:"status"` // 权益状态:active/revoked/expired;revoked 表示立即失效(例如退款/违规) - RevokedAt time.Time `gorm:"column:revoked_at;type:timestamp with time zone;comment:撤销时间:当 status=revoked 时写入;用于审计与追责" json:"revoked_at"` // 撤销时间:当 status=revoked 时写入;用于审计与追责 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now();用于审计" json:"created_at"` // 创建时间:默认 now();用于审计 - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now();更新 status 时写入" json:"updated_at"` // 更新时间:默认 now();更新 status 时写入 + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + OrderID int64 `gorm:"column:order_id;type:bigint" json:"order_id"` + Status string `gorm:"column:status;type:character varying(16);default:active" json:"status"` + RevokedAt time.Time `gorm:"column:revoked_at;type:timestamp with time zone" json:"revoked_at"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/content_access.query.gen.go b/backend/database/models/content_access.query.gen.go index e2a958a..aed602c 100644 --- a/backend/database/models/content_access.query.gen.go +++ b/backend/database/models/content_access.query.gen.go @@ -30,7 +30,7 @@ func newContentAccess(db *gorm.DB, opts ...gen.DOOption) contentAccessQuery { _contentAccessQuery.UserID = field.NewInt64(tableName, "user_id") _contentAccessQuery.ContentID = field.NewInt64(tableName, "content_id") _contentAccessQuery.OrderID = field.NewInt64(tableName, "order_id") - _contentAccessQuery.Status = field.NewField(tableName, "status") + _contentAccessQuery.Status = field.NewString(tableName, "status") _contentAccessQuery.RevokedAt = field.NewTime(tableName, "revoked_at") _contentAccessQuery.CreatedAt = field.NewTime(tableName, "created_at") _contentAccessQuery.UpdatedAt = field.NewTime(tableName, "updated_at") @@ -44,15 +44,15 @@ type contentAccessQuery struct { contentAccessQueryDo contentAccessQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离;与内容、用户归属一致 - UserID field.Int64 // 用户ID:权益所属用户;用于访问校验 - ContentID field.Int64 // 内容ID:权益对应内容;唯一约束 (tenant_id, user_id, content_id) - OrderID field.Int64 // 订单ID:产生该权益的订单;可为空(例如后台补发/迁移) - Status field.Field // 权益状态:active/revoked/expired;revoked 表示立即失效(例如退款/违规) - RevokedAt field.Time // 撤销时间:当 status=revoked 时写入;用于审计与追责 - CreatedAt field.Time // 创建时间:默认 now();用于审计 - UpdatedAt field.Time // 更新时间:默认 now();更新 status 时写入 + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + OrderID field.Int64 + Status field.String + RevokedAt field.Time + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -74,7 +74,7 @@ func (c *contentAccessQuery) updateTableName(table string) *contentAccessQuery { c.UserID = field.NewInt64(table, "user_id") c.ContentID = field.NewInt64(table, "content_id") c.OrderID = field.NewInt64(table, "order_id") - c.Status = field.NewField(table, "status") + c.Status = field.NewString(table, "status") c.RevokedAt = field.NewTime(table, "revoked_at") c.CreatedAt = field.NewTime(table, "created_at") c.UpdatedAt = field.NewTime(table, "updated_at") diff --git a/backend/database/models/content_assets.gen.go b/backend/database/models/content_assets.gen.go index d0a9b9c..1432a68 100644 --- a/backend/database/models/content_assets.gen.go +++ b/backend/database/models/content_assets.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" ) @@ -17,15 +15,15 @@ const TableNameContentAsset = "content_assets" // ContentAsset mapped from table type ContentAsset struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离;必须与 content_id、asset_id 所属租户一致" json:"tenant_id"` // 租户ID:多租户隔离;必须与 content_id、asset_id 所属租户一致 - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:操作人/绑定人;用于审计(通常为租户管理员或作者)" json:"user_id"` // 用户ID:操作人/绑定人;用于审计(通常为租户管理员或作者) - ContentID int64 `gorm:"column:content_id;type:bigint;not null;comment:内容ID:关联 contents.id;用于查询内容下资源列表" json:"content_id"` // 内容ID:关联 contents.id;用于查询内容下资源列表 - AssetID int64 `gorm:"column:asset_id;type:bigint;not null;comment:资源ID:关联 media_assets.id;用于查询资源归属内容" json:"asset_id"` // 资源ID:关联 media_assets.id;用于查询资源归属内容 - Role consts.ContentAssetRole `gorm:"column:role;type:character varying(32);not null;default:main;comment:资源角色:main/cover/preview;preview 必须为独立资源以满足禁下载与防绕过" json:"role"` // 资源角色:main/cover/preview;preview 必须为独立资源以满足禁下载与防绕过 - Sort int32 `gorm:"column:sort;type:integer;not null;comment:排序:同一 role 下的展示顺序,数值越小越靠前" json:"sort"` // 排序:同一 role 下的展示顺序,数值越小越靠前 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now();用于审计" json:"created_at"` // 创建时间:默认 now();用于审计 - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now();更新 sort/role 时写入" json:"updated_at"` // 更新时间:默认 now();更新 sort/role 时写入 + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + AssetID int64 `gorm:"column:asset_id;type:bigint;not null" json:"asset_id"` + Role string `gorm:"column:role;type:character varying(32);default:main" json:"role"` + Sort int32 `gorm:"column:sort;type:integer" json:"sort"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/content_assets.query.gen.go b/backend/database/models/content_assets.query.gen.go index 27bc95a..60eb917 100644 --- a/backend/database/models/content_assets.query.gen.go +++ b/backend/database/models/content_assets.query.gen.go @@ -30,7 +30,7 @@ func newContentAsset(db *gorm.DB, opts ...gen.DOOption) contentAssetQuery { _contentAssetQuery.UserID = field.NewInt64(tableName, "user_id") _contentAssetQuery.ContentID = field.NewInt64(tableName, "content_id") _contentAssetQuery.AssetID = field.NewInt64(tableName, "asset_id") - _contentAssetQuery.Role = field.NewField(tableName, "role") + _contentAssetQuery.Role = field.NewString(tableName, "role") _contentAssetQuery.Sort = field.NewInt32(tableName, "sort") _contentAssetQuery.CreatedAt = field.NewTime(tableName, "created_at") _contentAssetQuery.UpdatedAt = field.NewTime(tableName, "updated_at") @@ -44,15 +44,15 @@ type contentAssetQuery struct { contentAssetQueryDo contentAssetQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离;必须与 content_id、asset_id 所属租户一致 - UserID field.Int64 // 用户ID:操作人/绑定人;用于审计(通常为租户管理员或作者) - ContentID field.Int64 // 内容ID:关联 contents.id;用于查询内容下资源列表 - AssetID field.Int64 // 资源ID:关联 media_assets.id;用于查询资源归属内容 - Role field.Field // 资源角色:main/cover/preview;preview 必须为独立资源以满足禁下载与防绕过 - Sort field.Int32 // 排序:同一 role 下的展示顺序,数值越小越靠前 - CreatedAt field.Time // 创建时间:默认 now();用于审计 - UpdatedAt field.Time // 更新时间:默认 now();更新 sort/role 时写入 + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + AssetID field.Int64 + Role field.String + Sort field.Int32 + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -74,7 +74,7 @@ func (c *contentAssetQuery) updateTableName(table string) *contentAssetQuery { c.UserID = field.NewInt64(table, "user_id") c.ContentID = field.NewInt64(table, "content_id") c.AssetID = field.NewInt64(table, "asset_id") - c.Role = field.NewField(table, "role") + c.Role = field.NewString(table, "role") c.Sort = field.NewInt32(table, "sort") c.CreatedAt = field.NewTime(table, "created_at") c.UpdatedAt = field.NewTime(table, "updated_at") diff --git a/backend/database/models/content_prices.gen.go b/backend/database/models/content_prices.gen.go index 144986a..273b3d6 100644 --- a/backend/database/models/content_prices.gen.go +++ b/backend/database/models/content_prices.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" ) @@ -17,18 +15,18 @@ const TableNameContentPrice = "content_prices" // ContentPrice mapped from table type ContentPrice struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离;与内容归属一致" json:"tenant_id"` // 租户ID:多租户隔离;与内容归属一致 - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:设置/更新价格的操作人(通常为 tenant_admin);用于审计" json:"user_id"` // 用户ID:设置/更新价格的操作人(通常为 tenant_admin);用于审计 - ContentID int64 `gorm:"column:content_id;type:bigint;not null;comment:内容ID:唯一约束 (tenant_id, content_id);一个内容在一个租户内仅一份定价" json:"content_id"` // 内容ID:唯一约束 (tenant_id, content_id);一个内容在一个租户内仅一份定价 - Currency consts.Currency `gorm:"column:currency;type:character varying(16);not null;default:CNY;comment:币种:当前固定 CNY;金额单位为分" json:"currency"` // 币种:当前固定 CNY;金额单位为分 - PriceAmount int64 `gorm:"column:price_amount;type:bigint;not null;comment:基础价格:分;0 表示免费(可直接访问正片资源)" json:"price_amount"` // 基础价格:分;0 表示免费(可直接访问正片资源) - DiscountType consts.DiscountType `gorm:"column:discount_type;type:character varying(16);not null;default:none;comment:折扣类型:none/percent/amount;仅影响下单时成交价,需写入订单快照" json:"discount_type"` // 折扣类型:none/percent/amount;仅影响下单时成交价,需写入订单快照 - DiscountValue int64 `gorm:"column:discount_value;type:bigint;not null;comment:折扣值:percent=0-100(按业务校验);amount=分;none 时忽略" json:"discount_value"` // 折扣值:percent=0-100(按业务校验);amount=分;none 时忽略 - DiscountStartAt time.Time `gorm:"column:discount_start_at;type:timestamp with time zone;comment:折扣开始时间:可为空;为空表示立即生效(由业务逻辑解释)" json:"discount_start_at"` // 折扣开始时间:可为空;为空表示立即生效(由业务逻辑解释) - DiscountEndAt time.Time `gorm:"column:discount_end_at;type:timestamp with time zone;comment:折扣结束时间:可为空;为空表示长期有效(由业务逻辑解释)" json:"discount_end_at"` // 折扣结束时间:可为空;为空表示长期有效(由业务逻辑解释) - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now();用于审计" json:"created_at"` // 创建时间:默认 now();用于审计 - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now();更新价格/折扣时写入" json:"updated_at"` // 更新时间:默认 now();更新价格/折扣时写入 + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + Currency string `gorm:"column:currency;type:character varying(16);default:CNY" json:"currency"` + PriceAmount int64 `gorm:"column:price_amount;type:bigint;not null" json:"price_amount"` + DiscountType string `gorm:"column:discount_type;type:character varying(16);default:none" json:"discount_type"` + DiscountValue int64 `gorm:"column:discount_value;type:bigint" json:"discount_value"` + DiscountStartAt time.Time `gorm:"column:discount_start_at;type:timestamp with time zone" json:"discount_start_at"` + DiscountEndAt time.Time `gorm:"column:discount_end_at;type:timestamp with time zone" json:"discount_end_at"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/content_prices.query.gen.go b/backend/database/models/content_prices.query.gen.go index c3c8529..9738a37 100644 --- a/backend/database/models/content_prices.query.gen.go +++ b/backend/database/models/content_prices.query.gen.go @@ -29,9 +29,9 @@ func newContentPrice(db *gorm.DB, opts ...gen.DOOption) contentPriceQuery { _contentPriceQuery.TenantID = field.NewInt64(tableName, "tenant_id") _contentPriceQuery.UserID = field.NewInt64(tableName, "user_id") _contentPriceQuery.ContentID = field.NewInt64(tableName, "content_id") - _contentPriceQuery.Currency = field.NewField(tableName, "currency") + _contentPriceQuery.Currency = field.NewString(tableName, "currency") _contentPriceQuery.PriceAmount = field.NewInt64(tableName, "price_amount") - _contentPriceQuery.DiscountType = field.NewField(tableName, "discount_type") + _contentPriceQuery.DiscountType = field.NewString(tableName, "discount_type") _contentPriceQuery.DiscountValue = field.NewInt64(tableName, "discount_value") _contentPriceQuery.DiscountStartAt = field.NewTime(tableName, "discount_start_at") _contentPriceQuery.DiscountEndAt = field.NewTime(tableName, "discount_end_at") @@ -47,18 +47,18 @@ type contentPriceQuery struct { contentPriceQueryDo contentPriceQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离;与内容归属一致 - UserID field.Int64 // 用户ID:设置/更新价格的操作人(通常为 tenant_admin);用于审计 - ContentID field.Int64 // 内容ID:唯一约束 (tenant_id, content_id);一个内容在一个租户内仅一份定价 - Currency field.Field // 币种:当前固定 CNY;金额单位为分 - PriceAmount field.Int64 // 基础价格:分;0 表示免费(可直接访问正片资源) - DiscountType field.Field // 折扣类型:none/percent/amount;仅影响下单时成交价,需写入订单快照 - DiscountValue field.Int64 // 折扣值:percent=0-100(按业务校验);amount=分;none 时忽略 - DiscountStartAt field.Time // 折扣开始时间:可为空;为空表示立即生效(由业务逻辑解释) - DiscountEndAt field.Time // 折扣结束时间:可为空;为空表示长期有效(由业务逻辑解释) - CreatedAt field.Time // 创建时间:默认 now();用于审计 - UpdatedAt field.Time // 更新时间:默认 now();更新价格/折扣时写入 + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + Currency field.String + PriceAmount field.Int64 + DiscountType field.String + DiscountValue field.Int64 + DiscountStartAt field.Time + DiscountEndAt field.Time + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -79,9 +79,9 @@ func (c *contentPriceQuery) updateTableName(table string) *contentPriceQuery { c.TenantID = field.NewInt64(table, "tenant_id") c.UserID = field.NewInt64(table, "user_id") c.ContentID = field.NewInt64(table, "content_id") - c.Currency = field.NewField(table, "currency") + c.Currency = field.NewString(table, "currency") c.PriceAmount = field.NewInt64(table, "price_amount") - c.DiscountType = field.NewField(table, "discount_type") + c.DiscountType = field.NewString(table, "discount_type") c.DiscountValue = field.NewInt64(table, "discount_value") c.DiscountStartAt = field.NewTime(table, "discount_start_at") c.DiscountEndAt = field.NewTime(table, "discount_end_at") diff --git a/backend/database/models/contents.gen.go b/backend/database/models/contents.gen.go index cc28fed..c1389ef 100644 --- a/backend/database/models/contents.gen.go +++ b/backend/database/models/contents.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" "gorm.io/gorm" @@ -19,21 +17,25 @@ const TableNameContent = "contents" // Content mapped from table type Content struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增;用于内容引用" json:"id"` // 主键ID:自增;用于内容引用 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id" json:"tenant_id"` // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:内容创建者/发布者;用于权限与审计(例如私有内容仅作者可见)" json:"user_id"` // 用户ID:内容创建者/发布者;用于权限与审计(例如私有内容仅作者可见) - Title string `gorm:"column:title;type:character varying(255);not null;comment:标题:用于列表展示与搜索;建议限制长度(由业务校验)" json:"title"` // 标题:用于列表展示与搜索;建议限制长度(由业务校验) - Description string `gorm:"column:description;type:text;not null;comment:描述:用于详情页展示;可为空字符串" json:"description"` // 描述:用于详情页展示;可为空字符串 - Status consts.ContentStatus `gorm:"column:status;type:character varying(32);not null;default:draft;comment:状态:draft/reviewing/published/unpublished/blocked;published 才对外展示" json:"status"` // 状态:draft/reviewing/published/unpublished/blocked;published 才对外展示 - Visibility consts.ContentVisibility `gorm:"column:visibility;type:character varying(32);not null;default:tenant_only;comment:可见性:public/tenant_only/private;仅控制详情可见,正片资源仍需按价格/权益校验" json:"visibility"` // 可见性:public/tenant_only/private;仅控制详情可见,正片资源仍需按价格/权益校验 - PreviewSeconds int32 `gorm:"column:preview_seconds;type:integer;not null;default:60;comment:试看秒数:默认 60;只对 preview 资源生效;必须为正整数" json:"preview_seconds"` // 试看秒数:默认 60;只对 preview 资源生效;必须为正整数 - PreviewDownloadable bool `gorm:"column:preview_downloadable;type:boolean;not null;comment:试看是否允许下载:默认 false;当前策略固定为不允许下载(仅 streaming)" json:"preview_downloadable"` // 试看是否允许下载:默认 false;当前策略固定为不允许下载(仅 streaming) - PublishedAt time.Time `gorm:"column:published_at;type:timestamp with time zone;comment:发布时间:首次发布时写入;用于时间窗与排序" json:"published_at"` // 发布时间:首次发布时写入;用于时间窗与排序 - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone;comment:软删除时间:非空表示已删除;对外接口需过滤" json:"deleted_at"` // 软删除时间:非空表示已删除;对外接口需过滤 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now();用于审计与排序" json:"created_at"` // 创建时间:默认 now();用于审计与排序 - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now();编辑内容时写入" json:"updated_at"` // 更新时间:默认 now();编辑内容时写入 - Summary string `gorm:"column:summary;type:character varying(256);not null;comment:简介:用于列表/卡片展示的短文本;建议 <= 256 字符(由业务校验)" json:"summary"` // 简介:用于列表/卡片展示的短文本;建议 <= 256 字符(由业务校验) - Tags types.JSON `gorm:"column:tags;type:jsonb;not null;default:[];comment:标签:JSON 数组(字符串列表);用于分类/检索与聚合展示" json:"tags"` // 标签:JSON 数组(字符串列表);用于分类/检索与聚合展示 + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Title string `gorm:"column:title;type:character varying(255);not null" json:"title"` + Description string `gorm:"column:description;type:text;not null" json:"description"` + Status string `gorm:"column:status;type:character varying(32);default:draft" json:"status"` + Visibility string `gorm:"column:visibility;type:character varying(32);default:tenant_only" json:"visibility"` + PreviewSeconds int32 `gorm:"column:preview_seconds;type:integer;default:60" json:"preview_seconds"` + PreviewDownloadable bool `gorm:"column:preview_downloadable;type:boolean" json:"preview_downloadable"` + PublishedAt time.Time `gorm:"column:published_at;type:timestamp with time zone" json:"published_at"` + Summary string `gorm:"column:summary;type:character varying(256)" json:"summary"` + Tags types.JSON `gorm:"column:tags;type:jsonb;default:[]" json:"tags"` + Body string `gorm:"column:body;type:text" json:"body"` + Genre string `gorm:"column:genre;type:character varying(64)" json:"genre"` + Views int32 `gorm:"column:views;type:integer" json:"views"` + Likes int32 `gorm:"column:likes;type:integer" json:"likes"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` } // Quick operations without importing query package diff --git a/backend/database/models/contents.query.gen.go b/backend/database/models/contents.query.gen.go index fca7622..7bf9659 100644 --- a/backend/database/models/contents.query.gen.go +++ b/backend/database/models/contents.query.gen.go @@ -30,16 +30,20 @@ func newContent(db *gorm.DB, opts ...gen.DOOption) contentQuery { _contentQuery.UserID = field.NewInt64(tableName, "user_id") _contentQuery.Title = field.NewString(tableName, "title") _contentQuery.Description = field.NewString(tableName, "description") - _contentQuery.Status = field.NewField(tableName, "status") - _contentQuery.Visibility = field.NewField(tableName, "visibility") + _contentQuery.Status = field.NewString(tableName, "status") + _contentQuery.Visibility = field.NewString(tableName, "visibility") _contentQuery.PreviewSeconds = field.NewInt32(tableName, "preview_seconds") _contentQuery.PreviewDownloadable = field.NewBool(tableName, "preview_downloadable") _contentQuery.PublishedAt = field.NewTime(tableName, "published_at") - _contentQuery.DeletedAt = field.NewField(tableName, "deleted_at") - _contentQuery.CreatedAt = field.NewTime(tableName, "created_at") - _contentQuery.UpdatedAt = field.NewTime(tableName, "updated_at") _contentQuery.Summary = field.NewString(tableName, "summary") _contentQuery.Tags = field.NewJSONB(tableName, "tags") + _contentQuery.Body = field.NewString(tableName, "body") + _contentQuery.Genre = field.NewString(tableName, "genre") + _contentQuery.Views = field.NewInt32(tableName, "views") + _contentQuery.Likes = field.NewInt32(tableName, "likes") + _contentQuery.CreatedAt = field.NewTime(tableName, "created_at") + _contentQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _contentQuery.DeletedAt = field.NewField(tableName, "deleted_at") _contentQuery.fillFieldMap() @@ -50,21 +54,25 @@ type contentQuery struct { contentQueryDo contentQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增;用于内容引用 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID field.Int64 // 用户ID:内容创建者/发布者;用于权限与审计(例如私有内容仅作者可见) - Title field.String // 标题:用于列表展示与搜索;建议限制长度(由业务校验) - Description field.String // 描述:用于详情页展示;可为空字符串 - Status field.Field // 状态:draft/reviewing/published/unpublished/blocked;published 才对外展示 - Visibility field.Field // 可见性:public/tenant_only/private;仅控制详情可见,正片资源仍需按价格/权益校验 - PreviewSeconds field.Int32 // 试看秒数:默认 60;只对 preview 资源生效;必须为正整数 - PreviewDownloadable field.Bool // 试看是否允许下载:默认 false;当前策略固定为不允许下载(仅 streaming) - PublishedAt field.Time // 发布时间:首次发布时写入;用于时间窗与排序 - DeletedAt field.Field // 软删除时间:非空表示已删除;对外接口需过滤 - CreatedAt field.Time // 创建时间:默认 now();用于审计与排序 - UpdatedAt field.Time // 更新时间:默认 now();编辑内容时写入 - Summary field.String // 简介:用于列表/卡片展示的短文本;建议 <= 256 字符(由业务校验) - Tags field.JSONB // 标签:JSON 数组(字符串列表);用于分类/检索与聚合展示 + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Title field.String + Description field.String + Status field.String + Visibility field.String + PreviewSeconds field.Int32 + PreviewDownloadable field.Bool + PublishedAt field.Time + Summary field.String + Tags field.JSONB + Body field.String + Genre field.String + Views field.Int32 + Likes field.Int32 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field fieldMap map[string]field.Expr } @@ -86,16 +94,20 @@ func (c *contentQuery) updateTableName(table string) *contentQuery { c.UserID = field.NewInt64(table, "user_id") c.Title = field.NewString(table, "title") c.Description = field.NewString(table, "description") - c.Status = field.NewField(table, "status") - c.Visibility = field.NewField(table, "visibility") + c.Status = field.NewString(table, "status") + c.Visibility = field.NewString(table, "visibility") c.PreviewSeconds = field.NewInt32(table, "preview_seconds") c.PreviewDownloadable = field.NewBool(table, "preview_downloadable") c.PublishedAt = field.NewTime(table, "published_at") - c.DeletedAt = field.NewField(table, "deleted_at") - c.CreatedAt = field.NewTime(table, "created_at") - c.UpdatedAt = field.NewTime(table, "updated_at") c.Summary = field.NewString(table, "summary") c.Tags = field.NewJSONB(table, "tags") + c.Body = field.NewString(table, "body") + c.Genre = field.NewString(table, "genre") + c.Views = field.NewInt32(table, "views") + c.Likes = field.NewInt32(table, "likes") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") c.fillFieldMap() @@ -128,7 +140,7 @@ func (c *contentQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) } func (c *contentQuery) fillFieldMap() { - c.fieldMap = make(map[string]field.Expr, 15) + c.fieldMap = make(map[string]field.Expr, 19) c.fieldMap["id"] = c.ID c.fieldMap["tenant_id"] = c.TenantID c.fieldMap["user_id"] = c.UserID @@ -139,11 +151,15 @@ func (c *contentQuery) fillFieldMap() { c.fieldMap["preview_seconds"] = c.PreviewSeconds c.fieldMap["preview_downloadable"] = c.PreviewDownloadable c.fieldMap["published_at"] = c.PublishedAt - c.fieldMap["deleted_at"] = c.DeletedAt - c.fieldMap["created_at"] = c.CreatedAt - c.fieldMap["updated_at"] = c.UpdatedAt c.fieldMap["summary"] = c.Summary c.fieldMap["tags"] = c.Tags + c.fieldMap["body"] = c.Body + c.fieldMap["genre"] = c.Genre + c.fieldMap["views"] = c.Views + c.fieldMap["likes"] = c.Likes + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt } func (c contentQuery) clone(db *gorm.DB) contentQuery { diff --git a/backend/database/models/media_assets.gen.go b/backend/database/models/media_assets.gen.go index 05e633a..ba20847 100644 --- a/backend/database/models/media_assets.gen.go +++ b/backend/database/models/media_assets.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" "gorm.io/gorm" @@ -19,20 +17,20 @@ const TableNameMediaAsset = "media_assets" // MediaAsset mapped from table type MediaAsset struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增;仅用于内部关联" json:"id"` // 主键ID:自增;仅用于内部关联 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id" json:"tenant_id"` // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:资源上传者;用于审计与权限控制" json:"user_id"` // 用户ID:资源上传者;用于审计与权限控制 - Type consts.MediaAssetType `gorm:"column:type;type:character varying(32);not null;default:video;comment:资源类型:video/audio/image;决定后续处理流程(转码/缩略图/封面等)" json:"type"` // 资源类型:video/audio/image;决定后续处理流程(转码/缩略图/封面等) - Status consts.MediaAssetStatus `gorm:"column:status;type:character varying(32);not null;default:uploaded;comment:处理状态:uploaded/processing/ready/failed/deleted;ready 才可被内容引用对外提供" json:"status"` // 处理状态:uploaded/processing/ready/failed/deleted;ready 才可被内容引用对外提供 - Provider string `gorm:"column:provider;type:character varying(64);not null;comment:存储提供方:例如 s3/minio/oss;便于多存储扩展" json:"provider"` // 存储提供方:例如 s3/minio/oss;便于多存储扩展 - Bucket string `gorm:"column:bucket;type:character varying(128);not null;comment:存储桶:对象所在 bucket;与 provider 组合确定存储定位" json:"bucket"` // 存储桶:对象所在 bucket;与 provider 组合确定存储定位 - ObjectKey string `gorm:"column:object_key;type:character varying(512);not null;comment:对象键:对象在 bucket 内的 key;不得暴露可长期复用的直链(通过签名URL/token下发)" json:"object_key"` // 对象键:对象在 bucket 内的 key;不得暴露可长期复用的直链(通过签名URL/token下发) - Meta types.JSON `gorm:"column:meta;type:jsonb;not null;default:{};comment:元数据:JSON;包含 hash、duration、width、height、bitrate、codec 等;用于展示与计费/风控" json:"meta"` // 元数据:JSON;包含 hash、duration、width、height、bitrate、codec 等;用于展示与计费/风控 - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone;comment:软删除时间:非空表示已删除;对外接口需过滤" json:"deleted_at"` // 软删除时间:非空表示已删除;对外接口需过滤 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now();用于审计与排序" json:"created_at"` // 创建时间:默认 now();用于审计与排序 - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now();更新状态/元数据时写入" json:"updated_at"` // 更新时间:默认 now();更新状态/元数据时写入 - Variant consts.MediaAssetVariant `gorm:"column:variant;type:character varying(32);not null;default:main;comment:产物类型:main/preview;用于强制试看资源必须绑定独立产物,避免用正片绕过" json:"variant"` // 产物类型:main/preview;用于强制试看资源必须绑定独立产物,避免用正片绕过 - SourceAssetID int64 `gorm:"column:source_asset_id;type:bigint;comment:派生来源资源ID:preview 产物可指向对应 main 资源;用于建立 preview/main 的 1:1 追溯关系" json:"source_asset_id"` // 派生来源资源ID:preview 产物可指向对应 main 资源;用于建立 preview/main 的 1:1 追溯关系 + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Type string `gorm:"column:type;type:character varying(32);default:video" json:"type"` + Status string `gorm:"column:status;type:character varying(32);default:uploaded" json:"status"` + Provider string `gorm:"column:provider;type:character varying(64);not null" json:"provider"` + Bucket string `gorm:"column:bucket;type:character varying(128);not null" json:"bucket"` + ObjectKey string `gorm:"column:object_key;type:character varying(512);not null" json:"object_key"` + Meta types.JSON `gorm:"column:meta;type:jsonb;default:{}" json:"meta"` + Variant string `gorm:"column:variant;type:character varying(32);default:main" json:"variant"` + SourceAssetID int64 `gorm:"column:source_asset_id;type:bigint" json:"source_asset_id"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` } // Quick operations without importing query package diff --git a/backend/database/models/media_assets.query.gen.go b/backend/database/models/media_assets.query.gen.go index 2a69d96..dbc7764 100644 --- a/backend/database/models/media_assets.query.gen.go +++ b/backend/database/models/media_assets.query.gen.go @@ -28,17 +28,17 @@ func newMediaAsset(db *gorm.DB, opts ...gen.DOOption) mediaAssetQuery { _mediaAssetQuery.ID = field.NewInt64(tableName, "id") _mediaAssetQuery.TenantID = field.NewInt64(tableName, "tenant_id") _mediaAssetQuery.UserID = field.NewInt64(tableName, "user_id") - _mediaAssetQuery.Type = field.NewField(tableName, "type") - _mediaAssetQuery.Status = field.NewField(tableName, "status") + _mediaAssetQuery.Type = field.NewString(tableName, "type") + _mediaAssetQuery.Status = field.NewString(tableName, "status") _mediaAssetQuery.Provider = field.NewString(tableName, "provider") _mediaAssetQuery.Bucket = field.NewString(tableName, "bucket") _mediaAssetQuery.ObjectKey = field.NewString(tableName, "object_key") _mediaAssetQuery.Meta = field.NewJSONB(tableName, "meta") - _mediaAssetQuery.DeletedAt = field.NewField(tableName, "deleted_at") + _mediaAssetQuery.Variant = field.NewString(tableName, "variant") + _mediaAssetQuery.SourceAssetID = field.NewInt64(tableName, "source_asset_id") _mediaAssetQuery.CreatedAt = field.NewTime(tableName, "created_at") _mediaAssetQuery.UpdatedAt = field.NewTime(tableName, "updated_at") - _mediaAssetQuery.Variant = field.NewField(tableName, "variant") - _mediaAssetQuery.SourceAssetID = field.NewInt64(tableName, "source_asset_id") + _mediaAssetQuery.DeletedAt = field.NewField(tableName, "deleted_at") _mediaAssetQuery.fillFieldMap() @@ -49,20 +49,20 @@ type mediaAssetQuery struct { mediaAssetQueryDo mediaAssetQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增;仅用于内部关联 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID field.Int64 // 用户ID:资源上传者;用于审计与权限控制 - Type field.Field // 资源类型:video/audio/image;决定后续处理流程(转码/缩略图/封面等) - Status field.Field // 处理状态:uploaded/processing/ready/failed/deleted;ready 才可被内容引用对外提供 - Provider field.String // 存储提供方:例如 s3/minio/oss;便于多存储扩展 - Bucket field.String // 存储桶:对象所在 bucket;与 provider 组合确定存储定位 - ObjectKey field.String // 对象键:对象在 bucket 内的 key;不得暴露可长期复用的直链(通过签名URL/token下发) - Meta field.JSONB // 元数据:JSON;包含 hash、duration、width、height、bitrate、codec 等;用于展示与计费/风控 - DeletedAt field.Field // 软删除时间:非空表示已删除;对外接口需过滤 - CreatedAt field.Time // 创建时间:默认 now();用于审计与排序 - UpdatedAt field.Time // 更新时间:默认 now();更新状态/元数据时写入 - Variant field.Field // 产物类型:main/preview;用于强制试看资源必须绑定独立产物,避免用正片绕过 - SourceAssetID field.Int64 // 派生来源资源ID:preview 产物可指向对应 main 资源;用于建立 preview/main 的 1:1 追溯关系 + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Type field.String + Status field.String + Provider field.String + Bucket field.String + ObjectKey field.String + Meta field.JSONB + Variant field.String + SourceAssetID field.Int64 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field fieldMap map[string]field.Expr } @@ -82,17 +82,17 @@ func (m *mediaAssetQuery) updateTableName(table string) *mediaAssetQuery { m.ID = field.NewInt64(table, "id") m.TenantID = field.NewInt64(table, "tenant_id") m.UserID = field.NewInt64(table, "user_id") - m.Type = field.NewField(table, "type") - m.Status = field.NewField(table, "status") + m.Type = field.NewString(table, "type") + m.Status = field.NewString(table, "status") m.Provider = field.NewString(table, "provider") m.Bucket = field.NewString(table, "bucket") m.ObjectKey = field.NewString(table, "object_key") m.Meta = field.NewJSONB(table, "meta") - m.DeletedAt = field.NewField(table, "deleted_at") + m.Variant = field.NewString(table, "variant") + m.SourceAssetID = field.NewInt64(table, "source_asset_id") m.CreatedAt = field.NewTime(table, "created_at") m.UpdatedAt = field.NewTime(table, "updated_at") - m.Variant = field.NewField(table, "variant") - m.SourceAssetID = field.NewInt64(table, "source_asset_id") + m.DeletedAt = field.NewField(table, "deleted_at") m.fillFieldMap() @@ -135,11 +135,11 @@ func (m *mediaAssetQuery) fillFieldMap() { m.fieldMap["bucket"] = m.Bucket m.fieldMap["object_key"] = m.ObjectKey m.fieldMap["meta"] = m.Meta - m.fieldMap["deleted_at"] = m.DeletedAt - m.fieldMap["created_at"] = m.CreatedAt - m.fieldMap["updated_at"] = m.UpdatedAt m.fieldMap["variant"] = m.Variant m.fieldMap["source_asset_id"] = m.SourceAssetID + m.fieldMap["created_at"] = m.CreatedAt + m.fieldMap["updated_at"] = m.UpdatedAt + m.fieldMap["deleted_at"] = m.DeletedAt } func (m mediaAssetQuery) clone(db *gorm.DB) mediaAssetQuery { diff --git a/backend/database/models/notifications.gen.go b/backend/database/models/notifications.gen.go new file mode 100644 index 0000000..3854b06 --- /dev/null +++ b/backend/database/models/notifications.gen.go @@ -0,0 +1,62 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameNotification = "notifications" + +// Notification mapped from table +type Notification struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint" json:"tenant_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + Title string `gorm:"column:title;type:character varying(255);not null" json:"title"` + Content string `gorm:"column:content;type:text;not null" json:"content"` + IsRead bool `gorm:"column:is_read;type:boolean" json:"is_read"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Notification) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Notification.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Notification) Save(ctx context.Context) error { + return Q.Notification.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *Notification) Create(ctx context.Context) error { + return Q.Notification.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *Notification) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Notification.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Notification) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Notification.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Notification) Reload(ctx context.Context) error { + fresh, err := Q.Notification.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/notifications.query.gen.go b/backend/database/models/notifications.query.gen.go new file mode 100644 index 0000000..4d9d51b --- /dev/null +++ b/backend/database/models/notifications.query.gen.go @@ -0,0 +1,489 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newNotification(db *gorm.DB, opts ...gen.DOOption) notificationQuery { + _notificationQuery := notificationQuery{} + + _notificationQuery.notificationQueryDo.UseDB(db, opts...) + _notificationQuery.notificationQueryDo.UseModel(&Notification{}) + + tableName := _notificationQuery.notificationQueryDo.TableName() + _notificationQuery.ALL = field.NewAsterisk(tableName) + _notificationQuery.ID = field.NewInt64(tableName, "id") + _notificationQuery.UserID = field.NewInt64(tableName, "user_id") + _notificationQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _notificationQuery.Type = field.NewString(tableName, "type") + _notificationQuery.Title = field.NewString(tableName, "title") + _notificationQuery.Content = field.NewString(tableName, "content") + _notificationQuery.IsRead = field.NewBool(tableName, "is_read") + _notificationQuery.CreatedAt = field.NewTime(tableName, "created_at") + + _notificationQuery.fillFieldMap() + + return _notificationQuery +} + +type notificationQuery struct { + notificationQueryDo notificationQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + TenantID field.Int64 + Type field.String + Title field.String + Content field.String + IsRead field.Bool + CreatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (n notificationQuery) Table(newTableName string) *notificationQuery { + n.notificationQueryDo.UseTable(newTableName) + return n.updateTableName(newTableName) +} + +func (n notificationQuery) As(alias string) *notificationQuery { + n.notificationQueryDo.DO = *(n.notificationQueryDo.As(alias).(*gen.DO)) + return n.updateTableName(alias) +} + +func (n *notificationQuery) updateTableName(table string) *notificationQuery { + n.ALL = field.NewAsterisk(table) + n.ID = field.NewInt64(table, "id") + n.UserID = field.NewInt64(table, "user_id") + n.TenantID = field.NewInt64(table, "tenant_id") + n.Type = field.NewString(table, "type") + n.Title = field.NewString(table, "title") + n.Content = field.NewString(table, "content") + n.IsRead = field.NewBool(table, "is_read") + n.CreatedAt = field.NewTime(table, "created_at") + + n.fillFieldMap() + + return n +} + +func (n *notificationQuery) QueryContext(ctx context.Context) (*notificationQuery, *notificationQueryDo) { + return n, n.notificationQueryDo.WithContext(ctx) +} + +func (n *notificationQuery) WithContext(ctx context.Context) *notificationQueryDo { + return n.notificationQueryDo.WithContext(ctx) +} + +func (n notificationQuery) TableName() string { return n.notificationQueryDo.TableName() } + +func (n notificationQuery) Alias() string { return n.notificationQueryDo.Alias() } + +func (n notificationQuery) Columns(cols ...field.Expr) gen.Columns { + return n.notificationQueryDo.Columns(cols...) +} + +func (n *notificationQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := n.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (n *notificationQuery) fillFieldMap() { + n.fieldMap = make(map[string]field.Expr, 8) + n.fieldMap["id"] = n.ID + n.fieldMap["user_id"] = n.UserID + n.fieldMap["tenant_id"] = n.TenantID + n.fieldMap["type"] = n.Type + n.fieldMap["title"] = n.Title + n.fieldMap["content"] = n.Content + n.fieldMap["is_read"] = n.IsRead + n.fieldMap["created_at"] = n.CreatedAt +} + +func (n notificationQuery) clone(db *gorm.DB) notificationQuery { + n.notificationQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return n +} + +func (n notificationQuery) replaceDB(db *gorm.DB) notificationQuery { + n.notificationQueryDo.ReplaceDB(db) + return n +} + +type notificationQueryDo struct{ gen.DO } + +func (n notificationQueryDo) Debug() *notificationQueryDo { + return n.withDO(n.DO.Debug()) +} + +func (n notificationQueryDo) WithContext(ctx context.Context) *notificationQueryDo { + return n.withDO(n.DO.WithContext(ctx)) +} + +func (n notificationQueryDo) ReadDB() *notificationQueryDo { + return n.Clauses(dbresolver.Read) +} + +func (n notificationQueryDo) WriteDB() *notificationQueryDo { + return n.Clauses(dbresolver.Write) +} + +func (n notificationQueryDo) Session(config *gorm.Session) *notificationQueryDo { + return n.withDO(n.DO.Session(config)) +} + +func (n notificationQueryDo) Clauses(conds ...clause.Expression) *notificationQueryDo { + return n.withDO(n.DO.Clauses(conds...)) +} + +func (n notificationQueryDo) Returning(value interface{}, columns ...string) *notificationQueryDo { + return n.withDO(n.DO.Returning(value, columns...)) +} + +func (n notificationQueryDo) Not(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Not(conds...)) +} + +func (n notificationQueryDo) Or(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Or(conds...)) +} + +func (n notificationQueryDo) Select(conds ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Select(conds...)) +} + +func (n notificationQueryDo) Where(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Where(conds...)) +} + +func (n notificationQueryDo) Order(conds ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Order(conds...)) +} + +func (n notificationQueryDo) Distinct(cols ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Distinct(cols...)) +} + +func (n notificationQueryDo) Omit(cols ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Omit(cols...)) +} + +func (n notificationQueryDo) Join(table schema.Tabler, on ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Join(table, on...)) +} + +func (n notificationQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.LeftJoin(table, on...)) +} + +func (n notificationQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.RightJoin(table, on...)) +} + +func (n notificationQueryDo) Group(cols ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Group(cols...)) +} + +func (n notificationQueryDo) Having(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Having(conds...)) +} + +func (n notificationQueryDo) Limit(limit int) *notificationQueryDo { + return n.withDO(n.DO.Limit(limit)) +} + +func (n notificationQueryDo) Offset(offset int) *notificationQueryDo { + return n.withDO(n.DO.Offset(offset)) +} + +func (n notificationQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *notificationQueryDo { + return n.withDO(n.DO.Scopes(funcs...)) +} + +func (n notificationQueryDo) Unscoped() *notificationQueryDo { + return n.withDO(n.DO.Unscoped()) +} + +func (n notificationQueryDo) Create(values ...*Notification) error { + if len(values) == 0 { + return nil + } + return n.DO.Create(values) +} + +func (n notificationQueryDo) CreateInBatches(values []*Notification, batchSize int) error { + return n.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (n notificationQueryDo) Save(values ...*Notification) error { + if len(values) == 0 { + return nil + } + return n.DO.Save(values) +} + +func (n notificationQueryDo) First() (*Notification, error) { + if result, err := n.DO.First(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) Take() (*Notification, error) { + if result, err := n.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) Last() (*Notification, error) { + if result, err := n.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) Find() ([]*Notification, error) { + result, err := n.DO.Find() + return result.([]*Notification), err +} + +func (n notificationQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Notification, err error) { + buf := make([]*Notification, 0, batchSize) + err = n.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (n notificationQueryDo) FindInBatches(result *[]*Notification, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return n.DO.FindInBatches(result, batchSize, fc) +} + +func (n notificationQueryDo) Attrs(attrs ...field.AssignExpr) *notificationQueryDo { + return n.withDO(n.DO.Attrs(attrs...)) +} + +func (n notificationQueryDo) Assign(attrs ...field.AssignExpr) *notificationQueryDo { + return n.withDO(n.DO.Assign(attrs...)) +} + +func (n notificationQueryDo) Joins(fields ...field.RelationField) *notificationQueryDo { + for _, _f := range fields { + n = *n.withDO(n.DO.Joins(_f)) + } + return &n +} + +func (n notificationQueryDo) Preload(fields ...field.RelationField) *notificationQueryDo { + for _, _f := range fields { + n = *n.withDO(n.DO.Preload(_f)) + } + return &n +} + +func (n notificationQueryDo) FirstOrInit() (*Notification, error) { + if result, err := n.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) FirstOrCreate() (*Notification, error) { + if result, err := n.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) FindByPage(offset int, limit int) (result []*Notification, count int64, err error) { + result, err = n.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = n.Offset(-1).Limit(-1).Count() + return +} + +func (n notificationQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = n.Count() + if err != nil { + return + } + + err = n.Offset(offset).Limit(limit).Scan(result) + return +} + +func (n notificationQueryDo) Scan(result interface{}) (err error) { + return n.DO.Scan(result) +} + +func (n notificationQueryDo) Delete(models ...*Notification) (result gen.ResultInfo, err error) { + return n.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (n notificationQueryDo) ForceDelete() (gen.ResultInfo, error) { + return n.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (n notificationQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return n.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (n notificationQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return n.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (n notificationQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (n notificationQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (n notificationQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (n notificationQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (n notificationQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := n.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (n notificationQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := n.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (n notificationQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(n.TableName(), "id") + if err := n.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (n notificationQueryDo) GetByID(id int64) (*Notification, error) { + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (n notificationQueryDo) GetByIDs(ids ...int64) ([]*Notification, error) { + if len(ids) == 0 { + return []*Notification{}, nil + } + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (n notificationQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (n notificationQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.In(ids...)).Delete() +} + +func (n *notificationQueryDo) withDO(do gen.Dao) *notificationQueryDo { + n.DO = *do.(*gen.DO) + return n +} diff --git a/backend/database/models/order_items.gen.go b/backend/database/models/order_items.gen.go index 43930e2..19c69e7 100644 --- a/backend/database/models/order_items.gen.go +++ b/backend/database/models/order_items.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/database/fields" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" ) @@ -18,18 +16,16 @@ const TableNameOrderItem = "order_items" // OrderItem mapped from table type OrderItem struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;必须与 orders.tenant_id 一致" json:"tenant_id"` // 租户ID:多租户隔离关键字段;必须与 orders.tenant_id 一致 - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:下单用户(buyer);冗余字段用于查询加速与审计" json:"user_id"` // 用户ID:下单用户(buyer);冗余字段用于查询加速与审计 - OrderID int64 `gorm:"column:order_id;type:bigint;not null;comment:订单ID:关联 orders.id;用于聚合订单明细" json:"order_id"` // 订单ID:关联 orders.id;用于聚合订单明细 - ContentID int64 `gorm:"column:content_id;type:bigint;not null;comment:内容ID:关联 contents.id;用于生成/撤销 content_access" json:"content_id"` // 内容ID:关联 contents.id;用于生成/撤销 content_access - ContentUserID int64 `gorm:"column:content_user_id;type:bigint;not null;comment:内容作者用户ID:用于后续分成/对账扩展;当前可为 0 或写入内容创建者" json:"content_user_id"` // 内容作者用户ID:用于后续分成/对账扩展;当前可为 0 或写入内容创建者 - AmountPaid int64 `gorm:"column:amount_paid;type:bigint;not null;comment:该行实付金额:分;通常等于订单 amount_paid(单内容场景)" json:"amount_paid"` // 该行实付金额:分;通常等于订单 amount_paid(单内容场景) - Snapshot types.JSONType[fields.OrderItemsSnapshot] `gorm:"column:snapshot;type:jsonb;not null;default:{};comment:内容快照:JSON;建议包含 title/price/discount 等,用于历史展示与审计" json:"snapshot"` // 内容快照:JSON;建议包含 title/price/discount 等,用于历史展示与审计 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now()" json:"created_at"` // 创建时间:默认 now() - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now()" json:"updated_at"` // 更新时间:默认 now() - Order *Order `gorm:"foreignKey:OrderID;references:ID" json:"order,omitempty"` - Content *Content `gorm:"foreignKey:ContentID;references:ID" json:"content,omitempty"` + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + OrderID int64 `gorm:"column:order_id;type:bigint;not null" json:"order_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + ContentUserID int64 `gorm:"column:content_user_id;type:bigint;not null" json:"content_user_id"` + AmountPaid int64 `gorm:"column:amount_paid;type:bigint;not null" json:"amount_paid"` + Snapshot types.JSON `gorm:"column:snapshot;type:jsonb;default:{}" json:"snapshot"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/order_items.query.gen.go b/backend/database/models/order_items.query.gen.go index 91ad511..8bca5ee 100644 --- a/backend/database/models/order_items.query.gen.go +++ b/backend/database/models/order_items.query.gen.go @@ -35,17 +35,6 @@ func newOrderItem(db *gorm.DB, opts ...gen.DOOption) orderItemQuery { _orderItemQuery.Snapshot = field.NewJSONB(tableName, "snapshot") _orderItemQuery.CreatedAt = field.NewTime(tableName, "created_at") _orderItemQuery.UpdatedAt = field.NewTime(tableName, "updated_at") - _orderItemQuery.Order = orderItemQueryBelongsToOrder{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Order", "Order"), - } - - _orderItemQuery.Content = orderItemQueryBelongsToContent{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Content", "Content"), - } _orderItemQuery.fillFieldMap() @@ -56,19 +45,16 @@ type orderItemQuery struct { orderItemQueryDo orderItemQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;必须与 orders.tenant_id 一致 - UserID field.Int64 // 用户ID:下单用户(buyer);冗余字段用于查询加速与审计 - OrderID field.Int64 // 订单ID:关联 orders.id;用于聚合订单明细 - ContentID field.Int64 // 内容ID:关联 contents.id;用于生成/撤销 content_access - ContentUserID field.Int64 // 内容作者用户ID:用于后续分成/对账扩展;当前可为 0 或写入内容创建者 - AmountPaid field.Int64 // 该行实付金额:分;通常等于订单 amount_paid(单内容场景) - Snapshot field.JSONB // 内容快照:JSON;建议包含 title/price/discount 等,用于历史展示与审计 - CreatedAt field.Time // 创建时间:默认 now() - UpdatedAt field.Time // 更新时间:默认 now() - Order orderItemQueryBelongsToOrder - - Content orderItemQueryBelongsToContent + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + OrderID field.Int64 + ContentID field.Int64 + ContentUserID field.Int64 + AmountPaid field.Int64 + Snapshot field.JSONB + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -127,7 +113,7 @@ func (o *orderItemQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool } func (o *orderItemQuery) fillFieldMap() { - o.fieldMap = make(map[string]field.Expr, 12) + o.fieldMap = make(map[string]field.Expr, 10) o.fieldMap["id"] = o.ID o.fieldMap["tenant_id"] = o.TenantID o.fieldMap["user_id"] = o.UserID @@ -138,187 +124,18 @@ func (o *orderItemQuery) fillFieldMap() { o.fieldMap["snapshot"] = o.Snapshot o.fieldMap["created_at"] = o.CreatedAt o.fieldMap["updated_at"] = o.UpdatedAt - } func (o orderItemQuery) clone(db *gorm.DB) orderItemQuery { o.orderItemQueryDo.ReplaceConnPool(db.Statement.ConnPool) - o.Order.db = db.Session(&gorm.Session{Initialized: true}) - o.Order.db.Statement.ConnPool = db.Statement.ConnPool - o.Content.db = db.Session(&gorm.Session{Initialized: true}) - o.Content.db.Statement.ConnPool = db.Statement.ConnPool return o } func (o orderItemQuery) replaceDB(db *gorm.DB) orderItemQuery { o.orderItemQueryDo.ReplaceDB(db) - o.Order.db = db.Session(&gorm.Session{}) - o.Content.db = db.Session(&gorm.Session{}) return o } -type orderItemQueryBelongsToOrder struct { - db *gorm.DB - - field.RelationField -} - -func (a orderItemQueryBelongsToOrder) Where(conds ...field.Expr) *orderItemQueryBelongsToOrder { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a orderItemQueryBelongsToOrder) WithContext(ctx context.Context) *orderItemQueryBelongsToOrder { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a orderItemQueryBelongsToOrder) Session(session *gorm.Session) *orderItemQueryBelongsToOrder { - a.db = a.db.Session(session) - return &a -} - -func (a orderItemQueryBelongsToOrder) Model(m *OrderItem) *orderItemQueryBelongsToOrderTx { - return &orderItemQueryBelongsToOrderTx{a.db.Model(m).Association(a.Name())} -} - -func (a orderItemQueryBelongsToOrder) Unscoped() *orderItemQueryBelongsToOrder { - a.db = a.db.Unscoped() - return &a -} - -type orderItemQueryBelongsToOrderTx struct{ tx *gorm.Association } - -func (a orderItemQueryBelongsToOrderTx) Find() (result *Order, err error) { - return result, a.tx.Find(&result) -} - -func (a orderItemQueryBelongsToOrderTx) Append(values ...*Order) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a orderItemQueryBelongsToOrderTx) Replace(values ...*Order) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a orderItemQueryBelongsToOrderTx) Delete(values ...*Order) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a orderItemQueryBelongsToOrderTx) Clear() error { - return a.tx.Clear() -} - -func (a orderItemQueryBelongsToOrderTx) Count() int64 { - return a.tx.Count() -} - -func (a orderItemQueryBelongsToOrderTx) Unscoped() *orderItemQueryBelongsToOrderTx { - a.tx = a.tx.Unscoped() - return &a -} - -type orderItemQueryBelongsToContent struct { - db *gorm.DB - - field.RelationField -} - -func (a orderItemQueryBelongsToContent) Where(conds ...field.Expr) *orderItemQueryBelongsToContent { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a orderItemQueryBelongsToContent) WithContext(ctx context.Context) *orderItemQueryBelongsToContent { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a orderItemQueryBelongsToContent) Session(session *gorm.Session) *orderItemQueryBelongsToContent { - a.db = a.db.Session(session) - return &a -} - -func (a orderItemQueryBelongsToContent) Model(m *OrderItem) *orderItemQueryBelongsToContentTx { - return &orderItemQueryBelongsToContentTx{a.db.Model(m).Association(a.Name())} -} - -func (a orderItemQueryBelongsToContent) Unscoped() *orderItemQueryBelongsToContent { - a.db = a.db.Unscoped() - return &a -} - -type orderItemQueryBelongsToContentTx struct{ tx *gorm.Association } - -func (a orderItemQueryBelongsToContentTx) Find() (result *Content, err error) { - return result, a.tx.Find(&result) -} - -func (a orderItemQueryBelongsToContentTx) Append(values ...*Content) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a orderItemQueryBelongsToContentTx) Replace(values ...*Content) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a orderItemQueryBelongsToContentTx) Delete(values ...*Content) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a orderItemQueryBelongsToContentTx) Clear() error { - return a.tx.Clear() -} - -func (a orderItemQueryBelongsToContentTx) Count() int64 { - return a.tx.Count() -} - -func (a orderItemQueryBelongsToContentTx) Unscoped() *orderItemQueryBelongsToContentTx { - a.tx = a.tx.Unscoped() - return &a -} - type orderItemQueryDo struct{ gen.DO } func (o orderItemQueryDo) Debug() *orderItemQueryDo { diff --git a/backend/database/models/orders.gen.go b/backend/database/models/orders.gen.go index 2dff0d1..c0fa0ad 100644 --- a/backend/database/models/orders.gen.go +++ b/backend/database/models/orders.gen.go @@ -8,9 +8,6 @@ import ( "context" "time" - "quyun/v2/database/fields" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" ) @@ -19,25 +16,24 @@ const TableNameOrder = "orders" // Order mapped from table type Order struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增;用于关联订单明细、账本流水、权益等" json:"id"` // 主键ID:自增;用于关联订单明细、账本流水、权益等 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id" json:"tenant_id"` // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:下单用户(buyer);余额扣款与权益归属以该 user_id 为准" json:"user_id"` // 用户ID:下单用户(buyer);余额扣款与权益归属以该 user_id 为准 - Type consts.OrderType `gorm:"column:type;type:character varying(32);not null;default:content_purchase;comment:订单类型:content_purchase(购买内容)等;当前默认 content_purchase" json:"type"` // 订单类型:content_purchase(购买内容)等;当前默认 content_purchase - Status consts.OrderStatus `gorm:"column:status;type:character varying(32);not null;default:created;comment:订单状态:created/paid/refunding/refunded/canceled/failed;状态变更需与账本/权益保持一致" json:"status"` // 订单状态:created/paid/refunding/refunded/canceled/failed;状态变更需与账本/权益保持一致 - Currency consts.Currency `gorm:"column:currency;type:character varying(16);not null;default:CNY;comment:币种:当前固定 CNY;金额单位为分" json:"currency"` // 币种:当前固定 CNY;金额单位为分 - AmountOriginal int64 `gorm:"column:amount_original;type:bigint;not null;comment:原价金额:分;未折扣前金额(用于展示与对账)" json:"amount_original"` // 原价金额:分;未折扣前金额(用于展示与对账) - AmountDiscount int64 `gorm:"column:amount_discount;type:bigint;not null;comment:优惠金额:分;amount_paid = amount_original - amount_discount(下单时快照)" json:"amount_discount"` // 优惠金额:分;amount_paid = amount_original - amount_discount(下单时快照) - AmountPaid int64 `gorm:"column:amount_paid;type:bigint;not null;comment:实付金额:分;从租户内余额扣款的金额(下单时快照)" json:"amount_paid"` // 实付金额:分;从租户内余额扣款的金额(下单时快照) - Snapshot types.JSONType[fields.OrdersSnapshot] `gorm:"column:snapshot;type:jsonb;not null;default:{};comment:订单快照:JSON;建议包含 content 标题/定价/折扣、请求来源等,避免改价影响历史展示" json:"snapshot"` // 订单快照:JSON;建议包含 content 标题/定价/折扣、请求来源等,避免改价影响历史展示 - IdempotencyKey string `gorm:"column:idempotency_key;type:character varying(128);not null;comment:幂等键:同一租户同一用户同一业务请求可用;用于防重复下单/重复扣款(建议由客户端生成)" json:"idempotency_key"` // 幂等键:同一租户同一用户同一业务请求可用;用于防重复下单/重复扣款(建议由客户端生成) - PaidAt time.Time `gorm:"column:paid_at;type:timestamp with time zone;comment:支付/扣款完成时间:余额支付在 debit_purchase 成功后写入" json:"paid_at"` // 支付/扣款完成时间:余额支付在 debit_purchase 成功后写入 - RefundedAt time.Time `gorm:"column:refunded_at;type:timestamp with time zone;comment:退款完成时间:退款落账成功后写入" json:"refunded_at"` // 退款完成时间:退款落账成功后写入 - RefundForced bool `gorm:"column:refund_forced;type:boolean;not null;comment:是否强制退款:true 表示租户管理侧绕过时间窗执行退款(需审计)" json:"refund_forced"` // 是否强制退款:true 表示租户管理侧绕过时间窗执行退款(需审计) - RefundOperatorUserID int64 `gorm:"column:refund_operator_user_id;type:bigint;comment:退款操作人用户ID:租户管理员/系统;用于审计与追责" json:"refund_operator_user_id"` // 退款操作人用户ID:租户管理员/系统;用于审计与追责 - RefundReason string `gorm:"column:refund_reason;type:character varying(255);not null;comment:退款原因:后台/用户发起退款的原因说明;用于审计" json:"refund_reason"` // 退款原因:后台/用户发起退款的原因说明;用于审计 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now();用于审计与排序" json:"created_at"` // 创建时间:默认 now();用于审计与排序 - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now();状态变更/退款写入时更新" json:"updated_at"` // 更新时间:默认 now();状态变更/退款写入时更新 - Items []*OrderItem `gorm:"foreignKey:OrderID;references:ID" json:"items,omitempty"` + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Type string `gorm:"column:type;type:character varying(32);default:content_purchase" json:"type"` + Status string `gorm:"column:status;type:character varying(32);default:created" json:"status"` + Currency string `gorm:"column:currency;type:character varying(16);default:CNY" json:"currency"` + AmountOriginal int64 `gorm:"column:amount_original;type:bigint;not null" json:"amount_original"` + AmountDiscount int64 `gorm:"column:amount_discount;type:bigint;not null" json:"amount_discount"` + AmountPaid int64 `gorm:"column:amount_paid;type:bigint;not null" json:"amount_paid"` + Snapshot types.JSON `gorm:"column:snapshot;type:jsonb;default:{}" json:"snapshot"` + IdempotencyKey string `gorm:"column:idempotency_key;type:character varying(128);not null" json:"idempotency_key"` + PaidAt time.Time `gorm:"column:paid_at;type:timestamp with time zone" json:"paid_at"` + RefundedAt time.Time `gorm:"column:refunded_at;type:timestamp with time zone" json:"refunded_at"` + RefundForced bool `gorm:"column:refund_forced;type:boolean" json:"refund_forced"` + RefundOperatorUserID int64 `gorm:"column:refund_operator_user_id;type:bigint" json:"refund_operator_user_id"` + RefundReason string `gorm:"column:refund_reason;type:character varying(255)" json:"refund_reason"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/orders.query.gen.go b/backend/database/models/orders.query.gen.go index 65eb6b2..75f7780 100644 --- a/backend/database/models/orders.query.gen.go +++ b/backend/database/models/orders.query.gen.go @@ -28,9 +28,9 @@ func newOrder(db *gorm.DB, opts ...gen.DOOption) orderQuery { _orderQuery.ID = field.NewInt64(tableName, "id") _orderQuery.TenantID = field.NewInt64(tableName, "tenant_id") _orderQuery.UserID = field.NewInt64(tableName, "user_id") - _orderQuery.Type = field.NewField(tableName, "type") - _orderQuery.Status = field.NewField(tableName, "status") - _orderQuery.Currency = field.NewField(tableName, "currency") + _orderQuery.Type = field.NewString(tableName, "type") + _orderQuery.Status = field.NewString(tableName, "status") + _orderQuery.Currency = field.NewString(tableName, "currency") _orderQuery.AmountOriginal = field.NewInt64(tableName, "amount_original") _orderQuery.AmountDiscount = field.NewInt64(tableName, "amount_discount") _orderQuery.AmountPaid = field.NewInt64(tableName, "amount_paid") @@ -43,11 +43,6 @@ func newOrder(db *gorm.DB, opts ...gen.DOOption) orderQuery { _orderQuery.RefundReason = field.NewString(tableName, "refund_reason") _orderQuery.CreatedAt = field.NewTime(tableName, "created_at") _orderQuery.UpdatedAt = field.NewTime(tableName, "updated_at") - _orderQuery.Items = orderQueryHasManyItems{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Items", "OrderItem"), - } _orderQuery.fillFieldMap() @@ -58,25 +53,24 @@ type orderQuery struct { orderQueryDo orderQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增;用于关联订单明细、账本流水、权益等 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID field.Int64 // 用户ID:下单用户(buyer);余额扣款与权益归属以该 user_id 为准 - Type field.Field // 订单类型:content_purchase(购买内容)等;当前默认 content_purchase - Status field.Field // 订单状态:created/paid/refunding/refunded/canceled/failed;状态变更需与账本/权益保持一致 - Currency field.Field // 币种:当前固定 CNY;金额单位为分 - AmountOriginal field.Int64 // 原价金额:分;未折扣前金额(用于展示与对账) - AmountDiscount field.Int64 // 优惠金额:分;amount_paid = amount_original - amount_discount(下单时快照) - AmountPaid field.Int64 // 实付金额:分;从租户内余额扣款的金额(下单时快照) - Snapshot field.JSONB // 订单快照:JSON;建议包含 content 标题/定价/折扣、请求来源等,避免改价影响历史展示 - IdempotencyKey field.String // 幂等键:同一租户同一用户同一业务请求可用;用于防重复下单/重复扣款(建议由客户端生成) - PaidAt field.Time // 支付/扣款完成时间:余额支付在 debit_purchase 成功后写入 - RefundedAt field.Time // 退款完成时间:退款落账成功后写入 - RefundForced field.Bool // 是否强制退款:true 表示租户管理侧绕过时间窗执行退款(需审计) - RefundOperatorUserID field.Int64 // 退款操作人用户ID:租户管理员/系统;用于审计与追责 - RefundReason field.String // 退款原因:后台/用户发起退款的原因说明;用于审计 - CreatedAt field.Time // 创建时间:默认 now();用于审计与排序 - UpdatedAt field.Time // 更新时间:默认 now();状态变更/退款写入时更新 - Items orderQueryHasManyItems + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Type field.String + Status field.String + Currency field.String + AmountOriginal field.Int64 + AmountDiscount field.Int64 + AmountPaid field.Int64 + Snapshot field.JSONB + IdempotencyKey field.String + PaidAt field.Time + RefundedAt field.Time + RefundForced field.Bool + RefundOperatorUserID field.Int64 + RefundReason field.String + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -96,9 +90,9 @@ func (o *orderQuery) updateTableName(table string) *orderQuery { o.ID = field.NewInt64(table, "id") o.TenantID = field.NewInt64(table, "tenant_id") o.UserID = field.NewInt64(table, "user_id") - o.Type = field.NewField(table, "type") - o.Status = field.NewField(table, "status") - o.Currency = field.NewField(table, "currency") + o.Type = field.NewString(table, "type") + o.Status = field.NewString(table, "status") + o.Currency = field.NewString(table, "currency") o.AmountOriginal = field.NewInt64(table, "amount_original") o.AmountDiscount = field.NewInt64(table, "amount_discount") o.AmountPaid = field.NewInt64(table, "amount_paid") @@ -141,7 +135,7 @@ func (o *orderQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { } func (o *orderQuery) fillFieldMap() { - o.fieldMap = make(map[string]field.Expr, 19) + o.fieldMap = make(map[string]field.Expr, 18) o.fieldMap["id"] = o.ID o.fieldMap["tenant_id"] = o.TenantID o.fieldMap["user_id"] = o.UserID @@ -160,103 +154,18 @@ func (o *orderQuery) fillFieldMap() { o.fieldMap["refund_reason"] = o.RefundReason o.fieldMap["created_at"] = o.CreatedAt o.fieldMap["updated_at"] = o.UpdatedAt - } func (o orderQuery) clone(db *gorm.DB) orderQuery { o.orderQueryDo.ReplaceConnPool(db.Statement.ConnPool) - o.Items.db = db.Session(&gorm.Session{Initialized: true}) - o.Items.db.Statement.ConnPool = db.Statement.ConnPool return o } func (o orderQuery) replaceDB(db *gorm.DB) orderQuery { o.orderQueryDo.ReplaceDB(db) - o.Items.db = db.Session(&gorm.Session{}) return o } -type orderQueryHasManyItems struct { - db *gorm.DB - - field.RelationField -} - -func (a orderQueryHasManyItems) Where(conds ...field.Expr) *orderQueryHasManyItems { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a orderQueryHasManyItems) WithContext(ctx context.Context) *orderQueryHasManyItems { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a orderQueryHasManyItems) Session(session *gorm.Session) *orderQueryHasManyItems { - a.db = a.db.Session(session) - return &a -} - -func (a orderQueryHasManyItems) Model(m *Order) *orderQueryHasManyItemsTx { - return &orderQueryHasManyItemsTx{a.db.Model(m).Association(a.Name())} -} - -func (a orderQueryHasManyItems) Unscoped() *orderQueryHasManyItems { - a.db = a.db.Unscoped() - return &a -} - -type orderQueryHasManyItemsTx struct{ tx *gorm.Association } - -func (a orderQueryHasManyItemsTx) Find() (result []*OrderItem, err error) { - return result, a.tx.Find(&result) -} - -func (a orderQueryHasManyItemsTx) Append(values ...*OrderItem) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a orderQueryHasManyItemsTx) Replace(values ...*OrderItem) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a orderQueryHasManyItemsTx) Delete(values ...*OrderItem) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a orderQueryHasManyItemsTx) Clear() error { - return a.tx.Clear() -} - -func (a orderQueryHasManyItemsTx) Count() int64 { - return a.tx.Count() -} - -func (a orderQueryHasManyItemsTx) Unscoped() *orderQueryHasManyItemsTx { - a.tx = a.tx.Unscoped() - return &a -} - type orderQueryDo struct{ gen.DO } func (o orderQueryDo) Debug() *orderQueryDo { diff --git a/backend/database/models/payout_accounts.gen.go b/backend/database/models/payout_accounts.gen.go new file mode 100644 index 0000000..9e4c44d --- /dev/null +++ b/backend/database/models/payout_accounts.gen.go @@ -0,0 +1,63 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNamePayoutAccount = "payout_accounts" + +// PayoutAccount mapped from table +type PayoutAccount struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + Name string `gorm:"column:name;type:character varying(128);not null" json:"name"` + Account string `gorm:"column:account;type:character varying(128);not null" json:"account"` + Realname string `gorm:"column:realname;type:character varying(128);not null" json:"realname"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *PayoutAccount) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.PayoutAccount.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *PayoutAccount) Save(ctx context.Context) error { + return Q.PayoutAccount.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *PayoutAccount) Create(ctx context.Context) error { + return Q.PayoutAccount.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *PayoutAccount) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.PayoutAccount.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *PayoutAccount) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.PayoutAccount.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *PayoutAccount) Reload(ctx context.Context) error { + fresh, err := Q.PayoutAccount.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/payout_accounts.query.gen.go b/backend/database/models/payout_accounts.query.gen.go new file mode 100644 index 0000000..01caa3e --- /dev/null +++ b/backend/database/models/payout_accounts.query.gen.go @@ -0,0 +1,493 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newPayoutAccount(db *gorm.DB, opts ...gen.DOOption) payoutAccountQuery { + _payoutAccountQuery := payoutAccountQuery{} + + _payoutAccountQuery.payoutAccountQueryDo.UseDB(db, opts...) + _payoutAccountQuery.payoutAccountQueryDo.UseModel(&PayoutAccount{}) + + tableName := _payoutAccountQuery.payoutAccountQueryDo.TableName() + _payoutAccountQuery.ALL = field.NewAsterisk(tableName) + _payoutAccountQuery.ID = field.NewInt64(tableName, "id") + _payoutAccountQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _payoutAccountQuery.UserID = field.NewInt64(tableName, "user_id") + _payoutAccountQuery.Type = field.NewString(tableName, "type") + _payoutAccountQuery.Name = field.NewString(tableName, "name") + _payoutAccountQuery.Account = field.NewString(tableName, "account") + _payoutAccountQuery.Realname = field.NewString(tableName, "realname") + _payoutAccountQuery.CreatedAt = field.NewTime(tableName, "created_at") + _payoutAccountQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _payoutAccountQuery.fillFieldMap() + + return _payoutAccountQuery +} + +type payoutAccountQuery struct { + payoutAccountQueryDo payoutAccountQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Type field.String + Name field.String + Account field.String + Realname field.String + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (p payoutAccountQuery) Table(newTableName string) *payoutAccountQuery { + p.payoutAccountQueryDo.UseTable(newTableName) + return p.updateTableName(newTableName) +} + +func (p payoutAccountQuery) As(alias string) *payoutAccountQuery { + p.payoutAccountQueryDo.DO = *(p.payoutAccountQueryDo.As(alias).(*gen.DO)) + return p.updateTableName(alias) +} + +func (p *payoutAccountQuery) updateTableName(table string) *payoutAccountQuery { + p.ALL = field.NewAsterisk(table) + p.ID = field.NewInt64(table, "id") + p.TenantID = field.NewInt64(table, "tenant_id") + p.UserID = field.NewInt64(table, "user_id") + p.Type = field.NewString(table, "type") + p.Name = field.NewString(table, "name") + p.Account = field.NewString(table, "account") + p.Realname = field.NewString(table, "realname") + p.CreatedAt = field.NewTime(table, "created_at") + p.UpdatedAt = field.NewTime(table, "updated_at") + + p.fillFieldMap() + + return p +} + +func (p *payoutAccountQuery) QueryContext(ctx context.Context) (*payoutAccountQuery, *payoutAccountQueryDo) { + return p, p.payoutAccountQueryDo.WithContext(ctx) +} + +func (p *payoutAccountQuery) WithContext(ctx context.Context) *payoutAccountQueryDo { + return p.payoutAccountQueryDo.WithContext(ctx) +} + +func (p payoutAccountQuery) TableName() string { return p.payoutAccountQueryDo.TableName() } + +func (p payoutAccountQuery) Alias() string { return p.payoutAccountQueryDo.Alias() } + +func (p payoutAccountQuery) Columns(cols ...field.Expr) gen.Columns { + return p.payoutAccountQueryDo.Columns(cols...) +} + +func (p *payoutAccountQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := p.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (p *payoutAccountQuery) fillFieldMap() { + p.fieldMap = make(map[string]field.Expr, 9) + p.fieldMap["id"] = p.ID + p.fieldMap["tenant_id"] = p.TenantID + p.fieldMap["user_id"] = p.UserID + p.fieldMap["type"] = p.Type + p.fieldMap["name"] = p.Name + p.fieldMap["account"] = p.Account + p.fieldMap["realname"] = p.Realname + p.fieldMap["created_at"] = p.CreatedAt + p.fieldMap["updated_at"] = p.UpdatedAt +} + +func (p payoutAccountQuery) clone(db *gorm.DB) payoutAccountQuery { + p.payoutAccountQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return p +} + +func (p payoutAccountQuery) replaceDB(db *gorm.DB) payoutAccountQuery { + p.payoutAccountQueryDo.ReplaceDB(db) + return p +} + +type payoutAccountQueryDo struct{ gen.DO } + +func (p payoutAccountQueryDo) Debug() *payoutAccountQueryDo { + return p.withDO(p.DO.Debug()) +} + +func (p payoutAccountQueryDo) WithContext(ctx context.Context) *payoutAccountQueryDo { + return p.withDO(p.DO.WithContext(ctx)) +} + +func (p payoutAccountQueryDo) ReadDB() *payoutAccountQueryDo { + return p.Clauses(dbresolver.Read) +} + +func (p payoutAccountQueryDo) WriteDB() *payoutAccountQueryDo { + return p.Clauses(dbresolver.Write) +} + +func (p payoutAccountQueryDo) Session(config *gorm.Session) *payoutAccountQueryDo { + return p.withDO(p.DO.Session(config)) +} + +func (p payoutAccountQueryDo) Clauses(conds ...clause.Expression) *payoutAccountQueryDo { + return p.withDO(p.DO.Clauses(conds...)) +} + +func (p payoutAccountQueryDo) Returning(value interface{}, columns ...string) *payoutAccountQueryDo { + return p.withDO(p.DO.Returning(value, columns...)) +} + +func (p payoutAccountQueryDo) Not(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Not(conds...)) +} + +func (p payoutAccountQueryDo) Or(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Or(conds...)) +} + +func (p payoutAccountQueryDo) Select(conds ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Select(conds...)) +} + +func (p payoutAccountQueryDo) Where(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Where(conds...)) +} + +func (p payoutAccountQueryDo) Order(conds ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Order(conds...)) +} + +func (p payoutAccountQueryDo) Distinct(cols ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Distinct(cols...)) +} + +func (p payoutAccountQueryDo) Omit(cols ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Omit(cols...)) +} + +func (p payoutAccountQueryDo) Join(table schema.Tabler, on ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Join(table, on...)) +} + +func (p payoutAccountQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.LeftJoin(table, on...)) +} + +func (p payoutAccountQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.RightJoin(table, on...)) +} + +func (p payoutAccountQueryDo) Group(cols ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Group(cols...)) +} + +func (p payoutAccountQueryDo) Having(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Having(conds...)) +} + +func (p payoutAccountQueryDo) Limit(limit int) *payoutAccountQueryDo { + return p.withDO(p.DO.Limit(limit)) +} + +func (p payoutAccountQueryDo) Offset(offset int) *payoutAccountQueryDo { + return p.withDO(p.DO.Offset(offset)) +} + +func (p payoutAccountQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *payoutAccountQueryDo { + return p.withDO(p.DO.Scopes(funcs...)) +} + +func (p payoutAccountQueryDo) Unscoped() *payoutAccountQueryDo { + return p.withDO(p.DO.Unscoped()) +} + +func (p payoutAccountQueryDo) Create(values ...*PayoutAccount) error { + if len(values) == 0 { + return nil + } + return p.DO.Create(values) +} + +func (p payoutAccountQueryDo) CreateInBatches(values []*PayoutAccount, batchSize int) error { + return p.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (p payoutAccountQueryDo) Save(values ...*PayoutAccount) error { + if len(values) == 0 { + return nil + } + return p.DO.Save(values) +} + +func (p payoutAccountQueryDo) First() (*PayoutAccount, error) { + if result, err := p.DO.First(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) Take() (*PayoutAccount, error) { + if result, err := p.DO.Take(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) Last() (*PayoutAccount, error) { + if result, err := p.DO.Last(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) Find() ([]*PayoutAccount, error) { + result, err := p.DO.Find() + return result.([]*PayoutAccount), err +} + +func (p payoutAccountQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*PayoutAccount, err error) { + buf := make([]*PayoutAccount, 0, batchSize) + err = p.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (p payoutAccountQueryDo) FindInBatches(result *[]*PayoutAccount, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return p.DO.FindInBatches(result, batchSize, fc) +} + +func (p payoutAccountQueryDo) Attrs(attrs ...field.AssignExpr) *payoutAccountQueryDo { + return p.withDO(p.DO.Attrs(attrs...)) +} + +func (p payoutAccountQueryDo) Assign(attrs ...field.AssignExpr) *payoutAccountQueryDo { + return p.withDO(p.DO.Assign(attrs...)) +} + +func (p payoutAccountQueryDo) Joins(fields ...field.RelationField) *payoutAccountQueryDo { + for _, _f := range fields { + p = *p.withDO(p.DO.Joins(_f)) + } + return &p +} + +func (p payoutAccountQueryDo) Preload(fields ...field.RelationField) *payoutAccountQueryDo { + for _, _f := range fields { + p = *p.withDO(p.DO.Preload(_f)) + } + return &p +} + +func (p payoutAccountQueryDo) FirstOrInit() (*PayoutAccount, error) { + if result, err := p.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) FirstOrCreate() (*PayoutAccount, error) { + if result, err := p.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) FindByPage(offset int, limit int) (result []*PayoutAccount, count int64, err error) { + result, err = p.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = p.Offset(-1).Limit(-1).Count() + return +} + +func (p payoutAccountQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = p.Count() + if err != nil { + return + } + + err = p.Offset(offset).Limit(limit).Scan(result) + return +} + +func (p payoutAccountQueryDo) Scan(result interface{}) (err error) { + return p.DO.Scan(result) +} + +func (p payoutAccountQueryDo) Delete(models ...*PayoutAccount) (result gen.ResultInfo, err error) { + return p.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (p payoutAccountQueryDo) ForceDelete() (gen.ResultInfo, error) { + return p.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (p payoutAccountQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return p.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (p payoutAccountQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return p.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (p payoutAccountQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (p payoutAccountQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (p payoutAccountQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (p payoutAccountQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (p payoutAccountQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := p.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (p payoutAccountQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := p.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (p payoutAccountQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(p.TableName(), "id") + if err := p.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (p payoutAccountQueryDo) GetByID(id int64) (*PayoutAccount, error) { + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (p payoutAccountQueryDo) GetByIDs(ids ...int64) ([]*PayoutAccount, error) { + if len(ids) == 0 { + return []*PayoutAccount{}, nil + } + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (p payoutAccountQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (p payoutAccountQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.In(ids...)).Delete() +} + +func (p *payoutAccountQueryDo) withDO(do gen.Dao) *payoutAccountQueryDo { + p.DO = *do.(*gen.DO) + return p +} diff --git a/backend/database/models/query.gen.go b/backend/database/models/query.gen.go index 639fa93..e3e8b48 100644 --- a/backend/database/models/query.gen.go +++ b/backend/database/models/query.gen.go @@ -17,73 +17,93 @@ import ( var ( Q = new(Query) + CommentQuery *commentQuery ContentQuery *contentQuery ContentAccessQuery *contentAccessQuery ContentAssetQuery *contentAssetQuery ContentPriceQuery *contentPriceQuery MediaAssetQuery *mediaAssetQuery + NotificationQuery *notificationQuery OrderQuery *orderQuery OrderItemQuery *orderItemQuery + PayoutAccountQuery *payoutAccountQuery TenantQuery *tenantQuery TenantInviteQuery *tenantInviteQuery TenantJoinRequestQuery *tenantJoinRequestQuery TenantLedgerQuery *tenantLedgerQuery TenantUserQuery *tenantUserQuery UserQuery *userQuery + UserCommentActionQuery *userCommentActionQuery + UserContentActionQuery *userContentActionQuery ) func SetDefault(db *gorm.DB, opts ...gen.DOOption) { *Q = *Use(db, opts...) + CommentQuery = &Q.Comment ContentQuery = &Q.Content ContentAccessQuery = &Q.ContentAccess ContentAssetQuery = &Q.ContentAsset ContentPriceQuery = &Q.ContentPrice MediaAssetQuery = &Q.MediaAsset + NotificationQuery = &Q.Notification OrderQuery = &Q.Order OrderItemQuery = &Q.OrderItem + PayoutAccountQuery = &Q.PayoutAccount TenantQuery = &Q.Tenant TenantInviteQuery = &Q.TenantInvite TenantJoinRequestQuery = &Q.TenantJoinRequest TenantLedgerQuery = &Q.TenantLedger TenantUserQuery = &Q.TenantUser UserQuery = &Q.User + UserCommentActionQuery = &Q.UserCommentAction + UserContentActionQuery = &Q.UserContentAction } func Use(db *gorm.DB, opts ...gen.DOOption) *Query { return &Query{ db: db, + Comment: newComment(db, opts...), Content: newContent(db, opts...), ContentAccess: newContentAccess(db, opts...), ContentAsset: newContentAsset(db, opts...), ContentPrice: newContentPrice(db, opts...), MediaAsset: newMediaAsset(db, opts...), + Notification: newNotification(db, opts...), Order: newOrder(db, opts...), OrderItem: newOrderItem(db, opts...), + PayoutAccount: newPayoutAccount(db, opts...), Tenant: newTenant(db, opts...), TenantInvite: newTenantInvite(db, opts...), TenantJoinRequest: newTenantJoinRequest(db, opts...), TenantLedger: newTenantLedger(db, opts...), TenantUser: newTenantUser(db, opts...), User: newUser(db, opts...), + UserCommentAction: newUserCommentAction(db, opts...), + UserContentAction: newUserContentAction(db, opts...), } } type Query struct { db *gorm.DB + Comment commentQuery Content contentQuery ContentAccess contentAccessQuery ContentAsset contentAssetQuery ContentPrice contentPriceQuery MediaAsset mediaAssetQuery + Notification notificationQuery Order orderQuery OrderItem orderItemQuery + PayoutAccount payoutAccountQuery Tenant tenantQuery TenantInvite tenantInviteQuery TenantJoinRequest tenantJoinRequestQuery TenantLedger tenantLedgerQuery TenantUser tenantUserQuery User userQuery + UserCommentAction userCommentActionQuery + UserContentAction userContentActionQuery } func (q *Query) Available() bool { return q.db != nil } @@ -91,19 +111,24 @@ func (q *Query) Available() bool { return q.db != nil } func (q *Query) clone(db *gorm.DB) *Query { return &Query{ db: db, + Comment: q.Comment.clone(db), Content: q.Content.clone(db), ContentAccess: q.ContentAccess.clone(db), ContentAsset: q.ContentAsset.clone(db), ContentPrice: q.ContentPrice.clone(db), MediaAsset: q.MediaAsset.clone(db), + Notification: q.Notification.clone(db), Order: q.Order.clone(db), OrderItem: q.OrderItem.clone(db), + PayoutAccount: q.PayoutAccount.clone(db), Tenant: q.Tenant.clone(db), TenantInvite: q.TenantInvite.clone(db), TenantJoinRequest: q.TenantJoinRequest.clone(db), TenantLedger: q.TenantLedger.clone(db), TenantUser: q.TenantUser.clone(db), User: q.User.clone(db), + UserCommentAction: q.UserCommentAction.clone(db), + UserContentAction: q.UserContentAction.clone(db), } } @@ -118,53 +143,68 @@ func (q *Query) WriteDB() *Query { func (q *Query) ReplaceDB(db *gorm.DB) *Query { return &Query{ db: db, + Comment: q.Comment.replaceDB(db), Content: q.Content.replaceDB(db), ContentAccess: q.ContentAccess.replaceDB(db), ContentAsset: q.ContentAsset.replaceDB(db), ContentPrice: q.ContentPrice.replaceDB(db), MediaAsset: q.MediaAsset.replaceDB(db), + Notification: q.Notification.replaceDB(db), Order: q.Order.replaceDB(db), OrderItem: q.OrderItem.replaceDB(db), + PayoutAccount: q.PayoutAccount.replaceDB(db), Tenant: q.Tenant.replaceDB(db), TenantInvite: q.TenantInvite.replaceDB(db), TenantJoinRequest: q.TenantJoinRequest.replaceDB(db), TenantLedger: q.TenantLedger.replaceDB(db), TenantUser: q.TenantUser.replaceDB(db), User: q.User.replaceDB(db), + UserCommentAction: q.UserCommentAction.replaceDB(db), + UserContentAction: q.UserContentAction.replaceDB(db), } } type queryCtx struct { + Comment *commentQueryDo Content *contentQueryDo ContentAccess *contentAccessQueryDo ContentAsset *contentAssetQueryDo ContentPrice *contentPriceQueryDo MediaAsset *mediaAssetQueryDo + Notification *notificationQueryDo Order *orderQueryDo OrderItem *orderItemQueryDo + PayoutAccount *payoutAccountQueryDo Tenant *tenantQueryDo TenantInvite *tenantInviteQueryDo TenantJoinRequest *tenantJoinRequestQueryDo TenantLedger *tenantLedgerQueryDo TenantUser *tenantUserQueryDo User *userQueryDo + UserCommentAction *userCommentActionQueryDo + UserContentAction *userContentActionQueryDo } func (q *Query) WithContext(ctx context.Context) *queryCtx { return &queryCtx{ + Comment: q.Comment.WithContext(ctx), Content: q.Content.WithContext(ctx), ContentAccess: q.ContentAccess.WithContext(ctx), ContentAsset: q.ContentAsset.WithContext(ctx), ContentPrice: q.ContentPrice.WithContext(ctx), MediaAsset: q.MediaAsset.WithContext(ctx), + Notification: q.Notification.WithContext(ctx), Order: q.Order.WithContext(ctx), OrderItem: q.OrderItem.WithContext(ctx), + PayoutAccount: q.PayoutAccount.WithContext(ctx), Tenant: q.Tenant.WithContext(ctx), TenantInvite: q.TenantInvite.WithContext(ctx), TenantJoinRequest: q.TenantJoinRequest.WithContext(ctx), TenantLedger: q.TenantLedger.WithContext(ctx), TenantUser: q.TenantUser.WithContext(ctx), User: q.User.WithContext(ctx), + UserCommentAction: q.UserCommentAction.WithContext(ctx), + UserContentAction: q.UserContentAction.WithContext(ctx), } } diff --git a/backend/database/models/tenant_invites.gen.go b/backend/database/models/tenant_invites.gen.go index 1d61582..d05c47f 100644 --- a/backend/database/models/tenant_invites.gen.go +++ b/backend/database/models/tenant_invites.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" ) @@ -17,19 +15,19 @@ const TableNameTenantInvite = "tenant_invites" // TenantInvite mapped from table type TenantInvite struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id" json:"tenant_id"` // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:创建人用户ID:生成邀请码的租户管理员(审计用)" json:"user_id"` // 创建人用户ID:生成邀请码的租户管理员(审计用) - Code string `gorm:"column:code;type:character varying(64);not null;comment:邀请码:用户加入租户时提交;同一租户内唯一" json:"code"` // 邀请码:用户加入租户时提交;同一租户内唯一 - Status consts.TenantInviteStatus `gorm:"column:status;type:character varying(32);not null;default:active;comment:邀请状态:active/disabled/expired;expired 也可由 expires_at 推导,业务侧需保持一致" json:"status"` // 邀请状态:active/disabled/expired;expired 也可由 expires_at 推导,业务侧需保持一致 - MaxUses int32 `gorm:"column:max_uses;type:integer;not null;comment:最大可使用次数:0 表示不限制;>0 时 used_count 达到该值后视为失效" json:"max_uses"` // 最大可使用次数:0 表示不限制;>0 时 used_count 达到该值后视为失效 - UsedCount int32 `gorm:"column:used_count;type:integer;not null;comment:已使用次数:每次成功加入时 +1;需事务保证并发下不超发" json:"used_count"` // 已使用次数:每次成功加入时 +1;需事务保证并发下不超发 - ExpiresAt time.Time `gorm:"column:expires_at;type:timestamp with time zone;comment:过期时间:到期后不可再使用(UTC);为空表示不过期" json:"expires_at"` // 过期时间:到期后不可再使用(UTC);为空表示不过期 - DisabledAt time.Time `gorm:"column:disabled_at;type:timestamp with time zone;comment:禁用时间:租户管理员禁用该邀请的时间(UTC)" json:"disabled_at"` // 禁用时间:租户管理员禁用该邀请的时间(UTC) - DisabledOperatorUserID int64 `gorm:"column:disabled_operator_user_id;type:bigint;comment:禁用操作人用户ID:租户管理员(审计用)" json:"disabled_operator_user_id"` // 禁用操作人用户ID:租户管理员(审计用) - Remark string `gorm:"column:remark;type:character varying(255);not null;comment:备注:生成/禁用原因等(审计用)" json:"remark"` // 备注:生成/禁用原因等(审计用) - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now()" json:"created_at"` // 创建时间:默认 now() - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now()" json:"updated_at"` // 更新时间:默认 now() + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Code string `gorm:"column:code;type:character varying(64);not null" json:"code"` + Status string `gorm:"column:status;type:character varying(32);default:active" json:"status"` + MaxUses int32 `gorm:"column:max_uses;type:integer;not null" json:"max_uses"` + UsedCount int32 `gorm:"column:used_count;type:integer" json:"used_count"` + ExpiresAt time.Time `gorm:"column:expires_at;type:timestamp with time zone" json:"expires_at"` + DisabledAt time.Time `gorm:"column:disabled_at;type:timestamp with time zone" json:"disabled_at"` + DisabledOperatorUserID int64 `gorm:"column:disabled_operator_user_id;type:bigint" json:"disabled_operator_user_id"` + Remark string `gorm:"column:remark;type:character varying(255)" json:"remark"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/tenant_invites.query.gen.go b/backend/database/models/tenant_invites.query.gen.go index 464d880..f59820e 100644 --- a/backend/database/models/tenant_invites.query.gen.go +++ b/backend/database/models/tenant_invites.query.gen.go @@ -29,7 +29,7 @@ func newTenantInvite(db *gorm.DB, opts ...gen.DOOption) tenantInviteQuery { _tenantInviteQuery.TenantID = field.NewInt64(tableName, "tenant_id") _tenantInviteQuery.UserID = field.NewInt64(tableName, "user_id") _tenantInviteQuery.Code = field.NewString(tableName, "code") - _tenantInviteQuery.Status = field.NewField(tableName, "status") + _tenantInviteQuery.Status = field.NewString(tableName, "status") _tenantInviteQuery.MaxUses = field.NewInt32(tableName, "max_uses") _tenantInviteQuery.UsedCount = field.NewInt32(tableName, "used_count") _tenantInviteQuery.ExpiresAt = field.NewTime(tableName, "expires_at") @@ -48,19 +48,19 @@ type tenantInviteQuery struct { tenantInviteQueryDo tenantInviteQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID field.Int64 // 创建人用户ID:生成邀请码的租户管理员(审计用) - Code field.String // 邀请码:用户加入租户时提交;同一租户内唯一 - Status field.Field // 邀请状态:active/disabled/expired;expired 也可由 expires_at 推导,业务侧需保持一致 - MaxUses field.Int32 // 最大可使用次数:0 表示不限制;>0 时 used_count 达到该值后视为失效 - UsedCount field.Int32 // 已使用次数:每次成功加入时 +1;需事务保证并发下不超发 - ExpiresAt field.Time // 过期时间:到期后不可再使用(UTC);为空表示不过期 - DisabledAt field.Time // 禁用时间:租户管理员禁用该邀请的时间(UTC) - DisabledOperatorUserID field.Int64 // 禁用操作人用户ID:租户管理员(审计用) - Remark field.String // 备注:生成/禁用原因等(审计用) - CreatedAt field.Time // 创建时间:默认 now() - UpdatedAt field.Time // 更新时间:默认 now() + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Code field.String + Status field.String + MaxUses field.Int32 + UsedCount field.Int32 + ExpiresAt field.Time + DisabledAt field.Time + DisabledOperatorUserID field.Int64 + Remark field.String + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -81,7 +81,7 @@ func (t *tenantInviteQuery) updateTableName(table string) *tenantInviteQuery { t.TenantID = field.NewInt64(table, "tenant_id") t.UserID = field.NewInt64(table, "user_id") t.Code = field.NewString(table, "code") - t.Status = field.NewField(table, "status") + t.Status = field.NewString(table, "status") t.MaxUses = field.NewInt32(table, "max_uses") t.UsedCount = field.NewInt32(table, "used_count") t.ExpiresAt = field.NewTime(table, "expires_at") diff --git a/backend/database/models/tenant_join_requests.gen.go b/backend/database/models/tenant_join_requests.gen.go index 7c9a77c..916d79d 100644 --- a/backend/database/models/tenant_join_requests.gen.go +++ b/backend/database/models/tenant_join_requests.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" ) @@ -17,16 +15,16 @@ const TableNameTenantJoinRequest = "tenant_join_requests" // TenantJoinRequest mapped from table type TenantJoinRequest struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id" json:"tenant_id"` // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:申请人用户ID:发起加入申请的用户" json:"user_id"` // 申请人用户ID:发起加入申请的用户 - Status consts.TenantJoinRequestStatus `gorm:"column:status;type:character varying(32);not null;default:pending;comment:申请状态:pending/approved/rejected;状态变更需记录 decided_at 与 decided_operator_user_id" json:"status"` // 申请状态:pending/approved/rejected;状态变更需记录 decided_at 与 decided_operator_user_id - Reason string `gorm:"column:reason;type:character varying(255);not null;comment:申请原因:用户填写的加入说明(可选)" json:"reason"` // 申请原因:用户填写的加入说明(可选) - DecidedAt time.Time `gorm:"column:decided_at;type:timestamp with time zone;comment:处理时间:审核通过/拒绝时记录(UTC)" json:"decided_at"` // 处理时间:审核通过/拒绝时记录(UTC) - DecidedOperatorUserID int64 `gorm:"column:decided_operator_user_id;type:bigint;comment:处理人用户ID:租户管理员(审计用)" json:"decided_operator_user_id"` // 处理人用户ID:租户管理员(审计用) - DecidedReason string `gorm:"column:decided_reason;type:character varying(255);not null;comment:处理说明:管理员通过/拒绝的原因(可选,审计用)" json:"decided_reason"` // 处理说明:管理员通过/拒绝的原因(可选,审计用) - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now()" json:"created_at"` // 创建时间:默认 now() - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now()" json:"updated_at"` // 更新时间:默认 now() + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Status string `gorm:"column:status;type:character varying(32);default:pending" json:"status"` + Reason string `gorm:"column:reason;type:character varying(255);not null" json:"reason"` + DecidedAt time.Time `gorm:"column:decided_at;type:timestamp with time zone" json:"decided_at"` + DecidedOperatorUserID int64 `gorm:"column:decided_operator_user_id;type:bigint" json:"decided_operator_user_id"` + DecidedReason string `gorm:"column:decided_reason;type:character varying(255)" json:"decided_reason"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/tenant_join_requests.query.gen.go b/backend/database/models/tenant_join_requests.query.gen.go index dd60551..1db1fb2 100644 --- a/backend/database/models/tenant_join_requests.query.gen.go +++ b/backend/database/models/tenant_join_requests.query.gen.go @@ -28,7 +28,7 @@ func newTenantJoinRequest(db *gorm.DB, opts ...gen.DOOption) tenantJoinRequestQu _tenantJoinRequestQuery.ID = field.NewInt64(tableName, "id") _tenantJoinRequestQuery.TenantID = field.NewInt64(tableName, "tenant_id") _tenantJoinRequestQuery.UserID = field.NewInt64(tableName, "user_id") - _tenantJoinRequestQuery.Status = field.NewField(tableName, "status") + _tenantJoinRequestQuery.Status = field.NewString(tableName, "status") _tenantJoinRequestQuery.Reason = field.NewString(tableName, "reason") _tenantJoinRequestQuery.DecidedAt = field.NewTime(tableName, "decided_at") _tenantJoinRequestQuery.DecidedOperatorUserID = field.NewInt64(tableName, "decided_operator_user_id") @@ -45,16 +45,16 @@ type tenantJoinRequestQuery struct { tenantJoinRequestQueryDo tenantJoinRequestQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;所有查询/写入必须限定 tenant_id - UserID field.Int64 // 申请人用户ID:发起加入申请的用户 - Status field.Field // 申请状态:pending/approved/rejected;状态变更需记录 decided_at 与 decided_operator_user_id - Reason field.String // 申请原因:用户填写的加入说明(可选) - DecidedAt field.Time // 处理时间:审核通过/拒绝时记录(UTC) - DecidedOperatorUserID field.Int64 // 处理人用户ID:租户管理员(审计用) - DecidedReason field.String // 处理说明:管理员通过/拒绝的原因(可选,审计用) - CreatedAt field.Time // 创建时间:默认 now() - UpdatedAt field.Time // 更新时间:默认 now() + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Status field.String + Reason field.String + DecidedAt field.Time + DecidedOperatorUserID field.Int64 + DecidedReason field.String + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -74,7 +74,7 @@ func (t *tenantJoinRequestQuery) updateTableName(table string) *tenantJoinReques t.ID = field.NewInt64(table, "id") t.TenantID = field.NewInt64(table, "tenant_id") t.UserID = field.NewInt64(table, "user_id") - t.Status = field.NewField(table, "status") + t.Status = field.NewString(table, "status") t.Reason = field.NewString(table, "reason") t.DecidedAt = field.NewTime(table, "decided_at") t.DecidedOperatorUserID = field.NewInt64(table, "decided_operator_user_id") diff --git a/backend/database/models/tenant_ledgers.gen.go b/backend/database/models/tenant_ledgers.gen.go index 1a1fceb..da7b79c 100644 --- a/backend/database/models/tenant_ledgers.gen.go +++ b/backend/database/models/tenant_ledgers.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" ) @@ -17,24 +15,23 @@ const TableNameTenantLedger = "tenant_ledgers" // TenantLedger mapped from table type TenantLedger struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true;comment:主键ID:自增" json:"id"` // 主键ID:自增 - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null;comment:租户ID:多租户隔离关键字段;必须与 tenant_users.tenant_id 一致" json:"tenant_id"` // 租户ID:多租户隔离关键字段;必须与 tenant_users.tenant_id 一致 - UserID int64 `gorm:"column:user_id;type:bigint;not null;comment:用户ID:余额账户归属用户;对应 tenant_users.user_id" json:"user_id"` // 用户ID:余额账户归属用户;对应 tenant_users.user_id - OrderID int64 `gorm:"column:order_id;type:bigint;comment:关联订单ID:购买/退款类流水应关联 orders.id;非订单类可为空" json:"order_id"` // 关联订单ID:购买/退款类流水应关联 orders.id;非订单类可为空 - Type consts.TenantLedgerType `gorm:"column:type;type:character varying(32);not null;comment:流水类型:debit_purchase/credit_refund/freeze/unfreeze/adjustment;不同类型决定余额/冻结余额的变更方向" json:"type"` // 流水类型:debit_purchase/credit_refund/freeze/unfreeze/adjustment;不同类型决定余额/冻结余额的变更方向 - Amount int64 `gorm:"column:amount;type:bigint;not null;comment:流水金额:分/最小货币单位;通常为正数,方向由 type 决定(由业务层约束)" json:"amount"` // 流水金额:分/最小货币单位;通常为正数,方向由 type 决定(由业务层约束) - BalanceBefore int64 `gorm:"column:balance_before;type:bigint;not null;comment:变更前可用余额:用于审计与对账回放" json:"balance_before"` // 变更前可用余额:用于审计与对账回放 - BalanceAfter int64 `gorm:"column:balance_after;type:bigint;not null;comment:变更后可用余额:用于审计与对账回放" json:"balance_after"` // 变更后可用余额:用于审计与对账回放 - FrozenBefore int64 `gorm:"column:frozen_before;type:bigint;not null;comment:变更前冻结余额:用于审计与对账回放" json:"frozen_before"` // 变更前冻结余额:用于审计与对账回放 - FrozenAfter int64 `gorm:"column:frozen_after;type:bigint;not null;comment:变更后冻结余额:用于审计与对账回放" json:"frozen_after"` // 变更后冻结余额:用于审计与对账回放 - IdempotencyKey string `gorm:"column:idempotency_key;type:character varying(128);not null;comment:幂等键:同一租户同一用户同一业务操作固定;用于防止重复落账(建议由业务层生成)" json:"idempotency_key"` // 幂等键:同一租户同一用户同一业务操作固定;用于防止重复落账(建议由业务层生成) - Remark string `gorm:"column:remark;type:character varying(255);not null;comment:备注:业务说明/后台操作原因等;用于审计" json:"remark"` // 备注:业务说明/后台操作原因等;用于审计 - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now();comment:创建时间:默认 now()" json:"created_at"` // 创建时间:默认 now() - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now();comment:更新时间:默认 now()" json:"updated_at"` // 更新时间:默认 now() - OperatorUserID int64 `gorm:"column:operator_user_id;type:bigint;comment:操作者用户ID:谁触发该流水(admin/buyer/system);用于审计与追责;可为空(历史数据或无法识别时)" json:"operator_user_id"` // 操作者用户ID:谁触发该流水(admin/buyer/system);用于审计与追责;可为空(历史数据或无法识别时) - BizRefType string `gorm:"column:biz_ref_type;type:character varying(32);comment:业务引用类型:order/refund/etc;与 biz_ref_id 组成可选的结构化幂等/追溯键" json:"biz_ref_type"` // 业务引用类型:order/refund/etc;与 biz_ref_id 组成可选的结构化幂等/追溯键 - BizRefID int64 `gorm:"column:biz_ref_id;type:bigint;comment:业务引用ID:与 biz_ref_type 配合使用(例如 orders.id);用于对账与审计" json:"biz_ref_id"` // 业务引用ID:与 biz_ref_type 配合使用(例如 orders.id);用于对账与审计 - Order *Order `gorm:"foreignKey:OrderID;references:ID" json:"order,omitempty"` + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + OrderID int64 `gorm:"column:order_id;type:bigint" json:"order_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + Amount int64 `gorm:"column:amount;type:bigint;not null" json:"amount"` + BalanceBefore int64 `gorm:"column:balance_before;type:bigint;not null" json:"balance_before"` + BalanceAfter int64 `gorm:"column:balance_after;type:bigint;not null" json:"balance_after"` + FrozenBefore int64 `gorm:"column:frozen_before;type:bigint;not null" json:"frozen_before"` + FrozenAfter int64 `gorm:"column:frozen_after;type:bigint;not null" json:"frozen_after"` + IdempotencyKey string `gorm:"column:idempotency_key;type:character varying(128);not null" json:"idempotency_key"` + Remark string `gorm:"column:remark;type:character varying(255);not null" json:"remark"` + OperatorUserID int64 `gorm:"column:operator_user_id;type:bigint" json:"operator_user_id"` + BizRefType string `gorm:"column:biz_ref_type;type:character varying(32)" json:"biz_ref_type"` + BizRefID int64 `gorm:"column:biz_ref_id;type:bigint" json:"biz_ref_id"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/tenant_ledgers.query.gen.go b/backend/database/models/tenant_ledgers.query.gen.go index 9a90810..8d4c296 100644 --- a/backend/database/models/tenant_ledgers.query.gen.go +++ b/backend/database/models/tenant_ledgers.query.gen.go @@ -29,7 +29,7 @@ func newTenantLedger(db *gorm.DB, opts ...gen.DOOption) tenantLedgerQuery { _tenantLedgerQuery.TenantID = field.NewInt64(tableName, "tenant_id") _tenantLedgerQuery.UserID = field.NewInt64(tableName, "user_id") _tenantLedgerQuery.OrderID = field.NewInt64(tableName, "order_id") - _tenantLedgerQuery.Type = field.NewField(tableName, "type") + _tenantLedgerQuery.Type = field.NewString(tableName, "type") _tenantLedgerQuery.Amount = field.NewInt64(tableName, "amount") _tenantLedgerQuery.BalanceBefore = field.NewInt64(tableName, "balance_before") _tenantLedgerQuery.BalanceAfter = field.NewInt64(tableName, "balance_after") @@ -37,16 +37,11 @@ func newTenantLedger(db *gorm.DB, opts ...gen.DOOption) tenantLedgerQuery { _tenantLedgerQuery.FrozenAfter = field.NewInt64(tableName, "frozen_after") _tenantLedgerQuery.IdempotencyKey = field.NewString(tableName, "idempotency_key") _tenantLedgerQuery.Remark = field.NewString(tableName, "remark") - _tenantLedgerQuery.CreatedAt = field.NewTime(tableName, "created_at") - _tenantLedgerQuery.UpdatedAt = field.NewTime(tableName, "updated_at") _tenantLedgerQuery.OperatorUserID = field.NewInt64(tableName, "operator_user_id") _tenantLedgerQuery.BizRefType = field.NewString(tableName, "biz_ref_type") _tenantLedgerQuery.BizRefID = field.NewInt64(tableName, "biz_ref_id") - _tenantLedgerQuery.Order = tenantLedgerQueryBelongsToOrder{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Order", "Order"), - } + _tenantLedgerQuery.CreatedAt = field.NewTime(tableName, "created_at") + _tenantLedgerQuery.UpdatedAt = field.NewTime(tableName, "updated_at") _tenantLedgerQuery.fillFieldMap() @@ -57,24 +52,23 @@ type tenantLedgerQuery struct { tenantLedgerQueryDo tenantLedgerQueryDo ALL field.Asterisk - ID field.Int64 // 主键ID:自增 - TenantID field.Int64 // 租户ID:多租户隔离关键字段;必须与 tenant_users.tenant_id 一致 - UserID field.Int64 // 用户ID:余额账户归属用户;对应 tenant_users.user_id - OrderID field.Int64 // 关联订单ID:购买/退款类流水应关联 orders.id;非订单类可为空 - Type field.Field // 流水类型:debit_purchase/credit_refund/freeze/unfreeze/adjustment;不同类型决定余额/冻结余额的变更方向 - Amount field.Int64 // 流水金额:分/最小货币单位;通常为正数,方向由 type 决定(由业务层约束) - BalanceBefore field.Int64 // 变更前可用余额:用于审计与对账回放 - BalanceAfter field.Int64 // 变更后可用余额:用于审计与对账回放 - FrozenBefore field.Int64 // 变更前冻结余额:用于审计与对账回放 - FrozenAfter field.Int64 // 变更后冻结余额:用于审计与对账回放 - IdempotencyKey field.String // 幂等键:同一租户同一用户同一业务操作固定;用于防止重复落账(建议由业务层生成) - Remark field.String // 备注:业务说明/后台操作原因等;用于审计 - CreatedAt field.Time // 创建时间:默认 now() - UpdatedAt field.Time // 更新时间:默认 now() - OperatorUserID field.Int64 // 操作者用户ID:谁触发该流水(admin/buyer/system);用于审计与追责;可为空(历史数据或无法识别时) - BizRefType field.String // 业务引用类型:order/refund/etc;与 biz_ref_id 组成可选的结构化幂等/追溯键 - BizRefID field.Int64 // 业务引用ID:与 biz_ref_type 配合使用(例如 orders.id);用于对账与审计 - Order tenantLedgerQueryBelongsToOrder + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + OrderID field.Int64 + Type field.String + Amount field.Int64 + BalanceBefore field.Int64 + BalanceAfter field.Int64 + FrozenBefore field.Int64 + FrozenAfter field.Int64 + IdempotencyKey field.String + Remark field.String + OperatorUserID field.Int64 + BizRefType field.String + BizRefID field.Int64 + CreatedAt field.Time + UpdatedAt field.Time fieldMap map[string]field.Expr } @@ -95,7 +89,7 @@ func (t *tenantLedgerQuery) updateTableName(table string) *tenantLedgerQuery { t.TenantID = field.NewInt64(table, "tenant_id") t.UserID = field.NewInt64(table, "user_id") t.OrderID = field.NewInt64(table, "order_id") - t.Type = field.NewField(table, "type") + t.Type = field.NewString(table, "type") t.Amount = field.NewInt64(table, "amount") t.BalanceBefore = field.NewInt64(table, "balance_before") t.BalanceAfter = field.NewInt64(table, "balance_after") @@ -103,11 +97,11 @@ func (t *tenantLedgerQuery) updateTableName(table string) *tenantLedgerQuery { t.FrozenAfter = field.NewInt64(table, "frozen_after") t.IdempotencyKey = field.NewString(table, "idempotency_key") t.Remark = field.NewString(table, "remark") - t.CreatedAt = field.NewTime(table, "created_at") - t.UpdatedAt = field.NewTime(table, "updated_at") t.OperatorUserID = field.NewInt64(table, "operator_user_id") t.BizRefType = field.NewString(table, "biz_ref_type") t.BizRefID = field.NewInt64(table, "biz_ref_id") + t.CreatedAt = field.NewTime(table, "created_at") + t.UpdatedAt = field.NewTime(table, "updated_at") t.fillFieldMap() @@ -140,7 +134,7 @@ func (t *tenantLedgerQuery) GetFieldByName(fieldName string) (field.OrderExpr, b } func (t *tenantLedgerQuery) fillFieldMap() { - t.fieldMap = make(map[string]field.Expr, 18) + t.fieldMap = make(map[string]field.Expr, 17) t.fieldMap["id"] = t.ID t.fieldMap["tenant_id"] = t.TenantID t.fieldMap["user_id"] = t.UserID @@ -153,108 +147,23 @@ func (t *tenantLedgerQuery) fillFieldMap() { t.fieldMap["frozen_after"] = t.FrozenAfter t.fieldMap["idempotency_key"] = t.IdempotencyKey t.fieldMap["remark"] = t.Remark - t.fieldMap["created_at"] = t.CreatedAt - t.fieldMap["updated_at"] = t.UpdatedAt t.fieldMap["operator_user_id"] = t.OperatorUserID t.fieldMap["biz_ref_type"] = t.BizRefType t.fieldMap["biz_ref_id"] = t.BizRefID - + t.fieldMap["created_at"] = t.CreatedAt + t.fieldMap["updated_at"] = t.UpdatedAt } func (t tenantLedgerQuery) clone(db *gorm.DB) tenantLedgerQuery { t.tenantLedgerQueryDo.ReplaceConnPool(db.Statement.ConnPool) - t.Order.db = db.Session(&gorm.Session{Initialized: true}) - t.Order.db.Statement.ConnPool = db.Statement.ConnPool return t } func (t tenantLedgerQuery) replaceDB(db *gorm.DB) tenantLedgerQuery { t.tenantLedgerQueryDo.ReplaceDB(db) - t.Order.db = db.Session(&gorm.Session{}) return t } -type tenantLedgerQueryBelongsToOrder struct { - db *gorm.DB - - field.RelationField -} - -func (a tenantLedgerQueryBelongsToOrder) Where(conds ...field.Expr) *tenantLedgerQueryBelongsToOrder { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a tenantLedgerQueryBelongsToOrder) WithContext(ctx context.Context) *tenantLedgerQueryBelongsToOrder { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a tenantLedgerQueryBelongsToOrder) Session(session *gorm.Session) *tenantLedgerQueryBelongsToOrder { - a.db = a.db.Session(session) - return &a -} - -func (a tenantLedgerQueryBelongsToOrder) Model(m *TenantLedger) *tenantLedgerQueryBelongsToOrderTx { - return &tenantLedgerQueryBelongsToOrderTx{a.db.Model(m).Association(a.Name())} -} - -func (a tenantLedgerQueryBelongsToOrder) Unscoped() *tenantLedgerQueryBelongsToOrder { - a.db = a.db.Unscoped() - return &a -} - -type tenantLedgerQueryBelongsToOrderTx struct{ tx *gorm.Association } - -func (a tenantLedgerQueryBelongsToOrderTx) Find() (result *Order, err error) { - return result, a.tx.Find(&result) -} - -func (a tenantLedgerQueryBelongsToOrderTx) Append(values ...*Order) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a tenantLedgerQueryBelongsToOrderTx) Replace(values ...*Order) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a tenantLedgerQueryBelongsToOrderTx) Delete(values ...*Order) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a tenantLedgerQueryBelongsToOrderTx) Clear() error { - return a.tx.Clear() -} - -func (a tenantLedgerQueryBelongsToOrderTx) Count() int64 { - return a.tx.Count() -} - -func (a tenantLedgerQueryBelongsToOrderTx) Unscoped() *tenantLedgerQueryBelongsToOrderTx { - a.tx = a.tx.Unscoped() - return &a -} - type tenantLedgerQueryDo struct{ gen.DO } func (t tenantLedgerQueryDo) Debug() *tenantLedgerQueryDo { diff --git a/backend/database/models/tenant_users.gen.go b/backend/database/models/tenant_users.gen.go index a20a838..66dac9b 100644 --- a/backend/database/models/tenant_users.gen.go +++ b/backend/database/models/tenant_users.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" ) @@ -18,13 +16,13 @@ const TableNameTenantUser = "tenant_users" // TenantUser mapped from table type TenantUser struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` - TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` - UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` - Role types.Array[consts.TenantUserRole] `gorm:"column:role;type:text[];not null;default:ARRAY['member" json:"role"` - Status consts.UserStatus `gorm:"column:status;type:character varying(50);not null;default:verified" json:"status"` - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now()" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now()" json:"updated_at"` + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Role types.Array[string] `gorm:"column:role;type:text[];default:{member}" json:"role"` + Status string `gorm:"column:status;type:character varying(50);default:verified" json:"status"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/tenant_users.query.gen.go b/backend/database/models/tenant_users.query.gen.go index 7b3cf42..1e54b07 100644 --- a/backend/database/models/tenant_users.query.gen.go +++ b/backend/database/models/tenant_users.query.gen.go @@ -29,7 +29,7 @@ func newTenantUser(db *gorm.DB, opts ...gen.DOOption) tenantUserQuery { _tenantUserQuery.TenantID = field.NewInt64(tableName, "tenant_id") _tenantUserQuery.UserID = field.NewInt64(tableName, "user_id") _tenantUserQuery.Role = field.NewArray(tableName, "role") - _tenantUserQuery.Status = field.NewField(tableName, "status") + _tenantUserQuery.Status = field.NewString(tableName, "status") _tenantUserQuery.CreatedAt = field.NewTime(tableName, "created_at") _tenantUserQuery.UpdatedAt = field.NewTime(tableName, "updated_at") @@ -46,7 +46,7 @@ type tenantUserQuery struct { TenantID field.Int64 UserID field.Int64 Role field.Array - Status field.Field + Status field.String CreatedAt field.Time UpdatedAt field.Time @@ -69,7 +69,7 @@ func (t *tenantUserQuery) updateTableName(table string) *tenantUserQuery { t.TenantID = field.NewInt64(table, "tenant_id") t.UserID = field.NewInt64(table, "user_id") t.Role = field.NewArray(table, "role") - t.Status = field.NewField(table, "status") + t.Status = field.NewString(table, "status") t.CreatedAt = field.NewTime(table, "created_at") t.UpdatedAt = field.NewTime(table, "updated_at") diff --git a/backend/database/models/tenants.gen.go b/backend/database/models/tenants.gen.go index f0ddca8..359dbe8 100644 --- a/backend/database/models/tenants.gen.go +++ b/backend/database/models/tenants.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" ) @@ -18,17 +16,16 @@ const TableNameTenant = "tenants" // Tenant mapped from table type Tenant struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` - UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` - Code string `gorm:"column:code;type:character varying(64);not null" json:"code"` - UUID types.UUID `gorm:"column:uuid;type:uuid;not null" json:"uuid"` - Name string `gorm:"column:name;type:character varying(128);not null" json:"name"` - Status consts.TenantStatus `gorm:"column:status;type:character varying(64);not null" json:"status"` - Config types.JSON `gorm:"column:config;type:jsonb;not null;default:{}" json:"config"` - ExpiredAt time.Time `gorm:"column:expired_at;type:timestamp with time zone" json:"expired_at"` - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now()" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now()" json:"updated_at"` - Users []*User `gorm:"joinForeignKey:TenantID;joinReferences:UserID;many2many:tenant_users" json:"users,omitempty"` + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Code string `gorm:"column:code;type:character varying(64);not null" json:"code"` + UUID types.UUID `gorm:"column:uuid;type:uuid;not null" json:"uuid"` + Name string `gorm:"column:name;type:character varying(128);not null" json:"name"` + Status string `gorm:"column:status;type:character varying(64);not null" json:"status"` + Config types.JSON `gorm:"column:config;type:jsonb;default:{}" json:"config"` + ExpiredAt time.Time `gorm:"column:expired_at;type:timestamp with time zone" json:"expired_at"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` } // Quick operations without importing query package diff --git a/backend/database/models/tenants.query.gen.go b/backend/database/models/tenants.query.gen.go index eee716b..ef4497f 100644 --- a/backend/database/models/tenants.query.gen.go +++ b/backend/database/models/tenants.query.gen.go @@ -30,16 +30,11 @@ func newTenant(db *gorm.DB, opts ...gen.DOOption) tenantQuery { _tenantQuery.Code = field.NewString(tableName, "code") _tenantQuery.UUID = field.NewField(tableName, "uuid") _tenantQuery.Name = field.NewString(tableName, "name") - _tenantQuery.Status = field.NewField(tableName, "status") + _tenantQuery.Status = field.NewString(tableName, "status") _tenantQuery.Config = field.NewJSONB(tableName, "config") _tenantQuery.ExpiredAt = field.NewTime(tableName, "expired_at") _tenantQuery.CreatedAt = field.NewTime(tableName, "created_at") _tenantQuery.UpdatedAt = field.NewTime(tableName, "updated_at") - _tenantQuery.Users = tenantQueryManyToManyUsers{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Users", "User"), - } _tenantQuery.fillFieldMap() @@ -55,12 +50,11 @@ type tenantQuery struct { Code field.String UUID field.Field Name field.String - Status field.Field + Status field.String Config field.JSONB ExpiredAt field.Time CreatedAt field.Time UpdatedAt field.Time - Users tenantQueryManyToManyUsers fieldMap map[string]field.Expr } @@ -82,7 +76,7 @@ func (t *tenantQuery) updateTableName(table string) *tenantQuery { t.Code = field.NewString(table, "code") t.UUID = field.NewField(table, "uuid") t.Name = field.NewString(table, "name") - t.Status = field.NewField(table, "status") + t.Status = field.NewString(table, "status") t.Config = field.NewJSONB(table, "config") t.ExpiredAt = field.NewTime(table, "expired_at") t.CreatedAt = field.NewTime(table, "created_at") @@ -117,7 +111,7 @@ func (t *tenantQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { } func (t *tenantQuery) fillFieldMap() { - t.fieldMap = make(map[string]field.Expr, 11) + t.fieldMap = make(map[string]field.Expr, 10) t.fieldMap["id"] = t.ID t.fieldMap["user_id"] = t.UserID t.fieldMap["code"] = t.Code @@ -128,103 +122,18 @@ func (t *tenantQuery) fillFieldMap() { t.fieldMap["expired_at"] = t.ExpiredAt t.fieldMap["created_at"] = t.CreatedAt t.fieldMap["updated_at"] = t.UpdatedAt - } func (t tenantQuery) clone(db *gorm.DB) tenantQuery { t.tenantQueryDo.ReplaceConnPool(db.Statement.ConnPool) - t.Users.db = db.Session(&gorm.Session{Initialized: true}) - t.Users.db.Statement.ConnPool = db.Statement.ConnPool return t } func (t tenantQuery) replaceDB(db *gorm.DB) tenantQuery { t.tenantQueryDo.ReplaceDB(db) - t.Users.db = db.Session(&gorm.Session{}) return t } -type tenantQueryManyToManyUsers struct { - db *gorm.DB - - field.RelationField -} - -func (a tenantQueryManyToManyUsers) Where(conds ...field.Expr) *tenantQueryManyToManyUsers { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a tenantQueryManyToManyUsers) WithContext(ctx context.Context) *tenantQueryManyToManyUsers { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a tenantQueryManyToManyUsers) Session(session *gorm.Session) *tenantQueryManyToManyUsers { - a.db = a.db.Session(session) - return &a -} - -func (a tenantQueryManyToManyUsers) Model(m *Tenant) *tenantQueryManyToManyUsersTx { - return &tenantQueryManyToManyUsersTx{a.db.Model(m).Association(a.Name())} -} - -func (a tenantQueryManyToManyUsers) Unscoped() *tenantQueryManyToManyUsers { - a.db = a.db.Unscoped() - return &a -} - -type tenantQueryManyToManyUsersTx struct{ tx *gorm.Association } - -func (a tenantQueryManyToManyUsersTx) Find() (result []*User, err error) { - return result, a.tx.Find(&result) -} - -func (a tenantQueryManyToManyUsersTx) Append(values ...*User) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a tenantQueryManyToManyUsersTx) Replace(values ...*User) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a tenantQueryManyToManyUsersTx) Delete(values ...*User) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a tenantQueryManyToManyUsersTx) Clear() error { - return a.tx.Clear() -} - -func (a tenantQueryManyToManyUsersTx) Count() int64 { - return a.tx.Count() -} - -func (a tenantQueryManyToManyUsersTx) Unscoped() *tenantQueryManyToManyUsersTx { - a.tx = a.tx.Unscoped() - return &a -} - type tenantQueryDo struct{ gen.DO } func (t tenantQueryDo) Debug() *tenantQueryDo { diff --git a/backend/database/models/user_comment_actions.gen.go b/backend/database/models/user_comment_actions.gen.go new file mode 100644 index 0000000..174be0c --- /dev/null +++ b/backend/database/models/user_comment_actions.gen.go @@ -0,0 +1,59 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameUserCommentAction = "user_comment_actions" + +// UserCommentAction mapped from table +type UserCommentAction struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + CommentID int64 `gorm:"column:comment_id;type:bigint;not null" json:"comment_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *UserCommentAction) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserCommentAction.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *UserCommentAction) Save(ctx context.Context) error { + return Q.UserCommentAction.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *UserCommentAction) Create(ctx context.Context) error { + return Q.UserCommentAction.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *UserCommentAction) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserCommentAction.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *UserCommentAction) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserCommentAction.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *UserCommentAction) Reload(ctx context.Context) error { + fresh, err := Q.UserCommentAction.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/user_comment_actions.query.gen.go b/backend/database/models/user_comment_actions.query.gen.go new file mode 100644 index 0000000..1798ff7 --- /dev/null +++ b/backend/database/models/user_comment_actions.query.gen.go @@ -0,0 +1,477 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newUserCommentAction(db *gorm.DB, opts ...gen.DOOption) userCommentActionQuery { + _userCommentActionQuery := userCommentActionQuery{} + + _userCommentActionQuery.userCommentActionQueryDo.UseDB(db, opts...) + _userCommentActionQuery.userCommentActionQueryDo.UseModel(&UserCommentAction{}) + + tableName := _userCommentActionQuery.userCommentActionQueryDo.TableName() + _userCommentActionQuery.ALL = field.NewAsterisk(tableName) + _userCommentActionQuery.ID = field.NewInt64(tableName, "id") + _userCommentActionQuery.UserID = field.NewInt64(tableName, "user_id") + _userCommentActionQuery.CommentID = field.NewInt64(tableName, "comment_id") + _userCommentActionQuery.Type = field.NewString(tableName, "type") + _userCommentActionQuery.CreatedAt = field.NewTime(tableName, "created_at") + + _userCommentActionQuery.fillFieldMap() + + return _userCommentActionQuery +} + +type userCommentActionQuery struct { + userCommentActionQueryDo userCommentActionQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + CommentID field.Int64 + Type field.String + CreatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (u userCommentActionQuery) Table(newTableName string) *userCommentActionQuery { + u.userCommentActionQueryDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userCommentActionQuery) As(alias string) *userCommentActionQuery { + u.userCommentActionQueryDo.DO = *(u.userCommentActionQueryDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userCommentActionQuery) updateTableName(table string) *userCommentActionQuery { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewInt64(table, "id") + u.UserID = field.NewInt64(table, "user_id") + u.CommentID = field.NewInt64(table, "comment_id") + u.Type = field.NewString(table, "type") + u.CreatedAt = field.NewTime(table, "created_at") + + u.fillFieldMap() + + return u +} + +func (u *userCommentActionQuery) QueryContext(ctx context.Context) (*userCommentActionQuery, *userCommentActionQueryDo) { + return u, u.userCommentActionQueryDo.WithContext(ctx) +} + +func (u *userCommentActionQuery) WithContext(ctx context.Context) *userCommentActionQueryDo { + return u.userCommentActionQueryDo.WithContext(ctx) +} + +func (u userCommentActionQuery) TableName() string { return u.userCommentActionQueryDo.TableName() } + +func (u userCommentActionQuery) Alias() string { return u.userCommentActionQueryDo.Alias() } + +func (u userCommentActionQuery) Columns(cols ...field.Expr) gen.Columns { + return u.userCommentActionQueryDo.Columns(cols...) +} + +func (u *userCommentActionQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := u.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (u *userCommentActionQuery) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 5) + u.fieldMap["id"] = u.ID + u.fieldMap["user_id"] = u.UserID + u.fieldMap["comment_id"] = u.CommentID + u.fieldMap["type"] = u.Type + u.fieldMap["created_at"] = u.CreatedAt +} + +func (u userCommentActionQuery) clone(db *gorm.DB) userCommentActionQuery { + u.userCommentActionQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userCommentActionQuery) replaceDB(db *gorm.DB) userCommentActionQuery { + u.userCommentActionQueryDo.ReplaceDB(db) + return u +} + +type userCommentActionQueryDo struct{ gen.DO } + +func (u userCommentActionQueryDo) Debug() *userCommentActionQueryDo { + return u.withDO(u.DO.Debug()) +} + +func (u userCommentActionQueryDo) WithContext(ctx context.Context) *userCommentActionQueryDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userCommentActionQueryDo) ReadDB() *userCommentActionQueryDo { + return u.Clauses(dbresolver.Read) +} + +func (u userCommentActionQueryDo) WriteDB() *userCommentActionQueryDo { + return u.Clauses(dbresolver.Write) +} + +func (u userCommentActionQueryDo) Session(config *gorm.Session) *userCommentActionQueryDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userCommentActionQueryDo) Clauses(conds ...clause.Expression) *userCommentActionQueryDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userCommentActionQueryDo) Returning(value interface{}, columns ...string) *userCommentActionQueryDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userCommentActionQueryDo) Not(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userCommentActionQueryDo) Or(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userCommentActionQueryDo) Select(conds ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userCommentActionQueryDo) Where(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userCommentActionQueryDo) Order(conds ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userCommentActionQueryDo) Distinct(cols ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userCommentActionQueryDo) Omit(cols ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userCommentActionQueryDo) Join(table schema.Tabler, on ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userCommentActionQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userCommentActionQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userCommentActionQueryDo) Group(cols ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userCommentActionQueryDo) Having(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userCommentActionQueryDo) Limit(limit int) *userCommentActionQueryDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userCommentActionQueryDo) Offset(offset int) *userCommentActionQueryDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userCommentActionQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userCommentActionQueryDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userCommentActionQueryDo) Unscoped() *userCommentActionQueryDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userCommentActionQueryDo) Create(values ...*UserCommentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userCommentActionQueryDo) CreateInBatches(values []*UserCommentAction, batchSize int) error { + return u.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (u userCommentActionQueryDo) Save(values ...*UserCommentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userCommentActionQueryDo) First() (*UserCommentAction, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) Take() (*UserCommentAction, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) Last() (*UserCommentAction, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) Find() ([]*UserCommentAction, error) { + result, err := u.DO.Find() + return result.([]*UserCommentAction), err +} + +func (u userCommentActionQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*UserCommentAction, err error) { + buf := make([]*UserCommentAction, 0, batchSize) + err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (u userCommentActionQueryDo) FindInBatches(result *[]*UserCommentAction, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userCommentActionQueryDo) Attrs(attrs ...field.AssignExpr) *userCommentActionQueryDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userCommentActionQueryDo) Assign(attrs ...field.AssignExpr) *userCommentActionQueryDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userCommentActionQueryDo) Joins(fields ...field.RelationField) *userCommentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userCommentActionQueryDo) Preload(fields ...field.RelationField) *userCommentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userCommentActionQueryDo) FirstOrInit() (*UserCommentAction, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) FirstOrCreate() (*UserCommentAction, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) FindByPage(offset int, limit int) (result []*UserCommentAction, count int64, err error) { + result, err = u.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = u.Offset(-1).Limit(-1).Count() + return +} + +func (u userCommentActionQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = u.Count() + if err != nil { + return + } + + err = u.Offset(offset).Limit(limit).Scan(result) + return +} + +func (u userCommentActionQueryDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userCommentActionQueryDo) Delete(models ...*UserCommentAction) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (u userCommentActionQueryDo) ForceDelete() (gen.ResultInfo, error) { + return u.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (u userCommentActionQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (u userCommentActionQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (u userCommentActionQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (u userCommentActionQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (u userCommentActionQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (u userCommentActionQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (u userCommentActionQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := u.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (u userCommentActionQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := u.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (u userCommentActionQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(u.TableName(), "id") + if err := u.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (u userCommentActionQueryDo) GetByID(id int64) (*UserCommentAction, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (u userCommentActionQueryDo) GetByIDs(ids ...int64) ([]*UserCommentAction, error) { + if len(ids) == 0 { + return []*UserCommentAction{}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (u userCommentActionQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (u userCommentActionQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Delete() +} + +func (u *userCommentActionQueryDo) withDO(do gen.Dao) *userCommentActionQueryDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/backend/database/models/user_content_actions.gen.go b/backend/database/models/user_content_actions.gen.go new file mode 100644 index 0000000..c1eb247 --- /dev/null +++ b/backend/database/models/user_content_actions.gen.go @@ -0,0 +1,59 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameUserContentAction = "user_content_actions" + +// UserContentAction mapped from table +type UserContentAction struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *UserContentAction) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserContentAction.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *UserContentAction) Save(ctx context.Context) error { + return Q.UserContentAction.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *UserContentAction) Create(ctx context.Context) error { + return Q.UserContentAction.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *UserContentAction) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserContentAction.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *UserContentAction) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserContentAction.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *UserContentAction) Reload(ctx context.Context) error { + fresh, err := Q.UserContentAction.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/user_content_actions.query.gen.go b/backend/database/models/user_content_actions.query.gen.go new file mode 100644 index 0000000..54ce8a5 --- /dev/null +++ b/backend/database/models/user_content_actions.query.gen.go @@ -0,0 +1,477 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newUserContentAction(db *gorm.DB, opts ...gen.DOOption) userContentActionQuery { + _userContentActionQuery := userContentActionQuery{} + + _userContentActionQuery.userContentActionQueryDo.UseDB(db, opts...) + _userContentActionQuery.userContentActionQueryDo.UseModel(&UserContentAction{}) + + tableName := _userContentActionQuery.userContentActionQueryDo.TableName() + _userContentActionQuery.ALL = field.NewAsterisk(tableName) + _userContentActionQuery.ID = field.NewInt64(tableName, "id") + _userContentActionQuery.UserID = field.NewInt64(tableName, "user_id") + _userContentActionQuery.ContentID = field.NewInt64(tableName, "content_id") + _userContentActionQuery.Type = field.NewString(tableName, "type") + _userContentActionQuery.CreatedAt = field.NewTime(tableName, "created_at") + + _userContentActionQuery.fillFieldMap() + + return _userContentActionQuery +} + +type userContentActionQuery struct { + userContentActionQueryDo userContentActionQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + ContentID field.Int64 + Type field.String + CreatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (u userContentActionQuery) Table(newTableName string) *userContentActionQuery { + u.userContentActionQueryDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userContentActionQuery) As(alias string) *userContentActionQuery { + u.userContentActionQueryDo.DO = *(u.userContentActionQueryDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userContentActionQuery) updateTableName(table string) *userContentActionQuery { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewInt64(table, "id") + u.UserID = field.NewInt64(table, "user_id") + u.ContentID = field.NewInt64(table, "content_id") + u.Type = field.NewString(table, "type") + u.CreatedAt = field.NewTime(table, "created_at") + + u.fillFieldMap() + + return u +} + +func (u *userContentActionQuery) QueryContext(ctx context.Context) (*userContentActionQuery, *userContentActionQueryDo) { + return u, u.userContentActionQueryDo.WithContext(ctx) +} + +func (u *userContentActionQuery) WithContext(ctx context.Context) *userContentActionQueryDo { + return u.userContentActionQueryDo.WithContext(ctx) +} + +func (u userContentActionQuery) TableName() string { return u.userContentActionQueryDo.TableName() } + +func (u userContentActionQuery) Alias() string { return u.userContentActionQueryDo.Alias() } + +func (u userContentActionQuery) Columns(cols ...field.Expr) gen.Columns { + return u.userContentActionQueryDo.Columns(cols...) +} + +func (u *userContentActionQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := u.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (u *userContentActionQuery) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 5) + u.fieldMap["id"] = u.ID + u.fieldMap["user_id"] = u.UserID + u.fieldMap["content_id"] = u.ContentID + u.fieldMap["type"] = u.Type + u.fieldMap["created_at"] = u.CreatedAt +} + +func (u userContentActionQuery) clone(db *gorm.DB) userContentActionQuery { + u.userContentActionQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userContentActionQuery) replaceDB(db *gorm.DB) userContentActionQuery { + u.userContentActionQueryDo.ReplaceDB(db) + return u +} + +type userContentActionQueryDo struct{ gen.DO } + +func (u userContentActionQueryDo) Debug() *userContentActionQueryDo { + return u.withDO(u.DO.Debug()) +} + +func (u userContentActionQueryDo) WithContext(ctx context.Context) *userContentActionQueryDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userContentActionQueryDo) ReadDB() *userContentActionQueryDo { + return u.Clauses(dbresolver.Read) +} + +func (u userContentActionQueryDo) WriteDB() *userContentActionQueryDo { + return u.Clauses(dbresolver.Write) +} + +func (u userContentActionQueryDo) Session(config *gorm.Session) *userContentActionQueryDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userContentActionQueryDo) Clauses(conds ...clause.Expression) *userContentActionQueryDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userContentActionQueryDo) Returning(value interface{}, columns ...string) *userContentActionQueryDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userContentActionQueryDo) Not(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userContentActionQueryDo) Or(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userContentActionQueryDo) Select(conds ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userContentActionQueryDo) Where(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userContentActionQueryDo) Order(conds ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userContentActionQueryDo) Distinct(cols ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userContentActionQueryDo) Omit(cols ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userContentActionQueryDo) Join(table schema.Tabler, on ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userContentActionQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userContentActionQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userContentActionQueryDo) Group(cols ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userContentActionQueryDo) Having(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userContentActionQueryDo) Limit(limit int) *userContentActionQueryDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userContentActionQueryDo) Offset(offset int) *userContentActionQueryDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userContentActionQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userContentActionQueryDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userContentActionQueryDo) Unscoped() *userContentActionQueryDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userContentActionQueryDo) Create(values ...*UserContentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userContentActionQueryDo) CreateInBatches(values []*UserContentAction, batchSize int) error { + return u.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (u userContentActionQueryDo) Save(values ...*UserContentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userContentActionQueryDo) First() (*UserContentAction, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) Take() (*UserContentAction, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) Last() (*UserContentAction, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) Find() ([]*UserContentAction, error) { + result, err := u.DO.Find() + return result.([]*UserContentAction), err +} + +func (u userContentActionQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*UserContentAction, err error) { + buf := make([]*UserContentAction, 0, batchSize) + err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (u userContentActionQueryDo) FindInBatches(result *[]*UserContentAction, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userContentActionQueryDo) Attrs(attrs ...field.AssignExpr) *userContentActionQueryDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userContentActionQueryDo) Assign(attrs ...field.AssignExpr) *userContentActionQueryDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userContentActionQueryDo) Joins(fields ...field.RelationField) *userContentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userContentActionQueryDo) Preload(fields ...field.RelationField) *userContentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userContentActionQueryDo) FirstOrInit() (*UserContentAction, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) FirstOrCreate() (*UserContentAction, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) FindByPage(offset int, limit int) (result []*UserContentAction, count int64, err error) { + result, err = u.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = u.Offset(-1).Limit(-1).Count() + return +} + +func (u userContentActionQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = u.Count() + if err != nil { + return + } + + err = u.Offset(offset).Limit(limit).Scan(result) + return +} + +func (u userContentActionQueryDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userContentActionQueryDo) Delete(models ...*UserContentAction) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (u userContentActionQueryDo) ForceDelete() (gen.ResultInfo, error) { + return u.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (u userContentActionQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (u userContentActionQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (u userContentActionQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (u userContentActionQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (u userContentActionQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (u userContentActionQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (u userContentActionQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := u.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (u userContentActionQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := u.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (u userContentActionQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(u.TableName(), "id") + if err := u.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (u userContentActionQueryDo) GetByID(id int64) (*UserContentAction, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (u userContentActionQueryDo) GetByIDs(ids ...int64) ([]*UserContentAction, error) { + if len(ids) == 0 { + return []*UserContentAction{}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (u userContentActionQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (u userContentActionQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Delete() +} + +func (u *userContentActionQueryDo) withDO(do gen.Dao) *userContentActionQueryDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/backend/database/models/users.gen.go b/backend/database/models/users.gen.go index a70b227..4a5a2f5 100644 --- a/backend/database/models/users.gen.go +++ b/backend/database/models/users.gen.go @@ -8,8 +8,6 @@ import ( "context" "time" - "quyun/v2/pkg/consts" - "go.ipao.vip/gen" "go.ipao.vip/gen/types" "gorm.io/gorm" @@ -19,20 +17,27 @@ const TableNameUser = "users" // User mapped from table type User struct { - ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;not null;default:now()" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;not null;default:now()" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` - Username string `gorm:"column:username;type:character varying(255);not null" json:"username"` - Password string `gorm:"column:password;type:character varying(255);not null" json:"password"` - Roles types.Array[consts.Role] `gorm:"column:roles;type:text[];not null;default:ARRAY['user" json:"roles"` - Status consts.UserStatus `gorm:"column:status;type:character varying(50);not null;default:active" json:"status"` - Metas types.JSON `gorm:"column:metas;type:jsonb;not null;default:{}" json:"metas"` - Balance int64 `gorm:"column:balance;type:bigint;not null;comment:全局可用余额:分/最小货币单位;用户在所有已加入租户内共享该余额;默认 0" json:"balance"` // 全局可用余额:分/最小货币单位;用户在所有已加入租户内共享该余额;默认 0 - BalanceFrozen int64 `gorm:"column:balance_frozen;type:bigint;not null;comment:全局冻结余额:分/最小货币单位;用于下单冻结等;默认 0" json:"balance_frozen"` // 全局冻结余额:分/最小货币单位;用于下单冻结等;默认 0 - VerifiedAt time.Time `gorm:"column:verified_at;type:timestamp with time zone" json:"verified_at"` - OwnedTenant *Tenant `json:"owned,omitempty"` - Tenants []*Tenant `gorm:"joinForeignKey:UserID;joinReferences:TenantID;many2many:tenant_users" json:"tenants,omitempty"` + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + Username string `gorm:"column:username;type:character varying(255);not null" json:"username"` + Password string `gorm:"column:password;type:character varying(255);not null" json:"password"` + Roles types.Array[string] `gorm:"column:roles;type:text[];default:{user}" json:"roles"` + Status string `gorm:"column:status;type:character varying(50);default:active" json:"status"` + Metas types.JSON `gorm:"column:metas;type:jsonb;default:{}" json:"metas"` + Balance int64 `gorm:"column:balance;type:bigint" json:"balance"` + BalanceFrozen int64 `gorm:"column:balance_frozen;type:bigint" json:"balance_frozen"` + VerifiedAt time.Time `gorm:"column:verified_at;type:timestamp with time zone" json:"verified_at"` + Nickname string `gorm:"column:nickname;type:character varying(255)" json:"nickname"` + Avatar string `gorm:"column:avatar;type:character varying(512)" json:"avatar"` + Gender string `gorm:"column:gender;type:character varying(32);default:secret" json:"gender"` + Bio string `gorm:"column:bio;type:character varying(512)" json:"bio"` + Birthday types.Date `gorm:"column:birthday;type:date" json:"birthday"` + Location types.JSON `gorm:"column:location;type:jsonb;default:{}" json:"location"` + Points int64 `gorm:"column:points;type:bigint" json:"points"` + Phone string `gorm:"column:phone;type:character varying(32)" json:"phone"` + IsRealNameVerified bool `gorm:"column:is_real_name_verified;type:boolean" json:"is_real_name_verified"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` } // Quick operations without importing query package diff --git a/backend/database/models/users.query.gen.go b/backend/database/models/users.query.gen.go index 78100cd..03668b2 100644 --- a/backend/database/models/users.query.gen.go +++ b/backend/database/models/users.query.gen.go @@ -26,28 +26,26 @@ func newUser(db *gorm.DB, opts ...gen.DOOption) userQuery { tableName := _userQuery.userQueryDo.TableName() _userQuery.ALL = field.NewAsterisk(tableName) _userQuery.ID = field.NewInt64(tableName, "id") - _userQuery.CreatedAt = field.NewTime(tableName, "created_at") - _userQuery.UpdatedAt = field.NewTime(tableName, "updated_at") - _userQuery.DeletedAt = field.NewField(tableName, "deleted_at") _userQuery.Username = field.NewString(tableName, "username") _userQuery.Password = field.NewString(tableName, "password") _userQuery.Roles = field.NewArray(tableName, "roles") - _userQuery.Status = field.NewField(tableName, "status") + _userQuery.Status = field.NewString(tableName, "status") _userQuery.Metas = field.NewJSONB(tableName, "metas") _userQuery.Balance = field.NewInt64(tableName, "balance") _userQuery.BalanceFrozen = field.NewInt64(tableName, "balance_frozen") _userQuery.VerifiedAt = field.NewTime(tableName, "verified_at") - _userQuery.OwnedTenant = userQueryBelongsToOwnedTenant{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("OwnedTenant", "Tenant"), - } - - _userQuery.Tenants = userQueryManyToManyTenants{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Tenants", "Tenant"), - } + _userQuery.Nickname = field.NewString(tableName, "nickname") + _userQuery.Avatar = field.NewString(tableName, "avatar") + _userQuery.Gender = field.NewString(tableName, "gender") + _userQuery.Bio = field.NewString(tableName, "bio") + _userQuery.Birthday = field.NewField(tableName, "birthday") + _userQuery.Location = field.NewJSONB(tableName, "location") + _userQuery.Points = field.NewInt64(tableName, "points") + _userQuery.Phone = field.NewString(tableName, "phone") + _userQuery.IsRealNameVerified = field.NewBool(tableName, "is_real_name_verified") + _userQuery.CreatedAt = field.NewTime(tableName, "created_at") + _userQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _userQuery.DeletedAt = field.NewField(tableName, "deleted_at") _userQuery.fillFieldMap() @@ -57,22 +55,28 @@ func newUser(db *gorm.DB, opts ...gen.DOOption) userQuery { type userQuery struct { userQueryDo userQueryDo - ALL field.Asterisk - ID field.Int64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Username field.String - Password field.String - Roles field.Array - Status field.Field - Metas field.JSONB - Balance field.Int64 // 全局可用余额:分/最小货币单位;用户在所有已加入租户内共享该余额;默认 0 - BalanceFrozen field.Int64 // 全局冻结余额:分/最小货币单位;用于下单冻结等;默认 0 - VerifiedAt field.Time - OwnedTenant userQueryBelongsToOwnedTenant - - Tenants userQueryManyToManyTenants + ALL field.Asterisk + ID field.Int64 + Username field.String + Password field.String + Roles field.Array + Status field.String + Metas field.JSONB + Balance field.Int64 + BalanceFrozen field.Int64 + VerifiedAt field.Time + Nickname field.String + Avatar field.String + Gender field.String + Bio field.String + Birthday field.Field + Location field.JSONB + Points field.Int64 + Phone field.String + IsRealNameVerified field.Bool + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field fieldMap map[string]field.Expr } @@ -90,17 +94,26 @@ func (u userQuery) As(alias string) *userQuery { func (u *userQuery) updateTableName(table string) *userQuery { u.ALL = field.NewAsterisk(table) u.ID = field.NewInt64(table, "id") - u.CreatedAt = field.NewTime(table, "created_at") - u.UpdatedAt = field.NewTime(table, "updated_at") - u.DeletedAt = field.NewField(table, "deleted_at") u.Username = field.NewString(table, "username") u.Password = field.NewString(table, "password") u.Roles = field.NewArray(table, "roles") - u.Status = field.NewField(table, "status") + u.Status = field.NewString(table, "status") u.Metas = field.NewJSONB(table, "metas") u.Balance = field.NewInt64(table, "balance") u.BalanceFrozen = field.NewInt64(table, "balance_frozen") u.VerifiedAt = field.NewTime(table, "verified_at") + u.Nickname = field.NewString(table, "nickname") + u.Avatar = field.NewString(table, "avatar") + u.Gender = field.NewString(table, "gender") + u.Bio = field.NewString(table, "bio") + u.Birthday = field.NewField(table, "birthday") + u.Location = field.NewJSONB(table, "location") + u.Points = field.NewInt64(table, "points") + u.Phone = field.NewString(table, "phone") + u.IsRealNameVerified = field.NewBool(table, "is_real_name_verified") + u.CreatedAt = field.NewTime(table, "created_at") + u.UpdatedAt = field.NewTime(table, "updated_at") + u.DeletedAt = field.NewField(table, "deleted_at") u.fillFieldMap() @@ -131,11 +144,8 @@ func (u *userQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { } func (u *userQuery) fillFieldMap() { - u.fieldMap = make(map[string]field.Expr, 14) + u.fieldMap = make(map[string]field.Expr, 21) u.fieldMap["id"] = u.ID - u.fieldMap["created_at"] = u.CreatedAt - u.fieldMap["updated_at"] = u.UpdatedAt - u.fieldMap["deleted_at"] = u.DeletedAt u.fieldMap["username"] = u.Username u.fieldMap["password"] = u.Password u.fieldMap["roles"] = u.Roles @@ -144,187 +154,30 @@ func (u *userQuery) fillFieldMap() { u.fieldMap["balance"] = u.Balance u.fieldMap["balance_frozen"] = u.BalanceFrozen u.fieldMap["verified_at"] = u.VerifiedAt - + u.fieldMap["nickname"] = u.Nickname + u.fieldMap["avatar"] = u.Avatar + u.fieldMap["gender"] = u.Gender + u.fieldMap["bio"] = u.Bio + u.fieldMap["birthday"] = u.Birthday + u.fieldMap["location"] = u.Location + u.fieldMap["points"] = u.Points + u.fieldMap["phone"] = u.Phone + u.fieldMap["is_real_name_verified"] = u.IsRealNameVerified + u.fieldMap["created_at"] = u.CreatedAt + u.fieldMap["updated_at"] = u.UpdatedAt + u.fieldMap["deleted_at"] = u.DeletedAt } func (u userQuery) clone(db *gorm.DB) userQuery { u.userQueryDo.ReplaceConnPool(db.Statement.ConnPool) - u.OwnedTenant.db = db.Session(&gorm.Session{Initialized: true}) - u.OwnedTenant.db.Statement.ConnPool = db.Statement.ConnPool - u.Tenants.db = db.Session(&gorm.Session{Initialized: true}) - u.Tenants.db.Statement.ConnPool = db.Statement.ConnPool return u } func (u userQuery) replaceDB(db *gorm.DB) userQuery { u.userQueryDo.ReplaceDB(db) - u.OwnedTenant.db = db.Session(&gorm.Session{}) - u.Tenants.db = db.Session(&gorm.Session{}) return u } -type userQueryBelongsToOwnedTenant struct { - db *gorm.DB - - field.RelationField -} - -func (a userQueryBelongsToOwnedTenant) Where(conds ...field.Expr) *userQueryBelongsToOwnedTenant { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a userQueryBelongsToOwnedTenant) WithContext(ctx context.Context) *userQueryBelongsToOwnedTenant { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a userQueryBelongsToOwnedTenant) Session(session *gorm.Session) *userQueryBelongsToOwnedTenant { - a.db = a.db.Session(session) - return &a -} - -func (a userQueryBelongsToOwnedTenant) Model(m *User) *userQueryBelongsToOwnedTenantTx { - return &userQueryBelongsToOwnedTenantTx{a.db.Model(m).Association(a.Name())} -} - -func (a userQueryBelongsToOwnedTenant) Unscoped() *userQueryBelongsToOwnedTenant { - a.db = a.db.Unscoped() - return &a -} - -type userQueryBelongsToOwnedTenantTx struct{ tx *gorm.Association } - -func (a userQueryBelongsToOwnedTenantTx) Find() (result *Tenant, err error) { - return result, a.tx.Find(&result) -} - -func (a userQueryBelongsToOwnedTenantTx) Append(values ...*Tenant) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a userQueryBelongsToOwnedTenantTx) Replace(values ...*Tenant) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a userQueryBelongsToOwnedTenantTx) Delete(values ...*Tenant) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a userQueryBelongsToOwnedTenantTx) Clear() error { - return a.tx.Clear() -} - -func (a userQueryBelongsToOwnedTenantTx) Count() int64 { - return a.tx.Count() -} - -func (a userQueryBelongsToOwnedTenantTx) Unscoped() *userQueryBelongsToOwnedTenantTx { - a.tx = a.tx.Unscoped() - return &a -} - -type userQueryManyToManyTenants struct { - db *gorm.DB - - field.RelationField -} - -func (a userQueryManyToManyTenants) Where(conds ...field.Expr) *userQueryManyToManyTenants { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a userQueryManyToManyTenants) WithContext(ctx context.Context) *userQueryManyToManyTenants { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a userQueryManyToManyTenants) Session(session *gorm.Session) *userQueryManyToManyTenants { - a.db = a.db.Session(session) - return &a -} - -func (a userQueryManyToManyTenants) Model(m *User) *userQueryManyToManyTenantsTx { - return &userQueryManyToManyTenantsTx{a.db.Model(m).Association(a.Name())} -} - -func (a userQueryManyToManyTenants) Unscoped() *userQueryManyToManyTenants { - a.db = a.db.Unscoped() - return &a -} - -type userQueryManyToManyTenantsTx struct{ tx *gorm.Association } - -func (a userQueryManyToManyTenantsTx) Find() (result []*Tenant, err error) { - return result, a.tx.Find(&result) -} - -func (a userQueryManyToManyTenantsTx) Append(values ...*Tenant) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a userQueryManyToManyTenantsTx) Replace(values ...*Tenant) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a userQueryManyToManyTenantsTx) Delete(values ...*Tenant) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a userQueryManyToManyTenantsTx) Clear() error { - return a.tx.Clear() -} - -func (a userQueryManyToManyTenantsTx) Count() int64 { - return a.tx.Count() -} - -func (a userQueryManyToManyTenantsTx) Unscoped() *userQueryManyToManyTenantsTx { - a.tx = a.tx.Unscoped() - return &a -} - type userQueryDo struct{ gen.DO } func (u userQueryDo) Debug() *userQueryDo { diff --git a/backend/pkg/consts/api_enums.gen.go b/backend/pkg/consts/api_enums.gen.go new file mode 100644 index 0000000..4c949bd --- /dev/null +++ b/backend/pkg/consts/api_enums.gen.go @@ -0,0 +1,824 @@ +// Code generated by go-enum DO NOT EDIT. +// Version: - +// Revision: - +// Build Date: - +// Built By: - + +package consts + +import ( + "database/sql/driver" + "errors" + "fmt" + "strings" +) + +const ( + // GenderMale is a Gender of type male. + GenderMale Gender = "male" + // GenderFemale is a Gender of type female. + GenderFemale Gender = "female" + // GenderSecret is a Gender of type secret. + GenderSecret Gender = "secret" +) + +var ErrInvalidGender = fmt.Errorf("not a valid Gender, try [%s]", strings.Join(_GenderNames, ", ")) + +var _GenderNames = []string{ + string(GenderMale), + string(GenderFemale), + string(GenderSecret), +} + +// GenderNames returns a list of possible string values of Gender. +func GenderNames() []string { + tmp := make([]string, len(_GenderNames)) + copy(tmp, _GenderNames) + return tmp +} + +// GenderValues returns a list of the values for Gender +func GenderValues() []Gender { + return []Gender{ + GenderMale, + GenderFemale, + GenderSecret, + } +} + +// String implements the Stringer interface. +func (x Gender) String() string { + return string(x) +} + +// IsValid provides a quick way to determine if the typed value is +// part of the allowed enumerated values +func (x Gender) IsValid() bool { + _, err := ParseGender(string(x)) + return err == nil +} + +var _GenderValue = map[string]Gender{ + "male": GenderMale, + "female": GenderFemale, + "secret": GenderSecret, +} + +// ParseGender attempts to convert a string to a Gender. +func ParseGender(name string) (Gender, error) { + if x, ok := _GenderValue[name]; ok { + return x, nil + } + return Gender(""), fmt.Errorf("%s is %w", name, ErrInvalidGender) +} + +var errGenderNilPtr = errors.New("value pointer is nil") // one per type for package clashes + +// Scan implements the Scanner interface. +func (x *Gender) Scan(value interface{}) (err error) { + if value == nil { + *x = Gender("") + return + } + + // A wider range of scannable types. + // driver.Value values at the top of the list for expediency + switch v := value.(type) { + case string: + *x, err = ParseGender(v) + case []byte: + *x, err = ParseGender(string(v)) + case Gender: + *x = v + case *Gender: + if v == nil { + return errGenderNilPtr + } + *x = *v + case *string: + if v == nil { + return errGenderNilPtr + } + *x, err = ParseGender(*v) + default: + return errors.New("invalid type for Gender") + } + + return +} + +// Value implements the driver Valuer interface. +func (x Gender) Value() (driver.Value, error) { + return x.String(), nil +} + +// Set implements the Golang flag.Value interface func. +func (x *Gender) Set(val string) error { + v, err := ParseGender(val) + *x = v + return err +} + +// Get implements the Golang flag.Getter interface func. +func (x *Gender) Get() interface{} { + return *x +} + +// Type implements the github.com/spf13/pFlag Value interface. +func (x *Gender) Type() string { + return "Gender" +} + +type NullGender struct { + Gender Gender + Valid bool +} + +func NewNullGender(val interface{}) (x NullGender) { + err := x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + _ = err // make any errcheck linters happy + return +} + +// Scan implements the Scanner interface. +func (x *NullGender) Scan(value interface{}) (err error) { + if value == nil { + x.Gender, x.Valid = Gender(""), false + return + } + + err = x.Gender.Scan(value) + x.Valid = (err == nil) + return +} + +// Value implements the driver Valuer interface. +func (x NullGender) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + // driver.Value accepts int64 for int values. + return string(x.Gender), nil +} + +type NullGenderStr struct { + NullGender +} + +func NewNullGenderStr(val interface{}) (x NullGenderStr) { + x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + return +} + +// Value implements the driver Valuer interface. +func (x NullGenderStr) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + return x.Gender.String(), nil +} + +const ( + // NotificationTypeSystem is a NotificationType of type system. + NotificationTypeSystem NotificationType = "system" + // NotificationTypeOrder is a NotificationType of type order. + NotificationTypeOrder NotificationType = "order" + // NotificationTypeAudit is a NotificationType of type audit. + NotificationTypeAudit NotificationType = "audit" + // NotificationTypeInteraction is a NotificationType of type interaction. + NotificationTypeInteraction NotificationType = "interaction" +) + +var ErrInvalidNotificationType = fmt.Errorf("not a valid NotificationType, try [%s]", strings.Join(_NotificationTypeNames, ", ")) + +var _NotificationTypeNames = []string{ + string(NotificationTypeSystem), + string(NotificationTypeOrder), + string(NotificationTypeAudit), + string(NotificationTypeInteraction), +} + +// NotificationTypeNames returns a list of possible string values of NotificationType. +func NotificationTypeNames() []string { + tmp := make([]string, len(_NotificationTypeNames)) + copy(tmp, _NotificationTypeNames) + return tmp +} + +// NotificationTypeValues returns a list of the values for NotificationType +func NotificationTypeValues() []NotificationType { + return []NotificationType{ + NotificationTypeSystem, + NotificationTypeOrder, + NotificationTypeAudit, + NotificationTypeInteraction, + } +} + +// String implements the Stringer interface. +func (x NotificationType) String() string { + return string(x) +} + +// IsValid provides a quick way to determine if the typed value is +// part of the allowed enumerated values +func (x NotificationType) IsValid() bool { + _, err := ParseNotificationType(string(x)) + return err == nil +} + +var _NotificationTypeValue = map[string]NotificationType{ + "system": NotificationTypeSystem, + "order": NotificationTypeOrder, + "audit": NotificationTypeAudit, + "interaction": NotificationTypeInteraction, +} + +// ParseNotificationType attempts to convert a string to a NotificationType. +func ParseNotificationType(name string) (NotificationType, error) { + if x, ok := _NotificationTypeValue[name]; ok { + return x, nil + } + return NotificationType(""), fmt.Errorf("%s is %w", name, ErrInvalidNotificationType) +} + +var errNotificationTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes + +// Scan implements the Scanner interface. +func (x *NotificationType) Scan(value interface{}) (err error) { + if value == nil { + *x = NotificationType("") + return + } + + // A wider range of scannable types. + // driver.Value values at the top of the list for expediency + switch v := value.(type) { + case string: + *x, err = ParseNotificationType(v) + case []byte: + *x, err = ParseNotificationType(string(v)) + case NotificationType: + *x = v + case *NotificationType: + if v == nil { + return errNotificationTypeNilPtr + } + *x = *v + case *string: + if v == nil { + return errNotificationTypeNilPtr + } + *x, err = ParseNotificationType(*v) + default: + return errors.New("invalid type for NotificationType") + } + + return +} + +// Value implements the driver Valuer interface. +func (x NotificationType) Value() (driver.Value, error) { + return x.String(), nil +} + +// Set implements the Golang flag.Value interface func. +func (x *NotificationType) Set(val string) error { + v, err := ParseNotificationType(val) + *x = v + return err +} + +// Get implements the Golang flag.Getter interface func. +func (x *NotificationType) Get() interface{} { + return *x +} + +// Type implements the github.com/spf13/pFlag Value interface. +func (x *NotificationType) Type() string { + return "NotificationType" +} + +type NullNotificationType struct { + NotificationType NotificationType + Valid bool +} + +func NewNullNotificationType(val interface{}) (x NullNotificationType) { + err := x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + _ = err // make any errcheck linters happy + return +} + +// Scan implements the Scanner interface. +func (x *NullNotificationType) Scan(value interface{}) (err error) { + if value == nil { + x.NotificationType, x.Valid = NotificationType(""), false + return + } + + err = x.NotificationType.Scan(value) + x.Valid = (err == nil) + return +} + +// Value implements the driver Valuer interface. +func (x NullNotificationType) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + // driver.Value accepts int64 for int values. + return string(x.NotificationType), nil +} + +type NullNotificationTypeStr struct { + NullNotificationType +} + +func NewNullNotificationTypeStr(val interface{}) (x NullNotificationTypeStr) { + x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + return +} + +// Value implements the driver Valuer interface. +func (x NullNotificationTypeStr) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + return x.NotificationType.String(), nil +} + +const ( + // PayoutAccountTypeBank is a PayoutAccountType of type bank. + PayoutAccountTypeBank PayoutAccountType = "bank" + // PayoutAccountTypeAlipay is a PayoutAccountType of type alipay. + PayoutAccountTypeAlipay PayoutAccountType = "alipay" +) + +var ErrInvalidPayoutAccountType = fmt.Errorf("not a valid PayoutAccountType, try [%s]", strings.Join(_PayoutAccountTypeNames, ", ")) + +var _PayoutAccountTypeNames = []string{ + string(PayoutAccountTypeBank), + string(PayoutAccountTypeAlipay), +} + +// PayoutAccountTypeNames returns a list of possible string values of PayoutAccountType. +func PayoutAccountTypeNames() []string { + tmp := make([]string, len(_PayoutAccountTypeNames)) + copy(tmp, _PayoutAccountTypeNames) + return tmp +} + +// PayoutAccountTypeValues returns a list of the values for PayoutAccountType +func PayoutAccountTypeValues() []PayoutAccountType { + return []PayoutAccountType{ + PayoutAccountTypeBank, + PayoutAccountTypeAlipay, + } +} + +// String implements the Stringer interface. +func (x PayoutAccountType) String() string { + return string(x) +} + +// IsValid provides a quick way to determine if the typed value is +// part of the allowed enumerated values +func (x PayoutAccountType) IsValid() bool { + _, err := ParsePayoutAccountType(string(x)) + return err == nil +} + +var _PayoutAccountTypeValue = map[string]PayoutAccountType{ + "bank": PayoutAccountTypeBank, + "alipay": PayoutAccountTypeAlipay, +} + +// ParsePayoutAccountType attempts to convert a string to a PayoutAccountType. +func ParsePayoutAccountType(name string) (PayoutAccountType, error) { + if x, ok := _PayoutAccountTypeValue[name]; ok { + return x, nil + } + return PayoutAccountType(""), fmt.Errorf("%s is %w", name, ErrInvalidPayoutAccountType) +} + +var errPayoutAccountTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes + +// Scan implements the Scanner interface. +func (x *PayoutAccountType) Scan(value interface{}) (err error) { + if value == nil { + *x = PayoutAccountType("") + return + } + + // A wider range of scannable types. + // driver.Value values at the top of the list for expediency + switch v := value.(type) { + case string: + *x, err = ParsePayoutAccountType(v) + case []byte: + *x, err = ParsePayoutAccountType(string(v)) + case PayoutAccountType: + *x = v + case *PayoutAccountType: + if v == nil { + return errPayoutAccountTypeNilPtr + } + *x = *v + case *string: + if v == nil { + return errPayoutAccountTypeNilPtr + } + *x, err = ParsePayoutAccountType(*v) + default: + return errors.New("invalid type for PayoutAccountType") + } + + return +} + +// Value implements the driver Valuer interface. +func (x PayoutAccountType) Value() (driver.Value, error) { + return x.String(), nil +} + +// Set implements the Golang flag.Value interface func. +func (x *PayoutAccountType) Set(val string) error { + v, err := ParsePayoutAccountType(val) + *x = v + return err +} + +// Get implements the Golang flag.Getter interface func. +func (x *PayoutAccountType) Get() interface{} { + return *x +} + +// Type implements the github.com/spf13/pFlag Value interface. +func (x *PayoutAccountType) Type() string { + return "PayoutAccountType" +} + +type NullPayoutAccountType struct { + PayoutAccountType PayoutAccountType + Valid bool +} + +func NewNullPayoutAccountType(val interface{}) (x NullPayoutAccountType) { + err := x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + _ = err // make any errcheck linters happy + return +} + +// Scan implements the Scanner interface. +func (x *NullPayoutAccountType) Scan(value interface{}) (err error) { + if value == nil { + x.PayoutAccountType, x.Valid = PayoutAccountType(""), false + return + } + + err = x.PayoutAccountType.Scan(value) + x.Valid = (err == nil) + return +} + +// Value implements the driver Valuer interface. +func (x NullPayoutAccountType) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + // driver.Value accepts int64 for int values. + return string(x.PayoutAccountType), nil +} + +type NullPayoutAccountTypeStr struct { + NullPayoutAccountType +} + +func NewNullPayoutAccountTypeStr(val interface{}) (x NullPayoutAccountTypeStr) { + x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + return +} + +// Value implements the driver Valuer interface. +func (x NullPayoutAccountTypeStr) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + return x.PayoutAccountType.String(), nil +} + +const ( + // UserCommentActionTypeLike is a UserCommentActionType of type like. + UserCommentActionTypeLike UserCommentActionType = "like" +) + +var ErrInvalidUserCommentActionType = fmt.Errorf("not a valid UserCommentActionType, try [%s]", strings.Join(_UserCommentActionTypeNames, ", ")) + +var _UserCommentActionTypeNames = []string{ + string(UserCommentActionTypeLike), +} + +// UserCommentActionTypeNames returns a list of possible string values of UserCommentActionType. +func UserCommentActionTypeNames() []string { + tmp := make([]string, len(_UserCommentActionTypeNames)) + copy(tmp, _UserCommentActionTypeNames) + return tmp +} + +// UserCommentActionTypeValues returns a list of the values for UserCommentActionType +func UserCommentActionTypeValues() []UserCommentActionType { + return []UserCommentActionType{ + UserCommentActionTypeLike, + } +} + +// String implements the Stringer interface. +func (x UserCommentActionType) String() string { + return string(x) +} + +// IsValid provides a quick way to determine if the typed value is +// part of the allowed enumerated values +func (x UserCommentActionType) IsValid() bool { + _, err := ParseUserCommentActionType(string(x)) + return err == nil +} + +var _UserCommentActionTypeValue = map[string]UserCommentActionType{ + "like": UserCommentActionTypeLike, +} + +// ParseUserCommentActionType attempts to convert a string to a UserCommentActionType. +func ParseUserCommentActionType(name string) (UserCommentActionType, error) { + if x, ok := _UserCommentActionTypeValue[name]; ok { + return x, nil + } + return UserCommentActionType(""), fmt.Errorf("%s is %w", name, ErrInvalidUserCommentActionType) +} + +var errUserCommentActionTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes + +// Scan implements the Scanner interface. +func (x *UserCommentActionType) Scan(value interface{}) (err error) { + if value == nil { + *x = UserCommentActionType("") + return + } + + // A wider range of scannable types. + // driver.Value values at the top of the list for expediency + switch v := value.(type) { + case string: + *x, err = ParseUserCommentActionType(v) + case []byte: + *x, err = ParseUserCommentActionType(string(v)) + case UserCommentActionType: + *x = v + case *UserCommentActionType: + if v == nil { + return errUserCommentActionTypeNilPtr + } + *x = *v + case *string: + if v == nil { + return errUserCommentActionTypeNilPtr + } + *x, err = ParseUserCommentActionType(*v) + default: + return errors.New("invalid type for UserCommentActionType") + } + + return +} + +// Value implements the driver Valuer interface. +func (x UserCommentActionType) Value() (driver.Value, error) { + return x.String(), nil +} + +// Set implements the Golang flag.Value interface func. +func (x *UserCommentActionType) Set(val string) error { + v, err := ParseUserCommentActionType(val) + *x = v + return err +} + +// Get implements the Golang flag.Getter interface func. +func (x *UserCommentActionType) Get() interface{} { + return *x +} + +// Type implements the github.com/spf13/pFlag Value interface. +func (x *UserCommentActionType) Type() string { + return "UserCommentActionType" +} + +type NullUserCommentActionType struct { + UserCommentActionType UserCommentActionType + Valid bool +} + +func NewNullUserCommentActionType(val interface{}) (x NullUserCommentActionType) { + err := x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + _ = err // make any errcheck linters happy + return +} + +// Scan implements the Scanner interface. +func (x *NullUserCommentActionType) Scan(value interface{}) (err error) { + if value == nil { + x.UserCommentActionType, x.Valid = UserCommentActionType(""), false + return + } + + err = x.UserCommentActionType.Scan(value) + x.Valid = (err == nil) + return +} + +// Value implements the driver Valuer interface. +func (x NullUserCommentActionType) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + // driver.Value accepts int64 for int values. + return string(x.UserCommentActionType), nil +} + +type NullUserCommentActionTypeStr struct { + NullUserCommentActionType +} + +func NewNullUserCommentActionTypeStr(val interface{}) (x NullUserCommentActionTypeStr) { + x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + return +} + +// Value implements the driver Valuer interface. +func (x NullUserCommentActionTypeStr) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + return x.UserCommentActionType.String(), nil +} + +const ( + // UserContentActionTypeLike is a UserContentActionType of type like. + UserContentActionTypeLike UserContentActionType = "like" + // UserContentActionTypeFavorite is a UserContentActionType of type favorite. + UserContentActionTypeFavorite UserContentActionType = "favorite" +) + +var ErrInvalidUserContentActionType = fmt.Errorf("not a valid UserContentActionType, try [%s]", strings.Join(_UserContentActionTypeNames, ", ")) + +var _UserContentActionTypeNames = []string{ + string(UserContentActionTypeLike), + string(UserContentActionTypeFavorite), +} + +// UserContentActionTypeNames returns a list of possible string values of UserContentActionType. +func UserContentActionTypeNames() []string { + tmp := make([]string, len(_UserContentActionTypeNames)) + copy(tmp, _UserContentActionTypeNames) + return tmp +} + +// UserContentActionTypeValues returns a list of the values for UserContentActionType +func UserContentActionTypeValues() []UserContentActionType { + return []UserContentActionType{ + UserContentActionTypeLike, + UserContentActionTypeFavorite, + } +} + +// String implements the Stringer interface. +func (x UserContentActionType) String() string { + return string(x) +} + +// IsValid provides a quick way to determine if the typed value is +// part of the allowed enumerated values +func (x UserContentActionType) IsValid() bool { + _, err := ParseUserContentActionType(string(x)) + return err == nil +} + +var _UserContentActionTypeValue = map[string]UserContentActionType{ + "like": UserContentActionTypeLike, + "favorite": UserContentActionTypeFavorite, +} + +// ParseUserContentActionType attempts to convert a string to a UserContentActionType. +func ParseUserContentActionType(name string) (UserContentActionType, error) { + if x, ok := _UserContentActionTypeValue[name]; ok { + return x, nil + } + return UserContentActionType(""), fmt.Errorf("%s is %w", name, ErrInvalidUserContentActionType) +} + +var errUserContentActionTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes + +// Scan implements the Scanner interface. +func (x *UserContentActionType) Scan(value interface{}) (err error) { + if value == nil { + *x = UserContentActionType("") + return + } + + // A wider range of scannable types. + // driver.Value values at the top of the list for expediency + switch v := value.(type) { + case string: + *x, err = ParseUserContentActionType(v) + case []byte: + *x, err = ParseUserContentActionType(string(v)) + case UserContentActionType: + *x = v + case *UserContentActionType: + if v == nil { + return errUserContentActionTypeNilPtr + } + *x = *v + case *string: + if v == nil { + return errUserContentActionTypeNilPtr + } + *x, err = ParseUserContentActionType(*v) + default: + return errors.New("invalid type for UserContentActionType") + } + + return +} + +// Value implements the driver Valuer interface. +func (x UserContentActionType) Value() (driver.Value, error) { + return x.String(), nil +} + +// Set implements the Golang flag.Value interface func. +func (x *UserContentActionType) Set(val string) error { + v, err := ParseUserContentActionType(val) + *x = v + return err +} + +// Get implements the Golang flag.Getter interface func. +func (x *UserContentActionType) Get() interface{} { + return *x +} + +// Type implements the github.com/spf13/pFlag Value interface. +func (x *UserContentActionType) Type() string { + return "UserContentActionType" +} + +type NullUserContentActionType struct { + UserContentActionType UserContentActionType + Valid bool +} + +func NewNullUserContentActionType(val interface{}) (x NullUserContentActionType) { + err := x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + _ = err // make any errcheck linters happy + return +} + +// Scan implements the Scanner interface. +func (x *NullUserContentActionType) Scan(value interface{}) (err error) { + if value == nil { + x.UserContentActionType, x.Valid = UserContentActionType(""), false + return + } + + err = x.UserContentActionType.Scan(value) + x.Valid = (err == nil) + return +} + +// Value implements the driver Valuer interface. +func (x NullUserContentActionType) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + // driver.Value accepts int64 for int values. + return string(x.UserContentActionType), nil +} + +type NullUserContentActionTypeStr struct { + NullUserContentActionType +} + +func NewNullUserContentActionTypeStr(val interface{}) (x NullUserContentActionTypeStr) { + x.Scan(val) // yes, we ignore this error, it will just be an invalid value. + return +} + +// Value implements the driver Valuer interface. +func (x NullUserContentActionTypeStr) Value() (driver.Value, error) { + if !x.Valid { + return nil, nil + } + return x.UserContentActionType.String(), nil +} diff --git a/backend/pkg/consts/api_enums.go b/backend/pkg/consts/api_enums.go new file mode 100644 index 0000000..44d2619 --- /dev/null +++ b/backend/pkg/consts/api_enums.go @@ -0,0 +1,127 @@ +package consts + +import "quyun/v2/app/requests" + +// swagger:enum Gender +// ENUM( male, female, secret ) +type Gender string + +func (t Gender) Description() string { + switch t { + case GenderMale: + return "男" + case GenderFemale: + return "女" + case GenderSecret: + return "保密" + default: + return "未知" + } +} + +func GenderItems() []requests.KV { + values := GenderValues() + items := make([]requests.KV, 0, len(values)) + for _, v := range values { + items = append(items, requests.NewKV(string(v), v.Description())) + } + return items +} + +// swagger:enum UserContentActionType +// ENUM( like, favorite ) +type UserContentActionType string + +func (t UserContentActionType) Description() string { + switch t { + case UserContentActionTypeLike: + return "点赞" + case UserContentActionTypeFavorite: + return "收藏" + default: + return "未知" + } +} + +func UserContentActionTypeItems() []requests.KV { + values := UserContentActionTypeValues() + items := make([]requests.KV, 0, len(values)) + for _, v := range values { + items = append(items, requests.NewKV(string(v), v.Description())) + } + return items +} + +// swagger:enum UserCommentActionType +// ENUM( like ) +type UserCommentActionType string + +func (t UserCommentActionType) Description() string { + switch t { + case UserCommentActionTypeLike: + return "点赞" + default: + return "未知" + } +} + +func UserCommentActionTypeItems() []requests.KV { + values := UserCommentActionTypeValues() + items := make([]requests.KV, 0, len(values)) + for _, v := range values { + items = append(items, requests.NewKV(string(v), v.Description())) + } + return items +} + +// swagger:enum PayoutAccountType +// ENUM( bank, alipay ) +type PayoutAccountType string + +func (t PayoutAccountType) Description() string { + switch t { + case PayoutAccountTypeBank: + return "银行卡" + case PayoutAccountTypeAlipay: + return "支付宝" + default: + return "未知" + } +} + +func PayoutAccountTypeItems() []requests.KV { + values := PayoutAccountTypeValues() + items := make([]requests.KV, 0, len(values)) + for _, v := range values { + items = append(items, requests.NewKV(string(v), v.Description())) + } + return items +} + +// swagger:enum NotificationType +// ENUM( system, order, audit, interaction ) +type NotificationType string + +func (t NotificationType) Description() string { + switch t { + case NotificationTypeSystem: + return "系统通知" + case NotificationTypeOrder: + return "订单通知" + case NotificationTypeAudit: + return "审核通知" + case NotificationTypeInteraction: + return "互动通知" + default: + return "未知" + } +} + +func NotificationTypeItems() []requests.KV { + values := NotificationTypeValues() + items := make([]requests.KV, 0, len(values)) + for _, v := range values { + items = append(items, requests.NewKV(string(v), v.Description())) + } + return items +} diff --git a/models/comments.gen.go b/models/comments.gen.go new file mode 100644 index 0000000..50736e7 --- /dev/null +++ b/models/comments.gen.go @@ -0,0 +1,66 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "gorm.io/gorm" +) + +const TableNameComment = "comments" + +// Comment mapped from table +type Comment struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + ReplyTo int64 `gorm:"column:reply_to;type:bigint" json:"reply_to"` + Content string `gorm:"column:content;type:text;not null" json:"content"` + Likes int32 `gorm:"column:likes;type:integer" json:"likes"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Comment) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Comment) Save(ctx context.Context) error { return Q.Comment.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *Comment) Create(ctx context.Context) error { return Q.Comment.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *Comment) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Comment) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).Unscoped().Delete(m) +} + +// Restore sets deleted_at to NULL for this model's primary key using the default DB. +func (m *Comment) Restore(ctx context.Context) (gen.ResultInfo, error) { + return Q.Comment.WithContext(ctx).RestoreByID(m.ID) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Comment) Reload(ctx context.Context) error { + fresh, err := Q.Comment.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/comments.query.gen.go b/models/comments.query.gen.go new file mode 100644 index 0000000..3eaa50f --- /dev/null +++ b/models/comments.query.gen.go @@ -0,0 +1,510 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newComment(db *gorm.DB, opts ...gen.DOOption) commentQuery { + _commentQuery := commentQuery{} + + _commentQuery.commentQueryDo.UseDB(db, opts...) + _commentQuery.commentQueryDo.UseModel(&Comment{}) + + tableName := _commentQuery.commentQueryDo.TableName() + _commentQuery.ALL = field.NewAsterisk(tableName) + _commentQuery.ID = field.NewInt64(tableName, "id") + _commentQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _commentQuery.UserID = field.NewInt64(tableName, "user_id") + _commentQuery.ContentID = field.NewInt64(tableName, "content_id") + _commentQuery.ReplyTo = field.NewInt64(tableName, "reply_to") + _commentQuery.Content = field.NewString(tableName, "content") + _commentQuery.Likes = field.NewInt32(tableName, "likes") + _commentQuery.CreatedAt = field.NewTime(tableName, "created_at") + _commentQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _commentQuery.DeletedAt = field.NewField(tableName, "deleted_at") + + _commentQuery.fillFieldMap() + + return _commentQuery +} + +type commentQuery struct { + commentQueryDo commentQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + ReplyTo field.Int64 + Content field.String + Likes field.Int32 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + + fieldMap map[string]field.Expr +} + +func (c commentQuery) Table(newTableName string) *commentQuery { + c.commentQueryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c commentQuery) As(alias string) *commentQuery { + c.commentQueryDo.DO = *(c.commentQueryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *commentQuery) updateTableName(table string) *commentQuery { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.TenantID = field.NewInt64(table, "tenant_id") + c.UserID = field.NewInt64(table, "user_id") + c.ContentID = field.NewInt64(table, "content_id") + c.ReplyTo = field.NewInt64(table, "reply_to") + c.Content = field.NewString(table, "content") + c.Likes = field.NewInt32(table, "likes") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + + c.fillFieldMap() + + return c +} + +func (c *commentQuery) QueryContext(ctx context.Context) (*commentQuery, *commentQueryDo) { + return c, c.commentQueryDo.WithContext(ctx) +} + +func (c *commentQuery) WithContext(ctx context.Context) *commentQueryDo { + return c.commentQueryDo.WithContext(ctx) +} + +func (c commentQuery) TableName() string { return c.commentQueryDo.TableName() } + +func (c commentQuery) Alias() string { return c.commentQueryDo.Alias() } + +func (c commentQuery) Columns(cols ...field.Expr) gen.Columns { + return c.commentQueryDo.Columns(cols...) +} + +func (c *commentQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *commentQuery) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 10) + c.fieldMap["id"] = c.ID + c.fieldMap["tenant_id"] = c.TenantID + c.fieldMap["user_id"] = c.UserID + c.fieldMap["content_id"] = c.ContentID + c.fieldMap["reply_to"] = c.ReplyTo + c.fieldMap["content"] = c.Content + c.fieldMap["likes"] = c.Likes + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt +} + +func (c commentQuery) clone(db *gorm.DB) commentQuery { + c.commentQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c commentQuery) replaceDB(db *gorm.DB) commentQuery { + c.commentQueryDo.ReplaceDB(db) + return c +} + +type commentQueryDo struct{ gen.DO } + +func (c commentQueryDo) Debug() *commentQueryDo { + return c.withDO(c.DO.Debug()) +} + +func (c commentQueryDo) WithContext(ctx context.Context) *commentQueryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c commentQueryDo) ReadDB() *commentQueryDo { + return c.Clauses(dbresolver.Read) +} + +func (c commentQueryDo) WriteDB() *commentQueryDo { + return c.Clauses(dbresolver.Write) +} + +func (c commentQueryDo) Session(config *gorm.Session) *commentQueryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c commentQueryDo) Clauses(conds ...clause.Expression) *commentQueryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c commentQueryDo) Returning(value interface{}, columns ...string) *commentQueryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c commentQueryDo) Not(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c commentQueryDo) Or(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c commentQueryDo) Select(conds ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c commentQueryDo) Where(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c commentQueryDo) Order(conds ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c commentQueryDo) Distinct(cols ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c commentQueryDo) Omit(cols ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c commentQueryDo) Join(table schema.Tabler, on ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c commentQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c commentQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c commentQueryDo) Group(cols ...field.Expr) *commentQueryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c commentQueryDo) Having(conds ...gen.Condition) *commentQueryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c commentQueryDo) Limit(limit int) *commentQueryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c commentQueryDo) Offset(offset int) *commentQueryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c commentQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *commentQueryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c commentQueryDo) Unscoped() *commentQueryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c commentQueryDo) Create(values ...*Comment) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c commentQueryDo) CreateInBatches(values []*Comment, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c commentQueryDo) Save(values ...*Comment) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c commentQueryDo) First() (*Comment, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) Take() (*Comment, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) Last() (*Comment, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) Find() ([]*Comment, error) { + result, err := c.DO.Find() + return result.([]*Comment), err +} + +func (c commentQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Comment, err error) { + buf := make([]*Comment, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c commentQueryDo) FindInBatches(result *[]*Comment, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c commentQueryDo) Attrs(attrs ...field.AssignExpr) *commentQueryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c commentQueryDo) Assign(attrs ...field.AssignExpr) *commentQueryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c commentQueryDo) Joins(fields ...field.RelationField) *commentQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c commentQueryDo) Preload(fields ...field.RelationField) *commentQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c commentQueryDo) FirstOrInit() (*Comment, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) FirstOrCreate() (*Comment, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Comment), nil + } +} + +func (c commentQueryDo) FindByPage(offset int, limit int) (result []*Comment, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c commentQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c commentQueryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c commentQueryDo) Delete(models ...*Comment) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (c commentQueryDo) ForceDelete() (gen.ResultInfo, error) { + return c.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (c commentQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (c commentQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (c commentQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (c commentQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (c commentQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (c commentQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (c commentQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := c.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (c commentQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := c.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (c commentQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(c.TableName(), "id") + if err := c.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (c commentQueryDo) GetByID(id int64) (*Comment, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (c commentQueryDo) GetByIDs(ids ...int64) ([]*Comment, error) { + if len(ids) == 0 { + return []*Comment{}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (c commentQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (c commentQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Delete() +} + +// RestoreWhere sets deleted_at to NULL for rows matching current scope + conds. +func (c commentQueryDo) RestoreWhere(conds ...gen.Condition) (gen.ResultInfo, error) { + col := field.NewField(c.TableName(), "deleted_at") + return c.Unscoped().Where(conds...).UpdateColumn(col, nil) +} + +// RestoreByID sets deleted_at to NULL for the given primary key. +func (c commentQueryDo) RestoreByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + col := field.NewField(c.TableName(), "deleted_at") + return c.Unscoped().Where(pk.Eq(id)).UpdateColumn(col, nil) +} + +func (c *commentQueryDo) withDO(do gen.Dao) *commentQueryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/models/content_access.gen.go b/models/content_access.gen.go new file mode 100644 index 0000000..3a3555b --- /dev/null +++ b/models/content_access.gen.go @@ -0,0 +1,63 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameContentAccess = "content_access" + +// ContentAccess mapped from table +type ContentAccess struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + OrderID int64 `gorm:"column:order_id;type:bigint" json:"order_id"` + Status string `gorm:"column:status;type:character varying(16);default:active" json:"status"` + RevokedAt time.Time `gorm:"column:revoked_at;type:timestamp with time zone" json:"revoked_at"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *ContentAccess) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentAccess.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *ContentAccess) Save(ctx context.Context) error { + return Q.ContentAccess.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *ContentAccess) Create(ctx context.Context) error { + return Q.ContentAccess.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *ContentAccess) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentAccess.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *ContentAccess) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentAccess.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *ContentAccess) Reload(ctx context.Context) error { + fresh, err := Q.ContentAccess.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/content_access.go b/models/content_access.go similarity index 100% rename from backend/database/models/content_access.go rename to models/content_access.go diff --git a/models/content_access.query.gen.go b/models/content_access.query.gen.go new file mode 100644 index 0000000..aed602c --- /dev/null +++ b/models/content_access.query.gen.go @@ -0,0 +1,493 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newContentAccess(db *gorm.DB, opts ...gen.DOOption) contentAccessQuery { + _contentAccessQuery := contentAccessQuery{} + + _contentAccessQuery.contentAccessQueryDo.UseDB(db, opts...) + _contentAccessQuery.contentAccessQueryDo.UseModel(&ContentAccess{}) + + tableName := _contentAccessQuery.contentAccessQueryDo.TableName() + _contentAccessQuery.ALL = field.NewAsterisk(tableName) + _contentAccessQuery.ID = field.NewInt64(tableName, "id") + _contentAccessQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _contentAccessQuery.UserID = field.NewInt64(tableName, "user_id") + _contentAccessQuery.ContentID = field.NewInt64(tableName, "content_id") + _contentAccessQuery.OrderID = field.NewInt64(tableName, "order_id") + _contentAccessQuery.Status = field.NewString(tableName, "status") + _contentAccessQuery.RevokedAt = field.NewTime(tableName, "revoked_at") + _contentAccessQuery.CreatedAt = field.NewTime(tableName, "created_at") + _contentAccessQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _contentAccessQuery.fillFieldMap() + + return _contentAccessQuery +} + +type contentAccessQuery struct { + contentAccessQueryDo contentAccessQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + OrderID field.Int64 + Status field.String + RevokedAt field.Time + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (c contentAccessQuery) Table(newTableName string) *contentAccessQuery { + c.contentAccessQueryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c contentAccessQuery) As(alias string) *contentAccessQuery { + c.contentAccessQueryDo.DO = *(c.contentAccessQueryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *contentAccessQuery) updateTableName(table string) *contentAccessQuery { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.TenantID = field.NewInt64(table, "tenant_id") + c.UserID = field.NewInt64(table, "user_id") + c.ContentID = field.NewInt64(table, "content_id") + c.OrderID = field.NewInt64(table, "order_id") + c.Status = field.NewString(table, "status") + c.RevokedAt = field.NewTime(table, "revoked_at") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + + c.fillFieldMap() + + return c +} + +func (c *contentAccessQuery) QueryContext(ctx context.Context) (*contentAccessQuery, *contentAccessQueryDo) { + return c, c.contentAccessQueryDo.WithContext(ctx) +} + +func (c *contentAccessQuery) WithContext(ctx context.Context) *contentAccessQueryDo { + return c.contentAccessQueryDo.WithContext(ctx) +} + +func (c contentAccessQuery) TableName() string { return c.contentAccessQueryDo.TableName() } + +func (c contentAccessQuery) Alias() string { return c.contentAccessQueryDo.Alias() } + +func (c contentAccessQuery) Columns(cols ...field.Expr) gen.Columns { + return c.contentAccessQueryDo.Columns(cols...) +} + +func (c *contentAccessQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *contentAccessQuery) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 9) + c.fieldMap["id"] = c.ID + c.fieldMap["tenant_id"] = c.TenantID + c.fieldMap["user_id"] = c.UserID + c.fieldMap["content_id"] = c.ContentID + c.fieldMap["order_id"] = c.OrderID + c.fieldMap["status"] = c.Status + c.fieldMap["revoked_at"] = c.RevokedAt + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt +} + +func (c contentAccessQuery) clone(db *gorm.DB) contentAccessQuery { + c.contentAccessQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c contentAccessQuery) replaceDB(db *gorm.DB) contentAccessQuery { + c.contentAccessQueryDo.ReplaceDB(db) + return c +} + +type contentAccessQueryDo struct{ gen.DO } + +func (c contentAccessQueryDo) Debug() *contentAccessQueryDo { + return c.withDO(c.DO.Debug()) +} + +func (c contentAccessQueryDo) WithContext(ctx context.Context) *contentAccessQueryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c contentAccessQueryDo) ReadDB() *contentAccessQueryDo { + return c.Clauses(dbresolver.Read) +} + +func (c contentAccessQueryDo) WriteDB() *contentAccessQueryDo { + return c.Clauses(dbresolver.Write) +} + +func (c contentAccessQueryDo) Session(config *gorm.Session) *contentAccessQueryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c contentAccessQueryDo) Clauses(conds ...clause.Expression) *contentAccessQueryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c contentAccessQueryDo) Returning(value interface{}, columns ...string) *contentAccessQueryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c contentAccessQueryDo) Not(conds ...gen.Condition) *contentAccessQueryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c contentAccessQueryDo) Or(conds ...gen.Condition) *contentAccessQueryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c contentAccessQueryDo) Select(conds ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c contentAccessQueryDo) Where(conds ...gen.Condition) *contentAccessQueryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c contentAccessQueryDo) Order(conds ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c contentAccessQueryDo) Distinct(cols ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c contentAccessQueryDo) Omit(cols ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c contentAccessQueryDo) Join(table schema.Tabler, on ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c contentAccessQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c contentAccessQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c contentAccessQueryDo) Group(cols ...field.Expr) *contentAccessQueryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c contentAccessQueryDo) Having(conds ...gen.Condition) *contentAccessQueryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c contentAccessQueryDo) Limit(limit int) *contentAccessQueryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c contentAccessQueryDo) Offset(offset int) *contentAccessQueryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c contentAccessQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *contentAccessQueryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c contentAccessQueryDo) Unscoped() *contentAccessQueryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c contentAccessQueryDo) Create(values ...*ContentAccess) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c contentAccessQueryDo) CreateInBatches(values []*ContentAccess, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c contentAccessQueryDo) Save(values ...*ContentAccess) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c contentAccessQueryDo) First() (*ContentAccess, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*ContentAccess), nil + } +} + +func (c contentAccessQueryDo) Take() (*ContentAccess, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*ContentAccess), nil + } +} + +func (c contentAccessQueryDo) Last() (*ContentAccess, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*ContentAccess), nil + } +} + +func (c contentAccessQueryDo) Find() ([]*ContentAccess, error) { + result, err := c.DO.Find() + return result.([]*ContentAccess), err +} + +func (c contentAccessQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*ContentAccess, err error) { + buf := make([]*ContentAccess, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c contentAccessQueryDo) FindInBatches(result *[]*ContentAccess, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c contentAccessQueryDo) Attrs(attrs ...field.AssignExpr) *contentAccessQueryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c contentAccessQueryDo) Assign(attrs ...field.AssignExpr) *contentAccessQueryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c contentAccessQueryDo) Joins(fields ...field.RelationField) *contentAccessQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c contentAccessQueryDo) Preload(fields ...field.RelationField) *contentAccessQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c contentAccessQueryDo) FirstOrInit() (*ContentAccess, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*ContentAccess), nil + } +} + +func (c contentAccessQueryDo) FirstOrCreate() (*ContentAccess, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*ContentAccess), nil + } +} + +func (c contentAccessQueryDo) FindByPage(offset int, limit int) (result []*ContentAccess, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c contentAccessQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c contentAccessQueryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c contentAccessQueryDo) Delete(models ...*ContentAccess) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (c contentAccessQueryDo) ForceDelete() (gen.ResultInfo, error) { + return c.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (c contentAccessQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (c contentAccessQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (c contentAccessQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (c contentAccessQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (c contentAccessQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (c contentAccessQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (c contentAccessQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := c.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (c contentAccessQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := c.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (c contentAccessQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(c.TableName(), "id") + if err := c.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (c contentAccessQueryDo) GetByID(id int64) (*ContentAccess, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (c contentAccessQueryDo) GetByIDs(ids ...int64) ([]*ContentAccess, error) { + if len(ids) == 0 { + return []*ContentAccess{}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (c contentAccessQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (c contentAccessQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Delete() +} + +func (c *contentAccessQueryDo) withDO(do gen.Dao) *contentAccessQueryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/models/content_assets.gen.go b/models/content_assets.gen.go new file mode 100644 index 0000000..1432a68 --- /dev/null +++ b/models/content_assets.gen.go @@ -0,0 +1,63 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameContentAsset = "content_assets" + +// ContentAsset mapped from table +type ContentAsset struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + AssetID int64 `gorm:"column:asset_id;type:bigint;not null" json:"asset_id"` + Role string `gorm:"column:role;type:character varying(32);default:main" json:"role"` + Sort int32 `gorm:"column:sort;type:integer" json:"sort"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *ContentAsset) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentAsset.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *ContentAsset) Save(ctx context.Context) error { + return Q.ContentAsset.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *ContentAsset) Create(ctx context.Context) error { + return Q.ContentAsset.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *ContentAsset) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentAsset.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *ContentAsset) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentAsset.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *ContentAsset) Reload(ctx context.Context) error { + fresh, err := Q.ContentAsset.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/content_assets.query.gen.go b/models/content_assets.query.gen.go new file mode 100644 index 0000000..60eb917 --- /dev/null +++ b/models/content_assets.query.gen.go @@ -0,0 +1,493 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newContentAsset(db *gorm.DB, opts ...gen.DOOption) contentAssetQuery { + _contentAssetQuery := contentAssetQuery{} + + _contentAssetQuery.contentAssetQueryDo.UseDB(db, opts...) + _contentAssetQuery.contentAssetQueryDo.UseModel(&ContentAsset{}) + + tableName := _contentAssetQuery.contentAssetQueryDo.TableName() + _contentAssetQuery.ALL = field.NewAsterisk(tableName) + _contentAssetQuery.ID = field.NewInt64(tableName, "id") + _contentAssetQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _contentAssetQuery.UserID = field.NewInt64(tableName, "user_id") + _contentAssetQuery.ContentID = field.NewInt64(tableName, "content_id") + _contentAssetQuery.AssetID = field.NewInt64(tableName, "asset_id") + _contentAssetQuery.Role = field.NewString(tableName, "role") + _contentAssetQuery.Sort = field.NewInt32(tableName, "sort") + _contentAssetQuery.CreatedAt = field.NewTime(tableName, "created_at") + _contentAssetQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _contentAssetQuery.fillFieldMap() + + return _contentAssetQuery +} + +type contentAssetQuery struct { + contentAssetQueryDo contentAssetQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + AssetID field.Int64 + Role field.String + Sort field.Int32 + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (c contentAssetQuery) Table(newTableName string) *contentAssetQuery { + c.contentAssetQueryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c contentAssetQuery) As(alias string) *contentAssetQuery { + c.contentAssetQueryDo.DO = *(c.contentAssetQueryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *contentAssetQuery) updateTableName(table string) *contentAssetQuery { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.TenantID = field.NewInt64(table, "tenant_id") + c.UserID = field.NewInt64(table, "user_id") + c.ContentID = field.NewInt64(table, "content_id") + c.AssetID = field.NewInt64(table, "asset_id") + c.Role = field.NewString(table, "role") + c.Sort = field.NewInt32(table, "sort") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + + c.fillFieldMap() + + return c +} + +func (c *contentAssetQuery) QueryContext(ctx context.Context) (*contentAssetQuery, *contentAssetQueryDo) { + return c, c.contentAssetQueryDo.WithContext(ctx) +} + +func (c *contentAssetQuery) WithContext(ctx context.Context) *contentAssetQueryDo { + return c.contentAssetQueryDo.WithContext(ctx) +} + +func (c contentAssetQuery) TableName() string { return c.contentAssetQueryDo.TableName() } + +func (c contentAssetQuery) Alias() string { return c.contentAssetQueryDo.Alias() } + +func (c contentAssetQuery) Columns(cols ...field.Expr) gen.Columns { + return c.contentAssetQueryDo.Columns(cols...) +} + +func (c *contentAssetQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *contentAssetQuery) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 9) + c.fieldMap["id"] = c.ID + c.fieldMap["tenant_id"] = c.TenantID + c.fieldMap["user_id"] = c.UserID + c.fieldMap["content_id"] = c.ContentID + c.fieldMap["asset_id"] = c.AssetID + c.fieldMap["role"] = c.Role + c.fieldMap["sort"] = c.Sort + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt +} + +func (c contentAssetQuery) clone(db *gorm.DB) contentAssetQuery { + c.contentAssetQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c contentAssetQuery) replaceDB(db *gorm.DB) contentAssetQuery { + c.contentAssetQueryDo.ReplaceDB(db) + return c +} + +type contentAssetQueryDo struct{ gen.DO } + +func (c contentAssetQueryDo) Debug() *contentAssetQueryDo { + return c.withDO(c.DO.Debug()) +} + +func (c contentAssetQueryDo) WithContext(ctx context.Context) *contentAssetQueryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c contentAssetQueryDo) ReadDB() *contentAssetQueryDo { + return c.Clauses(dbresolver.Read) +} + +func (c contentAssetQueryDo) WriteDB() *contentAssetQueryDo { + return c.Clauses(dbresolver.Write) +} + +func (c contentAssetQueryDo) Session(config *gorm.Session) *contentAssetQueryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c contentAssetQueryDo) Clauses(conds ...clause.Expression) *contentAssetQueryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c contentAssetQueryDo) Returning(value interface{}, columns ...string) *contentAssetQueryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c contentAssetQueryDo) Not(conds ...gen.Condition) *contentAssetQueryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c contentAssetQueryDo) Or(conds ...gen.Condition) *contentAssetQueryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c contentAssetQueryDo) Select(conds ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c contentAssetQueryDo) Where(conds ...gen.Condition) *contentAssetQueryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c contentAssetQueryDo) Order(conds ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c contentAssetQueryDo) Distinct(cols ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c contentAssetQueryDo) Omit(cols ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c contentAssetQueryDo) Join(table schema.Tabler, on ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c contentAssetQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c contentAssetQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c contentAssetQueryDo) Group(cols ...field.Expr) *contentAssetQueryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c contentAssetQueryDo) Having(conds ...gen.Condition) *contentAssetQueryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c contentAssetQueryDo) Limit(limit int) *contentAssetQueryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c contentAssetQueryDo) Offset(offset int) *contentAssetQueryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c contentAssetQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *contentAssetQueryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c contentAssetQueryDo) Unscoped() *contentAssetQueryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c contentAssetQueryDo) Create(values ...*ContentAsset) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c contentAssetQueryDo) CreateInBatches(values []*ContentAsset, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c contentAssetQueryDo) Save(values ...*ContentAsset) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c contentAssetQueryDo) First() (*ContentAsset, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*ContentAsset), nil + } +} + +func (c contentAssetQueryDo) Take() (*ContentAsset, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*ContentAsset), nil + } +} + +func (c contentAssetQueryDo) Last() (*ContentAsset, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*ContentAsset), nil + } +} + +func (c contentAssetQueryDo) Find() ([]*ContentAsset, error) { + result, err := c.DO.Find() + return result.([]*ContentAsset), err +} + +func (c contentAssetQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*ContentAsset, err error) { + buf := make([]*ContentAsset, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c contentAssetQueryDo) FindInBatches(result *[]*ContentAsset, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c contentAssetQueryDo) Attrs(attrs ...field.AssignExpr) *contentAssetQueryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c contentAssetQueryDo) Assign(attrs ...field.AssignExpr) *contentAssetQueryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c contentAssetQueryDo) Joins(fields ...field.RelationField) *contentAssetQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c contentAssetQueryDo) Preload(fields ...field.RelationField) *contentAssetQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c contentAssetQueryDo) FirstOrInit() (*ContentAsset, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*ContentAsset), nil + } +} + +func (c contentAssetQueryDo) FirstOrCreate() (*ContentAsset, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*ContentAsset), nil + } +} + +func (c contentAssetQueryDo) FindByPage(offset int, limit int) (result []*ContentAsset, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c contentAssetQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c contentAssetQueryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c contentAssetQueryDo) Delete(models ...*ContentAsset) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (c contentAssetQueryDo) ForceDelete() (gen.ResultInfo, error) { + return c.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (c contentAssetQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (c contentAssetQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (c contentAssetQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (c contentAssetQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (c contentAssetQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (c contentAssetQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (c contentAssetQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := c.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (c contentAssetQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := c.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (c contentAssetQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(c.TableName(), "id") + if err := c.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (c contentAssetQueryDo) GetByID(id int64) (*ContentAsset, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (c contentAssetQueryDo) GetByIDs(ids ...int64) ([]*ContentAsset, error) { + if len(ids) == 0 { + return []*ContentAsset{}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (c contentAssetQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (c contentAssetQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Delete() +} + +func (c *contentAssetQueryDo) withDO(do gen.Dao) *contentAssetQueryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/models/content_prices.gen.go b/models/content_prices.gen.go new file mode 100644 index 0000000..273b3d6 --- /dev/null +++ b/models/content_prices.gen.go @@ -0,0 +1,66 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameContentPrice = "content_prices" + +// ContentPrice mapped from table +type ContentPrice struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + Currency string `gorm:"column:currency;type:character varying(16);default:CNY" json:"currency"` + PriceAmount int64 `gorm:"column:price_amount;type:bigint;not null" json:"price_amount"` + DiscountType string `gorm:"column:discount_type;type:character varying(16);default:none" json:"discount_type"` + DiscountValue int64 `gorm:"column:discount_value;type:bigint" json:"discount_value"` + DiscountStartAt time.Time `gorm:"column:discount_start_at;type:timestamp with time zone" json:"discount_start_at"` + DiscountEndAt time.Time `gorm:"column:discount_end_at;type:timestamp with time zone" json:"discount_end_at"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *ContentPrice) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentPrice.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *ContentPrice) Save(ctx context.Context) error { + return Q.ContentPrice.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *ContentPrice) Create(ctx context.Context) error { + return Q.ContentPrice.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *ContentPrice) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentPrice.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *ContentPrice) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.ContentPrice.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *ContentPrice) Reload(ctx context.Context) error { + fresh, err := Q.ContentPrice.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/content_prices.query.gen.go b/models/content_prices.query.gen.go new file mode 100644 index 0000000..9738a37 --- /dev/null +++ b/models/content_prices.query.gen.go @@ -0,0 +1,505 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newContentPrice(db *gorm.DB, opts ...gen.DOOption) contentPriceQuery { + _contentPriceQuery := contentPriceQuery{} + + _contentPriceQuery.contentPriceQueryDo.UseDB(db, opts...) + _contentPriceQuery.contentPriceQueryDo.UseModel(&ContentPrice{}) + + tableName := _contentPriceQuery.contentPriceQueryDo.TableName() + _contentPriceQuery.ALL = field.NewAsterisk(tableName) + _contentPriceQuery.ID = field.NewInt64(tableName, "id") + _contentPriceQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _contentPriceQuery.UserID = field.NewInt64(tableName, "user_id") + _contentPriceQuery.ContentID = field.NewInt64(tableName, "content_id") + _contentPriceQuery.Currency = field.NewString(tableName, "currency") + _contentPriceQuery.PriceAmount = field.NewInt64(tableName, "price_amount") + _contentPriceQuery.DiscountType = field.NewString(tableName, "discount_type") + _contentPriceQuery.DiscountValue = field.NewInt64(tableName, "discount_value") + _contentPriceQuery.DiscountStartAt = field.NewTime(tableName, "discount_start_at") + _contentPriceQuery.DiscountEndAt = field.NewTime(tableName, "discount_end_at") + _contentPriceQuery.CreatedAt = field.NewTime(tableName, "created_at") + _contentPriceQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _contentPriceQuery.fillFieldMap() + + return _contentPriceQuery +} + +type contentPriceQuery struct { + contentPriceQueryDo contentPriceQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + ContentID field.Int64 + Currency field.String + PriceAmount field.Int64 + DiscountType field.String + DiscountValue field.Int64 + DiscountStartAt field.Time + DiscountEndAt field.Time + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (c contentPriceQuery) Table(newTableName string) *contentPriceQuery { + c.contentPriceQueryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c contentPriceQuery) As(alias string) *contentPriceQuery { + c.contentPriceQueryDo.DO = *(c.contentPriceQueryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *contentPriceQuery) updateTableName(table string) *contentPriceQuery { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.TenantID = field.NewInt64(table, "tenant_id") + c.UserID = field.NewInt64(table, "user_id") + c.ContentID = field.NewInt64(table, "content_id") + c.Currency = field.NewString(table, "currency") + c.PriceAmount = field.NewInt64(table, "price_amount") + c.DiscountType = field.NewString(table, "discount_type") + c.DiscountValue = field.NewInt64(table, "discount_value") + c.DiscountStartAt = field.NewTime(table, "discount_start_at") + c.DiscountEndAt = field.NewTime(table, "discount_end_at") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + + c.fillFieldMap() + + return c +} + +func (c *contentPriceQuery) QueryContext(ctx context.Context) (*contentPriceQuery, *contentPriceQueryDo) { + return c, c.contentPriceQueryDo.WithContext(ctx) +} + +func (c *contentPriceQuery) WithContext(ctx context.Context) *contentPriceQueryDo { + return c.contentPriceQueryDo.WithContext(ctx) +} + +func (c contentPriceQuery) TableName() string { return c.contentPriceQueryDo.TableName() } + +func (c contentPriceQuery) Alias() string { return c.contentPriceQueryDo.Alias() } + +func (c contentPriceQuery) Columns(cols ...field.Expr) gen.Columns { + return c.contentPriceQueryDo.Columns(cols...) +} + +func (c *contentPriceQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *contentPriceQuery) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 12) + c.fieldMap["id"] = c.ID + c.fieldMap["tenant_id"] = c.TenantID + c.fieldMap["user_id"] = c.UserID + c.fieldMap["content_id"] = c.ContentID + c.fieldMap["currency"] = c.Currency + c.fieldMap["price_amount"] = c.PriceAmount + c.fieldMap["discount_type"] = c.DiscountType + c.fieldMap["discount_value"] = c.DiscountValue + c.fieldMap["discount_start_at"] = c.DiscountStartAt + c.fieldMap["discount_end_at"] = c.DiscountEndAt + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt +} + +func (c contentPriceQuery) clone(db *gorm.DB) contentPriceQuery { + c.contentPriceQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c contentPriceQuery) replaceDB(db *gorm.DB) contentPriceQuery { + c.contentPriceQueryDo.ReplaceDB(db) + return c +} + +type contentPriceQueryDo struct{ gen.DO } + +func (c contentPriceQueryDo) Debug() *contentPriceQueryDo { + return c.withDO(c.DO.Debug()) +} + +func (c contentPriceQueryDo) WithContext(ctx context.Context) *contentPriceQueryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c contentPriceQueryDo) ReadDB() *contentPriceQueryDo { + return c.Clauses(dbresolver.Read) +} + +func (c contentPriceQueryDo) WriteDB() *contentPriceQueryDo { + return c.Clauses(dbresolver.Write) +} + +func (c contentPriceQueryDo) Session(config *gorm.Session) *contentPriceQueryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c contentPriceQueryDo) Clauses(conds ...clause.Expression) *contentPriceQueryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c contentPriceQueryDo) Returning(value interface{}, columns ...string) *contentPriceQueryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c contentPriceQueryDo) Not(conds ...gen.Condition) *contentPriceQueryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c contentPriceQueryDo) Or(conds ...gen.Condition) *contentPriceQueryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c contentPriceQueryDo) Select(conds ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c contentPriceQueryDo) Where(conds ...gen.Condition) *contentPriceQueryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c contentPriceQueryDo) Order(conds ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c contentPriceQueryDo) Distinct(cols ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c contentPriceQueryDo) Omit(cols ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c contentPriceQueryDo) Join(table schema.Tabler, on ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c contentPriceQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c contentPriceQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c contentPriceQueryDo) Group(cols ...field.Expr) *contentPriceQueryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c contentPriceQueryDo) Having(conds ...gen.Condition) *contentPriceQueryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c contentPriceQueryDo) Limit(limit int) *contentPriceQueryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c contentPriceQueryDo) Offset(offset int) *contentPriceQueryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c contentPriceQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *contentPriceQueryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c contentPriceQueryDo) Unscoped() *contentPriceQueryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c contentPriceQueryDo) Create(values ...*ContentPrice) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c contentPriceQueryDo) CreateInBatches(values []*ContentPrice, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c contentPriceQueryDo) Save(values ...*ContentPrice) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c contentPriceQueryDo) First() (*ContentPrice, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*ContentPrice), nil + } +} + +func (c contentPriceQueryDo) Take() (*ContentPrice, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*ContentPrice), nil + } +} + +func (c contentPriceQueryDo) Last() (*ContentPrice, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*ContentPrice), nil + } +} + +func (c contentPriceQueryDo) Find() ([]*ContentPrice, error) { + result, err := c.DO.Find() + return result.([]*ContentPrice), err +} + +func (c contentPriceQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*ContentPrice, err error) { + buf := make([]*ContentPrice, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c contentPriceQueryDo) FindInBatches(result *[]*ContentPrice, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c contentPriceQueryDo) Attrs(attrs ...field.AssignExpr) *contentPriceQueryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c contentPriceQueryDo) Assign(attrs ...field.AssignExpr) *contentPriceQueryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c contentPriceQueryDo) Joins(fields ...field.RelationField) *contentPriceQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c contentPriceQueryDo) Preload(fields ...field.RelationField) *contentPriceQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c contentPriceQueryDo) FirstOrInit() (*ContentPrice, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*ContentPrice), nil + } +} + +func (c contentPriceQueryDo) FirstOrCreate() (*ContentPrice, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*ContentPrice), nil + } +} + +func (c contentPriceQueryDo) FindByPage(offset int, limit int) (result []*ContentPrice, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c contentPriceQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c contentPriceQueryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c contentPriceQueryDo) Delete(models ...*ContentPrice) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (c contentPriceQueryDo) ForceDelete() (gen.ResultInfo, error) { + return c.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (c contentPriceQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (c contentPriceQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (c contentPriceQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (c contentPriceQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (c contentPriceQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (c contentPriceQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (c contentPriceQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := c.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (c contentPriceQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := c.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (c contentPriceQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(c.TableName(), "id") + if err := c.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (c contentPriceQueryDo) GetByID(id int64) (*ContentPrice, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (c contentPriceQueryDo) GetByIDs(ids ...int64) ([]*ContentPrice, error) { + if len(ids) == 0 { + return []*ContentPrice{}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (c contentPriceQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (c contentPriceQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Delete() +} + +func (c *contentPriceQueryDo) withDO(do gen.Dao) *contentPriceQueryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/models/contents.gen.go b/models/contents.gen.go new file mode 100644 index 0000000..c1389ef --- /dev/null +++ b/models/contents.gen.go @@ -0,0 +1,76 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" + "gorm.io/gorm" +) + +const TableNameContent = "contents" + +// Content mapped from table +type Content struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Title string `gorm:"column:title;type:character varying(255);not null" json:"title"` + Description string `gorm:"column:description;type:text;not null" json:"description"` + Status string `gorm:"column:status;type:character varying(32);default:draft" json:"status"` + Visibility string `gorm:"column:visibility;type:character varying(32);default:tenant_only" json:"visibility"` + PreviewSeconds int32 `gorm:"column:preview_seconds;type:integer;default:60" json:"preview_seconds"` + PreviewDownloadable bool `gorm:"column:preview_downloadable;type:boolean" json:"preview_downloadable"` + PublishedAt time.Time `gorm:"column:published_at;type:timestamp with time zone" json:"published_at"` + Summary string `gorm:"column:summary;type:character varying(256)" json:"summary"` + Tags types.JSON `gorm:"column:tags;type:jsonb;default:[]" json:"tags"` + Body string `gorm:"column:body;type:text" json:"body"` + Genre string `gorm:"column:genre;type:character varying(64)" json:"genre"` + Views int32 `gorm:"column:views;type:integer" json:"views"` + Likes int32 `gorm:"column:likes;type:integer" json:"likes"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Content) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Content.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Content) Save(ctx context.Context) error { return Q.Content.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *Content) Create(ctx context.Context) error { return Q.Content.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *Content) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Content.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Content) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Content.WithContext(ctx).Unscoped().Delete(m) +} + +// Restore sets deleted_at to NULL for this model's primary key using the default DB. +func (m *Content) Restore(ctx context.Context) (gen.ResultInfo, error) { + return Q.Content.WithContext(ctx).RestoreByID(m.ID) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Content) Reload(ctx context.Context) error { + fresh, err := Q.Content.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/contents.query.gen.go b/models/contents.query.gen.go new file mode 100644 index 0000000..7bf9659 --- /dev/null +++ b/models/contents.query.gen.go @@ -0,0 +1,546 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newContent(db *gorm.DB, opts ...gen.DOOption) contentQuery { + _contentQuery := contentQuery{} + + _contentQuery.contentQueryDo.UseDB(db, opts...) + _contentQuery.contentQueryDo.UseModel(&Content{}) + + tableName := _contentQuery.contentQueryDo.TableName() + _contentQuery.ALL = field.NewAsterisk(tableName) + _contentQuery.ID = field.NewInt64(tableName, "id") + _contentQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _contentQuery.UserID = field.NewInt64(tableName, "user_id") + _contentQuery.Title = field.NewString(tableName, "title") + _contentQuery.Description = field.NewString(tableName, "description") + _contentQuery.Status = field.NewString(tableName, "status") + _contentQuery.Visibility = field.NewString(tableName, "visibility") + _contentQuery.PreviewSeconds = field.NewInt32(tableName, "preview_seconds") + _contentQuery.PreviewDownloadable = field.NewBool(tableName, "preview_downloadable") + _contentQuery.PublishedAt = field.NewTime(tableName, "published_at") + _contentQuery.Summary = field.NewString(tableName, "summary") + _contentQuery.Tags = field.NewJSONB(tableName, "tags") + _contentQuery.Body = field.NewString(tableName, "body") + _contentQuery.Genre = field.NewString(tableName, "genre") + _contentQuery.Views = field.NewInt32(tableName, "views") + _contentQuery.Likes = field.NewInt32(tableName, "likes") + _contentQuery.CreatedAt = field.NewTime(tableName, "created_at") + _contentQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _contentQuery.DeletedAt = field.NewField(tableName, "deleted_at") + + _contentQuery.fillFieldMap() + + return _contentQuery +} + +type contentQuery struct { + contentQueryDo contentQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Title field.String + Description field.String + Status field.String + Visibility field.String + PreviewSeconds field.Int32 + PreviewDownloadable field.Bool + PublishedAt field.Time + Summary field.String + Tags field.JSONB + Body field.String + Genre field.String + Views field.Int32 + Likes field.Int32 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + + fieldMap map[string]field.Expr +} + +func (c contentQuery) Table(newTableName string) *contentQuery { + c.contentQueryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c contentQuery) As(alias string) *contentQuery { + c.contentQueryDo.DO = *(c.contentQueryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *contentQuery) updateTableName(table string) *contentQuery { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.TenantID = field.NewInt64(table, "tenant_id") + c.UserID = field.NewInt64(table, "user_id") + c.Title = field.NewString(table, "title") + c.Description = field.NewString(table, "description") + c.Status = field.NewString(table, "status") + c.Visibility = field.NewString(table, "visibility") + c.PreviewSeconds = field.NewInt32(table, "preview_seconds") + c.PreviewDownloadable = field.NewBool(table, "preview_downloadable") + c.PublishedAt = field.NewTime(table, "published_at") + c.Summary = field.NewString(table, "summary") + c.Tags = field.NewJSONB(table, "tags") + c.Body = field.NewString(table, "body") + c.Genre = field.NewString(table, "genre") + c.Views = field.NewInt32(table, "views") + c.Likes = field.NewInt32(table, "likes") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + + c.fillFieldMap() + + return c +} + +func (c *contentQuery) QueryContext(ctx context.Context) (*contentQuery, *contentQueryDo) { + return c, c.contentQueryDo.WithContext(ctx) +} + +func (c *contentQuery) WithContext(ctx context.Context) *contentQueryDo { + return c.contentQueryDo.WithContext(ctx) +} + +func (c contentQuery) TableName() string { return c.contentQueryDo.TableName() } + +func (c contentQuery) Alias() string { return c.contentQueryDo.Alias() } + +func (c contentQuery) Columns(cols ...field.Expr) gen.Columns { + return c.contentQueryDo.Columns(cols...) +} + +func (c *contentQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *contentQuery) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 19) + c.fieldMap["id"] = c.ID + c.fieldMap["tenant_id"] = c.TenantID + c.fieldMap["user_id"] = c.UserID + c.fieldMap["title"] = c.Title + c.fieldMap["description"] = c.Description + c.fieldMap["status"] = c.Status + c.fieldMap["visibility"] = c.Visibility + c.fieldMap["preview_seconds"] = c.PreviewSeconds + c.fieldMap["preview_downloadable"] = c.PreviewDownloadable + c.fieldMap["published_at"] = c.PublishedAt + c.fieldMap["summary"] = c.Summary + c.fieldMap["tags"] = c.Tags + c.fieldMap["body"] = c.Body + c.fieldMap["genre"] = c.Genre + c.fieldMap["views"] = c.Views + c.fieldMap["likes"] = c.Likes + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt +} + +func (c contentQuery) clone(db *gorm.DB) contentQuery { + c.contentQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c contentQuery) replaceDB(db *gorm.DB) contentQuery { + c.contentQueryDo.ReplaceDB(db) + return c +} + +type contentQueryDo struct{ gen.DO } + +func (c contentQueryDo) Debug() *contentQueryDo { + return c.withDO(c.DO.Debug()) +} + +func (c contentQueryDo) WithContext(ctx context.Context) *contentQueryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c contentQueryDo) ReadDB() *contentQueryDo { + return c.Clauses(dbresolver.Read) +} + +func (c contentQueryDo) WriteDB() *contentQueryDo { + return c.Clauses(dbresolver.Write) +} + +func (c contentQueryDo) Session(config *gorm.Session) *contentQueryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c contentQueryDo) Clauses(conds ...clause.Expression) *contentQueryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c contentQueryDo) Returning(value interface{}, columns ...string) *contentQueryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c contentQueryDo) Not(conds ...gen.Condition) *contentQueryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c contentQueryDo) Or(conds ...gen.Condition) *contentQueryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c contentQueryDo) Select(conds ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c contentQueryDo) Where(conds ...gen.Condition) *contentQueryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c contentQueryDo) Order(conds ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c contentQueryDo) Distinct(cols ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c contentQueryDo) Omit(cols ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c contentQueryDo) Join(table schema.Tabler, on ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c contentQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c contentQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c contentQueryDo) Group(cols ...field.Expr) *contentQueryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c contentQueryDo) Having(conds ...gen.Condition) *contentQueryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c contentQueryDo) Limit(limit int) *contentQueryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c contentQueryDo) Offset(offset int) *contentQueryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c contentQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *contentQueryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c contentQueryDo) Unscoped() *contentQueryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c contentQueryDo) Create(values ...*Content) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c contentQueryDo) CreateInBatches(values []*Content, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c contentQueryDo) Save(values ...*Content) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c contentQueryDo) First() (*Content, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*Content), nil + } +} + +func (c contentQueryDo) Take() (*Content, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Content), nil + } +} + +func (c contentQueryDo) Last() (*Content, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Content), nil + } +} + +func (c contentQueryDo) Find() ([]*Content, error) { + result, err := c.DO.Find() + return result.([]*Content), err +} + +func (c contentQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Content, err error) { + buf := make([]*Content, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c contentQueryDo) FindInBatches(result *[]*Content, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c contentQueryDo) Attrs(attrs ...field.AssignExpr) *contentQueryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c contentQueryDo) Assign(attrs ...field.AssignExpr) *contentQueryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c contentQueryDo) Joins(fields ...field.RelationField) *contentQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c contentQueryDo) Preload(fields ...field.RelationField) *contentQueryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c contentQueryDo) FirstOrInit() (*Content, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Content), nil + } +} + +func (c contentQueryDo) FirstOrCreate() (*Content, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Content), nil + } +} + +func (c contentQueryDo) FindByPage(offset int, limit int) (result []*Content, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c contentQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c contentQueryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c contentQueryDo) Delete(models ...*Content) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (c contentQueryDo) ForceDelete() (gen.ResultInfo, error) { + return c.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (c contentQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (c contentQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return c.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (c contentQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (c contentQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (c contentQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (c contentQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := c.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (c contentQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := c.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (c contentQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := c.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (c contentQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(c.TableName(), "id") + if err := c.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (c contentQueryDo) GetByID(id int64) (*Content, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (c contentQueryDo) GetByIDs(ids ...int64) ([]*Content, error) { + if len(ids) == 0 { + return []*Content{}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (c contentQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (c contentQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(c.TableName(), "id") + return c.Where(pk.In(ids...)).Delete() +} + +// RestoreWhere sets deleted_at to NULL for rows matching current scope + conds. +func (c contentQueryDo) RestoreWhere(conds ...gen.Condition) (gen.ResultInfo, error) { + col := field.NewField(c.TableName(), "deleted_at") + return c.Unscoped().Where(conds...).UpdateColumn(col, nil) +} + +// RestoreByID sets deleted_at to NULL for the given primary key. +func (c contentQueryDo) RestoreByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(c.TableName(), "id") + col := field.NewField(c.TableName(), "deleted_at") + return c.Unscoped().Where(pk.Eq(id)).UpdateColumn(col, nil) +} + +func (c *contentQueryDo) withDO(do gen.Dao) *contentQueryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/models/media_assets.gen.go b/models/media_assets.gen.go new file mode 100644 index 0000000..ba20847 --- /dev/null +++ b/models/media_assets.gen.go @@ -0,0 +1,73 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" + "gorm.io/gorm" +) + +const TableNameMediaAsset = "media_assets" + +// MediaAsset mapped from table +type MediaAsset struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Type string `gorm:"column:type;type:character varying(32);default:video" json:"type"` + Status string `gorm:"column:status;type:character varying(32);default:uploaded" json:"status"` + Provider string `gorm:"column:provider;type:character varying(64);not null" json:"provider"` + Bucket string `gorm:"column:bucket;type:character varying(128);not null" json:"bucket"` + ObjectKey string `gorm:"column:object_key;type:character varying(512);not null" json:"object_key"` + Meta types.JSON `gorm:"column:meta;type:jsonb;default:{}" json:"meta"` + Variant string `gorm:"column:variant;type:character varying(32);default:main" json:"variant"` + SourceAssetID int64 `gorm:"column:source_asset_id;type:bigint" json:"source_asset_id"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *MediaAsset) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.MediaAsset.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *MediaAsset) Save(ctx context.Context) error { return Q.MediaAsset.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *MediaAsset) Create(ctx context.Context) error { + return Q.MediaAsset.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *MediaAsset) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.MediaAsset.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *MediaAsset) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.MediaAsset.WithContext(ctx).Unscoped().Delete(m) +} + +// Restore sets deleted_at to NULL for this model's primary key using the default DB. +func (m *MediaAsset) Restore(ctx context.Context) (gen.ResultInfo, error) { + return Q.MediaAsset.WithContext(ctx).RestoreByID(m.ID) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *MediaAsset) Reload(ctx context.Context) error { + fresh, err := Q.MediaAsset.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/media_assets.query.gen.go b/models/media_assets.query.gen.go new file mode 100644 index 0000000..dbc7764 --- /dev/null +++ b/models/media_assets.query.gen.go @@ -0,0 +1,526 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newMediaAsset(db *gorm.DB, opts ...gen.DOOption) mediaAssetQuery { + _mediaAssetQuery := mediaAssetQuery{} + + _mediaAssetQuery.mediaAssetQueryDo.UseDB(db, opts...) + _mediaAssetQuery.mediaAssetQueryDo.UseModel(&MediaAsset{}) + + tableName := _mediaAssetQuery.mediaAssetQueryDo.TableName() + _mediaAssetQuery.ALL = field.NewAsterisk(tableName) + _mediaAssetQuery.ID = field.NewInt64(tableName, "id") + _mediaAssetQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _mediaAssetQuery.UserID = field.NewInt64(tableName, "user_id") + _mediaAssetQuery.Type = field.NewString(tableName, "type") + _mediaAssetQuery.Status = field.NewString(tableName, "status") + _mediaAssetQuery.Provider = field.NewString(tableName, "provider") + _mediaAssetQuery.Bucket = field.NewString(tableName, "bucket") + _mediaAssetQuery.ObjectKey = field.NewString(tableName, "object_key") + _mediaAssetQuery.Meta = field.NewJSONB(tableName, "meta") + _mediaAssetQuery.Variant = field.NewString(tableName, "variant") + _mediaAssetQuery.SourceAssetID = field.NewInt64(tableName, "source_asset_id") + _mediaAssetQuery.CreatedAt = field.NewTime(tableName, "created_at") + _mediaAssetQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _mediaAssetQuery.DeletedAt = field.NewField(tableName, "deleted_at") + + _mediaAssetQuery.fillFieldMap() + + return _mediaAssetQuery +} + +type mediaAssetQuery struct { + mediaAssetQueryDo mediaAssetQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Type field.String + Status field.String + Provider field.String + Bucket field.String + ObjectKey field.String + Meta field.JSONB + Variant field.String + SourceAssetID field.Int64 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + + fieldMap map[string]field.Expr +} + +func (m mediaAssetQuery) Table(newTableName string) *mediaAssetQuery { + m.mediaAssetQueryDo.UseTable(newTableName) + return m.updateTableName(newTableName) +} + +func (m mediaAssetQuery) As(alias string) *mediaAssetQuery { + m.mediaAssetQueryDo.DO = *(m.mediaAssetQueryDo.As(alias).(*gen.DO)) + return m.updateTableName(alias) +} + +func (m *mediaAssetQuery) updateTableName(table string) *mediaAssetQuery { + m.ALL = field.NewAsterisk(table) + m.ID = field.NewInt64(table, "id") + m.TenantID = field.NewInt64(table, "tenant_id") + m.UserID = field.NewInt64(table, "user_id") + m.Type = field.NewString(table, "type") + m.Status = field.NewString(table, "status") + m.Provider = field.NewString(table, "provider") + m.Bucket = field.NewString(table, "bucket") + m.ObjectKey = field.NewString(table, "object_key") + m.Meta = field.NewJSONB(table, "meta") + m.Variant = field.NewString(table, "variant") + m.SourceAssetID = field.NewInt64(table, "source_asset_id") + m.CreatedAt = field.NewTime(table, "created_at") + m.UpdatedAt = field.NewTime(table, "updated_at") + m.DeletedAt = field.NewField(table, "deleted_at") + + m.fillFieldMap() + + return m +} + +func (m *mediaAssetQuery) QueryContext(ctx context.Context) (*mediaAssetQuery, *mediaAssetQueryDo) { + return m, m.mediaAssetQueryDo.WithContext(ctx) +} + +func (m *mediaAssetQuery) WithContext(ctx context.Context) *mediaAssetQueryDo { + return m.mediaAssetQueryDo.WithContext(ctx) +} + +func (m mediaAssetQuery) TableName() string { return m.mediaAssetQueryDo.TableName() } + +func (m mediaAssetQuery) Alias() string { return m.mediaAssetQueryDo.Alias() } + +func (m mediaAssetQuery) Columns(cols ...field.Expr) gen.Columns { + return m.mediaAssetQueryDo.Columns(cols...) +} + +func (m *mediaAssetQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := m.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (m *mediaAssetQuery) fillFieldMap() { + m.fieldMap = make(map[string]field.Expr, 14) + m.fieldMap["id"] = m.ID + m.fieldMap["tenant_id"] = m.TenantID + m.fieldMap["user_id"] = m.UserID + m.fieldMap["type"] = m.Type + m.fieldMap["status"] = m.Status + m.fieldMap["provider"] = m.Provider + m.fieldMap["bucket"] = m.Bucket + m.fieldMap["object_key"] = m.ObjectKey + m.fieldMap["meta"] = m.Meta + m.fieldMap["variant"] = m.Variant + m.fieldMap["source_asset_id"] = m.SourceAssetID + m.fieldMap["created_at"] = m.CreatedAt + m.fieldMap["updated_at"] = m.UpdatedAt + m.fieldMap["deleted_at"] = m.DeletedAt +} + +func (m mediaAssetQuery) clone(db *gorm.DB) mediaAssetQuery { + m.mediaAssetQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return m +} + +func (m mediaAssetQuery) replaceDB(db *gorm.DB) mediaAssetQuery { + m.mediaAssetQueryDo.ReplaceDB(db) + return m +} + +type mediaAssetQueryDo struct{ gen.DO } + +func (m mediaAssetQueryDo) Debug() *mediaAssetQueryDo { + return m.withDO(m.DO.Debug()) +} + +func (m mediaAssetQueryDo) WithContext(ctx context.Context) *mediaAssetQueryDo { + return m.withDO(m.DO.WithContext(ctx)) +} + +func (m mediaAssetQueryDo) ReadDB() *mediaAssetQueryDo { + return m.Clauses(dbresolver.Read) +} + +func (m mediaAssetQueryDo) WriteDB() *mediaAssetQueryDo { + return m.Clauses(dbresolver.Write) +} + +func (m mediaAssetQueryDo) Session(config *gorm.Session) *mediaAssetQueryDo { + return m.withDO(m.DO.Session(config)) +} + +func (m mediaAssetQueryDo) Clauses(conds ...clause.Expression) *mediaAssetQueryDo { + return m.withDO(m.DO.Clauses(conds...)) +} + +func (m mediaAssetQueryDo) Returning(value interface{}, columns ...string) *mediaAssetQueryDo { + return m.withDO(m.DO.Returning(value, columns...)) +} + +func (m mediaAssetQueryDo) Not(conds ...gen.Condition) *mediaAssetQueryDo { + return m.withDO(m.DO.Not(conds...)) +} + +func (m mediaAssetQueryDo) Or(conds ...gen.Condition) *mediaAssetQueryDo { + return m.withDO(m.DO.Or(conds...)) +} + +func (m mediaAssetQueryDo) Select(conds ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.Select(conds...)) +} + +func (m mediaAssetQueryDo) Where(conds ...gen.Condition) *mediaAssetQueryDo { + return m.withDO(m.DO.Where(conds...)) +} + +func (m mediaAssetQueryDo) Order(conds ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.Order(conds...)) +} + +func (m mediaAssetQueryDo) Distinct(cols ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.Distinct(cols...)) +} + +func (m mediaAssetQueryDo) Omit(cols ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.Omit(cols...)) +} + +func (m mediaAssetQueryDo) Join(table schema.Tabler, on ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.Join(table, on...)) +} + +func (m mediaAssetQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.LeftJoin(table, on...)) +} + +func (m mediaAssetQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.RightJoin(table, on...)) +} + +func (m mediaAssetQueryDo) Group(cols ...field.Expr) *mediaAssetQueryDo { + return m.withDO(m.DO.Group(cols...)) +} + +func (m mediaAssetQueryDo) Having(conds ...gen.Condition) *mediaAssetQueryDo { + return m.withDO(m.DO.Having(conds...)) +} + +func (m mediaAssetQueryDo) Limit(limit int) *mediaAssetQueryDo { + return m.withDO(m.DO.Limit(limit)) +} + +func (m mediaAssetQueryDo) Offset(offset int) *mediaAssetQueryDo { + return m.withDO(m.DO.Offset(offset)) +} + +func (m mediaAssetQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *mediaAssetQueryDo { + return m.withDO(m.DO.Scopes(funcs...)) +} + +func (m mediaAssetQueryDo) Unscoped() *mediaAssetQueryDo { + return m.withDO(m.DO.Unscoped()) +} + +func (m mediaAssetQueryDo) Create(values ...*MediaAsset) error { + if len(values) == 0 { + return nil + } + return m.DO.Create(values) +} + +func (m mediaAssetQueryDo) CreateInBatches(values []*MediaAsset, batchSize int) error { + return m.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (m mediaAssetQueryDo) Save(values ...*MediaAsset) error { + if len(values) == 0 { + return nil + } + return m.DO.Save(values) +} + +func (m mediaAssetQueryDo) First() (*MediaAsset, error) { + if result, err := m.DO.First(); err != nil { + return nil, err + } else { + return result.(*MediaAsset), nil + } +} + +func (m mediaAssetQueryDo) Take() (*MediaAsset, error) { + if result, err := m.DO.Take(); err != nil { + return nil, err + } else { + return result.(*MediaAsset), nil + } +} + +func (m mediaAssetQueryDo) Last() (*MediaAsset, error) { + if result, err := m.DO.Last(); err != nil { + return nil, err + } else { + return result.(*MediaAsset), nil + } +} + +func (m mediaAssetQueryDo) Find() ([]*MediaAsset, error) { + result, err := m.DO.Find() + return result.([]*MediaAsset), err +} + +func (m mediaAssetQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*MediaAsset, err error) { + buf := make([]*MediaAsset, 0, batchSize) + err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (m mediaAssetQueryDo) FindInBatches(result *[]*MediaAsset, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return m.DO.FindInBatches(result, batchSize, fc) +} + +func (m mediaAssetQueryDo) Attrs(attrs ...field.AssignExpr) *mediaAssetQueryDo { + return m.withDO(m.DO.Attrs(attrs...)) +} + +func (m mediaAssetQueryDo) Assign(attrs ...field.AssignExpr) *mediaAssetQueryDo { + return m.withDO(m.DO.Assign(attrs...)) +} + +func (m mediaAssetQueryDo) Joins(fields ...field.RelationField) *mediaAssetQueryDo { + for _, _f := range fields { + m = *m.withDO(m.DO.Joins(_f)) + } + return &m +} + +func (m mediaAssetQueryDo) Preload(fields ...field.RelationField) *mediaAssetQueryDo { + for _, _f := range fields { + m = *m.withDO(m.DO.Preload(_f)) + } + return &m +} + +func (m mediaAssetQueryDo) FirstOrInit() (*MediaAsset, error) { + if result, err := m.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*MediaAsset), nil + } +} + +func (m mediaAssetQueryDo) FirstOrCreate() (*MediaAsset, error) { + if result, err := m.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*MediaAsset), nil + } +} + +func (m mediaAssetQueryDo) FindByPage(offset int, limit int) (result []*MediaAsset, count int64, err error) { + result, err = m.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = m.Offset(-1).Limit(-1).Count() + return +} + +func (m mediaAssetQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = m.Count() + if err != nil { + return + } + + err = m.Offset(offset).Limit(limit).Scan(result) + return +} + +func (m mediaAssetQueryDo) Scan(result interface{}) (err error) { + return m.DO.Scan(result) +} + +func (m mediaAssetQueryDo) Delete(models ...*MediaAsset) (result gen.ResultInfo, err error) { + return m.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (m mediaAssetQueryDo) ForceDelete() (gen.ResultInfo, error) { + return m.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (m mediaAssetQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return m.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (m mediaAssetQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return m.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (m mediaAssetQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := m.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (m mediaAssetQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := m.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (m mediaAssetQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := m.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (m mediaAssetQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := m.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (m mediaAssetQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := m.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (m mediaAssetQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := m.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (m mediaAssetQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(m.TableName(), "id") + if err := m.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (m mediaAssetQueryDo) GetByID(id int64) (*MediaAsset, error) { + pk := field.NewInt64(m.TableName(), "id") + return m.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (m mediaAssetQueryDo) GetByIDs(ids ...int64) ([]*MediaAsset, error) { + if len(ids) == 0 { + return []*MediaAsset{}, nil + } + pk := field.NewInt64(m.TableName(), "id") + return m.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (m mediaAssetQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(m.TableName(), "id") + return m.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (m mediaAssetQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(m.TableName(), "id") + return m.Where(pk.In(ids...)).Delete() +} + +// RestoreWhere sets deleted_at to NULL for rows matching current scope + conds. +func (m mediaAssetQueryDo) RestoreWhere(conds ...gen.Condition) (gen.ResultInfo, error) { + col := field.NewField(m.TableName(), "deleted_at") + return m.Unscoped().Where(conds...).UpdateColumn(col, nil) +} + +// RestoreByID sets deleted_at to NULL for the given primary key. +func (m mediaAssetQueryDo) RestoreByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(m.TableName(), "id") + col := field.NewField(m.TableName(), "deleted_at") + return m.Unscoped().Where(pk.Eq(id)).UpdateColumn(col, nil) +} + +func (m *mediaAssetQueryDo) withDO(do gen.Dao) *mediaAssetQueryDo { + m.DO = *do.(*gen.DO) + return m +} diff --git a/models/notifications.gen.go b/models/notifications.gen.go new file mode 100644 index 0000000..3854b06 --- /dev/null +++ b/models/notifications.gen.go @@ -0,0 +1,62 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameNotification = "notifications" + +// Notification mapped from table +type Notification struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint" json:"tenant_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + Title string `gorm:"column:title;type:character varying(255);not null" json:"title"` + Content string `gorm:"column:content;type:text;not null" json:"content"` + IsRead bool `gorm:"column:is_read;type:boolean" json:"is_read"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Notification) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Notification.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Notification) Save(ctx context.Context) error { + return Q.Notification.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *Notification) Create(ctx context.Context) error { + return Q.Notification.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *Notification) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Notification.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Notification) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Notification.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Notification) Reload(ctx context.Context) error { + fresh, err := Q.Notification.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/notifications.query.gen.go b/models/notifications.query.gen.go new file mode 100644 index 0000000..4d9d51b --- /dev/null +++ b/models/notifications.query.gen.go @@ -0,0 +1,489 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newNotification(db *gorm.DB, opts ...gen.DOOption) notificationQuery { + _notificationQuery := notificationQuery{} + + _notificationQuery.notificationQueryDo.UseDB(db, opts...) + _notificationQuery.notificationQueryDo.UseModel(&Notification{}) + + tableName := _notificationQuery.notificationQueryDo.TableName() + _notificationQuery.ALL = field.NewAsterisk(tableName) + _notificationQuery.ID = field.NewInt64(tableName, "id") + _notificationQuery.UserID = field.NewInt64(tableName, "user_id") + _notificationQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _notificationQuery.Type = field.NewString(tableName, "type") + _notificationQuery.Title = field.NewString(tableName, "title") + _notificationQuery.Content = field.NewString(tableName, "content") + _notificationQuery.IsRead = field.NewBool(tableName, "is_read") + _notificationQuery.CreatedAt = field.NewTime(tableName, "created_at") + + _notificationQuery.fillFieldMap() + + return _notificationQuery +} + +type notificationQuery struct { + notificationQueryDo notificationQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + TenantID field.Int64 + Type field.String + Title field.String + Content field.String + IsRead field.Bool + CreatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (n notificationQuery) Table(newTableName string) *notificationQuery { + n.notificationQueryDo.UseTable(newTableName) + return n.updateTableName(newTableName) +} + +func (n notificationQuery) As(alias string) *notificationQuery { + n.notificationQueryDo.DO = *(n.notificationQueryDo.As(alias).(*gen.DO)) + return n.updateTableName(alias) +} + +func (n *notificationQuery) updateTableName(table string) *notificationQuery { + n.ALL = field.NewAsterisk(table) + n.ID = field.NewInt64(table, "id") + n.UserID = field.NewInt64(table, "user_id") + n.TenantID = field.NewInt64(table, "tenant_id") + n.Type = field.NewString(table, "type") + n.Title = field.NewString(table, "title") + n.Content = field.NewString(table, "content") + n.IsRead = field.NewBool(table, "is_read") + n.CreatedAt = field.NewTime(table, "created_at") + + n.fillFieldMap() + + return n +} + +func (n *notificationQuery) QueryContext(ctx context.Context) (*notificationQuery, *notificationQueryDo) { + return n, n.notificationQueryDo.WithContext(ctx) +} + +func (n *notificationQuery) WithContext(ctx context.Context) *notificationQueryDo { + return n.notificationQueryDo.WithContext(ctx) +} + +func (n notificationQuery) TableName() string { return n.notificationQueryDo.TableName() } + +func (n notificationQuery) Alias() string { return n.notificationQueryDo.Alias() } + +func (n notificationQuery) Columns(cols ...field.Expr) gen.Columns { + return n.notificationQueryDo.Columns(cols...) +} + +func (n *notificationQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := n.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (n *notificationQuery) fillFieldMap() { + n.fieldMap = make(map[string]field.Expr, 8) + n.fieldMap["id"] = n.ID + n.fieldMap["user_id"] = n.UserID + n.fieldMap["tenant_id"] = n.TenantID + n.fieldMap["type"] = n.Type + n.fieldMap["title"] = n.Title + n.fieldMap["content"] = n.Content + n.fieldMap["is_read"] = n.IsRead + n.fieldMap["created_at"] = n.CreatedAt +} + +func (n notificationQuery) clone(db *gorm.DB) notificationQuery { + n.notificationQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return n +} + +func (n notificationQuery) replaceDB(db *gorm.DB) notificationQuery { + n.notificationQueryDo.ReplaceDB(db) + return n +} + +type notificationQueryDo struct{ gen.DO } + +func (n notificationQueryDo) Debug() *notificationQueryDo { + return n.withDO(n.DO.Debug()) +} + +func (n notificationQueryDo) WithContext(ctx context.Context) *notificationQueryDo { + return n.withDO(n.DO.WithContext(ctx)) +} + +func (n notificationQueryDo) ReadDB() *notificationQueryDo { + return n.Clauses(dbresolver.Read) +} + +func (n notificationQueryDo) WriteDB() *notificationQueryDo { + return n.Clauses(dbresolver.Write) +} + +func (n notificationQueryDo) Session(config *gorm.Session) *notificationQueryDo { + return n.withDO(n.DO.Session(config)) +} + +func (n notificationQueryDo) Clauses(conds ...clause.Expression) *notificationQueryDo { + return n.withDO(n.DO.Clauses(conds...)) +} + +func (n notificationQueryDo) Returning(value interface{}, columns ...string) *notificationQueryDo { + return n.withDO(n.DO.Returning(value, columns...)) +} + +func (n notificationQueryDo) Not(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Not(conds...)) +} + +func (n notificationQueryDo) Or(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Or(conds...)) +} + +func (n notificationQueryDo) Select(conds ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Select(conds...)) +} + +func (n notificationQueryDo) Where(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Where(conds...)) +} + +func (n notificationQueryDo) Order(conds ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Order(conds...)) +} + +func (n notificationQueryDo) Distinct(cols ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Distinct(cols...)) +} + +func (n notificationQueryDo) Omit(cols ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Omit(cols...)) +} + +func (n notificationQueryDo) Join(table schema.Tabler, on ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Join(table, on...)) +} + +func (n notificationQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.LeftJoin(table, on...)) +} + +func (n notificationQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.RightJoin(table, on...)) +} + +func (n notificationQueryDo) Group(cols ...field.Expr) *notificationQueryDo { + return n.withDO(n.DO.Group(cols...)) +} + +func (n notificationQueryDo) Having(conds ...gen.Condition) *notificationQueryDo { + return n.withDO(n.DO.Having(conds...)) +} + +func (n notificationQueryDo) Limit(limit int) *notificationQueryDo { + return n.withDO(n.DO.Limit(limit)) +} + +func (n notificationQueryDo) Offset(offset int) *notificationQueryDo { + return n.withDO(n.DO.Offset(offset)) +} + +func (n notificationQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *notificationQueryDo { + return n.withDO(n.DO.Scopes(funcs...)) +} + +func (n notificationQueryDo) Unscoped() *notificationQueryDo { + return n.withDO(n.DO.Unscoped()) +} + +func (n notificationQueryDo) Create(values ...*Notification) error { + if len(values) == 0 { + return nil + } + return n.DO.Create(values) +} + +func (n notificationQueryDo) CreateInBatches(values []*Notification, batchSize int) error { + return n.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (n notificationQueryDo) Save(values ...*Notification) error { + if len(values) == 0 { + return nil + } + return n.DO.Save(values) +} + +func (n notificationQueryDo) First() (*Notification, error) { + if result, err := n.DO.First(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) Take() (*Notification, error) { + if result, err := n.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) Last() (*Notification, error) { + if result, err := n.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) Find() ([]*Notification, error) { + result, err := n.DO.Find() + return result.([]*Notification), err +} + +func (n notificationQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Notification, err error) { + buf := make([]*Notification, 0, batchSize) + err = n.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (n notificationQueryDo) FindInBatches(result *[]*Notification, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return n.DO.FindInBatches(result, batchSize, fc) +} + +func (n notificationQueryDo) Attrs(attrs ...field.AssignExpr) *notificationQueryDo { + return n.withDO(n.DO.Attrs(attrs...)) +} + +func (n notificationQueryDo) Assign(attrs ...field.AssignExpr) *notificationQueryDo { + return n.withDO(n.DO.Assign(attrs...)) +} + +func (n notificationQueryDo) Joins(fields ...field.RelationField) *notificationQueryDo { + for _, _f := range fields { + n = *n.withDO(n.DO.Joins(_f)) + } + return &n +} + +func (n notificationQueryDo) Preload(fields ...field.RelationField) *notificationQueryDo { + for _, _f := range fields { + n = *n.withDO(n.DO.Preload(_f)) + } + return &n +} + +func (n notificationQueryDo) FirstOrInit() (*Notification, error) { + if result, err := n.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) FirstOrCreate() (*Notification, error) { + if result, err := n.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Notification), nil + } +} + +func (n notificationQueryDo) FindByPage(offset int, limit int) (result []*Notification, count int64, err error) { + result, err = n.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = n.Offset(-1).Limit(-1).Count() + return +} + +func (n notificationQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = n.Count() + if err != nil { + return + } + + err = n.Offset(offset).Limit(limit).Scan(result) + return +} + +func (n notificationQueryDo) Scan(result interface{}) (err error) { + return n.DO.Scan(result) +} + +func (n notificationQueryDo) Delete(models ...*Notification) (result gen.ResultInfo, err error) { + return n.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (n notificationQueryDo) ForceDelete() (gen.ResultInfo, error) { + return n.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (n notificationQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return n.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (n notificationQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return n.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (n notificationQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (n notificationQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (n notificationQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (n notificationQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := n.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (n notificationQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := n.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (n notificationQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := n.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (n notificationQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(n.TableName(), "id") + if err := n.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (n notificationQueryDo) GetByID(id int64) (*Notification, error) { + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (n notificationQueryDo) GetByIDs(ids ...int64) ([]*Notification, error) { + if len(ids) == 0 { + return []*Notification{}, nil + } + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (n notificationQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (n notificationQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(n.TableName(), "id") + return n.Where(pk.In(ids...)).Delete() +} + +func (n *notificationQueryDo) withDO(do gen.Dao) *notificationQueryDo { + n.DO = *do.(*gen.DO) + return n +} diff --git a/models/order_items.gen.go b/models/order_items.gen.go new file mode 100644 index 0000000..19c69e7 --- /dev/null +++ b/models/order_items.gen.go @@ -0,0 +1,61 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" +) + +const TableNameOrderItem = "order_items" + +// OrderItem mapped from table +type OrderItem struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + OrderID int64 `gorm:"column:order_id;type:bigint;not null" json:"order_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + ContentUserID int64 `gorm:"column:content_user_id;type:bigint;not null" json:"content_user_id"` + AmountPaid int64 `gorm:"column:amount_paid;type:bigint;not null" json:"amount_paid"` + Snapshot types.JSON `gorm:"column:snapshot;type:jsonb;default:{}" json:"snapshot"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *OrderItem) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.OrderItem.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *OrderItem) Save(ctx context.Context) error { return Q.OrderItem.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *OrderItem) Create(ctx context.Context) error { return Q.OrderItem.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *OrderItem) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.OrderItem.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *OrderItem) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.OrderItem.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *OrderItem) Reload(ctx context.Context) error { + fresh, err := Q.OrderItem.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/order_items.query.gen.go b/models/order_items.query.gen.go new file mode 100644 index 0000000..8bca5ee --- /dev/null +++ b/models/order_items.query.gen.go @@ -0,0 +1,497 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newOrderItem(db *gorm.DB, opts ...gen.DOOption) orderItemQuery { + _orderItemQuery := orderItemQuery{} + + _orderItemQuery.orderItemQueryDo.UseDB(db, opts...) + _orderItemQuery.orderItemQueryDo.UseModel(&OrderItem{}) + + tableName := _orderItemQuery.orderItemQueryDo.TableName() + _orderItemQuery.ALL = field.NewAsterisk(tableName) + _orderItemQuery.ID = field.NewInt64(tableName, "id") + _orderItemQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _orderItemQuery.UserID = field.NewInt64(tableName, "user_id") + _orderItemQuery.OrderID = field.NewInt64(tableName, "order_id") + _orderItemQuery.ContentID = field.NewInt64(tableName, "content_id") + _orderItemQuery.ContentUserID = field.NewInt64(tableName, "content_user_id") + _orderItemQuery.AmountPaid = field.NewInt64(tableName, "amount_paid") + _orderItemQuery.Snapshot = field.NewJSONB(tableName, "snapshot") + _orderItemQuery.CreatedAt = field.NewTime(tableName, "created_at") + _orderItemQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _orderItemQuery.fillFieldMap() + + return _orderItemQuery +} + +type orderItemQuery struct { + orderItemQueryDo orderItemQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + OrderID field.Int64 + ContentID field.Int64 + ContentUserID field.Int64 + AmountPaid field.Int64 + Snapshot field.JSONB + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (o orderItemQuery) Table(newTableName string) *orderItemQuery { + o.orderItemQueryDo.UseTable(newTableName) + return o.updateTableName(newTableName) +} + +func (o orderItemQuery) As(alias string) *orderItemQuery { + o.orderItemQueryDo.DO = *(o.orderItemQueryDo.As(alias).(*gen.DO)) + return o.updateTableName(alias) +} + +func (o *orderItemQuery) updateTableName(table string) *orderItemQuery { + o.ALL = field.NewAsterisk(table) + o.ID = field.NewInt64(table, "id") + o.TenantID = field.NewInt64(table, "tenant_id") + o.UserID = field.NewInt64(table, "user_id") + o.OrderID = field.NewInt64(table, "order_id") + o.ContentID = field.NewInt64(table, "content_id") + o.ContentUserID = field.NewInt64(table, "content_user_id") + o.AmountPaid = field.NewInt64(table, "amount_paid") + o.Snapshot = field.NewJSONB(table, "snapshot") + o.CreatedAt = field.NewTime(table, "created_at") + o.UpdatedAt = field.NewTime(table, "updated_at") + + o.fillFieldMap() + + return o +} + +func (o *orderItemQuery) QueryContext(ctx context.Context) (*orderItemQuery, *orderItemQueryDo) { + return o, o.orderItemQueryDo.WithContext(ctx) +} + +func (o *orderItemQuery) WithContext(ctx context.Context) *orderItemQueryDo { + return o.orderItemQueryDo.WithContext(ctx) +} + +func (o orderItemQuery) TableName() string { return o.orderItemQueryDo.TableName() } + +func (o orderItemQuery) Alias() string { return o.orderItemQueryDo.Alias() } + +func (o orderItemQuery) Columns(cols ...field.Expr) gen.Columns { + return o.orderItemQueryDo.Columns(cols...) +} + +func (o *orderItemQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := o.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (o *orderItemQuery) fillFieldMap() { + o.fieldMap = make(map[string]field.Expr, 10) + o.fieldMap["id"] = o.ID + o.fieldMap["tenant_id"] = o.TenantID + o.fieldMap["user_id"] = o.UserID + o.fieldMap["order_id"] = o.OrderID + o.fieldMap["content_id"] = o.ContentID + o.fieldMap["content_user_id"] = o.ContentUserID + o.fieldMap["amount_paid"] = o.AmountPaid + o.fieldMap["snapshot"] = o.Snapshot + o.fieldMap["created_at"] = o.CreatedAt + o.fieldMap["updated_at"] = o.UpdatedAt +} + +func (o orderItemQuery) clone(db *gorm.DB) orderItemQuery { + o.orderItemQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return o +} + +func (o orderItemQuery) replaceDB(db *gorm.DB) orderItemQuery { + o.orderItemQueryDo.ReplaceDB(db) + return o +} + +type orderItemQueryDo struct{ gen.DO } + +func (o orderItemQueryDo) Debug() *orderItemQueryDo { + return o.withDO(o.DO.Debug()) +} + +func (o orderItemQueryDo) WithContext(ctx context.Context) *orderItemQueryDo { + return o.withDO(o.DO.WithContext(ctx)) +} + +func (o orderItemQueryDo) ReadDB() *orderItemQueryDo { + return o.Clauses(dbresolver.Read) +} + +func (o orderItemQueryDo) WriteDB() *orderItemQueryDo { + return o.Clauses(dbresolver.Write) +} + +func (o orderItemQueryDo) Session(config *gorm.Session) *orderItemQueryDo { + return o.withDO(o.DO.Session(config)) +} + +func (o orderItemQueryDo) Clauses(conds ...clause.Expression) *orderItemQueryDo { + return o.withDO(o.DO.Clauses(conds...)) +} + +func (o orderItemQueryDo) Returning(value interface{}, columns ...string) *orderItemQueryDo { + return o.withDO(o.DO.Returning(value, columns...)) +} + +func (o orderItemQueryDo) Not(conds ...gen.Condition) *orderItemQueryDo { + return o.withDO(o.DO.Not(conds...)) +} + +func (o orderItemQueryDo) Or(conds ...gen.Condition) *orderItemQueryDo { + return o.withDO(o.DO.Or(conds...)) +} + +func (o orderItemQueryDo) Select(conds ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.Select(conds...)) +} + +func (o orderItemQueryDo) Where(conds ...gen.Condition) *orderItemQueryDo { + return o.withDO(o.DO.Where(conds...)) +} + +func (o orderItemQueryDo) Order(conds ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.Order(conds...)) +} + +func (o orderItemQueryDo) Distinct(cols ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.Distinct(cols...)) +} + +func (o orderItemQueryDo) Omit(cols ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.Omit(cols...)) +} + +func (o orderItemQueryDo) Join(table schema.Tabler, on ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.Join(table, on...)) +} + +func (o orderItemQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.LeftJoin(table, on...)) +} + +func (o orderItemQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.RightJoin(table, on...)) +} + +func (o orderItemQueryDo) Group(cols ...field.Expr) *orderItemQueryDo { + return o.withDO(o.DO.Group(cols...)) +} + +func (o orderItemQueryDo) Having(conds ...gen.Condition) *orderItemQueryDo { + return o.withDO(o.DO.Having(conds...)) +} + +func (o orderItemQueryDo) Limit(limit int) *orderItemQueryDo { + return o.withDO(o.DO.Limit(limit)) +} + +func (o orderItemQueryDo) Offset(offset int) *orderItemQueryDo { + return o.withDO(o.DO.Offset(offset)) +} + +func (o orderItemQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *orderItemQueryDo { + return o.withDO(o.DO.Scopes(funcs...)) +} + +func (o orderItemQueryDo) Unscoped() *orderItemQueryDo { + return o.withDO(o.DO.Unscoped()) +} + +func (o orderItemQueryDo) Create(values ...*OrderItem) error { + if len(values) == 0 { + return nil + } + return o.DO.Create(values) +} + +func (o orderItemQueryDo) CreateInBatches(values []*OrderItem, batchSize int) error { + return o.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (o orderItemQueryDo) Save(values ...*OrderItem) error { + if len(values) == 0 { + return nil + } + return o.DO.Save(values) +} + +func (o orderItemQueryDo) First() (*OrderItem, error) { + if result, err := o.DO.First(); err != nil { + return nil, err + } else { + return result.(*OrderItem), nil + } +} + +func (o orderItemQueryDo) Take() (*OrderItem, error) { + if result, err := o.DO.Take(); err != nil { + return nil, err + } else { + return result.(*OrderItem), nil + } +} + +func (o orderItemQueryDo) Last() (*OrderItem, error) { + if result, err := o.DO.Last(); err != nil { + return nil, err + } else { + return result.(*OrderItem), nil + } +} + +func (o orderItemQueryDo) Find() ([]*OrderItem, error) { + result, err := o.DO.Find() + return result.([]*OrderItem), err +} + +func (o orderItemQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*OrderItem, err error) { + buf := make([]*OrderItem, 0, batchSize) + err = o.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (o orderItemQueryDo) FindInBatches(result *[]*OrderItem, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return o.DO.FindInBatches(result, batchSize, fc) +} + +func (o orderItemQueryDo) Attrs(attrs ...field.AssignExpr) *orderItemQueryDo { + return o.withDO(o.DO.Attrs(attrs...)) +} + +func (o orderItemQueryDo) Assign(attrs ...field.AssignExpr) *orderItemQueryDo { + return o.withDO(o.DO.Assign(attrs...)) +} + +func (o orderItemQueryDo) Joins(fields ...field.RelationField) *orderItemQueryDo { + for _, _f := range fields { + o = *o.withDO(o.DO.Joins(_f)) + } + return &o +} + +func (o orderItemQueryDo) Preload(fields ...field.RelationField) *orderItemQueryDo { + for _, _f := range fields { + o = *o.withDO(o.DO.Preload(_f)) + } + return &o +} + +func (o orderItemQueryDo) FirstOrInit() (*OrderItem, error) { + if result, err := o.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*OrderItem), nil + } +} + +func (o orderItemQueryDo) FirstOrCreate() (*OrderItem, error) { + if result, err := o.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*OrderItem), nil + } +} + +func (o orderItemQueryDo) FindByPage(offset int, limit int) (result []*OrderItem, count int64, err error) { + result, err = o.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = o.Offset(-1).Limit(-1).Count() + return +} + +func (o orderItemQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = o.Count() + if err != nil { + return + } + + err = o.Offset(offset).Limit(limit).Scan(result) + return +} + +func (o orderItemQueryDo) Scan(result interface{}) (err error) { + return o.DO.Scan(result) +} + +func (o orderItemQueryDo) Delete(models ...*OrderItem) (result gen.ResultInfo, err error) { + return o.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (o orderItemQueryDo) ForceDelete() (gen.ResultInfo, error) { + return o.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (o orderItemQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return o.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (o orderItemQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return o.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (o orderItemQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (o orderItemQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (o orderItemQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (o orderItemQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (o orderItemQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := o.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (o orderItemQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := o.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (o orderItemQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(o.TableName(), "id") + if err := o.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (o orderItemQueryDo) GetByID(id int64) (*OrderItem, error) { + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (o orderItemQueryDo) GetByIDs(ids ...int64) ([]*OrderItem, error) { + if len(ids) == 0 { + return []*OrderItem{}, nil + } + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (o orderItemQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (o orderItemQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.In(ids...)).Delete() +} + +func (o *orderItemQueryDo) withDO(do gen.Dao) *orderItemQueryDo { + o.DO = *do.(*gen.DO) + return o +} diff --git a/models/orders.gen.go b/models/orders.gen.go new file mode 100644 index 0000000..c0fa0ad --- /dev/null +++ b/models/orders.gen.go @@ -0,0 +1,69 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" +) + +const TableNameOrder = "orders" + +// Order mapped from table +type Order struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Type string `gorm:"column:type;type:character varying(32);default:content_purchase" json:"type"` + Status string `gorm:"column:status;type:character varying(32);default:created" json:"status"` + Currency string `gorm:"column:currency;type:character varying(16);default:CNY" json:"currency"` + AmountOriginal int64 `gorm:"column:amount_original;type:bigint;not null" json:"amount_original"` + AmountDiscount int64 `gorm:"column:amount_discount;type:bigint;not null" json:"amount_discount"` + AmountPaid int64 `gorm:"column:amount_paid;type:bigint;not null" json:"amount_paid"` + Snapshot types.JSON `gorm:"column:snapshot;type:jsonb;default:{}" json:"snapshot"` + IdempotencyKey string `gorm:"column:idempotency_key;type:character varying(128);not null" json:"idempotency_key"` + PaidAt time.Time `gorm:"column:paid_at;type:timestamp with time zone" json:"paid_at"` + RefundedAt time.Time `gorm:"column:refunded_at;type:timestamp with time zone" json:"refunded_at"` + RefundForced bool `gorm:"column:refund_forced;type:boolean" json:"refund_forced"` + RefundOperatorUserID int64 `gorm:"column:refund_operator_user_id;type:bigint" json:"refund_operator_user_id"` + RefundReason string `gorm:"column:refund_reason;type:character varying(255)" json:"refund_reason"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Order) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Order.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Order) Save(ctx context.Context) error { return Q.Order.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *Order) Create(ctx context.Context) error { return Q.Order.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *Order) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Order.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Order) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Order.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Order) Reload(ctx context.Context) error { + fresh, err := Q.Order.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/orders.query.gen.go b/models/orders.query.gen.go new file mode 100644 index 0000000..75f7780 --- /dev/null +++ b/models/orders.query.gen.go @@ -0,0 +1,527 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newOrder(db *gorm.DB, opts ...gen.DOOption) orderQuery { + _orderQuery := orderQuery{} + + _orderQuery.orderQueryDo.UseDB(db, opts...) + _orderQuery.orderQueryDo.UseModel(&Order{}) + + tableName := _orderQuery.orderQueryDo.TableName() + _orderQuery.ALL = field.NewAsterisk(tableName) + _orderQuery.ID = field.NewInt64(tableName, "id") + _orderQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _orderQuery.UserID = field.NewInt64(tableName, "user_id") + _orderQuery.Type = field.NewString(tableName, "type") + _orderQuery.Status = field.NewString(tableName, "status") + _orderQuery.Currency = field.NewString(tableName, "currency") + _orderQuery.AmountOriginal = field.NewInt64(tableName, "amount_original") + _orderQuery.AmountDiscount = field.NewInt64(tableName, "amount_discount") + _orderQuery.AmountPaid = field.NewInt64(tableName, "amount_paid") + _orderQuery.Snapshot = field.NewJSONB(tableName, "snapshot") + _orderQuery.IdempotencyKey = field.NewString(tableName, "idempotency_key") + _orderQuery.PaidAt = field.NewTime(tableName, "paid_at") + _orderQuery.RefundedAt = field.NewTime(tableName, "refunded_at") + _orderQuery.RefundForced = field.NewBool(tableName, "refund_forced") + _orderQuery.RefundOperatorUserID = field.NewInt64(tableName, "refund_operator_user_id") + _orderQuery.RefundReason = field.NewString(tableName, "refund_reason") + _orderQuery.CreatedAt = field.NewTime(tableName, "created_at") + _orderQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _orderQuery.fillFieldMap() + + return _orderQuery +} + +type orderQuery struct { + orderQueryDo orderQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Type field.String + Status field.String + Currency field.String + AmountOriginal field.Int64 + AmountDiscount field.Int64 + AmountPaid field.Int64 + Snapshot field.JSONB + IdempotencyKey field.String + PaidAt field.Time + RefundedAt field.Time + RefundForced field.Bool + RefundOperatorUserID field.Int64 + RefundReason field.String + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (o orderQuery) Table(newTableName string) *orderQuery { + o.orderQueryDo.UseTable(newTableName) + return o.updateTableName(newTableName) +} + +func (o orderQuery) As(alias string) *orderQuery { + o.orderQueryDo.DO = *(o.orderQueryDo.As(alias).(*gen.DO)) + return o.updateTableName(alias) +} + +func (o *orderQuery) updateTableName(table string) *orderQuery { + o.ALL = field.NewAsterisk(table) + o.ID = field.NewInt64(table, "id") + o.TenantID = field.NewInt64(table, "tenant_id") + o.UserID = field.NewInt64(table, "user_id") + o.Type = field.NewString(table, "type") + o.Status = field.NewString(table, "status") + o.Currency = field.NewString(table, "currency") + o.AmountOriginal = field.NewInt64(table, "amount_original") + o.AmountDiscount = field.NewInt64(table, "amount_discount") + o.AmountPaid = field.NewInt64(table, "amount_paid") + o.Snapshot = field.NewJSONB(table, "snapshot") + o.IdempotencyKey = field.NewString(table, "idempotency_key") + o.PaidAt = field.NewTime(table, "paid_at") + o.RefundedAt = field.NewTime(table, "refunded_at") + o.RefundForced = field.NewBool(table, "refund_forced") + o.RefundOperatorUserID = field.NewInt64(table, "refund_operator_user_id") + o.RefundReason = field.NewString(table, "refund_reason") + o.CreatedAt = field.NewTime(table, "created_at") + o.UpdatedAt = field.NewTime(table, "updated_at") + + o.fillFieldMap() + + return o +} + +func (o *orderQuery) QueryContext(ctx context.Context) (*orderQuery, *orderQueryDo) { + return o, o.orderQueryDo.WithContext(ctx) +} + +func (o *orderQuery) WithContext(ctx context.Context) *orderQueryDo { + return o.orderQueryDo.WithContext(ctx) +} + +func (o orderQuery) TableName() string { return o.orderQueryDo.TableName() } + +func (o orderQuery) Alias() string { return o.orderQueryDo.Alias() } + +func (o orderQuery) Columns(cols ...field.Expr) gen.Columns { return o.orderQueryDo.Columns(cols...) } + +func (o *orderQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := o.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (o *orderQuery) fillFieldMap() { + o.fieldMap = make(map[string]field.Expr, 18) + o.fieldMap["id"] = o.ID + o.fieldMap["tenant_id"] = o.TenantID + o.fieldMap["user_id"] = o.UserID + o.fieldMap["type"] = o.Type + o.fieldMap["status"] = o.Status + o.fieldMap["currency"] = o.Currency + o.fieldMap["amount_original"] = o.AmountOriginal + o.fieldMap["amount_discount"] = o.AmountDiscount + o.fieldMap["amount_paid"] = o.AmountPaid + o.fieldMap["snapshot"] = o.Snapshot + o.fieldMap["idempotency_key"] = o.IdempotencyKey + o.fieldMap["paid_at"] = o.PaidAt + o.fieldMap["refunded_at"] = o.RefundedAt + o.fieldMap["refund_forced"] = o.RefundForced + o.fieldMap["refund_operator_user_id"] = o.RefundOperatorUserID + o.fieldMap["refund_reason"] = o.RefundReason + o.fieldMap["created_at"] = o.CreatedAt + o.fieldMap["updated_at"] = o.UpdatedAt +} + +func (o orderQuery) clone(db *gorm.DB) orderQuery { + o.orderQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return o +} + +func (o orderQuery) replaceDB(db *gorm.DB) orderQuery { + o.orderQueryDo.ReplaceDB(db) + return o +} + +type orderQueryDo struct{ gen.DO } + +func (o orderQueryDo) Debug() *orderQueryDo { + return o.withDO(o.DO.Debug()) +} + +func (o orderQueryDo) WithContext(ctx context.Context) *orderQueryDo { + return o.withDO(o.DO.WithContext(ctx)) +} + +func (o orderQueryDo) ReadDB() *orderQueryDo { + return o.Clauses(dbresolver.Read) +} + +func (o orderQueryDo) WriteDB() *orderQueryDo { + return o.Clauses(dbresolver.Write) +} + +func (o orderQueryDo) Session(config *gorm.Session) *orderQueryDo { + return o.withDO(o.DO.Session(config)) +} + +func (o orderQueryDo) Clauses(conds ...clause.Expression) *orderQueryDo { + return o.withDO(o.DO.Clauses(conds...)) +} + +func (o orderQueryDo) Returning(value interface{}, columns ...string) *orderQueryDo { + return o.withDO(o.DO.Returning(value, columns...)) +} + +func (o orderQueryDo) Not(conds ...gen.Condition) *orderQueryDo { + return o.withDO(o.DO.Not(conds...)) +} + +func (o orderQueryDo) Or(conds ...gen.Condition) *orderQueryDo { + return o.withDO(o.DO.Or(conds...)) +} + +func (o orderQueryDo) Select(conds ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.Select(conds...)) +} + +func (o orderQueryDo) Where(conds ...gen.Condition) *orderQueryDo { + return o.withDO(o.DO.Where(conds...)) +} + +func (o orderQueryDo) Order(conds ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.Order(conds...)) +} + +func (o orderQueryDo) Distinct(cols ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.Distinct(cols...)) +} + +func (o orderQueryDo) Omit(cols ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.Omit(cols...)) +} + +func (o orderQueryDo) Join(table schema.Tabler, on ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.Join(table, on...)) +} + +func (o orderQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.LeftJoin(table, on...)) +} + +func (o orderQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.RightJoin(table, on...)) +} + +func (o orderQueryDo) Group(cols ...field.Expr) *orderQueryDo { + return o.withDO(o.DO.Group(cols...)) +} + +func (o orderQueryDo) Having(conds ...gen.Condition) *orderQueryDo { + return o.withDO(o.DO.Having(conds...)) +} + +func (o orderQueryDo) Limit(limit int) *orderQueryDo { + return o.withDO(o.DO.Limit(limit)) +} + +func (o orderQueryDo) Offset(offset int) *orderQueryDo { + return o.withDO(o.DO.Offset(offset)) +} + +func (o orderQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *orderQueryDo { + return o.withDO(o.DO.Scopes(funcs...)) +} + +func (o orderQueryDo) Unscoped() *orderQueryDo { + return o.withDO(o.DO.Unscoped()) +} + +func (o orderQueryDo) Create(values ...*Order) error { + if len(values) == 0 { + return nil + } + return o.DO.Create(values) +} + +func (o orderQueryDo) CreateInBatches(values []*Order, batchSize int) error { + return o.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (o orderQueryDo) Save(values ...*Order) error { + if len(values) == 0 { + return nil + } + return o.DO.Save(values) +} + +func (o orderQueryDo) First() (*Order, error) { + if result, err := o.DO.First(); err != nil { + return nil, err + } else { + return result.(*Order), nil + } +} + +func (o orderQueryDo) Take() (*Order, error) { + if result, err := o.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Order), nil + } +} + +func (o orderQueryDo) Last() (*Order, error) { + if result, err := o.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Order), nil + } +} + +func (o orderQueryDo) Find() ([]*Order, error) { + result, err := o.DO.Find() + return result.([]*Order), err +} + +func (o orderQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Order, err error) { + buf := make([]*Order, 0, batchSize) + err = o.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (o orderQueryDo) FindInBatches(result *[]*Order, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return o.DO.FindInBatches(result, batchSize, fc) +} + +func (o orderQueryDo) Attrs(attrs ...field.AssignExpr) *orderQueryDo { + return o.withDO(o.DO.Attrs(attrs...)) +} + +func (o orderQueryDo) Assign(attrs ...field.AssignExpr) *orderQueryDo { + return o.withDO(o.DO.Assign(attrs...)) +} + +func (o orderQueryDo) Joins(fields ...field.RelationField) *orderQueryDo { + for _, _f := range fields { + o = *o.withDO(o.DO.Joins(_f)) + } + return &o +} + +func (o orderQueryDo) Preload(fields ...field.RelationField) *orderQueryDo { + for _, _f := range fields { + o = *o.withDO(o.DO.Preload(_f)) + } + return &o +} + +func (o orderQueryDo) FirstOrInit() (*Order, error) { + if result, err := o.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Order), nil + } +} + +func (o orderQueryDo) FirstOrCreate() (*Order, error) { + if result, err := o.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Order), nil + } +} + +func (o orderQueryDo) FindByPage(offset int, limit int) (result []*Order, count int64, err error) { + result, err = o.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = o.Offset(-1).Limit(-1).Count() + return +} + +func (o orderQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = o.Count() + if err != nil { + return + } + + err = o.Offset(offset).Limit(limit).Scan(result) + return +} + +func (o orderQueryDo) Scan(result interface{}) (err error) { + return o.DO.Scan(result) +} + +func (o orderQueryDo) Delete(models ...*Order) (result gen.ResultInfo, err error) { + return o.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (o orderQueryDo) ForceDelete() (gen.ResultInfo, error) { + return o.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (o orderQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return o.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (o orderQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return o.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (o orderQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (o orderQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (o orderQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (o orderQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := o.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (o orderQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := o.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (o orderQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := o.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (o orderQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(o.TableName(), "id") + if err := o.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (o orderQueryDo) GetByID(id int64) (*Order, error) { + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (o orderQueryDo) GetByIDs(ids ...int64) ([]*Order, error) { + if len(ids) == 0 { + return []*Order{}, nil + } + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (o orderQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (o orderQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(o.TableName(), "id") + return o.Where(pk.In(ids...)).Delete() +} + +func (o *orderQueryDo) withDO(do gen.Dao) *orderQueryDo { + o.DO = *do.(*gen.DO) + return o +} diff --git a/models/payout_accounts.gen.go b/models/payout_accounts.gen.go new file mode 100644 index 0000000..9e4c44d --- /dev/null +++ b/models/payout_accounts.gen.go @@ -0,0 +1,63 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNamePayoutAccount = "payout_accounts" + +// PayoutAccount mapped from table +type PayoutAccount struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + Name string `gorm:"column:name;type:character varying(128);not null" json:"name"` + Account string `gorm:"column:account;type:character varying(128);not null" json:"account"` + Realname string `gorm:"column:realname;type:character varying(128);not null" json:"realname"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *PayoutAccount) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.PayoutAccount.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *PayoutAccount) Save(ctx context.Context) error { + return Q.PayoutAccount.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *PayoutAccount) Create(ctx context.Context) error { + return Q.PayoutAccount.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *PayoutAccount) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.PayoutAccount.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *PayoutAccount) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.PayoutAccount.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *PayoutAccount) Reload(ctx context.Context) error { + fresh, err := Q.PayoutAccount.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/payout_accounts.query.gen.go b/models/payout_accounts.query.gen.go new file mode 100644 index 0000000..01caa3e --- /dev/null +++ b/models/payout_accounts.query.gen.go @@ -0,0 +1,493 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newPayoutAccount(db *gorm.DB, opts ...gen.DOOption) payoutAccountQuery { + _payoutAccountQuery := payoutAccountQuery{} + + _payoutAccountQuery.payoutAccountQueryDo.UseDB(db, opts...) + _payoutAccountQuery.payoutAccountQueryDo.UseModel(&PayoutAccount{}) + + tableName := _payoutAccountQuery.payoutAccountQueryDo.TableName() + _payoutAccountQuery.ALL = field.NewAsterisk(tableName) + _payoutAccountQuery.ID = field.NewInt64(tableName, "id") + _payoutAccountQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _payoutAccountQuery.UserID = field.NewInt64(tableName, "user_id") + _payoutAccountQuery.Type = field.NewString(tableName, "type") + _payoutAccountQuery.Name = field.NewString(tableName, "name") + _payoutAccountQuery.Account = field.NewString(tableName, "account") + _payoutAccountQuery.Realname = field.NewString(tableName, "realname") + _payoutAccountQuery.CreatedAt = field.NewTime(tableName, "created_at") + _payoutAccountQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _payoutAccountQuery.fillFieldMap() + + return _payoutAccountQuery +} + +type payoutAccountQuery struct { + payoutAccountQueryDo payoutAccountQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Type field.String + Name field.String + Account field.String + Realname field.String + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (p payoutAccountQuery) Table(newTableName string) *payoutAccountQuery { + p.payoutAccountQueryDo.UseTable(newTableName) + return p.updateTableName(newTableName) +} + +func (p payoutAccountQuery) As(alias string) *payoutAccountQuery { + p.payoutAccountQueryDo.DO = *(p.payoutAccountQueryDo.As(alias).(*gen.DO)) + return p.updateTableName(alias) +} + +func (p *payoutAccountQuery) updateTableName(table string) *payoutAccountQuery { + p.ALL = field.NewAsterisk(table) + p.ID = field.NewInt64(table, "id") + p.TenantID = field.NewInt64(table, "tenant_id") + p.UserID = field.NewInt64(table, "user_id") + p.Type = field.NewString(table, "type") + p.Name = field.NewString(table, "name") + p.Account = field.NewString(table, "account") + p.Realname = field.NewString(table, "realname") + p.CreatedAt = field.NewTime(table, "created_at") + p.UpdatedAt = field.NewTime(table, "updated_at") + + p.fillFieldMap() + + return p +} + +func (p *payoutAccountQuery) QueryContext(ctx context.Context) (*payoutAccountQuery, *payoutAccountQueryDo) { + return p, p.payoutAccountQueryDo.WithContext(ctx) +} + +func (p *payoutAccountQuery) WithContext(ctx context.Context) *payoutAccountQueryDo { + return p.payoutAccountQueryDo.WithContext(ctx) +} + +func (p payoutAccountQuery) TableName() string { return p.payoutAccountQueryDo.TableName() } + +func (p payoutAccountQuery) Alias() string { return p.payoutAccountQueryDo.Alias() } + +func (p payoutAccountQuery) Columns(cols ...field.Expr) gen.Columns { + return p.payoutAccountQueryDo.Columns(cols...) +} + +func (p *payoutAccountQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := p.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (p *payoutAccountQuery) fillFieldMap() { + p.fieldMap = make(map[string]field.Expr, 9) + p.fieldMap["id"] = p.ID + p.fieldMap["tenant_id"] = p.TenantID + p.fieldMap["user_id"] = p.UserID + p.fieldMap["type"] = p.Type + p.fieldMap["name"] = p.Name + p.fieldMap["account"] = p.Account + p.fieldMap["realname"] = p.Realname + p.fieldMap["created_at"] = p.CreatedAt + p.fieldMap["updated_at"] = p.UpdatedAt +} + +func (p payoutAccountQuery) clone(db *gorm.DB) payoutAccountQuery { + p.payoutAccountQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return p +} + +func (p payoutAccountQuery) replaceDB(db *gorm.DB) payoutAccountQuery { + p.payoutAccountQueryDo.ReplaceDB(db) + return p +} + +type payoutAccountQueryDo struct{ gen.DO } + +func (p payoutAccountQueryDo) Debug() *payoutAccountQueryDo { + return p.withDO(p.DO.Debug()) +} + +func (p payoutAccountQueryDo) WithContext(ctx context.Context) *payoutAccountQueryDo { + return p.withDO(p.DO.WithContext(ctx)) +} + +func (p payoutAccountQueryDo) ReadDB() *payoutAccountQueryDo { + return p.Clauses(dbresolver.Read) +} + +func (p payoutAccountQueryDo) WriteDB() *payoutAccountQueryDo { + return p.Clauses(dbresolver.Write) +} + +func (p payoutAccountQueryDo) Session(config *gorm.Session) *payoutAccountQueryDo { + return p.withDO(p.DO.Session(config)) +} + +func (p payoutAccountQueryDo) Clauses(conds ...clause.Expression) *payoutAccountQueryDo { + return p.withDO(p.DO.Clauses(conds...)) +} + +func (p payoutAccountQueryDo) Returning(value interface{}, columns ...string) *payoutAccountQueryDo { + return p.withDO(p.DO.Returning(value, columns...)) +} + +func (p payoutAccountQueryDo) Not(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Not(conds...)) +} + +func (p payoutAccountQueryDo) Or(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Or(conds...)) +} + +func (p payoutAccountQueryDo) Select(conds ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Select(conds...)) +} + +func (p payoutAccountQueryDo) Where(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Where(conds...)) +} + +func (p payoutAccountQueryDo) Order(conds ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Order(conds...)) +} + +func (p payoutAccountQueryDo) Distinct(cols ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Distinct(cols...)) +} + +func (p payoutAccountQueryDo) Omit(cols ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Omit(cols...)) +} + +func (p payoutAccountQueryDo) Join(table schema.Tabler, on ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Join(table, on...)) +} + +func (p payoutAccountQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.LeftJoin(table, on...)) +} + +func (p payoutAccountQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.RightJoin(table, on...)) +} + +func (p payoutAccountQueryDo) Group(cols ...field.Expr) *payoutAccountQueryDo { + return p.withDO(p.DO.Group(cols...)) +} + +func (p payoutAccountQueryDo) Having(conds ...gen.Condition) *payoutAccountQueryDo { + return p.withDO(p.DO.Having(conds...)) +} + +func (p payoutAccountQueryDo) Limit(limit int) *payoutAccountQueryDo { + return p.withDO(p.DO.Limit(limit)) +} + +func (p payoutAccountQueryDo) Offset(offset int) *payoutAccountQueryDo { + return p.withDO(p.DO.Offset(offset)) +} + +func (p payoutAccountQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *payoutAccountQueryDo { + return p.withDO(p.DO.Scopes(funcs...)) +} + +func (p payoutAccountQueryDo) Unscoped() *payoutAccountQueryDo { + return p.withDO(p.DO.Unscoped()) +} + +func (p payoutAccountQueryDo) Create(values ...*PayoutAccount) error { + if len(values) == 0 { + return nil + } + return p.DO.Create(values) +} + +func (p payoutAccountQueryDo) CreateInBatches(values []*PayoutAccount, batchSize int) error { + return p.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (p payoutAccountQueryDo) Save(values ...*PayoutAccount) error { + if len(values) == 0 { + return nil + } + return p.DO.Save(values) +} + +func (p payoutAccountQueryDo) First() (*PayoutAccount, error) { + if result, err := p.DO.First(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) Take() (*PayoutAccount, error) { + if result, err := p.DO.Take(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) Last() (*PayoutAccount, error) { + if result, err := p.DO.Last(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) Find() ([]*PayoutAccount, error) { + result, err := p.DO.Find() + return result.([]*PayoutAccount), err +} + +func (p payoutAccountQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*PayoutAccount, err error) { + buf := make([]*PayoutAccount, 0, batchSize) + err = p.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (p payoutAccountQueryDo) FindInBatches(result *[]*PayoutAccount, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return p.DO.FindInBatches(result, batchSize, fc) +} + +func (p payoutAccountQueryDo) Attrs(attrs ...field.AssignExpr) *payoutAccountQueryDo { + return p.withDO(p.DO.Attrs(attrs...)) +} + +func (p payoutAccountQueryDo) Assign(attrs ...field.AssignExpr) *payoutAccountQueryDo { + return p.withDO(p.DO.Assign(attrs...)) +} + +func (p payoutAccountQueryDo) Joins(fields ...field.RelationField) *payoutAccountQueryDo { + for _, _f := range fields { + p = *p.withDO(p.DO.Joins(_f)) + } + return &p +} + +func (p payoutAccountQueryDo) Preload(fields ...field.RelationField) *payoutAccountQueryDo { + for _, _f := range fields { + p = *p.withDO(p.DO.Preload(_f)) + } + return &p +} + +func (p payoutAccountQueryDo) FirstOrInit() (*PayoutAccount, error) { + if result, err := p.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) FirstOrCreate() (*PayoutAccount, error) { + if result, err := p.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*PayoutAccount), nil + } +} + +func (p payoutAccountQueryDo) FindByPage(offset int, limit int) (result []*PayoutAccount, count int64, err error) { + result, err = p.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = p.Offset(-1).Limit(-1).Count() + return +} + +func (p payoutAccountQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = p.Count() + if err != nil { + return + } + + err = p.Offset(offset).Limit(limit).Scan(result) + return +} + +func (p payoutAccountQueryDo) Scan(result interface{}) (err error) { + return p.DO.Scan(result) +} + +func (p payoutAccountQueryDo) Delete(models ...*PayoutAccount) (result gen.ResultInfo, err error) { + return p.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (p payoutAccountQueryDo) ForceDelete() (gen.ResultInfo, error) { + return p.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (p payoutAccountQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return p.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (p payoutAccountQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return p.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (p payoutAccountQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (p payoutAccountQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (p payoutAccountQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (p payoutAccountQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := p.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (p payoutAccountQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := p.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (p payoutAccountQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := p.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (p payoutAccountQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(p.TableName(), "id") + if err := p.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (p payoutAccountQueryDo) GetByID(id int64) (*PayoutAccount, error) { + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (p payoutAccountQueryDo) GetByIDs(ids ...int64) ([]*PayoutAccount, error) { + if len(ids) == 0 { + return []*PayoutAccount{}, nil + } + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (p payoutAccountQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (p payoutAccountQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(p.TableName(), "id") + return p.Where(pk.In(ids...)).Delete() +} + +func (p *payoutAccountQueryDo) withDO(do gen.Dao) *payoutAccountQueryDo { + p.DO = *do.(*gen.DO) + return p +} diff --git a/models/query.gen.go b/models/query.gen.go new file mode 100644 index 0000000..e3e8b48 --- /dev/null +++ b/models/query.gen.go @@ -0,0 +1,239 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "database/sql" + + "gorm.io/gorm" + + "go.ipao.vip/gen" + + "gorm.io/plugin/dbresolver" +) + +var ( + Q = new(Query) + CommentQuery *commentQuery + ContentQuery *contentQuery + ContentAccessQuery *contentAccessQuery + ContentAssetQuery *contentAssetQuery + ContentPriceQuery *contentPriceQuery + MediaAssetQuery *mediaAssetQuery + NotificationQuery *notificationQuery + OrderQuery *orderQuery + OrderItemQuery *orderItemQuery + PayoutAccountQuery *payoutAccountQuery + TenantQuery *tenantQuery + TenantInviteQuery *tenantInviteQuery + TenantJoinRequestQuery *tenantJoinRequestQuery + TenantLedgerQuery *tenantLedgerQuery + TenantUserQuery *tenantUserQuery + UserQuery *userQuery + UserCommentActionQuery *userCommentActionQuery + UserContentActionQuery *userContentActionQuery +) + +func SetDefault(db *gorm.DB, opts ...gen.DOOption) { + *Q = *Use(db, opts...) + CommentQuery = &Q.Comment + ContentQuery = &Q.Content + ContentAccessQuery = &Q.ContentAccess + ContentAssetQuery = &Q.ContentAsset + ContentPriceQuery = &Q.ContentPrice + MediaAssetQuery = &Q.MediaAsset + NotificationQuery = &Q.Notification + OrderQuery = &Q.Order + OrderItemQuery = &Q.OrderItem + PayoutAccountQuery = &Q.PayoutAccount + TenantQuery = &Q.Tenant + TenantInviteQuery = &Q.TenantInvite + TenantJoinRequestQuery = &Q.TenantJoinRequest + TenantLedgerQuery = &Q.TenantLedger + TenantUserQuery = &Q.TenantUser + UserQuery = &Q.User + UserCommentActionQuery = &Q.UserCommentAction + UserContentActionQuery = &Q.UserContentAction +} + +func Use(db *gorm.DB, opts ...gen.DOOption) *Query { + return &Query{ + db: db, + Comment: newComment(db, opts...), + Content: newContent(db, opts...), + ContentAccess: newContentAccess(db, opts...), + ContentAsset: newContentAsset(db, opts...), + ContentPrice: newContentPrice(db, opts...), + MediaAsset: newMediaAsset(db, opts...), + Notification: newNotification(db, opts...), + Order: newOrder(db, opts...), + OrderItem: newOrderItem(db, opts...), + PayoutAccount: newPayoutAccount(db, opts...), + Tenant: newTenant(db, opts...), + TenantInvite: newTenantInvite(db, opts...), + TenantJoinRequest: newTenantJoinRequest(db, opts...), + TenantLedger: newTenantLedger(db, opts...), + TenantUser: newTenantUser(db, opts...), + User: newUser(db, opts...), + UserCommentAction: newUserCommentAction(db, opts...), + UserContentAction: newUserContentAction(db, opts...), + } +} + +type Query struct { + db *gorm.DB + + Comment commentQuery + Content contentQuery + ContentAccess contentAccessQuery + ContentAsset contentAssetQuery + ContentPrice contentPriceQuery + MediaAsset mediaAssetQuery + Notification notificationQuery + Order orderQuery + OrderItem orderItemQuery + PayoutAccount payoutAccountQuery + Tenant tenantQuery + TenantInvite tenantInviteQuery + TenantJoinRequest tenantJoinRequestQuery + TenantLedger tenantLedgerQuery + TenantUser tenantUserQuery + User userQuery + UserCommentAction userCommentActionQuery + UserContentAction userContentActionQuery +} + +func (q *Query) Available() bool { return q.db != nil } + +func (q *Query) clone(db *gorm.DB) *Query { + return &Query{ + db: db, + Comment: q.Comment.clone(db), + Content: q.Content.clone(db), + ContentAccess: q.ContentAccess.clone(db), + ContentAsset: q.ContentAsset.clone(db), + ContentPrice: q.ContentPrice.clone(db), + MediaAsset: q.MediaAsset.clone(db), + Notification: q.Notification.clone(db), + Order: q.Order.clone(db), + OrderItem: q.OrderItem.clone(db), + PayoutAccount: q.PayoutAccount.clone(db), + Tenant: q.Tenant.clone(db), + TenantInvite: q.TenantInvite.clone(db), + TenantJoinRequest: q.TenantJoinRequest.clone(db), + TenantLedger: q.TenantLedger.clone(db), + TenantUser: q.TenantUser.clone(db), + User: q.User.clone(db), + UserCommentAction: q.UserCommentAction.clone(db), + UserContentAction: q.UserContentAction.clone(db), + } +} + +func (q *Query) ReadDB() *Query { + return q.ReplaceDB(q.db.Clauses(dbresolver.Read)) +} + +func (q *Query) WriteDB() *Query { + return q.ReplaceDB(q.db.Clauses(dbresolver.Write)) +} + +func (q *Query) ReplaceDB(db *gorm.DB) *Query { + return &Query{ + db: db, + Comment: q.Comment.replaceDB(db), + Content: q.Content.replaceDB(db), + ContentAccess: q.ContentAccess.replaceDB(db), + ContentAsset: q.ContentAsset.replaceDB(db), + ContentPrice: q.ContentPrice.replaceDB(db), + MediaAsset: q.MediaAsset.replaceDB(db), + Notification: q.Notification.replaceDB(db), + Order: q.Order.replaceDB(db), + OrderItem: q.OrderItem.replaceDB(db), + PayoutAccount: q.PayoutAccount.replaceDB(db), + Tenant: q.Tenant.replaceDB(db), + TenantInvite: q.TenantInvite.replaceDB(db), + TenantJoinRequest: q.TenantJoinRequest.replaceDB(db), + TenantLedger: q.TenantLedger.replaceDB(db), + TenantUser: q.TenantUser.replaceDB(db), + User: q.User.replaceDB(db), + UserCommentAction: q.UserCommentAction.replaceDB(db), + UserContentAction: q.UserContentAction.replaceDB(db), + } +} + +type queryCtx struct { + Comment *commentQueryDo + Content *contentQueryDo + ContentAccess *contentAccessQueryDo + ContentAsset *contentAssetQueryDo + ContentPrice *contentPriceQueryDo + MediaAsset *mediaAssetQueryDo + Notification *notificationQueryDo + Order *orderQueryDo + OrderItem *orderItemQueryDo + PayoutAccount *payoutAccountQueryDo + Tenant *tenantQueryDo + TenantInvite *tenantInviteQueryDo + TenantJoinRequest *tenantJoinRequestQueryDo + TenantLedger *tenantLedgerQueryDo + TenantUser *tenantUserQueryDo + User *userQueryDo + UserCommentAction *userCommentActionQueryDo + UserContentAction *userContentActionQueryDo +} + +func (q *Query) WithContext(ctx context.Context) *queryCtx { + return &queryCtx{ + Comment: q.Comment.WithContext(ctx), + Content: q.Content.WithContext(ctx), + ContentAccess: q.ContentAccess.WithContext(ctx), + ContentAsset: q.ContentAsset.WithContext(ctx), + ContentPrice: q.ContentPrice.WithContext(ctx), + MediaAsset: q.MediaAsset.WithContext(ctx), + Notification: q.Notification.WithContext(ctx), + Order: q.Order.WithContext(ctx), + OrderItem: q.OrderItem.WithContext(ctx), + PayoutAccount: q.PayoutAccount.WithContext(ctx), + Tenant: q.Tenant.WithContext(ctx), + TenantInvite: q.TenantInvite.WithContext(ctx), + TenantJoinRequest: q.TenantJoinRequest.WithContext(ctx), + TenantLedger: q.TenantLedger.WithContext(ctx), + TenantUser: q.TenantUser.WithContext(ctx), + User: q.User.WithContext(ctx), + UserCommentAction: q.UserCommentAction.WithContext(ctx), + UserContentAction: q.UserContentAction.WithContext(ctx), + } +} + +func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error { + return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...) +} + +func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx { + tx := q.db.Begin(opts...) + return &QueryTx{Query: q.clone(tx), Error: tx.Error} +} + +type QueryTx struct { + *Query + Error error +} + +func (q *QueryTx) Commit() error { + return q.db.Commit().Error +} + +func (q *QueryTx) Rollback() error { + return q.db.Rollback().Error +} + +func (q *QueryTx) SavePoint(name string) error { + return q.db.SavePoint(name).Error +} + +func (q *QueryTx) RollbackTo(name string) error { + return q.db.RollbackTo(name).Error +} diff --git a/models/tenant_invites.gen.go b/models/tenant_invites.gen.go new file mode 100644 index 0000000..d05c47f --- /dev/null +++ b/models/tenant_invites.gen.go @@ -0,0 +1,67 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameTenantInvite = "tenant_invites" + +// TenantInvite mapped from table +type TenantInvite struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Code string `gorm:"column:code;type:character varying(64);not null" json:"code"` + Status string `gorm:"column:status;type:character varying(32);default:active" json:"status"` + MaxUses int32 `gorm:"column:max_uses;type:integer;not null" json:"max_uses"` + UsedCount int32 `gorm:"column:used_count;type:integer" json:"used_count"` + ExpiresAt time.Time `gorm:"column:expires_at;type:timestamp with time zone" json:"expires_at"` + DisabledAt time.Time `gorm:"column:disabled_at;type:timestamp with time zone" json:"disabled_at"` + DisabledOperatorUserID int64 `gorm:"column:disabled_operator_user_id;type:bigint" json:"disabled_operator_user_id"` + Remark string `gorm:"column:remark;type:character varying(255)" json:"remark"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *TenantInvite) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantInvite.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *TenantInvite) Save(ctx context.Context) error { + return Q.TenantInvite.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *TenantInvite) Create(ctx context.Context) error { + return Q.TenantInvite.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *TenantInvite) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantInvite.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *TenantInvite) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantInvite.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *TenantInvite) Reload(ctx context.Context) error { + fresh, err := Q.TenantInvite.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/tenant_invites.query.gen.go b/models/tenant_invites.query.gen.go new file mode 100644 index 0000000..f59820e --- /dev/null +++ b/models/tenant_invites.query.gen.go @@ -0,0 +1,509 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newTenantInvite(db *gorm.DB, opts ...gen.DOOption) tenantInviteQuery { + _tenantInviteQuery := tenantInviteQuery{} + + _tenantInviteQuery.tenantInviteQueryDo.UseDB(db, opts...) + _tenantInviteQuery.tenantInviteQueryDo.UseModel(&TenantInvite{}) + + tableName := _tenantInviteQuery.tenantInviteQueryDo.TableName() + _tenantInviteQuery.ALL = field.NewAsterisk(tableName) + _tenantInviteQuery.ID = field.NewInt64(tableName, "id") + _tenantInviteQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _tenantInviteQuery.UserID = field.NewInt64(tableName, "user_id") + _tenantInviteQuery.Code = field.NewString(tableName, "code") + _tenantInviteQuery.Status = field.NewString(tableName, "status") + _tenantInviteQuery.MaxUses = field.NewInt32(tableName, "max_uses") + _tenantInviteQuery.UsedCount = field.NewInt32(tableName, "used_count") + _tenantInviteQuery.ExpiresAt = field.NewTime(tableName, "expires_at") + _tenantInviteQuery.DisabledAt = field.NewTime(tableName, "disabled_at") + _tenantInviteQuery.DisabledOperatorUserID = field.NewInt64(tableName, "disabled_operator_user_id") + _tenantInviteQuery.Remark = field.NewString(tableName, "remark") + _tenantInviteQuery.CreatedAt = field.NewTime(tableName, "created_at") + _tenantInviteQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _tenantInviteQuery.fillFieldMap() + + return _tenantInviteQuery +} + +type tenantInviteQuery struct { + tenantInviteQueryDo tenantInviteQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Code field.String + Status field.String + MaxUses field.Int32 + UsedCount field.Int32 + ExpiresAt field.Time + DisabledAt field.Time + DisabledOperatorUserID field.Int64 + Remark field.String + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (t tenantInviteQuery) Table(newTableName string) *tenantInviteQuery { + t.tenantInviteQueryDo.UseTable(newTableName) + return t.updateTableName(newTableName) +} + +func (t tenantInviteQuery) As(alias string) *tenantInviteQuery { + t.tenantInviteQueryDo.DO = *(t.tenantInviteQueryDo.As(alias).(*gen.DO)) + return t.updateTableName(alias) +} + +func (t *tenantInviteQuery) updateTableName(table string) *tenantInviteQuery { + t.ALL = field.NewAsterisk(table) + t.ID = field.NewInt64(table, "id") + t.TenantID = field.NewInt64(table, "tenant_id") + t.UserID = field.NewInt64(table, "user_id") + t.Code = field.NewString(table, "code") + t.Status = field.NewString(table, "status") + t.MaxUses = field.NewInt32(table, "max_uses") + t.UsedCount = field.NewInt32(table, "used_count") + t.ExpiresAt = field.NewTime(table, "expires_at") + t.DisabledAt = field.NewTime(table, "disabled_at") + t.DisabledOperatorUserID = field.NewInt64(table, "disabled_operator_user_id") + t.Remark = field.NewString(table, "remark") + t.CreatedAt = field.NewTime(table, "created_at") + t.UpdatedAt = field.NewTime(table, "updated_at") + + t.fillFieldMap() + + return t +} + +func (t *tenantInviteQuery) QueryContext(ctx context.Context) (*tenantInviteQuery, *tenantInviteQueryDo) { + return t, t.tenantInviteQueryDo.WithContext(ctx) +} + +func (t *tenantInviteQuery) WithContext(ctx context.Context) *tenantInviteQueryDo { + return t.tenantInviteQueryDo.WithContext(ctx) +} + +func (t tenantInviteQuery) TableName() string { return t.tenantInviteQueryDo.TableName() } + +func (t tenantInviteQuery) Alias() string { return t.tenantInviteQueryDo.Alias() } + +func (t tenantInviteQuery) Columns(cols ...field.Expr) gen.Columns { + return t.tenantInviteQueryDo.Columns(cols...) +} + +func (t *tenantInviteQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := t.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (t *tenantInviteQuery) fillFieldMap() { + t.fieldMap = make(map[string]field.Expr, 13) + t.fieldMap["id"] = t.ID + t.fieldMap["tenant_id"] = t.TenantID + t.fieldMap["user_id"] = t.UserID + t.fieldMap["code"] = t.Code + t.fieldMap["status"] = t.Status + t.fieldMap["max_uses"] = t.MaxUses + t.fieldMap["used_count"] = t.UsedCount + t.fieldMap["expires_at"] = t.ExpiresAt + t.fieldMap["disabled_at"] = t.DisabledAt + t.fieldMap["disabled_operator_user_id"] = t.DisabledOperatorUserID + t.fieldMap["remark"] = t.Remark + t.fieldMap["created_at"] = t.CreatedAt + t.fieldMap["updated_at"] = t.UpdatedAt +} + +func (t tenantInviteQuery) clone(db *gorm.DB) tenantInviteQuery { + t.tenantInviteQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return t +} + +func (t tenantInviteQuery) replaceDB(db *gorm.DB) tenantInviteQuery { + t.tenantInviteQueryDo.ReplaceDB(db) + return t +} + +type tenantInviteQueryDo struct{ gen.DO } + +func (t tenantInviteQueryDo) Debug() *tenantInviteQueryDo { + return t.withDO(t.DO.Debug()) +} + +func (t tenantInviteQueryDo) WithContext(ctx context.Context) *tenantInviteQueryDo { + return t.withDO(t.DO.WithContext(ctx)) +} + +func (t tenantInviteQueryDo) ReadDB() *tenantInviteQueryDo { + return t.Clauses(dbresolver.Read) +} + +func (t tenantInviteQueryDo) WriteDB() *tenantInviteQueryDo { + return t.Clauses(dbresolver.Write) +} + +func (t tenantInviteQueryDo) Session(config *gorm.Session) *tenantInviteQueryDo { + return t.withDO(t.DO.Session(config)) +} + +func (t tenantInviteQueryDo) Clauses(conds ...clause.Expression) *tenantInviteQueryDo { + return t.withDO(t.DO.Clauses(conds...)) +} + +func (t tenantInviteQueryDo) Returning(value interface{}, columns ...string) *tenantInviteQueryDo { + return t.withDO(t.DO.Returning(value, columns...)) +} + +func (t tenantInviteQueryDo) Not(conds ...gen.Condition) *tenantInviteQueryDo { + return t.withDO(t.DO.Not(conds...)) +} + +func (t tenantInviteQueryDo) Or(conds ...gen.Condition) *tenantInviteQueryDo { + return t.withDO(t.DO.Or(conds...)) +} + +func (t tenantInviteQueryDo) Select(conds ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.Select(conds...)) +} + +func (t tenantInviteQueryDo) Where(conds ...gen.Condition) *tenantInviteQueryDo { + return t.withDO(t.DO.Where(conds...)) +} + +func (t tenantInviteQueryDo) Order(conds ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.Order(conds...)) +} + +func (t tenantInviteQueryDo) Distinct(cols ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.Distinct(cols...)) +} + +func (t tenantInviteQueryDo) Omit(cols ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.Omit(cols...)) +} + +func (t tenantInviteQueryDo) Join(table schema.Tabler, on ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.Join(table, on...)) +} + +func (t tenantInviteQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.LeftJoin(table, on...)) +} + +func (t tenantInviteQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.RightJoin(table, on...)) +} + +func (t tenantInviteQueryDo) Group(cols ...field.Expr) *tenantInviteQueryDo { + return t.withDO(t.DO.Group(cols...)) +} + +func (t tenantInviteQueryDo) Having(conds ...gen.Condition) *tenantInviteQueryDo { + return t.withDO(t.DO.Having(conds...)) +} + +func (t tenantInviteQueryDo) Limit(limit int) *tenantInviteQueryDo { + return t.withDO(t.DO.Limit(limit)) +} + +func (t tenantInviteQueryDo) Offset(offset int) *tenantInviteQueryDo { + return t.withDO(t.DO.Offset(offset)) +} + +func (t tenantInviteQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *tenantInviteQueryDo { + return t.withDO(t.DO.Scopes(funcs...)) +} + +func (t tenantInviteQueryDo) Unscoped() *tenantInviteQueryDo { + return t.withDO(t.DO.Unscoped()) +} + +func (t tenantInviteQueryDo) Create(values ...*TenantInvite) error { + if len(values) == 0 { + return nil + } + return t.DO.Create(values) +} + +func (t tenantInviteQueryDo) CreateInBatches(values []*TenantInvite, batchSize int) error { + return t.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (t tenantInviteQueryDo) Save(values ...*TenantInvite) error { + if len(values) == 0 { + return nil + } + return t.DO.Save(values) +} + +func (t tenantInviteQueryDo) First() (*TenantInvite, error) { + if result, err := t.DO.First(); err != nil { + return nil, err + } else { + return result.(*TenantInvite), nil + } +} + +func (t tenantInviteQueryDo) Take() (*TenantInvite, error) { + if result, err := t.DO.Take(); err != nil { + return nil, err + } else { + return result.(*TenantInvite), nil + } +} + +func (t tenantInviteQueryDo) Last() (*TenantInvite, error) { + if result, err := t.DO.Last(); err != nil { + return nil, err + } else { + return result.(*TenantInvite), nil + } +} + +func (t tenantInviteQueryDo) Find() ([]*TenantInvite, error) { + result, err := t.DO.Find() + return result.([]*TenantInvite), err +} + +func (t tenantInviteQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*TenantInvite, err error) { + buf := make([]*TenantInvite, 0, batchSize) + err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (t tenantInviteQueryDo) FindInBatches(result *[]*TenantInvite, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return t.DO.FindInBatches(result, batchSize, fc) +} + +func (t tenantInviteQueryDo) Attrs(attrs ...field.AssignExpr) *tenantInviteQueryDo { + return t.withDO(t.DO.Attrs(attrs...)) +} + +func (t tenantInviteQueryDo) Assign(attrs ...field.AssignExpr) *tenantInviteQueryDo { + return t.withDO(t.DO.Assign(attrs...)) +} + +func (t tenantInviteQueryDo) Joins(fields ...field.RelationField) *tenantInviteQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Joins(_f)) + } + return &t +} + +func (t tenantInviteQueryDo) Preload(fields ...field.RelationField) *tenantInviteQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Preload(_f)) + } + return &t +} + +func (t tenantInviteQueryDo) FirstOrInit() (*TenantInvite, error) { + if result, err := t.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*TenantInvite), nil + } +} + +func (t tenantInviteQueryDo) FirstOrCreate() (*TenantInvite, error) { + if result, err := t.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*TenantInvite), nil + } +} + +func (t tenantInviteQueryDo) FindByPage(offset int, limit int) (result []*TenantInvite, count int64, err error) { + result, err = t.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = t.Offset(-1).Limit(-1).Count() + return +} + +func (t tenantInviteQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = t.Count() + if err != nil { + return + } + + err = t.Offset(offset).Limit(limit).Scan(result) + return +} + +func (t tenantInviteQueryDo) Scan(result interface{}) (err error) { + return t.DO.Scan(result) +} + +func (t tenantInviteQueryDo) Delete(models ...*TenantInvite) (result gen.ResultInfo, err error) { + return t.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (t tenantInviteQueryDo) ForceDelete() (gen.ResultInfo, error) { + return t.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (t tenantInviteQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (t tenantInviteQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (t tenantInviteQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (t tenantInviteQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (t tenantInviteQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (t tenantInviteQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (t tenantInviteQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := t.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (t tenantInviteQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := t.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (t tenantInviteQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(t.TableName(), "id") + if err := t.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (t tenantInviteQueryDo) GetByID(id int64) (*TenantInvite, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (t tenantInviteQueryDo) GetByIDs(ids ...int64) ([]*TenantInvite, error) { + if len(ids) == 0 { + return []*TenantInvite{}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (t tenantInviteQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (t tenantInviteQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Delete() +} + +func (t *tenantInviteQueryDo) withDO(do gen.Dao) *tenantInviteQueryDo { + t.DO = *do.(*gen.DO) + return t +} diff --git a/models/tenant_join_requests.gen.go b/models/tenant_join_requests.gen.go new file mode 100644 index 0000000..916d79d --- /dev/null +++ b/models/tenant_join_requests.gen.go @@ -0,0 +1,64 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameTenantJoinRequest = "tenant_join_requests" + +// TenantJoinRequest mapped from table +type TenantJoinRequest struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Status string `gorm:"column:status;type:character varying(32);default:pending" json:"status"` + Reason string `gorm:"column:reason;type:character varying(255);not null" json:"reason"` + DecidedAt time.Time `gorm:"column:decided_at;type:timestamp with time zone" json:"decided_at"` + DecidedOperatorUserID int64 `gorm:"column:decided_operator_user_id;type:bigint" json:"decided_operator_user_id"` + DecidedReason string `gorm:"column:decided_reason;type:character varying(255)" json:"decided_reason"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *TenantJoinRequest) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantJoinRequest.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *TenantJoinRequest) Save(ctx context.Context) error { + return Q.TenantJoinRequest.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *TenantJoinRequest) Create(ctx context.Context) error { + return Q.TenantJoinRequest.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *TenantJoinRequest) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantJoinRequest.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *TenantJoinRequest) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantJoinRequest.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *TenantJoinRequest) Reload(ctx context.Context) error { + fresh, err := Q.TenantJoinRequest.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/tenant_join_requests.query.gen.go b/models/tenant_join_requests.query.gen.go new file mode 100644 index 0000000..1db1fb2 --- /dev/null +++ b/models/tenant_join_requests.query.gen.go @@ -0,0 +1,497 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newTenantJoinRequest(db *gorm.DB, opts ...gen.DOOption) tenantJoinRequestQuery { + _tenantJoinRequestQuery := tenantJoinRequestQuery{} + + _tenantJoinRequestQuery.tenantJoinRequestQueryDo.UseDB(db, opts...) + _tenantJoinRequestQuery.tenantJoinRequestQueryDo.UseModel(&TenantJoinRequest{}) + + tableName := _tenantJoinRequestQuery.tenantJoinRequestQueryDo.TableName() + _tenantJoinRequestQuery.ALL = field.NewAsterisk(tableName) + _tenantJoinRequestQuery.ID = field.NewInt64(tableName, "id") + _tenantJoinRequestQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _tenantJoinRequestQuery.UserID = field.NewInt64(tableName, "user_id") + _tenantJoinRequestQuery.Status = field.NewString(tableName, "status") + _tenantJoinRequestQuery.Reason = field.NewString(tableName, "reason") + _tenantJoinRequestQuery.DecidedAt = field.NewTime(tableName, "decided_at") + _tenantJoinRequestQuery.DecidedOperatorUserID = field.NewInt64(tableName, "decided_operator_user_id") + _tenantJoinRequestQuery.DecidedReason = field.NewString(tableName, "decided_reason") + _tenantJoinRequestQuery.CreatedAt = field.NewTime(tableName, "created_at") + _tenantJoinRequestQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _tenantJoinRequestQuery.fillFieldMap() + + return _tenantJoinRequestQuery +} + +type tenantJoinRequestQuery struct { + tenantJoinRequestQueryDo tenantJoinRequestQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Status field.String + Reason field.String + DecidedAt field.Time + DecidedOperatorUserID field.Int64 + DecidedReason field.String + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (t tenantJoinRequestQuery) Table(newTableName string) *tenantJoinRequestQuery { + t.tenantJoinRequestQueryDo.UseTable(newTableName) + return t.updateTableName(newTableName) +} + +func (t tenantJoinRequestQuery) As(alias string) *tenantJoinRequestQuery { + t.tenantJoinRequestQueryDo.DO = *(t.tenantJoinRequestQueryDo.As(alias).(*gen.DO)) + return t.updateTableName(alias) +} + +func (t *tenantJoinRequestQuery) updateTableName(table string) *tenantJoinRequestQuery { + t.ALL = field.NewAsterisk(table) + t.ID = field.NewInt64(table, "id") + t.TenantID = field.NewInt64(table, "tenant_id") + t.UserID = field.NewInt64(table, "user_id") + t.Status = field.NewString(table, "status") + t.Reason = field.NewString(table, "reason") + t.DecidedAt = field.NewTime(table, "decided_at") + t.DecidedOperatorUserID = field.NewInt64(table, "decided_operator_user_id") + t.DecidedReason = field.NewString(table, "decided_reason") + t.CreatedAt = field.NewTime(table, "created_at") + t.UpdatedAt = field.NewTime(table, "updated_at") + + t.fillFieldMap() + + return t +} + +func (t *tenantJoinRequestQuery) QueryContext(ctx context.Context) (*tenantJoinRequestQuery, *tenantJoinRequestQueryDo) { + return t, t.tenantJoinRequestQueryDo.WithContext(ctx) +} + +func (t *tenantJoinRequestQuery) WithContext(ctx context.Context) *tenantJoinRequestQueryDo { + return t.tenantJoinRequestQueryDo.WithContext(ctx) +} + +func (t tenantJoinRequestQuery) TableName() string { return t.tenantJoinRequestQueryDo.TableName() } + +func (t tenantJoinRequestQuery) Alias() string { return t.tenantJoinRequestQueryDo.Alias() } + +func (t tenantJoinRequestQuery) Columns(cols ...field.Expr) gen.Columns { + return t.tenantJoinRequestQueryDo.Columns(cols...) +} + +func (t *tenantJoinRequestQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := t.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (t *tenantJoinRequestQuery) fillFieldMap() { + t.fieldMap = make(map[string]field.Expr, 10) + t.fieldMap["id"] = t.ID + t.fieldMap["tenant_id"] = t.TenantID + t.fieldMap["user_id"] = t.UserID + t.fieldMap["status"] = t.Status + t.fieldMap["reason"] = t.Reason + t.fieldMap["decided_at"] = t.DecidedAt + t.fieldMap["decided_operator_user_id"] = t.DecidedOperatorUserID + t.fieldMap["decided_reason"] = t.DecidedReason + t.fieldMap["created_at"] = t.CreatedAt + t.fieldMap["updated_at"] = t.UpdatedAt +} + +func (t tenantJoinRequestQuery) clone(db *gorm.DB) tenantJoinRequestQuery { + t.tenantJoinRequestQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return t +} + +func (t tenantJoinRequestQuery) replaceDB(db *gorm.DB) tenantJoinRequestQuery { + t.tenantJoinRequestQueryDo.ReplaceDB(db) + return t +} + +type tenantJoinRequestQueryDo struct{ gen.DO } + +func (t tenantJoinRequestQueryDo) Debug() *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Debug()) +} + +func (t tenantJoinRequestQueryDo) WithContext(ctx context.Context) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.WithContext(ctx)) +} + +func (t tenantJoinRequestQueryDo) ReadDB() *tenantJoinRequestQueryDo { + return t.Clauses(dbresolver.Read) +} + +func (t tenantJoinRequestQueryDo) WriteDB() *tenantJoinRequestQueryDo { + return t.Clauses(dbresolver.Write) +} + +func (t tenantJoinRequestQueryDo) Session(config *gorm.Session) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Session(config)) +} + +func (t tenantJoinRequestQueryDo) Clauses(conds ...clause.Expression) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Clauses(conds...)) +} + +func (t tenantJoinRequestQueryDo) Returning(value interface{}, columns ...string) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Returning(value, columns...)) +} + +func (t tenantJoinRequestQueryDo) Not(conds ...gen.Condition) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Not(conds...)) +} + +func (t tenantJoinRequestQueryDo) Or(conds ...gen.Condition) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Or(conds...)) +} + +func (t tenantJoinRequestQueryDo) Select(conds ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Select(conds...)) +} + +func (t tenantJoinRequestQueryDo) Where(conds ...gen.Condition) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Where(conds...)) +} + +func (t tenantJoinRequestQueryDo) Order(conds ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Order(conds...)) +} + +func (t tenantJoinRequestQueryDo) Distinct(cols ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Distinct(cols...)) +} + +func (t tenantJoinRequestQueryDo) Omit(cols ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Omit(cols...)) +} + +func (t tenantJoinRequestQueryDo) Join(table schema.Tabler, on ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Join(table, on...)) +} + +func (t tenantJoinRequestQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.LeftJoin(table, on...)) +} + +func (t tenantJoinRequestQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.RightJoin(table, on...)) +} + +func (t tenantJoinRequestQueryDo) Group(cols ...field.Expr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Group(cols...)) +} + +func (t tenantJoinRequestQueryDo) Having(conds ...gen.Condition) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Having(conds...)) +} + +func (t tenantJoinRequestQueryDo) Limit(limit int) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Limit(limit)) +} + +func (t tenantJoinRequestQueryDo) Offset(offset int) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Offset(offset)) +} + +func (t tenantJoinRequestQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Scopes(funcs...)) +} + +func (t tenantJoinRequestQueryDo) Unscoped() *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Unscoped()) +} + +func (t tenantJoinRequestQueryDo) Create(values ...*TenantJoinRequest) error { + if len(values) == 0 { + return nil + } + return t.DO.Create(values) +} + +func (t tenantJoinRequestQueryDo) CreateInBatches(values []*TenantJoinRequest, batchSize int) error { + return t.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (t tenantJoinRequestQueryDo) Save(values ...*TenantJoinRequest) error { + if len(values) == 0 { + return nil + } + return t.DO.Save(values) +} + +func (t tenantJoinRequestQueryDo) First() (*TenantJoinRequest, error) { + if result, err := t.DO.First(); err != nil { + return nil, err + } else { + return result.(*TenantJoinRequest), nil + } +} + +func (t tenantJoinRequestQueryDo) Take() (*TenantJoinRequest, error) { + if result, err := t.DO.Take(); err != nil { + return nil, err + } else { + return result.(*TenantJoinRequest), nil + } +} + +func (t tenantJoinRequestQueryDo) Last() (*TenantJoinRequest, error) { + if result, err := t.DO.Last(); err != nil { + return nil, err + } else { + return result.(*TenantJoinRequest), nil + } +} + +func (t tenantJoinRequestQueryDo) Find() ([]*TenantJoinRequest, error) { + result, err := t.DO.Find() + return result.([]*TenantJoinRequest), err +} + +func (t tenantJoinRequestQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*TenantJoinRequest, err error) { + buf := make([]*TenantJoinRequest, 0, batchSize) + err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (t tenantJoinRequestQueryDo) FindInBatches(result *[]*TenantJoinRequest, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return t.DO.FindInBatches(result, batchSize, fc) +} + +func (t tenantJoinRequestQueryDo) Attrs(attrs ...field.AssignExpr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Attrs(attrs...)) +} + +func (t tenantJoinRequestQueryDo) Assign(attrs ...field.AssignExpr) *tenantJoinRequestQueryDo { + return t.withDO(t.DO.Assign(attrs...)) +} + +func (t tenantJoinRequestQueryDo) Joins(fields ...field.RelationField) *tenantJoinRequestQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Joins(_f)) + } + return &t +} + +func (t tenantJoinRequestQueryDo) Preload(fields ...field.RelationField) *tenantJoinRequestQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Preload(_f)) + } + return &t +} + +func (t tenantJoinRequestQueryDo) FirstOrInit() (*TenantJoinRequest, error) { + if result, err := t.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*TenantJoinRequest), nil + } +} + +func (t tenantJoinRequestQueryDo) FirstOrCreate() (*TenantJoinRequest, error) { + if result, err := t.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*TenantJoinRequest), nil + } +} + +func (t tenantJoinRequestQueryDo) FindByPage(offset int, limit int) (result []*TenantJoinRequest, count int64, err error) { + result, err = t.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = t.Offset(-1).Limit(-1).Count() + return +} + +func (t tenantJoinRequestQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = t.Count() + if err != nil { + return + } + + err = t.Offset(offset).Limit(limit).Scan(result) + return +} + +func (t tenantJoinRequestQueryDo) Scan(result interface{}) (err error) { + return t.DO.Scan(result) +} + +func (t tenantJoinRequestQueryDo) Delete(models ...*TenantJoinRequest) (result gen.ResultInfo, err error) { + return t.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (t tenantJoinRequestQueryDo) ForceDelete() (gen.ResultInfo, error) { + return t.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (t tenantJoinRequestQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (t tenantJoinRequestQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (t tenantJoinRequestQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (t tenantJoinRequestQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (t tenantJoinRequestQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (t tenantJoinRequestQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (t tenantJoinRequestQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := t.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (t tenantJoinRequestQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := t.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (t tenantJoinRequestQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(t.TableName(), "id") + if err := t.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (t tenantJoinRequestQueryDo) GetByID(id int64) (*TenantJoinRequest, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (t tenantJoinRequestQueryDo) GetByIDs(ids ...int64) ([]*TenantJoinRequest, error) { + if len(ids) == 0 { + return []*TenantJoinRequest{}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (t tenantJoinRequestQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (t tenantJoinRequestQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Delete() +} + +func (t *tenantJoinRequestQueryDo) withDO(do gen.Dao) *tenantJoinRequestQueryDo { + t.DO = *do.(*gen.DO) + return t +} diff --git a/models/tenant_ledgers.gen.go b/models/tenant_ledgers.gen.go new file mode 100644 index 0000000..da7b79c --- /dev/null +++ b/models/tenant_ledgers.gen.go @@ -0,0 +1,71 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameTenantLedger = "tenant_ledgers" + +// TenantLedger mapped from table +type TenantLedger struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + OrderID int64 `gorm:"column:order_id;type:bigint" json:"order_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + Amount int64 `gorm:"column:amount;type:bigint;not null" json:"amount"` + BalanceBefore int64 `gorm:"column:balance_before;type:bigint;not null" json:"balance_before"` + BalanceAfter int64 `gorm:"column:balance_after;type:bigint;not null" json:"balance_after"` + FrozenBefore int64 `gorm:"column:frozen_before;type:bigint;not null" json:"frozen_before"` + FrozenAfter int64 `gorm:"column:frozen_after;type:bigint;not null" json:"frozen_after"` + IdempotencyKey string `gorm:"column:idempotency_key;type:character varying(128);not null" json:"idempotency_key"` + Remark string `gorm:"column:remark;type:character varying(255);not null" json:"remark"` + OperatorUserID int64 `gorm:"column:operator_user_id;type:bigint" json:"operator_user_id"` + BizRefType string `gorm:"column:biz_ref_type;type:character varying(32)" json:"biz_ref_type"` + BizRefID int64 `gorm:"column:biz_ref_id;type:bigint" json:"biz_ref_id"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *TenantLedger) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantLedger.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *TenantLedger) Save(ctx context.Context) error { + return Q.TenantLedger.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *TenantLedger) Create(ctx context.Context) error { + return Q.TenantLedger.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *TenantLedger) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantLedger.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *TenantLedger) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantLedger.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *TenantLedger) Reload(ctx context.Context) error { + fresh, err := Q.TenantLedger.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/tenant_ledgers.query.gen.go b/models/tenant_ledgers.query.gen.go new file mode 100644 index 0000000..8d4c296 --- /dev/null +++ b/models/tenant_ledgers.query.gen.go @@ -0,0 +1,525 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newTenantLedger(db *gorm.DB, opts ...gen.DOOption) tenantLedgerQuery { + _tenantLedgerQuery := tenantLedgerQuery{} + + _tenantLedgerQuery.tenantLedgerQueryDo.UseDB(db, opts...) + _tenantLedgerQuery.tenantLedgerQueryDo.UseModel(&TenantLedger{}) + + tableName := _tenantLedgerQuery.tenantLedgerQueryDo.TableName() + _tenantLedgerQuery.ALL = field.NewAsterisk(tableName) + _tenantLedgerQuery.ID = field.NewInt64(tableName, "id") + _tenantLedgerQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _tenantLedgerQuery.UserID = field.NewInt64(tableName, "user_id") + _tenantLedgerQuery.OrderID = field.NewInt64(tableName, "order_id") + _tenantLedgerQuery.Type = field.NewString(tableName, "type") + _tenantLedgerQuery.Amount = field.NewInt64(tableName, "amount") + _tenantLedgerQuery.BalanceBefore = field.NewInt64(tableName, "balance_before") + _tenantLedgerQuery.BalanceAfter = field.NewInt64(tableName, "balance_after") + _tenantLedgerQuery.FrozenBefore = field.NewInt64(tableName, "frozen_before") + _tenantLedgerQuery.FrozenAfter = field.NewInt64(tableName, "frozen_after") + _tenantLedgerQuery.IdempotencyKey = field.NewString(tableName, "idempotency_key") + _tenantLedgerQuery.Remark = field.NewString(tableName, "remark") + _tenantLedgerQuery.OperatorUserID = field.NewInt64(tableName, "operator_user_id") + _tenantLedgerQuery.BizRefType = field.NewString(tableName, "biz_ref_type") + _tenantLedgerQuery.BizRefID = field.NewInt64(tableName, "biz_ref_id") + _tenantLedgerQuery.CreatedAt = field.NewTime(tableName, "created_at") + _tenantLedgerQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _tenantLedgerQuery.fillFieldMap() + + return _tenantLedgerQuery +} + +type tenantLedgerQuery struct { + tenantLedgerQueryDo tenantLedgerQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + OrderID field.Int64 + Type field.String + Amount field.Int64 + BalanceBefore field.Int64 + BalanceAfter field.Int64 + FrozenBefore field.Int64 + FrozenAfter field.Int64 + IdempotencyKey field.String + Remark field.String + OperatorUserID field.Int64 + BizRefType field.String + BizRefID field.Int64 + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (t tenantLedgerQuery) Table(newTableName string) *tenantLedgerQuery { + t.tenantLedgerQueryDo.UseTable(newTableName) + return t.updateTableName(newTableName) +} + +func (t tenantLedgerQuery) As(alias string) *tenantLedgerQuery { + t.tenantLedgerQueryDo.DO = *(t.tenantLedgerQueryDo.As(alias).(*gen.DO)) + return t.updateTableName(alias) +} + +func (t *tenantLedgerQuery) updateTableName(table string) *tenantLedgerQuery { + t.ALL = field.NewAsterisk(table) + t.ID = field.NewInt64(table, "id") + t.TenantID = field.NewInt64(table, "tenant_id") + t.UserID = field.NewInt64(table, "user_id") + t.OrderID = field.NewInt64(table, "order_id") + t.Type = field.NewString(table, "type") + t.Amount = field.NewInt64(table, "amount") + t.BalanceBefore = field.NewInt64(table, "balance_before") + t.BalanceAfter = field.NewInt64(table, "balance_after") + t.FrozenBefore = field.NewInt64(table, "frozen_before") + t.FrozenAfter = field.NewInt64(table, "frozen_after") + t.IdempotencyKey = field.NewString(table, "idempotency_key") + t.Remark = field.NewString(table, "remark") + t.OperatorUserID = field.NewInt64(table, "operator_user_id") + t.BizRefType = field.NewString(table, "biz_ref_type") + t.BizRefID = field.NewInt64(table, "biz_ref_id") + t.CreatedAt = field.NewTime(table, "created_at") + t.UpdatedAt = field.NewTime(table, "updated_at") + + t.fillFieldMap() + + return t +} + +func (t *tenantLedgerQuery) QueryContext(ctx context.Context) (*tenantLedgerQuery, *tenantLedgerQueryDo) { + return t, t.tenantLedgerQueryDo.WithContext(ctx) +} + +func (t *tenantLedgerQuery) WithContext(ctx context.Context) *tenantLedgerQueryDo { + return t.tenantLedgerQueryDo.WithContext(ctx) +} + +func (t tenantLedgerQuery) TableName() string { return t.tenantLedgerQueryDo.TableName() } + +func (t tenantLedgerQuery) Alias() string { return t.tenantLedgerQueryDo.Alias() } + +func (t tenantLedgerQuery) Columns(cols ...field.Expr) gen.Columns { + return t.tenantLedgerQueryDo.Columns(cols...) +} + +func (t *tenantLedgerQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := t.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (t *tenantLedgerQuery) fillFieldMap() { + t.fieldMap = make(map[string]field.Expr, 17) + t.fieldMap["id"] = t.ID + t.fieldMap["tenant_id"] = t.TenantID + t.fieldMap["user_id"] = t.UserID + t.fieldMap["order_id"] = t.OrderID + t.fieldMap["type"] = t.Type + t.fieldMap["amount"] = t.Amount + t.fieldMap["balance_before"] = t.BalanceBefore + t.fieldMap["balance_after"] = t.BalanceAfter + t.fieldMap["frozen_before"] = t.FrozenBefore + t.fieldMap["frozen_after"] = t.FrozenAfter + t.fieldMap["idempotency_key"] = t.IdempotencyKey + t.fieldMap["remark"] = t.Remark + t.fieldMap["operator_user_id"] = t.OperatorUserID + t.fieldMap["biz_ref_type"] = t.BizRefType + t.fieldMap["biz_ref_id"] = t.BizRefID + t.fieldMap["created_at"] = t.CreatedAt + t.fieldMap["updated_at"] = t.UpdatedAt +} + +func (t tenantLedgerQuery) clone(db *gorm.DB) tenantLedgerQuery { + t.tenantLedgerQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return t +} + +func (t tenantLedgerQuery) replaceDB(db *gorm.DB) tenantLedgerQuery { + t.tenantLedgerQueryDo.ReplaceDB(db) + return t +} + +type tenantLedgerQueryDo struct{ gen.DO } + +func (t tenantLedgerQueryDo) Debug() *tenantLedgerQueryDo { + return t.withDO(t.DO.Debug()) +} + +func (t tenantLedgerQueryDo) WithContext(ctx context.Context) *tenantLedgerQueryDo { + return t.withDO(t.DO.WithContext(ctx)) +} + +func (t tenantLedgerQueryDo) ReadDB() *tenantLedgerQueryDo { + return t.Clauses(dbresolver.Read) +} + +func (t tenantLedgerQueryDo) WriteDB() *tenantLedgerQueryDo { + return t.Clauses(dbresolver.Write) +} + +func (t tenantLedgerQueryDo) Session(config *gorm.Session) *tenantLedgerQueryDo { + return t.withDO(t.DO.Session(config)) +} + +func (t tenantLedgerQueryDo) Clauses(conds ...clause.Expression) *tenantLedgerQueryDo { + return t.withDO(t.DO.Clauses(conds...)) +} + +func (t tenantLedgerQueryDo) Returning(value interface{}, columns ...string) *tenantLedgerQueryDo { + return t.withDO(t.DO.Returning(value, columns...)) +} + +func (t tenantLedgerQueryDo) Not(conds ...gen.Condition) *tenantLedgerQueryDo { + return t.withDO(t.DO.Not(conds...)) +} + +func (t tenantLedgerQueryDo) Or(conds ...gen.Condition) *tenantLedgerQueryDo { + return t.withDO(t.DO.Or(conds...)) +} + +func (t tenantLedgerQueryDo) Select(conds ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Select(conds...)) +} + +func (t tenantLedgerQueryDo) Where(conds ...gen.Condition) *tenantLedgerQueryDo { + return t.withDO(t.DO.Where(conds...)) +} + +func (t tenantLedgerQueryDo) Order(conds ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Order(conds...)) +} + +func (t tenantLedgerQueryDo) Distinct(cols ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Distinct(cols...)) +} + +func (t tenantLedgerQueryDo) Omit(cols ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Omit(cols...)) +} + +func (t tenantLedgerQueryDo) Join(table schema.Tabler, on ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Join(table, on...)) +} + +func (t tenantLedgerQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.LeftJoin(table, on...)) +} + +func (t tenantLedgerQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.RightJoin(table, on...)) +} + +func (t tenantLedgerQueryDo) Group(cols ...field.Expr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Group(cols...)) +} + +func (t tenantLedgerQueryDo) Having(conds ...gen.Condition) *tenantLedgerQueryDo { + return t.withDO(t.DO.Having(conds...)) +} + +func (t tenantLedgerQueryDo) Limit(limit int) *tenantLedgerQueryDo { + return t.withDO(t.DO.Limit(limit)) +} + +func (t tenantLedgerQueryDo) Offset(offset int) *tenantLedgerQueryDo { + return t.withDO(t.DO.Offset(offset)) +} + +func (t tenantLedgerQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *tenantLedgerQueryDo { + return t.withDO(t.DO.Scopes(funcs...)) +} + +func (t tenantLedgerQueryDo) Unscoped() *tenantLedgerQueryDo { + return t.withDO(t.DO.Unscoped()) +} + +func (t tenantLedgerQueryDo) Create(values ...*TenantLedger) error { + if len(values) == 0 { + return nil + } + return t.DO.Create(values) +} + +func (t tenantLedgerQueryDo) CreateInBatches(values []*TenantLedger, batchSize int) error { + return t.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (t tenantLedgerQueryDo) Save(values ...*TenantLedger) error { + if len(values) == 0 { + return nil + } + return t.DO.Save(values) +} + +func (t tenantLedgerQueryDo) First() (*TenantLedger, error) { + if result, err := t.DO.First(); err != nil { + return nil, err + } else { + return result.(*TenantLedger), nil + } +} + +func (t tenantLedgerQueryDo) Take() (*TenantLedger, error) { + if result, err := t.DO.Take(); err != nil { + return nil, err + } else { + return result.(*TenantLedger), nil + } +} + +func (t tenantLedgerQueryDo) Last() (*TenantLedger, error) { + if result, err := t.DO.Last(); err != nil { + return nil, err + } else { + return result.(*TenantLedger), nil + } +} + +func (t tenantLedgerQueryDo) Find() ([]*TenantLedger, error) { + result, err := t.DO.Find() + return result.([]*TenantLedger), err +} + +func (t tenantLedgerQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*TenantLedger, err error) { + buf := make([]*TenantLedger, 0, batchSize) + err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (t tenantLedgerQueryDo) FindInBatches(result *[]*TenantLedger, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return t.DO.FindInBatches(result, batchSize, fc) +} + +func (t tenantLedgerQueryDo) Attrs(attrs ...field.AssignExpr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Attrs(attrs...)) +} + +func (t tenantLedgerQueryDo) Assign(attrs ...field.AssignExpr) *tenantLedgerQueryDo { + return t.withDO(t.DO.Assign(attrs...)) +} + +func (t tenantLedgerQueryDo) Joins(fields ...field.RelationField) *tenantLedgerQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Joins(_f)) + } + return &t +} + +func (t tenantLedgerQueryDo) Preload(fields ...field.RelationField) *tenantLedgerQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Preload(_f)) + } + return &t +} + +func (t tenantLedgerQueryDo) FirstOrInit() (*TenantLedger, error) { + if result, err := t.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*TenantLedger), nil + } +} + +func (t tenantLedgerQueryDo) FirstOrCreate() (*TenantLedger, error) { + if result, err := t.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*TenantLedger), nil + } +} + +func (t tenantLedgerQueryDo) FindByPage(offset int, limit int) (result []*TenantLedger, count int64, err error) { + result, err = t.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = t.Offset(-1).Limit(-1).Count() + return +} + +func (t tenantLedgerQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = t.Count() + if err != nil { + return + } + + err = t.Offset(offset).Limit(limit).Scan(result) + return +} + +func (t tenantLedgerQueryDo) Scan(result interface{}) (err error) { + return t.DO.Scan(result) +} + +func (t tenantLedgerQueryDo) Delete(models ...*TenantLedger) (result gen.ResultInfo, err error) { + return t.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (t tenantLedgerQueryDo) ForceDelete() (gen.ResultInfo, error) { + return t.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (t tenantLedgerQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (t tenantLedgerQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (t tenantLedgerQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (t tenantLedgerQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (t tenantLedgerQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (t tenantLedgerQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (t tenantLedgerQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := t.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (t tenantLedgerQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := t.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (t tenantLedgerQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(t.TableName(), "id") + if err := t.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (t tenantLedgerQueryDo) GetByID(id int64) (*TenantLedger, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (t tenantLedgerQueryDo) GetByIDs(ids ...int64) ([]*TenantLedger, error) { + if len(ids) == 0 { + return []*TenantLedger{}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (t tenantLedgerQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (t tenantLedgerQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Delete() +} + +func (t *tenantLedgerQueryDo) withDO(do gen.Dao) *tenantLedgerQueryDo { + t.DO = *do.(*gen.DO) + return t +} diff --git a/models/tenant_users.gen.go b/models/tenant_users.gen.go new file mode 100644 index 0000000..66dac9b --- /dev/null +++ b/models/tenant_users.gen.go @@ -0,0 +1,60 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" +) + +const TableNameTenantUser = "tenant_users" + +// TenantUser mapped from table +type TenantUser struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + TenantID int64 `gorm:"column:tenant_id;type:bigint;not null" json:"tenant_id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Role types.Array[string] `gorm:"column:role;type:text[];default:{member}" json:"role"` + Status string `gorm:"column:status;type:character varying(50);default:verified" json:"status"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *TenantUser) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantUser.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *TenantUser) Save(ctx context.Context) error { return Q.TenantUser.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *TenantUser) Create(ctx context.Context) error { + return Q.TenantUser.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *TenantUser) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantUser.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *TenantUser) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.TenantUser.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *TenantUser) Reload(ctx context.Context) error { + fresh, err := Q.TenantUser.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/tenant_users.query.gen.go b/models/tenant_users.query.gen.go new file mode 100644 index 0000000..1e54b07 --- /dev/null +++ b/models/tenant_users.query.gen.go @@ -0,0 +1,485 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newTenantUser(db *gorm.DB, opts ...gen.DOOption) tenantUserQuery { + _tenantUserQuery := tenantUserQuery{} + + _tenantUserQuery.tenantUserQueryDo.UseDB(db, opts...) + _tenantUserQuery.tenantUserQueryDo.UseModel(&TenantUser{}) + + tableName := _tenantUserQuery.tenantUserQueryDo.TableName() + _tenantUserQuery.ALL = field.NewAsterisk(tableName) + _tenantUserQuery.ID = field.NewInt64(tableName, "id") + _tenantUserQuery.TenantID = field.NewInt64(tableName, "tenant_id") + _tenantUserQuery.UserID = field.NewInt64(tableName, "user_id") + _tenantUserQuery.Role = field.NewArray(tableName, "role") + _tenantUserQuery.Status = field.NewString(tableName, "status") + _tenantUserQuery.CreatedAt = field.NewTime(tableName, "created_at") + _tenantUserQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _tenantUserQuery.fillFieldMap() + + return _tenantUserQuery +} + +type tenantUserQuery struct { + tenantUserQueryDo tenantUserQueryDo + + ALL field.Asterisk + ID field.Int64 + TenantID field.Int64 + UserID field.Int64 + Role field.Array + Status field.String + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (t tenantUserQuery) Table(newTableName string) *tenantUserQuery { + t.tenantUserQueryDo.UseTable(newTableName) + return t.updateTableName(newTableName) +} + +func (t tenantUserQuery) As(alias string) *tenantUserQuery { + t.tenantUserQueryDo.DO = *(t.tenantUserQueryDo.As(alias).(*gen.DO)) + return t.updateTableName(alias) +} + +func (t *tenantUserQuery) updateTableName(table string) *tenantUserQuery { + t.ALL = field.NewAsterisk(table) + t.ID = field.NewInt64(table, "id") + t.TenantID = field.NewInt64(table, "tenant_id") + t.UserID = field.NewInt64(table, "user_id") + t.Role = field.NewArray(table, "role") + t.Status = field.NewString(table, "status") + t.CreatedAt = field.NewTime(table, "created_at") + t.UpdatedAt = field.NewTime(table, "updated_at") + + t.fillFieldMap() + + return t +} + +func (t *tenantUserQuery) QueryContext(ctx context.Context) (*tenantUserQuery, *tenantUserQueryDo) { + return t, t.tenantUserQueryDo.WithContext(ctx) +} + +func (t *tenantUserQuery) WithContext(ctx context.Context) *tenantUserQueryDo { + return t.tenantUserQueryDo.WithContext(ctx) +} + +func (t tenantUserQuery) TableName() string { return t.tenantUserQueryDo.TableName() } + +func (t tenantUserQuery) Alias() string { return t.tenantUserQueryDo.Alias() } + +func (t tenantUserQuery) Columns(cols ...field.Expr) gen.Columns { + return t.tenantUserQueryDo.Columns(cols...) +} + +func (t *tenantUserQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := t.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (t *tenantUserQuery) fillFieldMap() { + t.fieldMap = make(map[string]field.Expr, 7) + t.fieldMap["id"] = t.ID + t.fieldMap["tenant_id"] = t.TenantID + t.fieldMap["user_id"] = t.UserID + t.fieldMap["role"] = t.Role + t.fieldMap["status"] = t.Status + t.fieldMap["created_at"] = t.CreatedAt + t.fieldMap["updated_at"] = t.UpdatedAt +} + +func (t tenantUserQuery) clone(db *gorm.DB) tenantUserQuery { + t.tenantUserQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return t +} + +func (t tenantUserQuery) replaceDB(db *gorm.DB) tenantUserQuery { + t.tenantUserQueryDo.ReplaceDB(db) + return t +} + +type tenantUserQueryDo struct{ gen.DO } + +func (t tenantUserQueryDo) Debug() *tenantUserQueryDo { + return t.withDO(t.DO.Debug()) +} + +func (t tenantUserQueryDo) WithContext(ctx context.Context) *tenantUserQueryDo { + return t.withDO(t.DO.WithContext(ctx)) +} + +func (t tenantUserQueryDo) ReadDB() *tenantUserQueryDo { + return t.Clauses(dbresolver.Read) +} + +func (t tenantUserQueryDo) WriteDB() *tenantUserQueryDo { + return t.Clauses(dbresolver.Write) +} + +func (t tenantUserQueryDo) Session(config *gorm.Session) *tenantUserQueryDo { + return t.withDO(t.DO.Session(config)) +} + +func (t tenantUserQueryDo) Clauses(conds ...clause.Expression) *tenantUserQueryDo { + return t.withDO(t.DO.Clauses(conds...)) +} + +func (t tenantUserQueryDo) Returning(value interface{}, columns ...string) *tenantUserQueryDo { + return t.withDO(t.DO.Returning(value, columns...)) +} + +func (t tenantUserQueryDo) Not(conds ...gen.Condition) *tenantUserQueryDo { + return t.withDO(t.DO.Not(conds...)) +} + +func (t tenantUserQueryDo) Or(conds ...gen.Condition) *tenantUserQueryDo { + return t.withDO(t.DO.Or(conds...)) +} + +func (t tenantUserQueryDo) Select(conds ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.Select(conds...)) +} + +func (t tenantUserQueryDo) Where(conds ...gen.Condition) *tenantUserQueryDo { + return t.withDO(t.DO.Where(conds...)) +} + +func (t tenantUserQueryDo) Order(conds ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.Order(conds...)) +} + +func (t tenantUserQueryDo) Distinct(cols ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.Distinct(cols...)) +} + +func (t tenantUserQueryDo) Omit(cols ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.Omit(cols...)) +} + +func (t tenantUserQueryDo) Join(table schema.Tabler, on ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.Join(table, on...)) +} + +func (t tenantUserQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.LeftJoin(table, on...)) +} + +func (t tenantUserQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.RightJoin(table, on...)) +} + +func (t tenantUserQueryDo) Group(cols ...field.Expr) *tenantUserQueryDo { + return t.withDO(t.DO.Group(cols...)) +} + +func (t tenantUserQueryDo) Having(conds ...gen.Condition) *tenantUserQueryDo { + return t.withDO(t.DO.Having(conds...)) +} + +func (t tenantUserQueryDo) Limit(limit int) *tenantUserQueryDo { + return t.withDO(t.DO.Limit(limit)) +} + +func (t tenantUserQueryDo) Offset(offset int) *tenantUserQueryDo { + return t.withDO(t.DO.Offset(offset)) +} + +func (t tenantUserQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *tenantUserQueryDo { + return t.withDO(t.DO.Scopes(funcs...)) +} + +func (t tenantUserQueryDo) Unscoped() *tenantUserQueryDo { + return t.withDO(t.DO.Unscoped()) +} + +func (t tenantUserQueryDo) Create(values ...*TenantUser) error { + if len(values) == 0 { + return nil + } + return t.DO.Create(values) +} + +func (t tenantUserQueryDo) CreateInBatches(values []*TenantUser, batchSize int) error { + return t.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (t tenantUserQueryDo) Save(values ...*TenantUser) error { + if len(values) == 0 { + return nil + } + return t.DO.Save(values) +} + +func (t tenantUserQueryDo) First() (*TenantUser, error) { + if result, err := t.DO.First(); err != nil { + return nil, err + } else { + return result.(*TenantUser), nil + } +} + +func (t tenantUserQueryDo) Take() (*TenantUser, error) { + if result, err := t.DO.Take(); err != nil { + return nil, err + } else { + return result.(*TenantUser), nil + } +} + +func (t tenantUserQueryDo) Last() (*TenantUser, error) { + if result, err := t.DO.Last(); err != nil { + return nil, err + } else { + return result.(*TenantUser), nil + } +} + +func (t tenantUserQueryDo) Find() ([]*TenantUser, error) { + result, err := t.DO.Find() + return result.([]*TenantUser), err +} + +func (t tenantUserQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*TenantUser, err error) { + buf := make([]*TenantUser, 0, batchSize) + err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (t tenantUserQueryDo) FindInBatches(result *[]*TenantUser, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return t.DO.FindInBatches(result, batchSize, fc) +} + +func (t tenantUserQueryDo) Attrs(attrs ...field.AssignExpr) *tenantUserQueryDo { + return t.withDO(t.DO.Attrs(attrs...)) +} + +func (t tenantUserQueryDo) Assign(attrs ...field.AssignExpr) *tenantUserQueryDo { + return t.withDO(t.DO.Assign(attrs...)) +} + +func (t tenantUserQueryDo) Joins(fields ...field.RelationField) *tenantUserQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Joins(_f)) + } + return &t +} + +func (t tenantUserQueryDo) Preload(fields ...field.RelationField) *tenantUserQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Preload(_f)) + } + return &t +} + +func (t tenantUserQueryDo) FirstOrInit() (*TenantUser, error) { + if result, err := t.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*TenantUser), nil + } +} + +func (t tenantUserQueryDo) FirstOrCreate() (*TenantUser, error) { + if result, err := t.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*TenantUser), nil + } +} + +func (t tenantUserQueryDo) FindByPage(offset int, limit int) (result []*TenantUser, count int64, err error) { + result, err = t.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = t.Offset(-1).Limit(-1).Count() + return +} + +func (t tenantUserQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = t.Count() + if err != nil { + return + } + + err = t.Offset(offset).Limit(limit).Scan(result) + return +} + +func (t tenantUserQueryDo) Scan(result interface{}) (err error) { + return t.DO.Scan(result) +} + +func (t tenantUserQueryDo) Delete(models ...*TenantUser) (result gen.ResultInfo, err error) { + return t.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (t tenantUserQueryDo) ForceDelete() (gen.ResultInfo, error) { + return t.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (t tenantUserQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (t tenantUserQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (t tenantUserQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (t tenantUserQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (t tenantUserQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (t tenantUserQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (t tenantUserQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := t.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (t tenantUserQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := t.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (t tenantUserQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(t.TableName(), "id") + if err := t.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (t tenantUserQueryDo) GetByID(id int64) (*TenantUser, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (t tenantUserQueryDo) GetByIDs(ids ...int64) ([]*TenantUser, error) { + if len(ids) == 0 { + return []*TenantUser{}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (t tenantUserQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (t tenantUserQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Delete() +} + +func (t *tenantUserQueryDo) withDO(do gen.Dao) *tenantUserQueryDo { + t.DO = *do.(*gen.DO) + return t +} diff --git a/models/tenants.gen.go b/models/tenants.gen.go new file mode 100644 index 0000000..359dbe8 --- /dev/null +++ b/models/tenants.gen.go @@ -0,0 +1,61 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" +) + +const TableNameTenant = "tenants" + +// Tenant mapped from table +type Tenant struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + Code string `gorm:"column:code;type:character varying(64);not null" json:"code"` + UUID types.UUID `gorm:"column:uuid;type:uuid;not null" json:"uuid"` + Name string `gorm:"column:name;type:character varying(128);not null" json:"name"` + Status string `gorm:"column:status;type:character varying(64);not null" json:"status"` + Config types.JSON `gorm:"column:config;type:jsonb;default:{}" json:"config"` + ExpiredAt time.Time `gorm:"column:expired_at;type:timestamp with time zone" json:"expired_at"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *Tenant) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.Tenant.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *Tenant) Save(ctx context.Context) error { return Q.Tenant.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *Tenant) Create(ctx context.Context) error { return Q.Tenant.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *Tenant) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Tenant.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *Tenant) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.Tenant.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *Tenant) Reload(ctx context.Context) error { + fresh, err := Q.Tenant.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/tenants.go b/models/tenants.go similarity index 100% rename from backend/database/models/tenants.go rename to models/tenants.go diff --git a/models/tenants.query.gen.go b/models/tenants.query.gen.go new file mode 100644 index 0000000..ef4497f --- /dev/null +++ b/models/tenants.query.gen.go @@ -0,0 +1,495 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newTenant(db *gorm.DB, opts ...gen.DOOption) tenantQuery { + _tenantQuery := tenantQuery{} + + _tenantQuery.tenantQueryDo.UseDB(db, opts...) + _tenantQuery.tenantQueryDo.UseModel(&Tenant{}) + + tableName := _tenantQuery.tenantQueryDo.TableName() + _tenantQuery.ALL = field.NewAsterisk(tableName) + _tenantQuery.ID = field.NewInt64(tableName, "id") + _tenantQuery.UserID = field.NewInt64(tableName, "user_id") + _tenantQuery.Code = field.NewString(tableName, "code") + _tenantQuery.UUID = field.NewField(tableName, "uuid") + _tenantQuery.Name = field.NewString(tableName, "name") + _tenantQuery.Status = field.NewString(tableName, "status") + _tenantQuery.Config = field.NewJSONB(tableName, "config") + _tenantQuery.ExpiredAt = field.NewTime(tableName, "expired_at") + _tenantQuery.CreatedAt = field.NewTime(tableName, "created_at") + _tenantQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + + _tenantQuery.fillFieldMap() + + return _tenantQuery +} + +type tenantQuery struct { + tenantQueryDo tenantQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + Code field.String + UUID field.Field + Name field.String + Status field.String + Config field.JSONB + ExpiredAt field.Time + CreatedAt field.Time + UpdatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (t tenantQuery) Table(newTableName string) *tenantQuery { + t.tenantQueryDo.UseTable(newTableName) + return t.updateTableName(newTableName) +} + +func (t tenantQuery) As(alias string) *tenantQuery { + t.tenantQueryDo.DO = *(t.tenantQueryDo.As(alias).(*gen.DO)) + return t.updateTableName(alias) +} + +func (t *tenantQuery) updateTableName(table string) *tenantQuery { + t.ALL = field.NewAsterisk(table) + t.ID = field.NewInt64(table, "id") + t.UserID = field.NewInt64(table, "user_id") + t.Code = field.NewString(table, "code") + t.UUID = field.NewField(table, "uuid") + t.Name = field.NewString(table, "name") + t.Status = field.NewString(table, "status") + t.Config = field.NewJSONB(table, "config") + t.ExpiredAt = field.NewTime(table, "expired_at") + t.CreatedAt = field.NewTime(table, "created_at") + t.UpdatedAt = field.NewTime(table, "updated_at") + + t.fillFieldMap() + + return t +} + +func (t *tenantQuery) QueryContext(ctx context.Context) (*tenantQuery, *tenantQueryDo) { + return t, t.tenantQueryDo.WithContext(ctx) +} + +func (t *tenantQuery) WithContext(ctx context.Context) *tenantQueryDo { + return t.tenantQueryDo.WithContext(ctx) +} + +func (t tenantQuery) TableName() string { return t.tenantQueryDo.TableName() } + +func (t tenantQuery) Alias() string { return t.tenantQueryDo.Alias() } + +func (t tenantQuery) Columns(cols ...field.Expr) gen.Columns { return t.tenantQueryDo.Columns(cols...) } + +func (t *tenantQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := t.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (t *tenantQuery) fillFieldMap() { + t.fieldMap = make(map[string]field.Expr, 10) + t.fieldMap["id"] = t.ID + t.fieldMap["user_id"] = t.UserID + t.fieldMap["code"] = t.Code + t.fieldMap["uuid"] = t.UUID + t.fieldMap["name"] = t.Name + t.fieldMap["status"] = t.Status + t.fieldMap["config"] = t.Config + t.fieldMap["expired_at"] = t.ExpiredAt + t.fieldMap["created_at"] = t.CreatedAt + t.fieldMap["updated_at"] = t.UpdatedAt +} + +func (t tenantQuery) clone(db *gorm.DB) tenantQuery { + t.tenantQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return t +} + +func (t tenantQuery) replaceDB(db *gorm.DB) tenantQuery { + t.tenantQueryDo.ReplaceDB(db) + return t +} + +type tenantQueryDo struct{ gen.DO } + +func (t tenantQueryDo) Debug() *tenantQueryDo { + return t.withDO(t.DO.Debug()) +} + +func (t tenantQueryDo) WithContext(ctx context.Context) *tenantQueryDo { + return t.withDO(t.DO.WithContext(ctx)) +} + +func (t tenantQueryDo) ReadDB() *tenantQueryDo { + return t.Clauses(dbresolver.Read) +} + +func (t tenantQueryDo) WriteDB() *tenantQueryDo { + return t.Clauses(dbresolver.Write) +} + +func (t tenantQueryDo) Session(config *gorm.Session) *tenantQueryDo { + return t.withDO(t.DO.Session(config)) +} + +func (t tenantQueryDo) Clauses(conds ...clause.Expression) *tenantQueryDo { + return t.withDO(t.DO.Clauses(conds...)) +} + +func (t tenantQueryDo) Returning(value interface{}, columns ...string) *tenantQueryDo { + return t.withDO(t.DO.Returning(value, columns...)) +} + +func (t tenantQueryDo) Not(conds ...gen.Condition) *tenantQueryDo { + return t.withDO(t.DO.Not(conds...)) +} + +func (t tenantQueryDo) Or(conds ...gen.Condition) *tenantQueryDo { + return t.withDO(t.DO.Or(conds...)) +} + +func (t tenantQueryDo) Select(conds ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.Select(conds...)) +} + +func (t tenantQueryDo) Where(conds ...gen.Condition) *tenantQueryDo { + return t.withDO(t.DO.Where(conds...)) +} + +func (t tenantQueryDo) Order(conds ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.Order(conds...)) +} + +func (t tenantQueryDo) Distinct(cols ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.Distinct(cols...)) +} + +func (t tenantQueryDo) Omit(cols ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.Omit(cols...)) +} + +func (t tenantQueryDo) Join(table schema.Tabler, on ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.Join(table, on...)) +} + +func (t tenantQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.LeftJoin(table, on...)) +} + +func (t tenantQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.RightJoin(table, on...)) +} + +func (t tenantQueryDo) Group(cols ...field.Expr) *tenantQueryDo { + return t.withDO(t.DO.Group(cols...)) +} + +func (t tenantQueryDo) Having(conds ...gen.Condition) *tenantQueryDo { + return t.withDO(t.DO.Having(conds...)) +} + +func (t tenantQueryDo) Limit(limit int) *tenantQueryDo { + return t.withDO(t.DO.Limit(limit)) +} + +func (t tenantQueryDo) Offset(offset int) *tenantQueryDo { + return t.withDO(t.DO.Offset(offset)) +} + +func (t tenantQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *tenantQueryDo { + return t.withDO(t.DO.Scopes(funcs...)) +} + +func (t tenantQueryDo) Unscoped() *tenantQueryDo { + return t.withDO(t.DO.Unscoped()) +} + +func (t tenantQueryDo) Create(values ...*Tenant) error { + if len(values) == 0 { + return nil + } + return t.DO.Create(values) +} + +func (t tenantQueryDo) CreateInBatches(values []*Tenant, batchSize int) error { + return t.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (t tenantQueryDo) Save(values ...*Tenant) error { + if len(values) == 0 { + return nil + } + return t.DO.Save(values) +} + +func (t tenantQueryDo) First() (*Tenant, error) { + if result, err := t.DO.First(); err != nil { + return nil, err + } else { + return result.(*Tenant), nil + } +} + +func (t tenantQueryDo) Take() (*Tenant, error) { + if result, err := t.DO.Take(); err != nil { + return nil, err + } else { + return result.(*Tenant), nil + } +} + +func (t tenantQueryDo) Last() (*Tenant, error) { + if result, err := t.DO.Last(); err != nil { + return nil, err + } else { + return result.(*Tenant), nil + } +} + +func (t tenantQueryDo) Find() ([]*Tenant, error) { + result, err := t.DO.Find() + return result.([]*Tenant), err +} + +func (t tenantQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Tenant, err error) { + buf := make([]*Tenant, 0, batchSize) + err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (t tenantQueryDo) FindInBatches(result *[]*Tenant, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return t.DO.FindInBatches(result, batchSize, fc) +} + +func (t tenantQueryDo) Attrs(attrs ...field.AssignExpr) *tenantQueryDo { + return t.withDO(t.DO.Attrs(attrs...)) +} + +func (t tenantQueryDo) Assign(attrs ...field.AssignExpr) *tenantQueryDo { + return t.withDO(t.DO.Assign(attrs...)) +} + +func (t tenantQueryDo) Joins(fields ...field.RelationField) *tenantQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Joins(_f)) + } + return &t +} + +func (t tenantQueryDo) Preload(fields ...field.RelationField) *tenantQueryDo { + for _, _f := range fields { + t = *t.withDO(t.DO.Preload(_f)) + } + return &t +} + +func (t tenantQueryDo) FirstOrInit() (*Tenant, error) { + if result, err := t.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*Tenant), nil + } +} + +func (t tenantQueryDo) FirstOrCreate() (*Tenant, error) { + if result, err := t.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*Tenant), nil + } +} + +func (t tenantQueryDo) FindByPage(offset int, limit int) (result []*Tenant, count int64, err error) { + result, err = t.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = t.Offset(-1).Limit(-1).Count() + return +} + +func (t tenantQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = t.Count() + if err != nil { + return + } + + err = t.Offset(offset).Limit(limit).Scan(result) + return +} + +func (t tenantQueryDo) Scan(result interface{}) (err error) { + return t.DO.Scan(result) +} + +func (t tenantQueryDo) Delete(models ...*Tenant) (result gen.ResultInfo, err error) { + return t.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (t tenantQueryDo) ForceDelete() (gen.ResultInfo, error) { + return t.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (t tenantQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (t tenantQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return t.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (t tenantQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (t tenantQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (t tenantQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (t tenantQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := t.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (t tenantQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := t.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (t tenantQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := t.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (t tenantQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(t.TableName(), "id") + if err := t.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (t tenantQueryDo) GetByID(id int64) (*Tenant, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (t tenantQueryDo) GetByIDs(ids ...int64) ([]*Tenant, error) { + if len(ids) == 0 { + return []*Tenant{}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (t tenantQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (t tenantQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(t.TableName(), "id") + return t.Where(pk.In(ids...)).Delete() +} + +func (t *tenantQueryDo) withDO(do gen.Dao) *tenantQueryDo { + t.DO = *do.(*gen.DO) + return t +} diff --git a/models/user_comment_actions.gen.go b/models/user_comment_actions.gen.go new file mode 100644 index 0000000..174be0c --- /dev/null +++ b/models/user_comment_actions.gen.go @@ -0,0 +1,59 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameUserCommentAction = "user_comment_actions" + +// UserCommentAction mapped from table +type UserCommentAction struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + CommentID int64 `gorm:"column:comment_id;type:bigint;not null" json:"comment_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *UserCommentAction) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserCommentAction.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *UserCommentAction) Save(ctx context.Context) error { + return Q.UserCommentAction.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *UserCommentAction) Create(ctx context.Context) error { + return Q.UserCommentAction.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *UserCommentAction) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserCommentAction.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *UserCommentAction) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserCommentAction.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *UserCommentAction) Reload(ctx context.Context) error { + fresh, err := Q.UserCommentAction.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/user_comment_actions.query.gen.go b/models/user_comment_actions.query.gen.go new file mode 100644 index 0000000..1798ff7 --- /dev/null +++ b/models/user_comment_actions.query.gen.go @@ -0,0 +1,477 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newUserCommentAction(db *gorm.DB, opts ...gen.DOOption) userCommentActionQuery { + _userCommentActionQuery := userCommentActionQuery{} + + _userCommentActionQuery.userCommentActionQueryDo.UseDB(db, opts...) + _userCommentActionQuery.userCommentActionQueryDo.UseModel(&UserCommentAction{}) + + tableName := _userCommentActionQuery.userCommentActionQueryDo.TableName() + _userCommentActionQuery.ALL = field.NewAsterisk(tableName) + _userCommentActionQuery.ID = field.NewInt64(tableName, "id") + _userCommentActionQuery.UserID = field.NewInt64(tableName, "user_id") + _userCommentActionQuery.CommentID = field.NewInt64(tableName, "comment_id") + _userCommentActionQuery.Type = field.NewString(tableName, "type") + _userCommentActionQuery.CreatedAt = field.NewTime(tableName, "created_at") + + _userCommentActionQuery.fillFieldMap() + + return _userCommentActionQuery +} + +type userCommentActionQuery struct { + userCommentActionQueryDo userCommentActionQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + CommentID field.Int64 + Type field.String + CreatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (u userCommentActionQuery) Table(newTableName string) *userCommentActionQuery { + u.userCommentActionQueryDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userCommentActionQuery) As(alias string) *userCommentActionQuery { + u.userCommentActionQueryDo.DO = *(u.userCommentActionQueryDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userCommentActionQuery) updateTableName(table string) *userCommentActionQuery { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewInt64(table, "id") + u.UserID = field.NewInt64(table, "user_id") + u.CommentID = field.NewInt64(table, "comment_id") + u.Type = field.NewString(table, "type") + u.CreatedAt = field.NewTime(table, "created_at") + + u.fillFieldMap() + + return u +} + +func (u *userCommentActionQuery) QueryContext(ctx context.Context) (*userCommentActionQuery, *userCommentActionQueryDo) { + return u, u.userCommentActionQueryDo.WithContext(ctx) +} + +func (u *userCommentActionQuery) WithContext(ctx context.Context) *userCommentActionQueryDo { + return u.userCommentActionQueryDo.WithContext(ctx) +} + +func (u userCommentActionQuery) TableName() string { return u.userCommentActionQueryDo.TableName() } + +func (u userCommentActionQuery) Alias() string { return u.userCommentActionQueryDo.Alias() } + +func (u userCommentActionQuery) Columns(cols ...field.Expr) gen.Columns { + return u.userCommentActionQueryDo.Columns(cols...) +} + +func (u *userCommentActionQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := u.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (u *userCommentActionQuery) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 5) + u.fieldMap["id"] = u.ID + u.fieldMap["user_id"] = u.UserID + u.fieldMap["comment_id"] = u.CommentID + u.fieldMap["type"] = u.Type + u.fieldMap["created_at"] = u.CreatedAt +} + +func (u userCommentActionQuery) clone(db *gorm.DB) userCommentActionQuery { + u.userCommentActionQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userCommentActionQuery) replaceDB(db *gorm.DB) userCommentActionQuery { + u.userCommentActionQueryDo.ReplaceDB(db) + return u +} + +type userCommentActionQueryDo struct{ gen.DO } + +func (u userCommentActionQueryDo) Debug() *userCommentActionQueryDo { + return u.withDO(u.DO.Debug()) +} + +func (u userCommentActionQueryDo) WithContext(ctx context.Context) *userCommentActionQueryDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userCommentActionQueryDo) ReadDB() *userCommentActionQueryDo { + return u.Clauses(dbresolver.Read) +} + +func (u userCommentActionQueryDo) WriteDB() *userCommentActionQueryDo { + return u.Clauses(dbresolver.Write) +} + +func (u userCommentActionQueryDo) Session(config *gorm.Session) *userCommentActionQueryDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userCommentActionQueryDo) Clauses(conds ...clause.Expression) *userCommentActionQueryDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userCommentActionQueryDo) Returning(value interface{}, columns ...string) *userCommentActionQueryDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userCommentActionQueryDo) Not(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userCommentActionQueryDo) Or(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userCommentActionQueryDo) Select(conds ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userCommentActionQueryDo) Where(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userCommentActionQueryDo) Order(conds ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userCommentActionQueryDo) Distinct(cols ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userCommentActionQueryDo) Omit(cols ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userCommentActionQueryDo) Join(table schema.Tabler, on ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userCommentActionQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userCommentActionQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userCommentActionQueryDo) Group(cols ...field.Expr) *userCommentActionQueryDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userCommentActionQueryDo) Having(conds ...gen.Condition) *userCommentActionQueryDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userCommentActionQueryDo) Limit(limit int) *userCommentActionQueryDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userCommentActionQueryDo) Offset(offset int) *userCommentActionQueryDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userCommentActionQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userCommentActionQueryDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userCommentActionQueryDo) Unscoped() *userCommentActionQueryDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userCommentActionQueryDo) Create(values ...*UserCommentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userCommentActionQueryDo) CreateInBatches(values []*UserCommentAction, batchSize int) error { + return u.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (u userCommentActionQueryDo) Save(values ...*UserCommentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userCommentActionQueryDo) First() (*UserCommentAction, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) Take() (*UserCommentAction, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) Last() (*UserCommentAction, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) Find() ([]*UserCommentAction, error) { + result, err := u.DO.Find() + return result.([]*UserCommentAction), err +} + +func (u userCommentActionQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*UserCommentAction, err error) { + buf := make([]*UserCommentAction, 0, batchSize) + err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (u userCommentActionQueryDo) FindInBatches(result *[]*UserCommentAction, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userCommentActionQueryDo) Attrs(attrs ...field.AssignExpr) *userCommentActionQueryDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userCommentActionQueryDo) Assign(attrs ...field.AssignExpr) *userCommentActionQueryDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userCommentActionQueryDo) Joins(fields ...field.RelationField) *userCommentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userCommentActionQueryDo) Preload(fields ...field.RelationField) *userCommentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userCommentActionQueryDo) FirstOrInit() (*UserCommentAction, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) FirstOrCreate() (*UserCommentAction, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*UserCommentAction), nil + } +} + +func (u userCommentActionQueryDo) FindByPage(offset int, limit int) (result []*UserCommentAction, count int64, err error) { + result, err = u.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = u.Offset(-1).Limit(-1).Count() + return +} + +func (u userCommentActionQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = u.Count() + if err != nil { + return + } + + err = u.Offset(offset).Limit(limit).Scan(result) + return +} + +func (u userCommentActionQueryDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userCommentActionQueryDo) Delete(models ...*UserCommentAction) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (u userCommentActionQueryDo) ForceDelete() (gen.ResultInfo, error) { + return u.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (u userCommentActionQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (u userCommentActionQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (u userCommentActionQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (u userCommentActionQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (u userCommentActionQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (u userCommentActionQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (u userCommentActionQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := u.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (u userCommentActionQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := u.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (u userCommentActionQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(u.TableName(), "id") + if err := u.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (u userCommentActionQueryDo) GetByID(id int64) (*UserCommentAction, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (u userCommentActionQueryDo) GetByIDs(ids ...int64) ([]*UserCommentAction, error) { + if len(ids) == 0 { + return []*UserCommentAction{}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (u userCommentActionQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (u userCommentActionQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Delete() +} + +func (u *userCommentActionQueryDo) withDO(do gen.Dao) *userCommentActionQueryDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/models/user_content_actions.gen.go b/models/user_content_actions.gen.go new file mode 100644 index 0000000..c1eb247 --- /dev/null +++ b/models/user_content_actions.gen.go @@ -0,0 +1,59 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" +) + +const TableNameUserContentAction = "user_content_actions" + +// UserContentAction mapped from table +type UserContentAction struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + UserID int64 `gorm:"column:user_id;type:bigint;not null" json:"user_id"` + ContentID int64 `gorm:"column:content_id;type:bigint;not null" json:"content_id"` + Type string `gorm:"column:type;type:character varying(32);not null" json:"type"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *UserContentAction) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserContentAction.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *UserContentAction) Save(ctx context.Context) error { + return Q.UserContentAction.WithContext(ctx).Save(m) +} + +// Create inserts the model using the default DB. +func (m *UserContentAction) Create(ctx context.Context) error { + return Q.UserContentAction.WithContext(ctx).Create(m) +} + +// Delete removes the row represented by the model using the default DB. +func (m *UserContentAction) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserContentAction.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *UserContentAction) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.UserContentAction.WithContext(ctx).Unscoped().Delete(m) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *UserContentAction) Reload(ctx context.Context) error { + fresh, err := Q.UserContentAction.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/models/user_content_actions.query.gen.go b/models/user_content_actions.query.gen.go new file mode 100644 index 0000000..54ce8a5 --- /dev/null +++ b/models/user_content_actions.query.gen.go @@ -0,0 +1,477 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newUserContentAction(db *gorm.DB, opts ...gen.DOOption) userContentActionQuery { + _userContentActionQuery := userContentActionQuery{} + + _userContentActionQuery.userContentActionQueryDo.UseDB(db, opts...) + _userContentActionQuery.userContentActionQueryDo.UseModel(&UserContentAction{}) + + tableName := _userContentActionQuery.userContentActionQueryDo.TableName() + _userContentActionQuery.ALL = field.NewAsterisk(tableName) + _userContentActionQuery.ID = field.NewInt64(tableName, "id") + _userContentActionQuery.UserID = field.NewInt64(tableName, "user_id") + _userContentActionQuery.ContentID = field.NewInt64(tableName, "content_id") + _userContentActionQuery.Type = field.NewString(tableName, "type") + _userContentActionQuery.CreatedAt = field.NewTime(tableName, "created_at") + + _userContentActionQuery.fillFieldMap() + + return _userContentActionQuery +} + +type userContentActionQuery struct { + userContentActionQueryDo userContentActionQueryDo + + ALL field.Asterisk + ID field.Int64 + UserID field.Int64 + ContentID field.Int64 + Type field.String + CreatedAt field.Time + + fieldMap map[string]field.Expr +} + +func (u userContentActionQuery) Table(newTableName string) *userContentActionQuery { + u.userContentActionQueryDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userContentActionQuery) As(alias string) *userContentActionQuery { + u.userContentActionQueryDo.DO = *(u.userContentActionQueryDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userContentActionQuery) updateTableName(table string) *userContentActionQuery { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewInt64(table, "id") + u.UserID = field.NewInt64(table, "user_id") + u.ContentID = field.NewInt64(table, "content_id") + u.Type = field.NewString(table, "type") + u.CreatedAt = field.NewTime(table, "created_at") + + u.fillFieldMap() + + return u +} + +func (u *userContentActionQuery) QueryContext(ctx context.Context) (*userContentActionQuery, *userContentActionQueryDo) { + return u, u.userContentActionQueryDo.WithContext(ctx) +} + +func (u *userContentActionQuery) WithContext(ctx context.Context) *userContentActionQueryDo { + return u.userContentActionQueryDo.WithContext(ctx) +} + +func (u userContentActionQuery) TableName() string { return u.userContentActionQueryDo.TableName() } + +func (u userContentActionQuery) Alias() string { return u.userContentActionQueryDo.Alias() } + +func (u userContentActionQuery) Columns(cols ...field.Expr) gen.Columns { + return u.userContentActionQueryDo.Columns(cols...) +} + +func (u *userContentActionQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := u.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (u *userContentActionQuery) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 5) + u.fieldMap["id"] = u.ID + u.fieldMap["user_id"] = u.UserID + u.fieldMap["content_id"] = u.ContentID + u.fieldMap["type"] = u.Type + u.fieldMap["created_at"] = u.CreatedAt +} + +func (u userContentActionQuery) clone(db *gorm.DB) userContentActionQuery { + u.userContentActionQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userContentActionQuery) replaceDB(db *gorm.DB) userContentActionQuery { + u.userContentActionQueryDo.ReplaceDB(db) + return u +} + +type userContentActionQueryDo struct{ gen.DO } + +func (u userContentActionQueryDo) Debug() *userContentActionQueryDo { + return u.withDO(u.DO.Debug()) +} + +func (u userContentActionQueryDo) WithContext(ctx context.Context) *userContentActionQueryDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userContentActionQueryDo) ReadDB() *userContentActionQueryDo { + return u.Clauses(dbresolver.Read) +} + +func (u userContentActionQueryDo) WriteDB() *userContentActionQueryDo { + return u.Clauses(dbresolver.Write) +} + +func (u userContentActionQueryDo) Session(config *gorm.Session) *userContentActionQueryDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userContentActionQueryDo) Clauses(conds ...clause.Expression) *userContentActionQueryDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userContentActionQueryDo) Returning(value interface{}, columns ...string) *userContentActionQueryDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userContentActionQueryDo) Not(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userContentActionQueryDo) Or(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userContentActionQueryDo) Select(conds ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userContentActionQueryDo) Where(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userContentActionQueryDo) Order(conds ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userContentActionQueryDo) Distinct(cols ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userContentActionQueryDo) Omit(cols ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userContentActionQueryDo) Join(table schema.Tabler, on ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userContentActionQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userContentActionQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userContentActionQueryDo) Group(cols ...field.Expr) *userContentActionQueryDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userContentActionQueryDo) Having(conds ...gen.Condition) *userContentActionQueryDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userContentActionQueryDo) Limit(limit int) *userContentActionQueryDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userContentActionQueryDo) Offset(offset int) *userContentActionQueryDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userContentActionQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userContentActionQueryDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userContentActionQueryDo) Unscoped() *userContentActionQueryDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userContentActionQueryDo) Create(values ...*UserContentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userContentActionQueryDo) CreateInBatches(values []*UserContentAction, batchSize int) error { + return u.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (u userContentActionQueryDo) Save(values ...*UserContentAction) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userContentActionQueryDo) First() (*UserContentAction, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) Take() (*UserContentAction, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) Last() (*UserContentAction, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) Find() ([]*UserContentAction, error) { + result, err := u.DO.Find() + return result.([]*UserContentAction), err +} + +func (u userContentActionQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*UserContentAction, err error) { + buf := make([]*UserContentAction, 0, batchSize) + err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (u userContentActionQueryDo) FindInBatches(result *[]*UserContentAction, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userContentActionQueryDo) Attrs(attrs ...field.AssignExpr) *userContentActionQueryDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userContentActionQueryDo) Assign(attrs ...field.AssignExpr) *userContentActionQueryDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userContentActionQueryDo) Joins(fields ...field.RelationField) *userContentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userContentActionQueryDo) Preload(fields ...field.RelationField) *userContentActionQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userContentActionQueryDo) FirstOrInit() (*UserContentAction, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) FirstOrCreate() (*UserContentAction, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*UserContentAction), nil + } +} + +func (u userContentActionQueryDo) FindByPage(offset int, limit int) (result []*UserContentAction, count int64, err error) { + result, err = u.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = u.Offset(-1).Limit(-1).Count() + return +} + +func (u userContentActionQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = u.Count() + if err != nil { + return + } + + err = u.Offset(offset).Limit(limit).Scan(result) + return +} + +func (u userContentActionQueryDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userContentActionQueryDo) Delete(models ...*UserContentAction) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (u userContentActionQueryDo) ForceDelete() (gen.ResultInfo, error) { + return u.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (u userContentActionQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (u userContentActionQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (u userContentActionQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (u userContentActionQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (u userContentActionQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (u userContentActionQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (u userContentActionQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := u.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (u userContentActionQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := u.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (u userContentActionQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(u.TableName(), "id") + if err := u.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (u userContentActionQueryDo) GetByID(id int64) (*UserContentAction, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (u userContentActionQueryDo) GetByIDs(ids ...int64) ([]*UserContentAction, error) { + if len(ids) == 0 { + return []*UserContentAction{}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (u userContentActionQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (u userContentActionQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Delete() +} + +func (u *userContentActionQueryDo) withDO(do gen.Dao) *userContentActionQueryDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/models/users.gen.go b/models/users.gen.go new file mode 100644 index 0000000..4a5a2f5 --- /dev/null +++ b/models/users.gen.go @@ -0,0 +1,78 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + "time" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/types" + "gorm.io/gorm" +) + +const TableNameUser = "users" + +// User mapped from table +type User struct { + ID int64 `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id"` + Username string `gorm:"column:username;type:character varying(255);not null" json:"username"` + Password string `gorm:"column:password;type:character varying(255);not null" json:"password"` + Roles types.Array[string] `gorm:"column:roles;type:text[];default:{user}" json:"roles"` + Status string `gorm:"column:status;type:character varying(50);default:active" json:"status"` + Metas types.JSON `gorm:"column:metas;type:jsonb;default:{}" json:"metas"` + Balance int64 `gorm:"column:balance;type:bigint" json:"balance"` + BalanceFrozen int64 `gorm:"column:balance_frozen;type:bigint" json:"balance_frozen"` + VerifiedAt time.Time `gorm:"column:verified_at;type:timestamp with time zone" json:"verified_at"` + Nickname string `gorm:"column:nickname;type:character varying(255)" json:"nickname"` + Avatar string `gorm:"column:avatar;type:character varying(512)" json:"avatar"` + Gender string `gorm:"column:gender;type:character varying(32);default:secret" json:"gender"` + Bio string `gorm:"column:bio;type:character varying(512)" json:"bio"` + Birthday types.Date `gorm:"column:birthday;type:date" json:"birthday"` + Location types.JSON `gorm:"column:location;type:jsonb;default:{}" json:"location"` + Points int64 `gorm:"column:points;type:bigint" json:"points"` + Phone string `gorm:"column:phone;type:character varying(32)" json:"phone"` + IsRealNameVerified bool `gorm:"column:is_real_name_verified;type:boolean" json:"is_real_name_verified"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp with time zone;default:now()" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp with time zone;default:now()" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp with time zone" json:"deleted_at"` +} + +// Quick operations without importing query package +// Update applies changed fields to the database using the default DB. +func (m *User) Update(ctx context.Context) (gen.ResultInfo, error) { + return Q.User.WithContext(ctx).Updates(m) +} + +// Save upserts the model using the default DB. +func (m *User) Save(ctx context.Context) error { return Q.User.WithContext(ctx).Save(m) } + +// Create inserts the model using the default DB. +func (m *User) Create(ctx context.Context) error { return Q.User.WithContext(ctx).Create(m) } + +// Delete removes the row represented by the model using the default DB. +func (m *User) Delete(ctx context.Context) (gen.ResultInfo, error) { + return Q.User.WithContext(ctx).Delete(m) +} + +// ForceDelete permanently deletes the row (ignores soft delete) using the default DB. +func (m *User) ForceDelete(ctx context.Context) (gen.ResultInfo, error) { + return Q.User.WithContext(ctx).Unscoped().Delete(m) +} + +// Restore sets deleted_at to NULL for this model's primary key using the default DB. +func (m *User) Restore(ctx context.Context) (gen.ResultInfo, error) { + return Q.User.WithContext(ctx).RestoreByID(m.ID) +} + +// Reload reloads the model from database by its primary key and overwrites current fields. +func (m *User) Reload(ctx context.Context) error { + fresh, err := Q.User.WithContext(ctx).GetByID(m.ID) + if err != nil { + return err + } + *m = *fresh + return nil +} diff --git a/backend/database/models/users.go b/models/users.go similarity index 57% rename from backend/database/models/users.go rename to models/users.go index fd15cd4..37d51ce 100644 --- a/backend/database/models/users.go +++ b/models/users.go @@ -16,7 +16,13 @@ func (m *User) ComparePassword(ctx context.Context, password string) bool { } func (m *User) HasRole(ctx context.Context, role consts.Role) bool { - return lo.Contains(m.Roles, role) + // m.Roles is types.Array[string] (aliased from text[]), so we need to cast/check manually if lo.Contains fails on type match + // or cast role to string. + // Error said: m.Roles is types.Array[string]. + // lo.Contains expects []T, val T. + // If m.Roles is []string, and role is consts.Role (string), it fails. + // We should cast m.Roles to []string (it likely already is) and role to string. + return lo.Contains([]string(m.Roles), string(role)) } // BeforeCreate diff --git a/models/users.query.gen.go b/models/users.query.gen.go new file mode 100644 index 0000000..03668b2 --- /dev/null +++ b/models/users.query.gen.go @@ -0,0 +1,552 @@ +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. +// Code generated by go.ipao.vip/gen. DO NOT EDIT. + +package models + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "go.ipao.vip/gen" + "go.ipao.vip/gen/field" + + "gorm.io/plugin/dbresolver" +) + +func newUser(db *gorm.DB, opts ...gen.DOOption) userQuery { + _userQuery := userQuery{} + + _userQuery.userQueryDo.UseDB(db, opts...) + _userQuery.userQueryDo.UseModel(&User{}) + + tableName := _userQuery.userQueryDo.TableName() + _userQuery.ALL = field.NewAsterisk(tableName) + _userQuery.ID = field.NewInt64(tableName, "id") + _userQuery.Username = field.NewString(tableName, "username") + _userQuery.Password = field.NewString(tableName, "password") + _userQuery.Roles = field.NewArray(tableName, "roles") + _userQuery.Status = field.NewString(tableName, "status") + _userQuery.Metas = field.NewJSONB(tableName, "metas") + _userQuery.Balance = field.NewInt64(tableName, "balance") + _userQuery.BalanceFrozen = field.NewInt64(tableName, "balance_frozen") + _userQuery.VerifiedAt = field.NewTime(tableName, "verified_at") + _userQuery.Nickname = field.NewString(tableName, "nickname") + _userQuery.Avatar = field.NewString(tableName, "avatar") + _userQuery.Gender = field.NewString(tableName, "gender") + _userQuery.Bio = field.NewString(tableName, "bio") + _userQuery.Birthday = field.NewField(tableName, "birthday") + _userQuery.Location = field.NewJSONB(tableName, "location") + _userQuery.Points = field.NewInt64(tableName, "points") + _userQuery.Phone = field.NewString(tableName, "phone") + _userQuery.IsRealNameVerified = field.NewBool(tableName, "is_real_name_verified") + _userQuery.CreatedAt = field.NewTime(tableName, "created_at") + _userQuery.UpdatedAt = field.NewTime(tableName, "updated_at") + _userQuery.DeletedAt = field.NewField(tableName, "deleted_at") + + _userQuery.fillFieldMap() + + return _userQuery +} + +type userQuery struct { + userQueryDo userQueryDo + + ALL field.Asterisk + ID field.Int64 + Username field.String + Password field.String + Roles field.Array + Status field.String + Metas field.JSONB + Balance field.Int64 + BalanceFrozen field.Int64 + VerifiedAt field.Time + Nickname field.String + Avatar field.String + Gender field.String + Bio field.String + Birthday field.Field + Location field.JSONB + Points field.Int64 + Phone field.String + IsRealNameVerified field.Bool + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + + fieldMap map[string]field.Expr +} + +func (u userQuery) Table(newTableName string) *userQuery { + u.userQueryDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userQuery) As(alias string) *userQuery { + u.userQueryDo.DO = *(u.userQueryDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userQuery) updateTableName(table string) *userQuery { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewInt64(table, "id") + u.Username = field.NewString(table, "username") + u.Password = field.NewString(table, "password") + u.Roles = field.NewArray(table, "roles") + u.Status = field.NewString(table, "status") + u.Metas = field.NewJSONB(table, "metas") + u.Balance = field.NewInt64(table, "balance") + u.BalanceFrozen = field.NewInt64(table, "balance_frozen") + u.VerifiedAt = field.NewTime(table, "verified_at") + u.Nickname = field.NewString(table, "nickname") + u.Avatar = field.NewString(table, "avatar") + u.Gender = field.NewString(table, "gender") + u.Bio = field.NewString(table, "bio") + u.Birthday = field.NewField(table, "birthday") + u.Location = field.NewJSONB(table, "location") + u.Points = field.NewInt64(table, "points") + u.Phone = field.NewString(table, "phone") + u.IsRealNameVerified = field.NewBool(table, "is_real_name_verified") + u.CreatedAt = field.NewTime(table, "created_at") + u.UpdatedAt = field.NewTime(table, "updated_at") + u.DeletedAt = field.NewField(table, "deleted_at") + + u.fillFieldMap() + + return u +} + +func (u *userQuery) QueryContext(ctx context.Context) (*userQuery, *userQueryDo) { + return u, u.userQueryDo.WithContext(ctx) +} + +func (u *userQuery) WithContext(ctx context.Context) *userQueryDo { + return u.userQueryDo.WithContext(ctx) +} + +func (u userQuery) TableName() string { return u.userQueryDo.TableName() } + +func (u userQuery) Alias() string { return u.userQueryDo.Alias() } + +func (u userQuery) Columns(cols ...field.Expr) gen.Columns { return u.userQueryDo.Columns(cols...) } + +func (u *userQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := u.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (u *userQuery) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 21) + u.fieldMap["id"] = u.ID + u.fieldMap["username"] = u.Username + u.fieldMap["password"] = u.Password + u.fieldMap["roles"] = u.Roles + u.fieldMap["status"] = u.Status + u.fieldMap["metas"] = u.Metas + u.fieldMap["balance"] = u.Balance + u.fieldMap["balance_frozen"] = u.BalanceFrozen + u.fieldMap["verified_at"] = u.VerifiedAt + u.fieldMap["nickname"] = u.Nickname + u.fieldMap["avatar"] = u.Avatar + u.fieldMap["gender"] = u.Gender + u.fieldMap["bio"] = u.Bio + u.fieldMap["birthday"] = u.Birthday + u.fieldMap["location"] = u.Location + u.fieldMap["points"] = u.Points + u.fieldMap["phone"] = u.Phone + u.fieldMap["is_real_name_verified"] = u.IsRealNameVerified + u.fieldMap["created_at"] = u.CreatedAt + u.fieldMap["updated_at"] = u.UpdatedAt + u.fieldMap["deleted_at"] = u.DeletedAt +} + +func (u userQuery) clone(db *gorm.DB) userQuery { + u.userQueryDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userQuery) replaceDB(db *gorm.DB) userQuery { + u.userQueryDo.ReplaceDB(db) + return u +} + +type userQueryDo struct{ gen.DO } + +func (u userQueryDo) Debug() *userQueryDo { + return u.withDO(u.DO.Debug()) +} + +func (u userQueryDo) WithContext(ctx context.Context) *userQueryDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userQueryDo) ReadDB() *userQueryDo { + return u.Clauses(dbresolver.Read) +} + +func (u userQueryDo) WriteDB() *userQueryDo { + return u.Clauses(dbresolver.Write) +} + +func (u userQueryDo) Session(config *gorm.Session) *userQueryDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userQueryDo) Clauses(conds ...clause.Expression) *userQueryDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userQueryDo) Returning(value interface{}, columns ...string) *userQueryDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userQueryDo) Not(conds ...gen.Condition) *userQueryDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userQueryDo) Or(conds ...gen.Condition) *userQueryDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userQueryDo) Select(conds ...field.Expr) *userQueryDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userQueryDo) Where(conds ...gen.Condition) *userQueryDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userQueryDo) Order(conds ...field.Expr) *userQueryDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userQueryDo) Distinct(cols ...field.Expr) *userQueryDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userQueryDo) Omit(cols ...field.Expr) *userQueryDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userQueryDo) Join(table schema.Tabler, on ...field.Expr) *userQueryDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userQueryDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *userQueryDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userQueryDo) Group(cols ...field.Expr) *userQueryDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userQueryDo) Having(conds ...gen.Condition) *userQueryDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userQueryDo) Limit(limit int) *userQueryDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userQueryDo) Offset(offset int) *userQueryDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userQueryDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userQueryDo) Unscoped() *userQueryDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userQueryDo) Create(values ...*User) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userQueryDo) CreateInBatches(values []*User, batchSize int) error { + return u.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (u userQueryDo) Save(values ...*User) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userQueryDo) First() (*User, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*User), nil + } +} + +func (u userQueryDo) Take() (*User, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*User), nil + } +} + +func (u userQueryDo) Last() (*User, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*User), nil + } +} + +func (u userQueryDo) Find() ([]*User, error) { + result, err := u.DO.Find() + return result.([]*User), err +} + +func (u userQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*User, err error) { + buf := make([]*User, 0, batchSize) + err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (u userQueryDo) FindInBatches(result *[]*User, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userQueryDo) Attrs(attrs ...field.AssignExpr) *userQueryDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userQueryDo) Assign(attrs ...field.AssignExpr) *userQueryDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userQueryDo) Joins(fields ...field.RelationField) *userQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userQueryDo) Preload(fields ...field.RelationField) *userQueryDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userQueryDo) FirstOrInit() (*User, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*User), nil + } +} + +func (u userQueryDo) FirstOrCreate() (*User, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*User), nil + } +} + +func (u userQueryDo) FindByPage(offset int, limit int) (result []*User, count int64, err error) { + result, err = u.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = u.Offset(-1).Limit(-1).Count() + return +} + +func (u userQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = u.Count() + if err != nil { + return + } + + err = u.Offset(offset).Limit(limit).Scan(result) + return +} + +func (u userQueryDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userQueryDo) Delete(models ...*User) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +// ForceDelete performs a permanent delete (ignores soft-delete) for current scope. +func (u userQueryDo) ForceDelete() (gen.ResultInfo, error) { + return u.Unscoped().Delete() +} + +// Inc increases the given column by step for current scope. +func (u userQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column + step + e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Dec decreases the given column by step for current scope. +func (u userQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) { + // column = column - step + e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step) + return u.DO.UpdateColumn(column, e) +} + +// Sum returns SUM(column) for current scope. +func (u userQueryDo) Sum(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Avg returns AVG(column) for current scope. +func (u userQueryDo) Avg(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Min returns MIN(column) for current scope. +func (u userQueryDo) Min(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// Max returns MAX(column) for current scope. +func (u userQueryDo) Max(column field.Expr) (float64, error) { + var _v float64 + agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr()) + if err := u.Select(agg).Scan(&_v); err != nil { + return 0, err + } + return _v, nil +} + +// PluckMap returns a map[key]value for selected key/value expressions within current scope. +func (u userQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) { + do := u.Select(key, val) + rows, err := do.DO.Rows() + if err != nil { + return nil, err + } + defer rows.Close() + mm := make(map[interface{}]interface{}) + for rows.Next() { + var k interface{} + var v interface{} + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + mm[k] = v + } + return mm, rows.Err() +} + +// Exists returns true if any record matches the given conditions. +func (u userQueryDo) Exists(conds ...gen.Condition) (bool, error) { + cnt, err := u.Where(conds...).Count() + if err != nil { + return false, err + } + return cnt > 0, nil +} + +// PluckIDs returns all primary key values under current scope. +func (u userQueryDo) PluckIDs() ([]int64, error) { + ids := make([]int64, 0, 16) + pk := field.NewInt64(u.TableName(), "id") + if err := u.DO.Pluck(pk, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// GetByID finds a single record by primary key. +func (u userQueryDo) GetByID(id int64) (*User, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).First() +} + +// GetByIDs finds records by primary key list. +func (u userQueryDo) GetByIDs(ids ...int64) ([]*User, error) { + if len(ids) == 0 { + return []*User{}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Find() +} + +// DeleteByID deletes records by primary key. +func (u userQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.Eq(id)).Delete() +} + +// DeleteByIDs deletes records by a list of primary keys. +func (u userQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) { + if len(ids) == 0 { + return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil + } + pk := field.NewInt64(u.TableName(), "id") + return u.Where(pk.In(ids...)).Delete() +} + +// RestoreWhere sets deleted_at to NULL for rows matching current scope + conds. +func (u userQueryDo) RestoreWhere(conds ...gen.Condition) (gen.ResultInfo, error) { + col := field.NewField(u.TableName(), "deleted_at") + return u.Unscoped().Where(conds...).UpdateColumn(col, nil) +} + +// RestoreByID sets deleted_at to NULL for the given primary key. +func (u userQueryDo) RestoreByID(id int64) (gen.ResultInfo, error) { + pk := field.NewInt64(u.TableName(), "id") + col := field.NewField(u.TableName(), "deleted_at") + return u.Unscoped().Where(pk.Eq(id)).UpdateColumn(col, nil) +} + +func (u *userQueryDo) withDO(do gen.Dao) *userQueryDo { + u.DO = *do.(*gen.DO) + return u +}