Refactor: Remove deprecated gRPC service files and implement new API structure

- Deleted old gRPC service definitions in `game_grpc.pb.go` and `public.go`.
- Added new API server implementations for objectstory, player, and shop services.
- Introduced configuration files for new APIs in `etc/*.yaml`.
- Created main entry points for each service in `objectstory.go`, `player.go`, and `shop.go`.
- Removed unused user update handler and user API files.
- Added utility functions for context management and HTTP header parsing.
- Introduced PostgreSQL backup configuration in `backup/postgreSql.yaml`.
This commit is contained in:
wwweww
2026-02-28 18:35:56 +08:00
parent d2f33b4b96
commit 19cc7a778c
349 changed files with 42548 additions and 1453 deletions
+14
View File
@@ -0,0 +1,14 @@
Name: wallet-api
Host: 0.0.0.0
Port: 8888
Prometheus:
Host: 0.0.0.0
Port: 4001
Path: /metrics
WalletRpcConf:
Target: k8s://juwan/wallet-rpc:8080
# k8s://juwan/<service name>:8080
+14
View File
@@ -0,0 +1,14 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package config
import (
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/zrpc"
)
type Config struct {
rest.RestConf
WalletRpcConf zrpc.RpcClientConf
}
+45
View File
@@ -0,0 +1,45 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
package handler
import (
"net/http"
wallet "juwan-backend/app/wallet/api/internal/handler/wallet"
"juwan-backend/app/wallet/api/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
// 获取余额
Method: http.MethodGet,
Path: "/balance",
Handler: wallet.GetBalanceHandler(serverCtx),
},
{
// 充值
Method: http.MethodPost,
Path: "/topup",
Handler: wallet.TopupHandler(serverCtx),
},
{
// 获取流水
Method: http.MethodGet,
Path: "/transactions",
Handler: wallet.ListTransactionsHandler(serverCtx),
},
{
// 提现
Method: http.MethodPost,
Path: "/withdraw",
Handler: wallet.WithdrawHandler(serverCtx),
},
},
rest.WithPrefix("/api/v1/wallet"),
)
}
@@ -0,0 +1,32 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"juwan-backend/app/wallet/api/internal/logic/wallet"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
)
// 获取余额
func GetBalanceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.EmptyResp
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := wallet.NewGetBalanceLogic(r.Context(), svcCtx)
resp, err := l.GetBalance(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -0,0 +1,32 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"juwan-backend/app/wallet/api/internal/logic/wallet"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
)
// 获取流水
func ListTransactionsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.PageReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := wallet.NewListTransactionsLogic(r.Context(), svcCtx)
resp, err := l.ListTransactions(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -0,0 +1,32 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"juwan-backend/app/wallet/api/internal/logic/wallet"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
)
// 充值
func TopupHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.TopupReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := wallet.NewTopupLogic(r.Context(), svcCtx)
resp, err := l.Topup(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -0,0 +1,32 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"juwan-backend/app/wallet/api/internal/logic/wallet"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
)
// 提现
func WithdrawHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.TopupReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := wallet.NewWithdrawLogic(r.Context(), svcCtx)
resp, err := l.Withdraw(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -0,0 +1,52 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"context"
"juwan-backend/app/wallet/rpc/pb"
"juwan-backend/common/utils/contextj"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetBalanceLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 获取余额
func NewGetBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBalanceLogic {
return &GetBalanceLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetBalanceLogic) GetBalance(req *types.EmptyResp) (resp *types.WalletBalance, err error) {
userID, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, err
}
out, err := l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID})
if err != nil {
return nil, err
}
if out.GetWallets() == nil {
return &types.WalletBalance{Balance: "0", FrozenBalance: "0"}, nil
}
return &types.WalletBalance{
Balance: out.Wallets.Balance,
FrozenBalance: out.Wallets.FrozenBalance,
}, nil
}
@@ -0,0 +1,80 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"context"
"strconv"
"time"
"juwan-backend/app/wallet/rpc/pb"
"juwan-backend/common/utils/contextj"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ListTransactionsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 获取流水
func NewListTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListTransactionsLogic {
return &ListTransactionsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ListTransactionsLogic) ListTransactions(req *types.PageReq) (resp *types.TransactionListResp, err error) {
userID, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, err
}
if req.Limit <= 0 {
req.Limit = 20
}
out, err := l.svcCtx.WalletRpc.SearchWalletTransactions(l.ctx, &pb.SearchWalletTransactionsReq{
Page: req.Offset / req.Limit,
Limit: req.Limit,
UserId: &userID,
})
if err != nil {
return nil, err
}
items := make([]types.Transaction, 0, len(out.GetWalletTransactions()))
for _, item := range out.GetWalletTransactions() {
if item == nil {
continue
}
tx := types.Transaction{
Id: item.Id,
Type: item.Type,
Amount: item.Amount,
Description: item.Description,
CreatedAt: time.Unix(item.CreatedAt, 0).Format(time.RFC3339),
}
if item.OrderId > 0 {
tx.OrderId = strconv.FormatInt(item.OrderId, 10)
}
items = append(items, tx)
}
return &types.TransactionListResp{
Items: items,
Meta: types.PageMeta{
Total: int64(len(items)),
Offset: req.Offset,
Limit: req.Limit,
},
}, nil
}
@@ -0,0 +1,127 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"context"
"errors"
"fmt"
"time"
"juwan-backend/app/wallet/rpc/pb"
"juwan-backend/common/utils/contextj"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
)
type TopupLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 充值
func NewTopupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopupLogic {
return &TopupLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *TopupLogic) Topup(req *types.TopupReq) (resp *types.EmptyResp, err error) {
amount, err := decimal.NewFromString(req.Amount)
if err != nil {
return nil, errors.New("invalid amount")
}
if !amount.GreaterThan(decimal.Zero) {
return nil, errors.New("amount must be greater than 0")
}
userID, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, err
}
walletResp, err := l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID})
if err != nil {
return nil, err
}
currentBalance := decimal.Zero
frozenBalance := decimal.Zero
expectedVersion := int64(0)
if walletResp.GetWallets() == nil {
zeroAmount := "0"
_, err = l.svcCtx.WalletRpc.AddWallets(l.ctx, &pb.AddWalletsReq{
UserId: userID,
Balance: zeroAmount,
FrozenBalance: zeroAmount,
UpdatedAt: time.Now().Unix(),
})
if err != nil {
return nil, err
}
walletResp, err = l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID})
if err != nil {
return nil, err
}
if walletResp.GetWallets() == nil {
return nil, errors.New("wallet not found")
}
currentBalance, err = decimal.NewFromString(walletResp.Wallets.Balance)
if err != nil {
return nil, errors.New("invalid wallet balance")
}
frozenBalance, err = decimal.NewFromString(walletResp.Wallets.FrozenBalance)
if err != nil {
return nil, errors.New("invalid wallet frozen balance")
}
expectedVersion = walletResp.Wallets.Version
} else {
currentBalance, err = decimal.NewFromString(walletResp.Wallets.Balance)
if err != nil {
return nil, errors.New("invalid wallet balance")
}
frozenBalance, err = decimal.NewFromString(walletResp.Wallets.FrozenBalance)
if err != nil {
return nil, errors.New("invalid wallet frozen balance")
}
expectedVersion = walletResp.Wallets.Version
}
newBalance := currentBalance.Add(amount)
newBalanceStr := newBalance.String()
frozenBalanceStr := frozenBalance.String()
updatedAt := time.Now().Unix()
_, err = l.svcCtx.WalletRpc.UpdateWallets(l.ctx, &pb.UpdateWalletsReq{
UserId: userID,
Balance: &newBalanceStr,
FrozenBalance: &frozenBalanceStr,
UpdatedAt: &updatedAt,
Version: &expectedVersion,
})
if err != nil {
return nil, err
}
desc := fmt.Sprintf("topup via %s", req.Method)
_, err = l.svcCtx.WalletRpc.AddWalletTransactions(l.ctx, &pb.AddWalletTransactionsReq{
UserId: userID,
Type: "topup",
Amount: amount.String(),
BalanceAfter: newBalanceStr,
Description: desc,
CreatedAt: updatedAt,
})
if err != nil {
return nil, err
}
return &types.EmptyResp{}, nil
}
@@ -0,0 +1,101 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package wallet
import (
"context"
"errors"
"fmt"
"time"
"juwan-backend/app/wallet/rpc/pb"
"juwan-backend/common/utils/contextj"
"juwan-backend/app/wallet/api/internal/svc"
"juwan-backend/app/wallet/api/internal/types"
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
)
type WithdrawLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 提现
func NewWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WithdrawLogic {
return &WithdrawLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WithdrawLogic) Withdraw(req *types.TopupReq) (resp *types.EmptyResp, err error) {
amount, err := decimal.NewFromString(req.Amount)
if err != nil {
return nil, errors.New("invalid amount")
}
if !amount.GreaterThan(decimal.Zero) {
return nil, errors.New("amount must be greater than 0")
}
userID, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, err
}
walletResp, err := l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID})
if err != nil {
return nil, err
}
if walletResp.GetWallets() == nil {
return nil, errors.New("wallet not found")
}
currentBalance, err := decimal.NewFromString(walletResp.Wallets.Balance)
if err != nil {
return nil, errors.New("invalid wallet balance")
}
frozenBalance, err := decimal.NewFromString(walletResp.Wallets.FrozenBalance)
if err != nil {
return nil, errors.New("invalid wallet frozen balance")
}
expectedVersion := walletResp.Wallets.Version
if currentBalance.LessThan(amount) {
return nil, errors.New("insufficient balance")
}
newBalance := currentBalance.Sub(amount)
newBalanceStr := newBalance.String()
frozenBalanceStr := frozenBalance.String()
updatedAt := time.Now().Unix()
_, err = l.svcCtx.WalletRpc.UpdateWallets(l.ctx, &pb.UpdateWalletsReq{
UserId: userID,
Balance: &newBalanceStr,
FrozenBalance: &frozenBalanceStr,
UpdatedAt: &updatedAt,
Version: &expectedVersion,
})
if err != nil {
return nil, err
}
desc := fmt.Sprintf("withdraw via %s", req.Method)
_, err = l.svcCtx.WalletRpc.AddWalletTransactions(l.ctx, &pb.AddWalletTransactionsReq{
UserId: userID,
Type: "withdrawal",
Amount: amount.String(),
BalanceAfter: newBalanceStr,
Description: desc,
CreatedAt: updatedAt,
})
if err != nil {
return nil, err
}
return &types.EmptyResp{}, nil
}
@@ -0,0 +1,23 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package svc
import (
"juwan-backend/app/wallet/api/internal/config"
"juwan-backend/app/wallet/rpc/walletservice"
"github.com/zeromicro/go-zero/zrpc"
)
type ServiceContext struct {
Config config.Config
WalletRpc walletservice.WalletService
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
WalletRpc: walletservice.NewWalletService(zrpc.MustNewClient(c.WalletRpcConf)),
}
}
+61
View File
@@ -0,0 +1,61 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
package types
type EmptyResp struct {
}
type PageMeta struct {
Total int64 `json:"total"`
Offset int64 `json:"offset"`
Limit int64 `json:"limit"`
}
type PageReq struct {
Offset int64 `form:"offset,default=0"`
Limit int64 `form:"limit,default=20"`
}
type SimpleUser struct {
Id string `json:"id"`
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
}
type TopupReq struct {
Amount string `json:"amount"`
Method string `json:"method"`
}
type Transaction struct {
Id int64 `json:"id"`
Type string `json:"type"`
Amount string `json:"amount"`
Description string `json:"description"`
OrderId string `json:"orderId,optional"`
CreatedAt string `json:"createdAt"`
}
type TransactionListResp struct {
Items []Transaction `json:"items"`
Meta PageMeta `json:"meta"`
}
type UserProfile struct {
Id string `json:"id"`
Username string `json:"username"`
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
Role string `json:"role"` // consumer, player, owner, admin
VerifiedRoles []string `json:"verifiedRoles"`
VerificationStatus map[string]string `json:"verificationStatus"`
Phone string `json:"phone,optional"`
Bio string `json:"bio,optional"`
CreatedAt string `json:"createdAt"`
}
type WalletBalance struct {
Balance string `json:"balance"`
FrozenBalance string `json:"frozenBalance"`
}
+34
View File
@@ -0,0 +1,34 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package main
import (
"flag"
"fmt"
"juwan-backend/app/wallet/api/internal/config"
"juwan-backend/app/wallet/api/internal/handler"
"juwan-backend/app/wallet/api/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/wallet-api.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}
+38
View File
@@ -0,0 +1,38 @@
Name: pb.rpc
ListenOn: 0.0.0.0:8080
Prometheus:
Host: 0.0.0.0
Port: 4001
Path: /metrics
# tcd:
# Hosts:
# - 127.0.0.1:2379
# Key: pb.rpc
# Target: k8s://juwan/<service name>.<namespace>:8080
SnowflakeRpcConf:
Target: k8s://juwan/snowflake-svc:8080
DB:
Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable"
Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable"
CacheConf:
- Host: "${REDIS_M_HOST}"
Type: node
Pass: "${REDIS_PASSWORD}"
User: "default"
- Host: "${REDIS_S_HOST}"
Type: node
Pass: "${REDIS_PASSWORD}"
User: "default"
Log:
Level: info
+17
View File
@@ -0,0 +1,17 @@
package config
import (
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/zrpc"
)
type Config struct {
zrpc.RpcServerConf
SnowflakeRpcConf zrpc.RpcClientConf
DB struct {
Master string
Slaves string
}
CacheConf cache.CacheConf
}
@@ -0,0 +1,85 @@
package logic
import (
"context"
"errors"
"strconv"
"time"
"juwan-backend/app/snowflake/rpc/snowflake"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
)
type AddWalletTransactionsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewAddWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddWalletTransactionsLogic {
return &AddWalletTransactionsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// -----------------------walletTransactions-----------------------
func (l *AddWalletTransactionsLogic) AddWalletTransactions(in *pb.AddWalletTransactionsReq) (*pb.AddWalletTransactionsResp, error) {
idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
if err != nil {
return nil, err
}
createdAt := time.Now()
if in.CreatedAt > 0 {
createdAt = time.Unix(in.CreatedAt, 0)
}
searchText := in.SearchText
if searchText == "" {
searchText = in.Type + " " + in.Description
}
amount, err := decimal.NewFromString(in.GetAmount())
if err != nil {
return nil, errors.New("invalid amount")
}
balanceAfter, err := decimal.NewFromString(in.GetBalanceAfter())
if err != nil {
return nil, errors.New("invalid balanceAfter")
}
tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx)
if err != nil {
return nil, err
}
_, err = tx.WalletTransactions.Create().
SetID(strconv.FormatInt(idResp.Id, 10)).
SetUserID(in.UserId).
SetType(in.Type).
SetAmount(amount).
SetBalanceAfter(balanceAfter).
SetDescription([]string{in.Description}).
SetOrderID(in.OrderId).
SetCreatedAt(createdAt).
SetSearchText(searchText).
Save(l.ctx)
if err != nil {
_ = tx.Rollback()
return nil, err
}
if err = tx.Commit(); err != nil {
return nil, err
}
return &pb.AddWalletTransactionsResp{}, nil
}
@@ -0,0 +1,72 @@
package logic
import (
"context"
"errors"
"time"
"juwan-backend/app/wallet/rpc/internal/models"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
)
type AddWalletsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewAddWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddWalletsLogic {
return &AddWalletsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// -----------------------wallets-----------------------
func (l *AddWalletsLogic) AddWallets(in *pb.AddWalletsReq) (*pb.AddWalletsResp, error) {
updatedAt := time.Now()
if in.UpdatedAt > 0 {
updatedAt = time.Unix(in.UpdatedAt, 0)
}
balance, err := decimal.NewFromString(in.GetBalance())
if err != nil {
return nil, errors.New("invalid balance")
}
frozenBalance, err := decimal.NewFromString(in.GetFrozenBalance())
if err != nil {
return nil, errors.New("invalid frozenBalance")
}
tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx)
if err != nil {
return nil, err
}
_, err = tx.Wallet.Create().
SetUserID(in.UserId).
SetBalance(balance).
SetFrozenBalance(frozenBalance).
SetVersion(1).
SetUpdatedAt(updatedAt).
Save(l.ctx)
if err != nil {
_ = tx.Rollback()
if models.IsConstraintError(err) {
return &pb.AddWalletsResp{}, nil
}
return nil, err
}
if err = tx.Commit(); err != nil {
return nil, err
}
return &pb.AddWalletsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type DelWalletTransactionsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewDelWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelWalletTransactionsLogic {
return &DelWalletTransactionsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *DelWalletTransactionsLogic) DelWalletTransactions(in *pb.DelWalletTransactionsReq) (*pb.DelWalletTransactionsResp, error) {
// todo: add your logic here and delete this line
return &pb.DelWalletTransactionsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type DelWalletsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewDelWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelWalletsLogic {
return &DelWalletsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *DelWalletsLogic) DelWallets(in *pb.DelWalletsReq) (*pb.DelWalletsResp, error) {
// todo: add your logic here and delete this line
return &pb.DelWalletsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type GetWalletTransactionsByIdLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetWalletTransactionsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWalletTransactionsByIdLogic {
return &GetWalletTransactionsByIdLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetWalletTransactionsByIdLogic) GetWalletTransactionsById(in *pb.GetWalletTransactionsByIdReq) (*pb.GetWalletTransactionsByIdResp, error) {
// todo: add your logic here and delete this line
return &pb.GetWalletTransactionsByIdResp{}, nil
}
@@ -0,0 +1,52 @@
package logic
import (
"context"
"juwan-backend/app/wallet/rpc/internal/models"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type GetWalletsByIdLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetWalletsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWalletsByIdLogic {
return &GetWalletsByIdLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetWalletsByIdLogic) GetWalletsById(in *pb.GetWalletsByIdReq) (*pb.GetWalletsByIdResp, error) {
item, err := l.svcCtx.WalletModelsRO.Wallet.Query().
Where(wallet.UserIDEQ(in.Id)).
First(l.ctx)
if err != nil {
if models.IsNotFound(err) {
return &pb.GetWalletsByIdResp{}, nil
}
return nil, err
}
updatedAt := int64(0)
if !item.UpdatedAt.IsZero() {
updatedAt = item.UpdatedAt.Unix()
}
return &pb.GetWalletsByIdResp{
Wallets: &pb.Wallets{
UserId: item.UserID,
Balance: item.Balance.String(),
FrozenBalance: item.FrozenBalance.String(),
UpdatedAt: updatedAt,
Version: int64(item.Version),
},
}, nil
}
@@ -0,0 +1,106 @@
package logic
import (
"context"
"errors"
"strconv"
"time"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
)
type SearchWalletTransactionsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSearchWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchWalletTransactionsLogic {
return &SearchWalletTransactionsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SearchWalletTransactionsLogic) SearchWalletTransactions(in *pb.SearchWalletTransactionsReq) (*pb.SearchWalletTransactionsResp, error) {
if in.Limit <= 0 {
in.Limit = 20
}
preds := make([]predicate.WalletTransactions, 0, 8)
if in.Id > 0 {
preds = append(preds, wallettransactions.IDEQ(strconv.FormatInt(in.Id, 10)))
}
if in.UserId != nil {
preds = append(preds, wallettransactions.UserIDEQ(in.GetUserId()))
}
if in.Type != nil && in.GetType() != "" {
preds = append(preds, wallettransactions.TypeEQ(in.GetType()))
}
if in.Amount != nil {
amount, perr := decimal.NewFromString(in.GetAmount())
if perr != nil {
return nil, errors.New("invalid amount")
}
preds = append(preds, wallettransactions.AmountEQ(amount))
}
if in.BalanceAfter != nil {
balanceAfter, perr := decimal.NewFromString(in.GetBalanceAfter())
if perr != nil {
return nil, errors.New("invalid balanceAfter")
}
preds = append(preds, wallettransactions.BalanceAfterEQ(balanceAfter))
}
if in.OrderId != nil {
preds = append(preds, wallettransactions.OrderIDEQ(in.GetOrderId()))
}
if in.CreatedAt != nil && in.GetCreatedAt() > 0 {
preds = append(preds, wallettransactions.CreatedAtGTE(time.Unix(in.GetCreatedAt(), 0)))
}
if in.SearchText != nil && in.GetSearchText() != "" {
preds = append(preds, wallettransactions.SearchTextContainsFold(in.GetSearchText()))
}
query := l.svcCtx.WalletModelsRO.WalletTransactions.Query()
if len(preds) > 0 {
query = query.Where(wallettransactions.And(preds...))
}
list, err := query.
Offset(int(in.Page * in.Limit)).
Limit(int(in.Limit)).
All(l.ctx)
if err != nil {
return nil, err
}
result := make([]*pb.WalletTransactions, 0, len(list))
for _, item := range list {
id, _ := strconv.ParseInt(item.ID, 10, 64)
description := ""
if len(item.Description) > 0 {
description = item.Description[0]
}
result = append(result, &pb.WalletTransactions{
Id: id,
UserId: item.UserID,
Type: item.Type,
Amount: item.Amount.String(),
BalanceAfter: item.BalanceAfter.String(),
Description: description,
OrderId: item.OrderID,
CreatedAt: item.CreatedAt.Unix(),
SearchText: item.SearchText,
})
}
return &pb.SearchWalletTransactionsResp{WalletTransactions: result}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type SearchWalletsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSearchWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchWalletsLogic {
return &SearchWalletsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SearchWalletsLogic) SearchWallets(in *pb.SearchWalletsReq) (*pb.SearchWalletsResp, error) {
// todo: add your logic here and delete this line
return &pb.SearchWalletsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateWalletTransactionsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateWalletTransactionsLogic {
return &UpdateWalletTransactionsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *UpdateWalletTransactionsLogic) UpdateWalletTransactions(in *pb.UpdateWalletTransactionsReq) (*pb.UpdateWalletTransactionsResp, error) {
// todo: add your logic here and delete this line
return &pb.UpdateWalletTransactionsResp{}, nil
}
@@ -0,0 +1,89 @@
package logic
import (
"context"
"errors"
"time"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateWalletsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateWalletsLogic {
return &UpdateWalletsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *UpdateWalletsLogic) UpdateWallets(in *pb.UpdateWalletsReq) (*pb.UpdateWalletsResp, error) {
if in.Version == nil {
return nil, errors.New("version is required")
}
tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx)
if err != nil {
return nil, err
}
updater := tx.Wallet.Update().
Where(wallet.UserIDEQ(in.UserId), wallet.VersionEQ(int(in.GetVersion()))).
AddVersion(1)
if in.Balance != nil {
parsedBalance, perr := decimal.NewFromString(in.GetBalance())
if perr != nil {
_ = tx.Rollback()
return nil, errors.New("invalid balance")
}
updater = updater.SetBalance(parsedBalance)
}
if in.FrozenBalance != nil {
parsedFrozenBalance, perr := decimal.NewFromString(in.GetFrozenBalance())
if perr != nil {
_ = tx.Rollback()
return nil, errors.New("invalid frozenBalance")
}
updater = updater.SetFrozenBalance(parsedFrozenBalance)
}
if in.UpdatedAt != nil && in.GetUpdatedAt() > 0 {
updater = updater.SetUpdatedAt(time.Unix(in.GetUpdatedAt(), 0))
} else {
updater = updater.SetUpdatedAt(time.Now())
}
affected, err := updater.Save(l.ctx)
if err != nil {
_ = tx.Rollback()
return nil, err
}
if affected == 0 {
exist, qerr := tx.Wallet.Query().Where(wallet.UserIDEQ(in.UserId)).Exist(l.ctx)
_ = tx.Rollback()
if qerr != nil {
return nil, qerr
}
if !exist {
return nil, errors.New("wallet not found")
}
return nil, errors.New("wallet update conflict")
}
if err = tx.Commit(); err != nil {
return nil, err
}
return &pb.UpdateWalletsResp{}, nil
}
+484
View File
@@ -0,0 +1,484 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"juwan-backend/app/wallet/rpc/internal/models/migrate"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Wallet is the client for interacting with the Wallet builders.
Wallet *WalletClient
// WalletTransactions is the client for interacting with the WalletTransactions builders.
WalletTransactions *WalletTransactionsClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Wallet = NewWalletClient(c.config)
c.WalletTransactions = NewWalletTransactionsClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("models: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Wallet: NewWalletClient(cfg),
WalletTransactions: NewWalletTransactionsClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Wallet: NewWalletClient(cfg),
WalletTransactions: NewWalletTransactionsClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Wallet.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Wallet.Use(hooks...)
c.WalletTransactions.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Wallet.Intercept(interceptors...)
c.WalletTransactions.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *WalletMutation:
return c.Wallet.mutate(ctx, m)
case *WalletTransactionsMutation:
return c.WalletTransactions.mutate(ctx, m)
default:
return nil, fmt.Errorf("models: unknown mutation type %T", m)
}
}
// WalletClient is a client for the Wallet schema.
type WalletClient struct {
config
}
// NewWalletClient returns a client for the Wallet from the given config.
func NewWalletClient(c config) *WalletClient {
return &WalletClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `wallet.Hooks(f(g(h())))`.
func (c *WalletClient) Use(hooks ...Hook) {
c.hooks.Wallet = append(c.hooks.Wallet, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `wallet.Intercept(f(g(h())))`.
func (c *WalletClient) Intercept(interceptors ...Interceptor) {
c.inters.Wallet = append(c.inters.Wallet, interceptors...)
}
// Create returns a builder for creating a Wallet entity.
func (c *WalletClient) Create() *WalletCreate {
mutation := newWalletMutation(c.config, OpCreate)
return &WalletCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Wallet entities.
func (c *WalletClient) CreateBulk(builders ...*WalletCreate) *WalletCreateBulk {
return &WalletCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *WalletClient) MapCreateBulk(slice any, setFunc func(*WalletCreate, int)) *WalletCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &WalletCreateBulk{err: fmt.Errorf("calling to WalletClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*WalletCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &WalletCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Wallet.
func (c *WalletClient) Update() *WalletUpdate {
mutation := newWalletMutation(c.config, OpUpdate)
return &WalletUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *WalletClient) UpdateOne(_m *Wallet) *WalletUpdateOne {
mutation := newWalletMutation(c.config, OpUpdateOne, withWallet(_m))
return &WalletUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *WalletClient) UpdateOneID(id int) *WalletUpdateOne {
mutation := newWalletMutation(c.config, OpUpdateOne, withWalletID(id))
return &WalletUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Wallet.
func (c *WalletClient) Delete() *WalletDelete {
mutation := newWalletMutation(c.config, OpDelete)
return &WalletDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *WalletClient) DeleteOne(_m *Wallet) *WalletDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *WalletClient) DeleteOneID(id int) *WalletDeleteOne {
builder := c.Delete().Where(wallet.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &WalletDeleteOne{builder}
}
// Query returns a query builder for Wallet.
func (c *WalletClient) Query() *WalletQuery {
return &WalletQuery{
config: c.config,
ctx: &QueryContext{Type: TypeWallet},
inters: c.Interceptors(),
}
}
// Get returns a Wallet entity by its id.
func (c *WalletClient) Get(ctx context.Context, id int) (*Wallet, error) {
return c.Query().Where(wallet.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *WalletClient) GetX(ctx context.Context, id int) *Wallet {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *WalletClient) Hooks() []Hook {
return c.hooks.Wallet
}
// Interceptors returns the client interceptors.
func (c *WalletClient) Interceptors() []Interceptor {
return c.inters.Wallet
}
func (c *WalletClient) mutate(ctx context.Context, m *WalletMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&WalletCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&WalletUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&WalletUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&WalletDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("models: unknown Wallet mutation op: %q", m.Op())
}
}
// WalletTransactionsClient is a client for the WalletTransactions schema.
type WalletTransactionsClient struct {
config
}
// NewWalletTransactionsClient returns a client for the WalletTransactions from the given config.
func NewWalletTransactionsClient(c config) *WalletTransactionsClient {
return &WalletTransactionsClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `wallettransactions.Hooks(f(g(h())))`.
func (c *WalletTransactionsClient) Use(hooks ...Hook) {
c.hooks.WalletTransactions = append(c.hooks.WalletTransactions, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `wallettransactions.Intercept(f(g(h())))`.
func (c *WalletTransactionsClient) Intercept(interceptors ...Interceptor) {
c.inters.WalletTransactions = append(c.inters.WalletTransactions, interceptors...)
}
// Create returns a builder for creating a WalletTransactions entity.
func (c *WalletTransactionsClient) Create() *WalletTransactionsCreate {
mutation := newWalletTransactionsMutation(c.config, OpCreate)
return &WalletTransactionsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of WalletTransactions entities.
func (c *WalletTransactionsClient) CreateBulk(builders ...*WalletTransactionsCreate) *WalletTransactionsCreateBulk {
return &WalletTransactionsCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *WalletTransactionsClient) MapCreateBulk(slice any, setFunc func(*WalletTransactionsCreate, int)) *WalletTransactionsCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &WalletTransactionsCreateBulk{err: fmt.Errorf("calling to WalletTransactionsClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*WalletTransactionsCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &WalletTransactionsCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for WalletTransactions.
func (c *WalletTransactionsClient) Update() *WalletTransactionsUpdate {
mutation := newWalletTransactionsMutation(c.config, OpUpdate)
return &WalletTransactionsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *WalletTransactionsClient) UpdateOne(_m *WalletTransactions) *WalletTransactionsUpdateOne {
mutation := newWalletTransactionsMutation(c.config, OpUpdateOne, withWalletTransactions(_m))
return &WalletTransactionsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *WalletTransactionsClient) UpdateOneID(id string) *WalletTransactionsUpdateOne {
mutation := newWalletTransactionsMutation(c.config, OpUpdateOne, withWalletTransactionsID(id))
return &WalletTransactionsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for WalletTransactions.
func (c *WalletTransactionsClient) Delete() *WalletTransactionsDelete {
mutation := newWalletTransactionsMutation(c.config, OpDelete)
return &WalletTransactionsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *WalletTransactionsClient) DeleteOne(_m *WalletTransactions) *WalletTransactionsDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *WalletTransactionsClient) DeleteOneID(id string) *WalletTransactionsDeleteOne {
builder := c.Delete().Where(wallettransactions.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &WalletTransactionsDeleteOne{builder}
}
// Query returns a query builder for WalletTransactions.
func (c *WalletTransactionsClient) Query() *WalletTransactionsQuery {
return &WalletTransactionsQuery{
config: c.config,
ctx: &QueryContext{Type: TypeWalletTransactions},
inters: c.Interceptors(),
}
}
// Get returns a WalletTransactions entity by its id.
func (c *WalletTransactionsClient) Get(ctx context.Context, id string) (*WalletTransactions, error) {
return c.Query().Where(wallettransactions.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *WalletTransactionsClient) GetX(ctx context.Context, id string) *WalletTransactions {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *WalletTransactionsClient) Hooks() []Hook {
return c.hooks.WalletTransactions
}
// Interceptors returns the client interceptors.
func (c *WalletTransactionsClient) Interceptors() []Interceptor {
return c.inters.WalletTransactions
}
func (c *WalletTransactionsClient) mutate(ctx context.Context, m *WalletTransactionsMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&WalletTransactionsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&WalletTransactionsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&WalletTransactionsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&WalletTransactionsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("models: unknown WalletTransactions mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Wallet, WalletTransactions []ent.Hook
}
inters struct {
Wallet, WalletTransactions []ent.Interceptor
}
)
+610
View File
@@ -0,0 +1,610 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
wallet.Table: wallet.ValidColumn,
wallettransactions.Table: wallettransactions.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "models: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "models: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "models: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "models: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)
@@ -0,0 +1,85 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"juwan-backend/app/wallet/rpc/internal/models"
// required by schema hooks.
_ "juwan-backend/app/wallet/rpc/internal/models/runtime"
"juwan-backend/app/wallet/rpc/internal/models/migrate"
"entgo.io/ent/dialect/sql/schema"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []models.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...models.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls models.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client {
o := newOptions(opts)
c, err := models.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls models.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *models.Client {
o := newOptions(opts)
c := models.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *models.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}
+210
View File
@@ -0,0 +1,210 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models"
)
// The WalletFunc type is an adapter to allow the use of ordinary
// function as Wallet mutator.
type WalletFunc func(context.Context, *models.WalletMutation) (models.Value, error)
// Mutate calls f(ctx, m).
func (f WalletFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) {
if mv, ok := m.(*models.WalletMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *models.WalletMutation", m)
}
// The WalletTransactionsFunc type is an adapter to allow the use of ordinary
// function as WalletTransactions mutator.
type WalletTransactionsFunc func(context.Context, *models.WalletTransactionsMutation) (models.Value, error)
// Mutate calls f(ctx, m).
func (f WalletTransactionsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) {
if mv, ok := m.(*models.WalletTransactionsMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *models.WalletTransactionsMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, models.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m models.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m models.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m models.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op models.Op) Condition {
return func(_ context.Context, m models.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m models.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m models.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m models.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk models.Hook, cond Condition) models.Hook {
return func(next models.Mutator) models.Mutator {
return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, models.Delete|models.Create)
func On(hk models.Hook, op models.Op) models.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, models.Update|models.UpdateOne)
func Unless(hk models.Hook, op models.Op) models.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) models.Hook {
return func(models.Mutator) models.Mutator {
return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []models.Hook {
// return []models.Hook{
// Reject(models.Delete|models.Update),
// }
// }
func Reject(op models.Op) models.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []models.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...models.Hook) Chain {
return Chain{append([]models.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() models.Hook {
return func(mutator models.Mutator) models.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...models.Hook) Chain {
newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}
@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}
@@ -0,0 +1,52 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// WalletsColumns holds the columns for the "wallets" table.
WalletsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "user_id", Type: field.TypeInt64, Unique: true},
{Name: "balance", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "decimal(12,2)"}},
{Name: "frozen_balance", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "decimal(12,2)"}},
{Name: "version", Type: field.TypeInt, Default: 1},
{Name: "updated_at", Type: field.TypeTime},
}
// WalletsTable holds the schema information for the "wallets" table.
WalletsTable = &schema.Table{
Name: "wallets",
Columns: WalletsColumns,
PrimaryKey: []*schema.Column{WalletsColumns[0]},
}
// WalletTransactionsColumns holds the columns for the "wallet_transactions" table.
WalletTransactionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true},
{Name: "user_id", Type: field.TypeInt64, Unique: true},
{Name: "type", Type: field.TypeString},
{Name: "amount", Type: field.TypeOther, Unique: true, SchemaType: map[string]string{"postgres": "decimal(12,2"}},
{Name: "balance_after", Type: field.TypeOther, Unique: true, SchemaType: map[string]string{"postgres": "decimal(12,2)"}},
{Name: "description", Type: field.TypeJSON},
{Name: "order_id", Type: field.TypeInt64, Unique: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "search_text", Type: field.TypeString},
}
// WalletTransactionsTable holds the schema information for the "wallet_transactions" table.
WalletTransactionsTable = &schema.Table{
Name: "wallet_transactions",
Columns: WalletTransactionsColumns,
PrimaryKey: []*schema.Column{WalletTransactionsColumns[0]},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
WalletsTable,
WalletTransactionsTable,
}
)
func init() {
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,13 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Wallet is the predicate function for wallet builders.
type Wallet func(*sql.Selector)
// WalletTransactions is the predicate function for wallettransactions builders.
type WalletTransactions func(*sql.Selector)
+30
View File
@@ -0,0 +1,30 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"juwan-backend/app/wallet/rpc/internal/models/schema"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"github.com/shopspring/decimal"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
walletFields := schema.Wallet{}.Fields()
_ = walletFields
// walletDescBalance is the schema descriptor for balance field.
walletDescBalance := walletFields[1].Descriptor()
// wallet.DefaultBalance holds the default value on creation for the balance field.
wallet.DefaultBalance = walletDescBalance.Default.(decimal.Decimal)
// walletDescFrozenBalance is the schema descriptor for frozen_balance field.
walletDescFrozenBalance := walletFields[2].Descriptor()
// wallet.DefaultFrozenBalance holds the default value on creation for the frozen_balance field.
wallet.DefaultFrozenBalance = walletDescFrozenBalance.Default.(decimal.Decimal)
// walletDescVersion is the schema descriptor for version field.
walletDescVersion := walletFields[3].Descriptor()
// wallet.DefaultVersion holds the default value on creation for the version field.
wallet.DefaultVersion = walletDescVersion.Default.(int)
}
@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in juwan-backend/app/wallet/rpc/internal/models/runtime.go
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)
@@ -0,0 +1,39 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/schema/field"
"github.com/shopspring/decimal"
)
var defalutBalance = decimal.RequireFromString("0.00")
// Wallet holds the schema definition for the Wallet entity.
type Wallet struct {
ent.Schema
}
// Fields of the Wallet.
func (Wallet) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id").Immutable().Unique(),
field.Other("balance", decimal.Decimal{}).
Default(defalutBalance).
SchemaType(map[string]string{
dialect.Postgres: "decimal(12,2)",
}),
field.Other("frozen_balance", decimal.Decimal{}).
Default(defalutBalance).
SchemaType(map[string]string{
dialect.Postgres: "decimal(12,2)",
}),
field.Int("version").Default(1),
field.Time("updated_at"),
}
}
// Edges of the Wallet.
func (Wallet) Edges() []ent.Edge {
return nil
}
@@ -0,0 +1,39 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/schema/field"
"github.com/shopspring/decimal"
)
// WalletTransactions holds the schema definition for the WalletTransactions entity.
type WalletTransactions struct {
ent.Schema
}
// Fields of the WalletTransactions.
func (WalletTransactions) Fields() []ent.Field {
return []ent.Field{
field.String("id").Immutable().Unique(),
field.Int64("user_id").Immutable().Unique(),
field.String("type"),
field.Other("amount", decimal.Decimal{}).
SchemaType(map[string]string{
dialect.Postgres: "decimal(12,2",
}).Unique().Immutable(),
field.Other("balance_after", decimal.Decimal{}).
SchemaType(map[string]string{
dialect.Postgres: "decimal(12,2)",
}).Unique().Immutable(),
field.Strings("description"),
field.Int64("order_id").Immutable().Unique(),
field.Time("created_at"),
field.String("search_text"),
}
}
// Edges of the WalletTransactions.
func (WalletTransactions) Edges() []ent.Edge {
return nil
}
+213
View File
@@ -0,0 +1,213 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Wallet is the client for interacting with the Wallet builders.
Wallet *WalletClient
// WalletTransactions is the client for interacting with the WalletTransactions builders.
WalletTransactions *WalletTransactionsClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Wallet = NewWalletClient(tx.config)
tx.WalletTransactions = NewWalletTransactionsClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Wallet.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)
+151
View File
@@ -0,0 +1,151 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/shopspring/decimal"
)
// Wallet is the model entity for the Wallet schema.
type Wallet struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int64 `json:"user_id,omitempty"`
// Balance holds the value of the "balance" field.
Balance decimal.Decimal `json:"balance,omitempty"`
// FrozenBalance holds the value of the "frozen_balance" field.
FrozenBalance decimal.Decimal `json:"frozen_balance,omitempty"`
// Version holds the value of the "version" field.
Version int `json:"version,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Wallet) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case wallet.FieldBalance, wallet.FieldFrozenBalance:
values[i] = new(decimal.Decimal)
case wallet.FieldID, wallet.FieldUserID, wallet.FieldVersion:
values[i] = new(sql.NullInt64)
case wallet.FieldUpdatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Wallet fields.
func (_m *Wallet) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case wallet.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case wallet.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = value.Int64
}
case wallet.FieldBalance:
if value, ok := values[i].(*decimal.Decimal); !ok {
return fmt.Errorf("unexpected type %T for field balance", values[i])
} else if value != nil {
_m.Balance = *value
}
case wallet.FieldFrozenBalance:
if value, ok := values[i].(*decimal.Decimal); !ok {
return fmt.Errorf("unexpected type %T for field frozen_balance", values[i])
} else if value != nil {
_m.FrozenBalance = *value
}
case wallet.FieldVersion:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field version", values[i])
} else if value.Valid {
_m.Version = int(value.Int64)
}
case wallet.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Wallet.
// This includes values selected through modifiers, order, etc.
func (_m *Wallet) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Wallet.
// Note that you need to call Wallet.Unwrap() before calling this method if this Wallet
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Wallet) Update() *WalletUpdateOne {
return NewWalletClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Wallet entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Wallet) Unwrap() *Wallet {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("models: Wallet is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Wallet) String() string {
var builder strings.Builder
builder.WriteString("Wallet(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("balance=")
builder.WriteString(fmt.Sprintf("%v", _m.Balance))
builder.WriteString(", ")
builder.WriteString("frozen_balance=")
builder.WriteString(fmt.Sprintf("%v", _m.FrozenBalance))
builder.WriteString(", ")
builder.WriteString("version=")
builder.WriteString(fmt.Sprintf("%v", _m.Version))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Wallets is a parsable slice of Wallet.
type Wallets []*Wallet
@@ -0,0 +1,89 @@
// Code generated by ent, DO NOT EDIT.
package wallet
import (
"entgo.io/ent/dialect/sql"
"github.com/shopspring/decimal"
)
const (
// Label holds the string label denoting the wallet type in the database.
Label = "wallet"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldBalance holds the string denoting the balance field in the database.
FieldBalance = "balance"
// FieldFrozenBalance holds the string denoting the frozen_balance field in the database.
FieldFrozenBalance = "frozen_balance"
// FieldVersion holds the string denoting the version field in the database.
FieldVersion = "version"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// Table holds the table name of the wallet in the database.
Table = "wallets"
)
// Columns holds all SQL columns for wallet fields.
var Columns = []string{
FieldID,
FieldUserID,
FieldBalance,
FieldFrozenBalance,
FieldVersion,
FieldUpdatedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultBalance holds the default value on creation for the "balance" field.
DefaultBalance decimal.Decimal
// DefaultFrozenBalance holds the default value on creation for the "frozen_balance" field.
DefaultFrozenBalance decimal.Decimal
// DefaultVersion holds the default value on creation for the "version" field.
DefaultVersion int
)
// OrderOption defines the ordering options for the Wallet queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByBalance orders the results by the balance field.
func ByBalance(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBalance, opts...).ToFunc()
}
// ByFrozenBalance orders the results by the frozen_balance field.
func ByFrozenBalance(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFrozenBalance, opts...).ToFunc()
}
// ByVersion orders the results by the version field.
func ByVersion(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVersion, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
@@ -0,0 +1,296 @@
// Code generated by ent, DO NOT EDIT.
package wallet
import (
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"time"
"entgo.io/ent/dialect/sql"
"github.com/shopspring/decimal"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Wallet {
return predicate.Wallet(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Wallet {
return predicate.Wallet(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Wallet {
return predicate.Wallet(sql.FieldLTE(FieldID, id))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldUserID, v))
}
// Balance applies equality check predicate on the "balance" field. It's identical to BalanceEQ.
func Balance(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldBalance, v))
}
// FrozenBalance applies equality check predicate on the "frozen_balance" field. It's identical to FrozenBalanceEQ.
func FrozenBalance(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldFrozenBalance, v))
}
// Version applies equality check predicate on the "version" field. It's identical to VersionEQ.
func Version(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldVersion, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldUpdatedAt, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int64) predicate.Wallet {
return predicate.Wallet(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int64) predicate.Wallet {
return predicate.Wallet(sql.FieldNotIn(FieldUserID, vs...))
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldGT(FieldUserID, v))
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldGTE(FieldUserID, v))
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldLT(FieldUserID, v))
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v int64) predicate.Wallet {
return predicate.Wallet(sql.FieldLTE(FieldUserID, v))
}
// BalanceEQ applies the EQ predicate on the "balance" field.
func BalanceEQ(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldBalance, v))
}
// BalanceNEQ applies the NEQ predicate on the "balance" field.
func BalanceNEQ(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldNEQ(FieldBalance, v))
}
// BalanceIn applies the In predicate on the "balance" field.
func BalanceIn(vs ...decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldIn(FieldBalance, vs...))
}
// BalanceNotIn applies the NotIn predicate on the "balance" field.
func BalanceNotIn(vs ...decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldNotIn(FieldBalance, vs...))
}
// BalanceGT applies the GT predicate on the "balance" field.
func BalanceGT(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldGT(FieldBalance, v))
}
// BalanceGTE applies the GTE predicate on the "balance" field.
func BalanceGTE(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldGTE(FieldBalance, v))
}
// BalanceLT applies the LT predicate on the "balance" field.
func BalanceLT(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldLT(FieldBalance, v))
}
// BalanceLTE applies the LTE predicate on the "balance" field.
func BalanceLTE(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldLTE(FieldBalance, v))
}
// FrozenBalanceEQ applies the EQ predicate on the "frozen_balance" field.
func FrozenBalanceEQ(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldFrozenBalance, v))
}
// FrozenBalanceNEQ applies the NEQ predicate on the "frozen_balance" field.
func FrozenBalanceNEQ(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldNEQ(FieldFrozenBalance, v))
}
// FrozenBalanceIn applies the In predicate on the "frozen_balance" field.
func FrozenBalanceIn(vs ...decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldIn(FieldFrozenBalance, vs...))
}
// FrozenBalanceNotIn applies the NotIn predicate on the "frozen_balance" field.
func FrozenBalanceNotIn(vs ...decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldNotIn(FieldFrozenBalance, vs...))
}
// FrozenBalanceGT applies the GT predicate on the "frozen_balance" field.
func FrozenBalanceGT(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldGT(FieldFrozenBalance, v))
}
// FrozenBalanceGTE applies the GTE predicate on the "frozen_balance" field.
func FrozenBalanceGTE(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldGTE(FieldFrozenBalance, v))
}
// FrozenBalanceLT applies the LT predicate on the "frozen_balance" field.
func FrozenBalanceLT(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldLT(FieldFrozenBalance, v))
}
// FrozenBalanceLTE applies the LTE predicate on the "frozen_balance" field.
func FrozenBalanceLTE(v decimal.Decimal) predicate.Wallet {
return predicate.Wallet(sql.FieldLTE(FieldFrozenBalance, v))
}
// VersionEQ applies the EQ predicate on the "version" field.
func VersionEQ(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldVersion, v))
}
// VersionNEQ applies the NEQ predicate on the "version" field.
func VersionNEQ(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldNEQ(FieldVersion, v))
}
// VersionIn applies the In predicate on the "version" field.
func VersionIn(vs ...int) predicate.Wallet {
return predicate.Wallet(sql.FieldIn(FieldVersion, vs...))
}
// VersionNotIn applies the NotIn predicate on the "version" field.
func VersionNotIn(vs ...int) predicate.Wallet {
return predicate.Wallet(sql.FieldNotIn(FieldVersion, vs...))
}
// VersionGT applies the GT predicate on the "version" field.
func VersionGT(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldGT(FieldVersion, v))
}
// VersionGTE applies the GTE predicate on the "version" field.
func VersionGTE(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldGTE(FieldVersion, v))
}
// VersionLT applies the LT predicate on the "version" field.
func VersionLT(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldLT(FieldVersion, v))
}
// VersionLTE applies the LTE predicate on the "version" field.
func VersionLTE(v int) predicate.Wallet {
return predicate.Wallet(sql.FieldLTE(FieldVersion, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Wallet {
return predicate.Wallet(sql.FieldLTE(FieldUpdatedAt, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Wallet) predicate.Wallet {
return predicate.Wallet(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Wallet) predicate.Wallet {
return predicate.Wallet(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Wallet) predicate.Wallet {
return predicate.Wallet(sql.NotPredicates(p))
}
@@ -0,0 +1,279 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/shopspring/decimal"
)
// WalletCreate is the builder for creating a Wallet entity.
type WalletCreate struct {
config
mutation *WalletMutation
hooks []Hook
}
// SetUserID sets the "user_id" field.
func (_c *WalletCreate) SetUserID(v int64) *WalletCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetBalance sets the "balance" field.
func (_c *WalletCreate) SetBalance(v decimal.Decimal) *WalletCreate {
_c.mutation.SetBalance(v)
return _c
}
// SetNillableBalance sets the "balance" field if the given value is not nil.
func (_c *WalletCreate) SetNillableBalance(v *decimal.Decimal) *WalletCreate {
if v != nil {
_c.SetBalance(*v)
}
return _c
}
// SetFrozenBalance sets the "frozen_balance" field.
func (_c *WalletCreate) SetFrozenBalance(v decimal.Decimal) *WalletCreate {
_c.mutation.SetFrozenBalance(v)
return _c
}
// SetNillableFrozenBalance sets the "frozen_balance" field if the given value is not nil.
func (_c *WalletCreate) SetNillableFrozenBalance(v *decimal.Decimal) *WalletCreate {
if v != nil {
_c.SetFrozenBalance(*v)
}
return _c
}
// SetVersion sets the "version" field.
func (_c *WalletCreate) SetVersion(v int) *WalletCreate {
_c.mutation.SetVersion(v)
return _c
}
// SetNillableVersion sets the "version" field if the given value is not nil.
func (_c *WalletCreate) SetNillableVersion(v *int) *WalletCreate {
if v != nil {
_c.SetVersion(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *WalletCreate) SetUpdatedAt(v time.Time) *WalletCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// Mutation returns the WalletMutation object of the builder.
func (_c *WalletCreate) Mutation() *WalletMutation {
return _c.mutation
}
// Save creates the Wallet in the database.
func (_c *WalletCreate) Save(ctx context.Context) (*Wallet, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *WalletCreate) SaveX(ctx context.Context) *Wallet {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *WalletCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *WalletCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *WalletCreate) defaults() {
if _, ok := _c.mutation.Balance(); !ok {
v := wallet.DefaultBalance
_c.mutation.SetBalance(v)
}
if _, ok := _c.mutation.FrozenBalance(); !ok {
v := wallet.DefaultFrozenBalance
_c.mutation.SetFrozenBalance(v)
}
if _, ok := _c.mutation.Version(); !ok {
v := wallet.DefaultVersion
_c.mutation.SetVersion(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *WalletCreate) check() error {
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "Wallet.user_id"`)}
}
if _, ok := _c.mutation.Balance(); !ok {
return &ValidationError{Name: "balance", err: errors.New(`models: missing required field "Wallet.balance"`)}
}
if _, ok := _c.mutation.FrozenBalance(); !ok {
return &ValidationError{Name: "frozen_balance", err: errors.New(`models: missing required field "Wallet.frozen_balance"`)}
}
if _, ok := _c.mutation.Version(); !ok {
return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Wallet.version"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Wallet.updated_at"`)}
}
return nil
}
func (_c *WalletCreate) sqlSave(ctx context.Context) (*Wallet, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *WalletCreate) createSpec() (*Wallet, *sqlgraph.CreateSpec) {
var (
_node = &Wallet{config: _c.config}
_spec = sqlgraph.NewCreateSpec(wallet.Table, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.UserID(); ok {
_spec.SetField(wallet.FieldUserID, field.TypeInt64, value)
_node.UserID = value
}
if value, ok := _c.mutation.Balance(); ok {
_spec.SetField(wallet.FieldBalance, field.TypeOther, value)
_node.Balance = value
}
if value, ok := _c.mutation.FrozenBalance(); ok {
_spec.SetField(wallet.FieldFrozenBalance, field.TypeOther, value)
_node.FrozenBalance = value
}
if value, ok := _c.mutation.Version(); ok {
_spec.SetField(wallet.FieldVersion, field.TypeInt, value)
_node.Version = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(wallet.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
return _node, _spec
}
// WalletCreateBulk is the builder for creating many Wallet entities in bulk.
type WalletCreateBulk struct {
config
err error
builders []*WalletCreate
}
// Save creates the Wallet entities in the database.
func (_c *WalletCreateBulk) Save(ctx context.Context) ([]*Wallet, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Wallet, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*WalletMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *WalletCreateBulk) SaveX(ctx context.Context) []*Wallet {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *WalletCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *WalletCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// WalletDelete is the builder for deleting a Wallet entity.
type WalletDelete struct {
config
hooks []Hook
mutation *WalletMutation
}
// Where appends a list predicates to the WalletDelete builder.
func (_d *WalletDelete) Where(ps ...predicate.Wallet) *WalletDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *WalletDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *WalletDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *WalletDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(wallet.Table, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// WalletDeleteOne is the builder for deleting a single Wallet entity.
type WalletDeleteOne struct {
_d *WalletDelete
}
// Where appends a list predicates to the WalletDelete builder.
func (_d *WalletDeleteOne) Where(ps ...predicate.Wallet) *WalletDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *WalletDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{wallet.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *WalletDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// WalletQuery is the builder for querying Wallet entities.
type WalletQuery struct {
config
ctx *QueryContext
order []wallet.OrderOption
inters []Interceptor
predicates []predicate.Wallet
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the WalletQuery builder.
func (_q *WalletQuery) Where(ps ...predicate.Wallet) *WalletQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *WalletQuery) Limit(limit int) *WalletQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *WalletQuery) Offset(offset int) *WalletQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *WalletQuery) Unique(unique bool) *WalletQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *WalletQuery) Order(o ...wallet.OrderOption) *WalletQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Wallet entity from the query.
// Returns a *NotFoundError when no Wallet was found.
func (_q *WalletQuery) First(ctx context.Context) (*Wallet, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{wallet.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *WalletQuery) FirstX(ctx context.Context) *Wallet {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Wallet ID from the query.
// Returns a *NotFoundError when no Wallet ID was found.
func (_q *WalletQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{wallet.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *WalletQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Wallet entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Wallet entity is found.
// Returns a *NotFoundError when no Wallet entities are found.
func (_q *WalletQuery) Only(ctx context.Context) (*Wallet, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{wallet.Label}
default:
return nil, &NotSingularError{wallet.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *WalletQuery) OnlyX(ctx context.Context) *Wallet {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Wallet ID in the query.
// Returns a *NotSingularError when more than one Wallet ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *WalletQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{wallet.Label}
default:
err = &NotSingularError{wallet.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *WalletQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Wallets.
func (_q *WalletQuery) All(ctx context.Context) ([]*Wallet, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Wallet, *WalletQuery]()
return withInterceptors[[]*Wallet](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *WalletQuery) AllX(ctx context.Context) []*Wallet {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Wallet IDs.
func (_q *WalletQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(wallet.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *WalletQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *WalletQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*WalletQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *WalletQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *WalletQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("models: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *WalletQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the WalletQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *WalletQuery) Clone() *WalletQuery {
if _q == nil {
return nil
}
return &WalletQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]wallet.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Wallet{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// UserID int64 `json:"user_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Wallet.Query().
// GroupBy(wallet.FieldUserID).
// Aggregate(models.Count()).
// Scan(ctx, &v)
func (_q *WalletQuery) GroupBy(field string, fields ...string) *WalletGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &WalletGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = wallet.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// UserID int64 `json:"user_id,omitempty"`
// }
//
// client.Wallet.Query().
// Select(wallet.FieldUserID).
// Scan(ctx, &v)
func (_q *WalletQuery) Select(fields ...string) *WalletSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &WalletSelect{WalletQuery: _q}
sbuild.label = wallet.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a WalletSelect configured with the given aggregations.
func (_q *WalletQuery) Aggregate(fns ...AggregateFunc) *WalletSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *WalletQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !wallet.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *WalletQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Wallet, error) {
var (
nodes = []*Wallet{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Wallet).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Wallet{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *WalletQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *WalletQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(wallet.Table, wallet.Columns, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, wallet.FieldID)
for i := range fields {
if fields[i] != wallet.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *WalletQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(wallet.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = wallet.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// WalletGroupBy is the group-by builder for Wallet entities.
type WalletGroupBy struct {
selector
build *WalletQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *WalletGroupBy) Aggregate(fns ...AggregateFunc) *WalletGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *WalletGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*WalletQuery, *WalletGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *WalletGroupBy) sqlScan(ctx context.Context, root *WalletQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// WalletSelect is the builder for selecting fields of Wallet entities.
type WalletSelect struct {
*WalletQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *WalletSelect) Aggregate(fns ...AggregateFunc) *WalletSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *WalletSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*WalletQuery, *WalletSelect](ctx, _s.WalletQuery, _s, _s.inters, v)
}
func (_s *WalletSelect) sqlScan(ctx context.Context, root *WalletQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
@@ -0,0 +1,333 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallet"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/shopspring/decimal"
)
// WalletUpdate is the builder for updating Wallet entities.
type WalletUpdate struct {
config
hooks []Hook
mutation *WalletMutation
}
// Where appends a list predicates to the WalletUpdate builder.
func (_u *WalletUpdate) Where(ps ...predicate.Wallet) *WalletUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetBalance sets the "balance" field.
func (_u *WalletUpdate) SetBalance(v decimal.Decimal) *WalletUpdate {
_u.mutation.SetBalance(v)
return _u
}
// SetNillableBalance sets the "balance" field if the given value is not nil.
func (_u *WalletUpdate) SetNillableBalance(v *decimal.Decimal) *WalletUpdate {
if v != nil {
_u.SetBalance(*v)
}
return _u
}
// SetFrozenBalance sets the "frozen_balance" field.
func (_u *WalletUpdate) SetFrozenBalance(v decimal.Decimal) *WalletUpdate {
_u.mutation.SetFrozenBalance(v)
return _u
}
// SetNillableFrozenBalance sets the "frozen_balance" field if the given value is not nil.
func (_u *WalletUpdate) SetNillableFrozenBalance(v *decimal.Decimal) *WalletUpdate {
if v != nil {
_u.SetFrozenBalance(*v)
}
return _u
}
// SetVersion sets the "version" field.
func (_u *WalletUpdate) SetVersion(v int) *WalletUpdate {
_u.mutation.ResetVersion()
_u.mutation.SetVersion(v)
return _u
}
// SetNillableVersion sets the "version" field if the given value is not nil.
func (_u *WalletUpdate) SetNillableVersion(v *int) *WalletUpdate {
if v != nil {
_u.SetVersion(*v)
}
return _u
}
// AddVersion adds value to the "version" field.
func (_u *WalletUpdate) AddVersion(v int) *WalletUpdate {
_u.mutation.AddVersion(v)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *WalletUpdate) SetUpdatedAt(v time.Time) *WalletUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *WalletUpdate) SetNillableUpdatedAt(v *time.Time) *WalletUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// Mutation returns the WalletMutation object of the builder.
func (_u *WalletUpdate) Mutation() *WalletMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *WalletUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *WalletUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *WalletUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *WalletUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *WalletUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(wallet.Table, wallet.Columns, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Balance(); ok {
_spec.SetField(wallet.FieldBalance, field.TypeOther, value)
}
if value, ok := _u.mutation.FrozenBalance(); ok {
_spec.SetField(wallet.FieldFrozenBalance, field.TypeOther, value)
}
if value, ok := _u.mutation.Version(); ok {
_spec.SetField(wallet.FieldVersion, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedVersion(); ok {
_spec.AddField(wallet.FieldVersion, field.TypeInt, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(wallet.FieldUpdatedAt, field.TypeTime, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{wallet.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// WalletUpdateOne is the builder for updating a single Wallet entity.
type WalletUpdateOne struct {
config
fields []string
hooks []Hook
mutation *WalletMutation
}
// SetBalance sets the "balance" field.
func (_u *WalletUpdateOne) SetBalance(v decimal.Decimal) *WalletUpdateOne {
_u.mutation.SetBalance(v)
return _u
}
// SetNillableBalance sets the "balance" field if the given value is not nil.
func (_u *WalletUpdateOne) SetNillableBalance(v *decimal.Decimal) *WalletUpdateOne {
if v != nil {
_u.SetBalance(*v)
}
return _u
}
// SetFrozenBalance sets the "frozen_balance" field.
func (_u *WalletUpdateOne) SetFrozenBalance(v decimal.Decimal) *WalletUpdateOne {
_u.mutation.SetFrozenBalance(v)
return _u
}
// SetNillableFrozenBalance sets the "frozen_balance" field if the given value is not nil.
func (_u *WalletUpdateOne) SetNillableFrozenBalance(v *decimal.Decimal) *WalletUpdateOne {
if v != nil {
_u.SetFrozenBalance(*v)
}
return _u
}
// SetVersion sets the "version" field.
func (_u *WalletUpdateOne) SetVersion(v int) *WalletUpdateOne {
_u.mutation.ResetVersion()
_u.mutation.SetVersion(v)
return _u
}
// SetNillableVersion sets the "version" field if the given value is not nil.
func (_u *WalletUpdateOne) SetNillableVersion(v *int) *WalletUpdateOne {
if v != nil {
_u.SetVersion(*v)
}
return _u
}
// AddVersion adds value to the "version" field.
func (_u *WalletUpdateOne) AddVersion(v int) *WalletUpdateOne {
_u.mutation.AddVersion(v)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *WalletUpdateOne) SetUpdatedAt(v time.Time) *WalletUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *WalletUpdateOne) SetNillableUpdatedAt(v *time.Time) *WalletUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// Mutation returns the WalletMutation object of the builder.
func (_u *WalletUpdateOne) Mutation() *WalletMutation {
return _u.mutation
}
// Where appends a list predicates to the WalletUpdate builder.
func (_u *WalletUpdateOne) Where(ps ...predicate.Wallet) *WalletUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *WalletUpdateOne) Select(field string, fields ...string) *WalletUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Wallet entity.
func (_u *WalletUpdateOne) Save(ctx context.Context) (*Wallet, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *WalletUpdateOne) SaveX(ctx context.Context) *Wallet {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *WalletUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *WalletUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *WalletUpdateOne) sqlSave(ctx context.Context) (_node *Wallet, err error) {
_spec := sqlgraph.NewUpdateSpec(wallet.Table, wallet.Columns, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Wallet.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, wallet.FieldID)
for _, f := range fields {
if !wallet.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
if f != wallet.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Balance(); ok {
_spec.SetField(wallet.FieldBalance, field.TypeOther, value)
}
if value, ok := _u.mutation.FrozenBalance(); ok {
_spec.SetField(wallet.FieldFrozenBalance, field.TypeOther, value)
}
if value, ok := _u.mutation.Version(); ok {
_spec.SetField(wallet.FieldVersion, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedVersion(); ok {
_spec.AddField(wallet.FieldVersion, field.TypeInt, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(wallet.FieldUpdatedAt, field.TypeTime, value)
}
_node = &Wallet{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{wallet.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
@@ -0,0 +1,191 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"encoding/json"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/shopspring/decimal"
)
// WalletTransactions is the model entity for the WalletTransactions schema.
type WalletTransactions struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int64 `json:"user_id,omitempty"`
// Type holds the value of the "type" field.
Type string `json:"type,omitempty"`
// Amount holds the value of the "amount" field.
Amount decimal.Decimal `json:"amount,omitempty"`
// BalanceAfter holds the value of the "balance_after" field.
BalanceAfter decimal.Decimal `json:"balance_after,omitempty"`
// Description holds the value of the "description" field.
Description []string `json:"description,omitempty"`
// OrderID holds the value of the "order_id" field.
OrderID int64 `json:"order_id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// SearchText holds the value of the "search_text" field.
SearchText string `json:"search_text,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*WalletTransactions) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case wallettransactions.FieldDescription:
values[i] = new([]byte)
case wallettransactions.FieldAmount, wallettransactions.FieldBalanceAfter:
values[i] = new(decimal.Decimal)
case wallettransactions.FieldUserID, wallettransactions.FieldOrderID:
values[i] = new(sql.NullInt64)
case wallettransactions.FieldID, wallettransactions.FieldType, wallettransactions.FieldSearchText:
values[i] = new(sql.NullString)
case wallettransactions.FieldCreatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the WalletTransactions fields.
func (_m *WalletTransactions) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case wallettransactions.FieldID:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value.Valid {
_m.ID = value.String
}
case wallettransactions.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = value.Int64
}
case wallettransactions.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_m.Type = value.String
}
case wallettransactions.FieldAmount:
if value, ok := values[i].(*decimal.Decimal); !ok {
return fmt.Errorf("unexpected type %T for field amount", values[i])
} else if value != nil {
_m.Amount = *value
}
case wallettransactions.FieldBalanceAfter:
if value, ok := values[i].(*decimal.Decimal); !ok {
return fmt.Errorf("unexpected type %T for field balance_after", values[i])
} else if value != nil {
_m.BalanceAfter = *value
}
case wallettransactions.FieldDescription:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Description); err != nil {
return fmt.Errorf("unmarshal field description: %w", err)
}
}
case wallettransactions.FieldOrderID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field order_id", values[i])
} else if value.Valid {
_m.OrderID = value.Int64
}
case wallettransactions.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case wallettransactions.FieldSearchText:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field search_text", values[i])
} else if value.Valid {
_m.SearchText = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the WalletTransactions.
// This includes values selected through modifiers, order, etc.
func (_m *WalletTransactions) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this WalletTransactions.
// Note that you need to call WalletTransactions.Unwrap() before calling this method if this WalletTransactions
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *WalletTransactions) Update() *WalletTransactionsUpdateOne {
return NewWalletTransactionsClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the WalletTransactions entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *WalletTransactions) Unwrap() *WalletTransactions {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("models: WalletTransactions is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *WalletTransactions) String() string {
var builder strings.Builder
builder.WriteString("WalletTransactions(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(_m.Type)
builder.WriteString(", ")
builder.WriteString("amount=")
builder.WriteString(fmt.Sprintf("%v", _m.Amount))
builder.WriteString(", ")
builder.WriteString("balance_after=")
builder.WriteString(fmt.Sprintf("%v", _m.BalanceAfter))
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(fmt.Sprintf("%v", _m.Description))
builder.WriteString(", ")
builder.WriteString("order_id=")
builder.WriteString(fmt.Sprintf("%v", _m.OrderID))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("search_text=")
builder.WriteString(_m.SearchText)
builder.WriteByte(')')
return builder.String()
}
// WalletTransactionsSlice is a parsable slice of WalletTransactions.
type WalletTransactionsSlice []*WalletTransactions
@@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package wallettransactions
import (
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the wallettransactions type in the database.
Label = "wallet_transactions"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldAmount holds the string denoting the amount field in the database.
FieldAmount = "amount"
// FieldBalanceAfter holds the string denoting the balance_after field in the database.
FieldBalanceAfter = "balance_after"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldOrderID holds the string denoting the order_id field in the database.
FieldOrderID = "order_id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldSearchText holds the string denoting the search_text field in the database.
FieldSearchText = "search_text"
// Table holds the table name of the wallettransactions in the database.
Table = "wallet_transactions"
)
// Columns holds all SQL columns for wallettransactions fields.
var Columns = []string{
FieldID,
FieldUserID,
FieldType,
FieldAmount,
FieldBalanceAfter,
FieldDescription,
FieldOrderID,
FieldCreatedAt,
FieldSearchText,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// OrderOption defines the ordering options for the WalletTransactions queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByAmount orders the results by the amount field.
func ByAmount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAmount, opts...).ToFunc()
}
// ByBalanceAfter orders the results by the balance_after field.
func ByBalanceAfter(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBalanceAfter, opts...).ToFunc()
}
// ByOrderID orders the results by the order_id field.
func ByOrderID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOrderID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// BySearchText orders the results by the search_text field.
func BySearchText(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSearchText, opts...).ToFunc()
}
@@ -0,0 +1,446 @@
// Code generated by ent, DO NOT EDIT.
package wallettransactions
import (
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"time"
"entgo.io/ent/dialect/sql"
"github.com/shopspring/decimal"
)
// ID filters vertices based on their ID field.
func ID(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldID, id))
}
// IDEqualFold applies the EqualFold predicate on the ID field.
func IDEqualFold(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEqualFold(FieldID, id))
}
// IDContainsFold applies the ContainsFold predicate on the ID field.
func IDContainsFold(id string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldContainsFold(FieldID, id))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldUserID, v))
}
// Type applies equality check predicate on the "type" field. It's identical to TypeEQ.
func Type(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldType, v))
}
// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ.
func Amount(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldAmount, v))
}
// BalanceAfter applies equality check predicate on the "balance_after" field. It's identical to BalanceAfterEQ.
func BalanceAfter(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldBalanceAfter, v))
}
// OrderID applies equality check predicate on the "order_id" field. It's identical to OrderIDEQ.
func OrderID(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldOrderID, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldCreatedAt, v))
}
// SearchText applies equality check predicate on the "search_text" field. It's identical to SearchTextEQ.
func SearchText(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldSearchText, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldUserID, vs...))
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldUserID, v))
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldUserID, v))
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldUserID, v))
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldUserID, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldType, vs...))
}
// TypeGT applies the GT predicate on the "type" field.
func TypeGT(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldType, v))
}
// TypeGTE applies the GTE predicate on the "type" field.
func TypeGTE(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldType, v))
}
// TypeLT applies the LT predicate on the "type" field.
func TypeLT(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldType, v))
}
// TypeLTE applies the LTE predicate on the "type" field.
func TypeLTE(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldType, v))
}
// TypeContains applies the Contains predicate on the "type" field.
func TypeContains(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldContains(FieldType, v))
}
// TypeHasPrefix applies the HasPrefix predicate on the "type" field.
func TypeHasPrefix(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldHasPrefix(FieldType, v))
}
// TypeHasSuffix applies the HasSuffix predicate on the "type" field.
func TypeHasSuffix(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldHasSuffix(FieldType, v))
}
// TypeEqualFold applies the EqualFold predicate on the "type" field.
func TypeEqualFold(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEqualFold(FieldType, v))
}
// TypeContainsFold applies the ContainsFold predicate on the "type" field.
func TypeContainsFold(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldContainsFold(FieldType, v))
}
// AmountEQ applies the EQ predicate on the "amount" field.
func AmountEQ(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldAmount, v))
}
// AmountNEQ applies the NEQ predicate on the "amount" field.
func AmountNEQ(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldAmount, v))
}
// AmountIn applies the In predicate on the "amount" field.
func AmountIn(vs ...decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldAmount, vs...))
}
// AmountNotIn applies the NotIn predicate on the "amount" field.
func AmountNotIn(vs ...decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldAmount, vs...))
}
// AmountGT applies the GT predicate on the "amount" field.
func AmountGT(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldAmount, v))
}
// AmountGTE applies the GTE predicate on the "amount" field.
func AmountGTE(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldAmount, v))
}
// AmountLT applies the LT predicate on the "amount" field.
func AmountLT(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldAmount, v))
}
// AmountLTE applies the LTE predicate on the "amount" field.
func AmountLTE(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldAmount, v))
}
// BalanceAfterEQ applies the EQ predicate on the "balance_after" field.
func BalanceAfterEQ(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldBalanceAfter, v))
}
// BalanceAfterNEQ applies the NEQ predicate on the "balance_after" field.
func BalanceAfterNEQ(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldBalanceAfter, v))
}
// BalanceAfterIn applies the In predicate on the "balance_after" field.
func BalanceAfterIn(vs ...decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldBalanceAfter, vs...))
}
// BalanceAfterNotIn applies the NotIn predicate on the "balance_after" field.
func BalanceAfterNotIn(vs ...decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldBalanceAfter, vs...))
}
// BalanceAfterGT applies the GT predicate on the "balance_after" field.
func BalanceAfterGT(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldBalanceAfter, v))
}
// BalanceAfterGTE applies the GTE predicate on the "balance_after" field.
func BalanceAfterGTE(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldBalanceAfter, v))
}
// BalanceAfterLT applies the LT predicate on the "balance_after" field.
func BalanceAfterLT(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldBalanceAfter, v))
}
// BalanceAfterLTE applies the LTE predicate on the "balance_after" field.
func BalanceAfterLTE(v decimal.Decimal) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldBalanceAfter, v))
}
// OrderIDEQ applies the EQ predicate on the "order_id" field.
func OrderIDEQ(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldOrderID, v))
}
// OrderIDNEQ applies the NEQ predicate on the "order_id" field.
func OrderIDNEQ(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldOrderID, v))
}
// OrderIDIn applies the In predicate on the "order_id" field.
func OrderIDIn(vs ...int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldOrderID, vs...))
}
// OrderIDNotIn applies the NotIn predicate on the "order_id" field.
func OrderIDNotIn(vs ...int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldOrderID, vs...))
}
// OrderIDGT applies the GT predicate on the "order_id" field.
func OrderIDGT(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldOrderID, v))
}
// OrderIDGTE applies the GTE predicate on the "order_id" field.
func OrderIDGTE(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldOrderID, v))
}
// OrderIDLT applies the LT predicate on the "order_id" field.
func OrderIDLT(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldOrderID, v))
}
// OrderIDLTE applies the LTE predicate on the "order_id" field.
func OrderIDLTE(v int64) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldOrderID, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldCreatedAt, v))
}
// SearchTextEQ applies the EQ predicate on the "search_text" field.
func SearchTextEQ(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEQ(FieldSearchText, v))
}
// SearchTextNEQ applies the NEQ predicate on the "search_text" field.
func SearchTextNEQ(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNEQ(FieldSearchText, v))
}
// SearchTextIn applies the In predicate on the "search_text" field.
func SearchTextIn(vs ...string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldIn(FieldSearchText, vs...))
}
// SearchTextNotIn applies the NotIn predicate on the "search_text" field.
func SearchTextNotIn(vs ...string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldNotIn(FieldSearchText, vs...))
}
// SearchTextGT applies the GT predicate on the "search_text" field.
func SearchTextGT(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGT(FieldSearchText, v))
}
// SearchTextGTE applies the GTE predicate on the "search_text" field.
func SearchTextGTE(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldGTE(FieldSearchText, v))
}
// SearchTextLT applies the LT predicate on the "search_text" field.
func SearchTextLT(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLT(FieldSearchText, v))
}
// SearchTextLTE applies the LTE predicate on the "search_text" field.
func SearchTextLTE(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldLTE(FieldSearchText, v))
}
// SearchTextContains applies the Contains predicate on the "search_text" field.
func SearchTextContains(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldContains(FieldSearchText, v))
}
// SearchTextHasPrefix applies the HasPrefix predicate on the "search_text" field.
func SearchTextHasPrefix(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldHasPrefix(FieldSearchText, v))
}
// SearchTextHasSuffix applies the HasSuffix predicate on the "search_text" field.
func SearchTextHasSuffix(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldHasSuffix(FieldSearchText, v))
}
// SearchTextEqualFold applies the EqualFold predicate on the "search_text" field.
func SearchTextEqualFold(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldEqualFold(FieldSearchText, v))
}
// SearchTextContainsFold applies the ContainsFold predicate on the "search_text" field.
func SearchTextContainsFold(v string) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.FieldContainsFold(FieldSearchText, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.WalletTransactions) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.WalletTransactions) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.WalletTransactions) predicate.WalletTransactions {
return predicate.WalletTransactions(sql.NotPredicates(p))
}
@@ -0,0 +1,287 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/shopspring/decimal"
)
// WalletTransactionsCreate is the builder for creating a WalletTransactions entity.
type WalletTransactionsCreate struct {
config
mutation *WalletTransactionsMutation
hooks []Hook
}
// SetUserID sets the "user_id" field.
func (_c *WalletTransactionsCreate) SetUserID(v int64) *WalletTransactionsCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetType sets the "type" field.
func (_c *WalletTransactionsCreate) SetType(v string) *WalletTransactionsCreate {
_c.mutation.SetType(v)
return _c
}
// SetAmount sets the "amount" field.
func (_c *WalletTransactionsCreate) SetAmount(v decimal.Decimal) *WalletTransactionsCreate {
_c.mutation.SetAmount(v)
return _c
}
// SetBalanceAfter sets the "balance_after" field.
func (_c *WalletTransactionsCreate) SetBalanceAfter(v decimal.Decimal) *WalletTransactionsCreate {
_c.mutation.SetBalanceAfter(v)
return _c
}
// SetDescription sets the "description" field.
func (_c *WalletTransactionsCreate) SetDescription(v []string) *WalletTransactionsCreate {
_c.mutation.SetDescription(v)
return _c
}
// SetOrderID sets the "order_id" field.
func (_c *WalletTransactionsCreate) SetOrderID(v int64) *WalletTransactionsCreate {
_c.mutation.SetOrderID(v)
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *WalletTransactionsCreate) SetCreatedAt(v time.Time) *WalletTransactionsCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetSearchText sets the "search_text" field.
func (_c *WalletTransactionsCreate) SetSearchText(v string) *WalletTransactionsCreate {
_c.mutation.SetSearchText(v)
return _c
}
// SetID sets the "id" field.
func (_c *WalletTransactionsCreate) SetID(v string) *WalletTransactionsCreate {
_c.mutation.SetID(v)
return _c
}
// Mutation returns the WalletTransactionsMutation object of the builder.
func (_c *WalletTransactionsCreate) Mutation() *WalletTransactionsMutation {
return _c.mutation
}
// Save creates the WalletTransactions in the database.
func (_c *WalletTransactionsCreate) Save(ctx context.Context) (*WalletTransactions, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *WalletTransactionsCreate) SaveX(ctx context.Context) *WalletTransactions {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *WalletTransactionsCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *WalletTransactionsCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *WalletTransactionsCreate) check() error {
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "WalletTransactions.user_id"`)}
}
if _, ok := _c.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`models: missing required field "WalletTransactions.type"`)}
}
if _, ok := _c.mutation.Amount(); !ok {
return &ValidationError{Name: "amount", err: errors.New(`models: missing required field "WalletTransactions.amount"`)}
}
if _, ok := _c.mutation.BalanceAfter(); !ok {
return &ValidationError{Name: "balance_after", err: errors.New(`models: missing required field "WalletTransactions.balance_after"`)}
}
if _, ok := _c.mutation.Description(); !ok {
return &ValidationError{Name: "description", err: errors.New(`models: missing required field "WalletTransactions.description"`)}
}
if _, ok := _c.mutation.OrderID(); !ok {
return &ValidationError{Name: "order_id", err: errors.New(`models: missing required field "WalletTransactions.order_id"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "WalletTransactions.created_at"`)}
}
if _, ok := _c.mutation.SearchText(); !ok {
return &ValidationError{Name: "search_text", err: errors.New(`models: missing required field "WalletTransactions.search_text"`)}
}
return nil
}
func (_c *WalletTransactionsCreate) sqlSave(ctx context.Context) (*WalletTransactions, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(string); ok {
_node.ID = id
} else {
return nil, fmt.Errorf("unexpected WalletTransactions.ID type: %T", _spec.ID.Value)
}
}
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *WalletTransactionsCreate) createSpec() (*WalletTransactions, *sqlgraph.CreateSpec) {
var (
_node = &WalletTransactions{config: _c.config}
_spec = sqlgraph.NewCreateSpec(wallettransactions.Table, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString))
)
if id, ok := _c.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := _c.mutation.UserID(); ok {
_spec.SetField(wallettransactions.FieldUserID, field.TypeInt64, value)
_node.UserID = value
}
if value, ok := _c.mutation.GetType(); ok {
_spec.SetField(wallettransactions.FieldType, field.TypeString, value)
_node.Type = value
}
if value, ok := _c.mutation.Amount(); ok {
_spec.SetField(wallettransactions.FieldAmount, field.TypeOther, value)
_node.Amount = value
}
if value, ok := _c.mutation.BalanceAfter(); ok {
_spec.SetField(wallettransactions.FieldBalanceAfter, field.TypeOther, value)
_node.BalanceAfter = value
}
if value, ok := _c.mutation.Description(); ok {
_spec.SetField(wallettransactions.FieldDescription, field.TypeJSON, value)
_node.Description = value
}
if value, ok := _c.mutation.OrderID(); ok {
_spec.SetField(wallettransactions.FieldOrderID, field.TypeInt64, value)
_node.OrderID = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(wallettransactions.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.SearchText(); ok {
_spec.SetField(wallettransactions.FieldSearchText, field.TypeString, value)
_node.SearchText = value
}
return _node, _spec
}
// WalletTransactionsCreateBulk is the builder for creating many WalletTransactions entities in bulk.
type WalletTransactionsCreateBulk struct {
config
err error
builders []*WalletTransactionsCreate
}
// Save creates the WalletTransactions entities in the database.
func (_c *WalletTransactionsCreateBulk) Save(ctx context.Context) ([]*WalletTransactions, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*WalletTransactions, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*WalletTransactionsMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *WalletTransactionsCreateBulk) SaveX(ctx context.Context) []*WalletTransactions {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *WalletTransactionsCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *WalletTransactionsCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// WalletTransactionsDelete is the builder for deleting a WalletTransactions entity.
type WalletTransactionsDelete struct {
config
hooks []Hook
mutation *WalletTransactionsMutation
}
// Where appends a list predicates to the WalletTransactionsDelete builder.
func (_d *WalletTransactionsDelete) Where(ps ...predicate.WalletTransactions) *WalletTransactionsDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *WalletTransactionsDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *WalletTransactionsDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *WalletTransactionsDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(wallettransactions.Table, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// WalletTransactionsDeleteOne is the builder for deleting a single WalletTransactions entity.
type WalletTransactionsDeleteOne struct {
_d *WalletTransactionsDelete
}
// Where appends a list predicates to the WalletTransactionsDelete builder.
func (_d *WalletTransactionsDeleteOne) Where(ps ...predicate.WalletTransactions) *WalletTransactionsDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *WalletTransactionsDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{wallettransactions.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *WalletTransactionsDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// WalletTransactionsQuery is the builder for querying WalletTransactions entities.
type WalletTransactionsQuery struct {
config
ctx *QueryContext
order []wallettransactions.OrderOption
inters []Interceptor
predicates []predicate.WalletTransactions
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the WalletTransactionsQuery builder.
func (_q *WalletTransactionsQuery) Where(ps ...predicate.WalletTransactions) *WalletTransactionsQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *WalletTransactionsQuery) Limit(limit int) *WalletTransactionsQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *WalletTransactionsQuery) Offset(offset int) *WalletTransactionsQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *WalletTransactionsQuery) Unique(unique bool) *WalletTransactionsQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *WalletTransactionsQuery) Order(o ...wallettransactions.OrderOption) *WalletTransactionsQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first WalletTransactions entity from the query.
// Returns a *NotFoundError when no WalletTransactions was found.
func (_q *WalletTransactionsQuery) First(ctx context.Context) (*WalletTransactions, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{wallettransactions.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *WalletTransactionsQuery) FirstX(ctx context.Context) *WalletTransactions {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first WalletTransactions ID from the query.
// Returns a *NotFoundError when no WalletTransactions ID was found.
func (_q *WalletTransactionsQuery) FirstID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{wallettransactions.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *WalletTransactionsQuery) FirstIDX(ctx context.Context) string {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single WalletTransactions entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one WalletTransactions entity is found.
// Returns a *NotFoundError when no WalletTransactions entities are found.
func (_q *WalletTransactionsQuery) Only(ctx context.Context) (*WalletTransactions, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{wallettransactions.Label}
default:
return nil, &NotSingularError{wallettransactions.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *WalletTransactionsQuery) OnlyX(ctx context.Context) *WalletTransactions {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only WalletTransactions ID in the query.
// Returns a *NotSingularError when more than one WalletTransactions ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *WalletTransactionsQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{wallettransactions.Label}
default:
err = &NotSingularError{wallettransactions.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *WalletTransactionsQuery) OnlyIDX(ctx context.Context) string {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of WalletTransactionsSlice.
func (_q *WalletTransactionsQuery) All(ctx context.Context) ([]*WalletTransactions, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*WalletTransactions, *WalletTransactionsQuery]()
return withInterceptors[[]*WalletTransactions](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *WalletTransactionsQuery) AllX(ctx context.Context) []*WalletTransactions {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of WalletTransactions IDs.
func (_q *WalletTransactionsQuery) IDs(ctx context.Context) (ids []string, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(wallettransactions.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *WalletTransactionsQuery) IDsX(ctx context.Context) []string {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *WalletTransactionsQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*WalletTransactionsQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *WalletTransactionsQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *WalletTransactionsQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("models: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *WalletTransactionsQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the WalletTransactionsQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *WalletTransactionsQuery) Clone() *WalletTransactionsQuery {
if _q == nil {
return nil
}
return &WalletTransactionsQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]wallettransactions.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.WalletTransactions{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// UserID int64 `json:"user_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.WalletTransactions.Query().
// GroupBy(wallettransactions.FieldUserID).
// Aggregate(models.Count()).
// Scan(ctx, &v)
func (_q *WalletTransactionsQuery) GroupBy(field string, fields ...string) *WalletTransactionsGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &WalletTransactionsGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = wallettransactions.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// UserID int64 `json:"user_id,omitempty"`
// }
//
// client.WalletTransactions.Query().
// Select(wallettransactions.FieldUserID).
// Scan(ctx, &v)
func (_q *WalletTransactionsQuery) Select(fields ...string) *WalletTransactionsSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &WalletTransactionsSelect{WalletTransactionsQuery: _q}
sbuild.label = wallettransactions.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a WalletTransactionsSelect configured with the given aggregations.
func (_q *WalletTransactionsQuery) Aggregate(fns ...AggregateFunc) *WalletTransactionsSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *WalletTransactionsQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !wallettransactions.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *WalletTransactionsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WalletTransactions, error) {
var (
nodes = []*WalletTransactions{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*WalletTransactions).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &WalletTransactions{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *WalletTransactionsQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *WalletTransactionsQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(wallettransactions.Table, wallettransactions.Columns, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, wallettransactions.FieldID)
for i := range fields {
if fields[i] != wallettransactions.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *WalletTransactionsQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(wallettransactions.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = wallettransactions.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// WalletTransactionsGroupBy is the group-by builder for WalletTransactions entities.
type WalletTransactionsGroupBy struct {
selector
build *WalletTransactionsQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *WalletTransactionsGroupBy) Aggregate(fns ...AggregateFunc) *WalletTransactionsGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *WalletTransactionsGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*WalletTransactionsQuery, *WalletTransactionsGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *WalletTransactionsGroupBy) sqlScan(ctx context.Context, root *WalletTransactionsQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// WalletTransactionsSelect is the builder for selecting fields of WalletTransactions entities.
type WalletTransactionsSelect struct {
*WalletTransactionsQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *WalletTransactionsSelect) Aggregate(fns ...AggregateFunc) *WalletTransactionsSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *WalletTransactionsSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*WalletTransactionsQuery, *WalletTransactionsSelect](ctx, _s.WalletTransactionsQuery, _s, _s.inters, v)
}
func (_s *WalletTransactionsSelect) sqlScan(ctx context.Context, root *WalletTransactionsQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
@@ -0,0 +1,319 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/wallet/rpc/internal/models/predicate"
"juwan-backend/app/wallet/rpc/internal/models/wallettransactions"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/dialect/sql/sqljson"
"entgo.io/ent/schema/field"
)
// WalletTransactionsUpdate is the builder for updating WalletTransactions entities.
type WalletTransactionsUpdate struct {
config
hooks []Hook
mutation *WalletTransactionsMutation
}
// Where appends a list predicates to the WalletTransactionsUpdate builder.
func (_u *WalletTransactionsUpdate) Where(ps ...predicate.WalletTransactions) *WalletTransactionsUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetType sets the "type" field.
func (_u *WalletTransactionsUpdate) SetType(v string) *WalletTransactionsUpdate {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *WalletTransactionsUpdate) SetNillableType(v *string) *WalletTransactionsUpdate {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *WalletTransactionsUpdate) SetDescription(v []string) *WalletTransactionsUpdate {
_u.mutation.SetDescription(v)
return _u
}
// AppendDescription appends value to the "description" field.
func (_u *WalletTransactionsUpdate) AppendDescription(v []string) *WalletTransactionsUpdate {
_u.mutation.AppendDescription(v)
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *WalletTransactionsUpdate) SetCreatedAt(v time.Time) *WalletTransactionsUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *WalletTransactionsUpdate) SetNillableCreatedAt(v *time.Time) *WalletTransactionsUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetSearchText sets the "search_text" field.
func (_u *WalletTransactionsUpdate) SetSearchText(v string) *WalletTransactionsUpdate {
_u.mutation.SetSearchText(v)
return _u
}
// SetNillableSearchText sets the "search_text" field if the given value is not nil.
func (_u *WalletTransactionsUpdate) SetNillableSearchText(v *string) *WalletTransactionsUpdate {
if v != nil {
_u.SetSearchText(*v)
}
return _u
}
// Mutation returns the WalletTransactionsMutation object of the builder.
func (_u *WalletTransactionsUpdate) Mutation() *WalletTransactionsMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *WalletTransactionsUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *WalletTransactionsUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *WalletTransactionsUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *WalletTransactionsUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *WalletTransactionsUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(wallettransactions.Table, wallettransactions.Columns, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(wallettransactions.FieldType, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(wallettransactions.FieldDescription, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedDescription(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, wallettransactions.FieldDescription, value)
})
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(wallettransactions.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.SearchText(); ok {
_spec.SetField(wallettransactions.FieldSearchText, field.TypeString, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{wallettransactions.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// WalletTransactionsUpdateOne is the builder for updating a single WalletTransactions entity.
type WalletTransactionsUpdateOne struct {
config
fields []string
hooks []Hook
mutation *WalletTransactionsMutation
}
// SetType sets the "type" field.
func (_u *WalletTransactionsUpdateOne) SetType(v string) *WalletTransactionsUpdateOne {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *WalletTransactionsUpdateOne) SetNillableType(v *string) *WalletTransactionsUpdateOne {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *WalletTransactionsUpdateOne) SetDescription(v []string) *WalletTransactionsUpdateOne {
_u.mutation.SetDescription(v)
return _u
}
// AppendDescription appends value to the "description" field.
func (_u *WalletTransactionsUpdateOne) AppendDescription(v []string) *WalletTransactionsUpdateOne {
_u.mutation.AppendDescription(v)
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *WalletTransactionsUpdateOne) SetCreatedAt(v time.Time) *WalletTransactionsUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *WalletTransactionsUpdateOne) SetNillableCreatedAt(v *time.Time) *WalletTransactionsUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetSearchText sets the "search_text" field.
func (_u *WalletTransactionsUpdateOne) SetSearchText(v string) *WalletTransactionsUpdateOne {
_u.mutation.SetSearchText(v)
return _u
}
// SetNillableSearchText sets the "search_text" field if the given value is not nil.
func (_u *WalletTransactionsUpdateOne) SetNillableSearchText(v *string) *WalletTransactionsUpdateOne {
if v != nil {
_u.SetSearchText(*v)
}
return _u
}
// Mutation returns the WalletTransactionsMutation object of the builder.
func (_u *WalletTransactionsUpdateOne) Mutation() *WalletTransactionsMutation {
return _u.mutation
}
// Where appends a list predicates to the WalletTransactionsUpdate builder.
func (_u *WalletTransactionsUpdateOne) Where(ps ...predicate.WalletTransactions) *WalletTransactionsUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *WalletTransactionsUpdateOne) Select(field string, fields ...string) *WalletTransactionsUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated WalletTransactions entity.
func (_u *WalletTransactionsUpdateOne) Save(ctx context.Context) (*WalletTransactions, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *WalletTransactionsUpdateOne) SaveX(ctx context.Context) *WalletTransactions {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *WalletTransactionsUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *WalletTransactionsUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *WalletTransactionsUpdateOne) sqlSave(ctx context.Context) (_node *WalletTransactions, err error) {
_spec := sqlgraph.NewUpdateSpec(wallettransactions.Table, wallettransactions.Columns, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "WalletTransactions.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, wallettransactions.FieldID)
for _, f := range fields {
if !wallettransactions.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
if f != wallettransactions.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(wallettransactions.FieldType, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(wallettransactions.FieldDescription, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedDescription(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, wallettransactions.FieldDescription, value)
})
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(wallettransactions.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.SearchText(); ok {
_spec.SetField(wallettransactions.FieldSearchText, field.TypeString, value)
}
_node = &WalletTransactions{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{wallettransactions.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
@@ -0,0 +1,76 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
// Source: wallet.proto
package server
import (
"context"
"juwan-backend/app/wallet/rpc/internal/logic"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
)
type WalletServiceServer struct {
svcCtx *svc.ServiceContext
pb.UnimplementedWalletServiceServer
}
func NewWalletServiceServer(svcCtx *svc.ServiceContext) *WalletServiceServer {
return &WalletServiceServer{
svcCtx: svcCtx,
}
}
// -----------------------walletTransactions-----------------------
func (s *WalletServiceServer) AddWalletTransactions(ctx context.Context, in *pb.AddWalletTransactionsReq) (*pb.AddWalletTransactionsResp, error) {
l := logic.NewAddWalletTransactionsLogic(ctx, s.svcCtx)
return l.AddWalletTransactions(in)
}
func (s *WalletServiceServer) UpdateWalletTransactions(ctx context.Context, in *pb.UpdateWalletTransactionsReq) (*pb.UpdateWalletTransactionsResp, error) {
l := logic.NewUpdateWalletTransactionsLogic(ctx, s.svcCtx)
return l.UpdateWalletTransactions(in)
}
func (s *WalletServiceServer) DelWalletTransactions(ctx context.Context, in *pb.DelWalletTransactionsReq) (*pb.DelWalletTransactionsResp, error) {
l := logic.NewDelWalletTransactionsLogic(ctx, s.svcCtx)
return l.DelWalletTransactions(in)
}
func (s *WalletServiceServer) GetWalletTransactionsById(ctx context.Context, in *pb.GetWalletTransactionsByIdReq) (*pb.GetWalletTransactionsByIdResp, error) {
l := logic.NewGetWalletTransactionsByIdLogic(ctx, s.svcCtx)
return l.GetWalletTransactionsById(in)
}
func (s *WalletServiceServer) SearchWalletTransactions(ctx context.Context, in *pb.SearchWalletTransactionsReq) (*pb.SearchWalletTransactionsResp, error) {
l := logic.NewSearchWalletTransactionsLogic(ctx, s.svcCtx)
return l.SearchWalletTransactions(in)
}
// -----------------------wallets-----------------------
func (s *WalletServiceServer) AddWallets(ctx context.Context, in *pb.AddWalletsReq) (*pb.AddWalletsResp, error) {
l := logic.NewAddWalletsLogic(ctx, s.svcCtx)
return l.AddWallets(in)
}
func (s *WalletServiceServer) UpdateWallets(ctx context.Context, in *pb.UpdateWalletsReq) (*pb.UpdateWalletsResp, error) {
l := logic.NewUpdateWalletsLogic(ctx, s.svcCtx)
return l.UpdateWallets(in)
}
func (s *WalletServiceServer) DelWallets(ctx context.Context, in *pb.DelWalletsReq) (*pb.DelWalletsResp, error) {
l := logic.NewDelWalletsLogic(ctx, s.svcCtx)
return l.DelWallets(in)
}
func (s *WalletServiceServer) GetWalletsById(ctx context.Context, in *pb.GetWalletsByIdReq) (*pb.GetWalletsByIdResp, error) {
l := logic.NewGetWalletsByIdLogic(ctx, s.svcCtx)
return l.GetWalletsById(in)
}
func (s *WalletServiceServer) SearchWallets(ctx context.Context, in *pb.SearchWalletsReq) (*pb.SearchWalletsResp, error) {
l := logic.NewSearchWalletsLogic(ctx, s.svcCtx)
return l.SearchWallets(in)
}
@@ -0,0 +1,63 @@
package svc
import (
"fmt"
"juwan-backend/app/snowflake/rpc/snowflake"
"juwan-backend/app/wallet/rpc/internal/config"
"juwan-backend/app/wallet/rpc/internal/models"
"juwan-backend/common/redisx"
"juwan-backend/common/snowflakex"
"juwan-backend/pkg/adapter"
"strings"
"time"
"ariga.io/entcache"
"entgo.io/ent/dialect/sql"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/zeromicro/go-zero/core/logx"
)
type ServiceContext struct {
Config config.Config
Snowflake snowflake.SnowflakeServiceClient
WalletModelsRW *models.Client
WalletModelsRO *models.Client
}
func NewServiceContext(c config.Config) *ServiceContext {
RWConn, err := sql.Open("pgx", c.DB.Master)
if err != nil {
panic(err)
}
ROConn, err := sql.Open("pgx", c.DB.Slaves)
if err != nil {
panic(err)
}
redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second)
if redisCluster == nil || err != nil {
logx.Errorf("failed to connect to Redis cluster: %v", err)
panic(err)
}
RWDrv := entcache.NewDriver(RWConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client)))
RODrv := entcache.NewDriver(ROConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client)))
entLogFn := func(v ...any) {
logx.Infof("[ent][wallet] %s", fmt.Sprint(v...))
}
modelOpts := []models.Option{models.Driver(RWDrv), models.Log(entLogFn)}
roModelOpts := []models.Option{models.Driver(RODrv), models.Log(entLogFn)}
if strings.EqualFold(c.Log.Level, "debug") {
modelOpts = append(modelOpts, models.Debug())
roModelOpts = append(roModelOpts, models.Debug())
}
return &ServiceContext{
Config: c,
Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf),
WalletModelsRW: models.NewClient(modelOpts...),
WalletModelsRO: models.NewClient(roModelOpts...),
}
}
+39
View File
@@ -0,0 +1,39 @@
package main
import (
"flag"
"fmt"
"juwan-backend/app/wallet/rpc/internal/config"
"juwan-backend/app/wallet/rpc/internal/server"
"juwan-backend/app/wallet/rpc/internal/svc"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/pb.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c, conf.UseEnv())
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
pb.RegisterWalletServiceServer(grpcServer, server.NewWalletServiceServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}
File diff suppressed because it is too large Load Diff
+467
View File
@@ -0,0 +1,467 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
// - protoc v5.29.6
// source: wallet.proto
package pb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
WalletService_AddWalletTransactions_FullMethodName = "/pb.walletService/AddWalletTransactions"
WalletService_UpdateWalletTransactions_FullMethodName = "/pb.walletService/UpdateWalletTransactions"
WalletService_DelWalletTransactions_FullMethodName = "/pb.walletService/DelWalletTransactions"
WalletService_GetWalletTransactionsById_FullMethodName = "/pb.walletService/GetWalletTransactionsById"
WalletService_SearchWalletTransactions_FullMethodName = "/pb.walletService/SearchWalletTransactions"
WalletService_AddWallets_FullMethodName = "/pb.walletService/AddWallets"
WalletService_UpdateWallets_FullMethodName = "/pb.walletService/UpdateWallets"
WalletService_DelWallets_FullMethodName = "/pb.walletService/DelWallets"
WalletService_GetWalletsById_FullMethodName = "/pb.walletService/GetWalletsById"
WalletService_SearchWallets_FullMethodName = "/pb.walletService/SearchWallets"
)
// WalletServiceClient is the client API for WalletService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type WalletServiceClient interface {
// -----------------------walletTransactions-----------------------
AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error)
UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error)
DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error)
GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error)
SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error)
// -----------------------wallets-----------------------
AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error)
UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error)
DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error)
GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error)
SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error)
}
type walletServiceClient struct {
cc grpc.ClientConnInterface
}
func NewWalletServiceClient(cc grpc.ClientConnInterface) WalletServiceClient {
return &walletServiceClient{cc}
}
func (c *walletServiceClient) AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddWalletTransactionsResp)
err := c.cc.Invoke(ctx, WalletService_AddWalletTransactions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateWalletTransactionsResp)
err := c.cc.Invoke(ctx, WalletService_UpdateWalletTransactions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DelWalletTransactionsResp)
err := c.cc.Invoke(ctx, WalletService_DelWalletTransactions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetWalletTransactionsByIdResp)
err := c.cc.Invoke(ctx, WalletService_GetWalletTransactionsById_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SearchWalletTransactionsResp)
err := c.cc.Invoke(ctx, WalletService_SearchWalletTransactions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddWalletsResp)
err := c.cc.Invoke(ctx, WalletService_AddWallets_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateWalletsResp)
err := c.cc.Invoke(ctx, WalletService_UpdateWallets_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DelWalletsResp)
err := c.cc.Invoke(ctx, WalletService_DelWallets_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetWalletsByIdResp)
err := c.cc.Invoke(ctx, WalletService_GetWalletsById_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *walletServiceClient) SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SearchWalletsResp)
err := c.cc.Invoke(ctx, WalletService_SearchWallets_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// WalletServiceServer is the server API for WalletService service.
// All implementations must embed UnimplementedWalletServiceServer
// for forward compatibility.
type WalletServiceServer interface {
// -----------------------walletTransactions-----------------------
AddWalletTransactions(context.Context, *AddWalletTransactionsReq) (*AddWalletTransactionsResp, error)
UpdateWalletTransactions(context.Context, *UpdateWalletTransactionsReq) (*UpdateWalletTransactionsResp, error)
DelWalletTransactions(context.Context, *DelWalletTransactionsReq) (*DelWalletTransactionsResp, error)
GetWalletTransactionsById(context.Context, *GetWalletTransactionsByIdReq) (*GetWalletTransactionsByIdResp, error)
SearchWalletTransactions(context.Context, *SearchWalletTransactionsReq) (*SearchWalletTransactionsResp, error)
// -----------------------wallets-----------------------
AddWallets(context.Context, *AddWalletsReq) (*AddWalletsResp, error)
UpdateWallets(context.Context, *UpdateWalletsReq) (*UpdateWalletsResp, error)
DelWallets(context.Context, *DelWalletsReq) (*DelWalletsResp, error)
GetWalletsById(context.Context, *GetWalletsByIdReq) (*GetWalletsByIdResp, error)
SearchWallets(context.Context, *SearchWalletsReq) (*SearchWalletsResp, error)
mustEmbedUnimplementedWalletServiceServer()
}
// UnimplementedWalletServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedWalletServiceServer struct{}
func (UnimplementedWalletServiceServer) AddWalletTransactions(context.Context, *AddWalletTransactionsReq) (*AddWalletTransactionsResp, error) {
return nil, status.Error(codes.Unimplemented, "method AddWalletTransactions not implemented")
}
func (UnimplementedWalletServiceServer) UpdateWalletTransactions(context.Context, *UpdateWalletTransactionsReq) (*UpdateWalletTransactionsResp, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateWalletTransactions not implemented")
}
func (UnimplementedWalletServiceServer) DelWalletTransactions(context.Context, *DelWalletTransactionsReq) (*DelWalletTransactionsResp, error) {
return nil, status.Error(codes.Unimplemented, "method DelWalletTransactions not implemented")
}
func (UnimplementedWalletServiceServer) GetWalletTransactionsById(context.Context, *GetWalletTransactionsByIdReq) (*GetWalletTransactionsByIdResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetWalletTransactionsById not implemented")
}
func (UnimplementedWalletServiceServer) SearchWalletTransactions(context.Context, *SearchWalletTransactionsReq) (*SearchWalletTransactionsResp, error) {
return nil, status.Error(codes.Unimplemented, "method SearchWalletTransactions not implemented")
}
func (UnimplementedWalletServiceServer) AddWallets(context.Context, *AddWalletsReq) (*AddWalletsResp, error) {
return nil, status.Error(codes.Unimplemented, "method AddWallets not implemented")
}
func (UnimplementedWalletServiceServer) UpdateWallets(context.Context, *UpdateWalletsReq) (*UpdateWalletsResp, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateWallets not implemented")
}
func (UnimplementedWalletServiceServer) DelWallets(context.Context, *DelWalletsReq) (*DelWalletsResp, error) {
return nil, status.Error(codes.Unimplemented, "method DelWallets not implemented")
}
func (UnimplementedWalletServiceServer) GetWalletsById(context.Context, *GetWalletsByIdReq) (*GetWalletsByIdResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetWalletsById not implemented")
}
func (UnimplementedWalletServiceServer) SearchWallets(context.Context, *SearchWalletsReq) (*SearchWalletsResp, error) {
return nil, status.Error(codes.Unimplemented, "method SearchWallets not implemented")
}
func (UnimplementedWalletServiceServer) mustEmbedUnimplementedWalletServiceServer() {}
func (UnimplementedWalletServiceServer) testEmbeddedByValue() {}
// UnsafeWalletServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to WalletServiceServer will
// result in compilation errors.
type UnsafeWalletServiceServer interface {
mustEmbedUnimplementedWalletServiceServer()
}
func RegisterWalletServiceServer(s grpc.ServiceRegistrar, srv WalletServiceServer) {
// If the following call panics, it indicates UnimplementedWalletServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&WalletService_ServiceDesc, srv)
}
func _WalletService_AddWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddWalletTransactionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).AddWalletTransactions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_AddWalletTransactions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).AddWalletTransactions(ctx, req.(*AddWalletTransactionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_UpdateWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateWalletTransactionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).UpdateWalletTransactions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_UpdateWalletTransactions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).UpdateWalletTransactions(ctx, req.(*UpdateWalletTransactionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_DelWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DelWalletTransactionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).DelWalletTransactions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_DelWalletTransactions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).DelWalletTransactions(ctx, req.(*DelWalletTransactionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_GetWalletTransactionsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetWalletTransactionsByIdReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).GetWalletTransactionsById(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_GetWalletTransactionsById_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).GetWalletTransactionsById(ctx, req.(*GetWalletTransactionsByIdReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_SearchWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchWalletTransactionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).SearchWalletTransactions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_SearchWalletTransactions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).SearchWalletTransactions(ctx, req.(*SearchWalletTransactionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_AddWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddWalletsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).AddWallets(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_AddWallets_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).AddWallets(ctx, req.(*AddWalletsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_UpdateWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateWalletsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).UpdateWallets(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_UpdateWallets_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).UpdateWallets(ctx, req.(*UpdateWalletsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_DelWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DelWalletsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).DelWallets(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_DelWallets_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).DelWallets(ctx, req.(*DelWalletsReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_GetWalletsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetWalletsByIdReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).GetWalletsById(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_GetWalletsById_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).GetWalletsById(ctx, req.(*GetWalletsByIdReq))
}
return interceptor(ctx, in, info, handler)
}
func _WalletService_SearchWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchWalletsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WalletServiceServer).SearchWallets(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: WalletService_SearchWallets_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WalletServiceServer).SearchWallets(ctx, req.(*SearchWalletsReq))
}
return interceptor(ctx, in, info, handler)
}
// WalletService_ServiceDesc is the grpc.ServiceDesc for WalletService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var WalletService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "pb.walletService",
HandlerType: (*WalletServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "AddWalletTransactions",
Handler: _WalletService_AddWalletTransactions_Handler,
},
{
MethodName: "UpdateWalletTransactions",
Handler: _WalletService_UpdateWalletTransactions_Handler,
},
{
MethodName: "DelWalletTransactions",
Handler: _WalletService_DelWalletTransactions_Handler,
},
{
MethodName: "GetWalletTransactionsById",
Handler: _WalletService_GetWalletTransactionsById_Handler,
},
{
MethodName: "SearchWalletTransactions",
Handler: _WalletService_SearchWalletTransactions_Handler,
},
{
MethodName: "AddWallets",
Handler: _WalletService_AddWallets_Handler,
},
{
MethodName: "UpdateWallets",
Handler: _WalletService_UpdateWallets_Handler,
},
{
MethodName: "DelWallets",
Handler: _WalletService_DelWallets_Handler,
},
{
MethodName: "GetWalletsById",
Handler: _WalletService_GetWalletsById_Handler,
},
{
MethodName: "SearchWallets",
Handler: _WalletService_SearchWallets_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "wallet.proto",
}
@@ -0,0 +1,116 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
// Source: wallet.proto
package walletservice
import (
"context"
"juwan-backend/app/wallet/rpc/pb"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
AddWalletTransactionsReq = pb.AddWalletTransactionsReq
AddWalletTransactionsResp = pb.AddWalletTransactionsResp
AddWalletsReq = pb.AddWalletsReq
AddWalletsResp = pb.AddWalletsResp
DelWalletTransactionsReq = pb.DelWalletTransactionsReq
DelWalletTransactionsResp = pb.DelWalletTransactionsResp
DelWalletsReq = pb.DelWalletsReq
DelWalletsResp = pb.DelWalletsResp
GetWalletTransactionsByIdReq = pb.GetWalletTransactionsByIdReq
GetWalletTransactionsByIdResp = pb.GetWalletTransactionsByIdResp
GetWalletsByIdReq = pb.GetWalletsByIdReq
GetWalletsByIdResp = pb.GetWalletsByIdResp
SearchWalletTransactionsReq = pb.SearchWalletTransactionsReq
SearchWalletTransactionsResp = pb.SearchWalletTransactionsResp
SearchWalletsReq = pb.SearchWalletsReq
SearchWalletsResp = pb.SearchWalletsResp
UpdateWalletTransactionsReq = pb.UpdateWalletTransactionsReq
UpdateWalletTransactionsResp = pb.UpdateWalletTransactionsResp
UpdateWalletsReq = pb.UpdateWalletsReq
UpdateWalletsResp = pb.UpdateWalletsResp
WalletTransactions = pb.WalletTransactions
Wallets = pb.Wallets
WalletService interface {
// -----------------------walletTransactions-----------------------
AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error)
UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error)
DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error)
GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error)
SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error)
// -----------------------wallets-----------------------
AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error)
UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error)
DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error)
GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error)
SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error)
}
defaultWalletService struct {
cli zrpc.Client
}
)
func NewWalletService(cli zrpc.Client) WalletService {
return &defaultWalletService{
cli: cli,
}
}
// -----------------------walletTransactions-----------------------
func (m *defaultWalletService) AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.AddWalletTransactions(ctx, in, opts...)
}
func (m *defaultWalletService) UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.UpdateWalletTransactions(ctx, in, opts...)
}
func (m *defaultWalletService) DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.DelWalletTransactions(ctx, in, opts...)
}
func (m *defaultWalletService) GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.GetWalletTransactionsById(ctx, in, opts...)
}
func (m *defaultWalletService) SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.SearchWalletTransactions(ctx, in, opts...)
}
// -----------------------wallets-----------------------
func (m *defaultWalletService) AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.AddWallets(ctx, in, opts...)
}
func (m *defaultWalletService) UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.UpdateWallets(ctx, in, opts...)
}
func (m *defaultWalletService) DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.DelWallets(ctx, in, opts...)
}
func (m *defaultWalletService) GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.GetWalletsById(ctx, in, opts...)
}
func (m *defaultWalletService) SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error) {
client := pb.NewWalletServiceClient(m.cli.Conn())
return client.SearchWallets(ctx, in, opts...)
}