Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
陈曦
sub2api
Commits
2fe8932c
Unverified
Commit
2fe8932c
authored
Feb 03, 2026
by
Call White
Committed by
GitHub
Feb 03, 2026
Browse files
Merge pull request #3 from cyhhao/main
merge to main
parents
2f2e76f9
adb77af1
Changes
267
Hide whitespace changes
Inline
Side-by-side
.github/workflows/backend-ci.yml
View file @
2fe8932c
...
...
@@ -19,7 +19,7 @@ jobs:
cache
:
true
-
name
:
Verify Go version
run
:
|
go version | grep -q 'go1.25.
5
'
go version | grep -q 'go1.25.
6
'
-
name
:
Unit tests
working-directory
:
backend
run
:
make test-unit
...
...
@@ -38,7 +38,7 @@ jobs:
cache
:
true
-
name
:
Verify Go version
run
:
|
go version | grep -q 'go1.25.
5
'
go version | grep -q 'go1.25.
6
'
-
name
:
golangci-lint
uses
:
golangci/golangci-lint-action@v9
with
:
...
...
.github/workflows/release.yml
View file @
2fe8932c
...
...
@@ -115,7 +115,7 @@ jobs:
-
name
:
Verify Go version
run
:
|
go version | grep -q 'go1.25.
5
'
go version | grep -q 'go1.25.
6
'
# Docker setup for GoReleaser
-
name
:
Set up QEMU
...
...
@@ -222,8 +222,9 @@ jobs:
REPO="${{ github.repository }}"
GHCR_IMAGE="ghcr.io/${REPO,,}" # ${,,} converts to lowercase
# 获取 tag message 内容
# 获取 tag message 内容
并转义 Markdown 特殊字符
TAG_MESSAGE='${{ steps.tag_message.outputs.message }}'
TAG_MESSAGE=$(echo "$TAG_MESSAGE" | sed 's/\([_*`\[]\)/\\\1/g')
# 限制消息长度(Telegram 消息限制 4096 字符,预留空间给头尾固定内容)
if [ ${#TAG_MESSAGE} -gt 3500 ]; then
...
...
.github/workflows/security-scan.yml
View file @
2fe8932c
...
...
@@ -22,7 +22,7 @@ jobs:
cache-dependency-path
:
backend/go.sum
-
name
:
Verify Go version
run
:
|
go version | grep -q 'go1.25.
5
'
go version | grep -q 'go1.25.
6
'
-
name
:
Run govulncheck
working-directory
:
backend
run
:
|
...
...
Dockerfile
View file @
2fe8932c
...
...
@@ -7,7 +7,7 @@
# =============================================================================
ARG
NODE_IMAGE=node:24-alpine
ARG
GOLANG_IMAGE=golang:1.25.
5
-alpine
ARG
GOLANG_IMAGE=golang:1.25.
6
-alpine
ARG
ALPINE_IMAGE=alpine:3.20
ARG
GOPROXY=https://goproxy.cn,direct
ARG
GOSUMDB=sum.golang.google.cn
...
...
README.md
View file @
2fe8932c
...
...
@@ -18,7 +18,7 @@ English | [中文](README_CN.md)
## Demo
Try Sub2API online:
**https://
v2.pincc.ai
/**
Try Sub2API online:
**https://
demo.sub2api.org
/**
Demo credentials (shared demo environment;
**not**
created automatically for self-hosted installs):
...
...
backend/cmd/server/VERSION
View file @
2fe8932c
0.1.
4
6
0.1.6
1
backend/cmd/server/main.go
View file @
2fe8932c
...
...
@@ -8,6 +8,7 @@ import (
"errors"
"flag"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
...
...
@@ -44,7 +45,25 @@ func init() {
}
}
// initLogger configures the default slog handler based on gin.Mode().
// In non-release mode, Debug level logs are enabled.
func
initLogger
()
{
var
level
slog
.
Level
if
gin
.
Mode
()
==
gin
.
ReleaseMode
{
level
=
slog
.
LevelInfo
}
else
{
level
=
slog
.
LevelDebug
}
handler
:=
slog
.
NewTextHandler
(
os
.
Stderr
,
&
slog
.
HandlerOptions
{
Level
:
level
,
})
slog
.
SetDefault
(
slog
.
New
(
handler
))
}
func
main
()
{
// Initialize slog logger based on gin mode
initLogger
()
// Parse command line flags
setupMode
:=
flag
.
Bool
(
"setup"
,
false
,
"Run setup wizard in CLI mode"
)
showVersion
:=
flag
.
Bool
(
"version"
,
false
,
"Show version information"
)
...
...
backend/cmd/server/wire.go
View file @
2fe8932c
...
...
@@ -70,6 +70,8 @@ func provideCleanup(
schedulerSnapshot
*
service
.
SchedulerSnapshotService
,
tokenRefresh
*
service
.
TokenRefreshService
,
accountExpiry
*
service
.
AccountExpiryService
,
subscriptionExpiry
*
service
.
SubscriptionExpiryService
,
usageCleanup
*
service
.
UsageCleanupService
,
pricing
*
service
.
PricingService
,
emailQueue
*
service
.
EmailQueueService
,
billingCache
*
service
.
BillingCacheService
,
...
...
@@ -123,6 +125,12 @@ func provideCleanup(
}
return
nil
}},
{
"UsageCleanupService"
,
func
()
error
{
if
usageCleanup
!=
nil
{
usageCleanup
.
Stop
()
}
return
nil
}},
{
"TokenRefreshService"
,
func
()
error
{
tokenRefresh
.
Stop
()
return
nil
...
...
@@ -131,6 +139,10 @@ func provideCleanup(
accountExpiry
.
Stop
()
return
nil
}},
{
"SubscriptionExpiryService"
,
func
()
error
{
subscriptionExpiry
.
Stop
()
return
nil
}},
{
"PricingService"
,
func
()
error
{
pricing
.
Stop
()
return
nil
...
...
backend/cmd/server/wire_gen.go
View file @
2fe8932c
...
...
@@ -63,7 +63,13 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
promoService
:=
service
.
NewPromoService
(
promoCodeRepository
,
userRepository
,
billingCacheService
,
client
,
apiKeyAuthCacheInvalidator
)
authService
:=
service
.
NewAuthService
(
userRepository
,
configConfig
,
settingService
,
emailService
,
turnstileService
,
emailQueueService
,
promoService
)
userService
:=
service
.
NewUserService
(
userRepository
,
apiKeyAuthCacheInvalidator
)
authHandler
:=
handler
.
NewAuthHandler
(
configConfig
,
authService
,
userService
,
settingService
,
promoService
)
secretEncryptor
,
err
:=
repository
.
NewAESEncryptor
(
configConfig
)
if
err
!=
nil
{
return
nil
,
err
}
totpCache
:=
repository
.
NewTotpCache
(
redisClient
)
totpService
:=
service
.
NewTotpService
(
userRepository
,
secretEncryptor
,
totpCache
,
settingService
,
emailService
,
emailQueueService
)
authHandler
:=
handler
.
NewAuthHandler
(
configConfig
,
authService
,
userService
,
settingService
,
promoService
,
totpService
)
userHandler
:=
handler
.
NewUserHandler
(
userService
)
apiKeyHandler
:=
handler
.
NewAPIKeyHandler
(
apiKeyService
)
usageLogRepository
:=
repository
.
NewUsageLogRepository
(
client
,
db
)
...
...
@@ -84,7 +90,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
}
dashboardAggregationService
:=
service
.
ProvideDashboardAggregationService
(
dashboardAggregationRepository
,
timingWheelService
,
configConfig
)
dashboardHandler
:=
admin
.
NewDashboardHandler
(
dashboardService
,
dashboardAggregationService
)
accountRepository
:=
repository
.
NewAccountRepository
(
client
,
db
)
schedulerCache
:=
repository
.
NewSchedulerCache
(
redisClient
)
accountRepository
:=
repository
.
NewAccountRepository
(
client
,
db
,
schedulerCache
)
proxyRepository
:=
repository
.
NewProxyRepository
(
client
,
db
)
proxyExitInfoProber
:=
repository
.
NewProxyExitInfoProber
(
configConfig
)
proxyLatencyCache
:=
repository
.
NewProxyLatencyCache
(
redisClient
)
...
...
@@ -105,21 +112,22 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
geminiTokenCache
:=
repository
.
NewGeminiTokenCache
(
redisClient
)
compositeTokenCacheInvalidator
:=
service
.
NewCompositeTokenCacheInvalidator
(
geminiTokenCache
)
rateLimitService
:=
service
.
ProvideRateLimitService
(
accountRepository
,
usageLogRepository
,
configConfig
,
geminiQuotaService
,
tempUnschedCache
,
timeoutCounterCache
,
settingService
,
compositeTokenCacheInvalidator
)
claudeUsageFetcher
:=
repository
.
NewClaudeUsageFetcher
()
httpUpstream
:=
repository
.
NewHTTPUpstream
(
configConfig
)
claudeUsageFetcher
:=
repository
.
NewClaudeUsageFetcher
(
httpUpstream
)
antigravityQuotaFetcher
:=
service
.
NewAntigravityQuotaFetcher
(
proxyRepository
)
usageCache
:=
service
.
NewUsageCache
()
accountUsageService
:=
service
.
NewAccountUsageService
(
accountRepository
,
usageLogRepository
,
claudeUsageFetcher
,
geminiQuotaService
,
antigravityQuotaFetcher
,
usageCache
)
identityCache
:=
repository
.
NewIdentityCache
(
redisClient
)
accountUsageService
:=
service
.
NewAccountUsageService
(
accountRepository
,
usageLogRepository
,
claudeUsageFetcher
,
geminiQuotaService
,
antigravityQuotaFetcher
,
usageCache
,
identityCache
)
geminiTokenProvider
:=
service
.
NewGeminiTokenProvider
(
accountRepository
,
geminiTokenCache
,
geminiOAuthService
)
gatewayCache
:=
repository
.
NewGatewayCache
(
redisClient
)
antigravityTokenProvider
:=
service
.
NewAntigravityTokenProvider
(
accountRepository
,
geminiTokenCache
,
antigravityOAuthService
)
httpUpstream
:=
repository
.
NewHTTPUpstream
(
configConfig
)
antigravityGatewayService
:=
service
.
NewAntigravityGatewayService
(
accountRepository
,
gatewayCache
,
antigravityTokenProvider
,
rateLimitService
,
httpUpstream
,
settingService
)
accountTestService
:=
service
.
NewAccountTestService
(
accountRepository
,
geminiTokenProvider
,
antigravityGatewayService
,
httpUpstream
,
configConfig
)
concurrencyCache
:=
repository
.
ProvideConcurrencyCache
(
redisClient
,
configConfig
)
concurrencyService
:=
service
.
ProvideConcurrencyService
(
concurrencyCache
,
accountRepository
,
configConfig
)
crsSyncService
:=
service
.
NewCRSSyncService
(
accountRepository
,
proxyRepository
,
oAuthService
,
openAIOAuthService
,
geminiOAuthService
,
configConfig
)
sessionLimitCache
:=
repository
.
ProvideSessionLimitCache
(
redisClient
,
configConfig
)
accountHandler
:=
admin
.
NewAccountHandler
(
adminService
,
oAuthService
,
openAIOAuthService
,
geminiOAuthService
,
antigravityOAuthService
,
rateLimitService
,
accountUsageService
,
accountTestService
,
concurrencyService
,
crsSyncService
,
sessionLimitCache
)
accountHandler
:=
admin
.
NewAccountHandler
(
adminService
,
oAuthService
,
openAIOAuthService
,
geminiOAuthService
,
antigravityOAuthService
,
rateLimitService
,
accountUsageService
,
accountTestService
,
concurrencyService
,
crsSyncService
,
sessionLimitCache
,
compositeTokenCacheInvalidator
)
oAuthHandler
:=
admin
.
NewOAuthHandler
(
oAuthService
)
openAIOAuthHandler
:=
admin
.
NewOpenAIOAuthHandler
(
openAIOAuthService
,
adminService
)
geminiOAuthHandler
:=
admin
.
NewGeminiOAuthHandler
(
geminiOAuthService
)
...
...
@@ -128,7 +136,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
adminRedeemHandler
:=
admin
.
NewRedeemHandler
(
adminService
)
promoHandler
:=
admin
.
NewPromoHandler
(
promoService
)
opsRepository
:=
repository
.
NewOpsRepository
(
db
)
schedulerCache
:=
repository
.
NewSchedulerCache
(
redisClient
)
schedulerOutboxRepository
:=
repository
.
NewSchedulerOutboxRepository
(
db
)
schedulerSnapshotService
:=
service
.
ProvideSchedulerSnapshotService
(
schedulerCache
,
schedulerOutboxRepository
,
accountRepository
,
groupRepository
,
configConfig
)
pricingRemoteClient
:=
repository
.
ProvidePricingRemoteClient
(
configConfig
)
...
...
@@ -137,7 +144,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
return
nil
,
err
}
billingService
:=
service
.
NewBillingService
(
configConfig
,
pricingService
)
identityCache
:=
repository
.
NewIdentityCache
(
redisClient
)
identityService
:=
service
.
NewIdentityService
(
identityCache
)
deferredService
:=
service
.
ProvideDeferredService
(
accountRepository
,
timingWheelService
)
claudeTokenProvider
:=
service
.
NewClaudeTokenProvider
(
accountRepository
,
geminiTokenCache
,
oAuthService
)
...
...
@@ -154,7 +160,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
updateService
:=
service
.
ProvideUpdateService
(
updateCache
,
gitHubReleaseClient
,
serviceBuildInfo
)
systemHandler
:=
handler
.
ProvideSystemHandler
(
updateService
)
adminSubscriptionHandler
:=
admin
.
NewSubscriptionHandler
(
subscriptionService
)
adminUsageHandler
:=
admin
.
NewUsageHandler
(
usageService
,
apiKeyService
,
adminService
)
usageCleanupRepository
:=
repository
.
NewUsageCleanupRepository
(
client
,
db
)
usageCleanupService
:=
service
.
ProvideUsageCleanupService
(
usageCleanupRepository
,
timingWheelService
,
dashboardAggregationService
,
configConfig
)
adminUsageHandler
:=
admin
.
NewUsageHandler
(
usageService
,
apiKeyService
,
adminService
,
usageCleanupService
)
userAttributeDefinitionRepository
:=
repository
.
NewUserAttributeDefinitionRepository
(
client
)
userAttributeValueRepository
:=
repository
.
NewUserAttributeValueRepository
(
client
)
userAttributeService
:=
service
.
NewUserAttributeService
(
userAttributeDefinitionRepository
,
userAttributeValueRepository
)
...
...
@@ -163,7 +171,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
gatewayHandler
:=
handler
.
NewGatewayHandler
(
gatewayService
,
geminiMessagesCompatService
,
antigravityGatewayService
,
userService
,
concurrencyService
,
billingCacheService
,
configConfig
)
openAIGatewayHandler
:=
handler
.
NewOpenAIGatewayHandler
(
openAIGatewayService
,
concurrencyService
,
billingCacheService
,
configConfig
)
handlerSettingHandler
:=
handler
.
ProvideSettingHandler
(
settingService
,
buildInfo
)
handlers
:=
handler
.
ProvideHandlers
(
authHandler
,
userHandler
,
apiKeyHandler
,
usageHandler
,
redeemHandler
,
subscriptionHandler
,
adminHandlers
,
gatewayHandler
,
openAIGatewayHandler
,
handlerSettingHandler
)
totpHandler
:=
handler
.
NewTotpHandler
(
totpService
)
handlers
:=
handler
.
ProvideHandlers
(
authHandler
,
userHandler
,
apiKeyHandler
,
usageHandler
,
redeemHandler
,
subscriptionHandler
,
adminHandlers
,
gatewayHandler
,
openAIGatewayHandler
,
handlerSettingHandler
,
totpHandler
)
jwtAuthMiddleware
:=
middleware
.
NewJWTAuthMiddleware
(
authService
,
userService
)
adminAuthMiddleware
:=
middleware
.
NewAdminAuthMiddleware
(
authService
,
userService
,
settingService
)
apiKeyAuthMiddleware
:=
middleware
.
NewAPIKeyAuthMiddleware
(
apiKeyService
,
subscriptionService
,
configConfig
)
...
...
@@ -176,7 +185,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
opsScheduledReportService
:=
service
.
ProvideOpsScheduledReportService
(
opsService
,
userService
,
emailService
,
redisClient
,
configConfig
)
tokenRefreshService
:=
service
.
ProvideTokenRefreshService
(
accountRepository
,
oAuthService
,
openAIOAuthService
,
geminiOAuthService
,
antigravityOAuthService
,
compositeTokenCacheInvalidator
,
configConfig
)
accountExpiryService
:=
service
.
ProvideAccountExpiryService
(
accountRepository
)
v
:=
provideCleanup
(
client
,
redisClient
,
opsMetricsCollector
,
opsAggregationService
,
opsAlertEvaluatorService
,
opsCleanupService
,
opsScheduledReportService
,
schedulerSnapshotService
,
tokenRefreshService
,
accountExpiryService
,
pricingService
,
emailQueueService
,
billingCacheService
,
oAuthService
,
openAIOAuthService
,
geminiOAuthService
,
antigravityOAuthService
)
subscriptionExpiryService
:=
service
.
ProvideSubscriptionExpiryService
(
userSubscriptionRepository
)
v
:=
provideCleanup
(
client
,
redisClient
,
opsMetricsCollector
,
opsAggregationService
,
opsAlertEvaluatorService
,
opsCleanupService
,
opsScheduledReportService
,
schedulerSnapshotService
,
tokenRefreshService
,
accountExpiryService
,
subscriptionExpiryService
,
usageCleanupService
,
pricingService
,
emailQueueService
,
billingCacheService
,
oAuthService
,
openAIOAuthService
,
geminiOAuthService
,
antigravityOAuthService
)
application
:=
&
Application
{
Server
:
httpServer
,
Cleanup
:
v
,
...
...
@@ -209,6 +219,8 @@ func provideCleanup(
schedulerSnapshot
*
service
.
SchedulerSnapshotService
,
tokenRefresh
*
service
.
TokenRefreshService
,
accountExpiry
*
service
.
AccountExpiryService
,
subscriptionExpiry
*
service
.
SubscriptionExpiryService
,
usageCleanup
*
service
.
UsageCleanupService
,
pricing
*
service
.
PricingService
,
emailQueue
*
service
.
EmailQueueService
,
billingCache
*
service
.
BillingCacheService
,
...
...
@@ -261,6 +273,12 @@ func provideCleanup(
}
return
nil
}},
{
"UsageCleanupService"
,
func
()
error
{
if
usageCleanup
!=
nil
{
usageCleanup
.
Stop
()
}
return
nil
}},
{
"TokenRefreshService"
,
func
()
error
{
tokenRefresh
.
Stop
()
return
nil
...
...
@@ -269,6 +287,10 @@ func provideCleanup(
accountExpiry
.
Stop
()
return
nil
}},
{
"SubscriptionExpiryService"
,
func
()
error
{
subscriptionExpiry
.
Stop
()
return
nil
}},
{
"PricingService"
,
func
()
error
{
pricing
.
Stop
()
return
nil
...
...
backend/ent/client.go
View file @
2fe8932c
...
...
@@ -24,6 +24,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
...
...
@@ -57,6 +58,8 @@ type Client struct {
RedeemCode
*
RedeemCodeClient
// Setting is the client for interacting with the Setting builders.
Setting
*
SettingClient
// UsageCleanupTask is the client for interacting with the UsageCleanupTask builders.
UsageCleanupTask
*
UsageCleanupTaskClient
// UsageLog is the client for interacting with the UsageLog builders.
UsageLog
*
UsageLogClient
// User is the client for interacting with the User builders.
...
...
@@ -89,6 +92,7 @@ func (c *Client) init() {
c
.
Proxy
=
NewProxyClient
(
c
.
config
)
c
.
RedeemCode
=
NewRedeemCodeClient
(
c
.
config
)
c
.
Setting
=
NewSettingClient
(
c
.
config
)
c
.
UsageCleanupTask
=
NewUsageCleanupTaskClient
(
c
.
config
)
c
.
UsageLog
=
NewUsageLogClient
(
c
.
config
)
c
.
User
=
NewUserClient
(
c
.
config
)
c
.
UserAllowedGroup
=
NewUserAllowedGroupClient
(
c
.
config
)
...
...
@@ -196,6 +200,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
Proxy
:
NewProxyClient
(
cfg
),
RedeemCode
:
NewRedeemCodeClient
(
cfg
),
Setting
:
NewSettingClient
(
cfg
),
UsageCleanupTask
:
NewUsageCleanupTaskClient
(
cfg
),
UsageLog
:
NewUsageLogClient
(
cfg
),
User
:
NewUserClient
(
cfg
),
UserAllowedGroup
:
NewUserAllowedGroupClient
(
cfg
),
...
...
@@ -230,6 +235,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
Proxy
:
NewProxyClient
(
cfg
),
RedeemCode
:
NewRedeemCodeClient
(
cfg
),
Setting
:
NewSettingClient
(
cfg
),
UsageCleanupTask
:
NewUsageCleanupTaskClient
(
cfg
),
UsageLog
:
NewUsageLogClient
(
cfg
),
User
:
NewUserClient
(
cfg
),
UserAllowedGroup
:
NewUserAllowedGroupClient
(
cfg
),
...
...
@@ -266,8 +272,9 @@ func (c *Client) Close() error {
func
(
c
*
Client
)
Use
(
hooks
...
Hook
)
{
for
_
,
n
:=
range
[]
interface
{
Use
(
...
Hook
)
}{
c
.
APIKey
,
c
.
Account
,
c
.
AccountGroup
,
c
.
Group
,
c
.
PromoCode
,
c
.
PromoCodeUsage
,
c
.
Proxy
,
c
.
RedeemCode
,
c
.
Setting
,
c
.
UsageLog
,
c
.
User
,
c
.
UserAllowedGroup
,
c
.
UserAttributeDefinition
,
c
.
UserAttributeValue
,
c
.
UserSubscription
,
c
.
Proxy
,
c
.
RedeemCode
,
c
.
Setting
,
c
.
UsageCleanupTask
,
c
.
UsageLog
,
c
.
User
,
c
.
UserAllowedGroup
,
c
.
UserAttributeDefinition
,
c
.
UserAttributeValue
,
c
.
UserSubscription
,
}
{
n
.
Use
(
hooks
...
)
}
...
...
@@ -278,8 +285,9 @@ func (c *Client) Use(hooks ...Hook) {
func
(
c
*
Client
)
Intercept
(
interceptors
...
Interceptor
)
{
for
_
,
n
:=
range
[]
interface
{
Intercept
(
...
Interceptor
)
}{
c
.
APIKey
,
c
.
Account
,
c
.
AccountGroup
,
c
.
Group
,
c
.
PromoCode
,
c
.
PromoCodeUsage
,
c
.
Proxy
,
c
.
RedeemCode
,
c
.
Setting
,
c
.
UsageLog
,
c
.
User
,
c
.
UserAllowedGroup
,
c
.
UserAttributeDefinition
,
c
.
UserAttributeValue
,
c
.
UserSubscription
,
c
.
Proxy
,
c
.
RedeemCode
,
c
.
Setting
,
c
.
UsageCleanupTask
,
c
.
UsageLog
,
c
.
User
,
c
.
UserAllowedGroup
,
c
.
UserAttributeDefinition
,
c
.
UserAttributeValue
,
c
.
UserSubscription
,
}
{
n
.
Intercept
(
interceptors
...
)
}
...
...
@@ -306,6 +314,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return
c
.
RedeemCode
.
mutate
(
ctx
,
m
)
case
*
SettingMutation
:
return
c
.
Setting
.
mutate
(
ctx
,
m
)
case
*
UsageCleanupTaskMutation
:
return
c
.
UsageCleanupTask
.
mutate
(
ctx
,
m
)
case
*
UsageLogMutation
:
return
c
.
UsageLog
.
mutate
(
ctx
,
m
)
case
*
UserMutation
:
...
...
@@ -1847,6 +1857,139 @@ func (c *SettingClient) mutate(ctx context.Context, m *SettingMutation) (Value,
}
}
// UsageCleanupTaskClient is a client for the UsageCleanupTask schema.
type
UsageCleanupTaskClient
struct
{
config
}
// NewUsageCleanupTaskClient returns a client for the UsageCleanupTask from the given config.
func
NewUsageCleanupTaskClient
(
c
config
)
*
UsageCleanupTaskClient
{
return
&
UsageCleanupTaskClient
{
config
:
c
}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `usagecleanuptask.Hooks(f(g(h())))`.
func
(
c
*
UsageCleanupTaskClient
)
Use
(
hooks
...
Hook
)
{
c
.
hooks
.
UsageCleanupTask
=
append
(
c
.
hooks
.
UsageCleanupTask
,
hooks
...
)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `usagecleanuptask.Intercept(f(g(h())))`.
func
(
c
*
UsageCleanupTaskClient
)
Intercept
(
interceptors
...
Interceptor
)
{
c
.
inters
.
UsageCleanupTask
=
append
(
c
.
inters
.
UsageCleanupTask
,
interceptors
...
)
}
// Create returns a builder for creating a UsageCleanupTask entity.
func
(
c
*
UsageCleanupTaskClient
)
Create
()
*
UsageCleanupTaskCreate
{
mutation
:=
newUsageCleanupTaskMutation
(
c
.
config
,
OpCreate
)
return
&
UsageCleanupTaskCreate
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
mutation
}
}
// CreateBulk returns a builder for creating a bulk of UsageCleanupTask entities.
func
(
c
*
UsageCleanupTaskClient
)
CreateBulk
(
builders
...*
UsageCleanupTaskCreate
)
*
UsageCleanupTaskCreateBulk
{
return
&
UsageCleanupTaskCreateBulk
{
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
*
UsageCleanupTaskClient
)
MapCreateBulk
(
slice
any
,
setFunc
func
(
*
UsageCleanupTaskCreate
,
int
))
*
UsageCleanupTaskCreateBulk
{
rv
:=
reflect
.
ValueOf
(
slice
)
if
rv
.
Kind
()
!=
reflect
.
Slice
{
return
&
UsageCleanupTaskCreateBulk
{
err
:
fmt
.
Errorf
(
"calling to UsageCleanupTaskClient.MapCreateBulk with wrong type %T, need slice"
,
slice
)}
}
builders
:=
make
([]
*
UsageCleanupTaskCreate
,
rv
.
Len
())
for
i
:=
0
;
i
<
rv
.
Len
();
i
++
{
builders
[
i
]
=
c
.
Create
()
setFunc
(
builders
[
i
],
i
)
}
return
&
UsageCleanupTaskCreateBulk
{
config
:
c
.
config
,
builders
:
builders
}
}
// Update returns an update builder for UsageCleanupTask.
func
(
c
*
UsageCleanupTaskClient
)
Update
()
*
UsageCleanupTaskUpdate
{
mutation
:=
newUsageCleanupTaskMutation
(
c
.
config
,
OpUpdate
)
return
&
UsageCleanupTaskUpdate
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
mutation
}
}
// UpdateOne returns an update builder for the given entity.
func
(
c
*
UsageCleanupTaskClient
)
UpdateOne
(
_m
*
UsageCleanupTask
)
*
UsageCleanupTaskUpdateOne
{
mutation
:=
newUsageCleanupTaskMutation
(
c
.
config
,
OpUpdateOne
,
withUsageCleanupTask
(
_m
))
return
&
UsageCleanupTaskUpdateOne
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
mutation
}
}
// UpdateOneID returns an update builder for the given id.
func
(
c
*
UsageCleanupTaskClient
)
UpdateOneID
(
id
int64
)
*
UsageCleanupTaskUpdateOne
{
mutation
:=
newUsageCleanupTaskMutation
(
c
.
config
,
OpUpdateOne
,
withUsageCleanupTaskID
(
id
))
return
&
UsageCleanupTaskUpdateOne
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
mutation
}
}
// Delete returns a delete builder for UsageCleanupTask.
func
(
c
*
UsageCleanupTaskClient
)
Delete
()
*
UsageCleanupTaskDelete
{
mutation
:=
newUsageCleanupTaskMutation
(
c
.
config
,
OpDelete
)
return
&
UsageCleanupTaskDelete
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
mutation
}
}
// DeleteOne returns a builder for deleting the given entity.
func
(
c
*
UsageCleanupTaskClient
)
DeleteOne
(
_m
*
UsageCleanupTask
)
*
UsageCleanupTaskDeleteOne
{
return
c
.
DeleteOneID
(
_m
.
ID
)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func
(
c
*
UsageCleanupTaskClient
)
DeleteOneID
(
id
int64
)
*
UsageCleanupTaskDeleteOne
{
builder
:=
c
.
Delete
()
.
Where
(
usagecleanuptask
.
ID
(
id
))
builder
.
mutation
.
id
=
&
id
builder
.
mutation
.
op
=
OpDeleteOne
return
&
UsageCleanupTaskDeleteOne
{
builder
}
}
// Query returns a query builder for UsageCleanupTask.
func
(
c
*
UsageCleanupTaskClient
)
Query
()
*
UsageCleanupTaskQuery
{
return
&
UsageCleanupTaskQuery
{
config
:
c
.
config
,
ctx
:
&
QueryContext
{
Type
:
TypeUsageCleanupTask
},
inters
:
c
.
Interceptors
(),
}
}
// Get returns a UsageCleanupTask entity by its id.
func
(
c
*
UsageCleanupTaskClient
)
Get
(
ctx
context
.
Context
,
id
int64
)
(
*
UsageCleanupTask
,
error
)
{
return
c
.
Query
()
.
Where
(
usagecleanuptask
.
ID
(
id
))
.
Only
(
ctx
)
}
// GetX is like Get, but panics if an error occurs.
func
(
c
*
UsageCleanupTaskClient
)
GetX
(
ctx
context
.
Context
,
id
int64
)
*
UsageCleanupTask
{
obj
,
err
:=
c
.
Get
(
ctx
,
id
)
if
err
!=
nil
{
panic
(
err
)
}
return
obj
}
// Hooks returns the client hooks.
func
(
c
*
UsageCleanupTaskClient
)
Hooks
()
[]
Hook
{
return
c
.
hooks
.
UsageCleanupTask
}
// Interceptors returns the client interceptors.
func
(
c
*
UsageCleanupTaskClient
)
Interceptors
()
[]
Interceptor
{
return
c
.
inters
.
UsageCleanupTask
}
func
(
c
*
UsageCleanupTaskClient
)
mutate
(
ctx
context
.
Context
,
m
*
UsageCleanupTaskMutation
)
(
Value
,
error
)
{
switch
m
.
Op
()
{
case
OpCreate
:
return
(
&
UsageCleanupTaskCreate
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
m
})
.
Save
(
ctx
)
case
OpUpdate
:
return
(
&
UsageCleanupTaskUpdate
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
m
})
.
Save
(
ctx
)
case
OpUpdateOne
:
return
(
&
UsageCleanupTaskUpdateOne
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
m
})
.
Save
(
ctx
)
case
OpDelete
,
OpDeleteOne
:
return
(
&
UsageCleanupTaskDelete
{
config
:
c
.
config
,
hooks
:
c
.
Hooks
(),
mutation
:
m
})
.
Exec
(
ctx
)
default
:
return
nil
,
fmt
.
Errorf
(
"ent: unknown UsageCleanupTask mutation op: %q"
,
m
.
Op
())
}
}
// UsageLogClient is a client for the UsageLog schema.
type
UsageLogClient
struct
{
config
...
...
@@ -2974,13 +3117,13 @@ func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscription
type
(
hooks
struct
{
APIKey
,
Account
,
AccountGroup
,
Group
,
PromoCode
,
PromoCodeUsage
,
Proxy
,
RedeemCode
,
Setting
,
UsageLog
,
User
,
UserAllowedGroup
,
UserAttributeDefinition
,
UserAttributeValue
,
UserSubscription
[]
ent
.
Hook
RedeemCode
,
Setting
,
UsageCleanupTask
,
UsageLog
,
User
,
UserAllowedGroup
,
UserAttributeDefinition
,
UserAttributeValue
,
UserSubscription
[]
ent
.
Hook
}
inters
struct
{
APIKey
,
Account
,
AccountGroup
,
Group
,
PromoCode
,
PromoCodeUsage
,
Proxy
,
RedeemCode
,
Setting
,
UsageLog
,
User
,
UserAllowedGroup
,
UserAttributeDefinition
,
UserAttributeValue
,
UserSubscription
[]
ent
.
Interceptor
RedeemCode
,
Setting
,
UsageCleanupTask
,
UsageLog
,
User
,
UserAllowedGroup
,
UserAttributeDefinition
,
UserAttributeValue
,
UserSubscription
[]
ent
.
Interceptor
}
)
...
...
backend/ent/ent.go
View file @
2fe8932c
...
...
@@ -21,6 +21,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
...
...
@@ -96,6 +97,7 @@ func checkColumn(t, c string) error {
proxy
.
Table
:
proxy
.
ValidColumn
,
redeemcode
.
Table
:
redeemcode
.
ValidColumn
,
setting
.
Table
:
setting
.
ValidColumn
,
usagecleanuptask
.
Table
:
usagecleanuptask
.
ValidColumn
,
usagelog
.
Table
:
usagelog
.
ValidColumn
,
user
.
Table
:
user
.
ValidColumn
,
userallowedgroup
.
Table
:
userallowedgroup
.
ValidColumn
,
...
...
backend/ent/hook/hook.go
View file @
2fe8932c
...
...
@@ -117,6 +117,18 @@ func (f SettingFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, err
return
nil
,
fmt
.
Errorf
(
"unexpected mutation type %T. expect *ent.SettingMutation"
,
m
)
}
// The UsageCleanupTaskFunc type is an adapter to allow the use of ordinary
// function as UsageCleanupTask mutator.
type
UsageCleanupTaskFunc
func
(
context
.
Context
,
*
ent
.
UsageCleanupTaskMutation
)
(
ent
.
Value
,
error
)
// Mutate calls f(ctx, m).
func
(
f
UsageCleanupTaskFunc
)
Mutate
(
ctx
context
.
Context
,
m
ent
.
Mutation
)
(
ent
.
Value
,
error
)
{
if
mv
,
ok
:=
m
.
(
*
ent
.
UsageCleanupTaskMutation
);
ok
{
return
f
(
ctx
,
mv
)
}
return
nil
,
fmt
.
Errorf
(
"unexpected mutation type %T. expect *ent.UsageCleanupTaskMutation"
,
m
)
}
// The UsageLogFunc type is an adapter to allow the use of ordinary
// function as UsageLog mutator.
type
UsageLogFunc
func
(
context
.
Context
,
*
ent
.
UsageLogMutation
)
(
ent
.
Value
,
error
)
...
...
backend/ent/intercept/intercept.go
View file @
2fe8932c
...
...
@@ -18,6 +18,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
...
...
@@ -325,6 +326,33 @@ func (f TraverseSetting) Traverse(ctx context.Context, q ent.Query) error {
return
fmt
.
Errorf
(
"unexpected query type %T. expect *ent.SettingQuery"
,
q
)
}
// The UsageCleanupTaskFunc type is an adapter to allow the use of ordinary function as a Querier.
type
UsageCleanupTaskFunc
func
(
context
.
Context
,
*
ent
.
UsageCleanupTaskQuery
)
(
ent
.
Value
,
error
)
// Query calls f(ctx, q).
func
(
f
UsageCleanupTaskFunc
)
Query
(
ctx
context
.
Context
,
q
ent
.
Query
)
(
ent
.
Value
,
error
)
{
if
q
,
ok
:=
q
.
(
*
ent
.
UsageCleanupTaskQuery
);
ok
{
return
f
(
ctx
,
q
)
}
return
nil
,
fmt
.
Errorf
(
"unexpected query type %T. expect *ent.UsageCleanupTaskQuery"
,
q
)
}
// The TraverseUsageCleanupTask type is an adapter to allow the use of ordinary function as Traverser.
type
TraverseUsageCleanupTask
func
(
context
.
Context
,
*
ent
.
UsageCleanupTaskQuery
)
error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func
(
f
TraverseUsageCleanupTask
)
Intercept
(
next
ent
.
Querier
)
ent
.
Querier
{
return
next
}
// Traverse calls f(ctx, q).
func
(
f
TraverseUsageCleanupTask
)
Traverse
(
ctx
context
.
Context
,
q
ent
.
Query
)
error
{
if
q
,
ok
:=
q
.
(
*
ent
.
UsageCleanupTaskQuery
);
ok
{
return
f
(
ctx
,
q
)
}
return
fmt
.
Errorf
(
"unexpected query type %T. expect *ent.UsageCleanupTaskQuery"
,
q
)
}
// The UsageLogFunc type is an adapter to allow the use of ordinary function as a Querier.
type
UsageLogFunc
func
(
context
.
Context
,
*
ent
.
UsageLogQuery
)
(
ent
.
Value
,
error
)
...
...
@@ -508,6 +536,8 @@ func NewQuery(q ent.Query) (Query, error) {
return
&
query
[
*
ent
.
RedeemCodeQuery
,
predicate
.
RedeemCode
,
redeemcode
.
OrderOption
]{
typ
:
ent
.
TypeRedeemCode
,
tq
:
q
},
nil
case
*
ent
.
SettingQuery
:
return
&
query
[
*
ent
.
SettingQuery
,
predicate
.
Setting
,
setting
.
OrderOption
]{
typ
:
ent
.
TypeSetting
,
tq
:
q
},
nil
case
*
ent
.
UsageCleanupTaskQuery
:
return
&
query
[
*
ent
.
UsageCleanupTaskQuery
,
predicate
.
UsageCleanupTask
,
usagecleanuptask
.
OrderOption
]{
typ
:
ent
.
TypeUsageCleanupTask
,
tq
:
q
},
nil
case
*
ent
.
UsageLogQuery
:
return
&
query
[
*
ent
.
UsageLogQuery
,
predicate
.
UsageLog
,
usagelog
.
OrderOption
]{
typ
:
ent
.
TypeUsageLog
,
tq
:
q
},
nil
case
*
ent
.
UserQuery
:
...
...
backend/ent/migrate/schema.go
View file @
2fe8932c
...
...
@@ -434,6 +434,44 @@ var (
Columns
:
SettingsColumns
,
PrimaryKey
:
[]
*
schema
.
Column
{
SettingsColumns
[
0
]},
}
// UsageCleanupTasksColumns holds the columns for the "usage_cleanup_tasks" table.
UsageCleanupTasksColumns
=
[]
*
schema
.
Column
{
{
Name
:
"id"
,
Type
:
field
.
TypeInt64
,
Increment
:
true
},
{
Name
:
"created_at"
,
Type
:
field
.
TypeTime
,
SchemaType
:
map
[
string
]
string
{
"postgres"
:
"timestamptz"
}},
{
Name
:
"updated_at"
,
Type
:
field
.
TypeTime
,
SchemaType
:
map
[
string
]
string
{
"postgres"
:
"timestamptz"
}},
{
Name
:
"status"
,
Type
:
field
.
TypeString
,
Size
:
20
},
{
Name
:
"filters"
,
Type
:
field
.
TypeJSON
},
{
Name
:
"created_by"
,
Type
:
field
.
TypeInt64
},
{
Name
:
"deleted_rows"
,
Type
:
field
.
TypeInt64
,
Default
:
0
},
{
Name
:
"error_message"
,
Type
:
field
.
TypeString
,
Nullable
:
true
},
{
Name
:
"canceled_by"
,
Type
:
field
.
TypeInt64
,
Nullable
:
true
},
{
Name
:
"canceled_at"
,
Type
:
field
.
TypeTime
,
Nullable
:
true
},
{
Name
:
"started_at"
,
Type
:
field
.
TypeTime
,
Nullable
:
true
},
{
Name
:
"finished_at"
,
Type
:
field
.
TypeTime
,
Nullable
:
true
},
}
// UsageCleanupTasksTable holds the schema information for the "usage_cleanup_tasks" table.
UsageCleanupTasksTable
=
&
schema
.
Table
{
Name
:
"usage_cleanup_tasks"
,
Columns
:
UsageCleanupTasksColumns
,
PrimaryKey
:
[]
*
schema
.
Column
{
UsageCleanupTasksColumns
[
0
]},
Indexes
:
[]
*
schema
.
Index
{
{
Name
:
"usagecleanuptask_status_created_at"
,
Unique
:
false
,
Columns
:
[]
*
schema
.
Column
{
UsageCleanupTasksColumns
[
3
],
UsageCleanupTasksColumns
[
1
]},
},
{
Name
:
"usagecleanuptask_created_at"
,
Unique
:
false
,
Columns
:
[]
*
schema
.
Column
{
UsageCleanupTasksColumns
[
1
]},
},
{
Name
:
"usagecleanuptask_canceled_at"
,
Unique
:
false
,
Columns
:
[]
*
schema
.
Column
{
UsageCleanupTasksColumns
[
9
]},
},
},
}
// UsageLogsColumns holds the columns for the "usage_logs" table.
UsageLogsColumns
=
[]
*
schema
.
Column
{
{
Name
:
"id"
,
Type
:
field
.
TypeInt64
,
Increment
:
true
},
...
...
@@ -572,6 +610,9 @@ var (
{
Name
:
"status"
,
Type
:
field
.
TypeString
,
Size
:
20
,
Default
:
"active"
},
{
Name
:
"username"
,
Type
:
field
.
TypeString
,
Size
:
100
,
Default
:
""
},
{
Name
:
"notes"
,
Type
:
field
.
TypeString
,
Default
:
""
,
SchemaType
:
map
[
string
]
string
{
"postgres"
:
"text"
}},
{
Name
:
"totp_secret_encrypted"
,
Type
:
field
.
TypeString
,
Nullable
:
true
,
SchemaType
:
map
[
string
]
string
{
"postgres"
:
"text"
}},
{
Name
:
"totp_enabled"
,
Type
:
field
.
TypeBool
,
Default
:
false
},
{
Name
:
"totp_enabled_at"
,
Type
:
field
.
TypeTime
,
Nullable
:
true
},
}
// UsersTable holds the schema information for the "users" table.
UsersTable
=
&
schema
.
Table
{
...
...
@@ -805,6 +846,7 @@ var (
ProxiesTable
,
RedeemCodesTable
,
SettingsTable
,
UsageCleanupTasksTable
,
UsageLogsTable
,
UsersTable
,
UserAllowedGroupsTable
,
...
...
@@ -851,6 +893,9 @@ func init() {
SettingsTable
.
Annotation
=
&
entsql
.
Annotation
{
Table
:
"settings"
,
}
UsageCleanupTasksTable
.
Annotation
=
&
entsql
.
Annotation
{
Table
:
"usage_cleanup_tasks"
,
}
UsageLogsTable
.
ForeignKeys
[
0
]
.
RefTable
=
APIKeysTable
UsageLogsTable
.
ForeignKeys
[
1
]
.
RefTable
=
AccountsTable
UsageLogsTable
.
ForeignKeys
[
2
]
.
RefTable
=
GroupsTable
...
...
backend/ent/mutation.go
View file @
2fe8932c
...
...
@@ -4,6 +4,7 @@ package ent
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
...
...
@@ -21,6 +22,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
...
...
@@ -47,6 +49,7 @@ const (
TypeProxy = "Proxy"
TypeRedeemCode = "RedeemCode"
TypeSetting = "Setting"
TypeUsageCleanupTask = "UsageCleanupTask"
TypeUsageLog = "UsageLog"
TypeUser = "User"
TypeUserAllowedGroup = "UserAllowedGroup"
...
...
@@ -10370,6 +10373,1089 @@ func (m *SettingMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown Setting edge %s", name)
}
// UsageCleanupTaskMutation represents an operation that mutates the UsageCleanupTask nodes in the graph.
type UsageCleanupTaskMutation struct {
config
op Op
typ string
id *int64
created_at *time.Time
updated_at *time.Time
status *string
filters *json.RawMessage
appendfilters json.RawMessage
created_by *int64
addcreated_by *int64
deleted_rows *int64
adddeleted_rows *int64
error_message *string
canceled_by *int64
addcanceled_by *int64
canceled_at *time.Time
started_at *time.Time
finished_at *time.Time
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*UsageCleanupTask, error)
predicates []predicate.UsageCleanupTask
}
var _ ent.Mutation = (*UsageCleanupTaskMutation)(nil)
// usagecleanuptaskOption allows management of the mutation configuration using functional options.
type usagecleanuptaskOption func(*UsageCleanupTaskMutation)
// newUsageCleanupTaskMutation creates new mutation for the UsageCleanupTask entity.
func newUsageCleanupTaskMutation(c config, op Op, opts ...usagecleanuptaskOption) *UsageCleanupTaskMutation {
m := &UsageCleanupTaskMutation{
config: c,
op: op,
typ: TypeUsageCleanupTask,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withUsageCleanupTaskID sets the ID field of the mutation.
func withUsageCleanupTaskID(id int64) usagecleanuptaskOption {
return func(m *UsageCleanupTaskMutation) {
var (
err error
once sync.Once
value *UsageCleanupTask
)
m.oldValue = func(ctx context.Context) (*UsageCleanupTask, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().UsageCleanupTask.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withUsageCleanupTask sets the old UsageCleanupTask of the mutation.
func withUsageCleanupTask(node *UsageCleanupTask) usagecleanuptaskOption {
return func(m *UsageCleanupTaskMutation) {
m.oldValue = func(context.Context) (*UsageCleanupTask, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m UsageCleanupTaskMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m UsageCleanupTaskMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *UsageCleanupTaskMutation) ID() (id int64, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *UsageCleanupTaskMutation) IDs(ctx context.Context) ([]int64, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int64{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().UsageCleanupTask.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetCreatedAt sets the "created_at" field.
func (m *UsageCleanupTaskMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *UsageCleanupTaskMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *UsageCleanupTaskMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *UsageCleanupTaskMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *UsageCleanupTaskMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *UsageCleanupTaskMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// SetStatus sets the "status" field.
func (m *UsageCleanupTaskMutation) SetStatus(s string) {
m.status = &s
}
// Status returns the value of the "status" field in the mutation.
func (m *UsageCleanupTaskMutation) Status() (r string, exists bool) {
v := m.status
if v == nil {
return
}
return *v, true
}
// OldStatus returns the old "status" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldStatus(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldStatus is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldStatus requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldStatus: %w", err)
}
return oldValue.Status, nil
}
// ResetStatus resets all changes to the "status" field.
func (m *UsageCleanupTaskMutation) ResetStatus() {
m.status = nil
}
// SetFilters sets the "filters" field.
func (m *UsageCleanupTaskMutation) SetFilters(jm json.RawMessage) {
m.filters = &jm
m.appendfilters = nil
}
// Filters returns the value of the "filters" field in the mutation.
func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) {
v := m.filters
if v == nil {
return
}
return *v, true
}
// OldFilters returns the old "filters" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMessage, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldFilters is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldFilters requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldFilters: %w", err)
}
return oldValue.Filters, nil
}
// AppendFilters adds jm to the "filters" field.
func (m *UsageCleanupTaskMutation) AppendFilters(jm json.RawMessage) {
m.appendfilters = append(m.appendfilters, jm...)
}
// AppendedFilters returns the list of values that were appended to the "filters" field in this mutation.
func (m *UsageCleanupTaskMutation) AppendedFilters() (json.RawMessage, bool) {
if len(m.appendfilters) == 0 {
return nil, false
}
return m.appendfilters, true
}
// ResetFilters resets all changes to the "filters" field.
func (m *UsageCleanupTaskMutation) ResetFilters() {
m.filters = nil
m.appendfilters = nil
}
// SetCreatedBy sets the "created_by" field.
func (m *UsageCleanupTaskMutation) SetCreatedBy(i int64) {
m.created_by = &i
m.addcreated_by = nil
}
// CreatedBy returns the value of the "created_by" field in the mutation.
func (m *UsageCleanupTaskMutation) CreatedBy() (r int64, exists bool) {
v := m.created_by
if v == nil {
return
}
return *v, true
}
// OldCreatedBy returns the old "created_by" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldCreatedBy(ctx context.Context) (v int64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedBy requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err)
}
return oldValue.CreatedBy, nil
}
// AddCreatedBy adds i to the "created_by" field.
func (m *UsageCleanupTaskMutation) AddCreatedBy(i int64) {
if m.addcreated_by != nil {
*m.addcreated_by += i
} else {
m.addcreated_by = &i
}
}
// AddedCreatedBy returns the value that was added to the "created_by" field in this mutation.
func (m *UsageCleanupTaskMutation) AddedCreatedBy() (r int64, exists bool) {
v := m.addcreated_by
if v == nil {
return
}
return *v, true
}
// ResetCreatedBy resets all changes to the "created_by" field.
func (m *UsageCleanupTaskMutation) ResetCreatedBy() {
m.created_by = nil
m.addcreated_by = nil
}
// SetDeletedRows sets the "deleted_rows" field.
func (m *UsageCleanupTaskMutation) SetDeletedRows(i int64) {
m.deleted_rows = &i
m.adddeleted_rows = nil
}
// DeletedRows returns the value of the "deleted_rows" field in the mutation.
func (m *UsageCleanupTaskMutation) DeletedRows() (r int64, exists bool) {
v := m.deleted_rows
if v == nil {
return
}
return *v, true
}
// OldDeletedRows returns the old "deleted_rows" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldDeletedRows(ctx context.Context) (v int64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDeletedRows is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDeletedRows requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDeletedRows: %w", err)
}
return oldValue.DeletedRows, nil
}
// AddDeletedRows adds i to the "deleted_rows" field.
func (m *UsageCleanupTaskMutation) AddDeletedRows(i int64) {
if m.adddeleted_rows != nil {
*m.adddeleted_rows += i
} else {
m.adddeleted_rows = &i
}
}
// AddedDeletedRows returns the value that was added to the "deleted_rows" field in this mutation.
func (m *UsageCleanupTaskMutation) AddedDeletedRows() (r int64, exists bool) {
v := m.adddeleted_rows
if v == nil {
return
}
return *v, true
}
// ResetDeletedRows resets all changes to the "deleted_rows" field.
func (m *UsageCleanupTaskMutation) ResetDeletedRows() {
m.deleted_rows = nil
m.adddeleted_rows = nil
}
// SetErrorMessage sets the "error_message" field.
func (m *UsageCleanupTaskMutation) SetErrorMessage(s string) {
m.error_message = &s
}
// ErrorMessage returns the value of the "error_message" field in the mutation.
func (m *UsageCleanupTaskMutation) ErrorMessage() (r string, exists bool) {
v := m.error_message
if v == nil {
return
}
return *v, true
}
// OldErrorMessage returns the old "error_message" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldErrorMessage(ctx context.Context) (v *string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldErrorMessage requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err)
}
return oldValue.ErrorMessage, nil
}
// ClearErrorMessage clears the value of the "error_message" field.
func (m *UsageCleanupTaskMutation) ClearErrorMessage() {
m.error_message = nil
m.clearedFields[usagecleanuptask.FieldErrorMessage] = struct{}{}
}
// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation.
func (m *UsageCleanupTaskMutation) ErrorMessageCleared() bool {
_, ok := m.clearedFields[usagecleanuptask.FieldErrorMessage]
return ok
}
// ResetErrorMessage resets all changes to the "error_message" field.
func (m *UsageCleanupTaskMutation) ResetErrorMessage() {
m.error_message = nil
delete(m.clearedFields, usagecleanuptask.FieldErrorMessage)
}
// SetCanceledBy sets the "canceled_by" field.
func (m *UsageCleanupTaskMutation) SetCanceledBy(i int64) {
m.canceled_by = &i
m.addcanceled_by = nil
}
// CanceledBy returns the value of the "canceled_by" field in the mutation.
func (m *UsageCleanupTaskMutation) CanceledBy() (r int64, exists bool) {
v := m.canceled_by
if v == nil {
return
}
return *v, true
}
// OldCanceledBy returns the old "canceled_by" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldCanceledBy(ctx context.Context) (v *int64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCanceledBy is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCanceledBy requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCanceledBy: %w", err)
}
return oldValue.CanceledBy, nil
}
// AddCanceledBy adds i to the "canceled_by" field.
func (m *UsageCleanupTaskMutation) AddCanceledBy(i int64) {
if m.addcanceled_by != nil {
*m.addcanceled_by += i
} else {
m.addcanceled_by = &i
}
}
// AddedCanceledBy returns the value that was added to the "canceled_by" field in this mutation.
func (m *UsageCleanupTaskMutation) AddedCanceledBy() (r int64, exists bool) {
v := m.addcanceled_by
if v == nil {
return
}
return *v, true
}
// ClearCanceledBy clears the value of the "canceled_by" field.
func (m *UsageCleanupTaskMutation) ClearCanceledBy() {
m.canceled_by = nil
m.addcanceled_by = nil
m.clearedFields[usagecleanuptask.FieldCanceledBy] = struct{}{}
}
// CanceledByCleared returns if the "canceled_by" field was cleared in this mutation.
func (m *UsageCleanupTaskMutation) CanceledByCleared() bool {
_, ok := m.clearedFields[usagecleanuptask.FieldCanceledBy]
return ok
}
// ResetCanceledBy resets all changes to the "canceled_by" field.
func (m *UsageCleanupTaskMutation) ResetCanceledBy() {
m.canceled_by = nil
m.addcanceled_by = nil
delete(m.clearedFields, usagecleanuptask.FieldCanceledBy)
}
// SetCanceledAt sets the "canceled_at" field.
func (m *UsageCleanupTaskMutation) SetCanceledAt(t time.Time) {
m.canceled_at = &t
}
// CanceledAt returns the value of the "canceled_at" field in the mutation.
func (m *UsageCleanupTaskMutation) CanceledAt() (r time.Time, exists bool) {
v := m.canceled_at
if v == nil {
return
}
return *v, true
}
// OldCanceledAt returns the old "canceled_at" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldCanceledAt(ctx context.Context) (v *time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCanceledAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCanceledAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCanceledAt: %w", err)
}
return oldValue.CanceledAt, nil
}
// ClearCanceledAt clears the value of the "canceled_at" field.
func (m *UsageCleanupTaskMutation) ClearCanceledAt() {
m.canceled_at = nil
m.clearedFields[usagecleanuptask.FieldCanceledAt] = struct{}{}
}
// CanceledAtCleared returns if the "canceled_at" field was cleared in this mutation.
func (m *UsageCleanupTaskMutation) CanceledAtCleared() bool {
_, ok := m.clearedFields[usagecleanuptask.FieldCanceledAt]
return ok
}
// ResetCanceledAt resets all changes to the "canceled_at" field.
func (m *UsageCleanupTaskMutation) ResetCanceledAt() {
m.canceled_at = nil
delete(m.clearedFields, usagecleanuptask.FieldCanceledAt)
}
// SetStartedAt sets the "started_at" field.
func (m *UsageCleanupTaskMutation) SetStartedAt(t time.Time) {
m.started_at = &t
}
// StartedAt returns the value of the "started_at" field in the mutation.
func (m *UsageCleanupTaskMutation) StartedAt() (r time.Time, exists bool) {
v := m.started_at
if v == nil {
return
}
return *v, true
}
// OldStartedAt returns the old "started_at" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldStartedAt(ctx context.Context) (v *time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldStartedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldStartedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldStartedAt: %w", err)
}
return oldValue.StartedAt, nil
}
// ClearStartedAt clears the value of the "started_at" field.
func (m *UsageCleanupTaskMutation) ClearStartedAt() {
m.started_at = nil
m.clearedFields[usagecleanuptask.FieldStartedAt] = struct{}{}
}
// StartedAtCleared returns if the "started_at" field was cleared in this mutation.
func (m *UsageCleanupTaskMutation) StartedAtCleared() bool {
_, ok := m.clearedFields[usagecleanuptask.FieldStartedAt]
return ok
}
// ResetStartedAt resets all changes to the "started_at" field.
func (m *UsageCleanupTaskMutation) ResetStartedAt() {
m.started_at = nil
delete(m.clearedFields, usagecleanuptask.FieldStartedAt)
}
// SetFinishedAt sets the "finished_at" field.
func (m *UsageCleanupTaskMutation) SetFinishedAt(t time.Time) {
m.finished_at = &t
}
// FinishedAt returns the value of the "finished_at" field in the mutation.
func (m *UsageCleanupTaskMutation) FinishedAt() (r time.Time, exists bool) {
v := m.finished_at
if v == nil {
return
}
return *v, true
}
// OldFinishedAt returns the old "finished_at" field's value of the UsageCleanupTask entity.
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageCleanupTaskMutation) OldFinishedAt(ctx context.Context) (v *time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldFinishedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldFinishedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldFinishedAt: %w", err)
}
return oldValue.FinishedAt, nil
}
// ClearFinishedAt clears the value of the "finished_at" field.
func (m *UsageCleanupTaskMutation) ClearFinishedAt() {
m.finished_at = nil
m.clearedFields[usagecleanuptask.FieldFinishedAt] = struct{}{}
}
// FinishedAtCleared returns if the "finished_at" field was cleared in this mutation.
func (m *UsageCleanupTaskMutation) FinishedAtCleared() bool {
_, ok := m.clearedFields[usagecleanuptask.FieldFinishedAt]
return ok
}
// ResetFinishedAt resets all changes to the "finished_at" field.
func (m *UsageCleanupTaskMutation) ResetFinishedAt() {
m.finished_at = nil
delete(m.clearedFields, usagecleanuptask.FieldFinishedAt)
}
// Where appends a list predicates to the UsageCleanupTaskMutation builder.
func (m *UsageCleanupTaskMutation) Where(ps ...predicate.UsageCleanupTask) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the UsageCleanupTaskMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *UsageCleanupTaskMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.UsageCleanupTask, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *UsageCleanupTaskMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *UsageCleanupTaskMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (UsageCleanupTask).
func (m *UsageCleanupTaskMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UsageCleanupTaskMutation) Fields() []string {
fields := make([]string, 0, 11)
if m.created_at != nil {
fields = append(fields, usagecleanuptask.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, usagecleanuptask.FieldUpdatedAt)
}
if m.status != nil {
fields = append(fields, usagecleanuptask.FieldStatus)
}
if m.filters != nil {
fields = append(fields, usagecleanuptask.FieldFilters)
}
if m.created_by != nil {
fields = append(fields, usagecleanuptask.FieldCreatedBy)
}
if m.deleted_rows != nil {
fields = append(fields, usagecleanuptask.FieldDeletedRows)
}
if m.error_message != nil {
fields = append(fields, usagecleanuptask.FieldErrorMessage)
}
if m.canceled_by != nil {
fields = append(fields, usagecleanuptask.FieldCanceledBy)
}
if m.canceled_at != nil {
fields = append(fields, usagecleanuptask.FieldCanceledAt)
}
if m.started_at != nil {
fields = append(fields, usagecleanuptask.FieldStartedAt)
}
if m.finished_at != nil {
fields = append(fields, usagecleanuptask.FieldFinishedAt)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *UsageCleanupTaskMutation) Field(name string) (ent.Value, bool) {
switch name {
case usagecleanuptask.FieldCreatedAt:
return m.CreatedAt()
case usagecleanuptask.FieldUpdatedAt:
return m.UpdatedAt()
case usagecleanuptask.FieldStatus:
return m.Status()
case usagecleanuptask.FieldFilters:
return m.Filters()
case usagecleanuptask.FieldCreatedBy:
return m.CreatedBy()
case usagecleanuptask.FieldDeletedRows:
return m.DeletedRows()
case usagecleanuptask.FieldErrorMessage:
return m.ErrorMessage()
case usagecleanuptask.FieldCanceledBy:
return m.CanceledBy()
case usagecleanuptask.FieldCanceledAt:
return m.CanceledAt()
case usagecleanuptask.FieldStartedAt:
return m.StartedAt()
case usagecleanuptask.FieldFinishedAt:
return m.FinishedAt()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *UsageCleanupTaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case usagecleanuptask.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case usagecleanuptask.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
case usagecleanuptask.FieldStatus:
return m.OldStatus(ctx)
case usagecleanuptask.FieldFilters:
return m.OldFilters(ctx)
case usagecleanuptask.FieldCreatedBy:
return m.OldCreatedBy(ctx)
case usagecleanuptask.FieldDeletedRows:
return m.OldDeletedRows(ctx)
case usagecleanuptask.FieldErrorMessage:
return m.OldErrorMessage(ctx)
case usagecleanuptask.FieldCanceledBy:
return m.OldCanceledBy(ctx)
case usagecleanuptask.FieldCanceledAt:
return m.OldCanceledAt(ctx)
case usagecleanuptask.FieldStartedAt:
return m.OldStartedAt(ctx)
case usagecleanuptask.FieldFinishedAt:
return m.OldFinishedAt(ctx)
}
return nil, fmt.Errorf("unknown UsageCleanupTask field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *UsageCleanupTaskMutation) SetField(name string, value ent.Value) error {
switch name {
case usagecleanuptask.FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case usagecleanuptask.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
case usagecleanuptask.FieldStatus:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetStatus(v)
return nil
case usagecleanuptask.FieldFilters:
v, ok := value.(json.RawMessage)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetFilters(v)
return nil
case usagecleanuptask.FieldCreatedBy:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedBy(v)
return nil
case usagecleanuptask.FieldDeletedRows:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDeletedRows(v)
return nil
case usagecleanuptask.FieldErrorMessage:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetErrorMessage(v)
return nil
case usagecleanuptask.FieldCanceledBy:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCanceledBy(v)
return nil
case usagecleanuptask.FieldCanceledAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCanceledAt(v)
return nil
case usagecleanuptask.FieldStartedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetStartedAt(v)
return nil
case usagecleanuptask.FieldFinishedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetFinishedAt(v)
return nil
}
return fmt.Errorf("unknown UsageCleanupTask field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *UsageCleanupTaskMutation) AddedFields() []string {
var fields []string
if m.addcreated_by != nil {
fields = append(fields, usagecleanuptask.FieldCreatedBy)
}
if m.adddeleted_rows != nil {
fields = append(fields, usagecleanuptask.FieldDeletedRows)
}
if m.addcanceled_by != nil {
fields = append(fields, usagecleanuptask.FieldCanceledBy)
}
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *UsageCleanupTaskMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case usagecleanuptask.FieldCreatedBy:
return m.AddedCreatedBy()
case usagecleanuptask.FieldDeletedRows:
return m.AddedDeletedRows()
case usagecleanuptask.FieldCanceledBy:
return m.AddedCanceledBy()
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *UsageCleanupTaskMutation) AddField(name string, value ent.Value) error {
switch name {
case usagecleanuptask.FieldCreatedBy:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCreatedBy(v)
return nil
case usagecleanuptask.FieldDeletedRows:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddDeletedRows(v)
return nil
case usagecleanuptask.FieldCanceledBy:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCanceledBy(v)
return nil
}
return fmt.Errorf("unknown UsageCleanupTask numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *UsageCleanupTaskMutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(usagecleanuptask.FieldErrorMessage) {
fields = append(fields, usagecleanuptask.FieldErrorMessage)
}
if m.FieldCleared(usagecleanuptask.FieldCanceledBy) {
fields = append(fields, usagecleanuptask.FieldCanceledBy)
}
if m.FieldCleared(usagecleanuptask.FieldCanceledAt) {
fields = append(fields, usagecleanuptask.FieldCanceledAt)
}
if m.FieldCleared(usagecleanuptask.FieldStartedAt) {
fields = append(fields, usagecleanuptask.FieldStartedAt)
}
if m.FieldCleared(usagecleanuptask.FieldFinishedAt) {
fields = append(fields, usagecleanuptask.FieldFinishedAt)
}
return fields
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *UsageCleanupTaskMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *UsageCleanupTaskMutation) ClearField(name string) error {
switch name {
case usagecleanuptask.FieldErrorMessage:
m.ClearErrorMessage()
return nil
case usagecleanuptask.FieldCanceledBy:
m.ClearCanceledBy()
return nil
case usagecleanuptask.FieldCanceledAt:
m.ClearCanceledAt()
return nil
case usagecleanuptask.FieldStartedAt:
m.ClearStartedAt()
return nil
case usagecleanuptask.FieldFinishedAt:
m.ClearFinishedAt()
return nil
}
return fmt.Errorf("unknown UsageCleanupTask nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *UsageCleanupTaskMutation) ResetField(name string) error {
switch name {
case usagecleanuptask.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case usagecleanuptask.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
case usagecleanuptask.FieldStatus:
m.ResetStatus()
return nil
case usagecleanuptask.FieldFilters:
m.ResetFilters()
return nil
case usagecleanuptask.FieldCreatedBy:
m.ResetCreatedBy()
return nil
case usagecleanuptask.FieldDeletedRows:
m.ResetDeletedRows()
return nil
case usagecleanuptask.FieldErrorMessage:
m.ResetErrorMessage()
return nil
case usagecleanuptask.FieldCanceledBy:
m.ResetCanceledBy()
return nil
case usagecleanuptask.FieldCanceledAt:
m.ResetCanceledAt()
return nil
case usagecleanuptask.FieldStartedAt:
m.ResetStartedAt()
return nil
case usagecleanuptask.FieldFinishedAt:
m.ResetFinishedAt()
return nil
}
return fmt.Errorf("unknown UsageCleanupTask field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *UsageCleanupTaskMutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *UsageCleanupTaskMutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *UsageCleanupTaskMutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *UsageCleanupTaskMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *UsageCleanupTaskMutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *UsageCleanupTaskMutation) EdgeCleared(name string) bool {
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *UsageCleanupTaskMutation) ClearEdge(name string) error {
return fmt.Errorf("unknown UsageCleanupTask unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *UsageCleanupTaskMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown UsageCleanupTask edge %s", name)
}
// UsageLogMutation represents an operation that mutates the UsageLog nodes in the graph.
type UsageLogMutation struct {
config
...
...
@@ -13274,6 +14360,9 @@ type UserMutation struct {
status *string
username *string
notes *string
totp_secret_encrypted *string
totp_enabled *bool
totp_enabled_at *time.Time
clearedFields map[string]struct{}
api_keys map[int64]struct{}
removedapi_keys map[int64]struct{}
...
...
@@ -13851,6 +14940,140 @@ func (m *UserMutation) ResetNotes() {
m.notes = nil
}
// SetTotpSecretEncrypted sets the "totp_secret_encrypted" field.
func (m *UserMutation) SetTotpSecretEncrypted(s string) {
m.totp_secret_encrypted = &s
}
// TotpSecretEncrypted returns the value of the "totp_secret_encrypted" field in the mutation.
func (m *UserMutation) TotpSecretEncrypted() (r string, exists bool) {
v := m.totp_secret_encrypted
if v == nil {
return
}
return *v, true
}
// OldTotpSecretEncrypted returns the old "totp_secret_encrypted" field's value of the User entity.
// If the User object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserMutation) OldTotpSecretEncrypted(ctx context.Context) (v *string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldTotpSecretEncrypted is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldTotpSecretEncrypted requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTotpSecretEncrypted: %w", err)
}
return oldValue.TotpSecretEncrypted, nil
}
// ClearTotpSecretEncrypted clears the value of the "totp_secret_encrypted" field.
func (m *UserMutation) ClearTotpSecretEncrypted() {
m.totp_secret_encrypted = nil
m.clearedFields[user.FieldTotpSecretEncrypted] = struct{}{}
}
// TotpSecretEncryptedCleared returns if the "totp_secret_encrypted" field was cleared in this mutation.
func (m *UserMutation) TotpSecretEncryptedCleared() bool {
_, ok := m.clearedFields[user.FieldTotpSecretEncrypted]
return ok
}
// ResetTotpSecretEncrypted resets all changes to the "totp_secret_encrypted" field.
func (m *UserMutation) ResetTotpSecretEncrypted() {
m.totp_secret_encrypted = nil
delete(m.clearedFields, user.FieldTotpSecretEncrypted)
}
// SetTotpEnabled sets the "totp_enabled" field.
func (m *UserMutation) SetTotpEnabled(b bool) {
m.totp_enabled = &b
}
// TotpEnabled returns the value of the "totp_enabled" field in the mutation.
func (m *UserMutation) TotpEnabled() (r bool, exists bool) {
v := m.totp_enabled
if v == nil {
return
}
return *v, true
}
// OldTotpEnabled returns the old "totp_enabled" field's value of the User entity.
// If the User object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserMutation) OldTotpEnabled(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldTotpEnabled is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldTotpEnabled requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTotpEnabled: %w", err)
}
return oldValue.TotpEnabled, nil
}
// ResetTotpEnabled resets all changes to the "totp_enabled" field.
func (m *UserMutation) ResetTotpEnabled() {
m.totp_enabled = nil
}
// SetTotpEnabledAt sets the "totp_enabled_at" field.
func (m *UserMutation) SetTotpEnabledAt(t time.Time) {
m.totp_enabled_at = &t
}
// TotpEnabledAt returns the value of the "totp_enabled_at" field in the mutation.
func (m *UserMutation) TotpEnabledAt() (r time.Time, exists bool) {
v := m.totp_enabled_at
if v == nil {
return
}
return *v, true
}
// OldTotpEnabledAt returns the old "totp_enabled_at" field's value of the User entity.
// If the User object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserMutation) OldTotpEnabledAt(ctx context.Context) (v *time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldTotpEnabledAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldTotpEnabledAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTotpEnabledAt: %w", err)
}
return oldValue.TotpEnabledAt, nil
}
// ClearTotpEnabledAt clears the value of the "totp_enabled_at" field.
func (m *UserMutation) ClearTotpEnabledAt() {
m.totp_enabled_at = nil
m.clearedFields[user.FieldTotpEnabledAt] = struct{}{}
}
// TotpEnabledAtCleared returns if the "totp_enabled_at" field was cleared in this mutation.
func (m *UserMutation) TotpEnabledAtCleared() bool {
_, ok := m.clearedFields[user.FieldTotpEnabledAt]
return ok
}
// ResetTotpEnabledAt resets all changes to the "totp_enabled_at" field.
func (m *UserMutation) ResetTotpEnabledAt() {
m.totp_enabled_at = nil
delete(m.clearedFields, user.FieldTotpEnabledAt)
}
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by ids.
func (m *UserMutation) AddAPIKeyIDs(ids ...int64) {
if m.api_keys == nil {
...
...
@@ -14317,7 +15540,7 @@ func (m *UserMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UserMutation) Fields() []string {
fields := make([]string, 0, 1
1
)
fields := make([]string, 0, 1
4
)
if m.created_at != nil {
fields = append(fields, user.FieldCreatedAt)
}
...
...
@@ -14351,6 +15574,15 @@ func (m *UserMutation) Fields() []string {
if m.notes != nil {
fields = append(fields, user.FieldNotes)
}
if m.totp_secret_encrypted != nil {
fields = append(fields, user.FieldTotpSecretEncrypted)
}
if m.totp_enabled != nil {
fields = append(fields, user.FieldTotpEnabled)
}
if m.totp_enabled_at != nil {
fields = append(fields, user.FieldTotpEnabledAt)
}
return fields
}
...
...
@@ -14381,6 +15613,12 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) {
return m.Username()
case user.FieldNotes:
return m.Notes()
case user.FieldTotpSecretEncrypted:
return m.TotpSecretEncrypted()
case user.FieldTotpEnabled:
return m.TotpEnabled()
case user.FieldTotpEnabledAt:
return m.TotpEnabledAt()
}
return nil, false
}
...
...
@@ -14412,6 +15650,12 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er
return m.OldUsername(ctx)
case user.FieldNotes:
return m.OldNotes(ctx)
case user.FieldTotpSecretEncrypted:
return m.OldTotpSecretEncrypted(ctx)
case user.FieldTotpEnabled:
return m.OldTotpEnabled(ctx)
case user.FieldTotpEnabledAt:
return m.OldTotpEnabledAt(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}
...
...
@@ -14498,6 +15742,27 @@ func (m *UserMutation) SetField(name string, value ent.Value) error {
}
m.SetNotes(v)
return nil
case user.FieldTotpSecretEncrypted:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTotpSecretEncrypted(v)
return nil
case user.FieldTotpEnabled:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTotpEnabled(v)
return nil
case user.FieldTotpEnabledAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTotpEnabledAt(v)
return nil
}
return fmt.Errorf("unknown User field %s", name)
}
...
...
@@ -14558,6 +15823,12 @@ func (m *UserMutation) ClearedFields() []string {
if m.FieldCleared(user.FieldDeletedAt) {
fields = append(fields, user.FieldDeletedAt)
}
if m.FieldCleared(user.FieldTotpSecretEncrypted) {
fields = append(fields, user.FieldTotpSecretEncrypted)
}
if m.FieldCleared(user.FieldTotpEnabledAt) {
fields = append(fields, user.FieldTotpEnabledAt)
}
return fields
}
...
...
@@ -14575,6 +15846,12 @@ func (m *UserMutation) ClearField(name string) error {
case user.FieldDeletedAt:
m.ClearDeletedAt()
return nil
case user.FieldTotpSecretEncrypted:
m.ClearTotpSecretEncrypted()
return nil
case user.FieldTotpEnabledAt:
m.ClearTotpEnabledAt()
return nil
}
return fmt.Errorf("unknown User nullable field %s", name)
}
...
...
@@ -14616,6 +15893,15 @@ func (m *UserMutation) ResetField(name string) error {
case user.FieldNotes:
m.ResetNotes()
return nil
case user.FieldTotpSecretEncrypted:
m.ResetTotpSecretEncrypted()
return nil
case user.FieldTotpEnabled:
m.ResetTotpEnabled()
return nil
case user.FieldTotpEnabledAt:
m.ResetTotpEnabledAt()
return nil
}
return fmt.Errorf("unknown User field %s", name)
}
...
...
backend/ent/predicate/predicate.go
View file @
2fe8932c
...
...
@@ -33,6 +33,9 @@ type RedeemCode func(*sql.Selector)
// Setting is the predicate function for setting builders.
type
Setting
func
(
*
sql
.
Selector
)
// UsageCleanupTask is the predicate function for usagecleanuptask builders.
type
UsageCleanupTask
func
(
*
sql
.
Selector
)
// UsageLog is the predicate function for usagelog builders.
type
UsageLog
func
(
*
sql
.
Selector
)
...
...
backend/ent/runtime/runtime.go
View file @
2fe8932c
...
...
@@ -15,6 +15,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/schema"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
...
...
@@ -495,6 +496,43 @@ func init() {
setting
.
DefaultUpdatedAt
=
settingDescUpdatedAt
.
Default
.
(
func
()
time
.
Time
)
// setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
setting
.
UpdateDefaultUpdatedAt
=
settingDescUpdatedAt
.
UpdateDefault
.
(
func
()
time
.
Time
)
usagecleanuptaskMixin
:=
schema
.
UsageCleanupTask
{}
.
Mixin
()
usagecleanuptaskMixinFields0
:=
usagecleanuptaskMixin
[
0
]
.
Fields
()
_
=
usagecleanuptaskMixinFields0
usagecleanuptaskFields
:=
schema
.
UsageCleanupTask
{}
.
Fields
()
_
=
usagecleanuptaskFields
// usagecleanuptaskDescCreatedAt is the schema descriptor for created_at field.
usagecleanuptaskDescCreatedAt
:=
usagecleanuptaskMixinFields0
[
0
]
.
Descriptor
()
// usagecleanuptask.DefaultCreatedAt holds the default value on creation for the created_at field.
usagecleanuptask
.
DefaultCreatedAt
=
usagecleanuptaskDescCreatedAt
.
Default
.
(
func
()
time
.
Time
)
// usagecleanuptaskDescUpdatedAt is the schema descriptor for updated_at field.
usagecleanuptaskDescUpdatedAt
:=
usagecleanuptaskMixinFields0
[
1
]
.
Descriptor
()
// usagecleanuptask.DefaultUpdatedAt holds the default value on creation for the updated_at field.
usagecleanuptask
.
DefaultUpdatedAt
=
usagecleanuptaskDescUpdatedAt
.
Default
.
(
func
()
time
.
Time
)
// usagecleanuptask.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
usagecleanuptask
.
UpdateDefaultUpdatedAt
=
usagecleanuptaskDescUpdatedAt
.
UpdateDefault
.
(
func
()
time
.
Time
)
// usagecleanuptaskDescStatus is the schema descriptor for status field.
usagecleanuptaskDescStatus
:=
usagecleanuptaskFields
[
0
]
.
Descriptor
()
// usagecleanuptask.StatusValidator is a validator for the "status" field. It is called by the builders before save.
usagecleanuptask
.
StatusValidator
=
func
()
func
(
string
)
error
{
validators
:=
usagecleanuptaskDescStatus
.
Validators
fns
:=
[
...
]
func
(
string
)
error
{
validators
[
0
]
.
(
func
(
string
)
error
),
validators
[
1
]
.
(
func
(
string
)
error
),
}
return
func
(
status
string
)
error
{
for
_
,
fn
:=
range
fns
{
if
err
:=
fn
(
status
);
err
!=
nil
{
return
err
}
}
return
nil
}
}()
// usagecleanuptaskDescDeletedRows is the schema descriptor for deleted_rows field.
usagecleanuptaskDescDeletedRows
:=
usagecleanuptaskFields
[
3
]
.
Descriptor
()
// usagecleanuptask.DefaultDeletedRows holds the default value on creation for the deleted_rows field.
usagecleanuptask
.
DefaultDeletedRows
=
usagecleanuptaskDescDeletedRows
.
Default
.
(
int64
)
usagelogFields
:=
schema
.
UsageLog
{}
.
Fields
()
_
=
usagelogFields
// usagelogDescRequestID is the schema descriptor for request_id field.
...
...
@@ -698,6 +736,10 @@ func init() {
userDescNotes
:=
userFields
[
7
]
.
Descriptor
()
// user.DefaultNotes holds the default value on creation for the notes field.
user
.
DefaultNotes
=
userDescNotes
.
Default
.
(
string
)
// userDescTotpEnabled is the schema descriptor for totp_enabled field.
userDescTotpEnabled
:=
userFields
[
9
]
.
Descriptor
()
// user.DefaultTotpEnabled holds the default value on creation for the totp_enabled field.
user
.
DefaultTotpEnabled
=
userDescTotpEnabled
.
Default
.
(
bool
)
userallowedgroupFields
:=
schema
.
UserAllowedGroup
{}
.
Fields
()
_
=
userallowedgroupFields
// userallowedgroupDescCreatedAt is the schema descriptor for created_at field.
...
...
backend/ent/schema/mixins/soft_delete.go
View file @
2fe8932c
...
...
@@ -5,6 +5,7 @@ package mixins
import
(
"context"
"fmt"
"reflect"
"time"
"entgo.io/ent"
...
...
@@ -12,7 +13,6 @@ import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
dbent
"github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/ent/intercept"
)
...
...
@@ -113,7 +113,6 @@ func (d SoftDeleteMixin) Hooks() []ent.Hook {
SetOp
(
ent
.
Op
)
SetDeletedAt
(
time
.
Time
)
WhereP
(
...
func
(
*
sql
.
Selector
))
Client
()
*
dbent
.
Client
})
if
!
ok
{
return
nil
,
fmt
.
Errorf
(
"unexpected mutation type %T"
,
m
)
...
...
@@ -124,7 +123,7 @@ func (d SoftDeleteMixin) Hooks() []ent.Hook {
mx
.
SetOp
(
ent
.
OpUpdate
)
// 设置删除时间为当前时间
mx
.
SetDeletedAt
(
time
.
Now
())
return
m
x
.
Client
()
.
Mutate
(
ctx
,
m
)
return
m
utateWithClient
(
ctx
,
m
,
next
)
})
},
}
...
...
@@ -137,3 +136,41 @@ func (d SoftDeleteMixin) applyPredicate(w interface{ WhereP(...func(*sql.Selecto
sql
.
FieldIsNull
(
d
.
Fields
()[
0
]
.
Descriptor
()
.
Name
),
)
}
func
mutateWithClient
(
ctx
context
.
Context
,
m
ent
.
Mutation
,
fallback
ent
.
Mutator
)
(
ent
.
Value
,
error
)
{
clientMethod
:=
reflect
.
ValueOf
(
m
)
.
MethodByName
(
"Client"
)
if
!
clientMethod
.
IsValid
()
||
clientMethod
.
Type
()
.
NumIn
()
!=
0
||
clientMethod
.
Type
()
.
NumOut
()
!=
1
{
return
nil
,
fmt
.
Errorf
(
"soft delete: mutation client method not found for %T"
,
m
)
}
client
:=
clientMethod
.
Call
(
nil
)[
0
]
mutateMethod
:=
client
.
MethodByName
(
"Mutate"
)
if
!
mutateMethod
.
IsValid
()
{
return
nil
,
fmt
.
Errorf
(
"soft delete: mutation client missing Mutate for %T"
,
m
)
}
if
mutateMethod
.
Type
()
.
NumIn
()
!=
2
||
mutateMethod
.
Type
()
.
NumOut
()
!=
2
{
return
nil
,
fmt
.
Errorf
(
"soft delete: mutation client signature mismatch for %T"
,
m
)
}
results
:=
mutateMethod
.
Call
([]
reflect
.
Value
{
reflect
.
ValueOf
(
ctx
),
reflect
.
ValueOf
(
m
)})
value
:=
results
[
0
]
.
Interface
()
var
err
error
if
!
results
[
1
]
.
IsNil
()
{
errValue
:=
results
[
1
]
.
Interface
()
typedErr
,
ok
:=
errValue
.
(
error
)
if
!
ok
{
return
nil
,
fmt
.
Errorf
(
"soft delete: unexpected error type %T for %T"
,
errValue
,
m
)
}
err
=
typedErr
}
if
err
!=
nil
{
return
nil
,
err
}
if
value
==
nil
{
return
nil
,
fmt
.
Errorf
(
"soft delete: mutation client returned nil for %T"
,
m
)
}
v
,
ok
:=
value
.
(
ent
.
Value
)
if
!
ok
{
return
nil
,
fmt
.
Errorf
(
"soft delete: unexpected value type %T for %T"
,
value
,
m
)
}
return
v
,
nil
}
backend/ent/schema/usage_cleanup_task.go
0 → 100644
View file @
2fe8932c
package
schema
import
(
"encoding/json"
"fmt"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// UsageCleanupTask 定义使用记录清理任务的 schema。
type
UsageCleanupTask
struct
{
ent
.
Schema
}
func
(
UsageCleanupTask
)
Annotations
()
[]
schema
.
Annotation
{
return
[]
schema
.
Annotation
{
entsql
.
Annotation
{
Table
:
"usage_cleanup_tasks"
},
}
}
func
(
UsageCleanupTask
)
Mixin
()
[]
ent
.
Mixin
{
return
[]
ent
.
Mixin
{
mixins
.
TimeMixin
{},
}
}
func
(
UsageCleanupTask
)
Fields
()
[]
ent
.
Field
{
return
[]
ent
.
Field
{
field
.
String
(
"status"
)
.
MaxLen
(
20
)
.
Validate
(
validateUsageCleanupStatus
),
field
.
JSON
(
"filters"
,
json
.
RawMessage
{}),
field
.
Int64
(
"created_by"
),
field
.
Int64
(
"deleted_rows"
)
.
Default
(
0
),
field
.
String
(
"error_message"
)
.
Optional
()
.
Nillable
(),
field
.
Int64
(
"canceled_by"
)
.
Optional
()
.
Nillable
(),
field
.
Time
(
"canceled_at"
)
.
Optional
()
.
Nillable
(),
field
.
Time
(
"started_at"
)
.
Optional
()
.
Nillable
(),
field
.
Time
(
"finished_at"
)
.
Optional
()
.
Nillable
(),
}
}
func
(
UsageCleanupTask
)
Indexes
()
[]
ent
.
Index
{
return
[]
ent
.
Index
{
index
.
Fields
(
"status"
,
"created_at"
),
index
.
Fields
(
"created_at"
),
index
.
Fields
(
"canceled_at"
),
}
}
func
validateUsageCleanupStatus
(
status
string
)
error
{
switch
status
{
case
"pending"
,
"running"
,
"succeeded"
,
"failed"
,
"canceled"
:
return
nil
default
:
return
fmt
.
Errorf
(
"invalid usage cleanup status: %s"
,
status
)
}
}
backend/ent/schema/user.go
View file @
2fe8932c
...
...
@@ -61,6 +61,17 @@ func (User) Fields() []ent.Field {
field
.
String
(
"notes"
)
.
SchemaType
(
map
[
string
]
string
{
dialect
.
Postgres
:
"text"
})
.
Default
(
""
),
// TOTP 双因素认证字段
field
.
String
(
"totp_secret_encrypted"
)
.
SchemaType
(
map
[
string
]
string
{
dialect
.
Postgres
:
"text"
})
.
Optional
()
.
Nillable
(),
field
.
Bool
(
"totp_enabled"
)
.
Default
(
false
),
field
.
Time
(
"totp_enabled_at"
)
.
Optional
()
.
Nillable
(),
}
}
...
...
Prev
1
2
3
4
5
…
14
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment