Commit 13262a56 authored by yangjianbo's avatar yangjianbo
Browse files

feat(sora): 新增 Sora 平台支持并修复高危安全和性能问题



新增功能:
- 新增 Sora 账号管理和 OAuth 认证
- 新增 Sora 视频/图片生成 API 网关
- 新增 Sora 任务调度和缓存机制
- 新增 Sora 使用统计和计费支持
- 前端增加 Sora 平台配置界面

安全修复(代码审核):
- [SEC-001] 限制媒体下载响应体大小(图片 20MB、视频 200MB),防止 DoS 攻击
- [SEC-002] 限制 SDK API 响应大小(1MB),防止内存耗尽
- [SEC-003] 修复 SSRF 风险,添加 URL 验证并强制使用代理配置

BUG 修复(代码审核):
- [BUG-001] 修复 for 循环内 defer 累积导致的资源泄漏
- [BUG-002] 修复图片并发槽位获取失败时已持有锁未释放的永久泄漏

性能优化(代码审核):
- [PERF-001] 添加 Sentinel Token 缓存(3 分钟有效期),减少 PoW 计算开销

技术细节:
- 使用 io.LimitReader 限制所有外部输入的大小
- 添加 urlvalidator 验证防止 SSRF 攻击
- 使用 sync.Map 实现线程安全的包级缓存
- 优化并发槽位管理,添加 releaseAll 模式防止泄漏

影响范围:
- 后端:新增 Sora 相关数据模型、服务、网关和管理接口
- 前端:新增 Sora 平台配置、账号管理和监控界面
- 配置:新增 Sora 相关配置项和环境变量
Co-Authored-By: default avatarClaude Sonnet 4.5 <noreply@anthropic.com>
parent bece1b52
...@@ -69,6 +69,8 @@ func provideCleanup( ...@@ -69,6 +69,8 @@ func provideCleanup(
opsScheduledReport *service.OpsScheduledReportService, opsScheduledReport *service.OpsScheduledReportService,
schedulerSnapshot *service.SchedulerSnapshotService, schedulerSnapshot *service.SchedulerSnapshotService,
tokenRefresh *service.TokenRefreshService, tokenRefresh *service.TokenRefreshService,
soraTokenRefresh *service.SoraTokenRefreshService,
soraCacheCleanup *service.SoraCacheCleanupService,
accountExpiry *service.AccountExpiryService, accountExpiry *service.AccountExpiryService,
usageCleanup *service.UsageCleanupService, usageCleanup *service.UsageCleanupService,
pricing *service.PricingService, pricing *service.PricingService,
...@@ -134,6 +136,18 @@ func provideCleanup( ...@@ -134,6 +136,18 @@ func provideCleanup(
tokenRefresh.Stop() tokenRefresh.Stop()
return nil return nil
}}, }},
{"SoraTokenRefreshService", func() error {
if soraTokenRefresh != nil {
soraTokenRefresh.Stop()
}
return nil
}},
{"SoraCacheCleanupService", func() error {
if soraCacheCleanup != nil {
soraCacheCleanup.Stop()
}
return nil
}},
{"AccountExpiryService", func() error { {"AccountExpiryService", func() error {
accountExpiry.Stop() accountExpiry.Stop()
return nil return nil
......
...@@ -129,6 +129,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -129,6 +129,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
proxyHandler := admin.NewProxyHandler(adminService) proxyHandler := admin.NewProxyHandler(adminService)
adminRedeemHandler := admin.NewRedeemHandler(adminService) adminRedeemHandler := admin.NewRedeemHandler(adminService)
promoHandler := admin.NewPromoHandler(promoService) promoHandler := admin.NewPromoHandler(promoService)
soraAccountRepository := repository.NewSoraAccountRepository(client)
soraUsageStatRepository := repository.NewSoraUsageStatRepository(client, db)
soraAccountHandler := admin.NewSoraAccountHandler(adminService, soraAccountRepository, soraUsageStatRepository)
opsRepository := repository.NewOpsRepository(db) opsRepository := repository.NewOpsRepository(db)
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db) schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig) schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
...@@ -161,11 +164,16 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -161,11 +164,16 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
userAttributeValueRepository := repository.NewUserAttributeValueRepository(client) userAttributeValueRepository := repository.NewUserAttributeValueRepository(client)
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository) userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
userAttributeHandler := admin.NewUserAttributeHandler(userAttributeService) userAttributeHandler := admin.NewUserAttributeHandler(userAttributeService)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler) adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, soraAccountHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler)
gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, configConfig) gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, configConfig)
openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, configConfig) openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, configConfig)
soraTaskRepository := repository.NewSoraTaskRepository(client)
soraCacheFileRepository := repository.NewSoraCacheFileRepository(client)
soraCacheService := service.NewSoraCacheService(configConfig, soraCacheFileRepository, settingService, accountRepository, httpUpstream)
soraGatewayService := service.NewSoraGatewayService(accountRepository, soraAccountRepository, soraUsageStatRepository, soraTaskRepository, soraCacheService, settingService, concurrencyService, configConfig, httpUpstream)
soraGatewayHandler := handler.NewSoraGatewayHandler(gatewayService, soraGatewayService, concurrencyService, billingCacheService, configConfig)
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo) handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo)
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler) handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, soraGatewayHandler, handlerSettingHandler)
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService) jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService)
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService) adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService)
apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig) apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig)
...@@ -177,8 +185,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -177,8 +185,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig) opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig)
opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig) opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, compositeTokenCacheInvalidator, configConfig) tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, compositeTokenCacheInvalidator, configConfig)
soraTokenRefreshService := service.ProvideSoraTokenRefreshService(accountRepository, soraAccountRepository, settingService, httpUpstream, configConfig)
soraCacheCleanupService := service.ProvideSoraCacheCleanupService(soraCacheFileRepository, settingService, configConfig)
accountExpiryService := service.ProvideAccountExpiryService(accountRepository) accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, schedulerSnapshotService, tokenRefreshService, accountExpiryService, usageCleanupService, pricingService, emailQueueService, billingCacheService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService) v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, schedulerSnapshotService, tokenRefreshService, soraTokenRefreshService, soraCacheCleanupService, accountExpiryService, usageCleanupService, pricingService, emailQueueService, billingCacheService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService)
application := &Application{ application := &Application{
Server: httpServer, Server: httpServer,
Cleanup: v, Cleanup: v,
...@@ -210,6 +220,8 @@ func provideCleanup( ...@@ -210,6 +220,8 @@ func provideCleanup(
opsScheduledReport *service.OpsScheduledReportService, opsScheduledReport *service.OpsScheduledReportService,
schedulerSnapshot *service.SchedulerSnapshotService, schedulerSnapshot *service.SchedulerSnapshotService,
tokenRefresh *service.TokenRefreshService, tokenRefresh *service.TokenRefreshService,
soraTokenRefresh *service.SoraTokenRefreshService,
soraCacheCleanup *service.SoraCacheCleanupService,
accountExpiry *service.AccountExpiryService, accountExpiry *service.AccountExpiryService,
usageCleanup *service.UsageCleanupService, usageCleanup *service.UsageCleanupService,
pricing *service.PricingService, pricing *service.PricingService,
...@@ -274,6 +286,18 @@ func provideCleanup( ...@@ -274,6 +286,18 @@ func provideCleanup(
tokenRefresh.Stop() tokenRefresh.Stop()
return nil return nil
}}, }},
{"SoraTokenRefreshService", func() error {
if soraTokenRefresh != nil {
soraTokenRefresh.Stop()
}
return nil
}},
{"SoraCacheCleanupService", func() error {
if soraCacheCleanup != nil {
soraCacheCleanup.Stop()
}
return nil
}},
{"AccountExpiryService", func() error { {"AccountExpiryService", func() error {
accountExpiry.Stop() accountExpiry.Stop()
return nil return nil
......
This diff is collapsed.
...@@ -21,6 +21,10 @@ import ( ...@@ -21,6 +21,10 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode" "github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/soraaccount"
"github.com/Wei-Shaw/sub2api/ent/soracachefile"
"github.com/Wei-Shaw/sub2api/ent/soratask"
"github.com/Wei-Shaw/sub2api/ent/sorausagestat"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
...@@ -97,6 +101,10 @@ func checkColumn(t, c string) error { ...@@ -97,6 +101,10 @@ func checkColumn(t, c string) error {
proxy.Table: proxy.ValidColumn, proxy.Table: proxy.ValidColumn,
redeemcode.Table: redeemcode.ValidColumn, redeemcode.Table: redeemcode.ValidColumn,
setting.Table: setting.ValidColumn, setting.Table: setting.ValidColumn,
soraaccount.Table: soraaccount.ValidColumn,
soracachefile.Table: soracachefile.ValidColumn,
soratask.Table: soratask.ValidColumn,
sorausagestat.Table: sorausagestat.ValidColumn,
usagecleanuptask.Table: usagecleanuptask.ValidColumn, usagecleanuptask.Table: usagecleanuptask.ValidColumn,
usagelog.Table: usagelog.ValidColumn, usagelog.Table: usagelog.ValidColumn,
user.Table: user.ValidColumn, user.Table: user.ValidColumn,
......
...@@ -117,6 +117,54 @@ func (f SettingFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, err ...@@ -117,6 +117,54 @@ 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) return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SettingMutation", m)
} }
// The SoraAccountFunc type is an adapter to allow the use of ordinary
// function as SoraAccount mutator.
type SoraAccountFunc func(context.Context, *ent.SoraAccountMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SoraAccountFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SoraAccountMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SoraAccountMutation", m)
}
// The SoraCacheFileFunc type is an adapter to allow the use of ordinary
// function as SoraCacheFile mutator.
type SoraCacheFileFunc func(context.Context, *ent.SoraCacheFileMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SoraCacheFileFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SoraCacheFileMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SoraCacheFileMutation", m)
}
// The SoraTaskFunc type is an adapter to allow the use of ordinary
// function as SoraTask mutator.
type SoraTaskFunc func(context.Context, *ent.SoraTaskMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SoraTaskFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SoraTaskMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SoraTaskMutation", m)
}
// The SoraUsageStatFunc type is an adapter to allow the use of ordinary
// function as SoraUsageStat mutator.
type SoraUsageStatFunc func(context.Context, *ent.SoraUsageStatMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SoraUsageStatFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SoraUsageStatMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SoraUsageStatMutation", m)
}
// The UsageCleanupTaskFunc type is an adapter to allow the use of ordinary // The UsageCleanupTaskFunc type is an adapter to allow the use of ordinary
// function as UsageCleanupTask mutator. // function as UsageCleanupTask mutator.
type UsageCleanupTaskFunc func(context.Context, *ent.UsageCleanupTaskMutation) (ent.Value, error) type UsageCleanupTaskFunc func(context.Context, *ent.UsageCleanupTaskMutation) (ent.Value, error)
......
...@@ -18,6 +18,10 @@ import ( ...@@ -18,6 +18,10 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode" "github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/soraaccount"
"github.com/Wei-Shaw/sub2api/ent/soracachefile"
"github.com/Wei-Shaw/sub2api/ent/soratask"
"github.com/Wei-Shaw/sub2api/ent/sorausagestat"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
...@@ -326,6 +330,114 @@ func (f TraverseSetting) Traverse(ctx context.Context, q ent.Query) error { ...@@ -326,6 +330,114 @@ func (f TraverseSetting) Traverse(ctx context.Context, q ent.Query) error {
return fmt.Errorf("unexpected query type %T. expect *ent.SettingQuery", q) return fmt.Errorf("unexpected query type %T. expect *ent.SettingQuery", q)
} }
// The SoraAccountFunc type is an adapter to allow the use of ordinary function as a Querier.
type SoraAccountFunc func(context.Context, *ent.SoraAccountQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f SoraAccountFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.SoraAccountQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.SoraAccountQuery", q)
}
// The TraverseSoraAccount type is an adapter to allow the use of ordinary function as Traverser.
type TraverseSoraAccount func(context.Context, *ent.SoraAccountQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseSoraAccount) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseSoraAccount) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.SoraAccountQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.SoraAccountQuery", q)
}
// The SoraCacheFileFunc type is an adapter to allow the use of ordinary function as a Querier.
type SoraCacheFileFunc func(context.Context, *ent.SoraCacheFileQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f SoraCacheFileFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.SoraCacheFileQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.SoraCacheFileQuery", q)
}
// The TraverseSoraCacheFile type is an adapter to allow the use of ordinary function as Traverser.
type TraverseSoraCacheFile func(context.Context, *ent.SoraCacheFileQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseSoraCacheFile) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseSoraCacheFile) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.SoraCacheFileQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.SoraCacheFileQuery", q)
}
// The SoraTaskFunc type is an adapter to allow the use of ordinary function as a Querier.
type SoraTaskFunc func(context.Context, *ent.SoraTaskQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f SoraTaskFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.SoraTaskQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.SoraTaskQuery", q)
}
// The TraverseSoraTask type is an adapter to allow the use of ordinary function as Traverser.
type TraverseSoraTask func(context.Context, *ent.SoraTaskQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseSoraTask) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseSoraTask) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.SoraTaskQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.SoraTaskQuery", q)
}
// The SoraUsageStatFunc type is an adapter to allow the use of ordinary function as a Querier.
type SoraUsageStatFunc func(context.Context, *ent.SoraUsageStatQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f SoraUsageStatFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.SoraUsageStatQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.SoraUsageStatQuery", q)
}
// The TraverseSoraUsageStat type is an adapter to allow the use of ordinary function as Traverser.
type TraverseSoraUsageStat func(context.Context, *ent.SoraUsageStatQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseSoraUsageStat) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseSoraUsageStat) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.SoraUsageStatQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.SoraUsageStatQuery", q)
}
// The UsageCleanupTaskFunc type is an adapter to allow the use of ordinary function as a Querier. // 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) type UsageCleanupTaskFunc func(context.Context, *ent.UsageCleanupTaskQuery) (ent.Value, error)
...@@ -536,6 +648,14 @@ func NewQuery(q ent.Query) (Query, error) { ...@@ -536,6 +648,14 @@ func NewQuery(q ent.Query) (Query, error) {
return &query[*ent.RedeemCodeQuery, predicate.RedeemCode, redeemcode.OrderOption]{typ: ent.TypeRedeemCode, tq: q}, nil return &query[*ent.RedeemCodeQuery, predicate.RedeemCode, redeemcode.OrderOption]{typ: ent.TypeRedeemCode, tq: q}, nil
case *ent.SettingQuery: case *ent.SettingQuery:
return &query[*ent.SettingQuery, predicate.Setting, setting.OrderOption]{typ: ent.TypeSetting, tq: q}, nil return &query[*ent.SettingQuery, predicate.Setting, setting.OrderOption]{typ: ent.TypeSetting, tq: q}, nil
case *ent.SoraAccountQuery:
return &query[*ent.SoraAccountQuery, predicate.SoraAccount, soraaccount.OrderOption]{typ: ent.TypeSoraAccount, tq: q}, nil
case *ent.SoraCacheFileQuery:
return &query[*ent.SoraCacheFileQuery, predicate.SoraCacheFile, soracachefile.OrderOption]{typ: ent.TypeSoraCacheFile, tq: q}, nil
case *ent.SoraTaskQuery:
return &query[*ent.SoraTaskQuery, predicate.SoraTask, soratask.OrderOption]{typ: ent.TypeSoraTask, tq: q}, nil
case *ent.SoraUsageStatQuery:
return &query[*ent.SoraUsageStatQuery, predicate.SoraUsageStat, sorausagestat.OrderOption]{typ: ent.TypeSoraUsageStat, tq: q}, nil
case *ent.UsageCleanupTaskQuery: case *ent.UsageCleanupTaskQuery:
return &query[*ent.UsageCleanupTaskQuery, predicate.UsageCleanupTask, usagecleanuptask.OrderOption]{typ: ent.TypeUsageCleanupTask, tq: q}, nil return &query[*ent.UsageCleanupTaskQuery, predicate.UsageCleanupTask, usagecleanuptask.OrderOption]{typ: ent.TypeUsageCleanupTask, tq: q}, nil
case *ent.UsageLogQuery: case *ent.UsageLogQuery:
......
...@@ -434,6 +434,172 @@ var ( ...@@ -434,6 +434,172 @@ var (
Columns: SettingsColumns, Columns: SettingsColumns,
PrimaryKey: []*schema.Column{SettingsColumns[0]}, PrimaryKey: []*schema.Column{SettingsColumns[0]},
} }
// SoraAccountsColumns holds the columns for the "sora_accounts" table.
SoraAccountsColumns = []*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: "account_id", Type: field.TypeInt64},
{Name: "access_token", Type: field.TypeString, Nullable: true},
{Name: "session_token", Type: field.TypeString, Nullable: true},
{Name: "refresh_token", Type: field.TypeString, Nullable: true},
{Name: "client_id", Type: field.TypeString, Nullable: true},
{Name: "email", Type: field.TypeString, Nullable: true},
{Name: "username", Type: field.TypeString, Nullable: true},
{Name: "remark", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "use_count", Type: field.TypeInt, Default: 0},
{Name: "plan_type", Type: field.TypeString, Nullable: true},
{Name: "plan_title", Type: field.TypeString, Nullable: true},
{Name: "subscription_end", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "sora_supported", Type: field.TypeBool, Default: false},
{Name: "sora_invite_code", Type: field.TypeString, Nullable: true},
{Name: "sora_redeemed_count", Type: field.TypeInt, Default: 0},
{Name: "sora_remaining_count", Type: field.TypeInt, Default: 0},
{Name: "sora_total_count", Type: field.TypeInt, Default: 0},
{Name: "sora_cooldown_until", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "cooled_until", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "image_enabled", Type: field.TypeBool, Default: true},
{Name: "video_enabled", Type: field.TypeBool, Default: true},
{Name: "image_concurrency", Type: field.TypeInt, Default: -1},
{Name: "video_concurrency", Type: field.TypeInt, Default: -1},
{Name: "is_expired", Type: field.TypeBool, Default: false},
}
// SoraAccountsTable holds the schema information for the "sora_accounts" table.
SoraAccountsTable = &schema.Table{
Name: "sora_accounts",
Columns: SoraAccountsColumns,
PrimaryKey: []*schema.Column{SoraAccountsColumns[0]},
Indexes: []*schema.Index{
{
Name: "soraaccount_account_id",
Unique: true,
Columns: []*schema.Column{SoraAccountsColumns[3]},
},
{
Name: "soraaccount_plan_type",
Unique: false,
Columns: []*schema.Column{SoraAccountsColumns[12]},
},
{
Name: "soraaccount_sora_supported",
Unique: false,
Columns: []*schema.Column{SoraAccountsColumns[15]},
},
{
Name: "soraaccount_image_enabled",
Unique: false,
Columns: []*schema.Column{SoraAccountsColumns[22]},
},
{
Name: "soraaccount_video_enabled",
Unique: false,
Columns: []*schema.Column{SoraAccountsColumns[23]},
},
},
}
// SoraCacheFilesColumns holds the columns for the "sora_cache_files" table.
SoraCacheFilesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "task_id", Type: field.TypeString, Nullable: true, Size: 120},
{Name: "account_id", Type: field.TypeInt64},
{Name: "user_id", Type: field.TypeInt64},
{Name: "media_type", Type: field.TypeString, Size: 32},
{Name: "original_url", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}},
{Name: "cache_path", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}},
{Name: "cache_url", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}},
{Name: "size_bytes", Type: field.TypeInt64, Default: 0},
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
}
// SoraCacheFilesTable holds the schema information for the "sora_cache_files" table.
SoraCacheFilesTable = &schema.Table{
Name: "sora_cache_files",
Columns: SoraCacheFilesColumns,
PrimaryKey: []*schema.Column{SoraCacheFilesColumns[0]},
Indexes: []*schema.Index{
{
Name: "soracachefile_account_id",
Unique: false,
Columns: []*schema.Column{SoraCacheFilesColumns[2]},
},
{
Name: "soracachefile_user_id",
Unique: false,
Columns: []*schema.Column{SoraCacheFilesColumns[3]},
},
{
Name: "soracachefile_media_type",
Unique: false,
Columns: []*schema.Column{SoraCacheFilesColumns[4]},
},
},
}
// SoraTasksColumns holds the columns for the "sora_tasks" table.
SoraTasksColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "task_id", Type: field.TypeString, Unique: true, Size: 120},
{Name: "account_id", Type: field.TypeInt64},
{Name: "model", Type: field.TypeString, Size: 120},
{Name: "prompt", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}},
{Name: "status", Type: field.TypeString, Size: 32, Default: "processing"},
{Name: "progress", Type: field.TypeFloat64, Default: 0},
{Name: "result_urls", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "error_message", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "retry_count", Type: field.TypeInt, Default: 0},
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "completed_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
}
// SoraTasksTable holds the schema information for the "sora_tasks" table.
SoraTasksTable = &schema.Table{
Name: "sora_tasks",
Columns: SoraTasksColumns,
PrimaryKey: []*schema.Column{SoraTasksColumns[0]},
Indexes: []*schema.Index{
{
Name: "soratask_account_id",
Unique: false,
Columns: []*schema.Column{SoraTasksColumns[2]},
},
{
Name: "soratask_status",
Unique: false,
Columns: []*schema.Column{SoraTasksColumns[5]},
},
},
}
// SoraUsageStatsColumns holds the columns for the "sora_usage_stats" table.
SoraUsageStatsColumns = []*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: "account_id", Type: field.TypeInt64},
{Name: "image_count", Type: field.TypeInt, Default: 0},
{Name: "video_count", Type: field.TypeInt, Default: 0},
{Name: "error_count", Type: field.TypeInt, Default: 0},
{Name: "last_error_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "today_image_count", Type: field.TypeInt, Default: 0},
{Name: "today_video_count", Type: field.TypeInt, Default: 0},
{Name: "today_error_count", Type: field.TypeInt, Default: 0},
{Name: "today_date", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "date"}},
{Name: "consecutive_error_count", Type: field.TypeInt, Default: 0},
}
// SoraUsageStatsTable holds the schema information for the "sora_usage_stats" table.
SoraUsageStatsTable = &schema.Table{
Name: "sora_usage_stats",
Columns: SoraUsageStatsColumns,
PrimaryKey: []*schema.Column{SoraUsageStatsColumns[0]},
Indexes: []*schema.Index{
{
Name: "sorausagestat_account_id",
Unique: true,
Columns: []*schema.Column{SoraUsageStatsColumns[3]},
},
{
Name: "sorausagestat_today_date",
Unique: false,
Columns: []*schema.Column{SoraUsageStatsColumns[11]},
},
},
}
// UsageCleanupTasksColumns holds the columns for the "usage_cleanup_tasks" table. // UsageCleanupTasksColumns holds the columns for the "usage_cleanup_tasks" table.
UsageCleanupTasksColumns = []*schema.Column{ UsageCleanupTasksColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true}, {Name: "id", Type: field.TypeInt64, Increment: true},
...@@ -843,6 +1009,10 @@ var ( ...@@ -843,6 +1009,10 @@ var (
ProxiesTable, ProxiesTable,
RedeemCodesTable, RedeemCodesTable,
SettingsTable, SettingsTable,
SoraAccountsTable,
SoraCacheFilesTable,
SoraTasksTable,
SoraUsageStatsTable,
UsageCleanupTasksTable, UsageCleanupTasksTable,
UsageLogsTable, UsageLogsTable,
UsersTable, UsersTable,
...@@ -890,6 +1060,18 @@ func init() { ...@@ -890,6 +1060,18 @@ func init() {
SettingsTable.Annotation = &entsql.Annotation{ SettingsTable.Annotation = &entsql.Annotation{
Table: "settings", Table: "settings",
} }
SoraAccountsTable.Annotation = &entsql.Annotation{
Table: "sora_accounts",
}
SoraCacheFilesTable.Annotation = &entsql.Annotation{
Table: "sora_cache_files",
}
SoraTasksTable.Annotation = &entsql.Annotation{
Table: "sora_tasks",
}
SoraUsageStatsTable.Annotation = &entsql.Annotation{
Table: "sora_usage_stats",
}
UsageCleanupTasksTable.Annotation = &entsql.Annotation{ UsageCleanupTasksTable.Annotation = &entsql.Annotation{
Table: "usage_cleanup_tasks", Table: "usage_cleanup_tasks",
} }
......
This diff is collapsed.
...@@ -33,6 +33,18 @@ type RedeemCode func(*sql.Selector) ...@@ -33,6 +33,18 @@ type RedeemCode func(*sql.Selector)
// Setting is the predicate function for setting builders. // Setting is the predicate function for setting builders.
type Setting func(*sql.Selector) type Setting func(*sql.Selector)
// SoraAccount is the predicate function for soraaccount builders.
type SoraAccount func(*sql.Selector)
// SoraCacheFile is the predicate function for soracachefile builders.
type SoraCacheFile func(*sql.Selector)
// SoraTask is the predicate function for soratask builders.
type SoraTask func(*sql.Selector)
// SoraUsageStat is the predicate function for sorausagestat builders.
type SoraUsageStat func(*sql.Selector)
// UsageCleanupTask is the predicate function for usagecleanuptask builders. // UsageCleanupTask is the predicate function for usagecleanuptask builders.
type UsageCleanupTask func(*sql.Selector) type UsageCleanupTask func(*sql.Selector)
......
...@@ -15,6 +15,10 @@ import ( ...@@ -15,6 +15,10 @@ import (
"github.com/Wei-Shaw/sub2api/ent/redeemcode" "github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/schema" "github.com/Wei-Shaw/sub2api/ent/schema"
"github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/soraaccount"
"github.com/Wei-Shaw/sub2api/ent/soracachefile"
"github.com/Wei-Shaw/sub2api/ent/soratask"
"github.com/Wei-Shaw/sub2api/ent/sorausagestat"
"github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask"
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
...@@ -496,6 +500,150 @@ func init() { ...@@ -496,6 +500,150 @@ func init() {
setting.DefaultUpdatedAt = settingDescUpdatedAt.Default.(func() time.Time) setting.DefaultUpdatedAt = settingDescUpdatedAt.Default.(func() time.Time)
// setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. // setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
setting.UpdateDefaultUpdatedAt = settingDescUpdatedAt.UpdateDefault.(func() time.Time) setting.UpdateDefaultUpdatedAt = settingDescUpdatedAt.UpdateDefault.(func() time.Time)
soraaccountMixin := schema.SoraAccount{}.Mixin()
soraaccountMixinFields0 := soraaccountMixin[0].Fields()
_ = soraaccountMixinFields0
soraaccountFields := schema.SoraAccount{}.Fields()
_ = soraaccountFields
// soraaccountDescCreatedAt is the schema descriptor for created_at field.
soraaccountDescCreatedAt := soraaccountMixinFields0[0].Descriptor()
// soraaccount.DefaultCreatedAt holds the default value on creation for the created_at field.
soraaccount.DefaultCreatedAt = soraaccountDescCreatedAt.Default.(func() time.Time)
// soraaccountDescUpdatedAt is the schema descriptor for updated_at field.
soraaccountDescUpdatedAt := soraaccountMixinFields0[1].Descriptor()
// soraaccount.DefaultUpdatedAt holds the default value on creation for the updated_at field.
soraaccount.DefaultUpdatedAt = soraaccountDescUpdatedAt.Default.(func() time.Time)
// soraaccount.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
soraaccount.UpdateDefaultUpdatedAt = soraaccountDescUpdatedAt.UpdateDefault.(func() time.Time)
// soraaccountDescUseCount is the schema descriptor for use_count field.
soraaccountDescUseCount := soraaccountFields[8].Descriptor()
// soraaccount.DefaultUseCount holds the default value on creation for the use_count field.
soraaccount.DefaultUseCount = soraaccountDescUseCount.Default.(int)
// soraaccountDescSoraSupported is the schema descriptor for sora_supported field.
soraaccountDescSoraSupported := soraaccountFields[12].Descriptor()
// soraaccount.DefaultSoraSupported holds the default value on creation for the sora_supported field.
soraaccount.DefaultSoraSupported = soraaccountDescSoraSupported.Default.(bool)
// soraaccountDescSoraRedeemedCount is the schema descriptor for sora_redeemed_count field.
soraaccountDescSoraRedeemedCount := soraaccountFields[14].Descriptor()
// soraaccount.DefaultSoraRedeemedCount holds the default value on creation for the sora_redeemed_count field.
soraaccount.DefaultSoraRedeemedCount = soraaccountDescSoraRedeemedCount.Default.(int)
// soraaccountDescSoraRemainingCount is the schema descriptor for sora_remaining_count field.
soraaccountDescSoraRemainingCount := soraaccountFields[15].Descriptor()
// soraaccount.DefaultSoraRemainingCount holds the default value on creation for the sora_remaining_count field.
soraaccount.DefaultSoraRemainingCount = soraaccountDescSoraRemainingCount.Default.(int)
// soraaccountDescSoraTotalCount is the schema descriptor for sora_total_count field.
soraaccountDescSoraTotalCount := soraaccountFields[16].Descriptor()
// soraaccount.DefaultSoraTotalCount holds the default value on creation for the sora_total_count field.
soraaccount.DefaultSoraTotalCount = soraaccountDescSoraTotalCount.Default.(int)
// soraaccountDescImageEnabled is the schema descriptor for image_enabled field.
soraaccountDescImageEnabled := soraaccountFields[19].Descriptor()
// soraaccount.DefaultImageEnabled holds the default value on creation for the image_enabled field.
soraaccount.DefaultImageEnabled = soraaccountDescImageEnabled.Default.(bool)
// soraaccountDescVideoEnabled is the schema descriptor for video_enabled field.
soraaccountDescVideoEnabled := soraaccountFields[20].Descriptor()
// soraaccount.DefaultVideoEnabled holds the default value on creation for the video_enabled field.
soraaccount.DefaultVideoEnabled = soraaccountDescVideoEnabled.Default.(bool)
// soraaccountDescImageConcurrency is the schema descriptor for image_concurrency field.
soraaccountDescImageConcurrency := soraaccountFields[21].Descriptor()
// soraaccount.DefaultImageConcurrency holds the default value on creation for the image_concurrency field.
soraaccount.DefaultImageConcurrency = soraaccountDescImageConcurrency.Default.(int)
// soraaccountDescVideoConcurrency is the schema descriptor for video_concurrency field.
soraaccountDescVideoConcurrency := soraaccountFields[22].Descriptor()
// soraaccount.DefaultVideoConcurrency holds the default value on creation for the video_concurrency field.
soraaccount.DefaultVideoConcurrency = soraaccountDescVideoConcurrency.Default.(int)
// soraaccountDescIsExpired is the schema descriptor for is_expired field.
soraaccountDescIsExpired := soraaccountFields[23].Descriptor()
// soraaccount.DefaultIsExpired holds the default value on creation for the is_expired field.
soraaccount.DefaultIsExpired = soraaccountDescIsExpired.Default.(bool)
soracachefileFields := schema.SoraCacheFile{}.Fields()
_ = soracachefileFields
// soracachefileDescTaskID is the schema descriptor for task_id field.
soracachefileDescTaskID := soracachefileFields[0].Descriptor()
// soracachefile.TaskIDValidator is a validator for the "task_id" field. It is called by the builders before save.
soracachefile.TaskIDValidator = soracachefileDescTaskID.Validators[0].(func(string) error)
// soracachefileDescMediaType is the schema descriptor for media_type field.
soracachefileDescMediaType := soracachefileFields[3].Descriptor()
// soracachefile.MediaTypeValidator is a validator for the "media_type" field. It is called by the builders before save.
soracachefile.MediaTypeValidator = soracachefileDescMediaType.Validators[0].(func(string) error)
// soracachefileDescSizeBytes is the schema descriptor for size_bytes field.
soracachefileDescSizeBytes := soracachefileFields[7].Descriptor()
// soracachefile.DefaultSizeBytes holds the default value on creation for the size_bytes field.
soracachefile.DefaultSizeBytes = soracachefileDescSizeBytes.Default.(int64)
// soracachefileDescCreatedAt is the schema descriptor for created_at field.
soracachefileDescCreatedAt := soracachefileFields[8].Descriptor()
// soracachefile.DefaultCreatedAt holds the default value on creation for the created_at field.
soracachefile.DefaultCreatedAt = soracachefileDescCreatedAt.Default.(func() time.Time)
sorataskFields := schema.SoraTask{}.Fields()
_ = sorataskFields
// sorataskDescTaskID is the schema descriptor for task_id field.
sorataskDescTaskID := sorataskFields[0].Descriptor()
// soratask.TaskIDValidator is a validator for the "task_id" field. It is called by the builders before save.
soratask.TaskIDValidator = sorataskDescTaskID.Validators[0].(func(string) error)
// sorataskDescModel is the schema descriptor for model field.
sorataskDescModel := sorataskFields[2].Descriptor()
// soratask.ModelValidator is a validator for the "model" field. It is called by the builders before save.
soratask.ModelValidator = sorataskDescModel.Validators[0].(func(string) error)
// sorataskDescStatus is the schema descriptor for status field.
sorataskDescStatus := sorataskFields[4].Descriptor()
// soratask.DefaultStatus holds the default value on creation for the status field.
soratask.DefaultStatus = sorataskDescStatus.Default.(string)
// soratask.StatusValidator is a validator for the "status" field. It is called by the builders before save.
soratask.StatusValidator = sorataskDescStatus.Validators[0].(func(string) error)
// sorataskDescProgress is the schema descriptor for progress field.
sorataskDescProgress := sorataskFields[5].Descriptor()
// soratask.DefaultProgress holds the default value on creation for the progress field.
soratask.DefaultProgress = sorataskDescProgress.Default.(float64)
// sorataskDescRetryCount is the schema descriptor for retry_count field.
sorataskDescRetryCount := sorataskFields[8].Descriptor()
// soratask.DefaultRetryCount holds the default value on creation for the retry_count field.
soratask.DefaultRetryCount = sorataskDescRetryCount.Default.(int)
// sorataskDescCreatedAt is the schema descriptor for created_at field.
sorataskDescCreatedAt := sorataskFields[9].Descriptor()
// soratask.DefaultCreatedAt holds the default value on creation for the created_at field.
soratask.DefaultCreatedAt = sorataskDescCreatedAt.Default.(func() time.Time)
sorausagestatMixin := schema.SoraUsageStat{}.Mixin()
sorausagestatMixinFields0 := sorausagestatMixin[0].Fields()
_ = sorausagestatMixinFields0
sorausagestatFields := schema.SoraUsageStat{}.Fields()
_ = sorausagestatFields
// sorausagestatDescCreatedAt is the schema descriptor for created_at field.
sorausagestatDescCreatedAt := sorausagestatMixinFields0[0].Descriptor()
// sorausagestat.DefaultCreatedAt holds the default value on creation for the created_at field.
sorausagestat.DefaultCreatedAt = sorausagestatDescCreatedAt.Default.(func() time.Time)
// sorausagestatDescUpdatedAt is the schema descriptor for updated_at field.
sorausagestatDescUpdatedAt := sorausagestatMixinFields0[1].Descriptor()
// sorausagestat.DefaultUpdatedAt holds the default value on creation for the updated_at field.
sorausagestat.DefaultUpdatedAt = sorausagestatDescUpdatedAt.Default.(func() time.Time)
// sorausagestat.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
sorausagestat.UpdateDefaultUpdatedAt = sorausagestatDescUpdatedAt.UpdateDefault.(func() time.Time)
// sorausagestatDescImageCount is the schema descriptor for image_count field.
sorausagestatDescImageCount := sorausagestatFields[1].Descriptor()
// sorausagestat.DefaultImageCount holds the default value on creation for the image_count field.
sorausagestat.DefaultImageCount = sorausagestatDescImageCount.Default.(int)
// sorausagestatDescVideoCount is the schema descriptor for video_count field.
sorausagestatDescVideoCount := sorausagestatFields[2].Descriptor()
// sorausagestat.DefaultVideoCount holds the default value on creation for the video_count field.
sorausagestat.DefaultVideoCount = sorausagestatDescVideoCount.Default.(int)
// sorausagestatDescErrorCount is the schema descriptor for error_count field.
sorausagestatDescErrorCount := sorausagestatFields[3].Descriptor()
// sorausagestat.DefaultErrorCount holds the default value on creation for the error_count field.
sorausagestat.DefaultErrorCount = sorausagestatDescErrorCount.Default.(int)
// sorausagestatDescTodayImageCount is the schema descriptor for today_image_count field.
sorausagestatDescTodayImageCount := sorausagestatFields[5].Descriptor()
// sorausagestat.DefaultTodayImageCount holds the default value on creation for the today_image_count field.
sorausagestat.DefaultTodayImageCount = sorausagestatDescTodayImageCount.Default.(int)
// sorausagestatDescTodayVideoCount is the schema descriptor for today_video_count field.
sorausagestatDescTodayVideoCount := sorausagestatFields[6].Descriptor()
// sorausagestat.DefaultTodayVideoCount holds the default value on creation for the today_video_count field.
sorausagestat.DefaultTodayVideoCount = sorausagestatDescTodayVideoCount.Default.(int)
// sorausagestatDescTodayErrorCount is the schema descriptor for today_error_count field.
sorausagestatDescTodayErrorCount := sorausagestatFields[7].Descriptor()
// sorausagestat.DefaultTodayErrorCount holds the default value on creation for the today_error_count field.
sorausagestat.DefaultTodayErrorCount = sorausagestatDescTodayErrorCount.Default.(int)
// sorausagestatDescConsecutiveErrorCount is the schema descriptor for consecutive_error_count field.
sorausagestatDescConsecutiveErrorCount := sorausagestatFields[9].Descriptor()
// sorausagestat.DefaultConsecutiveErrorCount holds the default value on creation for the consecutive_error_count field.
sorausagestat.DefaultConsecutiveErrorCount = sorausagestatDescConsecutiveErrorCount.Default.(int)
usagecleanuptaskMixin := schema.UsageCleanupTask{}.Mixin() usagecleanuptaskMixin := schema.UsageCleanupTask{}.Mixin()
usagecleanuptaskMixinFields0 := usagecleanuptaskMixin[0].Fields() usagecleanuptaskMixinFields0 := usagecleanuptaskMixin[0].Fields()
_ = usagecleanuptaskMixinFields0 _ = usagecleanuptaskMixinFields0
......
// Package schema 定义 Ent ORM 的数据库 schema。
// 每个文件对应一个数据库实体(表),定义其字段、边(关联)和索引。
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// SoraAccount 定义 Sora 账号扩展表。
type SoraAccount struct {
ent.Schema
}
// Annotations 返回 schema 的注解配置。
func (SoraAccount) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "sora_accounts"},
}
}
// Mixin 返回该 schema 使用的混入组件。
func (SoraAccount) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
// Fields 定义 SoraAccount 的字段。
func (SoraAccount) Fields() []ent.Field {
return []ent.Field{
field.Int64("account_id").
Comment("关联 accounts 表的 ID"),
field.String("access_token").
Optional().
Nillable(),
field.String("session_token").
Optional().
Nillable(),
field.String("refresh_token").
Optional().
Nillable(),
field.String("client_id").
Optional().
Nillable(),
field.String("email").
Optional().
Nillable(),
field.String("username").
Optional().
Nillable(),
field.String("remark").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Int("use_count").
Default(0),
field.String("plan_type").
Optional().
Nillable(),
field.String("plan_title").
Optional().
Nillable(),
field.Time("subscription_end").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Bool("sora_supported").
Default(false),
field.String("sora_invite_code").
Optional().
Nillable(),
field.Int("sora_redeemed_count").
Default(0),
field.Int("sora_remaining_count").
Default(0),
field.Int("sora_total_count").
Default(0),
field.Time("sora_cooldown_until").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("cooled_until").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Bool("image_enabled").
Default(true),
field.Bool("video_enabled").
Default(true),
field.Int("image_concurrency").
Default(-1),
field.Int("video_concurrency").
Default(-1),
field.Bool("is_expired").
Default(false),
}
}
// Indexes 定义索引。
func (SoraAccount) Indexes() []ent.Index {
return []ent.Index{
index.Fields("account_id").Unique(),
index.Fields("plan_type"),
index.Fields("sora_supported"),
index.Fields("image_enabled"),
index.Fields("video_enabled"),
}
}
// Package schema 定义 Ent ORM 的数据库 schema。
// 每个文件对应一个数据库实体(表),定义其字段、边(关联)和索引。
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// SoraCacheFile 定义 Sora 缓存文件表。
type SoraCacheFile struct {
ent.Schema
}
// Annotations 返回 schema 的注解配置。
func (SoraCacheFile) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "sora_cache_files"},
}
}
// Fields 定义 SoraCacheFile 的字段。
func (SoraCacheFile) Fields() []ent.Field {
return []ent.Field{
field.String("task_id").
MaxLen(120).
Optional().
Nillable(),
field.Int64("account_id"),
field.Int64("user_id"),
field.String("media_type").
MaxLen(32),
field.String("original_url").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("cache_path").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("cache_url").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Int64("size_bytes").
Default(0),
field.Time("created_at").
Default(time.Now).
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
}
}
// Indexes 定义索引。
func (SoraCacheFile) Indexes() []ent.Index {
return []ent.Index{
index.Fields("account_id"),
index.Fields("user_id"),
index.Fields("media_type"),
}
}
// Package schema 定义 Ent ORM 的数据库 schema。
// 每个文件对应一个数据库实体(表),定义其字段、边(关联)和索引。
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// SoraTask 定义 Sora 任务记录表。
type SoraTask struct {
ent.Schema
}
// Annotations 返回 schema 的注解配置。
func (SoraTask) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "sora_tasks"},
}
}
// Fields 定义 SoraTask 的字段。
func (SoraTask) Fields() []ent.Field {
return []ent.Field{
field.String("task_id").
MaxLen(120).
Unique(),
field.Int64("account_id"),
field.String("model").
MaxLen(120),
field.String("prompt").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("status").
MaxLen(32).
Default("processing"),
field.Float("progress").
Default(0),
field.String("result_urls").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("error_message").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Int("retry_count").
Default(0),
field.Time("created_at").
Default(time.Now).
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("completed_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
}
}
// Indexes 定义索引。
func (SoraTask) Indexes() []ent.Index {
return []ent.Index{
index.Fields("account_id"),
index.Fields("status"),
}
}
// Package schema 定义 Ent ORM 的数据库 schema。
// 每个文件对应一个数据库实体(表),定义其字段、边(关联)和索引。
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// SoraUsageStat 定义 Sora 调用统计表。
type SoraUsageStat struct {
ent.Schema
}
// Annotations 返回 schema 的注解配置。
func (SoraUsageStat) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "sora_usage_stats"},
}
}
// Mixin 返回该 schema 使用的混入组件。
func (SoraUsageStat) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
// Fields 定义 SoraUsageStat 的字段。
func (SoraUsageStat) Fields() []ent.Field {
return []ent.Field{
field.Int64("account_id").
Comment("关联 accounts 表的 ID"),
field.Int("image_count").
Default(0),
field.Int("video_count").
Default(0),
field.Int("error_count").
Default(0),
field.Time("last_error_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Int("today_image_count").
Default(0),
field.Int("today_video_count").
Default(0),
field.Int("today_error_count").
Default(0),
field.Time("today_date").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "date"}),
field.Int("consecutive_error_count").
Default(0),
}
}
// Indexes 定义索引。
func (SoraUsageStat) Indexes() []ent.Index {
return []ent.Index{
index.Fields("account_id").Unique(),
index.Fields("today_date"),
}
}
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/soraaccount"
)
// SoraAccount is the model entity for the SoraAccount schema.
type SoraAccount struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// 关联 accounts 表的 ID
AccountID int64 `json:"account_id,omitempty"`
// AccessToken holds the value of the "access_token" field.
AccessToken *string `json:"access_token,omitempty"`
// SessionToken holds the value of the "session_token" field.
SessionToken *string `json:"session_token,omitempty"`
// RefreshToken holds the value of the "refresh_token" field.
RefreshToken *string `json:"refresh_token,omitempty"`
// ClientID holds the value of the "client_id" field.
ClientID *string `json:"client_id,omitempty"`
// Email holds the value of the "email" field.
Email *string `json:"email,omitempty"`
// Username holds the value of the "username" field.
Username *string `json:"username,omitempty"`
// Remark holds the value of the "remark" field.
Remark *string `json:"remark,omitempty"`
// UseCount holds the value of the "use_count" field.
UseCount int `json:"use_count,omitempty"`
// PlanType holds the value of the "plan_type" field.
PlanType *string `json:"plan_type,omitempty"`
// PlanTitle holds the value of the "plan_title" field.
PlanTitle *string `json:"plan_title,omitempty"`
// SubscriptionEnd holds the value of the "subscription_end" field.
SubscriptionEnd *time.Time `json:"subscription_end,omitempty"`
// SoraSupported holds the value of the "sora_supported" field.
SoraSupported bool `json:"sora_supported,omitempty"`
// SoraInviteCode holds the value of the "sora_invite_code" field.
SoraInviteCode *string `json:"sora_invite_code,omitempty"`
// SoraRedeemedCount holds the value of the "sora_redeemed_count" field.
SoraRedeemedCount int `json:"sora_redeemed_count,omitempty"`
// SoraRemainingCount holds the value of the "sora_remaining_count" field.
SoraRemainingCount int `json:"sora_remaining_count,omitempty"`
// SoraTotalCount holds the value of the "sora_total_count" field.
SoraTotalCount int `json:"sora_total_count,omitempty"`
// SoraCooldownUntil holds the value of the "sora_cooldown_until" field.
SoraCooldownUntil *time.Time `json:"sora_cooldown_until,omitempty"`
// CooledUntil holds the value of the "cooled_until" field.
CooledUntil *time.Time `json:"cooled_until,omitempty"`
// ImageEnabled holds the value of the "image_enabled" field.
ImageEnabled bool `json:"image_enabled,omitempty"`
// VideoEnabled holds the value of the "video_enabled" field.
VideoEnabled bool `json:"video_enabled,omitempty"`
// ImageConcurrency holds the value of the "image_concurrency" field.
ImageConcurrency int `json:"image_concurrency,omitempty"`
// VideoConcurrency holds the value of the "video_concurrency" field.
VideoConcurrency int `json:"video_concurrency,omitempty"`
// IsExpired holds the value of the "is_expired" field.
IsExpired bool `json:"is_expired,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*SoraAccount) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case soraaccount.FieldSoraSupported, soraaccount.FieldImageEnabled, soraaccount.FieldVideoEnabled, soraaccount.FieldIsExpired:
values[i] = new(sql.NullBool)
case soraaccount.FieldID, soraaccount.FieldAccountID, soraaccount.FieldUseCount, soraaccount.FieldSoraRedeemedCount, soraaccount.FieldSoraRemainingCount, soraaccount.FieldSoraTotalCount, soraaccount.FieldImageConcurrency, soraaccount.FieldVideoConcurrency:
values[i] = new(sql.NullInt64)
case soraaccount.FieldAccessToken, soraaccount.FieldSessionToken, soraaccount.FieldRefreshToken, soraaccount.FieldClientID, soraaccount.FieldEmail, soraaccount.FieldUsername, soraaccount.FieldRemark, soraaccount.FieldPlanType, soraaccount.FieldPlanTitle, soraaccount.FieldSoraInviteCode:
values[i] = new(sql.NullString)
case soraaccount.FieldCreatedAt, soraaccount.FieldUpdatedAt, soraaccount.FieldSubscriptionEnd, soraaccount.FieldSoraCooldownUntil, soraaccount.FieldCooledUntil:
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 SoraAccount fields.
func (_m *SoraAccount) 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 soraaccount.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int64(value.Int64)
case soraaccount.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 soraaccount.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
case soraaccount.FieldAccountID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field account_id", values[i])
} else if value.Valid {
_m.AccountID = value.Int64
}
case soraaccount.FieldAccessToken:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field access_token", values[i])
} else if value.Valid {
_m.AccessToken = new(string)
*_m.AccessToken = value.String
}
case soraaccount.FieldSessionToken:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field session_token", values[i])
} else if value.Valid {
_m.SessionToken = new(string)
*_m.SessionToken = value.String
}
case soraaccount.FieldRefreshToken:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field refresh_token", values[i])
} else if value.Valid {
_m.RefreshToken = new(string)
*_m.RefreshToken = value.String
}
case soraaccount.FieldClientID:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field client_id", values[i])
} else if value.Valid {
_m.ClientID = new(string)
*_m.ClientID = value.String
}
case soraaccount.FieldEmail:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field email", values[i])
} else if value.Valid {
_m.Email = new(string)
*_m.Email = value.String
}
case soraaccount.FieldUsername:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field username", values[i])
} else if value.Valid {
_m.Username = new(string)
*_m.Username = value.String
}
case soraaccount.FieldRemark:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field remark", values[i])
} else if value.Valid {
_m.Remark = new(string)
*_m.Remark = value.String
}
case soraaccount.FieldUseCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field use_count", values[i])
} else if value.Valid {
_m.UseCount = int(value.Int64)
}
case soraaccount.FieldPlanType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field plan_type", values[i])
} else if value.Valid {
_m.PlanType = new(string)
*_m.PlanType = value.String
}
case soraaccount.FieldPlanTitle:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field plan_title", values[i])
} else if value.Valid {
_m.PlanTitle = new(string)
*_m.PlanTitle = value.String
}
case soraaccount.FieldSubscriptionEnd:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field subscription_end", values[i])
} else if value.Valid {
_m.SubscriptionEnd = new(time.Time)
*_m.SubscriptionEnd = value.Time
}
case soraaccount.FieldSoraSupported:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field sora_supported", values[i])
} else if value.Valid {
_m.SoraSupported = value.Bool
}
case soraaccount.FieldSoraInviteCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field sora_invite_code", values[i])
} else if value.Valid {
_m.SoraInviteCode = new(string)
*_m.SoraInviteCode = value.String
}
case soraaccount.FieldSoraRedeemedCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field sora_redeemed_count", values[i])
} else if value.Valid {
_m.SoraRedeemedCount = int(value.Int64)
}
case soraaccount.FieldSoraRemainingCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field sora_remaining_count", values[i])
} else if value.Valid {
_m.SoraRemainingCount = int(value.Int64)
}
case soraaccount.FieldSoraTotalCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field sora_total_count", values[i])
} else if value.Valid {
_m.SoraTotalCount = int(value.Int64)
}
case soraaccount.FieldSoraCooldownUntil:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field sora_cooldown_until", values[i])
} else if value.Valid {
_m.SoraCooldownUntil = new(time.Time)
*_m.SoraCooldownUntil = value.Time
}
case soraaccount.FieldCooledUntil:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field cooled_until", values[i])
} else if value.Valid {
_m.CooledUntil = new(time.Time)
*_m.CooledUntil = value.Time
}
case soraaccount.FieldImageEnabled:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field image_enabled", values[i])
} else if value.Valid {
_m.ImageEnabled = value.Bool
}
case soraaccount.FieldVideoEnabled:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field video_enabled", values[i])
} else if value.Valid {
_m.VideoEnabled = value.Bool
}
case soraaccount.FieldImageConcurrency:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field image_concurrency", values[i])
} else if value.Valid {
_m.ImageConcurrency = int(value.Int64)
}
case soraaccount.FieldVideoConcurrency:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field video_concurrency", values[i])
} else if value.Valid {
_m.VideoConcurrency = int(value.Int64)
}
case soraaccount.FieldIsExpired:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field is_expired", values[i])
} else if value.Valid {
_m.IsExpired = value.Bool
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the SoraAccount.
// This includes values selected through modifiers, order, etc.
func (_m *SoraAccount) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this SoraAccount.
// Note that you need to call SoraAccount.Unwrap() before calling this method if this SoraAccount
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *SoraAccount) Update() *SoraAccountUpdateOne {
return NewSoraAccountClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the SoraAccount 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 *SoraAccount) Unwrap() *SoraAccount {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: SoraAccount is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *SoraAccount) String() string {
var builder strings.Builder
builder.WriteString("SoraAccount(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("account_id=")
builder.WriteString(fmt.Sprintf("%v", _m.AccountID))
builder.WriteString(", ")
if v := _m.AccessToken; v != nil {
builder.WriteString("access_token=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.SessionToken; v != nil {
builder.WriteString("session_token=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.RefreshToken; v != nil {
builder.WriteString("refresh_token=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.ClientID; v != nil {
builder.WriteString("client_id=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.Email; v != nil {
builder.WriteString("email=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.Username; v != nil {
builder.WriteString("username=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.Remark; v != nil {
builder.WriteString("remark=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("use_count=")
builder.WriteString(fmt.Sprintf("%v", _m.UseCount))
builder.WriteString(", ")
if v := _m.PlanType; v != nil {
builder.WriteString("plan_type=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.PlanTitle; v != nil {
builder.WriteString("plan_title=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.SubscriptionEnd; v != nil {
builder.WriteString("subscription_end=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("sora_supported=")
builder.WriteString(fmt.Sprintf("%v", _m.SoraSupported))
builder.WriteString(", ")
if v := _m.SoraInviteCode; v != nil {
builder.WriteString("sora_invite_code=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("sora_redeemed_count=")
builder.WriteString(fmt.Sprintf("%v", _m.SoraRedeemedCount))
builder.WriteString(", ")
builder.WriteString("sora_remaining_count=")
builder.WriteString(fmt.Sprintf("%v", _m.SoraRemainingCount))
builder.WriteString(", ")
builder.WriteString("sora_total_count=")
builder.WriteString(fmt.Sprintf("%v", _m.SoraTotalCount))
builder.WriteString(", ")
if v := _m.SoraCooldownUntil; v != nil {
builder.WriteString("sora_cooldown_until=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.CooledUntil; v != nil {
builder.WriteString("cooled_until=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("image_enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.ImageEnabled))
builder.WriteString(", ")
builder.WriteString("video_enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.VideoEnabled))
builder.WriteString(", ")
builder.WriteString("image_concurrency=")
builder.WriteString(fmt.Sprintf("%v", _m.ImageConcurrency))
builder.WriteString(", ")
builder.WriteString("video_concurrency=")
builder.WriteString(fmt.Sprintf("%v", _m.VideoConcurrency))
builder.WriteString(", ")
builder.WriteString("is_expired=")
builder.WriteString(fmt.Sprintf("%v", _m.IsExpired))
builder.WriteByte(')')
return builder.String()
}
// SoraAccounts is a parsable slice of SoraAccount.
type SoraAccounts []*SoraAccount
// Code generated by ent, DO NOT EDIT.
package soraaccount
import (
"time"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the soraaccount type in the database.
Label = "sora_account"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldAccountID holds the string denoting the account_id field in the database.
FieldAccountID = "account_id"
// FieldAccessToken holds the string denoting the access_token field in the database.
FieldAccessToken = "access_token"
// FieldSessionToken holds the string denoting the session_token field in the database.
FieldSessionToken = "session_token"
// FieldRefreshToken holds the string denoting the refresh_token field in the database.
FieldRefreshToken = "refresh_token"
// FieldClientID holds the string denoting the client_id field in the database.
FieldClientID = "client_id"
// FieldEmail holds the string denoting the email field in the database.
FieldEmail = "email"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldRemark holds the string denoting the remark field in the database.
FieldRemark = "remark"
// FieldUseCount holds the string denoting the use_count field in the database.
FieldUseCount = "use_count"
// FieldPlanType holds the string denoting the plan_type field in the database.
FieldPlanType = "plan_type"
// FieldPlanTitle holds the string denoting the plan_title field in the database.
FieldPlanTitle = "plan_title"
// FieldSubscriptionEnd holds the string denoting the subscription_end field in the database.
FieldSubscriptionEnd = "subscription_end"
// FieldSoraSupported holds the string denoting the sora_supported field in the database.
FieldSoraSupported = "sora_supported"
// FieldSoraInviteCode holds the string denoting the sora_invite_code field in the database.
FieldSoraInviteCode = "sora_invite_code"
// FieldSoraRedeemedCount holds the string denoting the sora_redeemed_count field in the database.
FieldSoraRedeemedCount = "sora_redeemed_count"
// FieldSoraRemainingCount holds the string denoting the sora_remaining_count field in the database.
FieldSoraRemainingCount = "sora_remaining_count"
// FieldSoraTotalCount holds the string denoting the sora_total_count field in the database.
FieldSoraTotalCount = "sora_total_count"
// FieldSoraCooldownUntil holds the string denoting the sora_cooldown_until field in the database.
FieldSoraCooldownUntil = "sora_cooldown_until"
// FieldCooledUntil holds the string denoting the cooled_until field in the database.
FieldCooledUntil = "cooled_until"
// FieldImageEnabled holds the string denoting the image_enabled field in the database.
FieldImageEnabled = "image_enabled"
// FieldVideoEnabled holds the string denoting the video_enabled field in the database.
FieldVideoEnabled = "video_enabled"
// FieldImageConcurrency holds the string denoting the image_concurrency field in the database.
FieldImageConcurrency = "image_concurrency"
// FieldVideoConcurrency holds the string denoting the video_concurrency field in the database.
FieldVideoConcurrency = "video_concurrency"
// FieldIsExpired holds the string denoting the is_expired field in the database.
FieldIsExpired = "is_expired"
// Table holds the table name of the soraaccount in the database.
Table = "sora_accounts"
)
// Columns holds all SQL columns for soraaccount fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldAccountID,
FieldAccessToken,
FieldSessionToken,
FieldRefreshToken,
FieldClientID,
FieldEmail,
FieldUsername,
FieldRemark,
FieldUseCount,
FieldPlanType,
FieldPlanTitle,
FieldSubscriptionEnd,
FieldSoraSupported,
FieldSoraInviteCode,
FieldSoraRedeemedCount,
FieldSoraRemainingCount,
FieldSoraTotalCount,
FieldSoraCooldownUntil,
FieldCooledUntil,
FieldImageEnabled,
FieldVideoEnabled,
FieldImageConcurrency,
FieldVideoConcurrency,
FieldIsExpired,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// DefaultUseCount holds the default value on creation for the "use_count" field.
DefaultUseCount int
// DefaultSoraSupported holds the default value on creation for the "sora_supported" field.
DefaultSoraSupported bool
// DefaultSoraRedeemedCount holds the default value on creation for the "sora_redeemed_count" field.
DefaultSoraRedeemedCount int
// DefaultSoraRemainingCount holds the default value on creation for the "sora_remaining_count" field.
DefaultSoraRemainingCount int
// DefaultSoraTotalCount holds the default value on creation for the "sora_total_count" field.
DefaultSoraTotalCount int
// DefaultImageEnabled holds the default value on creation for the "image_enabled" field.
DefaultImageEnabled bool
// DefaultVideoEnabled holds the default value on creation for the "video_enabled" field.
DefaultVideoEnabled bool
// DefaultImageConcurrency holds the default value on creation for the "image_concurrency" field.
DefaultImageConcurrency int
// DefaultVideoConcurrency holds the default value on creation for the "video_concurrency" field.
DefaultVideoConcurrency int
// DefaultIsExpired holds the default value on creation for the "is_expired" field.
DefaultIsExpired bool
)
// OrderOption defines the ordering options for the SoraAccount 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()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByAccountID orders the results by the account_id field.
func ByAccountID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAccountID, opts...).ToFunc()
}
// ByAccessToken orders the results by the access_token field.
func ByAccessToken(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAccessToken, opts...).ToFunc()
}
// BySessionToken orders the results by the session_token field.
func BySessionToken(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSessionToken, opts...).ToFunc()
}
// ByRefreshToken orders the results by the refresh_token field.
func ByRefreshToken(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRefreshToken, opts...).ToFunc()
}
// ByClientID orders the results by the client_id field.
func ByClientID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldClientID, opts...).ToFunc()
}
// ByEmail orders the results by the email field.
func ByEmail(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEmail, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByRemark orders the results by the remark field.
func ByRemark(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRemark, opts...).ToFunc()
}
// ByUseCount orders the results by the use_count field.
func ByUseCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUseCount, opts...).ToFunc()
}
// ByPlanType orders the results by the plan_type field.
func ByPlanType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPlanType, opts...).ToFunc()
}
// ByPlanTitle orders the results by the plan_title field.
func ByPlanTitle(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPlanTitle, opts...).ToFunc()
}
// BySubscriptionEnd orders the results by the subscription_end field.
func BySubscriptionEnd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSubscriptionEnd, opts...).ToFunc()
}
// BySoraSupported orders the results by the sora_supported field.
func BySoraSupported(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSoraSupported, opts...).ToFunc()
}
// BySoraInviteCode orders the results by the sora_invite_code field.
func BySoraInviteCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSoraInviteCode, opts...).ToFunc()
}
// BySoraRedeemedCount orders the results by the sora_redeemed_count field.
func BySoraRedeemedCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSoraRedeemedCount, opts...).ToFunc()
}
// BySoraRemainingCount orders the results by the sora_remaining_count field.
func BySoraRemainingCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSoraRemainingCount, opts...).ToFunc()
}
// BySoraTotalCount orders the results by the sora_total_count field.
func BySoraTotalCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSoraTotalCount, opts...).ToFunc()
}
// BySoraCooldownUntil orders the results by the sora_cooldown_until field.
func BySoraCooldownUntil(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSoraCooldownUntil, opts...).ToFunc()
}
// ByCooledUntil orders the results by the cooled_until field.
func ByCooledUntil(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCooledUntil, opts...).ToFunc()
}
// ByImageEnabled orders the results by the image_enabled field.
func ByImageEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldImageEnabled, opts...).ToFunc()
}
// ByVideoEnabled orders the results by the video_enabled field.
func ByVideoEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVideoEnabled, opts...).ToFunc()
}
// ByImageConcurrency orders the results by the image_concurrency field.
func ByImageConcurrency(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldImageConcurrency, opts...).ToFunc()
}
// ByVideoConcurrency orders the results by the video_concurrency field.
func ByVideoConcurrency(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVideoConcurrency, opts...).ToFunc()
}
// ByIsExpired orders the results by the is_expired field.
func ByIsExpired(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldIsExpired, opts...).ToFunc()
}
This diff is collapsed.
This diff is collapsed.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/soraaccount"
)
// SoraAccountDelete is the builder for deleting a SoraAccount entity.
type SoraAccountDelete struct {
config
hooks []Hook
mutation *SoraAccountMutation
}
// Where appends a list predicates to the SoraAccountDelete builder.
func (_d *SoraAccountDelete) Where(ps ...predicate.SoraAccount) *SoraAccountDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *SoraAccountDelete) 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 *SoraAccountDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *SoraAccountDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(soraaccount.Table, sqlgraph.NewFieldSpec(soraaccount.FieldID, field.TypeInt64))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// SoraAccountDeleteOne is the builder for deleting a single SoraAccount entity.
type SoraAccountDeleteOne struct {
_d *SoraAccountDelete
}
// Where appends a list predicates to the SoraAccountDelete builder.
func (_d *SoraAccountDeleteOne) Where(ps ...predicate.SoraAccount) *SoraAccountDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *SoraAccountDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{soraaccount.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *SoraAccountDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/soraaccount"
)
// SoraAccountQuery is the builder for querying SoraAccount entities.
type SoraAccountQuery struct {
config
ctx *QueryContext
order []soraaccount.OrderOption
inters []Interceptor
predicates []predicate.SoraAccount
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the SoraAccountQuery builder.
func (_q *SoraAccountQuery) Where(ps ...predicate.SoraAccount) *SoraAccountQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *SoraAccountQuery) Limit(limit int) *SoraAccountQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *SoraAccountQuery) Offset(offset int) *SoraAccountQuery {
_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 *SoraAccountQuery) Unique(unique bool) *SoraAccountQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *SoraAccountQuery) Order(o ...soraaccount.OrderOption) *SoraAccountQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first SoraAccount entity from the query.
// Returns a *NotFoundError when no SoraAccount was found.
func (_q *SoraAccountQuery) First(ctx context.Context) (*SoraAccount, 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{soraaccount.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *SoraAccountQuery) FirstX(ctx context.Context) *SoraAccount {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first SoraAccount ID from the query.
// Returns a *NotFoundError when no SoraAccount ID was found.
func (_q *SoraAccountQuery) FirstID(ctx context.Context) (id int64, err error) {
var ids []int64
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{soraaccount.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *SoraAccountQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single SoraAccount entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one SoraAccount entity is found.
// Returns a *NotFoundError when no SoraAccount entities are found.
func (_q *SoraAccountQuery) Only(ctx context.Context) (*SoraAccount, 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{soraaccount.Label}
default:
return nil, &NotSingularError{soraaccount.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *SoraAccountQuery) OnlyX(ctx context.Context) *SoraAccount {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only SoraAccount ID in the query.
// Returns a *NotSingularError when more than one SoraAccount ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *SoraAccountQuery) OnlyID(ctx context.Context) (id int64, err error) {
var ids []int64
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{soraaccount.Label}
default:
err = &NotSingularError{soraaccount.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *SoraAccountQuery) OnlyIDX(ctx context.Context) int64 {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of SoraAccounts.
func (_q *SoraAccountQuery) All(ctx context.Context) ([]*SoraAccount, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*SoraAccount, *SoraAccountQuery]()
return withInterceptors[[]*SoraAccount](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *SoraAccountQuery) AllX(ctx context.Context) []*SoraAccount {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of SoraAccount IDs.
func (_q *SoraAccountQuery) IDs(ctx context.Context) (ids []int64, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(soraaccount.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *SoraAccountQuery) IDsX(ctx context.Context) []int64 {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *SoraAccountQuery) 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[*SoraAccountQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *SoraAccountQuery) 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 *SoraAccountQuery) 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("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *SoraAccountQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the SoraAccountQuery 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 *SoraAccountQuery) Clone() *SoraAccountQuery {
if _q == nil {
return nil
}
return &SoraAccountQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]soraaccount.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.SoraAccount{}, _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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.SoraAccount.Query().
// GroupBy(soraaccount.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *SoraAccountQuery) GroupBy(field string, fields ...string) *SoraAccountGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &SoraAccountGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = soraaccount.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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.SoraAccount.Query().
// Select(soraaccount.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *SoraAccountQuery) Select(fields ...string) *SoraAccountSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &SoraAccountSelect{SoraAccountQuery: _q}
sbuild.label = soraaccount.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a SoraAccountSelect configured with the given aggregations.
func (_q *SoraAccountQuery) Aggregate(fns ...AggregateFunc) *SoraAccountSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *SoraAccountQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !soraaccount.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: 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 *SoraAccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SoraAccount, error) {
var (
nodes = []*SoraAccount{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*SoraAccount).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &SoraAccount{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
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 *SoraAccountQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_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 *SoraAccountQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(soraaccount.Table, soraaccount.Columns, sqlgraph.NewFieldSpec(soraaccount.FieldID, field.TypeInt64))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, soraaccount.FieldID)
for i := range fields {
if fields[i] != soraaccount.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 *SoraAccountQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(soraaccount.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = soraaccount.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 _, m := range _q.modifiers {
m(selector)
}
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
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *SoraAccountQuery) ForUpdate(opts ...sql.LockOption) *SoraAccountQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *SoraAccountQuery) ForShare(opts ...sql.LockOption) *SoraAccountQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// SoraAccountGroupBy is the group-by builder for SoraAccount entities.
type SoraAccountGroupBy struct {
selector
build *SoraAccountQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *SoraAccountGroupBy) Aggregate(fns ...AggregateFunc) *SoraAccountGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *SoraAccountGroupBy) 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[*SoraAccountQuery, *SoraAccountGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *SoraAccountGroupBy) sqlScan(ctx context.Context, root *SoraAccountQuery, 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)
}
// SoraAccountSelect is the builder for selecting fields of SoraAccount entities.
type SoraAccountSelect struct {
*SoraAccountQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *SoraAccountSelect) Aggregate(fns ...AggregateFunc) *SoraAccountSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *SoraAccountSelect) 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[*SoraAccountQuery, *SoraAccountSelect](ctx, _s.SoraAccountQuery, _s, _s.inters, v)
}
func (_s *SoraAccountSelect) sqlScan(ctx context.Context, root *SoraAccountQuery, 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)
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment