refactor(数据库): 迁移持久层到 Ent 并清理 GORM

将仓储层/基础设施改为 Ent + 原生 SQL 执行路径,并移除 AutoMigrate 与 GORM 依赖。
重构内容包括:
- 仓储层改用 Ent/SQL(含 usage_log/account 等复杂查询),统一错误映射
- 基础设施与 setup 初始化切换为 Ent + SQL migrations
- 集成测试与 fixtures 迁移到 Ent 事务模型
- 清理遗留 GORM 模型/依赖,补充迁移与文档说明
- 增加根目录 Makefile 便于前后端编译

测试:
- go test -tags unit ./...
- go test -tags integration ./...
This commit is contained in:
yangjianbo
2025-12-29 10:03:27 +08:00
parent fd51ff6970
commit 3d617de577
149 changed files with 62892 additions and 3212 deletions

18
AGENTS.md Normal file
View File

@@ -0,0 +1,18 @@
<!-- OPENSPEC:START -->
# OpenSpec Instructions
These instructions are for AI assistants working in this project.
Always open `@/openspec/AGENTS.md` when the request:
- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding
Use `@/openspec/AGENTS.md` to learn:
- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Keep this managed block so 'openspec update' can refresh the instructions.
<!-- OPENSPEC:END -->

12
Makefile Normal file
View File

@@ -0,0 +1,12 @@
.PHONY: build build-backend build-frontend
# 一键编译前后端
build: build-backend build-frontend
# 编译后端(复用 backend/Makefile
build-backend:
@$(MAKE) -C backend build
# 编译前端(需要已安装依赖)
build-frontend:
@npm --prefix frontend run build

View File

@@ -20,6 +20,8 @@ English | [中文](README_CN.md)
Try Sub2API online: **https://v2.pincc.ai/** Try Sub2API online: **https://v2.pincc.ai/**
Demo credentials (shared demo environment; **not** created automatically for self-hosted installs):
| Email | Password | | Email | Password |
|-------|----------| |-------|----------|
| admin@sub2api.com | admin123 | | admin@sub2api.com | admin123 |
@@ -260,8 +262,10 @@ jwt:
expire_hour: 24 expire_hour: 24
default: default:
admin_email: "admin@example.com" user_concurrency: 5
admin_password: "admin123" user_balance: 0
api_key_prefix: "sk-"
rate_multiplier: 1.0
``` ```
```bash ```bash
@@ -281,6 +285,16 @@ cd frontend
npm run dev npm run dev
``` ```
#### Code Generation
When editing `backend/ent/schema`, regenerate Ent + Wire:
```bash
cd backend
go generate ./ent
go generate ./cmd/server
```
--- ---
## Project Structure ## Project Structure

View File

@@ -20,6 +20,8 @@
体验地址:**https://v2.pincc.ai/** 体验地址:**https://v2.pincc.ai/**
演示账号(共享演示环境;自建部署不会自动创建该账号):
| 邮箱 | 密码 | | 邮箱 | 密码 |
|------|------| |------|------|
| admin@sub2api.com | admin123 | | admin@sub2api.com | admin123 |
@@ -260,8 +262,10 @@ jwt:
expire_hour: 24 expire_hour: 24
default: default:
admin_email: "admin@example.com" user_concurrency: 5
admin_password: "admin123" user_balance: 0
api_key_prefix: "sk-"
rate_multiplier: 1.0
``` ```
```bash ```bash
@@ -281,6 +285,16 @@ cd frontend
npm run dev npm run dev
``` ```
#### 代码生成
修改 `backend/ent/schema` 后,需要重新生成 Ent + Wire
```bash
cd backend
go generate ./ent
go generate ./cmd/server
```
--- ---
## 项目结构 ## 项目结构

View File

@@ -15,6 +15,7 @@ import (
"syscall" "syscall"
"time" "time"
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
"github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler" "github.com/Wei-Shaw/sub2api/internal/handler"
"github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/server/middleware"

View File

@@ -9,6 +9,7 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler" "github.com/Wei-Shaw/sub2api/internal/handler"
"github.com/Wei-Shaw/sub2api/internal/infrastructure" "github.com/Wei-Shaw/sub2api/internal/infrastructure"
@@ -19,7 +20,6 @@ import (
"github.com/google/wire" "github.com/google/wire"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gorm.io/gorm"
) )
type Application struct { type Application struct {
@@ -62,7 +62,7 @@ func provideServiceBuildInfo(buildInfo handler.BuildInfo) service.BuildInfo {
} }
func provideCleanup( func provideCleanup(
db *gorm.DB, entClient *ent.Client,
rdb *redis.Client, rdb *redis.Client,
tokenRefresh *service.TokenRefreshService, tokenRefresh *service.TokenRefreshService,
pricing *service.PricingService, pricing *service.PricingService,
@@ -107,12 +107,8 @@ func provideCleanup(
{"Redis", func() error { {"Redis", func() error {
return rdb.Close() return rdb.Close()
}}, }},
{"Database", func() error { {"Ent", func() error {
sqlDB, err := db.DB() return entClient.Close()
if err != nil {
return err
}
return sqlDB.Close()
}}, }},
} }

View File

@@ -8,6 +8,7 @@ package main
import ( import (
"context" "context"
"github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler" "github.com/Wei-Shaw/sub2api/internal/handler"
"github.com/Wei-Shaw/sub2api/internal/handler/admin" "github.com/Wei-Shaw/sub2api/internal/handler/admin"
@@ -17,7 +18,6 @@ import (
"github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service" "github.com/Wei-Shaw/sub2api/internal/service"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gorm.io/gorm"
"log" "log"
"net/http" "net/http"
"time" "time"
@@ -25,6 +25,7 @@ import (
import ( import (
_ "embed" _ "embed"
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
) )
// Injectors from wire.go: // Injectors from wire.go:
@@ -34,15 +35,19 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
db, err := infrastructure.ProvideDB(configConfig) client, err := infrastructure.ProvideEnt(configConfig)
if err != nil { if err != nil {
return nil, err return nil, err
} }
userRepository := repository.NewUserRepository(db) sqlDB, err := infrastructure.ProvideSQLDB(client)
settingRepository := repository.NewSettingRepository(db) if err != nil {
return nil, err
}
userRepository := repository.NewUserRepository(client, sqlDB)
settingRepository := repository.NewSettingRepository(client)
settingService := service.NewSettingService(settingRepository, configConfig) settingService := service.NewSettingService(settingRepository, configConfig)
client := infrastructure.ProvideRedis(configConfig) redisClient := infrastructure.ProvideRedis(configConfig)
emailCache := repository.NewEmailCache(client) emailCache := repository.NewEmailCache(redisClient)
emailService := service.NewEmailService(settingRepository, emailCache) emailService := service.NewEmailService(settingRepository, emailCache)
turnstileVerifier := repository.NewTurnstileVerifier() turnstileVerifier := repository.NewTurnstileVerifier()
turnstileService := service.NewTurnstileService(settingService, turnstileVerifier) turnstileService := service.NewTurnstileService(settingService, turnstileVerifier)
@@ -51,27 +56,27 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
userService := service.NewUserService(userRepository) userService := service.NewUserService(userRepository)
authHandler := handler.NewAuthHandler(authService, userService) authHandler := handler.NewAuthHandler(authService, userService)
userHandler := handler.NewUserHandler(userService) userHandler := handler.NewUserHandler(userService)
apiKeyRepository := repository.NewApiKeyRepository(db) apiKeyRepository := repository.NewApiKeyRepository(client)
groupRepository := repository.NewGroupRepository(db) groupRepository := repository.NewGroupRepository(client, sqlDB)
userSubscriptionRepository := repository.NewUserSubscriptionRepository(db) userSubscriptionRepository := repository.NewUserSubscriptionRepository(client)
apiKeyCache := repository.NewApiKeyCache(client) apiKeyCache := repository.NewApiKeyCache(redisClient)
apiKeyService := service.NewApiKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, apiKeyCache, configConfig) apiKeyService := service.NewApiKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, apiKeyCache, configConfig)
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
usageLogRepository := repository.NewUsageLogRepository(db) usageLogRepository := repository.NewUsageLogRepository(client, sqlDB)
usageService := service.NewUsageService(usageLogRepository, userRepository) usageService := service.NewUsageService(usageLogRepository, userRepository)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService)
redeemCodeRepository := repository.NewRedeemCodeRepository(db) redeemCodeRepository := repository.NewRedeemCodeRepository(client)
billingCache := repository.NewBillingCache(client) billingCache := repository.NewBillingCache(redisClient)
billingCacheService := service.NewBillingCacheService(billingCache, userRepository, userSubscriptionRepository) billingCacheService := service.NewBillingCacheService(billingCache, userRepository, userSubscriptionRepository)
subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService) subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService)
redeemCache := repository.NewRedeemCache(client) redeemCache := repository.NewRedeemCache(redisClient)
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService) redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService)
redeemHandler := handler.NewRedeemHandler(redeemService) redeemHandler := handler.NewRedeemHandler(redeemService)
subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService) subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService)
dashboardService := service.NewDashboardService(usageLogRepository) dashboardService := service.NewDashboardService(usageLogRepository)
dashboardHandler := admin.NewDashboardHandler(dashboardService) dashboardHandler := admin.NewDashboardHandler(dashboardService)
accountRepository := repository.NewAccountRepository(db) accountRepository := repository.NewAccountRepository(client, sqlDB)
proxyRepository := repository.NewProxyRepository(db) proxyRepository := repository.NewProxyRepository(client, sqlDB)
proxyExitInfoProber := repository.NewProxyExitInfoProber() proxyExitInfoProber := repository.NewProxyExitInfoProber()
adminService := service.NewAdminService(userRepository, groupRepository, accountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, billingCacheService, proxyExitInfoProber) adminService := service.NewAdminService(userRepository, groupRepository, accountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, billingCacheService, proxyExitInfoProber)
adminUserHandler := admin.NewUserHandler(adminService) adminUserHandler := admin.NewUserHandler(adminService)
@@ -86,11 +91,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
rateLimitService := service.NewRateLimitService(accountRepository, configConfig) rateLimitService := service.NewRateLimitService(accountRepository, configConfig)
claudeUsageFetcher := repository.NewClaudeUsageFetcher() claudeUsageFetcher := repository.NewClaudeUsageFetcher()
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher) accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher)
geminiTokenCache := repository.NewGeminiTokenCache(client) geminiTokenCache := repository.NewGeminiTokenCache(redisClient)
geminiTokenProvider := service.NewGeminiTokenProvider(accountRepository, geminiTokenCache, geminiOAuthService) geminiTokenProvider := service.NewGeminiTokenProvider(accountRepository, geminiTokenCache, geminiOAuthService)
httpUpstream := repository.NewHTTPUpstream(configConfig) httpUpstream := repository.NewHTTPUpstream(configConfig)
accountTestService := service.NewAccountTestService(accountRepository, oAuthService, openAIOAuthService, geminiTokenProvider, httpUpstream) accountTestService := service.NewAccountTestService(accountRepository, oAuthService, openAIOAuthService, geminiTokenProvider, httpUpstream)
concurrencyCache := repository.NewConcurrencyCache(client) concurrencyCache := repository.NewConcurrencyCache(redisClient)
concurrencyService := service.NewConcurrencyService(concurrencyCache) concurrencyService := service.NewConcurrencyService(concurrencyCache)
crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService) crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService)
accountHandler := admin.NewAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService) accountHandler := admin.NewAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService)
@@ -100,7 +105,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
proxyHandler := admin.NewProxyHandler(adminService) proxyHandler := admin.NewProxyHandler(adminService)
adminRedeemHandler := admin.NewRedeemHandler(adminService) adminRedeemHandler := admin.NewRedeemHandler(adminService)
settingHandler := admin.NewSettingHandler(settingService, emailService) settingHandler := admin.NewSettingHandler(settingService, emailService)
updateCache := repository.NewUpdateCache(client) updateCache := repository.NewUpdateCache(redisClient)
gitHubReleaseClient := repository.NewGitHubReleaseClient() gitHubReleaseClient := repository.NewGitHubReleaseClient()
serviceBuildInfo := provideServiceBuildInfo(buildInfo) serviceBuildInfo := provideServiceBuildInfo(buildInfo)
updateService := service.ProvideUpdateService(updateCache, gitHubReleaseClient, serviceBuildInfo) updateService := service.ProvideUpdateService(updateCache, gitHubReleaseClient, serviceBuildInfo)
@@ -108,14 +113,14 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
adminSubscriptionHandler := admin.NewSubscriptionHandler(subscriptionService) adminSubscriptionHandler := admin.NewSubscriptionHandler(subscriptionService)
adminUsageHandler := admin.NewUsageHandler(usageService, apiKeyService, adminService) adminUsageHandler := admin.NewUsageHandler(usageService, apiKeyService, adminService)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, proxyHandler, adminRedeemHandler, settingHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler) adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, proxyHandler, adminRedeemHandler, settingHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler)
gatewayCache := repository.NewGatewayCache(client) gatewayCache := repository.NewGatewayCache(redisClient)
pricingRemoteClient := repository.NewPricingRemoteClient() pricingRemoteClient := repository.NewPricingRemoteClient()
pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient) pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient)
if err != nil { if err != nil {
return nil, err return nil, err
} }
billingService := service.NewBillingService(configConfig, pricingService) billingService := service.NewBillingService(configConfig, pricingService)
identityCache := repository.NewIdentityCache(client) identityCache := repository.NewIdentityCache(redisClient)
identityService := service.NewIdentityService(identityCache) identityService := service.NewIdentityService(identityCache)
timingWheelService := service.ProvideTimingWheelService() timingWheelService := service.ProvideTimingWheelService()
deferredService := service.ProvideDeferredService(accountRepository, timingWheelService) deferredService := service.ProvideDeferredService(accountRepository, timingWheelService)
@@ -132,7 +137,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, apiKeyService, subscriptionService) engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, apiKeyService, subscriptionService)
httpServer := server.ProvideHTTPServer(configConfig, engine) httpServer := server.ProvideHTTPServer(configConfig, engine)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig) tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig)
v := provideCleanup(db, client, tokenRefreshService, pricingService, emailQueueService, oAuthService, openAIOAuthService, geminiOAuthService) v := provideCleanup(client, redisClient, tokenRefreshService, pricingService, emailQueueService, oAuthService, openAIOAuthService, geminiOAuthService)
application := &Application{ application := &Application{
Server: httpServer, Server: httpServer,
Cleanup: v, Cleanup: v,
@@ -155,7 +160,7 @@ func provideServiceBuildInfo(buildInfo handler.BuildInfo) service.BuildInfo {
} }
func provideCleanup( func provideCleanup(
db *gorm.DB, entClient *ent.Client,
rdb *redis.Client, rdb *redis.Client,
tokenRefresh *service.TokenRefreshService, tokenRefresh *service.TokenRefreshService,
pricing *service.PricingService, pricing *service.PricingService,
@@ -199,12 +204,8 @@ func provideCleanup(
{"Redis", func() error { {"Redis", func() error {
return rdb.Close() return rdb.Close()
}}, }},
{"Database", func() error { {"Ent", func() error {
sqlDB, err := db.DB() return entClient.Close()
if err != nil {
return err
}
return sqlDB.Close()
}}, }},
} }

407
backend/ent/account.go Normal file
View File

@@ -0,0 +1,407 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/account"
)
// Account is the model entity for the Account schema.
type Account 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"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Platform holds the value of the "platform" field.
Platform string `json:"platform,omitempty"`
// Type holds the value of the "type" field.
Type string `json:"type,omitempty"`
// Credentials holds the value of the "credentials" field.
Credentials map[string]interface{} `json:"credentials,omitempty"`
// Extra holds the value of the "extra" field.
Extra map[string]interface{} `json:"extra,omitempty"`
// ProxyID holds the value of the "proxy_id" field.
ProxyID *int64 `json:"proxy_id,omitempty"`
// Concurrency holds the value of the "concurrency" field.
Concurrency int `json:"concurrency,omitempty"`
// Priority holds the value of the "priority" field.
Priority int `json:"priority,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// ErrorMessage holds the value of the "error_message" field.
ErrorMessage *string `json:"error_message,omitempty"`
// LastUsedAt holds the value of the "last_used_at" field.
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
// Schedulable holds the value of the "schedulable" field.
Schedulable bool `json:"schedulable,omitempty"`
// RateLimitedAt holds the value of the "rate_limited_at" field.
RateLimitedAt *time.Time `json:"rate_limited_at,omitempty"`
// RateLimitResetAt holds the value of the "rate_limit_reset_at" field.
RateLimitResetAt *time.Time `json:"rate_limit_reset_at,omitempty"`
// OverloadUntil holds the value of the "overload_until" field.
OverloadUntil *time.Time `json:"overload_until,omitempty"`
// SessionWindowStart holds the value of the "session_window_start" field.
SessionWindowStart *time.Time `json:"session_window_start,omitempty"`
// SessionWindowEnd holds the value of the "session_window_end" field.
SessionWindowEnd *time.Time `json:"session_window_end,omitempty"`
// SessionWindowStatus holds the value of the "session_window_status" field.
SessionWindowStatus *string `json:"session_window_status,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AccountQuery when eager-loading is set.
Edges AccountEdges `json:"edges"`
selectValues sql.SelectValues
}
// AccountEdges holds the relations/edges for other nodes in the graph.
type AccountEdges struct {
// Groups holds the value of the groups edge.
Groups []*Group `json:"groups,omitempty"`
// AccountGroups holds the value of the account_groups edge.
AccountGroups []*AccountGroup `json:"account_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// GroupsOrErr returns the Groups value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) GroupsOrErr() ([]*Group, error) {
if e.loadedTypes[0] {
return e.Groups, nil
}
return nil, &NotLoadedError{edge: "groups"}
}
// AccountGroupsOrErr returns the AccountGroups value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
if e.loadedTypes[1] {
return e.AccountGroups, nil
}
return nil, &NotLoadedError{edge: "account_groups"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Account) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case account.FieldCredentials, account.FieldExtra:
values[i] = new([]byte)
case account.FieldSchedulable:
values[i] = new(sql.NullBool)
case account.FieldID, account.FieldProxyID, account.FieldConcurrency, account.FieldPriority:
values[i] = new(sql.NullInt64)
case account.FieldName, account.FieldPlatform, account.FieldType, account.FieldStatus, account.FieldErrorMessage, account.FieldSessionWindowStatus:
values[i] = new(sql.NullString)
case account.FieldCreatedAt, account.FieldUpdatedAt, account.FieldDeletedAt, account.FieldLastUsedAt, account.FieldRateLimitedAt, account.FieldRateLimitResetAt, account.FieldOverloadUntil, account.FieldSessionWindowStart, account.FieldSessionWindowEnd:
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 Account fields.
func (_m *Account) 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 account.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 account.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 account.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 account.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(time.Time)
*_m.DeletedAt = value.Time
}
case account.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case account.FieldPlatform:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field platform", values[i])
} else if value.Valid {
_m.Platform = value.String
}
case account.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_m.Type = value.String
}
case account.FieldCredentials:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field credentials", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Credentials); err != nil {
return fmt.Errorf("unmarshal field credentials: %w", err)
}
}
case account.FieldExtra:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field extra", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Extra); err != nil {
return fmt.Errorf("unmarshal field extra: %w", err)
}
}
case account.FieldProxyID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field proxy_id", values[i])
} else if value.Valid {
_m.ProxyID = new(int64)
*_m.ProxyID = value.Int64
}
case account.FieldConcurrency:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field concurrency", values[i])
} else if value.Valid {
_m.Concurrency = int(value.Int64)
}
case account.FieldPriority:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field priority", values[i])
} else if value.Valid {
_m.Priority = int(value.Int64)
}
case account.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
case account.FieldErrorMessage:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field error_message", values[i])
} else if value.Valid {
_m.ErrorMessage = new(string)
*_m.ErrorMessage = value.String
}
case account.FieldLastUsedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field last_used_at", values[i])
} else if value.Valid {
_m.LastUsedAt = new(time.Time)
*_m.LastUsedAt = value.Time
}
case account.FieldSchedulable:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field schedulable", values[i])
} else if value.Valid {
_m.Schedulable = value.Bool
}
case account.FieldRateLimitedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field rate_limited_at", values[i])
} else if value.Valid {
_m.RateLimitedAt = new(time.Time)
*_m.RateLimitedAt = value.Time
}
case account.FieldRateLimitResetAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field rate_limit_reset_at", values[i])
} else if value.Valid {
_m.RateLimitResetAt = new(time.Time)
*_m.RateLimitResetAt = value.Time
}
case account.FieldOverloadUntil:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field overload_until", values[i])
} else if value.Valid {
_m.OverloadUntil = new(time.Time)
*_m.OverloadUntil = value.Time
}
case account.FieldSessionWindowStart:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field session_window_start", values[i])
} else if value.Valid {
_m.SessionWindowStart = new(time.Time)
*_m.SessionWindowStart = value.Time
}
case account.FieldSessionWindowEnd:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field session_window_end", values[i])
} else if value.Valid {
_m.SessionWindowEnd = new(time.Time)
*_m.SessionWindowEnd = value.Time
}
case account.FieldSessionWindowStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field session_window_status", values[i])
} else if value.Valid {
_m.SessionWindowStatus = new(string)
*_m.SessionWindowStatus = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Account.
// This includes values selected through modifiers, order, etc.
func (_m *Account) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryGroups queries the "groups" edge of the Account entity.
func (_m *Account) QueryGroups() *GroupQuery {
return NewAccountClient(_m.config).QueryGroups(_m)
}
// QueryAccountGroups queries the "account_groups" edge of the Account entity.
func (_m *Account) QueryAccountGroups() *AccountGroupQuery {
return NewAccountClient(_m.config).QueryAccountGroups(_m)
}
// Update returns a builder for updating this Account.
// Note that you need to call Account.Unwrap() before calling this method if this Account
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Account) Update() *AccountUpdateOne {
return NewAccountClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Account 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 *Account) Unwrap() *Account {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Account is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Account) String() string {
var builder strings.Builder
builder.WriteString("Account(")
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(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("platform=")
builder.WriteString(_m.Platform)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(_m.Type)
builder.WriteString(", ")
builder.WriteString("credentials=")
builder.WriteString(fmt.Sprintf("%v", _m.Credentials))
builder.WriteString(", ")
builder.WriteString("extra=")
builder.WriteString(fmt.Sprintf("%v", _m.Extra))
builder.WriteString(", ")
if v := _m.ProxyID; v != nil {
builder.WriteString("proxy_id=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("concurrency=")
builder.WriteString(fmt.Sprintf("%v", _m.Concurrency))
builder.WriteString(", ")
builder.WriteString("priority=")
builder.WriteString(fmt.Sprintf("%v", _m.Priority))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
if v := _m.ErrorMessage; v != nil {
builder.WriteString("error_message=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.LastUsedAt; v != nil {
builder.WriteString("last_used_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("schedulable=")
builder.WriteString(fmt.Sprintf("%v", _m.Schedulable))
builder.WriteString(", ")
if v := _m.RateLimitedAt; v != nil {
builder.WriteString("rate_limited_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.RateLimitResetAt; v != nil {
builder.WriteString("rate_limit_reset_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.OverloadUntil; v != nil {
builder.WriteString("overload_until=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.SessionWindowStart; v != nil {
builder.WriteString("session_window_start=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.SessionWindowEnd; v != nil {
builder.WriteString("session_window_end=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.SessionWindowStatus; v != nil {
builder.WriteString("session_window_status=")
builder.WriteString(*v)
}
builder.WriteByte(')')
return builder.String()
}
// Accounts is a parsable slice of Account.
type Accounts []*Account

View File

@@ -0,0 +1,303 @@
// Code generated by ent, DO NOT EDIT.
package account
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the account type in the database.
Label = "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"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldPlatform holds the string denoting the platform field in the database.
FieldPlatform = "platform"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldCredentials holds the string denoting the credentials field in the database.
FieldCredentials = "credentials"
// FieldExtra holds the string denoting the extra field in the database.
FieldExtra = "extra"
// FieldProxyID holds the string denoting the proxy_id field in the database.
FieldProxyID = "proxy_id"
// FieldConcurrency holds the string denoting the concurrency field in the database.
FieldConcurrency = "concurrency"
// FieldPriority holds the string denoting the priority field in the database.
FieldPriority = "priority"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldErrorMessage holds the string denoting the error_message field in the database.
FieldErrorMessage = "error_message"
// FieldLastUsedAt holds the string denoting the last_used_at field in the database.
FieldLastUsedAt = "last_used_at"
// FieldSchedulable holds the string denoting the schedulable field in the database.
FieldSchedulable = "schedulable"
// FieldRateLimitedAt holds the string denoting the rate_limited_at field in the database.
FieldRateLimitedAt = "rate_limited_at"
// FieldRateLimitResetAt holds the string denoting the rate_limit_reset_at field in the database.
FieldRateLimitResetAt = "rate_limit_reset_at"
// FieldOverloadUntil holds the string denoting the overload_until field in the database.
FieldOverloadUntil = "overload_until"
// FieldSessionWindowStart holds the string denoting the session_window_start field in the database.
FieldSessionWindowStart = "session_window_start"
// FieldSessionWindowEnd holds the string denoting the session_window_end field in the database.
FieldSessionWindowEnd = "session_window_end"
// FieldSessionWindowStatus holds the string denoting the session_window_status field in the database.
FieldSessionWindowStatus = "session_window_status"
// EdgeGroups holds the string denoting the groups edge name in mutations.
EdgeGroups = "groups"
// EdgeAccountGroups holds the string denoting the account_groups edge name in mutations.
EdgeAccountGroups = "account_groups"
// Table holds the table name of the account in the database.
Table = "accounts"
// GroupsTable is the table that holds the groups relation/edge. The primary key declared below.
GroupsTable = "account_groups"
// GroupsInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupsInverseTable = "groups"
// AccountGroupsTable is the table that holds the account_groups relation/edge.
AccountGroupsTable = "account_groups"
// AccountGroupsInverseTable is the table name for the AccountGroup entity.
// It exists in this package in order to avoid circular dependency with the "accountgroup" package.
AccountGroupsInverseTable = "account_groups"
// AccountGroupsColumn is the table column denoting the account_groups relation/edge.
AccountGroupsColumn = "account_id"
)
// Columns holds all SQL columns for account fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldName,
FieldPlatform,
FieldType,
FieldCredentials,
FieldExtra,
FieldProxyID,
FieldConcurrency,
FieldPriority,
FieldStatus,
FieldErrorMessage,
FieldLastUsedAt,
FieldSchedulable,
FieldRateLimitedAt,
FieldRateLimitResetAt,
FieldOverloadUntil,
FieldSessionWindowStart,
FieldSessionWindowEnd,
FieldSessionWindowStatus,
}
var (
// GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the
// primary key for the groups relation (M2M).
GroupsPrimaryKey = []string{"account_id", "group_id"}
)
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "github.com/Wei-Shaw/sub2api/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
// 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
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
PlatformValidator func(string) error
// TypeValidator is a validator for the "type" field. It is called by the builders before save.
TypeValidator func(string) error
// DefaultCredentials holds the default value on creation for the "credentials" field.
DefaultCredentials func() map[string]interface{}
// DefaultExtra holds the default value on creation for the "extra" field.
DefaultExtra func() map[string]interface{}
// DefaultConcurrency holds the default value on creation for the "concurrency" field.
DefaultConcurrency int
// DefaultPriority holds the default value on creation for the "priority" field.
DefaultPriority int
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DefaultSchedulable holds the default value on creation for the "schedulable" field.
DefaultSchedulable bool
// SessionWindowStatusValidator is a validator for the "session_window_status" field. It is called by the builders before save.
SessionWindowStatusValidator func(string) error
)
// OrderOption defines the ordering options for the Account 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()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByPlatform orders the results by the platform field.
func ByPlatform(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPlatform, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByProxyID orders the results by the proxy_id field.
func ByProxyID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldProxyID, opts...).ToFunc()
}
// ByConcurrency orders the results by the concurrency field.
func ByConcurrency(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldConcurrency, opts...).ToFunc()
}
// ByPriority orders the results by the priority field.
func ByPriority(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPriority, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByErrorMessage orders the results by the error_message field.
func ByErrorMessage(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldErrorMessage, opts...).ToFunc()
}
// ByLastUsedAt orders the results by the last_used_at field.
func ByLastUsedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLastUsedAt, opts...).ToFunc()
}
// BySchedulable orders the results by the schedulable field.
func BySchedulable(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSchedulable, opts...).ToFunc()
}
// ByRateLimitedAt orders the results by the rate_limited_at field.
func ByRateLimitedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRateLimitedAt, opts...).ToFunc()
}
// ByRateLimitResetAt orders the results by the rate_limit_reset_at field.
func ByRateLimitResetAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRateLimitResetAt, opts...).ToFunc()
}
// ByOverloadUntil orders the results by the overload_until field.
func ByOverloadUntil(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOverloadUntil, opts...).ToFunc()
}
// BySessionWindowStart orders the results by the session_window_start field.
func BySessionWindowStart(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSessionWindowStart, opts...).ToFunc()
}
// BySessionWindowEnd orders the results by the session_window_end field.
func BySessionWindowEnd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSessionWindowEnd, opts...).ToFunc()
}
// BySessionWindowStatus orders the results by the session_window_status field.
func BySessionWindowStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSessionWindowStatus, opts...).ToFunc()
}
// ByGroupsCount orders the results by groups count.
func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...)
}
}
// ByGroups orders the results by groups terms.
func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAccountGroupsCount orders the results by account_groups count.
func ByAccountGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAccountGroupsStep(), opts...)
}
}
// ByAccountGroups orders the results by account_groups terms.
func ByAccountGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAccountGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...),
)
}
func newAccountGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AccountGroupsInverseTable, AccountGroupsColumn),
sqlgraph.Edge(sqlgraph.O2M, true, AccountGroupsTable, AccountGroupsColumn),
)
}

1192
backend/ent/account/where.go Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
// 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/account"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// AccountDelete is the builder for deleting a Account entity.
type AccountDelete struct {
config
hooks []Hook
mutation *AccountMutation
}
// Where appends a list predicates to the AccountDelete builder.
func (_d *AccountDelete) Where(ps ...predicate.Account) *AccountDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *AccountDelete) 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 *AccountDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *AccountDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(account.Table, sqlgraph.NewFieldSpec(account.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
}
// AccountDeleteOne is the builder for deleting a single Account entity.
type AccountDeleteOne struct {
_d *AccountDelete
}
// Where appends a list predicates to the AccountDelete builder.
func (_d *AccountDeleteOne) Where(ps ...predicate.Account) *AccountDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *AccountDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{account.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *AccountDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,711 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// AccountQuery is the builder for querying Account entities.
type AccountQuery struct {
config
ctx *QueryContext
order []account.OrderOption
inters []Interceptor
predicates []predicate.Account
withGroups *GroupQuery
withAccountGroups *AccountGroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the AccountQuery builder.
func (_q *AccountQuery) Where(ps ...predicate.Account) *AccountQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *AccountQuery) Limit(limit int) *AccountQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *AccountQuery) Offset(offset int) *AccountQuery {
_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 *AccountQuery) Unique(unique bool) *AccountQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *AccountQuery) Order(o ...account.OrderOption) *AccountQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryGroups chains the current query on the "groups" edge.
func (_q *AccountQuery) QueryGroups() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, account.GroupsTable, account.GroupsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryAccountGroups chains the current query on the "account_groups" edge.
func (_q *AccountQuery) QueryAccountGroups() *AccountGroupQuery {
query := (&AccountGroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(accountgroup.Table, accountgroup.AccountColumn),
sqlgraph.Edge(sqlgraph.O2M, true, account.AccountGroupsTable, account.AccountGroupsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Account entity from the query.
// Returns a *NotFoundError when no Account was found.
func (_q *AccountQuery) First(ctx context.Context) (*Account, 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{account.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *AccountQuery) FirstX(ctx context.Context) *Account {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Account ID from the query.
// Returns a *NotFoundError when no Account ID was found.
func (_q *AccountQuery) 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{account.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *AccountQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Account entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Account entity is found.
// Returns a *NotFoundError when no Account entities are found.
func (_q *AccountQuery) Only(ctx context.Context) (*Account, 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{account.Label}
default:
return nil, &NotSingularError{account.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *AccountQuery) OnlyX(ctx context.Context) *Account {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Account ID in the query.
// Returns a *NotSingularError when more than one Account ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *AccountQuery) 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{account.Label}
default:
err = &NotSingularError{account.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *AccountQuery) 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 Accounts.
func (_q *AccountQuery) All(ctx context.Context) ([]*Account, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Account, *AccountQuery]()
return withInterceptors[[]*Account](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *AccountQuery) AllX(ctx context.Context) []*Account {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Account IDs.
func (_q *AccountQuery) 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(account.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *AccountQuery) 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 *AccountQuery) 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[*AccountQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *AccountQuery) 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 *AccountQuery) 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 *AccountQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the AccountQuery 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 *AccountQuery) Clone() *AccountQuery {
if _q == nil {
return nil
}
return &AccountQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]account.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Account{}, _q.predicates...),
withGroups: _q.withGroups.Clone(),
withAccountGroups: _q.withAccountGroups.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithGroups tells the query-builder to eager-load the nodes that are connected to
// the "groups" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithGroups(opts ...func(*GroupQuery)) *AccountQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroups = query
return _q
}
// WithAccountGroups tells the query-builder to eager-load the nodes that are connected to
// the "account_groups" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithAccountGroups(opts ...func(*AccountGroupQuery)) *AccountQuery {
query := (&AccountGroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withAccountGroups = query
return _q
}
// 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.Account.Query().
// GroupBy(account.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *AccountQuery) GroupBy(field string, fields ...string) *AccountGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &AccountGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = account.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.Account.Query().
// Select(account.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *AccountQuery) Select(fields ...string) *AccountSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &AccountSelect{AccountQuery: _q}
sbuild.label = account.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a AccountSelect configured with the given aggregations.
func (_q *AccountQuery) Aggregate(fns ...AggregateFunc) *AccountSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *AccountQuery) 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 !account.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 *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Account, error) {
var (
nodes = []*Account{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withGroups != nil,
_q.withAccountGroups != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Account).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Account{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withGroups; query != nil {
if err := _q.loadGroups(ctx, query, nodes,
func(n *Account) { n.Edges.Groups = []*Group{} },
func(n *Account, e *Group) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil {
return nil, err
}
}
if query := _q.withAccountGroups; query != nil {
if err := _q.loadAccountGroups(ctx, query, nodes,
func(n *Account) { n.Edges.AccountGroups = []*AccountGroup{} },
func(n *Account, e *AccountGroup) { n.Edges.AccountGroups = append(n.Edges.AccountGroups, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *AccountQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes []*Account, init func(*Account), assign func(*Account, *Group)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int64]*Account)
nids := make(map[int64]map[*Account]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(account.GroupsTable)
s.Join(joinT).On(s.C(group.FieldID), joinT.C(account.GroupsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(account.GroupsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(account.GroupsPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := values[0].(*sql.NullInt64).Int64
inValue := values[1].(*sql.NullInt64).Int64
if nids[inValue] == nil {
nids[inValue] = map[*Account]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Group](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "groups" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *AccountQuery) loadAccountGroups(ctx context.Context, query *AccountGroupQuery, nodes []*Account, init func(*Account), assign func(*Account, *AccountGroup)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*Account)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
if len(query.ctx.Fields) > 0 {
query.ctx.AppendFieldOnce(accountgroup.FieldAccountID)
}
query.Where(predicate.AccountGroup(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(account.AccountGroupsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.AccountID
node, ok := nodeids[fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "account_id" returned %v for node %v`, fk, n)
}
assign(node, n)
}
return nil
}
func (_q *AccountQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *AccountQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(account.Table, account.Columns, sqlgraph.NewFieldSpec(account.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, account.FieldID)
for i := range fields {
if fields[i] != account.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 *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(account.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = account.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AccountGroupBy is the group-by builder for Account entities.
type AccountGroupBy struct {
selector
build *AccountQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *AccountGroupBy) Aggregate(fns ...AggregateFunc) *AccountGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *AccountGroupBy) 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[*AccountQuery, *AccountGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *AccountGroupBy) sqlScan(ctx context.Context, root *AccountQuery, 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)
}
// AccountSelect is the builder for selecting fields of Account entities.
type AccountSelect struct {
*AccountQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *AccountSelect) Aggregate(fns ...AggregateFunc) *AccountSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *AccountSelect) 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[*AccountQuery, *AccountSelect](ctx, _s.AccountQuery, _s, _s.inters, v)
}
func (_s *AccountSelect) sqlScan(ctx context.Context, root *AccountQuery, 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)
}

File diff suppressed because it is too large Load Diff

176
backend/ent/accountgroup.go Normal file
View File

@@ -0,0 +1,176 @@
// 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/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/group"
)
// AccountGroup is the model entity for the AccountGroup schema.
type AccountGroup struct {
config `json:"-"`
// AccountID holds the value of the "account_id" field.
AccountID int64 `json:"account_id,omitempty"`
// GroupID holds the value of the "group_id" field.
GroupID int64 `json:"group_id,omitempty"`
// Priority holds the value of the "priority" field.
Priority int `json:"priority,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AccountGroupQuery when eager-loading is set.
Edges AccountGroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// AccountGroupEdges holds the relations/edges for other nodes in the graph.
type AccountGroupEdges struct {
// Account holds the value of the account edge.
Account *Account `json:"account,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// AccountOrErr returns the Account value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e AccountGroupEdges) AccountOrErr() (*Account, error) {
if e.Account != nil {
return e.Account, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: account.Label}
}
return nil, &NotLoadedError{edge: "account"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e AccountGroupEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*AccountGroup) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case accountgroup.FieldAccountID, accountgroup.FieldGroupID, accountgroup.FieldPriority:
values[i] = new(sql.NullInt64)
case accountgroup.FieldCreatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the AccountGroup fields.
func (_m *AccountGroup) 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 accountgroup.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 accountgroup.FieldGroupID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field group_id", values[i])
} else if value.Valid {
_m.GroupID = value.Int64
}
case accountgroup.FieldPriority:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field priority", values[i])
} else if value.Valid {
_m.Priority = int(value.Int64)
}
case accountgroup.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the AccountGroup.
// This includes values selected through modifiers, order, etc.
func (_m *AccountGroup) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryAccount queries the "account" edge of the AccountGroup entity.
func (_m *AccountGroup) QueryAccount() *AccountQuery {
return NewAccountGroupClient(_m.config).QueryAccount(_m)
}
// QueryGroup queries the "group" edge of the AccountGroup entity.
func (_m *AccountGroup) QueryGroup() *GroupQuery {
return NewAccountGroupClient(_m.config).QueryGroup(_m)
}
// Update returns a builder for updating this AccountGroup.
// Note that you need to call AccountGroup.Unwrap() before calling this method if this AccountGroup
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *AccountGroup) Update() *AccountGroupUpdateOne {
return NewAccountGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the AccountGroup 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 *AccountGroup) Unwrap() *AccountGroup {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: AccountGroup is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *AccountGroup) String() string {
var builder strings.Builder
builder.WriteString("AccountGroup(")
builder.WriteString("account_id=")
builder.WriteString(fmt.Sprintf("%v", _m.AccountID))
builder.WriteString(", ")
builder.WriteString("group_id=")
builder.WriteString(fmt.Sprintf("%v", _m.GroupID))
builder.WriteString(", ")
builder.WriteString("priority=")
builder.WriteString(fmt.Sprintf("%v", _m.Priority))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// AccountGroups is a parsable slice of AccountGroup.
type AccountGroups []*AccountGroup

View File

@@ -0,0 +1,123 @@
// Code generated by ent, DO NOT EDIT.
package accountgroup
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the accountgroup type in the database.
Label = "account_group"
// FieldAccountID holds the string denoting the account_id field in the database.
FieldAccountID = "account_id"
// FieldGroupID holds the string denoting the group_id field in the database.
FieldGroupID = "group_id"
// FieldPriority holds the string denoting the priority field in the database.
FieldPriority = "priority"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// EdgeAccount holds the string denoting the account edge name in mutations.
EdgeAccount = "account"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// AccountFieldID holds the string denoting the ID field of the Account.
AccountFieldID = "id"
// GroupFieldID holds the string denoting the ID field of the Group.
GroupFieldID = "id"
// Table holds the table name of the accountgroup in the database.
Table = "account_groups"
// AccountTable is the table that holds the account relation/edge.
AccountTable = "account_groups"
// AccountInverseTable is the table name for the Account entity.
// It exists in this package in order to avoid circular dependency with the "account" package.
AccountInverseTable = "accounts"
// AccountColumn is the table column denoting the account relation/edge.
AccountColumn = "account_id"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "account_groups"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
)
// Columns holds all SQL columns for accountgroup fields.
var Columns = []string{
FieldAccountID,
FieldGroupID,
FieldPriority,
FieldCreatedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultPriority holds the default value on creation for the "priority" field.
DefaultPriority int
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the AccountGroup queries.
type OrderOption func(*sql.Selector)
// ByAccountID orders the results by the account_id field.
func ByAccountID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAccountID, opts...).ToFunc()
}
// ByGroupID orders the results by the group_id field.
func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGroupID, opts...).ToFunc()
}
// ByPriority orders the results by the priority field.
func ByPriority(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPriority, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByAccountField orders the results by account field.
func ByAccountField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAccountStep(), sql.OrderByField(field, opts...))
}
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
func newAccountStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, AccountColumn),
sqlgraph.To(AccountInverseTable, AccountFieldID),
sqlgraph.Edge(sqlgraph.M2O, false, AccountTable, AccountColumn),
)
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, GroupColumn),
sqlgraph.To(GroupInverseTable, GroupFieldID),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
}

View File

@@ -0,0 +1,212 @@
// Code generated by ent, DO NOT EDIT.
package accountgroup
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// AccountID applies equality check predicate on the "account_id" field. It's identical to AccountIDEQ.
func AccountID(v int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldAccountID, v))
}
// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
func GroupID(v int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldGroupID, v))
}
// Priority applies equality check predicate on the "priority" field. It's identical to PriorityEQ.
func Priority(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldPriority, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldCreatedAt, v))
}
// AccountIDEQ applies the EQ predicate on the "account_id" field.
func AccountIDEQ(v int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldAccountID, v))
}
// AccountIDNEQ applies the NEQ predicate on the "account_id" field.
func AccountIDNEQ(v int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNEQ(FieldAccountID, v))
}
// AccountIDIn applies the In predicate on the "account_id" field.
func AccountIDIn(vs ...int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldIn(FieldAccountID, vs...))
}
// AccountIDNotIn applies the NotIn predicate on the "account_id" field.
func AccountIDNotIn(vs ...int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNotIn(FieldAccountID, vs...))
}
// GroupIDEQ applies the EQ predicate on the "group_id" field.
func GroupIDEQ(v int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldGroupID, v))
}
// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
func GroupIDNEQ(v int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNEQ(FieldGroupID, v))
}
// GroupIDIn applies the In predicate on the "group_id" field.
func GroupIDIn(vs ...int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldIn(FieldGroupID, vs...))
}
// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
func GroupIDNotIn(vs ...int64) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNotIn(FieldGroupID, vs...))
}
// PriorityEQ applies the EQ predicate on the "priority" field.
func PriorityEQ(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldPriority, v))
}
// PriorityNEQ applies the NEQ predicate on the "priority" field.
func PriorityNEQ(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNEQ(FieldPriority, v))
}
// PriorityIn applies the In predicate on the "priority" field.
func PriorityIn(vs ...int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldIn(FieldPriority, vs...))
}
// PriorityNotIn applies the NotIn predicate on the "priority" field.
func PriorityNotIn(vs ...int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNotIn(FieldPriority, vs...))
}
// PriorityGT applies the GT predicate on the "priority" field.
func PriorityGT(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldGT(FieldPriority, v))
}
// PriorityGTE applies the GTE predicate on the "priority" field.
func PriorityGTE(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldGTE(FieldPriority, v))
}
// PriorityLT applies the LT predicate on the "priority" field.
func PriorityLT(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldLT(FieldPriority, v))
}
// PriorityLTE applies the LTE predicate on the "priority" field.
func PriorityLTE(v int) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldLTE(FieldPriority, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.AccountGroup {
return predicate.AccountGroup(sql.FieldLTE(FieldCreatedAt, v))
}
// HasAccount applies the HasEdge predicate on the "account" edge.
func HasAccount() predicate.AccountGroup {
return predicate.AccountGroup(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, AccountColumn),
sqlgraph.Edge(sqlgraph.M2O, false, AccountTable, AccountColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAccountWith applies the HasEdge predicate on the "account" edge with a given conditions (other predicates).
func HasAccountWith(preds ...predicate.Account) predicate.AccountGroup {
return predicate.AccountGroup(func(s *sql.Selector) {
step := newAccountStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.AccountGroup {
return predicate.AccountGroup(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, GroupColumn),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.AccountGroup {
return predicate.AccountGroup(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.AccountGroup) predicate.AccountGroup {
return predicate.AccountGroup(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.AccountGroup) predicate.AccountGroup {
return predicate.AccountGroup(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.AccountGroup) predicate.AccountGroup {
return predicate.AccountGroup(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,653 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/group"
)
// AccountGroupCreate is the builder for creating a AccountGroup entity.
type AccountGroupCreate struct {
config
mutation *AccountGroupMutation
hooks []Hook
conflict []sql.ConflictOption
}
// SetAccountID sets the "account_id" field.
func (_c *AccountGroupCreate) SetAccountID(v int64) *AccountGroupCreate {
_c.mutation.SetAccountID(v)
return _c
}
// SetGroupID sets the "group_id" field.
func (_c *AccountGroupCreate) SetGroupID(v int64) *AccountGroupCreate {
_c.mutation.SetGroupID(v)
return _c
}
// SetPriority sets the "priority" field.
func (_c *AccountGroupCreate) SetPriority(v int) *AccountGroupCreate {
_c.mutation.SetPriority(v)
return _c
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (_c *AccountGroupCreate) SetNillablePriority(v *int) *AccountGroupCreate {
if v != nil {
_c.SetPriority(*v)
}
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *AccountGroupCreate) SetCreatedAt(v time.Time) *AccountGroupCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *AccountGroupCreate) SetNillableCreatedAt(v *time.Time) *AccountGroupCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetAccount sets the "account" edge to the Account entity.
func (_c *AccountGroupCreate) SetAccount(v *Account) *AccountGroupCreate {
return _c.SetAccountID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_c *AccountGroupCreate) SetGroup(v *Group) *AccountGroupCreate {
return _c.SetGroupID(v.ID)
}
// Mutation returns the AccountGroupMutation object of the builder.
func (_c *AccountGroupCreate) Mutation() *AccountGroupMutation {
return _c.mutation
}
// Save creates the AccountGroup in the database.
func (_c *AccountGroupCreate) Save(ctx context.Context) (*AccountGroup, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *AccountGroupCreate) SaveX(ctx context.Context) *AccountGroup {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *AccountGroupCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *AccountGroupCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *AccountGroupCreate) defaults() {
if _, ok := _c.mutation.Priority(); !ok {
v := accountgroup.DefaultPriority
_c.mutation.SetPriority(v)
}
if _, ok := _c.mutation.CreatedAt(); !ok {
v := accountgroup.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *AccountGroupCreate) check() error {
if _, ok := _c.mutation.AccountID(); !ok {
return &ValidationError{Name: "account_id", err: errors.New(`ent: missing required field "AccountGroup.account_id"`)}
}
if _, ok := _c.mutation.GroupID(); !ok {
return &ValidationError{Name: "group_id", err: errors.New(`ent: missing required field "AccountGroup.group_id"`)}
}
if _, ok := _c.mutation.Priority(); !ok {
return &ValidationError{Name: "priority", err: errors.New(`ent: missing required field "AccountGroup.priority"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "AccountGroup.created_at"`)}
}
if len(_c.mutation.AccountIDs()) == 0 {
return &ValidationError{Name: "account", err: errors.New(`ent: missing required edge "AccountGroup.account"`)}
}
if len(_c.mutation.GroupIDs()) == 0 {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "AccountGroup.group"`)}
}
return nil
}
func (_c *AccountGroupCreate) sqlSave(ctx context.Context) (*AccountGroup, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}
func (_c *AccountGroupCreate) createSpec() (*AccountGroup, *sqlgraph.CreateSpec) {
var (
_node = &AccountGroup{config: _c.config}
_spec = sqlgraph.NewCreateSpec(accountgroup.Table, nil)
)
_spec.OnConflict = _c.conflict
if value, ok := _c.mutation.Priority(); ok {
_spec.SetField(accountgroup.FieldPriority, field.TypeInt, value)
_node.Priority = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(accountgroup.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := _c.mutation.AccountIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.AccountTable,
Columns: []string{accountgroup.AccountColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.AccountID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.GroupTable,
Columns: []string{accountgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.GroupID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.AccountGroup.Create().
// SetAccountID(v).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.AccountGroupUpsert) {
// SetAccountID(v+v).
// }).
// Exec(ctx)
func (_c *AccountGroupCreate) OnConflict(opts ...sql.ConflictOption) *AccountGroupUpsertOne {
_c.conflict = opts
return &AccountGroupUpsertOne{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.AccountGroup.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *AccountGroupCreate) OnConflictColumns(columns ...string) *AccountGroupUpsertOne {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &AccountGroupUpsertOne{
create: _c,
}
}
type (
// AccountGroupUpsertOne is the builder for "upsert"-ing
// one AccountGroup node.
AccountGroupUpsertOne struct {
create *AccountGroupCreate
}
// AccountGroupUpsert is the "OnConflict" setter.
AccountGroupUpsert struct {
*sql.UpdateSet
}
)
// SetAccountID sets the "account_id" field.
func (u *AccountGroupUpsert) SetAccountID(v int64) *AccountGroupUpsert {
u.Set(accountgroup.FieldAccountID, v)
return u
}
// UpdateAccountID sets the "account_id" field to the value that was provided on create.
func (u *AccountGroupUpsert) UpdateAccountID() *AccountGroupUpsert {
u.SetExcluded(accountgroup.FieldAccountID)
return u
}
// SetGroupID sets the "group_id" field.
func (u *AccountGroupUpsert) SetGroupID(v int64) *AccountGroupUpsert {
u.Set(accountgroup.FieldGroupID, v)
return u
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *AccountGroupUpsert) UpdateGroupID() *AccountGroupUpsert {
u.SetExcluded(accountgroup.FieldGroupID)
return u
}
// SetPriority sets the "priority" field.
func (u *AccountGroupUpsert) SetPriority(v int) *AccountGroupUpsert {
u.Set(accountgroup.FieldPriority, v)
return u
}
// UpdatePriority sets the "priority" field to the value that was provided on create.
func (u *AccountGroupUpsert) UpdatePriority() *AccountGroupUpsert {
u.SetExcluded(accountgroup.FieldPriority)
return u
}
// AddPriority adds v to the "priority" field.
func (u *AccountGroupUpsert) AddPriority(v int) *AccountGroupUpsert {
u.Add(accountgroup.FieldPriority, v)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
// client.AccountGroup.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *AccountGroupUpsertOne) UpdateNewValues() *AccountGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
if _, exists := u.create.mutation.CreatedAt(); exists {
s.SetIgnore(accountgroup.FieldCreatedAt)
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.AccountGroup.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *AccountGroupUpsertOne) Ignore() *AccountGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *AccountGroupUpsertOne) DoNothing() *AccountGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the AccountGroupCreate.OnConflict
// documentation for more info.
func (u *AccountGroupUpsertOne) Update(set func(*AccountGroupUpsert)) *AccountGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&AccountGroupUpsert{UpdateSet: update})
}))
return u
}
// SetAccountID sets the "account_id" field.
func (u *AccountGroupUpsertOne) SetAccountID(v int64) *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.SetAccountID(v)
})
}
// UpdateAccountID sets the "account_id" field to the value that was provided on create.
func (u *AccountGroupUpsertOne) UpdateAccountID() *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.UpdateAccountID()
})
}
// SetGroupID sets the "group_id" field.
func (u *AccountGroupUpsertOne) SetGroupID(v int64) *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.SetGroupID(v)
})
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *AccountGroupUpsertOne) UpdateGroupID() *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.UpdateGroupID()
})
}
// SetPriority sets the "priority" field.
func (u *AccountGroupUpsertOne) SetPriority(v int) *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.SetPriority(v)
})
}
// AddPriority adds v to the "priority" field.
func (u *AccountGroupUpsertOne) AddPriority(v int) *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.AddPriority(v)
})
}
// UpdatePriority sets the "priority" field to the value that was provided on create.
func (u *AccountGroupUpsertOne) UpdatePriority() *AccountGroupUpsertOne {
return u.Update(func(s *AccountGroupUpsert) {
s.UpdatePriority()
})
}
// Exec executes the query.
func (u *AccountGroupUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for AccountGroupCreate.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *AccountGroupUpsertOne) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}
// AccountGroupCreateBulk is the builder for creating many AccountGroup entities in bulk.
type AccountGroupCreateBulk struct {
config
err error
builders []*AccountGroupCreate
conflict []sql.ConflictOption
}
// Save creates the AccountGroup entities in the database.
func (_c *AccountGroupCreateBulk) Save(ctx context.Context) ([]*AccountGroup, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*AccountGroup, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AccountGroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
spec.OnConflict = _c.conflict
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *AccountGroupCreateBulk) SaveX(ctx context.Context) []*AccountGroup {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *AccountGroupCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *AccountGroupCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.AccountGroup.CreateBulk(builders...).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.AccountGroupUpsert) {
// SetAccountID(v+v).
// }).
// Exec(ctx)
func (_c *AccountGroupCreateBulk) OnConflict(opts ...sql.ConflictOption) *AccountGroupUpsertBulk {
_c.conflict = opts
return &AccountGroupUpsertBulk{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.AccountGroup.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *AccountGroupCreateBulk) OnConflictColumns(columns ...string) *AccountGroupUpsertBulk {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &AccountGroupUpsertBulk{
create: _c,
}
}
// AccountGroupUpsertBulk is the builder for "upsert"-ing
// a bulk of AccountGroup nodes.
type AccountGroupUpsertBulk struct {
create *AccountGroupCreateBulk
}
// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
// client.AccountGroup.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *AccountGroupUpsertBulk) UpdateNewValues() *AccountGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
for _, b := range u.create.builders {
if _, exists := b.mutation.CreatedAt(); exists {
s.SetIgnore(accountgroup.FieldCreatedAt)
}
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.AccountGroup.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *AccountGroupUpsertBulk) Ignore() *AccountGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *AccountGroupUpsertBulk) DoNothing() *AccountGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the AccountGroupCreateBulk.OnConflict
// documentation for more info.
func (u *AccountGroupUpsertBulk) Update(set func(*AccountGroupUpsert)) *AccountGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&AccountGroupUpsert{UpdateSet: update})
}))
return u
}
// SetAccountID sets the "account_id" field.
func (u *AccountGroupUpsertBulk) SetAccountID(v int64) *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.SetAccountID(v)
})
}
// UpdateAccountID sets the "account_id" field to the value that was provided on create.
func (u *AccountGroupUpsertBulk) UpdateAccountID() *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.UpdateAccountID()
})
}
// SetGroupID sets the "group_id" field.
func (u *AccountGroupUpsertBulk) SetGroupID(v int64) *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.SetGroupID(v)
})
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *AccountGroupUpsertBulk) UpdateGroupID() *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.UpdateGroupID()
})
}
// SetPriority sets the "priority" field.
func (u *AccountGroupUpsertBulk) SetPriority(v int) *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.SetPriority(v)
})
}
// AddPriority adds v to the "priority" field.
func (u *AccountGroupUpsertBulk) AddPriority(v int) *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.AddPriority(v)
})
}
// UpdatePriority sets the "priority" field to the value that was provided on create.
func (u *AccountGroupUpsertBulk) UpdatePriority() *AccountGroupUpsertBulk {
return u.Update(func(s *AccountGroupUpsert) {
s.UpdatePriority()
})
}
// Exec executes the query.
func (u *AccountGroupUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
return u.create.err
}
for i, b := range u.create.builders {
if len(b.conflict) != 0 {
return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the AccountGroupCreateBulk instead", i)
}
}
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for AccountGroupCreateBulk.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *AccountGroupUpsertBulk) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,87 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// AccountGroupDelete is the builder for deleting a AccountGroup entity.
type AccountGroupDelete struct {
config
hooks []Hook
mutation *AccountGroupMutation
}
// Where appends a list predicates to the AccountGroupDelete builder.
func (_d *AccountGroupDelete) Where(ps ...predicate.AccountGroup) *AccountGroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *AccountGroupDelete) 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 *AccountGroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *AccountGroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(accountgroup.Table, nil)
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
}
// AccountGroupDeleteOne is the builder for deleting a single AccountGroup entity.
type AccountGroupDeleteOne struct {
_d *AccountGroupDelete
}
// Where appends a list predicates to the AccountGroupDelete builder.
func (_d *AccountGroupDeleteOne) Where(ps ...predicate.AccountGroup) *AccountGroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *AccountGroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{accountgroup.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *AccountGroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,603 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// AccountGroupQuery is the builder for querying AccountGroup entities.
type AccountGroupQuery struct {
config
ctx *QueryContext
order []accountgroup.OrderOption
inters []Interceptor
predicates []predicate.AccountGroup
withAccount *AccountQuery
withGroup *GroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the AccountGroupQuery builder.
func (_q *AccountGroupQuery) Where(ps ...predicate.AccountGroup) *AccountGroupQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *AccountGroupQuery) Limit(limit int) *AccountGroupQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *AccountGroupQuery) Offset(offset int) *AccountGroupQuery {
_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 *AccountGroupQuery) Unique(unique bool) *AccountGroupQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *AccountGroupQuery) Order(o ...accountgroup.OrderOption) *AccountGroupQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryAccount chains the current query on the "account" edge.
func (_q *AccountGroupQuery) QueryAccount() *AccountQuery {
query := (&AccountClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(accountgroup.Table, accountgroup.AccountColumn, selector),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, accountgroup.AccountTable, accountgroup.AccountColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryGroup chains the current query on the "group" edge.
func (_q *AccountGroupQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(accountgroup.Table, accountgroup.GroupColumn, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, accountgroup.GroupTable, accountgroup.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first AccountGroup entity from the query.
// Returns a *NotFoundError when no AccountGroup was found.
func (_q *AccountGroupQuery) First(ctx context.Context) (*AccountGroup, 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{accountgroup.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *AccountGroupQuery) FirstX(ctx context.Context) *AccountGroup {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// Only returns a single AccountGroup entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one AccountGroup entity is found.
// Returns a *NotFoundError when no AccountGroup entities are found.
func (_q *AccountGroupQuery) Only(ctx context.Context) (*AccountGroup, 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{accountgroup.Label}
default:
return nil, &NotSingularError{accountgroup.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *AccountGroupQuery) OnlyX(ctx context.Context) *AccountGroup {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// All executes the query and returns a list of AccountGroups.
func (_q *AccountGroupQuery) All(ctx context.Context) ([]*AccountGroup, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*AccountGroup, *AccountGroupQuery]()
return withInterceptors[[]*AccountGroup](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *AccountGroupQuery) AllX(ctx context.Context) []*AccountGroup {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// Count returns the count of the given query.
func (_q *AccountGroupQuery) 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[*AccountGroupQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *AccountGroupQuery) 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 *AccountGroupQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.First(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 *AccountGroupQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the AccountGroupQuery 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 *AccountGroupQuery) Clone() *AccountGroupQuery {
if _q == nil {
return nil
}
return &AccountGroupQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]accountgroup.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.AccountGroup{}, _q.predicates...),
withAccount: _q.withAccount.Clone(),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithAccount tells the query-builder to eager-load the nodes that are connected to
// the "account" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountGroupQuery) WithAccount(opts ...func(*AccountQuery)) *AccountGroupQuery {
query := (&AccountClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withAccount = query
return _q
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountGroupQuery) WithGroup(opts ...func(*GroupQuery)) *AccountGroupQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = query
return _q
}
// 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 {
// AccountID int64 `json:"account_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.AccountGroup.Query().
// GroupBy(accountgroup.FieldAccountID).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *AccountGroupQuery) GroupBy(field string, fields ...string) *AccountGroupGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &AccountGroupGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = accountgroup.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 {
// AccountID int64 `json:"account_id,omitempty"`
// }
//
// client.AccountGroup.Query().
// Select(accountgroup.FieldAccountID).
// Scan(ctx, &v)
func (_q *AccountGroupQuery) Select(fields ...string) *AccountGroupSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &AccountGroupSelect{AccountGroupQuery: _q}
sbuild.label = accountgroup.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a AccountGroupSelect configured with the given aggregations.
func (_q *AccountGroupQuery) Aggregate(fns ...AggregateFunc) *AccountGroupSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *AccountGroupQuery) 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 !accountgroup.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 *AccountGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AccountGroup, error) {
var (
nodes = []*AccountGroup{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withAccount != nil,
_q.withGroup != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*AccountGroup).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &AccountGroup{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withAccount; query != nil {
if err := _q.loadAccount(ctx, query, nodes, nil,
func(n *AccountGroup, e *Account) { n.Edges.Account = e }); err != nil {
return nil, err
}
}
if query := _q.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes, nil,
func(n *AccountGroup, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *AccountGroupQuery) loadAccount(ctx context.Context, query *AccountQuery, nodes []*AccountGroup, init func(*AccountGroup), assign func(*AccountGroup, *Account)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*AccountGroup)
for i := range nodes {
fk := nodes[i].AccountID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(account.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "account_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *AccountGroupQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*AccountGroup, init func(*AccountGroup), assign func(*AccountGroup, *Group)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*AccountGroup)
for i := range nodes {
fk := nodes[i].GroupID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *AccountGroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Unique = false
_spec.Node.Columns = nil
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *AccountGroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(accountgroup.Table, accountgroup.Columns, nil)
_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))
for i := range fields {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
if _q.withAccount != nil {
_spec.Node.AddColumnOnce(accountgroup.FieldAccountID)
}
if _q.withGroup != nil {
_spec.Node.AddColumnOnce(accountgroup.FieldGroupID)
}
}
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 *AccountGroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(accountgroup.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = accountgroup.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AccountGroupGroupBy is the group-by builder for AccountGroup entities.
type AccountGroupGroupBy struct {
selector
build *AccountGroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *AccountGroupGroupBy) Aggregate(fns ...AggregateFunc) *AccountGroupGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *AccountGroupGroupBy) 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[*AccountGroupQuery, *AccountGroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *AccountGroupGroupBy) sqlScan(ctx context.Context, root *AccountGroupQuery, 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)
}
// AccountGroupSelect is the builder for selecting fields of AccountGroup entities.
type AccountGroupSelect struct {
*AccountGroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *AccountGroupSelect) Aggregate(fns ...AggregateFunc) *AccountGroupSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *AccountGroupSelect) 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[*AccountGroupQuery, *AccountGroupSelect](ctx, _s.AccountGroupQuery, _s, _s.inters, v)
}
func (_s *AccountGroupSelect) sqlScan(ctx context.Context, root *AccountGroupQuery, 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)
}

View File

@@ -0,0 +1,477 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// AccountGroupUpdate is the builder for updating AccountGroup entities.
type AccountGroupUpdate struct {
config
hooks []Hook
mutation *AccountGroupMutation
}
// Where appends a list predicates to the AccountGroupUpdate builder.
func (_u *AccountGroupUpdate) Where(ps ...predicate.AccountGroup) *AccountGroupUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetAccountID sets the "account_id" field.
func (_u *AccountGroupUpdate) SetAccountID(v int64) *AccountGroupUpdate {
_u.mutation.SetAccountID(v)
return _u
}
// SetNillableAccountID sets the "account_id" field if the given value is not nil.
func (_u *AccountGroupUpdate) SetNillableAccountID(v *int64) *AccountGroupUpdate {
if v != nil {
_u.SetAccountID(*v)
}
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *AccountGroupUpdate) SetGroupID(v int64) *AccountGroupUpdate {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *AccountGroupUpdate) SetNillableGroupID(v *int64) *AccountGroupUpdate {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// SetPriority sets the "priority" field.
func (_u *AccountGroupUpdate) SetPriority(v int) *AccountGroupUpdate {
_u.mutation.ResetPriority()
_u.mutation.SetPriority(v)
return _u
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (_u *AccountGroupUpdate) SetNillablePriority(v *int) *AccountGroupUpdate {
if v != nil {
_u.SetPriority(*v)
}
return _u
}
// AddPriority adds value to the "priority" field.
func (_u *AccountGroupUpdate) AddPriority(v int) *AccountGroupUpdate {
_u.mutation.AddPriority(v)
return _u
}
// SetAccount sets the "account" edge to the Account entity.
func (_u *AccountGroupUpdate) SetAccount(v *Account) *AccountGroupUpdate {
return _u.SetAccountID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *AccountGroupUpdate) SetGroup(v *Group) *AccountGroupUpdate {
return _u.SetGroupID(v.ID)
}
// Mutation returns the AccountGroupMutation object of the builder.
func (_u *AccountGroupUpdate) Mutation() *AccountGroupMutation {
return _u.mutation
}
// ClearAccount clears the "account" edge to the Account entity.
func (_u *AccountGroupUpdate) ClearAccount() *AccountGroupUpdate {
_u.mutation.ClearAccount()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *AccountGroupUpdate) ClearGroup() *AccountGroupUpdate {
_u.mutation.ClearGroup()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *AccountGroupUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *AccountGroupUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *AccountGroupUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *AccountGroupUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *AccountGroupUpdate) check() error {
if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "AccountGroup.account"`)
}
if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "AccountGroup.group"`)
}
return nil
}
func (_u *AccountGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(accountgroup.Table, accountgroup.Columns, sqlgraph.NewFieldSpec(accountgroup.FieldAccountID, field.TypeInt64), sqlgraph.NewFieldSpec(accountgroup.FieldGroupID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Priority(); ok {
_spec.SetField(accountgroup.FieldPriority, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedPriority(); ok {
_spec.AddField(accountgroup.FieldPriority, field.TypeInt, value)
}
if _u.mutation.AccountCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.AccountTable,
Columns: []string{accountgroup.AccountColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.AccountIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.AccountTable,
Columns: []string{accountgroup.AccountColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.GroupTable,
Columns: []string{accountgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.GroupTable,
Columns: []string{accountgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{accountgroup.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// AccountGroupUpdateOne is the builder for updating a single AccountGroup entity.
type AccountGroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *AccountGroupMutation
}
// SetAccountID sets the "account_id" field.
func (_u *AccountGroupUpdateOne) SetAccountID(v int64) *AccountGroupUpdateOne {
_u.mutation.SetAccountID(v)
return _u
}
// SetNillableAccountID sets the "account_id" field if the given value is not nil.
func (_u *AccountGroupUpdateOne) SetNillableAccountID(v *int64) *AccountGroupUpdateOne {
if v != nil {
_u.SetAccountID(*v)
}
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *AccountGroupUpdateOne) SetGroupID(v int64) *AccountGroupUpdateOne {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *AccountGroupUpdateOne) SetNillableGroupID(v *int64) *AccountGroupUpdateOne {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// SetPriority sets the "priority" field.
func (_u *AccountGroupUpdateOne) SetPriority(v int) *AccountGroupUpdateOne {
_u.mutation.ResetPriority()
_u.mutation.SetPriority(v)
return _u
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (_u *AccountGroupUpdateOne) SetNillablePriority(v *int) *AccountGroupUpdateOne {
if v != nil {
_u.SetPriority(*v)
}
return _u
}
// AddPriority adds value to the "priority" field.
func (_u *AccountGroupUpdateOne) AddPriority(v int) *AccountGroupUpdateOne {
_u.mutation.AddPriority(v)
return _u
}
// SetAccount sets the "account" edge to the Account entity.
func (_u *AccountGroupUpdateOne) SetAccount(v *Account) *AccountGroupUpdateOne {
return _u.SetAccountID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *AccountGroupUpdateOne) SetGroup(v *Group) *AccountGroupUpdateOne {
return _u.SetGroupID(v.ID)
}
// Mutation returns the AccountGroupMutation object of the builder.
func (_u *AccountGroupUpdateOne) Mutation() *AccountGroupMutation {
return _u.mutation
}
// ClearAccount clears the "account" edge to the Account entity.
func (_u *AccountGroupUpdateOne) ClearAccount() *AccountGroupUpdateOne {
_u.mutation.ClearAccount()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *AccountGroupUpdateOne) ClearGroup() *AccountGroupUpdateOne {
_u.mutation.ClearGroup()
return _u
}
// Where appends a list predicates to the AccountGroupUpdate builder.
func (_u *AccountGroupUpdateOne) Where(ps ...predicate.AccountGroup) *AccountGroupUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *AccountGroupUpdateOne) Select(field string, fields ...string) *AccountGroupUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated AccountGroup entity.
func (_u *AccountGroupUpdateOne) Save(ctx context.Context) (*AccountGroup, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *AccountGroupUpdateOne) SaveX(ctx context.Context) *AccountGroup {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *AccountGroupUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *AccountGroupUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *AccountGroupUpdateOne) check() error {
if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "AccountGroup.account"`)
}
if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "AccountGroup.group"`)
}
return nil
}
func (_u *AccountGroupUpdateOne) sqlSave(ctx context.Context) (_node *AccountGroup, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(accountgroup.Table, accountgroup.Columns, sqlgraph.NewFieldSpec(accountgroup.FieldAccountID, field.TypeInt64), sqlgraph.NewFieldSpec(accountgroup.FieldGroupID, field.TypeInt64))
if id, ok := _u.mutation.AccountID(); !ok {
return nil, &ValidationError{Name: "account_id", err: errors.New(`ent: missing "AccountGroup.account_id" for update`)}
} else {
_spec.Node.CompositeID[0].Value = id
}
if id, ok := _u.mutation.GroupID(); !ok {
return nil, &ValidationError{Name: "group_id", err: errors.New(`ent: missing "AccountGroup.group_id" for update`)}
} else {
_spec.Node.CompositeID[1].Value = id
}
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, len(fields))
for i, f := range fields {
if !accountgroup.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
_spec.Node.Columns[i] = f
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Priority(); ok {
_spec.SetField(accountgroup.FieldPriority, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedPriority(); ok {
_spec.AddField(accountgroup.FieldPriority, field.TypeInt, value)
}
if _u.mutation.AccountCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.AccountTable,
Columns: []string{accountgroup.AccountColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.AccountIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.AccountTable,
Columns: []string{accountgroup.AccountColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.GroupTable,
Columns: []string{accountgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: accountgroup.GroupTable,
Columns: []string{accountgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &AccountGroup{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{accountgroup.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

237
backend/ent/apikey.go Normal file
View File

@@ -0,0 +1,237 @@
// 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/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// ApiKey is the model entity for the ApiKey schema.
type ApiKey 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"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int64 `json:"user_id,omitempty"`
// Key holds the value of the "key" field.
Key string `json:"key,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// GroupID holds the value of the "group_id" field.
GroupID *int64 `json:"group_id,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the ApiKeyQuery when eager-loading is set.
Edges ApiKeyEdges `json:"edges"`
selectValues sql.SelectValues
}
// ApiKeyEdges holds the relations/edges for other nodes in the graph.
type ApiKeyEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ApiKeyEdges) UserOrErr() (*User, error) {
if e.User != nil {
return e.User, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "user"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ApiKeyEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*ApiKey) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case apikey.FieldID, apikey.FieldUserID, apikey.FieldGroupID:
values[i] = new(sql.NullInt64)
case apikey.FieldKey, apikey.FieldName, apikey.FieldStatus:
values[i] = new(sql.NullString)
case apikey.FieldCreatedAt, apikey.FieldUpdatedAt, apikey.FieldDeletedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the ApiKey fields.
func (_m *ApiKey) 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 apikey.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 apikey.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 apikey.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 apikey.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(time.Time)
*_m.DeletedAt = value.Time
}
case apikey.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = value.Int64
}
case apikey.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case apikey.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case apikey.FieldGroupID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field group_id", values[i])
} else if value.Valid {
_m.GroupID = new(int64)
*_m.GroupID = value.Int64
}
case apikey.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the ApiKey.
// This includes values selected through modifiers, order, etc.
func (_m *ApiKey) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the ApiKey entity.
func (_m *ApiKey) QueryUser() *UserQuery {
return NewApiKeyClient(_m.config).QueryUser(_m)
}
// QueryGroup queries the "group" edge of the ApiKey entity.
func (_m *ApiKey) QueryGroup() *GroupQuery {
return NewApiKeyClient(_m.config).QueryGroup(_m)
}
// Update returns a builder for updating this ApiKey.
// Note that you need to call ApiKey.Unwrap() before calling this method if this ApiKey
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *ApiKey) Update() *ApiKeyUpdateOne {
return NewApiKeyClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the ApiKey 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 *ApiKey) Unwrap() *ApiKey {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: ApiKey is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *ApiKey) String() string {
var builder strings.Builder
builder.WriteString("ApiKey(")
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(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
if v := _m.GroupID; v != nil {
builder.WriteString("group_id=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteByte(')')
return builder.String()
}
// ApiKeys is a parsable slice of ApiKey.
type ApiKeys []*ApiKey

View File

@@ -0,0 +1,177 @@
// Code generated by ent, DO NOT EDIT.
package apikey
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the apikey type in the database.
Label = "api_key"
// 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"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldGroupID holds the string denoting the group_id field in the database.
FieldGroupID = "group_id"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// Table holds the table name of the apikey in the database.
Table = "api_keys"
// UserTable is the table that holds the user relation/edge.
UserTable = "api_keys"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_id"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "api_keys"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
)
// Columns holds all SQL columns for apikey fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldUserID,
FieldKey,
FieldName,
FieldGroupID,
FieldStatus,
}
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "github.com/Wei-Shaw/sub2api/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
// 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
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
)
// OrderOption defines the ordering options for the ApiKey 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()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByGroupID orders the results by the group_id field.
func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGroupID, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
}

532
backend/ent/apikey/where.go Normal file
View File

@@ -0,0 +1,532 @@
// Code generated by ent, DO NOT EDIT.
package apikey
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldDeletedAt, v))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldUserID, v))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldKey, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldName, v))
}
// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
func GroupID(v int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldGroupID, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldStatus, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v time.Time) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.ApiKey {
return predicate.ApiKey(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotNull(FieldDeletedAt))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldUserID, vs...))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldContainsFold(FieldKey, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldContainsFold(FieldName, v))
}
// GroupIDEQ applies the EQ predicate on the "group_id" field.
func GroupIDEQ(v int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldGroupID, v))
}
// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
func GroupIDNEQ(v int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldGroupID, v))
}
// GroupIDIn applies the In predicate on the "group_id" field.
func GroupIDIn(vs ...int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldGroupID, vs...))
}
// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
func GroupIDNotIn(vs ...int64) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldGroupID, vs...))
}
// GroupIDIsNil applies the IsNil predicate on the "group_id" field.
func GroupIDIsNil() predicate.ApiKey {
return predicate.ApiKey(sql.FieldIsNull(FieldGroupID))
}
// GroupIDNotNil applies the NotNil predicate on the "group_id" field.
func GroupIDNotNil() predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotNull(FieldGroupID))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.ApiKey {
return predicate.ApiKey(sql.FieldContainsFold(FieldStatus, v))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.ApiKey {
return predicate.ApiKey(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.ApiKey {
return predicate.ApiKey(func(s *sql.Selector) {
step := newUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.ApiKey {
return predicate.ApiKey(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.ApiKey {
return predicate.ApiKey(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.ApiKey) predicate.ApiKey {
return predicate.ApiKey(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.ApiKey) predicate.ApiKey {
return predicate.ApiKey(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.ApiKey) predicate.ApiKey {
return predicate.ApiKey(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,955 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// ApiKeyCreate is the builder for creating a ApiKey entity.
type ApiKeyCreate struct {
config
mutation *ApiKeyMutation
hooks []Hook
conflict []sql.ConflictOption
}
// SetCreatedAt sets the "created_at" field.
func (_c *ApiKeyCreate) SetCreatedAt(v time.Time) *ApiKeyCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableCreatedAt(v *time.Time) *ApiKeyCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *ApiKeyCreate) SetUpdatedAt(v time.Time) *ApiKeyCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableUpdatedAt(v *time.Time) *ApiKeyCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetDeletedAt sets the "deleted_at" field.
func (_c *ApiKeyCreate) SetDeletedAt(v time.Time) *ApiKeyCreate {
_c.mutation.SetDeletedAt(v)
return _c
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableDeletedAt(v *time.Time) *ApiKeyCreate {
if v != nil {
_c.SetDeletedAt(*v)
}
return _c
}
// SetUserID sets the "user_id" field.
func (_c *ApiKeyCreate) SetUserID(v int64) *ApiKeyCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetKey sets the "key" field.
func (_c *ApiKeyCreate) SetKey(v string) *ApiKeyCreate {
_c.mutation.SetKey(v)
return _c
}
// SetName sets the "name" field.
func (_c *ApiKeyCreate) SetName(v string) *ApiKeyCreate {
_c.mutation.SetName(v)
return _c
}
// SetGroupID sets the "group_id" field.
func (_c *ApiKeyCreate) SetGroupID(v int64) *ApiKeyCreate {
_c.mutation.SetGroupID(v)
return _c
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableGroupID(v *int64) *ApiKeyCreate {
if v != nil {
_c.SetGroupID(*v)
}
return _c
}
// SetStatus sets the "status" field.
func (_c *ApiKeyCreate) SetStatus(v string) *ApiKeyCreate {
_c.mutation.SetStatus(v)
return _c
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableStatus(v *string) *ApiKeyCreate {
if v != nil {
_c.SetStatus(*v)
}
return _c
}
// SetUser sets the "user" edge to the User entity.
func (_c *ApiKeyCreate) SetUser(v *User) *ApiKeyCreate {
return _c.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_c *ApiKeyCreate) SetGroup(v *Group) *ApiKeyCreate {
return _c.SetGroupID(v.ID)
}
// Mutation returns the ApiKeyMutation object of the builder.
func (_c *ApiKeyCreate) Mutation() *ApiKeyMutation {
return _c.mutation
}
// Save creates the ApiKey in the database.
func (_c *ApiKeyCreate) Save(ctx context.Context) (*ApiKey, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *ApiKeyCreate) SaveX(ctx context.Context) *ApiKey {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ApiKeyCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ApiKeyCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *ApiKeyCreate) defaults() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
if apikey.DefaultCreatedAt == nil {
return fmt.Errorf("ent: uninitialized apikey.DefaultCreatedAt (forgotten import ent/runtime?)")
}
v := apikey.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
if apikey.DefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized apikey.DefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := apikey.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
if _, ok := _c.mutation.Status(); !ok {
v := apikey.DefaultStatus
_c.mutation.SetStatus(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *ApiKeyCreate) check() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ApiKey.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ApiKey.updated_at"`)}
}
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "ApiKey.user_id"`)}
}
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "ApiKey.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := apikey.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "ApiKey.key": %w`, err)}
}
}
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ApiKey.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := apikey.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ApiKey.name": %w`, err)}
}
}
if _, ok := _c.mutation.Status(); !ok {
return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "ApiKey.status"`)}
}
if v, ok := _c.mutation.Status(); ok {
if err := apikey.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "ApiKey.status": %w`, err)}
}
}
if len(_c.mutation.UserIDs()) == 0 {
return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "ApiKey.user"`)}
}
return nil
}
func (_c *ApiKeyCreate) sqlSave(ctx context.Context) (*ApiKey, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int64(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *ApiKeyCreate) createSpec() (*ApiKey, *sqlgraph.CreateSpec) {
var (
_node = &ApiKey{config: _c.config}
_spec = sqlgraph.NewCreateSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeInt64))
)
_spec.OnConflict = _c.conflict
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(apikey.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if value, ok := _c.mutation.DeletedAt(); ok {
_spec.SetField(apikey.FieldDeletedAt, field.TypeTime, value)
_node.DeletedAt = &value
}
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(apikey.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(apikey.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.Status(); ok {
_spec.SetField(apikey.FieldStatus, field.TypeString, value)
_node.Status = value
}
if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.UserTable,
Columns: []string{apikey.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.UserID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.GroupTable,
Columns: []string{apikey.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.GroupID = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.ApiKey.Create().
// SetCreatedAt(v).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.ApiKeyUpsert) {
// SetCreatedAt(v+v).
// }).
// Exec(ctx)
func (_c *ApiKeyCreate) OnConflict(opts ...sql.ConflictOption) *ApiKeyUpsertOne {
_c.conflict = opts
return &ApiKeyUpsertOne{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.ApiKey.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *ApiKeyCreate) OnConflictColumns(columns ...string) *ApiKeyUpsertOne {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &ApiKeyUpsertOne{
create: _c,
}
}
type (
// ApiKeyUpsertOne is the builder for "upsert"-ing
// one ApiKey node.
ApiKeyUpsertOne struct {
create *ApiKeyCreate
}
// ApiKeyUpsert is the "OnConflict" setter.
ApiKeyUpsert struct {
*sql.UpdateSet
}
)
// SetUpdatedAt sets the "updated_at" field.
func (u *ApiKeyUpsert) SetUpdatedAt(v time.Time) *ApiKeyUpsert {
u.Set(apikey.FieldUpdatedAt, v)
return u
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateUpdatedAt() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldUpdatedAt)
return u
}
// SetDeletedAt sets the "deleted_at" field.
func (u *ApiKeyUpsert) SetDeletedAt(v time.Time) *ApiKeyUpsert {
u.Set(apikey.FieldDeletedAt, v)
return u
}
// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateDeletedAt() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldDeletedAt)
return u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *ApiKeyUpsert) ClearDeletedAt() *ApiKeyUpsert {
u.SetNull(apikey.FieldDeletedAt)
return u
}
// SetUserID sets the "user_id" field.
func (u *ApiKeyUpsert) SetUserID(v int64) *ApiKeyUpsert {
u.Set(apikey.FieldUserID, v)
return u
}
// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateUserID() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldUserID)
return u
}
// SetKey sets the "key" field.
func (u *ApiKeyUpsert) SetKey(v string) *ApiKeyUpsert {
u.Set(apikey.FieldKey, v)
return u
}
// UpdateKey sets the "key" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateKey() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldKey)
return u
}
// SetName sets the "name" field.
func (u *ApiKeyUpsert) SetName(v string) *ApiKeyUpsert {
u.Set(apikey.FieldName, v)
return u
}
// UpdateName sets the "name" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateName() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldName)
return u
}
// SetGroupID sets the "group_id" field.
func (u *ApiKeyUpsert) SetGroupID(v int64) *ApiKeyUpsert {
u.Set(apikey.FieldGroupID, v)
return u
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateGroupID() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldGroupID)
return u
}
// ClearGroupID clears the value of the "group_id" field.
func (u *ApiKeyUpsert) ClearGroupID() *ApiKeyUpsert {
u.SetNull(apikey.FieldGroupID)
return u
}
// SetStatus sets the "status" field.
func (u *ApiKeyUpsert) SetStatus(v string) *ApiKeyUpsert {
u.Set(apikey.FieldStatus, v)
return u
}
// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateStatus() *ApiKeyUpsert {
u.SetExcluded(apikey.FieldStatus)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
// client.ApiKey.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *ApiKeyUpsertOne) UpdateNewValues() *ApiKeyUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
if _, exists := u.create.mutation.CreatedAt(); exists {
s.SetIgnore(apikey.FieldCreatedAt)
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.ApiKey.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *ApiKeyUpsertOne) Ignore() *ApiKeyUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *ApiKeyUpsertOne) DoNothing() *ApiKeyUpsertOne {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the ApiKeyCreate.OnConflict
// documentation for more info.
func (u *ApiKeyUpsertOne) Update(set func(*ApiKeyUpsert)) *ApiKeyUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&ApiKeyUpsert{UpdateSet: update})
}))
return u
}
// SetUpdatedAt sets the "updated_at" field.
func (u *ApiKeyUpsertOne) SetUpdatedAt(v time.Time) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetUpdatedAt(v)
})
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateUpdatedAt() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateUpdatedAt()
})
}
// SetDeletedAt sets the "deleted_at" field.
func (u *ApiKeyUpsertOne) SetDeletedAt(v time.Time) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetDeletedAt(v)
})
}
// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateDeletedAt() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateDeletedAt()
})
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *ApiKeyUpsertOne) ClearDeletedAt() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.ClearDeletedAt()
})
}
// SetUserID sets the "user_id" field.
func (u *ApiKeyUpsertOne) SetUserID(v int64) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetUserID(v)
})
}
// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateUserID() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateUserID()
})
}
// SetKey sets the "key" field.
func (u *ApiKeyUpsertOne) SetKey(v string) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetKey(v)
})
}
// UpdateKey sets the "key" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateKey() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateKey()
})
}
// SetName sets the "name" field.
func (u *ApiKeyUpsertOne) SetName(v string) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetName(v)
})
}
// UpdateName sets the "name" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateName() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateName()
})
}
// SetGroupID sets the "group_id" field.
func (u *ApiKeyUpsertOne) SetGroupID(v int64) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetGroupID(v)
})
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateGroupID() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateGroupID()
})
}
// ClearGroupID clears the value of the "group_id" field.
func (u *ApiKeyUpsertOne) ClearGroupID() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.ClearGroupID()
})
}
// SetStatus sets the "status" field.
func (u *ApiKeyUpsertOne) SetStatus(v string) *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.SetStatus(v)
})
}
// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateStatus() *ApiKeyUpsertOne {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateStatus()
})
}
// Exec executes the query.
func (u *ApiKeyUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for ApiKeyCreate.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *ApiKeyUpsertOne) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}
// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *ApiKeyUpsertOne) ID(ctx context.Context) (id int64, err error) {
node, err := u.create.Save(ctx)
if err != nil {
return id, err
}
return node.ID, nil
}
// IDX is like ID, but panics if an error occurs.
func (u *ApiKeyUpsertOne) IDX(ctx context.Context) int64 {
id, err := u.ID(ctx)
if err != nil {
panic(err)
}
return id
}
// ApiKeyCreateBulk is the builder for creating many ApiKey entities in bulk.
type ApiKeyCreateBulk struct {
config
err error
builders []*ApiKeyCreate
conflict []sql.ConflictOption
}
// Save creates the ApiKey entities in the database.
func (_c *ApiKeyCreateBulk) Save(ctx context.Context) ([]*ApiKey, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*ApiKey, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ApiKeyMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
spec.OnConflict = _c.conflict
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int64(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *ApiKeyCreateBulk) SaveX(ctx context.Context) []*ApiKey {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ApiKeyCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ApiKeyCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.ApiKey.CreateBulk(builders...).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.ApiKeyUpsert) {
// SetCreatedAt(v+v).
// }).
// Exec(ctx)
func (_c *ApiKeyCreateBulk) OnConflict(opts ...sql.ConflictOption) *ApiKeyUpsertBulk {
_c.conflict = opts
return &ApiKeyUpsertBulk{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.ApiKey.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *ApiKeyCreateBulk) OnConflictColumns(columns ...string) *ApiKeyUpsertBulk {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &ApiKeyUpsertBulk{
create: _c,
}
}
// ApiKeyUpsertBulk is the builder for "upsert"-ing
// a bulk of ApiKey nodes.
type ApiKeyUpsertBulk struct {
create *ApiKeyCreateBulk
}
// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
// client.ApiKey.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *ApiKeyUpsertBulk) UpdateNewValues() *ApiKeyUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
for _, b := range u.create.builders {
if _, exists := b.mutation.CreatedAt(); exists {
s.SetIgnore(apikey.FieldCreatedAt)
}
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.ApiKey.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *ApiKeyUpsertBulk) Ignore() *ApiKeyUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *ApiKeyUpsertBulk) DoNothing() *ApiKeyUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the ApiKeyCreateBulk.OnConflict
// documentation for more info.
func (u *ApiKeyUpsertBulk) Update(set func(*ApiKeyUpsert)) *ApiKeyUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&ApiKeyUpsert{UpdateSet: update})
}))
return u
}
// SetUpdatedAt sets the "updated_at" field.
func (u *ApiKeyUpsertBulk) SetUpdatedAt(v time.Time) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetUpdatedAt(v)
})
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateUpdatedAt() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateUpdatedAt()
})
}
// SetDeletedAt sets the "deleted_at" field.
func (u *ApiKeyUpsertBulk) SetDeletedAt(v time.Time) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetDeletedAt(v)
})
}
// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateDeletedAt() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateDeletedAt()
})
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *ApiKeyUpsertBulk) ClearDeletedAt() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.ClearDeletedAt()
})
}
// SetUserID sets the "user_id" field.
func (u *ApiKeyUpsertBulk) SetUserID(v int64) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetUserID(v)
})
}
// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateUserID() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateUserID()
})
}
// SetKey sets the "key" field.
func (u *ApiKeyUpsertBulk) SetKey(v string) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetKey(v)
})
}
// UpdateKey sets the "key" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateKey() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateKey()
})
}
// SetName sets the "name" field.
func (u *ApiKeyUpsertBulk) SetName(v string) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetName(v)
})
}
// UpdateName sets the "name" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateName() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateName()
})
}
// SetGroupID sets the "group_id" field.
func (u *ApiKeyUpsertBulk) SetGroupID(v int64) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetGroupID(v)
})
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateGroupID() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateGroupID()
})
}
// ClearGroupID clears the value of the "group_id" field.
func (u *ApiKeyUpsertBulk) ClearGroupID() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.ClearGroupID()
})
}
// SetStatus sets the "status" field.
func (u *ApiKeyUpsertBulk) SetStatus(v string) *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.SetStatus(v)
})
}
// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateStatus() *ApiKeyUpsertBulk {
return u.Update(func(s *ApiKeyUpsert) {
s.UpdateStatus()
})
}
// Exec executes the query.
func (u *ApiKeyUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
return u.create.err
}
for i, b := range u.create.builders {
if len(b.conflict) != 0 {
return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the ApiKeyCreateBulk instead", i)
}
}
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for ApiKeyCreateBulk.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *ApiKeyUpsertBulk) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// 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/apikey"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ApiKeyDelete is the builder for deleting a ApiKey entity.
type ApiKeyDelete struct {
config
hooks []Hook
mutation *ApiKeyMutation
}
// Where appends a list predicates to the ApiKeyDelete builder.
func (_d *ApiKeyDelete) Where(ps ...predicate.ApiKey) *ApiKeyDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *ApiKeyDelete) 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 *ApiKeyDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *ApiKeyDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.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
}
// ApiKeyDeleteOne is the builder for deleting a single ApiKey entity.
type ApiKeyDeleteOne struct {
_d *ApiKeyDelete
}
// Where appends a list predicates to the ApiKeyDelete builder.
func (_d *ApiKeyDeleteOne) Where(ps ...predicate.ApiKey) *ApiKeyDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *ApiKeyDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{apikey.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ApiKeyDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

684
backend/ent/apikey_query.go Normal file
View File

@@ -0,0 +1,684 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// ApiKeyQuery is the builder for querying ApiKey entities.
type ApiKeyQuery struct {
config
ctx *QueryContext
order []apikey.OrderOption
inters []Interceptor
predicates []predicate.ApiKey
withUser *UserQuery
withGroup *GroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ApiKeyQuery builder.
func (_q *ApiKeyQuery) Where(ps ...predicate.ApiKey) *ApiKeyQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *ApiKeyQuery) Limit(limit int) *ApiKeyQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *ApiKeyQuery) Offset(offset int) *ApiKeyQuery {
_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 *ApiKeyQuery) Unique(unique bool) *ApiKeyQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *ApiKeyQuery) Order(o ...apikey.OrderOption) *ApiKeyQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUser chains the current query on the "user" edge.
func (_q *ApiKeyQuery) QueryUser() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(apikey.Table, apikey.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, apikey.UserTable, apikey.UserColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryGroup chains the current query on the "group" edge.
func (_q *ApiKeyQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(apikey.Table, apikey.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, apikey.GroupTable, apikey.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first ApiKey entity from the query.
// Returns a *NotFoundError when no ApiKey was found.
func (_q *ApiKeyQuery) First(ctx context.Context) (*ApiKey, 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{apikey.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *ApiKeyQuery) FirstX(ctx context.Context) *ApiKey {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first ApiKey ID from the query.
// Returns a *NotFoundError when no ApiKey ID was found.
func (_q *ApiKeyQuery) 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{apikey.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *ApiKeyQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single ApiKey entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one ApiKey entity is found.
// Returns a *NotFoundError when no ApiKey entities are found.
func (_q *ApiKeyQuery) Only(ctx context.Context) (*ApiKey, 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{apikey.Label}
default:
return nil, &NotSingularError{apikey.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *ApiKeyQuery) OnlyX(ctx context.Context) *ApiKey {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only ApiKey ID in the query.
// Returns a *NotSingularError when more than one ApiKey ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *ApiKeyQuery) 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{apikey.Label}
default:
err = &NotSingularError{apikey.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *ApiKeyQuery) 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 ApiKeys.
func (_q *ApiKeyQuery) All(ctx context.Context) ([]*ApiKey, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*ApiKey, *ApiKeyQuery]()
return withInterceptors[[]*ApiKey](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *ApiKeyQuery) AllX(ctx context.Context) []*ApiKey {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of ApiKey IDs.
func (_q *ApiKeyQuery) 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(apikey.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *ApiKeyQuery) 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 *ApiKeyQuery) 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[*ApiKeyQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *ApiKeyQuery) 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 *ApiKeyQuery) 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 *ApiKeyQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ApiKeyQuery 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 *ApiKeyQuery) Clone() *ApiKeyQuery {
if _q == nil {
return nil
}
return &ApiKeyQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]apikey.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.ApiKey{}, _q.predicates...),
withUser: _q.withUser.Clone(),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ApiKeyQuery) WithUser(opts ...func(*UserQuery)) *ApiKeyQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUser = query
return _q
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ApiKeyQuery) WithGroup(opts ...func(*GroupQuery)) *ApiKeyQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = query
return _q
}
// 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.ApiKey.Query().
// GroupBy(apikey.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *ApiKeyQuery) GroupBy(field string, fields ...string) *ApiKeyGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &ApiKeyGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = apikey.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.ApiKey.Query().
// Select(apikey.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *ApiKeyQuery) Select(fields ...string) *ApiKeySelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &ApiKeySelect{ApiKeyQuery: _q}
sbuild.label = apikey.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a ApiKeySelect configured with the given aggregations.
func (_q *ApiKeyQuery) Aggregate(fns ...AggregateFunc) *ApiKeySelect {
return _q.Select().Aggregate(fns...)
}
func (_q *ApiKeyQuery) 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 !apikey.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 *ApiKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ApiKey, error) {
var (
nodes = []*ApiKey{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withUser != nil,
_q.withGroup != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*ApiKey).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &ApiKey{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUser; query != nil {
if err := _q.loadUser(ctx, query, nodes, nil,
func(n *ApiKey, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
if query := _q.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes, nil,
func(n *ApiKey, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *ApiKeyQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*ApiKey, init func(*ApiKey), assign func(*ApiKey, *User)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*ApiKey)
for i := range nodes {
fk := nodes[i].UserID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *ApiKeyQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*ApiKey, init func(*ApiKey), assign func(*ApiKey, *Group)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*ApiKey)
for i := range nodes {
if nodes[i].GroupID == nil {
continue
}
fk := *nodes[i].GroupID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *ApiKeyQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *ApiKeyQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.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, apikey.FieldID)
for i := range fields {
if fields[i] != apikey.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withUser != nil {
_spec.Node.AddColumnOnce(apikey.FieldUserID)
}
if _q.withGroup != nil {
_spec.Node.AddColumnOnce(apikey.FieldGroupID)
}
}
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 *ApiKeyQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(apikey.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = apikey.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ApiKeyGroupBy is the group-by builder for ApiKey entities.
type ApiKeyGroupBy struct {
selector
build *ApiKeyQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *ApiKeyGroupBy) Aggregate(fns ...AggregateFunc) *ApiKeyGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *ApiKeyGroupBy) 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[*ApiKeyQuery, *ApiKeyGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *ApiKeyGroupBy) sqlScan(ctx context.Context, root *ApiKeyQuery, 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)
}
// ApiKeySelect is the builder for selecting fields of ApiKey entities.
type ApiKeySelect struct {
*ApiKeyQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *ApiKeySelect) Aggregate(fns ...AggregateFunc) *ApiKeySelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *ApiKeySelect) 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[*ApiKeyQuery, *ApiKeySelect](ctx, _s.ApiKeyQuery, _s, _s.inters, v)
}
func (_s *ApiKeySelect) sqlScan(ctx context.Context, root *ApiKeyQuery, 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)
}

View File

@@ -0,0 +1,660 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// ApiKeyUpdate is the builder for updating ApiKey entities.
type ApiKeyUpdate struct {
config
hooks []Hook
mutation *ApiKeyMutation
}
// Where appends a list predicates to the ApiKeyUpdate builder.
func (_u *ApiKeyUpdate) Where(ps ...predicate.ApiKey) *ApiKeyUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ApiKeyUpdate) SetUpdatedAt(v time.Time) *ApiKeyUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ApiKeyUpdate) SetDeletedAt(v time.Time) *ApiKeyUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ApiKeyUpdate) SetNillableDeletedAt(v *time.Time) *ApiKeyUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ApiKeyUpdate) ClearDeletedAt() *ApiKeyUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetUserID sets the "user_id" field.
func (_u *ApiKeyUpdate) SetUserID(v int64) *ApiKeyUpdate {
_u.mutation.SetUserID(v)
return _u
}
// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *ApiKeyUpdate) SetNillableUserID(v *int64) *ApiKeyUpdate {
if v != nil {
_u.SetUserID(*v)
}
return _u
}
// SetKey sets the "key" field.
func (_u *ApiKeyUpdate) SetKey(v string) *ApiKeyUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *ApiKeyUpdate) SetNillableKey(v *string) *ApiKeyUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetName sets the "name" field.
func (_u *ApiKeyUpdate) SetName(v string) *ApiKeyUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *ApiKeyUpdate) SetNillableName(v *string) *ApiKeyUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *ApiKeyUpdate) SetGroupID(v int64) *ApiKeyUpdate {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *ApiKeyUpdate) SetNillableGroupID(v *int64) *ApiKeyUpdate {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// ClearGroupID clears the value of the "group_id" field.
func (_u *ApiKeyUpdate) ClearGroupID() *ApiKeyUpdate {
_u.mutation.ClearGroupID()
return _u
}
// SetStatus sets the "status" field.
func (_u *ApiKeyUpdate) SetStatus(v string) *ApiKeyUpdate {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *ApiKeyUpdate) SetNillableStatus(v *string) *ApiKeyUpdate {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// SetUser sets the "user" edge to the User entity.
func (_u *ApiKeyUpdate) SetUser(v *User) *ApiKeyUpdate {
return _u.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *ApiKeyUpdate) SetGroup(v *Group) *ApiKeyUpdate {
return _u.SetGroupID(v.ID)
}
// Mutation returns the ApiKeyMutation object of the builder.
func (_u *ApiKeyUpdate) Mutation() *ApiKeyMutation {
return _u.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (_u *ApiKeyUpdate) ClearUser() *ApiKeyUpdate {
_u.mutation.ClearUser()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *ApiKeyUpdate) ClearGroup() *ApiKeyUpdate {
_u.mutation.ClearGroup()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ApiKeyUpdate) Save(ctx context.Context) (int, error) {
if err := _u.defaults(); err != nil {
return 0, err
}
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ApiKeyUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *ApiKeyUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ApiKeyUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *ApiKeyUpdate) defaults() error {
if _, ok := _u.mutation.UpdatedAt(); !ok {
if apikey.UpdateDefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized apikey.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := apikey.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_u *ApiKeyUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := apikey.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "ApiKey.key": %w`, err)}
}
}
if v, ok := _u.mutation.Name(); ok {
if err := apikey.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ApiKey.name": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := apikey.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "ApiKey.status": %w`, err)}
}
}
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "ApiKey.user"`)
}
return nil
}
func (_u *ApiKeyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(apikey.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(apikey.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(apikey.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(apikey.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(apikey.FieldStatus, field.TypeString, value)
}
if _u.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.UserTable,
Columns: []string{apikey.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.UserTable,
Columns: []string{apikey.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.GroupTable,
Columns: []string{apikey.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.GroupTable,
Columns: []string{apikey.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{apikey.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// ApiKeyUpdateOne is the builder for updating a single ApiKey entity.
type ApiKeyUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ApiKeyMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ApiKeyUpdateOne) SetUpdatedAt(v time.Time) *ApiKeyUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ApiKeyUpdateOne) SetDeletedAt(v time.Time) *ApiKeyUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ApiKeyUpdateOne) SetNillableDeletedAt(v *time.Time) *ApiKeyUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ApiKeyUpdateOne) ClearDeletedAt() *ApiKeyUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetUserID sets the "user_id" field.
func (_u *ApiKeyUpdateOne) SetUserID(v int64) *ApiKeyUpdateOne {
_u.mutation.SetUserID(v)
return _u
}
// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *ApiKeyUpdateOne) SetNillableUserID(v *int64) *ApiKeyUpdateOne {
if v != nil {
_u.SetUserID(*v)
}
return _u
}
// SetKey sets the "key" field.
func (_u *ApiKeyUpdateOne) SetKey(v string) *ApiKeyUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *ApiKeyUpdateOne) SetNillableKey(v *string) *ApiKeyUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetName sets the "name" field.
func (_u *ApiKeyUpdateOne) SetName(v string) *ApiKeyUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *ApiKeyUpdateOne) SetNillableName(v *string) *ApiKeyUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *ApiKeyUpdateOne) SetGroupID(v int64) *ApiKeyUpdateOne {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *ApiKeyUpdateOne) SetNillableGroupID(v *int64) *ApiKeyUpdateOne {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// ClearGroupID clears the value of the "group_id" field.
func (_u *ApiKeyUpdateOne) ClearGroupID() *ApiKeyUpdateOne {
_u.mutation.ClearGroupID()
return _u
}
// SetStatus sets the "status" field.
func (_u *ApiKeyUpdateOne) SetStatus(v string) *ApiKeyUpdateOne {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *ApiKeyUpdateOne) SetNillableStatus(v *string) *ApiKeyUpdateOne {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// SetUser sets the "user" edge to the User entity.
func (_u *ApiKeyUpdateOne) SetUser(v *User) *ApiKeyUpdateOne {
return _u.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *ApiKeyUpdateOne) SetGroup(v *Group) *ApiKeyUpdateOne {
return _u.SetGroupID(v.ID)
}
// Mutation returns the ApiKeyMutation object of the builder.
func (_u *ApiKeyUpdateOne) Mutation() *ApiKeyMutation {
return _u.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (_u *ApiKeyUpdateOne) ClearUser() *ApiKeyUpdateOne {
_u.mutation.ClearUser()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *ApiKeyUpdateOne) ClearGroup() *ApiKeyUpdateOne {
_u.mutation.ClearGroup()
return _u
}
// Where appends a list predicates to the ApiKeyUpdate builder.
func (_u *ApiKeyUpdateOne) Where(ps ...predicate.ApiKey) *ApiKeyUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *ApiKeyUpdateOne) Select(field string, fields ...string) *ApiKeyUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated ApiKey entity.
func (_u *ApiKeyUpdateOne) Save(ctx context.Context) (*ApiKey, error) {
if err := _u.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ApiKeyUpdateOne) SaveX(ctx context.Context) *ApiKey {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *ApiKeyUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ApiKeyUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *ApiKeyUpdateOne) defaults() error {
if _, ok := _u.mutation.UpdatedAt(); !ok {
if apikey.UpdateDefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized apikey.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := apikey.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_u *ApiKeyUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := apikey.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "ApiKey.key": %w`, err)}
}
}
if v, ok := _u.mutation.Name(); ok {
if err := apikey.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ApiKey.name": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := apikey.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "ApiKey.status": %w`, err)}
}
}
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "ApiKey.user"`)
}
return nil
}
func (_u *ApiKeyUpdateOne) sqlSave(ctx context.Context) (_node *ApiKey, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ApiKey.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, apikey.FieldID)
for _, f := range fields {
if !apikey.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != apikey.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(apikey.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(apikey.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(apikey.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(apikey.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(apikey.FieldStatus, field.TypeString, value)
}
if _u.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.UserTable,
Columns: []string{apikey.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.UserTable,
Columns: []string{apikey.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.GroupTable,
Columns: []string{apikey.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: apikey.GroupTable,
Columns: []string{apikey.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &ApiKey{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{apikey.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

1950
backend/ent/client.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
package ent
import "entgo.io/ent/dialect"
// Driver 暴露底层 driver供需要 raw SQL 的集成层使用。
func (c *Client) Driver() dialect.Driver {
return c.driver
}

626
backend/ent/ent.go Normal file
View File

@@ -0,0 +1,626 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
account.Table: account.ValidColumn,
accountgroup.Table: accountgroup.ValidColumn,
apikey.Table: apikey.ValidColumn,
group.Table: group.ValidColumn,
proxy.Table: proxy.ValidColumn,
redeemcode.Table: redeemcode.ValidColumn,
setting.Table: setting.ValidColumn,
user.Table: user.ValidColumn,
userallowedgroup.Table: userallowedgroup.ValidColumn,
usersubscription.Table: usersubscription.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View File

@@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"github.com/Wei-Shaw/sub2api/ent"
// required by schema hooks.
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"github.com/Wei-Shaw/sub2api/ent/migrate"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

3
backend/ent/generate.go Normal file
View File

@@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/upsert,intercept --idtype int64 ./schema

379
backend/ent/group.go Normal file
View File

@@ -0,0 +1,379 @@
// 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/group"
)
// Group is the model entity for the Group schema.
type Group 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"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description *string `json:"description,omitempty"`
// RateMultiplier holds the value of the "rate_multiplier" field.
RateMultiplier float64 `json:"rate_multiplier,omitempty"`
// IsExclusive holds the value of the "is_exclusive" field.
IsExclusive bool `json:"is_exclusive,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Platform holds the value of the "platform" field.
Platform string `json:"platform,omitempty"`
// SubscriptionType holds the value of the "subscription_type" field.
SubscriptionType string `json:"subscription_type,omitempty"`
// DailyLimitUsd holds the value of the "daily_limit_usd" field.
DailyLimitUsd *float64 `json:"daily_limit_usd,omitempty"`
// WeeklyLimitUsd holds the value of the "weekly_limit_usd" field.
WeeklyLimitUsd *float64 `json:"weekly_limit_usd,omitempty"`
// MonthlyLimitUsd holds the value of the "monthly_limit_usd" field.
MonthlyLimitUsd *float64 `json:"monthly_limit_usd,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// APIKeys holds the value of the api_keys edge.
APIKeys []*ApiKey `json:"api_keys,omitempty"`
// RedeemCodes holds the value of the redeem_codes edge.
RedeemCodes []*RedeemCode `json:"redeem_codes,omitempty"`
// Subscriptions holds the value of the subscriptions edge.
Subscriptions []*UserSubscription `json:"subscriptions,omitempty"`
// Accounts holds the value of the accounts edge.
Accounts []*Account `json:"accounts,omitempty"`
// AllowedUsers holds the value of the allowed_users edge.
AllowedUsers []*User `json:"allowed_users,omitempty"`
// AccountGroups holds the value of the account_groups edge.
AccountGroups []*AccountGroup `json:"account_groups,omitempty"`
// UserAllowedGroups holds the value of the user_allowed_groups edge.
UserAllowedGroups []*UserAllowedGroup `json:"user_allowed_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [7]bool
}
// APIKeysOrErr returns the APIKeys value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) APIKeysOrErr() ([]*ApiKey, error) {
if e.loadedTypes[0] {
return e.APIKeys, nil
}
return nil, &NotLoadedError{edge: "api_keys"}
}
// RedeemCodesOrErr returns the RedeemCodes value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) RedeemCodesOrErr() ([]*RedeemCode, error) {
if e.loadedTypes[1] {
return e.RedeemCodes, nil
}
return nil, &NotLoadedError{edge: "redeem_codes"}
}
// SubscriptionsOrErr returns the Subscriptions value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) SubscriptionsOrErr() ([]*UserSubscription, error) {
if e.loadedTypes[2] {
return e.Subscriptions, nil
}
return nil, &NotLoadedError{edge: "subscriptions"}
}
// AccountsOrErr returns the Accounts value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) AccountsOrErr() ([]*Account, error) {
if e.loadedTypes[3] {
return e.Accounts, nil
}
return nil, &NotLoadedError{edge: "accounts"}
}
// AllowedUsersOrErr returns the AllowedUsers value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) AllowedUsersOrErr() ([]*User, error) {
if e.loadedTypes[4] {
return e.AllowedUsers, nil
}
return nil, &NotLoadedError{edge: "allowed_users"}
}
// AccountGroupsOrErr returns the AccountGroups value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
if e.loadedTypes[5] {
return e.AccountGroups, nil
}
return nil, &NotLoadedError{edge: "account_groups"}
}
// UserAllowedGroupsOrErr returns the UserAllowedGroups value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UserAllowedGroupsOrErr() ([]*UserAllowedGroup, error) {
if e.loadedTypes[6] {
return e.UserAllowedGroups, nil
}
return nil, &NotLoadedError{edge: "user_allowed_groups"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldIsExclusive:
values[i] = new(sql.NullBool)
case group.FieldRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd:
values[i] = new(sql.NullFloat64)
case group.FieldID:
values[i] = new(sql.NullInt64)
case group.FieldName, group.FieldDescription, group.FieldStatus, group.FieldPlatform, group.FieldSubscriptionType:
values[i] = new(sql.NullString)
case group.FieldCreatedAt, group.FieldUpdatedAt, group.FieldDeletedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (_m *Group) 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 group.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 group.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 group.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 group.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(time.Time)
*_m.DeletedAt = value.Time
}
case group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case group.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
_m.Description = new(string)
*_m.Description = value.String
}
case group.FieldRateMultiplier:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field rate_multiplier", values[i])
} else if value.Valid {
_m.RateMultiplier = value.Float64
}
case group.FieldIsExclusive:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field is_exclusive", values[i])
} else if value.Valid {
_m.IsExclusive = value.Bool
}
case group.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
case group.FieldPlatform:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field platform", values[i])
} else if value.Valid {
_m.Platform = value.String
}
case group.FieldSubscriptionType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field subscription_type", values[i])
} else if value.Valid {
_m.SubscriptionType = value.String
}
case group.FieldDailyLimitUsd:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field daily_limit_usd", values[i])
} else if value.Valid {
_m.DailyLimitUsd = new(float64)
*_m.DailyLimitUsd = value.Float64
}
case group.FieldWeeklyLimitUsd:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field weekly_limit_usd", values[i])
} else if value.Valid {
_m.WeeklyLimitUsd = new(float64)
*_m.WeeklyLimitUsd = value.Float64
}
case group.FieldMonthlyLimitUsd:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field monthly_limit_usd", values[i])
} else if value.Valid {
_m.MonthlyLimitUsd = new(float64)
*_m.MonthlyLimitUsd = value.Float64
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Group.
// This includes values selected through modifiers, order, etc.
func (_m *Group) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryAPIKeys queries the "api_keys" edge of the Group entity.
func (_m *Group) QueryAPIKeys() *ApiKeyQuery {
return NewGroupClient(_m.config).QueryAPIKeys(_m)
}
// QueryRedeemCodes queries the "redeem_codes" edge of the Group entity.
func (_m *Group) QueryRedeemCodes() *RedeemCodeQuery {
return NewGroupClient(_m.config).QueryRedeemCodes(_m)
}
// QuerySubscriptions queries the "subscriptions" edge of the Group entity.
func (_m *Group) QuerySubscriptions() *UserSubscriptionQuery {
return NewGroupClient(_m.config).QuerySubscriptions(_m)
}
// QueryAccounts queries the "accounts" edge of the Group entity.
func (_m *Group) QueryAccounts() *AccountQuery {
return NewGroupClient(_m.config).QueryAccounts(_m)
}
// QueryAllowedUsers queries the "allowed_users" edge of the Group entity.
func (_m *Group) QueryAllowedUsers() *UserQuery {
return NewGroupClient(_m.config).QueryAllowedUsers(_m)
}
// QueryAccountGroups queries the "account_groups" edge of the Group entity.
func (_m *Group) QueryAccountGroups() *AccountGroupQuery {
return NewGroupClient(_m.config).QueryAccountGroups(_m)
}
// QueryUserAllowedGroups queries the "user_allowed_groups" edge of the Group entity.
func (_m *Group) QueryUserAllowedGroups() *UserAllowedGroupQuery {
return NewGroupClient(_m.config).QueryUserAllowedGroups(_m)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Group) Update() *GroupUpdateOne {
return NewGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Group 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 *Group) Unwrap() *Group {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
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(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
if v := _m.Description; v != nil {
builder.WriteString("description=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", _m.RateMultiplier))
builder.WriteString(", ")
builder.WriteString("is_exclusive=")
builder.WriteString(fmt.Sprintf("%v", _m.IsExclusive))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
builder.WriteString("platform=")
builder.WriteString(_m.Platform)
builder.WriteString(", ")
builder.WriteString("subscription_type=")
builder.WriteString(_m.SubscriptionType)
builder.WriteString(", ")
if v := _m.DailyLimitUsd; v != nil {
builder.WriteString("daily_limit_usd=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
if v := _m.WeeklyLimitUsd; v != nil {
builder.WriteString("weekly_limit_usd=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
if v := _m.MonthlyLimitUsd; v != nil {
builder.WriteString("monthly_limit_usd=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group

396
backend/ent/group/group.go Normal file
View File

@@ -0,0 +1,396 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// 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"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldRateMultiplier holds the string denoting the rate_multiplier field in the database.
FieldRateMultiplier = "rate_multiplier"
// FieldIsExclusive holds the string denoting the is_exclusive field in the database.
FieldIsExclusive = "is_exclusive"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldPlatform holds the string denoting the platform field in the database.
FieldPlatform = "platform"
// FieldSubscriptionType holds the string denoting the subscription_type field in the database.
FieldSubscriptionType = "subscription_type"
// FieldDailyLimitUsd holds the string denoting the daily_limit_usd field in the database.
FieldDailyLimitUsd = "daily_limit_usd"
// FieldWeeklyLimitUsd holds the string denoting the weekly_limit_usd field in the database.
FieldWeeklyLimitUsd = "weekly_limit_usd"
// FieldMonthlyLimitUsd holds the string denoting the monthly_limit_usd field in the database.
FieldMonthlyLimitUsd = "monthly_limit_usd"
// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.
EdgeAPIKeys = "api_keys"
// EdgeRedeemCodes holds the string denoting the redeem_codes edge name in mutations.
EdgeRedeemCodes = "redeem_codes"
// EdgeSubscriptions holds the string denoting the subscriptions edge name in mutations.
EdgeSubscriptions = "subscriptions"
// EdgeAccounts holds the string denoting the accounts edge name in mutations.
EdgeAccounts = "accounts"
// EdgeAllowedUsers holds the string denoting the allowed_users edge name in mutations.
EdgeAllowedUsers = "allowed_users"
// EdgeAccountGroups holds the string denoting the account_groups edge name in mutations.
EdgeAccountGroups = "account_groups"
// EdgeUserAllowedGroups holds the string denoting the user_allowed_groups edge name in mutations.
EdgeUserAllowedGroups = "user_allowed_groups"
// Table holds the table name of the group in the database.
Table = "groups"
// APIKeysTable is the table that holds the api_keys relation/edge.
APIKeysTable = "api_keys"
// APIKeysInverseTable is the table name for the ApiKey entity.
// It exists in this package in order to avoid circular dependency with the "apikey" package.
APIKeysInverseTable = "api_keys"
// APIKeysColumn is the table column denoting the api_keys relation/edge.
APIKeysColumn = "group_id"
// RedeemCodesTable is the table that holds the redeem_codes relation/edge.
RedeemCodesTable = "redeem_codes"
// RedeemCodesInverseTable is the table name for the RedeemCode entity.
// It exists in this package in order to avoid circular dependency with the "redeemcode" package.
RedeemCodesInverseTable = "redeem_codes"
// RedeemCodesColumn is the table column denoting the redeem_codes relation/edge.
RedeemCodesColumn = "group_id"
// SubscriptionsTable is the table that holds the subscriptions relation/edge.
SubscriptionsTable = "user_subscriptions"
// SubscriptionsInverseTable is the table name for the UserSubscription entity.
// It exists in this package in order to avoid circular dependency with the "usersubscription" package.
SubscriptionsInverseTable = "user_subscriptions"
// SubscriptionsColumn is the table column denoting the subscriptions relation/edge.
SubscriptionsColumn = "group_id"
// AccountsTable is the table that holds the accounts relation/edge. The primary key declared below.
AccountsTable = "account_groups"
// AccountsInverseTable is the table name for the Account entity.
// It exists in this package in order to avoid circular dependency with the "account" package.
AccountsInverseTable = "accounts"
// AllowedUsersTable is the table that holds the allowed_users relation/edge. The primary key declared below.
AllowedUsersTable = "user_allowed_groups"
// AllowedUsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
AllowedUsersInverseTable = "users"
// AccountGroupsTable is the table that holds the account_groups relation/edge.
AccountGroupsTable = "account_groups"
// AccountGroupsInverseTable is the table name for the AccountGroup entity.
// It exists in this package in order to avoid circular dependency with the "accountgroup" package.
AccountGroupsInverseTable = "account_groups"
// AccountGroupsColumn is the table column denoting the account_groups relation/edge.
AccountGroupsColumn = "group_id"
// UserAllowedGroupsTable is the table that holds the user_allowed_groups relation/edge.
UserAllowedGroupsTable = "user_allowed_groups"
// UserAllowedGroupsInverseTable is the table name for the UserAllowedGroup entity.
// It exists in this package in order to avoid circular dependency with the "userallowedgroup" package.
UserAllowedGroupsInverseTable = "user_allowed_groups"
// UserAllowedGroupsColumn is the table column denoting the user_allowed_groups relation/edge.
UserAllowedGroupsColumn = "group_id"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldName,
FieldDescription,
FieldRateMultiplier,
FieldIsExclusive,
FieldStatus,
FieldPlatform,
FieldSubscriptionType,
FieldDailyLimitUsd,
FieldWeeklyLimitUsd,
FieldMonthlyLimitUsd,
}
var (
// AccountsPrimaryKey and AccountsColumn2 are the table columns denoting the
// primary key for the accounts relation (M2M).
AccountsPrimaryKey = []string{"account_id", "group_id"}
// AllowedUsersPrimaryKey and AllowedUsersColumn2 are the table columns denoting the
// primary key for the allowed_users relation (M2M).
AllowedUsersPrimaryKey = []string{"user_id", "group_id"}
)
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "github.com/Wei-Shaw/sub2api/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
// 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
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultRateMultiplier holds the default value on creation for the "rate_multiplier" field.
DefaultRateMultiplier float64
// DefaultIsExclusive holds the default value on creation for the "is_exclusive" field.
DefaultIsExclusive bool
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DefaultPlatform holds the default value on creation for the "platform" field.
DefaultPlatform string
// PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
PlatformValidator func(string) error
// DefaultSubscriptionType holds the default value on creation for the "subscription_type" field.
DefaultSubscriptionType string
// SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save.
SubscriptionTypeValidator func(string) error
)
// OrderOption defines the ordering options for the Group 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()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByDescription orders the results by the description field.
func ByDescription(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDescription, opts...).ToFunc()
}
// ByRateMultiplier orders the results by the rate_multiplier field.
func ByRateMultiplier(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRateMultiplier, opts...).ToFunc()
}
// ByIsExclusive orders the results by the is_exclusive field.
func ByIsExclusive(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldIsExclusive, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByPlatform orders the results by the platform field.
func ByPlatform(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPlatform, opts...).ToFunc()
}
// BySubscriptionType orders the results by the subscription_type field.
func BySubscriptionType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSubscriptionType, opts...).ToFunc()
}
// ByDailyLimitUsd orders the results by the daily_limit_usd field.
func ByDailyLimitUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDailyLimitUsd, opts...).ToFunc()
}
// ByWeeklyLimitUsd orders the results by the weekly_limit_usd field.
func ByWeeklyLimitUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWeeklyLimitUsd, opts...).ToFunc()
}
// ByMonthlyLimitUsd orders the results by the monthly_limit_usd field.
func ByMonthlyLimitUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMonthlyLimitUsd, opts...).ToFunc()
}
// ByAPIKeysCount orders the results by api_keys count.
func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAPIKeysStep(), opts...)
}
}
// ByAPIKeys orders the results by api_keys terms.
func ByAPIKeys(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAPIKeysStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByRedeemCodesCount orders the results by redeem_codes count.
func ByRedeemCodesCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newRedeemCodesStep(), opts...)
}
}
// ByRedeemCodes orders the results by redeem_codes terms.
func ByRedeemCodes(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newRedeemCodesStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// BySubscriptionsCount orders the results by subscriptions count.
func BySubscriptionsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newSubscriptionsStep(), opts...)
}
}
// BySubscriptions orders the results by subscriptions terms.
func BySubscriptions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newSubscriptionsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAccountsCount orders the results by accounts count.
func ByAccountsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAccountsStep(), opts...)
}
}
// ByAccounts orders the results by accounts terms.
func ByAccounts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAccountsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAllowedUsersCount orders the results by allowed_users count.
func ByAllowedUsersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAllowedUsersStep(), opts...)
}
}
// ByAllowedUsers orders the results by allowed_users terms.
func ByAllowedUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAllowedUsersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAccountGroupsCount orders the results by account_groups count.
func ByAccountGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAccountGroupsStep(), opts...)
}
}
// ByAccountGroups orders the results by account_groups terms.
func ByAccountGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAccountGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByUserAllowedGroupsCount orders the results by user_allowed_groups count.
func ByUserAllowedGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUserAllowedGroupsStep(), opts...)
}
}
// ByUserAllowedGroups orders the results by user_allowed_groups terms.
func ByUserAllowedGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserAllowedGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newAPIKeysStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(APIKeysInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn),
)
}
func newRedeemCodesStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(RedeemCodesInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, RedeemCodesTable, RedeemCodesColumn),
)
}
func newSubscriptionsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(SubscriptionsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn),
)
}
func newAccountsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AccountsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, AccountsTable, AccountsPrimaryKey...),
)
}
func newAllowedUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AllowedUsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, AllowedUsersTable, AllowedUsersPrimaryKey...),
)
}
func newAccountGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AccountGroupsInverseTable, AccountGroupsColumn),
sqlgraph.Edge(sqlgraph.O2M, true, AccountGroupsTable, AccountGroupsColumn),
)
}
func newUserAllowedGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserAllowedGroupsInverseTable, UserAllowedGroupsColumn),
sqlgraph.Edge(sqlgraph.O2M, true, UserAllowedGroupsTable, UserAllowedGroupsColumn),
)
}

962
backend/ent/group/where.go Normal file
View File

@@ -0,0 +1,962 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.Group {
return predicate.Group(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.Group {
return predicate.Group(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.Group {
return predicate.Group(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDeletedAt, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDescription, v))
}
// RateMultiplier applies equality check predicate on the "rate_multiplier" field. It's identical to RateMultiplierEQ.
func RateMultiplier(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldRateMultiplier, v))
}
// IsExclusive applies equality check predicate on the "is_exclusive" field. It's identical to IsExclusiveEQ.
func IsExclusive(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldIsExclusive, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldStatus, v))
}
// Platform applies equality check predicate on the "platform" field. It's identical to PlatformEQ.
func Platform(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPlatform, v))
}
// SubscriptionType applies equality check predicate on the "subscription_type" field. It's identical to SubscriptionTypeEQ.
func SubscriptionType(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldSubscriptionType, v))
}
// DailyLimitUsd applies equality check predicate on the "daily_limit_usd" field. It's identical to DailyLimitUsdEQ.
func DailyLimitUsd(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDailyLimitUsd, v))
}
// WeeklyLimitUsd applies equality check predicate on the "weekly_limit_usd" field. It's identical to WeeklyLimitUsdEQ.
func WeeklyLimitUsd(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldWeeklyLimitUsd, v))
}
// MonthlyLimitUsd applies equality check predicate on the "monthly_limit_usd" field. It's identical to MonthlyLimitUsdEQ.
func MonthlyLimitUsd(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldMonthlyLimitUsd, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Group {
return predicate.Group(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Group {
return predicate.Group(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Group {
return predicate.Group(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Group {
return predicate.Group(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Group {
return predicate.Group(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Group {
return predicate.Group(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...time.Time) predicate.Group {
return predicate.Group(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...time.Time) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v time.Time) predicate.Group {
return predicate.Group(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v time.Time) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v time.Time) predicate.Group {
return predicate.Group(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v time.Time) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.Group {
return predicate.Group(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldDeletedAt))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldName, v))
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDescription, v))
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldDescription, v))
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldDescription, vs...))
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldDescription, vs...))
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldDescription, v))
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldDescription, v))
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldDescription, v))
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldDescription, v))
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldDescription, v))
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldDescription, v))
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldDescription, v))
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.Group {
return predicate.Group(sql.FieldIsNull(FieldDescription))
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldDescription))
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldDescription, v))
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldDescription, v))
}
// RateMultiplierEQ applies the EQ predicate on the "rate_multiplier" field.
func RateMultiplierEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldRateMultiplier, v))
}
// RateMultiplierNEQ applies the NEQ predicate on the "rate_multiplier" field.
func RateMultiplierNEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldRateMultiplier, v))
}
// RateMultiplierIn applies the In predicate on the "rate_multiplier" field.
func RateMultiplierIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldIn(FieldRateMultiplier, vs...))
}
// RateMultiplierNotIn applies the NotIn predicate on the "rate_multiplier" field.
func RateMultiplierNotIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldRateMultiplier, vs...))
}
// RateMultiplierGT applies the GT predicate on the "rate_multiplier" field.
func RateMultiplierGT(v float64) predicate.Group {
return predicate.Group(sql.FieldGT(FieldRateMultiplier, v))
}
// RateMultiplierGTE applies the GTE predicate on the "rate_multiplier" field.
func RateMultiplierGTE(v float64) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldRateMultiplier, v))
}
// RateMultiplierLT applies the LT predicate on the "rate_multiplier" field.
func RateMultiplierLT(v float64) predicate.Group {
return predicate.Group(sql.FieldLT(FieldRateMultiplier, v))
}
// RateMultiplierLTE applies the LTE predicate on the "rate_multiplier" field.
func RateMultiplierLTE(v float64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldRateMultiplier, v))
}
// IsExclusiveEQ applies the EQ predicate on the "is_exclusive" field.
func IsExclusiveEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldIsExclusive, v))
}
// IsExclusiveNEQ applies the NEQ predicate on the "is_exclusive" field.
func IsExclusiveNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldIsExclusive, v))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldStatus, v))
}
// PlatformEQ applies the EQ predicate on the "platform" field.
func PlatformEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPlatform, v))
}
// PlatformNEQ applies the NEQ predicate on the "platform" field.
func PlatformNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldPlatform, v))
}
// PlatformIn applies the In predicate on the "platform" field.
func PlatformIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldPlatform, vs...))
}
// PlatformNotIn applies the NotIn predicate on the "platform" field.
func PlatformNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldPlatform, vs...))
}
// PlatformGT applies the GT predicate on the "platform" field.
func PlatformGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldPlatform, v))
}
// PlatformGTE applies the GTE predicate on the "platform" field.
func PlatformGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldPlatform, v))
}
// PlatformLT applies the LT predicate on the "platform" field.
func PlatformLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldPlatform, v))
}
// PlatformLTE applies the LTE predicate on the "platform" field.
func PlatformLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldPlatform, v))
}
// PlatformContains applies the Contains predicate on the "platform" field.
func PlatformContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldPlatform, v))
}
// PlatformHasPrefix applies the HasPrefix predicate on the "platform" field.
func PlatformHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldPlatform, v))
}
// PlatformHasSuffix applies the HasSuffix predicate on the "platform" field.
func PlatformHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldPlatform, v))
}
// PlatformEqualFold applies the EqualFold predicate on the "platform" field.
func PlatformEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldPlatform, v))
}
// PlatformContainsFold applies the ContainsFold predicate on the "platform" field.
func PlatformContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldPlatform, v))
}
// SubscriptionTypeEQ applies the EQ predicate on the "subscription_type" field.
func SubscriptionTypeEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldSubscriptionType, v))
}
// SubscriptionTypeNEQ applies the NEQ predicate on the "subscription_type" field.
func SubscriptionTypeNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldSubscriptionType, v))
}
// SubscriptionTypeIn applies the In predicate on the "subscription_type" field.
func SubscriptionTypeIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldSubscriptionType, vs...))
}
// SubscriptionTypeNotIn applies the NotIn predicate on the "subscription_type" field.
func SubscriptionTypeNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldSubscriptionType, vs...))
}
// SubscriptionTypeGT applies the GT predicate on the "subscription_type" field.
func SubscriptionTypeGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldSubscriptionType, v))
}
// SubscriptionTypeGTE applies the GTE predicate on the "subscription_type" field.
func SubscriptionTypeGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldSubscriptionType, v))
}
// SubscriptionTypeLT applies the LT predicate on the "subscription_type" field.
func SubscriptionTypeLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldSubscriptionType, v))
}
// SubscriptionTypeLTE applies the LTE predicate on the "subscription_type" field.
func SubscriptionTypeLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldSubscriptionType, v))
}
// SubscriptionTypeContains applies the Contains predicate on the "subscription_type" field.
func SubscriptionTypeContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldSubscriptionType, v))
}
// SubscriptionTypeHasPrefix applies the HasPrefix predicate on the "subscription_type" field.
func SubscriptionTypeHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldSubscriptionType, v))
}
// SubscriptionTypeHasSuffix applies the HasSuffix predicate on the "subscription_type" field.
func SubscriptionTypeHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldSubscriptionType, v))
}
// SubscriptionTypeEqualFold applies the EqualFold predicate on the "subscription_type" field.
func SubscriptionTypeEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldSubscriptionType, v))
}
// SubscriptionTypeContainsFold applies the ContainsFold predicate on the "subscription_type" field.
func SubscriptionTypeContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldSubscriptionType, v))
}
// DailyLimitUsdEQ applies the EQ predicate on the "daily_limit_usd" field.
func DailyLimitUsdEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDailyLimitUsd, v))
}
// DailyLimitUsdNEQ applies the NEQ predicate on the "daily_limit_usd" field.
func DailyLimitUsdNEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldDailyLimitUsd, v))
}
// DailyLimitUsdIn applies the In predicate on the "daily_limit_usd" field.
func DailyLimitUsdIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldIn(FieldDailyLimitUsd, vs...))
}
// DailyLimitUsdNotIn applies the NotIn predicate on the "daily_limit_usd" field.
func DailyLimitUsdNotIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldDailyLimitUsd, vs...))
}
// DailyLimitUsdGT applies the GT predicate on the "daily_limit_usd" field.
func DailyLimitUsdGT(v float64) predicate.Group {
return predicate.Group(sql.FieldGT(FieldDailyLimitUsd, v))
}
// DailyLimitUsdGTE applies the GTE predicate on the "daily_limit_usd" field.
func DailyLimitUsdGTE(v float64) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldDailyLimitUsd, v))
}
// DailyLimitUsdLT applies the LT predicate on the "daily_limit_usd" field.
func DailyLimitUsdLT(v float64) predicate.Group {
return predicate.Group(sql.FieldLT(FieldDailyLimitUsd, v))
}
// DailyLimitUsdLTE applies the LTE predicate on the "daily_limit_usd" field.
func DailyLimitUsdLTE(v float64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldDailyLimitUsd, v))
}
// DailyLimitUsdIsNil applies the IsNil predicate on the "daily_limit_usd" field.
func DailyLimitUsdIsNil() predicate.Group {
return predicate.Group(sql.FieldIsNull(FieldDailyLimitUsd))
}
// DailyLimitUsdNotNil applies the NotNil predicate on the "daily_limit_usd" field.
func DailyLimitUsdNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldDailyLimitUsd))
}
// WeeklyLimitUsdEQ applies the EQ predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldWeeklyLimitUsd, v))
}
// WeeklyLimitUsdNEQ applies the NEQ predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdNEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldWeeklyLimitUsd, v))
}
// WeeklyLimitUsdIn applies the In predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldIn(FieldWeeklyLimitUsd, vs...))
}
// WeeklyLimitUsdNotIn applies the NotIn predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdNotIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldWeeklyLimitUsd, vs...))
}
// WeeklyLimitUsdGT applies the GT predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdGT(v float64) predicate.Group {
return predicate.Group(sql.FieldGT(FieldWeeklyLimitUsd, v))
}
// WeeklyLimitUsdGTE applies the GTE predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdGTE(v float64) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldWeeklyLimitUsd, v))
}
// WeeklyLimitUsdLT applies the LT predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdLT(v float64) predicate.Group {
return predicate.Group(sql.FieldLT(FieldWeeklyLimitUsd, v))
}
// WeeklyLimitUsdLTE applies the LTE predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdLTE(v float64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldWeeklyLimitUsd, v))
}
// WeeklyLimitUsdIsNil applies the IsNil predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdIsNil() predicate.Group {
return predicate.Group(sql.FieldIsNull(FieldWeeklyLimitUsd))
}
// WeeklyLimitUsdNotNil applies the NotNil predicate on the "weekly_limit_usd" field.
func WeeklyLimitUsdNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldWeeklyLimitUsd))
}
// MonthlyLimitUsdEQ applies the EQ predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldMonthlyLimitUsd, v))
}
// MonthlyLimitUsdNEQ applies the NEQ predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdNEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldMonthlyLimitUsd, v))
}
// MonthlyLimitUsdIn applies the In predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldIn(FieldMonthlyLimitUsd, vs...))
}
// MonthlyLimitUsdNotIn applies the NotIn predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdNotIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldMonthlyLimitUsd, vs...))
}
// MonthlyLimitUsdGT applies the GT predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdGT(v float64) predicate.Group {
return predicate.Group(sql.FieldGT(FieldMonthlyLimitUsd, v))
}
// MonthlyLimitUsdGTE applies the GTE predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdGTE(v float64) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldMonthlyLimitUsd, v))
}
// MonthlyLimitUsdLT applies the LT predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdLT(v float64) predicate.Group {
return predicate.Group(sql.FieldLT(FieldMonthlyLimitUsd, v))
}
// MonthlyLimitUsdLTE applies the LTE predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdLTE(v float64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldMonthlyLimitUsd, v))
}
// MonthlyLimitUsdIsNil applies the IsNil predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdIsNil() predicate.Group {
return predicate.Group(sql.FieldIsNull(FieldMonthlyLimitUsd))
}
// MonthlyLimitUsdNotNil applies the NotNil predicate on the "monthly_limit_usd" field.
func MonthlyLimitUsdNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldMonthlyLimitUsd))
}
// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.
func HasAPIKeys() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAPIKeysWith applies the HasEdge predicate on the "api_keys" edge with a given conditions (other predicates).
func HasAPIKeysWith(preds ...predicate.ApiKey) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newAPIKeysStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasRedeemCodes applies the HasEdge predicate on the "redeem_codes" edge.
func HasRedeemCodes() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, RedeemCodesTable, RedeemCodesColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasRedeemCodesWith applies the HasEdge predicate on the "redeem_codes" edge with a given conditions (other predicates).
func HasRedeemCodesWith(preds ...predicate.RedeemCode) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newRedeemCodesStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasSubscriptions applies the HasEdge predicate on the "subscriptions" edge.
func HasSubscriptions() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasSubscriptionsWith applies the HasEdge predicate on the "subscriptions" edge with a given conditions (other predicates).
func HasSubscriptionsWith(preds ...predicate.UserSubscription) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newSubscriptionsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAccounts applies the HasEdge predicate on the "accounts" edge.
func HasAccounts() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, AccountsTable, AccountsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAccountsWith applies the HasEdge predicate on the "accounts" edge with a given conditions (other predicates).
func HasAccountsWith(preds ...predicate.Account) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newAccountsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAllowedUsers applies the HasEdge predicate on the "allowed_users" edge.
func HasAllowedUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, AllowedUsersTable, AllowedUsersPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAllowedUsersWith applies the HasEdge predicate on the "allowed_users" edge with a given conditions (other predicates).
func HasAllowedUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newAllowedUsersStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAccountGroups applies the HasEdge predicate on the "account_groups" edge.
func HasAccountGroups() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, AccountGroupsTable, AccountGroupsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAccountGroupsWith applies the HasEdge predicate on the "account_groups" edge with a given conditions (other predicates).
func HasAccountGroupsWith(preds ...predicate.AccountGroup) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newAccountGroupsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasUserAllowedGroups applies the HasEdge predicate on the "user_allowed_groups" edge.
func HasUserAllowedGroups() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, UserAllowedGroupsTable, UserAllowedGroupsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserAllowedGroupsWith applies the HasEdge predicate on the "user_allowed_groups" edge with a given conditions (other predicates).
func HasUserAllowedGroupsWith(preds ...predicate.UserAllowedGroup) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newUserAllowedGroupsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(sql.NotPredicates(p))
}

1555
backend/ent/group_create.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
// 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/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *GroupDelete) 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 *GroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.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
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
_d *GroupDelete
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *GroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

1118
backend/ent/group_query.go Normal file

File diff suppressed because it is too large Load Diff

1687
backend/ent/group_update.go Normal file

File diff suppressed because it is too large Load Diff

307
backend/ent/hook/hook.go Normal file
View File

@@ -0,0 +1,307 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"github.com/Wei-Shaw/sub2api/ent"
)
// The AccountFunc type is an adapter to allow the use of ordinary
// function as Account mutator.
type AccountFunc func(context.Context, *ent.AccountMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f AccountFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.AccountMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AccountMutation", m)
}
// The AccountGroupFunc type is an adapter to allow the use of ordinary
// function as AccountGroup mutator.
type AccountGroupFunc func(context.Context, *ent.AccountGroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f AccountGroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.AccountGroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AccountGroupMutation", m)
}
// The ApiKeyFunc type is an adapter to allow the use of ordinary
// function as ApiKey mutator.
type ApiKeyFunc func(context.Context, *ent.ApiKeyMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ApiKeyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.ApiKeyMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ApiKeyMutation", m)
}
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.GroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
}
// The ProxyFunc type is an adapter to allow the use of ordinary
// function as Proxy mutator.
type ProxyFunc func(context.Context, *ent.ProxyMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ProxyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.ProxyMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ProxyMutation", m)
}
// The RedeemCodeFunc type is an adapter to allow the use of ordinary
// function as RedeemCode mutator.
type RedeemCodeFunc func(context.Context, *ent.RedeemCodeMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f RedeemCodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.RedeemCodeMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RedeemCodeMutation", m)
}
// The SettingFunc type is an adapter to allow the use of ordinary
// function as Setting mutator.
type SettingFunc func(context.Context, *ent.SettingMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SettingFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SettingMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SettingMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
// The UserAllowedGroupFunc type is an adapter to allow the use of ordinary
// function as UserAllowedGroup mutator.
type UserAllowedGroupFunc func(context.Context, *ent.UserAllowedGroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserAllowedGroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserAllowedGroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAllowedGroupMutation", m)
}
// The UserSubscriptionFunc type is an adapter to allow the use of ordinary
// function as UserSubscription mutator.
type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserSubscriptionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserSubscriptionMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserSubscriptionMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

View File

@@ -0,0 +1,419 @@
// Code generated by ent, DO NOT EDIT.
package intercept
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
)
// The Query interface represents an operation that queries a graph.
// By using this interface, users can write generic code that manipulates
// query builders of different types.
type Query interface {
// Type returns the string representation of the query type.
Type() string
// Limit the number of records to be returned by this query.
Limit(int)
// Offset to start from.
Offset(int)
// Unique configures the query builder to filter duplicate records.
Unique(bool)
// Order specifies how the records should be ordered.
Order(...func(*sql.Selector))
// WhereP appends storage-level predicates to the query builder. Using this method, users
// can use type-assertion to append predicates that do not depend on any generated package.
WhereP(...func(*sql.Selector))
}
// The Func type is an adapter that allows ordinary functions to be used as interceptors.
// Unlike traversal functions, interceptors are skipped during graph traversals. Note that the
// implementation of Func is different from the one defined in entgo.io/ent.InterceptFunc.
type Func func(context.Context, Query) error
// Intercept calls f(ctx, q) and then applied the next Querier.
func (f Func) Intercept(next ent.Querier) ent.Querier {
return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) {
query, err := NewQuery(q)
if err != nil {
return nil, err
}
if err := f(ctx, query); err != nil {
return nil, err
}
return next.Query(ctx, q)
})
}
// The TraverseFunc type is an adapter to allow the use of ordinary function as Traverser.
// If f is a function with the appropriate signature, TraverseFunc(f) is a Traverser that calls f.
type TraverseFunc func(context.Context, Query) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseFunc) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseFunc) Traverse(ctx context.Context, q ent.Query) error {
query, err := NewQuery(q)
if err != nil {
return err
}
return f(ctx, query)
}
// The AccountFunc type is an adapter to allow the use of ordinary function as a Querier.
type AccountFunc func(context.Context, *ent.AccountQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f AccountFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.AccountQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.AccountQuery", q)
}
// The TraverseAccount type is an adapter to allow the use of ordinary function as Traverser.
type TraverseAccount func(context.Context, *ent.AccountQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseAccount) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseAccount) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.AccountQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.AccountQuery", q)
}
// The AccountGroupFunc type is an adapter to allow the use of ordinary function as a Querier.
type AccountGroupFunc func(context.Context, *ent.AccountGroupQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f AccountGroupFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.AccountGroupQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.AccountGroupQuery", q)
}
// The TraverseAccountGroup type is an adapter to allow the use of ordinary function as Traverser.
type TraverseAccountGroup func(context.Context, *ent.AccountGroupQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseAccountGroup) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseAccountGroup) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.AccountGroupQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.AccountGroupQuery", q)
}
// The ApiKeyFunc type is an adapter to allow the use of ordinary function as a Querier.
type ApiKeyFunc func(context.Context, *ent.ApiKeyQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f ApiKeyFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.ApiKeyQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.ApiKeyQuery", q)
}
// The TraverseApiKey type is an adapter to allow the use of ordinary function as Traverser.
type TraverseApiKey func(context.Context, *ent.ApiKeyQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseApiKey) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseApiKey) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ApiKeyQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.ApiKeyQuery", q)
}
// The GroupFunc type is an adapter to allow the use of ordinary function as a Querier.
type GroupFunc func(context.Context, *ent.GroupQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f GroupFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.GroupQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.GroupQuery", q)
}
// The TraverseGroup type is an adapter to allow the use of ordinary function as Traverser.
type TraverseGroup func(context.Context, *ent.GroupQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseGroup) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseGroup) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.GroupQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.GroupQuery", q)
}
// The ProxyFunc type is an adapter to allow the use of ordinary function as a Querier.
type ProxyFunc func(context.Context, *ent.ProxyQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f ProxyFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.ProxyQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.ProxyQuery", q)
}
// The TraverseProxy type is an adapter to allow the use of ordinary function as Traverser.
type TraverseProxy func(context.Context, *ent.ProxyQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseProxy) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseProxy) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ProxyQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.ProxyQuery", q)
}
// The RedeemCodeFunc type is an adapter to allow the use of ordinary function as a Querier.
type RedeemCodeFunc func(context.Context, *ent.RedeemCodeQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f RedeemCodeFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.RedeemCodeQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.RedeemCodeQuery", q)
}
// The TraverseRedeemCode type is an adapter to allow the use of ordinary function as Traverser.
type TraverseRedeemCode func(context.Context, *ent.RedeemCodeQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseRedeemCode) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseRedeemCode) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.RedeemCodeQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.RedeemCodeQuery", q)
}
// The SettingFunc type is an adapter to allow the use of ordinary function as a Querier.
type SettingFunc func(context.Context, *ent.SettingQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f SettingFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.SettingQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.SettingQuery", q)
}
// The TraverseSetting type is an adapter to allow the use of ordinary function as Traverser.
type TraverseSetting func(context.Context, *ent.SettingQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseSetting) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseSetting) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.SettingQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.SettingQuery", q)
}
// The UserFunc type is an adapter to allow the use of ordinary function as a Querier.
type UserFunc func(context.Context, *ent.UserQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f UserFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.UserQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserQuery", q)
}
// The TraverseUser type is an adapter to allow the use of ordinary function as Traverser.
type TraverseUser func(context.Context, *ent.UserQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseUser) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseUser) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.UserQuery", q)
}
// The UserAllowedGroupFunc type is an adapter to allow the use of ordinary function as a Querier.
type UserAllowedGroupFunc func(context.Context, *ent.UserAllowedGroupQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f UserAllowedGroupFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.UserAllowedGroupQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserAllowedGroupQuery", q)
}
// The TraverseUserAllowedGroup type is an adapter to allow the use of ordinary function as Traverser.
type TraverseUserAllowedGroup func(context.Context, *ent.UserAllowedGroupQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseUserAllowedGroup) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseUserAllowedGroup) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserAllowedGroupQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.UserAllowedGroupQuery", q)
}
// The UserSubscriptionFunc type is an adapter to allow the use of ordinary function as a Querier.
type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f UserSubscriptionFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.UserSubscriptionQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserSubscriptionQuery", q)
}
// The TraverseUserSubscription type is an adapter to allow the use of ordinary function as Traverser.
type TraverseUserSubscription func(context.Context, *ent.UserSubscriptionQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseUserSubscription) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseUserSubscription) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserSubscriptionQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.UserSubscriptionQuery", q)
}
// NewQuery returns the generic Query interface for the given typed query.
func NewQuery(q ent.Query) (Query, error) {
switch q := q.(type) {
case *ent.AccountQuery:
return &query[*ent.AccountQuery, predicate.Account, account.OrderOption]{typ: ent.TypeAccount, tq: q}, nil
case *ent.AccountGroupQuery:
return &query[*ent.AccountGroupQuery, predicate.AccountGroup, accountgroup.OrderOption]{typ: ent.TypeAccountGroup, tq: q}, nil
case *ent.ApiKeyQuery:
return &query[*ent.ApiKeyQuery, predicate.ApiKey, apikey.OrderOption]{typ: ent.TypeApiKey, tq: q}, nil
case *ent.GroupQuery:
return &query[*ent.GroupQuery, predicate.Group, group.OrderOption]{typ: ent.TypeGroup, tq: q}, nil
case *ent.ProxyQuery:
return &query[*ent.ProxyQuery, predicate.Proxy, proxy.OrderOption]{typ: ent.TypeProxy, tq: q}, nil
case *ent.RedeemCodeQuery:
return &query[*ent.RedeemCodeQuery, predicate.RedeemCode, redeemcode.OrderOption]{typ: ent.TypeRedeemCode, tq: q}, nil
case *ent.SettingQuery:
return &query[*ent.SettingQuery, predicate.Setting, setting.OrderOption]{typ: ent.TypeSetting, tq: q}, nil
case *ent.UserQuery:
return &query[*ent.UserQuery, predicate.User, user.OrderOption]{typ: ent.TypeUser, tq: q}, nil
case *ent.UserAllowedGroupQuery:
return &query[*ent.UserAllowedGroupQuery, predicate.UserAllowedGroup, userallowedgroup.OrderOption]{typ: ent.TypeUserAllowedGroup, tq: q}, nil
case *ent.UserSubscriptionQuery:
return &query[*ent.UserSubscriptionQuery, predicate.UserSubscription, usersubscription.OrderOption]{typ: ent.TypeUserSubscription, tq: q}, nil
default:
return nil, fmt.Errorf("unknown query type %T", q)
}
}
type query[T any, P ~func(*sql.Selector), R ~func(*sql.Selector)] struct {
typ string
tq interface {
Limit(int) T
Offset(int) T
Unique(bool) T
Order(...R) T
Where(...P) T
}
}
func (q query[T, P, R]) Type() string {
return q.typ
}
func (q query[T, P, R]) Limit(limit int) {
q.tq.Limit(limit)
}
func (q query[T, P, R]) Offset(offset int) {
q.tq.Offset(offset)
}
func (q query[T, P, R]) Unique(unique bool) {
q.tq.Unique(unique)
}
func (q query[T, P, R]) Order(orders ...func(*sql.Selector)) {
rs := make([]R, len(orders))
for i := range orders {
rs[i] = orders[i]
}
q.tq.Order(rs...)
}
func (q query[T, P, R]) WhereP(ps ...func(*sql.Selector)) {
p := make([]P, len(ps))
for i := range ps {
p[i] = ps[i]
}
q.tq.Where(p...)
}

View File

@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View File

@@ -0,0 +1,568 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// AccountsColumns holds the columns for the "accounts" table.
AccountsColumns = []*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: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "platform", Type: field.TypeString, Size: 50},
{Name: "type", Type: field.TypeString, Size: 20},
{Name: "credentials", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "extra", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "proxy_id", Type: field.TypeInt64, Nullable: true},
{Name: "concurrency", Type: field.TypeInt, Default: 3},
{Name: "priority", Type: field.TypeInt, Default: 50},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "error_message", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "last_used_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "schedulable", Type: field.TypeBool, Default: true},
{Name: "rate_limited_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "rate_limit_reset_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "overload_until", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "session_window_start", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "session_window_end", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "session_window_status", Type: field.TypeString, Nullable: true, Size: 20},
}
// AccountsTable holds the schema information for the "accounts" table.
AccountsTable = &schema.Table{
Name: "accounts",
Columns: AccountsColumns,
PrimaryKey: []*schema.Column{AccountsColumns[0]},
Indexes: []*schema.Index{
{
Name: "account_platform",
Unique: false,
Columns: []*schema.Column{AccountsColumns[5]},
},
{
Name: "account_type",
Unique: false,
Columns: []*schema.Column{AccountsColumns[6]},
},
{
Name: "account_status",
Unique: false,
Columns: []*schema.Column{AccountsColumns[12]},
},
{
Name: "account_proxy_id",
Unique: false,
Columns: []*schema.Column{AccountsColumns[9]},
},
{
Name: "account_priority",
Unique: false,
Columns: []*schema.Column{AccountsColumns[11]},
},
{
Name: "account_last_used_at",
Unique: false,
Columns: []*schema.Column{AccountsColumns[14]},
},
{
Name: "account_schedulable",
Unique: false,
Columns: []*schema.Column{AccountsColumns[15]},
},
{
Name: "account_rate_limited_at",
Unique: false,
Columns: []*schema.Column{AccountsColumns[16]},
},
{
Name: "account_rate_limit_reset_at",
Unique: false,
Columns: []*schema.Column{AccountsColumns[17]},
},
{
Name: "account_overload_until",
Unique: false,
Columns: []*schema.Column{AccountsColumns[18]},
},
{
Name: "account_deleted_at",
Unique: false,
Columns: []*schema.Column{AccountsColumns[3]},
},
},
}
// AccountGroupsColumns holds the columns for the "account_groups" table.
AccountGroupsColumns = []*schema.Column{
{Name: "priority", Type: field.TypeInt, Default: 50},
{Name: "created_at", Type: field.TypeTime},
{Name: "account_id", Type: field.TypeInt64},
{Name: "group_id", Type: field.TypeInt64},
}
// AccountGroupsTable holds the schema information for the "account_groups" table.
AccountGroupsTable = &schema.Table{
Name: "account_groups",
Columns: AccountGroupsColumns,
PrimaryKey: []*schema.Column{AccountGroupsColumns[2], AccountGroupsColumns[3]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "account_groups_accounts_account",
Columns: []*schema.Column{AccountGroupsColumns[2]},
RefColumns: []*schema.Column{AccountsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "account_groups_groups_group",
Columns: []*schema.Column{AccountGroupsColumns[3]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "accountgroup_group_id",
Unique: false,
Columns: []*schema.Column{AccountGroupsColumns[3]},
},
{
Name: "accountgroup_priority",
Unique: false,
Columns: []*schema.Column{AccountGroupsColumns[0]},
},
},
}
// APIKeysColumns holds the columns for the "api_keys" table.
APIKeysColumns = []*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: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "key", Type: field.TypeString, Unique: true, Size: 128},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "group_id", Type: field.TypeInt64, Nullable: true},
{Name: "user_id", Type: field.TypeInt64},
}
// APIKeysTable holds the schema information for the "api_keys" table.
APIKeysTable = &schema.Table{
Name: "api_keys",
Columns: APIKeysColumns,
PrimaryKey: []*schema.Column{APIKeysColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "api_keys_groups_api_keys",
Columns: []*schema.Column{APIKeysColumns[7]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "api_keys_users_api_keys",
Columns: []*schema.Column{APIKeysColumns[8]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "apikey_key",
Unique: true,
Columns: []*schema.Column{APIKeysColumns[4]},
},
{
Name: "apikey_user_id",
Unique: false,
Columns: []*schema.Column{APIKeysColumns[8]},
},
{
Name: "apikey_group_id",
Unique: false,
Columns: []*schema.Column{APIKeysColumns[7]},
},
{
Name: "apikey_status",
Unique: false,
Columns: []*schema.Column{APIKeysColumns[6]},
},
{
Name: "apikey_deleted_at",
Unique: false,
Columns: []*schema.Column{APIKeysColumns[3]},
},
},
}
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*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: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Unique: true, Size: 100},
{Name: "description", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "is_exclusive", Type: field.TypeBool, Default: false},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "platform", Type: field.TypeString, Size: 50, Default: "anthropic"},
{Name: "subscription_type", Type: field.TypeString, Size: 20, Default: "standard"},
{Name: "daily_limit_usd", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
{Name: "weekly_limit_usd", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
{Name: "monthly_limit_usd", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
Indexes: []*schema.Index{
{
Name: "group_name",
Unique: true,
Columns: []*schema.Column{GroupsColumns[4]},
},
{
Name: "group_status",
Unique: false,
Columns: []*schema.Column{GroupsColumns[8]},
},
{
Name: "group_platform",
Unique: false,
Columns: []*schema.Column{GroupsColumns[9]},
},
{
Name: "group_subscription_type",
Unique: false,
Columns: []*schema.Column{GroupsColumns[10]},
},
{
Name: "group_is_exclusive",
Unique: false,
Columns: []*schema.Column{GroupsColumns[7]},
},
{
Name: "group_deleted_at",
Unique: false,
Columns: []*schema.Column{GroupsColumns[3]},
},
},
}
// ProxiesColumns holds the columns for the "proxies" table.
ProxiesColumns = []*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: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "protocol", Type: field.TypeString, Size: 20},
{Name: "host", Type: field.TypeString, Size: 255},
{Name: "port", Type: field.TypeInt},
{Name: "username", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "password", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
}
// ProxiesTable holds the schema information for the "proxies" table.
ProxiesTable = &schema.Table{
Name: "proxies",
Columns: ProxiesColumns,
PrimaryKey: []*schema.Column{ProxiesColumns[0]},
Indexes: []*schema.Index{
{
Name: "proxy_status",
Unique: false,
Columns: []*schema.Column{ProxiesColumns[10]},
},
{
Name: "proxy_deleted_at",
Unique: false,
Columns: []*schema.Column{ProxiesColumns[3]},
},
},
}
// RedeemCodesColumns holds the columns for the "redeem_codes" table.
RedeemCodesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "code", Type: field.TypeString, Unique: true, Size: 32},
{Name: "type", Type: field.TypeString, Size: 20, Default: "balance"},
{Name: "value", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
{Name: "status", Type: field.TypeString, Size: 20, Default: "unused"},
{Name: "used_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "notes", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "validity_days", Type: field.TypeInt, Default: 30},
{Name: "group_id", Type: field.TypeInt64, Nullable: true},
{Name: "used_by", Type: field.TypeInt64, Nullable: true},
}
// RedeemCodesTable holds the schema information for the "redeem_codes" table.
RedeemCodesTable = &schema.Table{
Name: "redeem_codes",
Columns: RedeemCodesColumns,
PrimaryKey: []*schema.Column{RedeemCodesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "redeem_codes_groups_redeem_codes",
Columns: []*schema.Column{RedeemCodesColumns[9]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "redeem_codes_users_redeem_codes",
Columns: []*schema.Column{RedeemCodesColumns[10]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
Indexes: []*schema.Index{
{
Name: "redeemcode_code",
Unique: true,
Columns: []*schema.Column{RedeemCodesColumns[1]},
},
{
Name: "redeemcode_status",
Unique: false,
Columns: []*schema.Column{RedeemCodesColumns[4]},
},
{
Name: "redeemcode_used_by",
Unique: false,
Columns: []*schema.Column{RedeemCodesColumns[10]},
},
{
Name: "redeemcode_group_id",
Unique: false,
Columns: []*schema.Column{RedeemCodesColumns[9]},
},
},
}
// SettingsColumns holds the columns for the "settings" table.
SettingsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100},
{Name: "value", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
}
// SettingsTable holds the schema information for the "settings" table.
SettingsTable = &schema.Table{
Name: "settings",
Columns: SettingsColumns,
PrimaryKey: []*schema.Column{SettingsColumns[0]},
Indexes: []*schema.Index{
{
Name: "setting_key",
Unique: true,
Columns: []*schema.Column{SettingsColumns[1]},
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*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: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "email", Type: field.TypeString, Unique: true, Size: 255},
{Name: "password_hash", Type: field.TypeString, Size: 255},
{Name: "role", Type: field.TypeString, Size: 20, Default: "user"},
{Name: "balance", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
{Name: "concurrency", Type: field.TypeInt, Default: 5},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "username", Type: field.TypeString, Size: 100, Default: ""},
{Name: "wechat", Type: field.TypeString, Size: 100, Default: ""},
{Name: "notes", Type: field.TypeString, Default: "", SchemaType: map[string]string{"postgres": "text"}},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
Indexes: []*schema.Index{
{
Name: "user_email",
Unique: true,
Columns: []*schema.Column{UsersColumns[4]},
},
{
Name: "user_status",
Unique: false,
Columns: []*schema.Column{UsersColumns[9]},
},
{
Name: "user_deleted_at",
Unique: false,
Columns: []*schema.Column{UsersColumns[3]},
},
},
}
// UserAllowedGroupsColumns holds the columns for the "user_allowed_groups" table.
UserAllowedGroupsColumns = []*schema.Column{
{Name: "created_at", Type: field.TypeTime},
{Name: "user_id", Type: field.TypeInt64},
{Name: "group_id", Type: field.TypeInt64},
}
// UserAllowedGroupsTable holds the schema information for the "user_allowed_groups" table.
UserAllowedGroupsTable = &schema.Table{
Name: "user_allowed_groups",
Columns: UserAllowedGroupsColumns,
PrimaryKey: []*schema.Column{UserAllowedGroupsColumns[1], UserAllowedGroupsColumns[2]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_allowed_groups_users_user",
Columns: []*schema.Column{UserAllowedGroupsColumns[1]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "user_allowed_groups_groups_group",
Columns: []*schema.Column{UserAllowedGroupsColumns[2]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "userallowedgroup_group_id",
Unique: false,
Columns: []*schema.Column{UserAllowedGroupsColumns[2]},
},
},
}
// UserSubscriptionsColumns holds the columns for the "user_subscriptions" table.
UserSubscriptionsColumns = []*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: "starts_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "expires_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "daily_window_start", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "weekly_window_start", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "monthly_window_start", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "daily_usage_usd", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "weekly_usage_usd", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "monthly_usage_usd", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "assigned_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "notes", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "group_id", Type: field.TypeInt64},
{Name: "user_id", Type: field.TypeInt64},
{Name: "assigned_by", Type: field.TypeInt64, Nullable: true},
}
// UserSubscriptionsTable holds the schema information for the "user_subscriptions" table.
UserSubscriptionsTable = &schema.Table{
Name: "user_subscriptions",
Columns: UserSubscriptionsColumns,
PrimaryKey: []*schema.Column{UserSubscriptionsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_subscriptions_groups_subscriptions",
Columns: []*schema.Column{UserSubscriptionsColumns[14]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "user_subscriptions_users_subscriptions",
Columns: []*schema.Column{UserSubscriptionsColumns[15]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "user_subscriptions_users_assigned_subscriptions",
Columns: []*schema.Column{UserSubscriptionsColumns[16]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
Indexes: []*schema.Index{
{
Name: "usersubscription_user_id",
Unique: false,
Columns: []*schema.Column{UserSubscriptionsColumns[15]},
},
{
Name: "usersubscription_group_id",
Unique: false,
Columns: []*schema.Column{UserSubscriptionsColumns[14]},
},
{
Name: "usersubscription_status",
Unique: false,
Columns: []*schema.Column{UserSubscriptionsColumns[5]},
},
{
Name: "usersubscription_expires_at",
Unique: false,
Columns: []*schema.Column{UserSubscriptionsColumns[4]},
},
{
Name: "usersubscription_assigned_by",
Unique: false,
Columns: []*schema.Column{UserSubscriptionsColumns[16]},
},
{
Name: "usersubscription_user_id_group_id",
Unique: true,
Columns: []*schema.Column{UserSubscriptionsColumns[15], UserSubscriptionsColumns[14]},
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
AccountsTable,
AccountGroupsTable,
APIKeysTable,
GroupsTable,
ProxiesTable,
RedeemCodesTable,
SettingsTable,
UsersTable,
UserAllowedGroupsTable,
UserSubscriptionsTable,
}
)
func init() {
AccountsTable.Annotation = &entsql.Annotation{
Table: "accounts",
}
AccountGroupsTable.ForeignKeys[0].RefTable = AccountsTable
AccountGroupsTable.ForeignKeys[1].RefTable = GroupsTable
AccountGroupsTable.Annotation = &entsql.Annotation{
Table: "account_groups",
}
APIKeysTable.ForeignKeys[0].RefTable = GroupsTable
APIKeysTable.ForeignKeys[1].RefTable = UsersTable
APIKeysTable.Annotation = &entsql.Annotation{
Table: "api_keys",
}
GroupsTable.Annotation = &entsql.Annotation{
Table: "groups",
}
ProxiesTable.Annotation = &entsql.Annotation{
Table: "proxies",
}
RedeemCodesTable.ForeignKeys[0].RefTable = GroupsTable
RedeemCodesTable.ForeignKeys[1].RefTable = UsersTable
RedeemCodesTable.Annotation = &entsql.Annotation{
Table: "redeem_codes",
}
SettingsTable.Annotation = &entsql.Annotation{
Table: "settings",
}
UsersTable.Annotation = &entsql.Annotation{
Table: "users",
}
UserAllowedGroupsTable.ForeignKeys[0].RefTable = UsersTable
UserAllowedGroupsTable.ForeignKeys[1].RefTable = GroupsTable
UserAllowedGroupsTable.Annotation = &entsql.Annotation{
Table: "user_allowed_groups",
}
UserSubscriptionsTable.ForeignKeys[0].RefTable = GroupsTable
UserSubscriptionsTable.ForeignKeys[1].RefTable = UsersTable
UserSubscriptionsTable.ForeignKeys[2].RefTable = UsersTable
UserSubscriptionsTable.Annotation = &entsql.Annotation{
Table: "user_subscriptions",
}
}

10572
backend/ent/mutation.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Account is the predicate function for account builders.
type Account func(*sql.Selector)
// AccountGroup is the predicate function for accountgroup builders.
type AccountGroup func(*sql.Selector)
// ApiKey is the predicate function for apikey builders.
type ApiKey func(*sql.Selector)
// Group is the predicate function for group builders.
type Group func(*sql.Selector)
// Proxy is the predicate function for proxy builders.
type Proxy func(*sql.Selector)
// RedeemCode is the predicate function for redeemcode builders.
type RedeemCode func(*sql.Selector)
// Setting is the predicate function for setting builders.
type Setting func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)
// UserAllowedGroup is the predicate function for userallowedgroup builders.
type UserAllowedGroup func(*sql.Selector)
// UserSubscription is the predicate function for usersubscription builders.
type UserSubscription func(*sql.Selector)

214
backend/ent/proxy.go Normal file
View File

@@ -0,0 +1,214 @@
// 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/proxy"
)
// Proxy is the model entity for the Proxy schema.
type Proxy 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"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Protocol holds the value of the "protocol" field.
Protocol string `json:"protocol,omitempty"`
// Host holds the value of the "host" field.
Host string `json:"host,omitempty"`
// Port holds the value of the "port" field.
Port int `json:"port,omitempty"`
// Username holds the value of the "username" field.
Username *string `json:"username,omitempty"`
// Password holds the value of the "password" field.
Password *string `json:"password,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Proxy) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case proxy.FieldID, proxy.FieldPort:
values[i] = new(sql.NullInt64)
case proxy.FieldName, proxy.FieldProtocol, proxy.FieldHost, proxy.FieldUsername, proxy.FieldPassword, proxy.FieldStatus:
values[i] = new(sql.NullString)
case proxy.FieldCreatedAt, proxy.FieldUpdatedAt, proxy.FieldDeletedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Proxy fields.
func (_m *Proxy) 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 proxy.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 proxy.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 proxy.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 proxy.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(time.Time)
*_m.DeletedAt = value.Time
}
case proxy.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case proxy.FieldProtocol:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field protocol", values[i])
} else if value.Valid {
_m.Protocol = value.String
}
case proxy.FieldHost:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field host", values[i])
} else if value.Valid {
_m.Host = value.String
}
case proxy.FieldPort:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field port", values[i])
} else if value.Valid {
_m.Port = int(value.Int64)
}
case proxy.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 proxy.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
_m.Password = new(string)
*_m.Password = value.String
}
case proxy.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Proxy.
// This includes values selected through modifiers, order, etc.
func (_m *Proxy) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Proxy.
// Note that you need to call Proxy.Unwrap() before calling this method if this Proxy
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Proxy) Update() *ProxyUpdateOne {
return NewProxyClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Proxy 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 *Proxy) Unwrap() *Proxy {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Proxy is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Proxy) String() string {
var builder strings.Builder
builder.WriteString("Proxy(")
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(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("protocol=")
builder.WriteString(_m.Protocol)
builder.WriteString(", ")
builder.WriteString("host=")
builder.WriteString(_m.Host)
builder.WriteString(", ")
builder.WriteString("port=")
builder.WriteString(fmt.Sprintf("%v", _m.Port))
builder.WriteString(", ")
if v := _m.Username; v != nil {
builder.WriteString("username=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.Password; v != nil {
builder.WriteString("password=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteByte(')')
return builder.String()
}
// Proxies is a parsable slice of Proxy.
type Proxies []*Proxy

152
backend/ent/proxy/proxy.go Normal file
View File

@@ -0,0 +1,152 @@
// Code generated by ent, DO NOT EDIT.
package proxy
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the proxy type in the database.
Label = "proxy"
// 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"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldProtocol holds the string denoting the protocol field in the database.
FieldProtocol = "protocol"
// FieldHost holds the string denoting the host field in the database.
FieldHost = "host"
// FieldPort holds the string denoting the port field in the database.
FieldPort = "port"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// Table holds the table name of the proxy in the database.
Table = "proxies"
)
// Columns holds all SQL columns for proxy fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldName,
FieldProtocol,
FieldHost,
FieldPort,
FieldUsername,
FieldPassword,
FieldStatus,
}
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "github.com/Wei-Shaw/sub2api/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
// 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
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// ProtocolValidator is a validator for the "protocol" field. It is called by the builders before save.
ProtocolValidator func(string) error
// HostValidator is a validator for the "host" field. It is called by the builders before save.
HostValidator func(string) error
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
)
// OrderOption defines the ordering options for the Proxy 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()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByProtocol orders the results by the protocol field.
func ByProtocol(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldProtocol, opts...).ToFunc()
}
// ByHost orders the results by the host field.
func ByHost(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldHost, opts...).ToFunc()
}
// ByPort orders the results by the port field.
func ByPort(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPort, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}

700
backend/ent/proxy/where.go Normal file
View File

@@ -0,0 +1,700 @@
// Code generated by ent, DO NOT EDIT.
package proxy
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldDeletedAt, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldName, v))
}
// Protocol applies equality check predicate on the "protocol" field. It's identical to ProtocolEQ.
func Protocol(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldProtocol, v))
}
// Host applies equality check predicate on the "host" field. It's identical to HostEQ.
func Host(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldHost, v))
}
// Port applies equality check predicate on the "port" field. It's identical to PortEQ.
func Port(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldPort, v))
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldUsername, v))
}
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
func Password(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldPassword, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldStatus, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v time.Time) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.Proxy {
return predicate.Proxy(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.Proxy {
return predicate.Proxy(sql.FieldNotNull(FieldDeletedAt))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContainsFold(FieldName, v))
}
// ProtocolEQ applies the EQ predicate on the "protocol" field.
func ProtocolEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldProtocol, v))
}
// ProtocolNEQ applies the NEQ predicate on the "protocol" field.
func ProtocolNEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldProtocol, v))
}
// ProtocolIn applies the In predicate on the "protocol" field.
func ProtocolIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldProtocol, vs...))
}
// ProtocolNotIn applies the NotIn predicate on the "protocol" field.
func ProtocolNotIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldProtocol, vs...))
}
// ProtocolGT applies the GT predicate on the "protocol" field.
func ProtocolGT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldProtocol, v))
}
// ProtocolGTE applies the GTE predicate on the "protocol" field.
func ProtocolGTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldProtocol, v))
}
// ProtocolLT applies the LT predicate on the "protocol" field.
func ProtocolLT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldProtocol, v))
}
// ProtocolLTE applies the LTE predicate on the "protocol" field.
func ProtocolLTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldProtocol, v))
}
// ProtocolContains applies the Contains predicate on the "protocol" field.
func ProtocolContains(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContains(FieldProtocol, v))
}
// ProtocolHasPrefix applies the HasPrefix predicate on the "protocol" field.
func ProtocolHasPrefix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasPrefix(FieldProtocol, v))
}
// ProtocolHasSuffix applies the HasSuffix predicate on the "protocol" field.
func ProtocolHasSuffix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasSuffix(FieldProtocol, v))
}
// ProtocolEqualFold applies the EqualFold predicate on the "protocol" field.
func ProtocolEqualFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEqualFold(FieldProtocol, v))
}
// ProtocolContainsFold applies the ContainsFold predicate on the "protocol" field.
func ProtocolContainsFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContainsFold(FieldProtocol, v))
}
// HostEQ applies the EQ predicate on the "host" field.
func HostEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldHost, v))
}
// HostNEQ applies the NEQ predicate on the "host" field.
func HostNEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldHost, v))
}
// HostIn applies the In predicate on the "host" field.
func HostIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldHost, vs...))
}
// HostNotIn applies the NotIn predicate on the "host" field.
func HostNotIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldHost, vs...))
}
// HostGT applies the GT predicate on the "host" field.
func HostGT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldHost, v))
}
// HostGTE applies the GTE predicate on the "host" field.
func HostGTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldHost, v))
}
// HostLT applies the LT predicate on the "host" field.
func HostLT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldHost, v))
}
// HostLTE applies the LTE predicate on the "host" field.
func HostLTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldHost, v))
}
// HostContains applies the Contains predicate on the "host" field.
func HostContains(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContains(FieldHost, v))
}
// HostHasPrefix applies the HasPrefix predicate on the "host" field.
func HostHasPrefix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasPrefix(FieldHost, v))
}
// HostHasSuffix applies the HasSuffix predicate on the "host" field.
func HostHasSuffix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasSuffix(FieldHost, v))
}
// HostEqualFold applies the EqualFold predicate on the "host" field.
func HostEqualFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEqualFold(FieldHost, v))
}
// HostContainsFold applies the ContainsFold predicate on the "host" field.
func HostContainsFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContainsFold(FieldHost, v))
}
// PortEQ applies the EQ predicate on the "port" field.
func PortEQ(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldPort, v))
}
// PortNEQ applies the NEQ predicate on the "port" field.
func PortNEQ(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldPort, v))
}
// PortIn applies the In predicate on the "port" field.
func PortIn(vs ...int) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldPort, vs...))
}
// PortNotIn applies the NotIn predicate on the "port" field.
func PortNotIn(vs ...int) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldPort, vs...))
}
// PortGT applies the GT predicate on the "port" field.
func PortGT(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldPort, v))
}
// PortGTE applies the GTE predicate on the "port" field.
func PortGTE(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldPort, v))
}
// PortLT applies the LT predicate on the "port" field.
func PortLT(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldPort, v))
}
// PortLTE applies the LTE predicate on the "port" field.
func PortLTE(v int) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldPort, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldUsername, v))
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldUsername, v))
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldUsername, vs...))
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldUsername, vs...))
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldUsername, v))
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldUsername, v))
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldUsername, v))
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldUsername, v))
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContains(FieldUsername, v))
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasPrefix(FieldUsername, v))
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasSuffix(FieldUsername, v))
}
// UsernameIsNil applies the IsNil predicate on the "username" field.
func UsernameIsNil() predicate.Proxy {
return predicate.Proxy(sql.FieldIsNull(FieldUsername))
}
// UsernameNotNil applies the NotNil predicate on the "username" field.
func UsernameNotNil() predicate.Proxy {
return predicate.Proxy(sql.FieldNotNull(FieldUsername))
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEqualFold(FieldUsername, v))
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContainsFold(FieldUsername, v))
}
// PasswordEQ applies the EQ predicate on the "password" field.
func PasswordEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldPassword, v))
}
// PasswordNEQ applies the NEQ predicate on the "password" field.
func PasswordNEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldPassword, v))
}
// PasswordIn applies the In predicate on the "password" field.
func PasswordIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldPassword, vs...))
}
// PasswordNotIn applies the NotIn predicate on the "password" field.
func PasswordNotIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldPassword, vs...))
}
// PasswordGT applies the GT predicate on the "password" field.
func PasswordGT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldPassword, v))
}
// PasswordGTE applies the GTE predicate on the "password" field.
func PasswordGTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldPassword, v))
}
// PasswordLT applies the LT predicate on the "password" field.
func PasswordLT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldPassword, v))
}
// PasswordLTE applies the LTE predicate on the "password" field.
func PasswordLTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldPassword, v))
}
// PasswordContains applies the Contains predicate on the "password" field.
func PasswordContains(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContains(FieldPassword, v))
}
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
func PasswordHasPrefix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasPrefix(FieldPassword, v))
}
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
func PasswordHasSuffix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordIsNil applies the IsNil predicate on the "password" field.
func PasswordIsNil() predicate.Proxy {
return predicate.Proxy(sql.FieldIsNull(FieldPassword))
}
// PasswordNotNil applies the NotNil predicate on the "password" field.
func PasswordNotNil() predicate.Proxy {
return predicate.Proxy(sql.FieldNotNull(FieldPassword))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEqualFold(FieldPassword, v))
}
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
func PasswordContainsFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContainsFold(FieldPassword, v))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.Proxy {
return predicate.Proxy(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.Proxy {
return predicate.Proxy(sql.FieldContainsFold(FieldStatus, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Proxy) predicate.Proxy {
return predicate.Proxy(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Proxy) predicate.Proxy {
return predicate.Proxy(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Proxy) predicate.Proxy {
return predicate.Proxy(sql.NotPredicates(p))
}

1080
backend/ent/proxy_create.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
// 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/proxy"
)
// ProxyDelete is the builder for deleting a Proxy entity.
type ProxyDelete struct {
config
hooks []Hook
mutation *ProxyMutation
}
// Where appends a list predicates to the ProxyDelete builder.
func (_d *ProxyDelete) Where(ps ...predicate.Proxy) *ProxyDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *ProxyDelete) 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 *ProxyDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *ProxyDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(proxy.Table, sqlgraph.NewFieldSpec(proxy.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
}
// ProxyDeleteOne is the builder for deleting a single Proxy entity.
type ProxyDeleteOne struct {
_d *ProxyDelete
}
// Where appends a list predicates to the ProxyDelete builder.
func (_d *ProxyDeleteOne) Where(ps ...predicate.Proxy) *ProxyDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *ProxyDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{proxy.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ProxyDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

527
backend/ent/proxy_query.go Normal file
View File

@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"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/proxy"
)
// ProxyQuery is the builder for querying Proxy entities.
type ProxyQuery struct {
config
ctx *QueryContext
order []proxy.OrderOption
inters []Interceptor
predicates []predicate.Proxy
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ProxyQuery builder.
func (_q *ProxyQuery) Where(ps ...predicate.Proxy) *ProxyQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *ProxyQuery) Limit(limit int) *ProxyQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *ProxyQuery) Offset(offset int) *ProxyQuery {
_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 *ProxyQuery) Unique(unique bool) *ProxyQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *ProxyQuery) Order(o ...proxy.OrderOption) *ProxyQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Proxy entity from the query.
// Returns a *NotFoundError when no Proxy was found.
func (_q *ProxyQuery) First(ctx context.Context) (*Proxy, 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{proxy.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *ProxyQuery) FirstX(ctx context.Context) *Proxy {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Proxy ID from the query.
// Returns a *NotFoundError when no Proxy ID was found.
func (_q *ProxyQuery) 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{proxy.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *ProxyQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Proxy entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Proxy entity is found.
// Returns a *NotFoundError when no Proxy entities are found.
func (_q *ProxyQuery) Only(ctx context.Context) (*Proxy, 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{proxy.Label}
default:
return nil, &NotSingularError{proxy.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *ProxyQuery) OnlyX(ctx context.Context) *Proxy {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Proxy ID in the query.
// Returns a *NotSingularError when more than one Proxy ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *ProxyQuery) 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{proxy.Label}
default:
err = &NotSingularError{proxy.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *ProxyQuery) 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 Proxies.
func (_q *ProxyQuery) All(ctx context.Context) ([]*Proxy, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Proxy, *ProxyQuery]()
return withInterceptors[[]*Proxy](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *ProxyQuery) AllX(ctx context.Context) []*Proxy {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Proxy IDs.
func (_q *ProxyQuery) 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(proxy.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *ProxyQuery) 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 *ProxyQuery) 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[*ProxyQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *ProxyQuery) 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 *ProxyQuery) 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 *ProxyQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ProxyQuery 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 *ProxyQuery) Clone() *ProxyQuery {
if _q == nil {
return nil
}
return &ProxyQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]proxy.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Proxy{}, _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.Proxy.Query().
// GroupBy(proxy.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *ProxyQuery) GroupBy(field string, fields ...string) *ProxyGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &ProxyGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = proxy.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.Proxy.Query().
// Select(proxy.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *ProxyQuery) Select(fields ...string) *ProxySelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &ProxySelect{ProxyQuery: _q}
sbuild.label = proxy.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a ProxySelect configured with the given aggregations.
func (_q *ProxyQuery) Aggregate(fns ...AggregateFunc) *ProxySelect {
return _q.Select().Aggregate(fns...)
}
func (_q *ProxyQuery) 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 !proxy.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 *ProxyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Proxy, error) {
var (
nodes = []*Proxy{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Proxy).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Proxy{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *ProxyQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *ProxyQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(proxy.Table, proxy.Columns, sqlgraph.NewFieldSpec(proxy.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, proxy.FieldID)
for i := range fields {
if fields[i] != proxy.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 *ProxyQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(proxy.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = proxy.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ProxyGroupBy is the group-by builder for Proxy entities.
type ProxyGroupBy struct {
selector
build *ProxyQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *ProxyGroupBy) Aggregate(fns ...AggregateFunc) *ProxyGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *ProxyGroupBy) 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[*ProxyQuery, *ProxyGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *ProxyGroupBy) sqlScan(ctx context.Context, root *ProxyQuery, 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)
}
// ProxySelect is the builder for selecting fields of Proxy entities.
type ProxySelect struct {
*ProxyQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *ProxySelect) Aggregate(fns ...AggregateFunc) *ProxySelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *ProxySelect) 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[*ProxyQuery, *ProxySelect](ctx, _s.ProxyQuery, _s, _s.inters, v)
}
func (_s *ProxySelect) sqlScan(ctx context.Context, root *ProxyQuery, 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)
}

646
backend/ent/proxy_update.go Normal file
View File

@@ -0,0 +1,646 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"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/proxy"
)
// ProxyUpdate is the builder for updating Proxy entities.
type ProxyUpdate struct {
config
hooks []Hook
mutation *ProxyMutation
}
// Where appends a list predicates to the ProxyUpdate builder.
func (_u *ProxyUpdate) Where(ps ...predicate.Proxy) *ProxyUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ProxyUpdate) SetUpdatedAt(v time.Time) *ProxyUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ProxyUpdate) SetDeletedAt(v time.Time) *ProxyUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillableDeletedAt(v *time.Time) *ProxyUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ProxyUpdate) ClearDeletedAt() *ProxyUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetName sets the "name" field.
func (_u *ProxyUpdate) SetName(v string) *ProxyUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillableName(v *string) *ProxyUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetProtocol sets the "protocol" field.
func (_u *ProxyUpdate) SetProtocol(v string) *ProxyUpdate {
_u.mutation.SetProtocol(v)
return _u
}
// SetNillableProtocol sets the "protocol" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillableProtocol(v *string) *ProxyUpdate {
if v != nil {
_u.SetProtocol(*v)
}
return _u
}
// SetHost sets the "host" field.
func (_u *ProxyUpdate) SetHost(v string) *ProxyUpdate {
_u.mutation.SetHost(v)
return _u
}
// SetNillableHost sets the "host" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillableHost(v *string) *ProxyUpdate {
if v != nil {
_u.SetHost(*v)
}
return _u
}
// SetPort sets the "port" field.
func (_u *ProxyUpdate) SetPort(v int) *ProxyUpdate {
_u.mutation.ResetPort()
_u.mutation.SetPort(v)
return _u
}
// SetNillablePort sets the "port" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillablePort(v *int) *ProxyUpdate {
if v != nil {
_u.SetPort(*v)
}
return _u
}
// AddPort adds value to the "port" field.
func (_u *ProxyUpdate) AddPort(v int) *ProxyUpdate {
_u.mutation.AddPort(v)
return _u
}
// SetUsername sets the "username" field.
func (_u *ProxyUpdate) SetUsername(v string) *ProxyUpdate {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillableUsername(v *string) *ProxyUpdate {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// ClearUsername clears the value of the "username" field.
func (_u *ProxyUpdate) ClearUsername() *ProxyUpdate {
_u.mutation.ClearUsername()
return _u
}
// SetPassword sets the "password" field.
func (_u *ProxyUpdate) SetPassword(v string) *ProxyUpdate {
_u.mutation.SetPassword(v)
return _u
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillablePassword(v *string) *ProxyUpdate {
if v != nil {
_u.SetPassword(*v)
}
return _u
}
// ClearPassword clears the value of the "password" field.
func (_u *ProxyUpdate) ClearPassword() *ProxyUpdate {
_u.mutation.ClearPassword()
return _u
}
// SetStatus sets the "status" field.
func (_u *ProxyUpdate) SetStatus(v string) *ProxyUpdate {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *ProxyUpdate) SetNillableStatus(v *string) *ProxyUpdate {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// Mutation returns the ProxyMutation object of the builder.
func (_u *ProxyUpdate) Mutation() *ProxyMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ProxyUpdate) Save(ctx context.Context) (int, error) {
if err := _u.defaults(); err != nil {
return 0, err
}
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ProxyUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *ProxyUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ProxyUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *ProxyUpdate) defaults() error {
if _, ok := _u.mutation.UpdatedAt(); !ok {
if proxy.UpdateDefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized proxy.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := proxy.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_u *ProxyUpdate) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := proxy.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Proxy.name": %w`, err)}
}
}
if v, ok := _u.mutation.Protocol(); ok {
if err := proxy.ProtocolValidator(v); err != nil {
return &ValidationError{Name: "protocol", err: fmt.Errorf(`ent: validator failed for field "Proxy.protocol": %w`, err)}
}
}
if v, ok := _u.mutation.Host(); ok {
if err := proxy.HostValidator(v); err != nil {
return &ValidationError{Name: "host", err: fmt.Errorf(`ent: validator failed for field "Proxy.host": %w`, err)}
}
}
if v, ok := _u.mutation.Username(); ok {
if err := proxy.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "Proxy.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := proxy.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "Proxy.password": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := proxy.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Proxy.status": %w`, err)}
}
}
return nil
}
func (_u *ProxyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(proxy.Table, proxy.Columns, sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(proxy.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(proxy.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(proxy.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(proxy.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Protocol(); ok {
_spec.SetField(proxy.FieldProtocol, field.TypeString, value)
}
if value, ok := _u.mutation.Host(); ok {
_spec.SetField(proxy.FieldHost, field.TypeString, value)
}
if value, ok := _u.mutation.Port(); ok {
_spec.SetField(proxy.FieldPort, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedPort(); ok {
_spec.AddField(proxy.FieldPort, field.TypeInt, value)
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(proxy.FieldUsername, field.TypeString, value)
}
if _u.mutation.UsernameCleared() {
_spec.ClearField(proxy.FieldUsername, field.TypeString)
}
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(proxy.FieldPassword, field.TypeString, value)
}
if _u.mutation.PasswordCleared() {
_spec.ClearField(proxy.FieldPassword, field.TypeString)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(proxy.FieldStatus, field.TypeString, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{proxy.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// ProxyUpdateOne is the builder for updating a single Proxy entity.
type ProxyUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ProxyMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ProxyUpdateOne) SetUpdatedAt(v time.Time) *ProxyUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ProxyUpdateOne) SetDeletedAt(v time.Time) *ProxyUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillableDeletedAt(v *time.Time) *ProxyUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ProxyUpdateOne) ClearDeletedAt() *ProxyUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetName sets the "name" field.
func (_u *ProxyUpdateOne) SetName(v string) *ProxyUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillableName(v *string) *ProxyUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetProtocol sets the "protocol" field.
func (_u *ProxyUpdateOne) SetProtocol(v string) *ProxyUpdateOne {
_u.mutation.SetProtocol(v)
return _u
}
// SetNillableProtocol sets the "protocol" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillableProtocol(v *string) *ProxyUpdateOne {
if v != nil {
_u.SetProtocol(*v)
}
return _u
}
// SetHost sets the "host" field.
func (_u *ProxyUpdateOne) SetHost(v string) *ProxyUpdateOne {
_u.mutation.SetHost(v)
return _u
}
// SetNillableHost sets the "host" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillableHost(v *string) *ProxyUpdateOne {
if v != nil {
_u.SetHost(*v)
}
return _u
}
// SetPort sets the "port" field.
func (_u *ProxyUpdateOne) SetPort(v int) *ProxyUpdateOne {
_u.mutation.ResetPort()
_u.mutation.SetPort(v)
return _u
}
// SetNillablePort sets the "port" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillablePort(v *int) *ProxyUpdateOne {
if v != nil {
_u.SetPort(*v)
}
return _u
}
// AddPort adds value to the "port" field.
func (_u *ProxyUpdateOne) AddPort(v int) *ProxyUpdateOne {
_u.mutation.AddPort(v)
return _u
}
// SetUsername sets the "username" field.
func (_u *ProxyUpdateOne) SetUsername(v string) *ProxyUpdateOne {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillableUsername(v *string) *ProxyUpdateOne {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// ClearUsername clears the value of the "username" field.
func (_u *ProxyUpdateOne) ClearUsername() *ProxyUpdateOne {
_u.mutation.ClearUsername()
return _u
}
// SetPassword sets the "password" field.
func (_u *ProxyUpdateOne) SetPassword(v string) *ProxyUpdateOne {
_u.mutation.SetPassword(v)
return _u
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillablePassword(v *string) *ProxyUpdateOne {
if v != nil {
_u.SetPassword(*v)
}
return _u
}
// ClearPassword clears the value of the "password" field.
func (_u *ProxyUpdateOne) ClearPassword() *ProxyUpdateOne {
_u.mutation.ClearPassword()
return _u
}
// SetStatus sets the "status" field.
func (_u *ProxyUpdateOne) SetStatus(v string) *ProxyUpdateOne {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *ProxyUpdateOne) SetNillableStatus(v *string) *ProxyUpdateOne {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// Mutation returns the ProxyMutation object of the builder.
func (_u *ProxyUpdateOne) Mutation() *ProxyMutation {
return _u.mutation
}
// Where appends a list predicates to the ProxyUpdate builder.
func (_u *ProxyUpdateOne) Where(ps ...predicate.Proxy) *ProxyUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *ProxyUpdateOne) Select(field string, fields ...string) *ProxyUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Proxy entity.
func (_u *ProxyUpdateOne) Save(ctx context.Context) (*Proxy, error) {
if err := _u.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ProxyUpdateOne) SaveX(ctx context.Context) *Proxy {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *ProxyUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ProxyUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *ProxyUpdateOne) defaults() error {
if _, ok := _u.mutation.UpdatedAt(); !ok {
if proxy.UpdateDefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized proxy.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := proxy.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_u *ProxyUpdateOne) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := proxy.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Proxy.name": %w`, err)}
}
}
if v, ok := _u.mutation.Protocol(); ok {
if err := proxy.ProtocolValidator(v); err != nil {
return &ValidationError{Name: "protocol", err: fmt.Errorf(`ent: validator failed for field "Proxy.protocol": %w`, err)}
}
}
if v, ok := _u.mutation.Host(); ok {
if err := proxy.HostValidator(v); err != nil {
return &ValidationError{Name: "host", err: fmt.Errorf(`ent: validator failed for field "Proxy.host": %w`, err)}
}
}
if v, ok := _u.mutation.Username(); ok {
if err := proxy.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "Proxy.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := proxy.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "Proxy.password": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := proxy.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Proxy.status": %w`, err)}
}
}
return nil
}
func (_u *ProxyUpdateOne) sqlSave(ctx context.Context) (_node *Proxy, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(proxy.Table, proxy.Columns, sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Proxy.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, proxy.FieldID)
for _, f := range fields {
if !proxy.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != proxy.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(proxy.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(proxy.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(proxy.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(proxy.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Protocol(); ok {
_spec.SetField(proxy.FieldProtocol, field.TypeString, value)
}
if value, ok := _u.mutation.Host(); ok {
_spec.SetField(proxy.FieldHost, field.TypeString, value)
}
if value, ok := _u.mutation.Port(); ok {
_spec.SetField(proxy.FieldPort, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedPort(); ok {
_spec.AddField(proxy.FieldPort, field.TypeInt, value)
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(proxy.FieldUsername, field.TypeString, value)
}
if _u.mutation.UsernameCleared() {
_spec.ClearField(proxy.FieldUsername, field.TypeString)
}
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(proxy.FieldPassword, field.TypeString, value)
}
if _u.mutation.PasswordCleared() {
_spec.ClearField(proxy.FieldPassword, field.TypeString)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(proxy.FieldStatus, field.TypeString, value)
}
_node = &Proxy{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{proxy.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

267
backend/ent/redeemcode.go Normal file
View File

@@ -0,0 +1,267 @@
// 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/group"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// RedeemCode is the model entity for the RedeemCode schema.
type RedeemCode struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// Code holds the value of the "code" field.
Code string `json:"code,omitempty"`
// Type holds the value of the "type" field.
Type string `json:"type,omitempty"`
// Value holds the value of the "value" field.
Value float64 `json:"value,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// UsedBy holds the value of the "used_by" field.
UsedBy *int64 `json:"used_by,omitempty"`
// UsedAt holds the value of the "used_at" field.
UsedAt *time.Time `json:"used_at,omitempty"`
// Notes holds the value of the "notes" field.
Notes *string `json:"notes,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// GroupID holds the value of the "group_id" field.
GroupID *int64 `json:"group_id,omitempty"`
// ValidityDays holds the value of the "validity_days" field.
ValidityDays int `json:"validity_days,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the RedeemCodeQuery when eager-loading is set.
Edges RedeemCodeEdges `json:"edges"`
selectValues sql.SelectValues
}
// RedeemCodeEdges holds the relations/edges for other nodes in the graph.
type RedeemCodeEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e RedeemCodeEdges) UserOrErr() (*User, error) {
if e.User != nil {
return e.User, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "user"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e RedeemCodeEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*RedeemCode) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case redeemcode.FieldValue:
values[i] = new(sql.NullFloat64)
case redeemcode.FieldID, redeemcode.FieldUsedBy, redeemcode.FieldGroupID, redeemcode.FieldValidityDays:
values[i] = new(sql.NullInt64)
case redeemcode.FieldCode, redeemcode.FieldType, redeemcode.FieldStatus, redeemcode.FieldNotes:
values[i] = new(sql.NullString)
case redeemcode.FieldUsedAt, redeemcode.FieldCreatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the RedeemCode fields.
func (_m *RedeemCode) 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 redeemcode.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 redeemcode.FieldCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field code", values[i])
} else if value.Valid {
_m.Code = value.String
}
case redeemcode.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_m.Type = value.String
}
case redeemcode.FieldValue:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field value", values[i])
} else if value.Valid {
_m.Value = value.Float64
}
case redeemcode.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
case redeemcode.FieldUsedBy:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field used_by", values[i])
} else if value.Valid {
_m.UsedBy = new(int64)
*_m.UsedBy = value.Int64
}
case redeemcode.FieldUsedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field used_at", values[i])
} else if value.Valid {
_m.UsedAt = new(time.Time)
*_m.UsedAt = value.Time
}
case redeemcode.FieldNotes:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[i])
} else if value.Valid {
_m.Notes = new(string)
*_m.Notes = value.String
}
case redeemcode.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 redeemcode.FieldGroupID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field group_id", values[i])
} else if value.Valid {
_m.GroupID = new(int64)
*_m.GroupID = value.Int64
}
case redeemcode.FieldValidityDays:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field validity_days", values[i])
} else if value.Valid {
_m.ValidityDays = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// GetValue returns the ent.Value that was dynamically selected and assigned to the RedeemCode.
// This includes values selected through modifiers, order, etc.
func (_m *RedeemCode) GetValue(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the RedeemCode entity.
func (_m *RedeemCode) QueryUser() *UserQuery {
return NewRedeemCodeClient(_m.config).QueryUser(_m)
}
// QueryGroup queries the "group" edge of the RedeemCode entity.
func (_m *RedeemCode) QueryGroup() *GroupQuery {
return NewRedeemCodeClient(_m.config).QueryGroup(_m)
}
// Update returns a builder for updating this RedeemCode.
// Note that you need to call RedeemCode.Unwrap() before calling this method if this RedeemCode
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *RedeemCode) Update() *RedeemCodeUpdateOne {
return NewRedeemCodeClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the RedeemCode 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 *RedeemCode) Unwrap() *RedeemCode {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: RedeemCode is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *RedeemCode) String() string {
var builder strings.Builder
builder.WriteString("RedeemCode(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("code=")
builder.WriteString(_m.Code)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(_m.Type)
builder.WriteString(", ")
builder.WriteString("value=")
builder.WriteString(fmt.Sprintf("%v", _m.Value))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
if v := _m.UsedBy; v != nil {
builder.WriteString("used_by=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
if v := _m.UsedAt; v != nil {
builder.WriteString("used_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.Notes; v != nil {
builder.WriteString("notes=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := _m.GroupID; v != nil {
builder.WriteString("group_id=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("validity_days=")
builder.WriteString(fmt.Sprintf("%v", _m.ValidityDays))
builder.WriteByte(')')
return builder.String()
}
// RedeemCodes is a parsable slice of RedeemCode.
type RedeemCodes []*RedeemCode

View File

@@ -0,0 +1,187 @@
// Code generated by ent, DO NOT EDIT.
package redeemcode
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the redeemcode type in the database.
Label = "redeem_code"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCode holds the string denoting the code field in the database.
FieldCode = "code"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldValue holds the string denoting the value field in the database.
FieldValue = "value"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldUsedBy holds the string denoting the used_by field in the database.
FieldUsedBy = "used_by"
// FieldUsedAt holds the string denoting the used_at field in the database.
FieldUsedAt = "used_at"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldGroupID holds the string denoting the group_id field in the database.
FieldGroupID = "group_id"
// FieldValidityDays holds the string denoting the validity_days field in the database.
FieldValidityDays = "validity_days"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// Table holds the table name of the redeemcode in the database.
Table = "redeem_codes"
// UserTable is the table that holds the user relation/edge.
UserTable = "redeem_codes"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "used_by"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "redeem_codes"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
)
// Columns holds all SQL columns for redeemcode fields.
var Columns = []string{
FieldID,
FieldCode,
FieldType,
FieldValue,
FieldStatus,
FieldUsedBy,
FieldUsedAt,
FieldNotes,
FieldCreatedAt,
FieldGroupID,
FieldValidityDays,
}
// 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 (
// CodeValidator is a validator for the "code" field. It is called by the builders before save.
CodeValidator func(string) error
// DefaultType holds the default value on creation for the "type" field.
DefaultType string
// TypeValidator is a validator for the "type" field. It is called by the builders before save.
TypeValidator func(string) error
// DefaultValue holds the default value on creation for the "value" field.
DefaultValue float64
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultValidityDays holds the default value on creation for the "validity_days" field.
DefaultValidityDays int
)
// OrderOption defines the ordering options for the RedeemCode 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()
}
// ByCode orders the results by the code field.
func ByCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCode, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByValue orders the results by the value field.
func ByValue(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValue, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByUsedBy orders the results by the used_by field.
func ByUsedBy(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsedBy, opts...).ToFunc()
}
// ByUsedAt orders the results by the used_at field.
func ByUsedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsedAt, opts...).ToFunc()
}
// ByNotes orders the results by the notes field.
func ByNotes(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotes, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByGroupID orders the results by the group_id field.
func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGroupID, opts...).ToFunc()
}
// ByValidityDays orders the results by the validity_days field.
func ByValidityDays(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValidityDays, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
}

View File

@@ -0,0 +1,667 @@
// Code generated by ent, DO NOT EDIT.
package redeemcode
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldID, id))
}
// Code applies equality check predicate on the "code" field. It's identical to CodeEQ.
func Code(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldCode, v))
}
// Type applies equality check predicate on the "type" field. It's identical to TypeEQ.
func Type(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldType, v))
}
// Value applies equality check predicate on the "value" field. It's identical to ValueEQ.
func Value(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldValue, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldStatus, v))
}
// UsedBy applies equality check predicate on the "used_by" field. It's identical to UsedByEQ.
func UsedBy(v int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldUsedBy, v))
}
// UsedAt applies equality check predicate on the "used_at" field. It's identical to UsedAtEQ.
func UsedAt(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldUsedAt, v))
}
// Notes applies equality check predicate on the "notes" field. It's identical to NotesEQ.
func Notes(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldNotes, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldCreatedAt, v))
}
// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
func GroupID(v int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldGroupID, v))
}
// ValidityDays applies equality check predicate on the "validity_days" field. It's identical to ValidityDaysEQ.
func ValidityDays(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldValidityDays, v))
}
// CodeEQ applies the EQ predicate on the "code" field.
func CodeEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldCode, v))
}
// CodeNEQ applies the NEQ predicate on the "code" field.
func CodeNEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldCode, v))
}
// CodeIn applies the In predicate on the "code" field.
func CodeIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldCode, vs...))
}
// CodeNotIn applies the NotIn predicate on the "code" field.
func CodeNotIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldCode, vs...))
}
// CodeGT applies the GT predicate on the "code" field.
func CodeGT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldCode, v))
}
// CodeGTE applies the GTE predicate on the "code" field.
func CodeGTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldCode, v))
}
// CodeLT applies the LT predicate on the "code" field.
func CodeLT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldCode, v))
}
// CodeLTE applies the LTE predicate on the "code" field.
func CodeLTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldCode, v))
}
// CodeContains applies the Contains predicate on the "code" field.
func CodeContains(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContains(FieldCode, v))
}
// CodeHasPrefix applies the HasPrefix predicate on the "code" field.
func CodeHasPrefix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasPrefix(FieldCode, v))
}
// CodeHasSuffix applies the HasSuffix predicate on the "code" field.
func CodeHasSuffix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasSuffix(FieldCode, v))
}
// CodeEqualFold applies the EqualFold predicate on the "code" field.
func CodeEqualFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEqualFold(FieldCode, v))
}
// CodeContainsFold applies the ContainsFold predicate on the "code" field.
func CodeContainsFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContainsFold(FieldCode, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldType, vs...))
}
// TypeGT applies the GT predicate on the "type" field.
func TypeGT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldType, v))
}
// TypeGTE applies the GTE predicate on the "type" field.
func TypeGTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldType, v))
}
// TypeLT applies the LT predicate on the "type" field.
func TypeLT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldType, v))
}
// TypeLTE applies the LTE predicate on the "type" field.
func TypeLTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldType, v))
}
// TypeContains applies the Contains predicate on the "type" field.
func TypeContains(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContains(FieldType, v))
}
// TypeHasPrefix applies the HasPrefix predicate on the "type" field.
func TypeHasPrefix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasPrefix(FieldType, v))
}
// TypeHasSuffix applies the HasSuffix predicate on the "type" field.
func TypeHasSuffix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasSuffix(FieldType, v))
}
// TypeEqualFold applies the EqualFold predicate on the "type" field.
func TypeEqualFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEqualFold(FieldType, v))
}
// TypeContainsFold applies the ContainsFold predicate on the "type" field.
func TypeContainsFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContainsFold(FieldType, v))
}
// ValueEQ applies the EQ predicate on the "value" field.
func ValueEQ(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldValue, v))
}
// ValueNEQ applies the NEQ predicate on the "value" field.
func ValueNEQ(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldValue, v))
}
// ValueIn applies the In predicate on the "value" field.
func ValueIn(vs ...float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldValue, vs...))
}
// ValueNotIn applies the NotIn predicate on the "value" field.
func ValueNotIn(vs ...float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldValue, vs...))
}
// ValueGT applies the GT predicate on the "value" field.
func ValueGT(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldValue, v))
}
// ValueGTE applies the GTE predicate on the "value" field.
func ValueGTE(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldValue, v))
}
// ValueLT applies the LT predicate on the "value" field.
func ValueLT(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldValue, v))
}
// ValueLTE applies the LTE predicate on the "value" field.
func ValueLTE(v float64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldValue, v))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContainsFold(FieldStatus, v))
}
// UsedByEQ applies the EQ predicate on the "used_by" field.
func UsedByEQ(v int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldUsedBy, v))
}
// UsedByNEQ applies the NEQ predicate on the "used_by" field.
func UsedByNEQ(v int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldUsedBy, v))
}
// UsedByIn applies the In predicate on the "used_by" field.
func UsedByIn(vs ...int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldUsedBy, vs...))
}
// UsedByNotIn applies the NotIn predicate on the "used_by" field.
func UsedByNotIn(vs ...int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldUsedBy, vs...))
}
// UsedByIsNil applies the IsNil predicate on the "used_by" field.
func UsedByIsNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIsNull(FieldUsedBy))
}
// UsedByNotNil applies the NotNil predicate on the "used_by" field.
func UsedByNotNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotNull(FieldUsedBy))
}
// UsedAtEQ applies the EQ predicate on the "used_at" field.
func UsedAtEQ(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldUsedAt, v))
}
// UsedAtNEQ applies the NEQ predicate on the "used_at" field.
func UsedAtNEQ(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldUsedAt, v))
}
// UsedAtIn applies the In predicate on the "used_at" field.
func UsedAtIn(vs ...time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldUsedAt, vs...))
}
// UsedAtNotIn applies the NotIn predicate on the "used_at" field.
func UsedAtNotIn(vs ...time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldUsedAt, vs...))
}
// UsedAtGT applies the GT predicate on the "used_at" field.
func UsedAtGT(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldUsedAt, v))
}
// UsedAtGTE applies the GTE predicate on the "used_at" field.
func UsedAtGTE(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldUsedAt, v))
}
// UsedAtLT applies the LT predicate on the "used_at" field.
func UsedAtLT(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldUsedAt, v))
}
// UsedAtLTE applies the LTE predicate on the "used_at" field.
func UsedAtLTE(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldUsedAt, v))
}
// UsedAtIsNil applies the IsNil predicate on the "used_at" field.
func UsedAtIsNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIsNull(FieldUsedAt))
}
// UsedAtNotNil applies the NotNil predicate on the "used_at" field.
func UsedAtNotNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotNull(FieldUsedAt))
}
// NotesEQ applies the EQ predicate on the "notes" field.
func NotesEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldNotes, v))
}
// NotesNEQ applies the NEQ predicate on the "notes" field.
func NotesNEQ(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldNotes, v))
}
// NotesIn applies the In predicate on the "notes" field.
func NotesIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldNotes, vs...))
}
// NotesNotIn applies the NotIn predicate on the "notes" field.
func NotesNotIn(vs ...string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldNotes, vs...))
}
// NotesGT applies the GT predicate on the "notes" field.
func NotesGT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldNotes, v))
}
// NotesGTE applies the GTE predicate on the "notes" field.
func NotesGTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldNotes, v))
}
// NotesLT applies the LT predicate on the "notes" field.
func NotesLT(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldNotes, v))
}
// NotesLTE applies the LTE predicate on the "notes" field.
func NotesLTE(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldNotes, v))
}
// NotesContains applies the Contains predicate on the "notes" field.
func NotesContains(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContains(FieldNotes, v))
}
// NotesHasPrefix applies the HasPrefix predicate on the "notes" field.
func NotesHasPrefix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasPrefix(FieldNotes, v))
}
// NotesHasSuffix applies the HasSuffix predicate on the "notes" field.
func NotesHasSuffix(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldHasSuffix(FieldNotes, v))
}
// NotesIsNil applies the IsNil predicate on the "notes" field.
func NotesIsNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIsNull(FieldNotes))
}
// NotesNotNil applies the NotNil predicate on the "notes" field.
func NotesNotNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotNull(FieldNotes))
}
// NotesEqualFold applies the EqualFold predicate on the "notes" field.
func NotesEqualFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEqualFold(FieldNotes, v))
}
// NotesContainsFold applies the ContainsFold predicate on the "notes" field.
func NotesContainsFold(v string) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldContainsFold(FieldNotes, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldCreatedAt, v))
}
// GroupIDEQ applies the EQ predicate on the "group_id" field.
func GroupIDEQ(v int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldGroupID, v))
}
// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
func GroupIDNEQ(v int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldGroupID, v))
}
// GroupIDIn applies the In predicate on the "group_id" field.
func GroupIDIn(vs ...int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldGroupID, vs...))
}
// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
func GroupIDNotIn(vs ...int64) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldGroupID, vs...))
}
// GroupIDIsNil applies the IsNil predicate on the "group_id" field.
func GroupIDIsNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIsNull(FieldGroupID))
}
// GroupIDNotNil applies the NotNil predicate on the "group_id" field.
func GroupIDNotNil() predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotNull(FieldGroupID))
}
// ValidityDaysEQ applies the EQ predicate on the "validity_days" field.
func ValidityDaysEQ(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldEQ(FieldValidityDays, v))
}
// ValidityDaysNEQ applies the NEQ predicate on the "validity_days" field.
func ValidityDaysNEQ(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNEQ(FieldValidityDays, v))
}
// ValidityDaysIn applies the In predicate on the "validity_days" field.
func ValidityDaysIn(vs ...int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldIn(FieldValidityDays, vs...))
}
// ValidityDaysNotIn applies the NotIn predicate on the "validity_days" field.
func ValidityDaysNotIn(vs ...int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldNotIn(FieldValidityDays, vs...))
}
// ValidityDaysGT applies the GT predicate on the "validity_days" field.
func ValidityDaysGT(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGT(FieldValidityDays, v))
}
// ValidityDaysGTE applies the GTE predicate on the "validity_days" field.
func ValidityDaysGTE(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldGTE(FieldValidityDays, v))
}
// ValidityDaysLT applies the LT predicate on the "validity_days" field.
func ValidityDaysLT(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLT(FieldValidityDays, v))
}
// ValidityDaysLTE applies the LTE predicate on the "validity_days" field.
func ValidityDaysLTE(v int) predicate.RedeemCode {
return predicate.RedeemCode(sql.FieldLTE(FieldValidityDays, v))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.RedeemCode {
return predicate.RedeemCode(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.RedeemCode {
return predicate.RedeemCode(func(s *sql.Selector) {
step := newUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.RedeemCode {
return predicate.RedeemCode(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.RedeemCode {
return predicate.RedeemCode(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.RedeemCode) predicate.RedeemCode {
return predicate.RedeemCode(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.RedeemCode) predicate.RedeemCode {
return predicate.RedeemCode(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.RedeemCode) predicate.RedeemCode {
return predicate.RedeemCode(sql.NotPredicates(p))
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
// 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/redeemcode"
)
// RedeemCodeDelete is the builder for deleting a RedeemCode entity.
type RedeemCodeDelete struct {
config
hooks []Hook
mutation *RedeemCodeMutation
}
// Where appends a list predicates to the RedeemCodeDelete builder.
func (_d *RedeemCodeDelete) Where(ps ...predicate.RedeemCode) *RedeemCodeDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *RedeemCodeDelete) 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 *RedeemCodeDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *RedeemCodeDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(redeemcode.Table, sqlgraph.NewFieldSpec(redeemcode.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
}
// RedeemCodeDeleteOne is the builder for deleting a single RedeemCode entity.
type RedeemCodeDeleteOne struct {
_d *RedeemCodeDelete
}
// Where appends a list predicates to the RedeemCodeDelete builder.
func (_d *RedeemCodeDeleteOne) Where(ps ...predicate.RedeemCode) *RedeemCodeDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *RedeemCodeDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{redeemcode.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *RedeemCodeDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,687 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// RedeemCodeQuery is the builder for querying RedeemCode entities.
type RedeemCodeQuery struct {
config
ctx *QueryContext
order []redeemcode.OrderOption
inters []Interceptor
predicates []predicate.RedeemCode
withUser *UserQuery
withGroup *GroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the RedeemCodeQuery builder.
func (_q *RedeemCodeQuery) Where(ps ...predicate.RedeemCode) *RedeemCodeQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *RedeemCodeQuery) Limit(limit int) *RedeemCodeQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *RedeemCodeQuery) Offset(offset int) *RedeemCodeQuery {
_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 *RedeemCodeQuery) Unique(unique bool) *RedeemCodeQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *RedeemCodeQuery) Order(o ...redeemcode.OrderOption) *RedeemCodeQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUser chains the current query on the "user" edge.
func (_q *RedeemCodeQuery) QueryUser() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(redeemcode.Table, redeemcode.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, redeemcode.UserTable, redeemcode.UserColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryGroup chains the current query on the "group" edge.
func (_q *RedeemCodeQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(redeemcode.Table, redeemcode.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, redeemcode.GroupTable, redeemcode.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first RedeemCode entity from the query.
// Returns a *NotFoundError when no RedeemCode was found.
func (_q *RedeemCodeQuery) First(ctx context.Context) (*RedeemCode, 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{redeemcode.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *RedeemCodeQuery) FirstX(ctx context.Context) *RedeemCode {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first RedeemCode ID from the query.
// Returns a *NotFoundError when no RedeemCode ID was found.
func (_q *RedeemCodeQuery) 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{redeemcode.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *RedeemCodeQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single RedeemCode entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one RedeemCode entity is found.
// Returns a *NotFoundError when no RedeemCode entities are found.
func (_q *RedeemCodeQuery) Only(ctx context.Context) (*RedeemCode, 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{redeemcode.Label}
default:
return nil, &NotSingularError{redeemcode.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *RedeemCodeQuery) OnlyX(ctx context.Context) *RedeemCode {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only RedeemCode ID in the query.
// Returns a *NotSingularError when more than one RedeemCode ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *RedeemCodeQuery) 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{redeemcode.Label}
default:
err = &NotSingularError{redeemcode.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *RedeemCodeQuery) 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 RedeemCodes.
func (_q *RedeemCodeQuery) All(ctx context.Context) ([]*RedeemCode, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*RedeemCode, *RedeemCodeQuery]()
return withInterceptors[[]*RedeemCode](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *RedeemCodeQuery) AllX(ctx context.Context) []*RedeemCode {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of RedeemCode IDs.
func (_q *RedeemCodeQuery) 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(redeemcode.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *RedeemCodeQuery) 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 *RedeemCodeQuery) 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[*RedeemCodeQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *RedeemCodeQuery) 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 *RedeemCodeQuery) 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 *RedeemCodeQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the RedeemCodeQuery 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 *RedeemCodeQuery) Clone() *RedeemCodeQuery {
if _q == nil {
return nil
}
return &RedeemCodeQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]redeemcode.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.RedeemCode{}, _q.predicates...),
withUser: _q.withUser.Clone(),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *RedeemCodeQuery) WithUser(opts ...func(*UserQuery)) *RedeemCodeQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUser = query
return _q
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *RedeemCodeQuery) WithGroup(opts ...func(*GroupQuery)) *RedeemCodeQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = query
return _q
}
// 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 {
// Code string `json:"code,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.RedeemCode.Query().
// GroupBy(redeemcode.FieldCode).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *RedeemCodeQuery) GroupBy(field string, fields ...string) *RedeemCodeGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &RedeemCodeGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = redeemcode.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 {
// Code string `json:"code,omitempty"`
// }
//
// client.RedeemCode.Query().
// Select(redeemcode.FieldCode).
// Scan(ctx, &v)
func (_q *RedeemCodeQuery) Select(fields ...string) *RedeemCodeSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &RedeemCodeSelect{RedeemCodeQuery: _q}
sbuild.label = redeemcode.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a RedeemCodeSelect configured with the given aggregations.
func (_q *RedeemCodeQuery) Aggregate(fns ...AggregateFunc) *RedeemCodeSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *RedeemCodeQuery) 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 !redeemcode.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 *RedeemCodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RedeemCode, error) {
var (
nodes = []*RedeemCode{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withUser != nil,
_q.withGroup != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*RedeemCode).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &RedeemCode{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUser; query != nil {
if err := _q.loadUser(ctx, query, nodes, nil,
func(n *RedeemCode, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
if query := _q.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes, nil,
func(n *RedeemCode, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *RedeemCodeQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*RedeemCode, init func(*RedeemCode), assign func(*RedeemCode, *User)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*RedeemCode)
for i := range nodes {
if nodes[i].UsedBy == nil {
continue
}
fk := *nodes[i].UsedBy
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "used_by" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *RedeemCodeQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*RedeemCode, init func(*RedeemCode), assign func(*RedeemCode, *Group)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*RedeemCode)
for i := range nodes {
if nodes[i].GroupID == nil {
continue
}
fk := *nodes[i].GroupID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *RedeemCodeQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *RedeemCodeQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(redeemcode.Table, redeemcode.Columns, sqlgraph.NewFieldSpec(redeemcode.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, redeemcode.FieldID)
for i := range fields {
if fields[i] != redeemcode.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withUser != nil {
_spec.Node.AddColumnOnce(redeemcode.FieldUsedBy)
}
if _q.withGroup != nil {
_spec.Node.AddColumnOnce(redeemcode.FieldGroupID)
}
}
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 *RedeemCodeQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(redeemcode.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = redeemcode.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// RedeemCodeGroupBy is the group-by builder for RedeemCode entities.
type RedeemCodeGroupBy struct {
selector
build *RedeemCodeQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *RedeemCodeGroupBy) Aggregate(fns ...AggregateFunc) *RedeemCodeGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *RedeemCodeGroupBy) 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[*RedeemCodeQuery, *RedeemCodeGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *RedeemCodeGroupBy) sqlScan(ctx context.Context, root *RedeemCodeQuery, 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)
}
// RedeemCodeSelect is the builder for selecting fields of RedeemCode entities.
type RedeemCodeSelect struct {
*RedeemCodeQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *RedeemCodeSelect) Aggregate(fns ...AggregateFunc) *RedeemCodeSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *RedeemCodeSelect) 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[*RedeemCodeQuery, *RedeemCodeSelect](ctx, _s.RedeemCodeQuery, _s, _s.inters, v)
}
func (_s *RedeemCodeSelect) sqlScan(ctx context.Context, root *RedeemCodeQuery, 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)
}

View File

@@ -0,0 +1,806 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/user"
)
// RedeemCodeUpdate is the builder for updating RedeemCode entities.
type RedeemCodeUpdate struct {
config
hooks []Hook
mutation *RedeemCodeMutation
}
// Where appends a list predicates to the RedeemCodeUpdate builder.
func (_u *RedeemCodeUpdate) Where(ps ...predicate.RedeemCode) *RedeemCodeUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetCode sets the "code" field.
func (_u *RedeemCodeUpdate) SetCode(v string) *RedeemCodeUpdate {
_u.mutation.SetCode(v)
return _u
}
// SetNillableCode sets the "code" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableCode(v *string) *RedeemCodeUpdate {
if v != nil {
_u.SetCode(*v)
}
return _u
}
// SetType sets the "type" field.
func (_u *RedeemCodeUpdate) SetType(v string) *RedeemCodeUpdate {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableType(v *string) *RedeemCodeUpdate {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *RedeemCodeUpdate) SetValue(v float64) *RedeemCodeUpdate {
_u.mutation.ResetValue()
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableValue(v *float64) *RedeemCodeUpdate {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// AddValue adds value to the "value" field.
func (_u *RedeemCodeUpdate) AddValue(v float64) *RedeemCodeUpdate {
_u.mutation.AddValue(v)
return _u
}
// SetStatus sets the "status" field.
func (_u *RedeemCodeUpdate) SetStatus(v string) *RedeemCodeUpdate {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableStatus(v *string) *RedeemCodeUpdate {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// SetUsedBy sets the "used_by" field.
func (_u *RedeemCodeUpdate) SetUsedBy(v int64) *RedeemCodeUpdate {
_u.mutation.SetUsedBy(v)
return _u
}
// SetNillableUsedBy sets the "used_by" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableUsedBy(v *int64) *RedeemCodeUpdate {
if v != nil {
_u.SetUsedBy(*v)
}
return _u
}
// ClearUsedBy clears the value of the "used_by" field.
func (_u *RedeemCodeUpdate) ClearUsedBy() *RedeemCodeUpdate {
_u.mutation.ClearUsedBy()
return _u
}
// SetUsedAt sets the "used_at" field.
func (_u *RedeemCodeUpdate) SetUsedAt(v time.Time) *RedeemCodeUpdate {
_u.mutation.SetUsedAt(v)
return _u
}
// SetNillableUsedAt sets the "used_at" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableUsedAt(v *time.Time) *RedeemCodeUpdate {
if v != nil {
_u.SetUsedAt(*v)
}
return _u
}
// ClearUsedAt clears the value of the "used_at" field.
func (_u *RedeemCodeUpdate) ClearUsedAt() *RedeemCodeUpdate {
_u.mutation.ClearUsedAt()
return _u
}
// SetNotes sets the "notes" field.
func (_u *RedeemCodeUpdate) SetNotes(v string) *RedeemCodeUpdate {
_u.mutation.SetNotes(v)
return _u
}
// SetNillableNotes sets the "notes" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableNotes(v *string) *RedeemCodeUpdate {
if v != nil {
_u.SetNotes(*v)
}
return _u
}
// ClearNotes clears the value of the "notes" field.
func (_u *RedeemCodeUpdate) ClearNotes() *RedeemCodeUpdate {
_u.mutation.ClearNotes()
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *RedeemCodeUpdate) SetGroupID(v int64) *RedeemCodeUpdate {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableGroupID(v *int64) *RedeemCodeUpdate {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// ClearGroupID clears the value of the "group_id" field.
func (_u *RedeemCodeUpdate) ClearGroupID() *RedeemCodeUpdate {
_u.mutation.ClearGroupID()
return _u
}
// SetValidityDays sets the "validity_days" field.
func (_u *RedeemCodeUpdate) SetValidityDays(v int) *RedeemCodeUpdate {
_u.mutation.ResetValidityDays()
_u.mutation.SetValidityDays(v)
return _u
}
// SetNillableValidityDays sets the "validity_days" field if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableValidityDays(v *int) *RedeemCodeUpdate {
if v != nil {
_u.SetValidityDays(*v)
}
return _u
}
// AddValidityDays adds value to the "validity_days" field.
func (_u *RedeemCodeUpdate) AddValidityDays(v int) *RedeemCodeUpdate {
_u.mutation.AddValidityDays(v)
return _u
}
// SetUserID sets the "user" edge to the User entity by ID.
func (_u *RedeemCodeUpdate) SetUserID(id int64) *RedeemCodeUpdate {
_u.mutation.SetUserID(id)
return _u
}
// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (_u *RedeemCodeUpdate) SetNillableUserID(id *int64) *RedeemCodeUpdate {
if id != nil {
_u = _u.SetUserID(*id)
}
return _u
}
// SetUser sets the "user" edge to the User entity.
func (_u *RedeemCodeUpdate) SetUser(v *User) *RedeemCodeUpdate {
return _u.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *RedeemCodeUpdate) SetGroup(v *Group) *RedeemCodeUpdate {
return _u.SetGroupID(v.ID)
}
// Mutation returns the RedeemCodeMutation object of the builder.
func (_u *RedeemCodeUpdate) Mutation() *RedeemCodeMutation {
return _u.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (_u *RedeemCodeUpdate) ClearUser() *RedeemCodeUpdate {
_u.mutation.ClearUser()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *RedeemCodeUpdate) ClearGroup() *RedeemCodeUpdate {
_u.mutation.ClearGroup()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *RedeemCodeUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *RedeemCodeUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *RedeemCodeUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *RedeemCodeUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *RedeemCodeUpdate) check() error {
if v, ok := _u.mutation.Code(); ok {
if err := redeemcode.CodeValidator(v); err != nil {
return &ValidationError{Name: "code", err: fmt.Errorf(`ent: validator failed for field "RedeemCode.code": %w`, err)}
}
}
if v, ok := _u.mutation.GetType(); ok {
if err := redeemcode.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "RedeemCode.type": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := redeemcode.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "RedeemCode.status": %w`, err)}
}
}
return nil
}
func (_u *RedeemCodeUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(redeemcode.Table, redeemcode.Columns, sqlgraph.NewFieldSpec(redeemcode.FieldID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Code(); ok {
_spec.SetField(redeemcode.FieldCode, field.TypeString, value)
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(redeemcode.FieldType, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(redeemcode.FieldValue, field.TypeFloat64, value)
}
if value, ok := _u.mutation.AddedValue(); ok {
_spec.AddField(redeemcode.FieldValue, field.TypeFloat64, value)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(redeemcode.FieldStatus, field.TypeString, value)
}
if value, ok := _u.mutation.UsedAt(); ok {
_spec.SetField(redeemcode.FieldUsedAt, field.TypeTime, value)
}
if _u.mutation.UsedAtCleared() {
_spec.ClearField(redeemcode.FieldUsedAt, field.TypeTime)
}
if value, ok := _u.mutation.Notes(); ok {
_spec.SetField(redeemcode.FieldNotes, field.TypeString, value)
}
if _u.mutation.NotesCleared() {
_spec.ClearField(redeemcode.FieldNotes, field.TypeString)
}
if value, ok := _u.mutation.ValidityDays(); ok {
_spec.SetField(redeemcode.FieldValidityDays, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedValidityDays(); ok {
_spec.AddField(redeemcode.FieldValidityDays, field.TypeInt, value)
}
if _u.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.UserTable,
Columns: []string{redeemcode.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.UserTable,
Columns: []string{redeemcode.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.GroupTable,
Columns: []string{redeemcode.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.GroupTable,
Columns: []string{redeemcode.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{redeemcode.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// RedeemCodeUpdateOne is the builder for updating a single RedeemCode entity.
type RedeemCodeUpdateOne struct {
config
fields []string
hooks []Hook
mutation *RedeemCodeMutation
}
// SetCode sets the "code" field.
func (_u *RedeemCodeUpdateOne) SetCode(v string) *RedeemCodeUpdateOne {
_u.mutation.SetCode(v)
return _u
}
// SetNillableCode sets the "code" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableCode(v *string) *RedeemCodeUpdateOne {
if v != nil {
_u.SetCode(*v)
}
return _u
}
// SetType sets the "type" field.
func (_u *RedeemCodeUpdateOne) SetType(v string) *RedeemCodeUpdateOne {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableType(v *string) *RedeemCodeUpdateOne {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *RedeemCodeUpdateOne) SetValue(v float64) *RedeemCodeUpdateOne {
_u.mutation.ResetValue()
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableValue(v *float64) *RedeemCodeUpdateOne {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// AddValue adds value to the "value" field.
func (_u *RedeemCodeUpdateOne) AddValue(v float64) *RedeemCodeUpdateOne {
_u.mutation.AddValue(v)
return _u
}
// SetStatus sets the "status" field.
func (_u *RedeemCodeUpdateOne) SetStatus(v string) *RedeemCodeUpdateOne {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableStatus(v *string) *RedeemCodeUpdateOne {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// SetUsedBy sets the "used_by" field.
func (_u *RedeemCodeUpdateOne) SetUsedBy(v int64) *RedeemCodeUpdateOne {
_u.mutation.SetUsedBy(v)
return _u
}
// SetNillableUsedBy sets the "used_by" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableUsedBy(v *int64) *RedeemCodeUpdateOne {
if v != nil {
_u.SetUsedBy(*v)
}
return _u
}
// ClearUsedBy clears the value of the "used_by" field.
func (_u *RedeemCodeUpdateOne) ClearUsedBy() *RedeemCodeUpdateOne {
_u.mutation.ClearUsedBy()
return _u
}
// SetUsedAt sets the "used_at" field.
func (_u *RedeemCodeUpdateOne) SetUsedAt(v time.Time) *RedeemCodeUpdateOne {
_u.mutation.SetUsedAt(v)
return _u
}
// SetNillableUsedAt sets the "used_at" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableUsedAt(v *time.Time) *RedeemCodeUpdateOne {
if v != nil {
_u.SetUsedAt(*v)
}
return _u
}
// ClearUsedAt clears the value of the "used_at" field.
func (_u *RedeemCodeUpdateOne) ClearUsedAt() *RedeemCodeUpdateOne {
_u.mutation.ClearUsedAt()
return _u
}
// SetNotes sets the "notes" field.
func (_u *RedeemCodeUpdateOne) SetNotes(v string) *RedeemCodeUpdateOne {
_u.mutation.SetNotes(v)
return _u
}
// SetNillableNotes sets the "notes" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableNotes(v *string) *RedeemCodeUpdateOne {
if v != nil {
_u.SetNotes(*v)
}
return _u
}
// ClearNotes clears the value of the "notes" field.
func (_u *RedeemCodeUpdateOne) ClearNotes() *RedeemCodeUpdateOne {
_u.mutation.ClearNotes()
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *RedeemCodeUpdateOne) SetGroupID(v int64) *RedeemCodeUpdateOne {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableGroupID(v *int64) *RedeemCodeUpdateOne {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// ClearGroupID clears the value of the "group_id" field.
func (_u *RedeemCodeUpdateOne) ClearGroupID() *RedeemCodeUpdateOne {
_u.mutation.ClearGroupID()
return _u
}
// SetValidityDays sets the "validity_days" field.
func (_u *RedeemCodeUpdateOne) SetValidityDays(v int) *RedeemCodeUpdateOne {
_u.mutation.ResetValidityDays()
_u.mutation.SetValidityDays(v)
return _u
}
// SetNillableValidityDays sets the "validity_days" field if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableValidityDays(v *int) *RedeemCodeUpdateOne {
if v != nil {
_u.SetValidityDays(*v)
}
return _u
}
// AddValidityDays adds value to the "validity_days" field.
func (_u *RedeemCodeUpdateOne) AddValidityDays(v int) *RedeemCodeUpdateOne {
_u.mutation.AddValidityDays(v)
return _u
}
// SetUserID sets the "user" edge to the User entity by ID.
func (_u *RedeemCodeUpdateOne) SetUserID(id int64) *RedeemCodeUpdateOne {
_u.mutation.SetUserID(id)
return _u
}
// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (_u *RedeemCodeUpdateOne) SetNillableUserID(id *int64) *RedeemCodeUpdateOne {
if id != nil {
_u = _u.SetUserID(*id)
}
return _u
}
// SetUser sets the "user" edge to the User entity.
func (_u *RedeemCodeUpdateOne) SetUser(v *User) *RedeemCodeUpdateOne {
return _u.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *RedeemCodeUpdateOne) SetGroup(v *Group) *RedeemCodeUpdateOne {
return _u.SetGroupID(v.ID)
}
// Mutation returns the RedeemCodeMutation object of the builder.
func (_u *RedeemCodeUpdateOne) Mutation() *RedeemCodeMutation {
return _u.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (_u *RedeemCodeUpdateOne) ClearUser() *RedeemCodeUpdateOne {
_u.mutation.ClearUser()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *RedeemCodeUpdateOne) ClearGroup() *RedeemCodeUpdateOne {
_u.mutation.ClearGroup()
return _u
}
// Where appends a list predicates to the RedeemCodeUpdate builder.
func (_u *RedeemCodeUpdateOne) Where(ps ...predicate.RedeemCode) *RedeemCodeUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *RedeemCodeUpdateOne) Select(field string, fields ...string) *RedeemCodeUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated RedeemCode entity.
func (_u *RedeemCodeUpdateOne) Save(ctx context.Context) (*RedeemCode, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *RedeemCodeUpdateOne) SaveX(ctx context.Context) *RedeemCode {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *RedeemCodeUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *RedeemCodeUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *RedeemCodeUpdateOne) check() error {
if v, ok := _u.mutation.Code(); ok {
if err := redeemcode.CodeValidator(v); err != nil {
return &ValidationError{Name: "code", err: fmt.Errorf(`ent: validator failed for field "RedeemCode.code": %w`, err)}
}
}
if v, ok := _u.mutation.GetType(); ok {
if err := redeemcode.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "RedeemCode.type": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := redeemcode.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "RedeemCode.status": %w`, err)}
}
}
return nil
}
func (_u *RedeemCodeUpdateOne) sqlSave(ctx context.Context) (_node *RedeemCode, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(redeemcode.Table, redeemcode.Columns, sqlgraph.NewFieldSpec(redeemcode.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "RedeemCode.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, redeemcode.FieldID)
for _, f := range fields {
if !redeemcode.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != redeemcode.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Code(); ok {
_spec.SetField(redeemcode.FieldCode, field.TypeString, value)
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(redeemcode.FieldType, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(redeemcode.FieldValue, field.TypeFloat64, value)
}
if value, ok := _u.mutation.AddedValue(); ok {
_spec.AddField(redeemcode.FieldValue, field.TypeFloat64, value)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(redeemcode.FieldStatus, field.TypeString, value)
}
if value, ok := _u.mutation.UsedAt(); ok {
_spec.SetField(redeemcode.FieldUsedAt, field.TypeTime, value)
}
if _u.mutation.UsedAtCleared() {
_spec.ClearField(redeemcode.FieldUsedAt, field.TypeTime)
}
if value, ok := _u.mutation.Notes(); ok {
_spec.SetField(redeemcode.FieldNotes, field.TypeString, value)
}
if _u.mutation.NotesCleared() {
_spec.ClearField(redeemcode.FieldNotes, field.TypeString)
}
if value, ok := _u.mutation.ValidityDays(); ok {
_spec.SetField(redeemcode.FieldValidityDays, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedValidityDays(); ok {
_spec.AddField(redeemcode.FieldValidityDays, field.TypeInt, value)
}
if _u.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.UserTable,
Columns: []string{redeemcode.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.UserTable,
Columns: []string{redeemcode.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.GroupTable,
Columns: []string{redeemcode.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: redeemcode.GroupTable,
Columns: []string{redeemcode.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &RedeemCode{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{redeemcode.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

5
backend/ent/runtime.go Normal file
View File

@@ -0,0 +1,5 @@
// Code generated by ent, DO NOT EDIT.
package ent
// The schema-stitching logic is generated in github.com/Wei-Shaw/sub2api/ent/runtime/runtime.go

View File

@@ -0,0 +1,562 @@
// Code generated by ent, DO NOT EDIT.
package runtime
import (
"time"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/schema"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
accountMixin := schema.Account{}.Mixin()
accountMixinHooks1 := accountMixin[1].Hooks()
account.Hooks[0] = accountMixinHooks1[0]
accountMixinInters1 := accountMixin[1].Interceptors()
account.Interceptors[0] = accountMixinInters1[0]
accountMixinFields0 := accountMixin[0].Fields()
_ = accountMixinFields0
accountFields := schema.Account{}.Fields()
_ = accountFields
// accountDescCreatedAt is the schema descriptor for created_at field.
accountDescCreatedAt := accountMixinFields0[0].Descriptor()
// account.DefaultCreatedAt holds the default value on creation for the created_at field.
account.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)
// accountDescUpdatedAt is the schema descriptor for updated_at field.
accountDescUpdatedAt := accountMixinFields0[1].Descriptor()
// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.
account.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)
// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
account.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)
// accountDescName is the schema descriptor for name field.
accountDescName := accountFields[0].Descriptor()
// account.NameValidator is a validator for the "name" field. It is called by the builders before save.
account.NameValidator = func() func(string) error {
validators := accountDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// accountDescPlatform is the schema descriptor for platform field.
accountDescPlatform := accountFields[1].Descriptor()
// account.PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
account.PlatformValidator = func() func(string) error {
validators := accountDescPlatform.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(platform string) error {
for _, fn := range fns {
if err := fn(platform); err != nil {
return err
}
}
return nil
}
}()
// accountDescType is the schema descriptor for type field.
accountDescType := accountFields[2].Descriptor()
// account.TypeValidator is a validator for the "type" field. It is called by the builders before save.
account.TypeValidator = func() func(string) error {
validators := accountDescType.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(_type string) error {
for _, fn := range fns {
if err := fn(_type); err != nil {
return err
}
}
return nil
}
}()
// accountDescCredentials is the schema descriptor for credentials field.
accountDescCredentials := accountFields[3].Descriptor()
// account.DefaultCredentials holds the default value on creation for the credentials field.
account.DefaultCredentials = accountDescCredentials.Default.(func() map[string]interface{})
// accountDescExtra is the schema descriptor for extra field.
accountDescExtra := accountFields[4].Descriptor()
// account.DefaultExtra holds the default value on creation for the extra field.
account.DefaultExtra = accountDescExtra.Default.(func() map[string]interface{})
// accountDescConcurrency is the schema descriptor for concurrency field.
accountDescConcurrency := accountFields[6].Descriptor()
// account.DefaultConcurrency holds the default value on creation for the concurrency field.
account.DefaultConcurrency = accountDescConcurrency.Default.(int)
// accountDescPriority is the schema descriptor for priority field.
accountDescPriority := accountFields[7].Descriptor()
// account.DefaultPriority holds the default value on creation for the priority field.
account.DefaultPriority = accountDescPriority.Default.(int)
// accountDescStatus is the schema descriptor for status field.
accountDescStatus := accountFields[8].Descriptor()
// account.DefaultStatus holds the default value on creation for the status field.
account.DefaultStatus = accountDescStatus.Default.(string)
// account.StatusValidator is a validator for the "status" field. It is called by the builders before save.
account.StatusValidator = accountDescStatus.Validators[0].(func(string) error)
// accountDescSchedulable is the schema descriptor for schedulable field.
accountDescSchedulable := accountFields[11].Descriptor()
// account.DefaultSchedulable holds the default value on creation for the schedulable field.
account.DefaultSchedulable = accountDescSchedulable.Default.(bool)
// accountDescSessionWindowStatus is the schema descriptor for session_window_status field.
accountDescSessionWindowStatus := accountFields[17].Descriptor()
// account.SessionWindowStatusValidator is a validator for the "session_window_status" field. It is called by the builders before save.
account.SessionWindowStatusValidator = accountDescSessionWindowStatus.Validators[0].(func(string) error)
accountgroupFields := schema.AccountGroup{}.Fields()
_ = accountgroupFields
// accountgroupDescPriority is the schema descriptor for priority field.
accountgroupDescPriority := accountgroupFields[2].Descriptor()
// accountgroup.DefaultPriority holds the default value on creation for the priority field.
accountgroup.DefaultPriority = accountgroupDescPriority.Default.(int)
// accountgroupDescCreatedAt is the schema descriptor for created_at field.
accountgroupDescCreatedAt := accountgroupFields[3].Descriptor()
// accountgroup.DefaultCreatedAt holds the default value on creation for the created_at field.
accountgroup.DefaultCreatedAt = accountgroupDescCreatedAt.Default.(func() time.Time)
apikeyMixin := schema.ApiKey{}.Mixin()
apikeyMixinHooks1 := apikeyMixin[1].Hooks()
apikey.Hooks[0] = apikeyMixinHooks1[0]
apikeyMixinInters1 := apikeyMixin[1].Interceptors()
apikey.Interceptors[0] = apikeyMixinInters1[0]
apikeyMixinFields0 := apikeyMixin[0].Fields()
_ = apikeyMixinFields0
apikeyFields := schema.ApiKey{}.Fields()
_ = apikeyFields
// apikeyDescCreatedAt is the schema descriptor for created_at field.
apikeyDescCreatedAt := apikeyMixinFields0[0].Descriptor()
// apikey.DefaultCreatedAt holds the default value on creation for the created_at field.
apikey.DefaultCreatedAt = apikeyDescCreatedAt.Default.(func() time.Time)
// apikeyDescUpdatedAt is the schema descriptor for updated_at field.
apikeyDescUpdatedAt := apikeyMixinFields0[1].Descriptor()
// apikey.DefaultUpdatedAt holds the default value on creation for the updated_at field.
apikey.DefaultUpdatedAt = apikeyDescUpdatedAt.Default.(func() time.Time)
// apikey.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
apikey.UpdateDefaultUpdatedAt = apikeyDescUpdatedAt.UpdateDefault.(func() time.Time)
// apikeyDescKey is the schema descriptor for key field.
apikeyDescKey := apikeyFields[1].Descriptor()
// apikey.KeyValidator is a validator for the "key" field. It is called by the builders before save.
apikey.KeyValidator = func() func(string) error {
validators := apikeyDescKey.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(key string) error {
for _, fn := range fns {
if err := fn(key); err != nil {
return err
}
}
return nil
}
}()
// apikeyDescName is the schema descriptor for name field.
apikeyDescName := apikeyFields[2].Descriptor()
// apikey.NameValidator is a validator for the "name" field. It is called by the builders before save.
apikey.NameValidator = func() func(string) error {
validators := apikeyDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// apikeyDescStatus is the schema descriptor for status field.
apikeyDescStatus := apikeyFields[4].Descriptor()
// apikey.DefaultStatus holds the default value on creation for the status field.
apikey.DefaultStatus = apikeyDescStatus.Default.(string)
// apikey.StatusValidator is a validator for the "status" field. It is called by the builders before save.
apikey.StatusValidator = apikeyDescStatus.Validators[0].(func(string) error)
groupMixin := schema.Group{}.Mixin()
groupMixinHooks1 := groupMixin[1].Hooks()
group.Hooks[0] = groupMixinHooks1[0]
groupMixinInters1 := groupMixin[1].Interceptors()
group.Interceptors[0] = groupMixinInters1[0]
groupMixinFields0 := groupMixin[0].Fields()
_ = groupMixinFields0
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescCreatedAt is the schema descriptor for created_at field.
groupDescCreatedAt := groupMixinFields0[0].Descriptor()
// group.DefaultCreatedAt holds the default value on creation for the created_at field.
group.DefaultCreatedAt = groupDescCreatedAt.Default.(func() time.Time)
// groupDescUpdatedAt is the schema descriptor for updated_at field.
groupDescUpdatedAt := groupMixinFields0[1].Descriptor()
// group.DefaultUpdatedAt holds the default value on creation for the updated_at field.
group.DefaultUpdatedAt = groupDescUpdatedAt.Default.(func() time.Time)
// group.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
group.UpdateDefaultUpdatedAt = groupDescUpdatedAt.UpdateDefault.(func() time.Time)
// groupDescName is the schema descriptor for name field.
groupDescName := groupFields[0].Descriptor()
// group.NameValidator is a validator for the "name" field. It is called by the builders before save.
group.NameValidator = func() func(string) error {
validators := groupDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// groupDescRateMultiplier is the schema descriptor for rate_multiplier field.
groupDescRateMultiplier := groupFields[2].Descriptor()
// group.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
group.DefaultRateMultiplier = groupDescRateMultiplier.Default.(float64)
// groupDescIsExclusive is the schema descriptor for is_exclusive field.
groupDescIsExclusive := groupFields[3].Descriptor()
// group.DefaultIsExclusive holds the default value on creation for the is_exclusive field.
group.DefaultIsExclusive = groupDescIsExclusive.Default.(bool)
// groupDescStatus is the schema descriptor for status field.
groupDescStatus := groupFields[4].Descriptor()
// group.DefaultStatus holds the default value on creation for the status field.
group.DefaultStatus = groupDescStatus.Default.(string)
// group.StatusValidator is a validator for the "status" field. It is called by the builders before save.
group.StatusValidator = groupDescStatus.Validators[0].(func(string) error)
// groupDescPlatform is the schema descriptor for platform field.
groupDescPlatform := groupFields[5].Descriptor()
// group.DefaultPlatform holds the default value on creation for the platform field.
group.DefaultPlatform = groupDescPlatform.Default.(string)
// group.PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
group.PlatformValidator = groupDescPlatform.Validators[0].(func(string) error)
// groupDescSubscriptionType is the schema descriptor for subscription_type field.
groupDescSubscriptionType := groupFields[6].Descriptor()
// group.DefaultSubscriptionType holds the default value on creation for the subscription_type field.
group.DefaultSubscriptionType = groupDescSubscriptionType.Default.(string)
// group.SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save.
group.SubscriptionTypeValidator = groupDescSubscriptionType.Validators[0].(func(string) error)
proxyMixin := schema.Proxy{}.Mixin()
proxyMixinHooks1 := proxyMixin[1].Hooks()
proxy.Hooks[0] = proxyMixinHooks1[0]
proxyMixinInters1 := proxyMixin[1].Interceptors()
proxy.Interceptors[0] = proxyMixinInters1[0]
proxyMixinFields0 := proxyMixin[0].Fields()
_ = proxyMixinFields0
proxyFields := schema.Proxy{}.Fields()
_ = proxyFields
// proxyDescCreatedAt is the schema descriptor for created_at field.
proxyDescCreatedAt := proxyMixinFields0[0].Descriptor()
// proxy.DefaultCreatedAt holds the default value on creation for the created_at field.
proxy.DefaultCreatedAt = proxyDescCreatedAt.Default.(func() time.Time)
// proxyDescUpdatedAt is the schema descriptor for updated_at field.
proxyDescUpdatedAt := proxyMixinFields0[1].Descriptor()
// proxy.DefaultUpdatedAt holds the default value on creation for the updated_at field.
proxy.DefaultUpdatedAt = proxyDescUpdatedAt.Default.(func() time.Time)
// proxy.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
proxy.UpdateDefaultUpdatedAt = proxyDescUpdatedAt.UpdateDefault.(func() time.Time)
// proxyDescName is the schema descriptor for name field.
proxyDescName := proxyFields[0].Descriptor()
// proxy.NameValidator is a validator for the "name" field. It is called by the builders before save.
proxy.NameValidator = func() func(string) error {
validators := proxyDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// proxyDescProtocol is the schema descriptor for protocol field.
proxyDescProtocol := proxyFields[1].Descriptor()
// proxy.ProtocolValidator is a validator for the "protocol" field. It is called by the builders before save.
proxy.ProtocolValidator = func() func(string) error {
validators := proxyDescProtocol.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(protocol string) error {
for _, fn := range fns {
if err := fn(protocol); err != nil {
return err
}
}
return nil
}
}()
// proxyDescHost is the schema descriptor for host field.
proxyDescHost := proxyFields[2].Descriptor()
// proxy.HostValidator is a validator for the "host" field. It is called by the builders before save.
proxy.HostValidator = func() func(string) error {
validators := proxyDescHost.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(host string) error {
for _, fn := range fns {
if err := fn(host); err != nil {
return err
}
}
return nil
}
}()
// proxyDescUsername is the schema descriptor for username field.
proxyDescUsername := proxyFields[4].Descriptor()
// proxy.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
proxy.UsernameValidator = proxyDescUsername.Validators[0].(func(string) error)
// proxyDescPassword is the schema descriptor for password field.
proxyDescPassword := proxyFields[5].Descriptor()
// proxy.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
proxy.PasswordValidator = proxyDescPassword.Validators[0].(func(string) error)
// proxyDescStatus is the schema descriptor for status field.
proxyDescStatus := proxyFields[6].Descriptor()
// proxy.DefaultStatus holds the default value on creation for the status field.
proxy.DefaultStatus = proxyDescStatus.Default.(string)
// proxy.StatusValidator is a validator for the "status" field. It is called by the builders before save.
proxy.StatusValidator = proxyDescStatus.Validators[0].(func(string) error)
redeemcodeFields := schema.RedeemCode{}.Fields()
_ = redeemcodeFields
// redeemcodeDescCode is the schema descriptor for code field.
redeemcodeDescCode := redeemcodeFields[0].Descriptor()
// redeemcode.CodeValidator is a validator for the "code" field. It is called by the builders before save.
redeemcode.CodeValidator = func() func(string) error {
validators := redeemcodeDescCode.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(code string) error {
for _, fn := range fns {
if err := fn(code); err != nil {
return err
}
}
return nil
}
}()
// redeemcodeDescType is the schema descriptor for type field.
redeemcodeDescType := redeemcodeFields[1].Descriptor()
// redeemcode.DefaultType holds the default value on creation for the type field.
redeemcode.DefaultType = redeemcodeDescType.Default.(string)
// redeemcode.TypeValidator is a validator for the "type" field. It is called by the builders before save.
redeemcode.TypeValidator = redeemcodeDescType.Validators[0].(func(string) error)
// redeemcodeDescValue is the schema descriptor for value field.
redeemcodeDescValue := redeemcodeFields[2].Descriptor()
// redeemcode.DefaultValue holds the default value on creation for the value field.
redeemcode.DefaultValue = redeemcodeDescValue.Default.(float64)
// redeemcodeDescStatus is the schema descriptor for status field.
redeemcodeDescStatus := redeemcodeFields[3].Descriptor()
// redeemcode.DefaultStatus holds the default value on creation for the status field.
redeemcode.DefaultStatus = redeemcodeDescStatus.Default.(string)
// redeemcode.StatusValidator is a validator for the "status" field. It is called by the builders before save.
redeemcode.StatusValidator = redeemcodeDescStatus.Validators[0].(func(string) error)
// redeemcodeDescCreatedAt is the schema descriptor for created_at field.
redeemcodeDescCreatedAt := redeemcodeFields[7].Descriptor()
// redeemcode.DefaultCreatedAt holds the default value on creation for the created_at field.
redeemcode.DefaultCreatedAt = redeemcodeDescCreatedAt.Default.(func() time.Time)
// redeemcodeDescValidityDays is the schema descriptor for validity_days field.
redeemcodeDescValidityDays := redeemcodeFields[9].Descriptor()
// redeemcode.DefaultValidityDays holds the default value on creation for the validity_days field.
redeemcode.DefaultValidityDays = redeemcodeDescValidityDays.Default.(int)
settingFields := schema.Setting{}.Fields()
_ = settingFields
// settingDescKey is the schema descriptor for key field.
settingDescKey := settingFields[0].Descriptor()
// setting.KeyValidator is a validator for the "key" field. It is called by the builders before save.
setting.KeyValidator = func() func(string) error {
validators := settingDescKey.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(key string) error {
for _, fn := range fns {
if err := fn(key); err != nil {
return err
}
}
return nil
}
}()
// settingDescValue is the schema descriptor for value field.
settingDescValue := settingFields[1].Descriptor()
// setting.ValueValidator is a validator for the "value" field. It is called by the builders before save.
setting.ValueValidator = settingDescValue.Validators[0].(func(string) error)
// settingDescUpdatedAt is the schema descriptor for updated_at field.
settingDescUpdatedAt := settingFields[2].Descriptor()
// setting.DefaultUpdatedAt holds the default value on creation for the updated_at field.
setting.DefaultUpdatedAt = settingDescUpdatedAt.Default.(func() time.Time)
// setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
setting.UpdateDefaultUpdatedAt = settingDescUpdatedAt.UpdateDefault.(func() time.Time)
userMixin := schema.User{}.Mixin()
userMixinHooks1 := userMixin[1].Hooks()
user.Hooks[0] = userMixinHooks1[0]
userMixinInters1 := userMixin[1].Interceptors()
user.Interceptors[0] = userMixinInters1[0]
userMixinFields0 := userMixin[0].Fields()
_ = userMixinFields0
userFields := schema.User{}.Fields()
_ = userFields
// userDescCreatedAt is the schema descriptor for created_at field.
userDescCreatedAt := userMixinFields0[0].Descriptor()
// user.DefaultCreatedAt holds the default value on creation for the created_at field.
user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
// userDescUpdatedAt is the schema descriptor for updated_at field.
userDescUpdatedAt := userMixinFields0[1].Descriptor()
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
// user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time)
// userDescEmail is the schema descriptor for email field.
userDescEmail := userFields[0].Descriptor()
// user.EmailValidator is a validator for the "email" field. It is called by the builders before save.
user.EmailValidator = func() func(string) error {
validators := userDescEmail.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(email string) error {
for _, fn := range fns {
if err := fn(email); err != nil {
return err
}
}
return nil
}
}()
// userDescPasswordHash is the schema descriptor for password_hash field.
userDescPasswordHash := userFields[1].Descriptor()
// user.PasswordHashValidator is a validator for the "password_hash" field. It is called by the builders before save.
user.PasswordHashValidator = func() func(string) error {
validators := userDescPasswordHash.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(password_hash string) error {
for _, fn := range fns {
if err := fn(password_hash); err != nil {
return err
}
}
return nil
}
}()
// userDescRole is the schema descriptor for role field.
userDescRole := userFields[2].Descriptor()
// user.DefaultRole holds the default value on creation for the role field.
user.DefaultRole = userDescRole.Default.(string)
// user.RoleValidator is a validator for the "role" field. It is called by the builders before save.
user.RoleValidator = userDescRole.Validators[0].(func(string) error)
// userDescBalance is the schema descriptor for balance field.
userDescBalance := userFields[3].Descriptor()
// user.DefaultBalance holds the default value on creation for the balance field.
user.DefaultBalance = userDescBalance.Default.(float64)
// userDescConcurrency is the schema descriptor for concurrency field.
userDescConcurrency := userFields[4].Descriptor()
// user.DefaultConcurrency holds the default value on creation for the concurrency field.
user.DefaultConcurrency = userDescConcurrency.Default.(int)
// userDescStatus is the schema descriptor for status field.
userDescStatus := userFields[5].Descriptor()
// user.DefaultStatus holds the default value on creation for the status field.
user.DefaultStatus = userDescStatus.Default.(string)
// user.StatusValidator is a validator for the "status" field. It is called by the builders before save.
user.StatusValidator = userDescStatus.Validators[0].(func(string) error)
// userDescUsername is the schema descriptor for username field.
userDescUsername := userFields[6].Descriptor()
// user.DefaultUsername holds the default value on creation for the username field.
user.DefaultUsername = userDescUsername.Default.(string)
// user.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
user.UsernameValidator = userDescUsername.Validators[0].(func(string) error)
// userDescWechat is the schema descriptor for wechat field.
userDescWechat := userFields[7].Descriptor()
// user.DefaultWechat holds the default value on creation for the wechat field.
user.DefaultWechat = userDescWechat.Default.(string)
// user.WechatValidator is a validator for the "wechat" field. It is called by the builders before save.
user.WechatValidator = userDescWechat.Validators[0].(func(string) error)
// userDescNotes is the schema descriptor for notes field.
userDescNotes := userFields[8].Descriptor()
// user.DefaultNotes holds the default value on creation for the notes field.
user.DefaultNotes = userDescNotes.Default.(string)
userallowedgroupFields := schema.UserAllowedGroup{}.Fields()
_ = userallowedgroupFields
// userallowedgroupDescCreatedAt is the schema descriptor for created_at field.
userallowedgroupDescCreatedAt := userallowedgroupFields[2].Descriptor()
// userallowedgroup.DefaultCreatedAt holds the default value on creation for the created_at field.
userallowedgroup.DefaultCreatedAt = userallowedgroupDescCreatedAt.Default.(func() time.Time)
usersubscriptionMixin := schema.UserSubscription{}.Mixin()
usersubscriptionMixinFields0 := usersubscriptionMixin[0].Fields()
_ = usersubscriptionMixinFields0
usersubscriptionFields := schema.UserSubscription{}.Fields()
_ = usersubscriptionFields
// usersubscriptionDescCreatedAt is the schema descriptor for created_at field.
usersubscriptionDescCreatedAt := usersubscriptionMixinFields0[0].Descriptor()
// usersubscription.DefaultCreatedAt holds the default value on creation for the created_at field.
usersubscription.DefaultCreatedAt = usersubscriptionDescCreatedAt.Default.(func() time.Time)
// usersubscriptionDescUpdatedAt is the schema descriptor for updated_at field.
usersubscriptionDescUpdatedAt := usersubscriptionMixinFields0[1].Descriptor()
// usersubscription.DefaultUpdatedAt holds the default value on creation for the updated_at field.
usersubscription.DefaultUpdatedAt = usersubscriptionDescUpdatedAt.Default.(func() time.Time)
// usersubscription.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
usersubscription.UpdateDefaultUpdatedAt = usersubscriptionDescUpdatedAt.UpdateDefault.(func() time.Time)
// usersubscriptionDescStatus is the schema descriptor for status field.
usersubscriptionDescStatus := usersubscriptionFields[4].Descriptor()
// usersubscription.DefaultStatus holds the default value on creation for the status field.
usersubscription.DefaultStatus = usersubscriptionDescStatus.Default.(string)
// usersubscription.StatusValidator is a validator for the "status" field. It is called by the builders before save.
usersubscription.StatusValidator = usersubscriptionDescStatus.Validators[0].(func(string) error)
// usersubscriptionDescDailyUsageUsd is the schema descriptor for daily_usage_usd field.
usersubscriptionDescDailyUsageUsd := usersubscriptionFields[8].Descriptor()
// usersubscription.DefaultDailyUsageUsd holds the default value on creation for the daily_usage_usd field.
usersubscription.DefaultDailyUsageUsd = usersubscriptionDescDailyUsageUsd.Default.(float64)
// usersubscriptionDescWeeklyUsageUsd is the schema descriptor for weekly_usage_usd field.
usersubscriptionDescWeeklyUsageUsd := usersubscriptionFields[9].Descriptor()
// usersubscription.DefaultWeeklyUsageUsd holds the default value on creation for the weekly_usage_usd field.
usersubscription.DefaultWeeklyUsageUsd = usersubscriptionDescWeeklyUsageUsd.Default.(float64)
// usersubscriptionDescMonthlyUsageUsd is the schema descriptor for monthly_usage_usd field.
usersubscriptionDescMonthlyUsageUsd := usersubscriptionFields[10].Descriptor()
// usersubscription.DefaultMonthlyUsageUsd holds the default value on creation for the monthly_usage_usd field.
usersubscription.DefaultMonthlyUsageUsd = usersubscriptionDescMonthlyUsageUsd.Default.(float64)
// usersubscriptionDescAssignedAt is the schema descriptor for assigned_at field.
usersubscriptionDescAssignedAt := usersubscriptionFields[12].Descriptor()
// usersubscription.DefaultAssignedAt holds the default value on creation for the assigned_at field.
usersubscription.DefaultAssignedAt = usersubscriptionDescAssignedAt.Default.(func() time.Time)
}
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)

View File

@@ -0,0 +1,190 @@
// Package schema 定义 Ent ORM 的数据库 schema。
// 每个文件对应一个数据库实体(表),定义其字段、边(关联)和索引。
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/service"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// Account 定义 AI API 账户实体的 schema。
//
// 账户是系统的核心资源,代表一个可用于调用 AI API 的凭证。
// 例如:一个 Claude API 账户、一个 Gemini OAuth 账户等。
//
// 主要功能:
// - 存储不同平台Claude、Gemini、OpenAI 等)的 API 凭证
// - 支持多种认证类型api_key、oauth、cookie 等)
// - 管理账户的调度状态(可调度、速率限制、过载等)
// - 通过分组机制实现账户的灵活分配
type Account struct {
ent.Schema
}
// Annotations 返回 schema 的注解配置。
// 这里指定数据库表名为 "accounts"。
func (Account) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "accounts"},
}
}
// Mixin 返回该 schema 使用的混入组件。
// - TimeMixin: 自动管理 created_at 和 updated_at 时间戳
// - SoftDeleteMixin: 提供软删除功能deleted_at
func (Account) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
// Fields 定义账户实体的所有字段。
func (Account) Fields() []ent.Field {
return []ent.Field{
// name: 账户显示名称,用于在界面中标识账户
field.String("name").
MaxLen(100).
NotEmpty(),
// platform: 所属平台,如 "claude", "gemini", "openai" 等
field.String("platform").
MaxLen(50).
NotEmpty(),
// type: 认证类型,如 "api_key", "oauth", "cookie" 等
// 不同类型决定了 credentials 中存储的数据结构
field.String("type").
MaxLen(20).
NotEmpty(),
// credentials: 认证凭证,以 JSONB 格式存储
// 结构取决于 type 字段:
// - api_key: {"api_key": "sk-xxx"}
// - oauth: {"access_token": "...", "refresh_token": "...", "expires_at": "..."}
// - cookie: {"session_key": "..."}
field.JSON("credentials", map[string]any{}).
Default(func() map[string]any { return map[string]any{} }).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
// extra: 扩展数据,存储平台特定的额外信息
// 如 CRS 账户的 crs_account_id、组织信息等
field.JSON("extra", map[string]any{}).
Default(func() map[string]any { return map[string]any{} }).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
// proxy_id: 关联的代理配置 ID可选
// 用于需要通过特定代理访问 API 的场景
field.Int64("proxy_id").
Optional().
Nillable(),
// concurrency: 账户最大并发请求数
// 用于限制同一时间对该账户发起的请求数量
field.Int("concurrency").
Default(3),
// priority: 账户优先级,数值越小优先级越高
// 调度器会优先使用高优先级的账户
field.Int("priority").
Default(50),
// status: 账户状态,如 "active", "error", "disabled"
field.String("status").
MaxLen(20).
Default(service.StatusActive),
// error_message: 错误信息,记录账户异常时的详细信息
field.String("error_message").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
// last_used_at: 最后使用时间,用于统计和调度
field.Time("last_used_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
// ========== 调度和速率限制相关字段 ==========
// 这些字段在 migrations/005_schema_parity.sql 中添加
// schedulable: 是否可被调度器选中
// false 表示账户暂时不参与请求分配(如正在刷新 token
field.Bool("schedulable").
Default(true),
// rate_limited_at: 触发速率限制的时间
// 当收到 429 错误时记录
field.Time("rate_limited_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
// rate_limit_reset_at: 速率限制预计解除的时间
// 调度器会在此时间之前避免使用该账户
field.Time("rate_limit_reset_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
// overload_until: 过载状态解除时间
// 当收到 529 错误API 过载)时设置
field.Time("overload_until").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
// session_window_*: 会话窗口相关字段
// 用于管理某些需要会话时间窗口的 API如 Claude Pro
field.Time("session_window_start").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("session_window_end").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.String("session_window_status").
Optional().
Nillable().
MaxLen(20),
}
}
// Edges 定义账户实体的关联关系。
func (Account) Edges() []ent.Edge {
return []ent.Edge{
// groups: 账户所属的分组(多对多关系)
// 通过 account_groups 中间表实现
// 一个账户可以属于多个分组,一个分组可以包含多个账户
edge.To("groups", Group.Type).
Through("account_groups", AccountGroup.Type),
}
}
// Indexes 定义数据库索引,优化查询性能。
// 每个索引对应一个常用的查询条件。
func (Account) Indexes() []ent.Index {
return []ent.Index{
index.Fields("platform"), // 按平台筛选
index.Fields("type"), // 按认证类型筛选
index.Fields("status"), // 按状态筛选
index.Fields("proxy_id"), // 按代理筛选
index.Fields("priority"), // 按优先级排序
index.Fields("last_used_at"), // 按最后使用时间排序
index.Fields("schedulable"), // 筛选可调度账户
index.Fields("rate_limited_at"), // 筛选速率限制账户
index.Fields("rate_limit_reset_at"), // 筛选速率限制解除时间
index.Fields("overload_until"), // 筛选过载账户
index.Fields("deleted_at"), // 软删除查询优化
}
}

View File

@@ -0,0 +1,58 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// AccountGroup holds the edge schema definition for the account_groups relationship.
// It stores extra fields (priority, created_at) and uses a composite primary key.
type AccountGroup struct {
ent.Schema
}
func (AccountGroup) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "account_groups"},
// Composite primary key: (account_id, group_id).
field.ID("account_id", "group_id"),
}
}
func (AccountGroup) Fields() []ent.Field {
return []ent.Field{
field.Int64("account_id"),
field.Int64("group_id"),
field.Int("priority").
Default(50),
field.Time("created_at").
Immutable().
Default(time.Now),
}
}
func (AccountGroup) Edges() []ent.Edge {
return []ent.Edge{
edge.To("account", Account.Type).
Unique().
Required().
Field("account_id"),
edge.To("group", Group.Type).
Unique().
Required().
Field("group_id"),
}
}
func (AccountGroup) Indexes() []ent.Index {
return []ent.Index{
index.Fields("group_id"),
index.Fields("priority"),
}
}

View File

@@ -0,0 +1,74 @@
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/service"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// ApiKey holds the schema definition for the ApiKey entity.
type ApiKey struct {
ent.Schema
}
func (ApiKey) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "api_keys"},
}
}
func (ApiKey) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
func (ApiKey) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id"),
field.String("key").
MaxLen(128).
NotEmpty().
Unique(),
field.String("name").
MaxLen(100).
NotEmpty(),
field.Int64("group_id").
Optional().
Nillable(),
field.String("status").
MaxLen(20).
Default(service.StatusActive),
}
}
func (ApiKey) Edges() []ent.Edge {
return []ent.Edge{
edge.From("user", User.Type).
Ref("api_keys").
Field("user_id").
Unique().
Required(),
edge.From("group", Group.Type).
Ref("api_keys").
Field("group_id").
Unique(),
}
}
func (ApiKey) Indexes() []ent.Index {
return []ent.Index{
index.Fields("key").Unique(),
index.Fields("user_id"),
index.Fields("group_id"),
index.Fields("status"),
index.Fields("deleted_at"),
}
}

View File

@@ -0,0 +1,98 @@
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/service"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// Group holds the schema definition for the Group entity.
type Group struct {
ent.Schema
}
func (Group) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "groups"},
}
}
func (Group) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(100).
NotEmpty().
Unique(),
field.String("description").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Float("rate_multiplier").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(1.0),
field.Bool("is_exclusive").
Default(false),
field.String("status").
MaxLen(20).
Default(service.StatusActive),
// Subscription-related fields (added by migration 003)
field.String("platform").
MaxLen(50).
Default(service.PlatformAnthropic),
field.String("subscription_type").
MaxLen(20).
Default(service.SubscriptionTypeStandard),
field.Float("daily_limit_usd").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
field.Float("weekly_limit_usd").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
field.Float("monthly_limit_usd").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
}
}
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.To("api_keys", ApiKey.Type),
edge.To("redeem_codes", RedeemCode.Type),
edge.To("subscriptions", UserSubscription.Type),
edge.From("accounts", Account.Type).
Ref("groups").
Through("account_groups", AccountGroup.Type),
edge.From("allowed_users", User.Type).
Ref("allowed_groups").
Through("user_allowed_groups", UserAllowedGroup.Type),
}
}
func (Group) Indexes() []ent.Index {
return []ent.Index{
index.Fields("name").Unique(),
index.Fields("status"),
index.Fields("platform"),
index.Fields("subscription_type"),
index.Fields("is_exclusive"),
index.Fields("deleted_at"),
}
}

View File

@@ -0,0 +1,142 @@
// Package mixins 提供 Ent schema 的可复用混入组件。
// 包括时间戳混入、软删除混入等通用功能。
package mixins
import (
"context"
"fmt"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// SoftDeleteMixin 实现基于 deleted_at 时间戳的软删除功能。
//
// 软删除特性:
// - 删除操作不会真正删除数据库记录,而是设置 deleted_at 时间戳
// - 所有查询默认自动过滤 deleted_at IS NULL只返回"未删除"的记录
// - 通过 SkipSoftDelete(ctx) 可以绕过软删除过滤器,查询或真正删除记录
//
// 实现原理:
// - 使用 Ent 的 Interceptor 拦截所有查询,自动添加 deleted_at IS NULL 条件
// - 使用 Ent 的 Hook 拦截删除操作,将 DELETE 转换为 UPDATE SET deleted_at = NOW()
//
// 使用示例:
//
// func (User) Mixin() []ent.Mixin {
// return []ent.Mixin{
// mixins.SoftDeleteMixin{},
// }
// }
type SoftDeleteMixin struct {
mixin.Schema
}
// Fields 定义软删除所需的字段。
// deleted_at 字段:
// - 类型为 TIMESTAMPTZ精确记录删除时间
// - Optional 和 Nillable 确保新记录时该字段为 NULL
// - NULL 表示记录未被删除,非 NULL 表示已软删除
func (SoftDeleteMixin) Fields() []ent.Field {
return []ent.Field{
field.Time("deleted_at").
Optional().
Nillable().
SchemaType(map[string]string{
dialect.Postgres: "timestamptz",
}),
}
}
// softDeleteKey 是用于在 context 中标记跳过软删除的键类型。
// 使用空结构体作为键可以避免与其他包的键冲突。
type softDeleteKey struct{}
// SkipSoftDelete 返回一个新的 context用于跳过软删除的拦截器和变更器。
//
// 使用场景:
// - 查询已软删除的记录(如管理员查看回收站)
// - 执行真正的物理删除(如彻底清理数据)
// - 恢复软删除的记录
//
// 示例:
//
// // 查询包含已删除记录的所有用户
// users, err := client.User.Query().All(mixins.SkipSoftDelete(ctx))
//
// // 真正删除记录
// client.User.DeleteOneID(id).Exec(mixins.SkipSoftDelete(ctx))
func SkipSoftDelete(parent context.Context) context.Context {
return context.WithValue(parent, softDeleteKey{}, true)
}
// Interceptors 返回查询拦截器列表。
// 拦截器会自动为所有查询添加 deleted_at IS NULL 条件,
// 确保软删除的记录不会出现在普通查询结果中。
func (d SoftDeleteMixin) Interceptors() []ent.Interceptor {
return []ent.Interceptor{
ent.TraverseFunc(func(ctx context.Context, q ent.Query) error {
// 检查是否需要跳过软删除过滤
if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
return nil
}
// 为查询添加 deleted_at IS NULL 条件
w, ok := q.(interface{ WhereP(...func(*sql.Selector)) })
if ok {
d.applyPredicate(w)
}
return nil
}),
}
}
// Hooks 返回变更钩子列表。
// 钩子会拦截 DELETE 操作,将其转换为 UPDATE SET deleted_at = NOW()。
// 这样删除操作实际上只是标记记录为已删除,而不是真正删除。
func (d SoftDeleteMixin) Hooks() []ent.Hook {
return []ent.Hook{
func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
// 只处理删除操作
if m.Op() != ent.OpDelete && m.Op() != ent.OpDeleteOne {
return next.Mutate(ctx, m)
}
// 检查是否需要执行真正的删除
if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
return next.Mutate(ctx, m)
}
// 类型断言,获取 mutation 的扩展接口
mx, ok := m.(interface {
SetOp(ent.Op)
Client() interface {
Mutate(context.Context, ent.Mutation) (ent.Value, error)
}
SetDeletedAt(time.Time)
WhereP(...func(*sql.Selector))
})
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// 添加软删除过滤条件,确保不会影响已删除的记录
d.applyPredicate(mx)
// 将 DELETE 操作转换为 UPDATE 操作
mx.SetOp(ent.OpUpdate)
// 设置删除时间为当前时间
mx.SetDeletedAt(time.Now())
return mx.Client().Mutate(ctx, m)
})
},
}
}
// applyPredicate 为查询添加 deleted_at IS NULL 条件。
// 这是软删除过滤的核心实现。
func (d SoftDeleteMixin) applyPredicate(w interface{ WhereP(...func(*sql.Selector)) }) {
w.WhereP(
sql.FieldIsNull(d.Fields()[0].Descriptor().Name),
)
}

View File

@@ -0,0 +1,32 @@
package mixins
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// TimeMixin provides created_at and updated_at fields compatible with the existing schema.
type TimeMixin struct {
mixin.Schema
}
func (TimeMixin) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Immutable().
Default(time.Now).
SchemaType(map[string]string{
dialect.Postgres: "timestamptz",
}),
field.Time("updated_at").
Default(time.Now).
UpdateDefault(time.Now).
SchemaType(map[string]string{
dialect.Postgres: "timestamptz",
}),
}
}

View File

@@ -0,0 +1,62 @@
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// Proxy holds the schema definition for the Proxy entity.
type Proxy struct {
ent.Schema
}
func (Proxy) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "proxies"},
}
}
func (Proxy) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
func (Proxy) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(100).
NotEmpty(),
field.String("protocol").
MaxLen(20).
NotEmpty(),
field.String("host").
MaxLen(255).
NotEmpty(),
field.Int("port"),
field.String("username").
MaxLen(100).
Optional().
Nillable(),
field.String("password").
MaxLen(100).
Optional().
Nillable(),
field.String("status").
MaxLen(20).
Default("active"),
}
}
func (Proxy) Indexes() []ent.Index {
return []ent.Index{
index.Fields("status"),
index.Fields("deleted_at"),
}
}

View File

@@ -0,0 +1,86 @@
package schema
import (
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// RedeemCode holds the schema definition for the RedeemCode entity.
type RedeemCode struct {
ent.Schema
}
func (RedeemCode) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "redeem_codes"},
}
}
func (RedeemCode) Fields() []ent.Field {
return []ent.Field{
field.String("code").
MaxLen(32).
NotEmpty().
Unique(),
field.String("type").
MaxLen(20).
Default(service.RedeemTypeBalance),
field.Float("value").
SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
Default(0),
field.String("status").
MaxLen(20).
Default(service.StatusUnused),
field.Int64("used_by").
Optional().
Nillable(),
field.Time("used_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.String("notes").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Time("created_at").
Immutable().
Default(time.Now).
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Int64("group_id").
Optional().
Nillable(),
field.Int("validity_days").
Default(30),
}
}
func (RedeemCode) Edges() []ent.Edge {
return []ent.Edge{
edge.From("user", User.Type).
Ref("redeem_codes").
Field("used_by").
Unique(),
edge.From("group", Group.Type).
Ref("redeem_codes").
Field("group_id").
Unique(),
}
}
func (RedeemCode) Indexes() []ent.Index {
return []ent.Index{
index.Fields("code").Unique(),
index.Fields("status"),
index.Fields("used_by"),
index.Fields("group_id"),
}
}

View File

@@ -0,0 +1,49 @@
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"
)
// Setting holds the schema definition for the Setting entity.
type Setting struct {
ent.Schema
}
func (Setting) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "settings"},
}
}
func (Setting) Fields() []ent.Field {
return []ent.Field{
field.String("key").
MaxLen(100).
NotEmpty().
Unique(),
field.String("value").
NotEmpty().
SchemaType(map[string]string{
dialect.Postgres: "text",
}),
field.Time("updated_at").
Default(time.Now).
UpdateDefault(time.Now).
SchemaType(map[string]string{
dialect.Postgres: "timestamptz",
}),
}
}
func (Setting) Indexes() []ent.Index {
return []ent.Index{
index.Fields("key").Unique(),
}
}

View File

@@ -0,0 +1,85 @@
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/service"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "users"},
}
}
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("email").
MaxLen(255).
NotEmpty().
Unique(),
field.String("password_hash").
MaxLen(255).
NotEmpty(),
field.String("role").
MaxLen(20).
Default(service.RoleUser),
field.Float("balance").
SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
Default(0),
field.Int("concurrency").
Default(5),
field.String("status").
MaxLen(20).
Default(service.StatusActive),
// Optional profile fields (added later; default '' in DB migration)
field.String("username").
MaxLen(100).
Default(""),
field.String("wechat").
MaxLen(100).
Default(""),
field.String("notes").
SchemaType(map[string]string{dialect.Postgres: "text"}).
Default(""),
}
}
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("api_keys", ApiKey.Type),
edge.To("redeem_codes", RedeemCode.Type),
edge.To("subscriptions", UserSubscription.Type),
edge.To("assigned_subscriptions", UserSubscription.Type),
edge.To("allowed_groups", Group.Type).
Through("user_allowed_groups", UserAllowedGroup.Type),
}
}
func (User) Indexes() []ent.Index {
return []ent.Index{
index.Fields("email").Unique(),
index.Fields("status"),
index.Fields("deleted_at"),
}
}

View File

@@ -0,0 +1,55 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// UserAllowedGroup holds the edge schema definition for the user_allowed_groups relationship.
// It replaces the legacy users.allowed_groups BIGINT[] column.
type UserAllowedGroup struct {
ent.Schema
}
func (UserAllowedGroup) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "user_allowed_groups"},
// Composite primary key: (user_id, group_id).
field.ID("user_id", "group_id"),
}
}
func (UserAllowedGroup) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id"),
field.Int64("group_id"),
field.Time("created_at").
Immutable().
Default(time.Now),
}
}
func (UserAllowedGroup) Edges() []ent.Edge {
return []ent.Edge{
edge.To("user", User.Type).
Unique().
Required().
Field("user_id"),
edge.To("group", Group.Type).
Unique().
Required().
Field("group_id"),
}
}
func (UserAllowedGroup) Indexes() []ent.Index {
return []ent.Index{
index.Fields("group_id"),
}
}

View File

@@ -0,0 +1,113 @@
package schema
import (
"time"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/service"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// UserSubscription holds the schema definition for the UserSubscription entity.
type UserSubscription struct {
ent.Schema
}
func (UserSubscription) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "user_subscriptions"},
}
}
func (UserSubscription) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
func (UserSubscription) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id"),
field.Int64("group_id"),
field.Time("starts_at").
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("expires_at").
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.String("status").
MaxLen(20).
Default(service.SubscriptionStatusActive),
field.Time("daily_window_start").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("weekly_window_start").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("monthly_window_start").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Float("daily_usage_usd").
SchemaType(map[string]string{dialect.Postgres: "decimal(20,10)"}).
Default(0),
field.Float("weekly_usage_usd").
SchemaType(map[string]string{dialect.Postgres: "decimal(20,10)"}).
Default(0),
field.Float("monthly_usage_usd").
SchemaType(map[string]string{dialect.Postgres: "decimal(20,10)"}).
Default(0),
field.Int64("assigned_by").
Optional().
Nillable(),
field.Time("assigned_at").
Default(time.Now).
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.String("notes").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
}
}
func (UserSubscription) Edges() []ent.Edge {
return []ent.Edge{
edge.From("user", User.Type).
Ref("subscriptions").
Field("user_id").
Unique().
Required(),
edge.From("group", Group.Type).
Ref("subscriptions").
Field("group_id").
Unique().
Required(),
edge.From("assigned_by_user", User.Type).
Ref("assigned_subscriptions").
Field("assigned_by").
Unique(),
}
}
func (UserSubscription) Indexes() []ent.Index {
return []ent.Index{
index.Fields("user_id"),
index.Fields("group_id"),
index.Fields("status"),
index.Fields("expires_at"),
index.Fields("assigned_by"),
index.Fields("user_id", "group_id").Unique(),
}
}

128
backend/ent/setting.go Normal file
View File

@@ -0,0 +1,128 @@
// 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/setting"
)
// Setting is the model entity for the Setting schema.
type Setting struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// Key holds the value of the "key" field.
Key string `json:"key,omitempty"`
// Value holds the value of the "value" field.
Value string `json:"value,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Setting) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case setting.FieldID:
values[i] = new(sql.NullInt64)
case setting.FieldKey, setting.FieldValue:
values[i] = new(sql.NullString)
case setting.FieldUpdatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Setting fields.
func (_m *Setting) 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 setting.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 setting.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case setting.FieldValue:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field value", values[i])
} else if value.Valid {
_m.Value = value.String
}
case setting.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// GetValue returns the ent.Value that was dynamically selected and assigned to the Setting.
// This includes values selected through modifiers, order, etc.
func (_m *Setting) GetValue(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Setting.
// Note that you need to call Setting.Unwrap() before calling this method if this Setting
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Setting) Update() *SettingUpdateOne {
return NewSettingClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Setting 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 *Setting) Unwrap() *Setting {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Setting is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Setting) String() string {
var builder strings.Builder
builder.WriteString("Setting(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("value=")
builder.WriteString(_m.Value)
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Settings is a parsable slice of Setting.
type Settings []*Setting

View File

@@ -0,0 +1,76 @@
// Code generated by ent, DO NOT EDIT.
package setting
import (
"time"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the setting type in the database.
Label = "setting"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldValue holds the string denoting the value field in the database.
FieldValue = "value"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// Table holds the table name of the setting in the database.
Table = "settings"
)
// Columns holds all SQL columns for setting fields.
var Columns = []string{
FieldID,
FieldKey,
FieldValue,
FieldUpdatedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
// ValueValidator is a validator for the "value" field. It is called by the builders before save.
ValueValidator func(string) error
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
)
// OrderOption defines the ordering options for the Setting 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()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByValue orders the results by the value field.
func ByValue(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValue, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}

View File

@@ -0,0 +1,255 @@
// Code generated by ent, DO NOT EDIT.
package setting
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldID, id))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldKey, v))
}
// Value applies equality check predicate on the "value" field. It's identical to ValueEQ.
func Value(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldValue, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldUpdatedAt, v))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.Setting {
return predicate.Setting(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldContainsFold(FieldKey, v))
}
// ValueEQ applies the EQ predicate on the "value" field.
func ValueEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldValue, v))
}
// ValueNEQ applies the NEQ predicate on the "value" field.
func ValueNEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldValue, v))
}
// ValueIn applies the In predicate on the "value" field.
func ValueIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldValue, vs...))
}
// ValueNotIn applies the NotIn predicate on the "value" field.
func ValueNotIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldValue, vs...))
}
// ValueGT applies the GT predicate on the "value" field.
func ValueGT(v string) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldValue, v))
}
// ValueGTE applies the GTE predicate on the "value" field.
func ValueGTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldValue, v))
}
// ValueLT applies the LT predicate on the "value" field.
func ValueLT(v string) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldValue, v))
}
// ValueLTE applies the LTE predicate on the "value" field.
func ValueLTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldValue, v))
}
// ValueContains applies the Contains predicate on the "value" field.
func ValueContains(v string) predicate.Setting {
return predicate.Setting(sql.FieldContains(FieldValue, v))
}
// ValueHasPrefix applies the HasPrefix predicate on the "value" field.
func ValueHasPrefix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasPrefix(FieldValue, v))
}
// ValueHasSuffix applies the HasSuffix predicate on the "value" field.
func ValueHasSuffix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasSuffix(FieldValue, v))
}
// ValueEqualFold applies the EqualFold predicate on the "value" field.
func ValueEqualFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldEqualFold(FieldValue, v))
}
// ValueContainsFold applies the ContainsFold predicate on the "value" field.
func ValueContainsFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldContainsFold(FieldValue, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldUpdatedAt, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Setting) predicate.Setting {
return predicate.Setting(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Setting) predicate.Setting {
return predicate.Setting(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Setting) predicate.Setting {
return predicate.Setting(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,589 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/setting"
)
// SettingCreate is the builder for creating a Setting entity.
type SettingCreate struct {
config
mutation *SettingMutation
hooks []Hook
conflict []sql.ConflictOption
}
// SetKey sets the "key" field.
func (_c *SettingCreate) SetKey(v string) *SettingCreate {
_c.mutation.SetKey(v)
return _c
}
// SetValue sets the "value" field.
func (_c *SettingCreate) SetValue(v string) *SettingCreate {
_c.mutation.SetValue(v)
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *SettingCreate) SetUpdatedAt(v time.Time) *SettingCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *SettingCreate) SetNillableUpdatedAt(v *time.Time) *SettingCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// Mutation returns the SettingMutation object of the builder.
func (_c *SettingCreate) Mutation() *SettingMutation {
return _c.mutation
}
// Save creates the Setting in the database.
func (_c *SettingCreate) Save(ctx context.Context) (*Setting, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *SettingCreate) SaveX(ctx context.Context) *Setting {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *SettingCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *SettingCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *SettingCreate) defaults() {
if _, ok := _c.mutation.UpdatedAt(); !ok {
v := setting.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *SettingCreate) check() error {
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Setting.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if _, ok := _c.mutation.Value(); !ok {
return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Setting.value"`)}
}
if v, ok := _c.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Setting.updated_at"`)}
}
return nil
}
func (_c *SettingCreate) sqlSave(ctx context.Context) (*Setting, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int64(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *SettingCreate) createSpec() (*Setting, *sqlgraph.CreateSpec) {
var (
_node = &Setting{config: _c.config}
_spec = sqlgraph.NewCreateSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt64))
)
_spec.OnConflict = _c.conflict
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
_node.Value = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(setting.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
return _node, _spec
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.Setting.Create().
// SetKey(v).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.SettingUpsert) {
// SetKey(v+v).
// }).
// Exec(ctx)
func (_c *SettingCreate) OnConflict(opts ...sql.ConflictOption) *SettingUpsertOne {
_c.conflict = opts
return &SettingUpsertOne{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.Setting.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *SettingCreate) OnConflictColumns(columns ...string) *SettingUpsertOne {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &SettingUpsertOne{
create: _c,
}
}
type (
// SettingUpsertOne is the builder for "upsert"-ing
// one Setting node.
SettingUpsertOne struct {
create *SettingCreate
}
// SettingUpsert is the "OnConflict" setter.
SettingUpsert struct {
*sql.UpdateSet
}
)
// SetKey sets the "key" field.
func (u *SettingUpsert) SetKey(v string) *SettingUpsert {
u.Set(setting.FieldKey, v)
return u
}
// UpdateKey sets the "key" field to the value that was provided on create.
func (u *SettingUpsert) UpdateKey() *SettingUpsert {
u.SetExcluded(setting.FieldKey)
return u
}
// SetValue sets the "value" field.
func (u *SettingUpsert) SetValue(v string) *SettingUpsert {
u.Set(setting.FieldValue, v)
return u
}
// UpdateValue sets the "value" field to the value that was provided on create.
func (u *SettingUpsert) UpdateValue() *SettingUpsert {
u.SetExcluded(setting.FieldValue)
return u
}
// SetUpdatedAt sets the "updated_at" field.
func (u *SettingUpsert) SetUpdatedAt(v time.Time) *SettingUpsert {
u.Set(setting.FieldUpdatedAt, v)
return u
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *SettingUpsert) UpdateUpdatedAt() *SettingUpsert {
u.SetExcluded(setting.FieldUpdatedAt)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
// client.Setting.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *SettingUpsertOne) UpdateNewValues() *SettingUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.Setting.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *SettingUpsertOne) Ignore() *SettingUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *SettingUpsertOne) DoNothing() *SettingUpsertOne {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the SettingCreate.OnConflict
// documentation for more info.
func (u *SettingUpsertOne) Update(set func(*SettingUpsert)) *SettingUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&SettingUpsert{UpdateSet: update})
}))
return u
}
// SetKey sets the "key" field.
func (u *SettingUpsertOne) SetKey(v string) *SettingUpsertOne {
return u.Update(func(s *SettingUpsert) {
s.SetKey(v)
})
}
// UpdateKey sets the "key" field to the value that was provided on create.
func (u *SettingUpsertOne) UpdateKey() *SettingUpsertOne {
return u.Update(func(s *SettingUpsert) {
s.UpdateKey()
})
}
// SetValue sets the "value" field.
func (u *SettingUpsertOne) SetValue(v string) *SettingUpsertOne {
return u.Update(func(s *SettingUpsert) {
s.SetValue(v)
})
}
// UpdateValue sets the "value" field to the value that was provided on create.
func (u *SettingUpsertOne) UpdateValue() *SettingUpsertOne {
return u.Update(func(s *SettingUpsert) {
s.UpdateValue()
})
}
// SetUpdatedAt sets the "updated_at" field.
func (u *SettingUpsertOne) SetUpdatedAt(v time.Time) *SettingUpsertOne {
return u.Update(func(s *SettingUpsert) {
s.SetUpdatedAt(v)
})
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *SettingUpsertOne) UpdateUpdatedAt() *SettingUpsertOne {
return u.Update(func(s *SettingUpsert) {
s.UpdateUpdatedAt()
})
}
// Exec executes the query.
func (u *SettingUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for SettingCreate.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *SettingUpsertOne) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}
// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *SettingUpsertOne) ID(ctx context.Context) (id int64, err error) {
node, err := u.create.Save(ctx)
if err != nil {
return id, err
}
return node.ID, nil
}
// IDX is like ID, but panics if an error occurs.
func (u *SettingUpsertOne) IDX(ctx context.Context) int64 {
id, err := u.ID(ctx)
if err != nil {
panic(err)
}
return id
}
// SettingCreateBulk is the builder for creating many Setting entities in bulk.
type SettingCreateBulk struct {
config
err error
builders []*SettingCreate
conflict []sql.ConflictOption
}
// Save creates the Setting entities in the database.
func (_c *SettingCreateBulk) Save(ctx context.Context) ([]*Setting, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Setting, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SettingMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
spec.OnConflict = _c.conflict
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int64(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *SettingCreateBulk) SaveX(ctx context.Context) []*Setting {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *SettingCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *SettingCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.Setting.CreateBulk(builders...).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.SettingUpsert) {
// SetKey(v+v).
// }).
// Exec(ctx)
func (_c *SettingCreateBulk) OnConflict(opts ...sql.ConflictOption) *SettingUpsertBulk {
_c.conflict = opts
return &SettingUpsertBulk{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.Setting.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *SettingCreateBulk) OnConflictColumns(columns ...string) *SettingUpsertBulk {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &SettingUpsertBulk{
create: _c,
}
}
// SettingUpsertBulk is the builder for "upsert"-ing
// a bulk of Setting nodes.
type SettingUpsertBulk struct {
create *SettingCreateBulk
}
// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
// client.Setting.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *SettingUpsertBulk) UpdateNewValues() *SettingUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.Setting.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *SettingUpsertBulk) Ignore() *SettingUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *SettingUpsertBulk) DoNothing() *SettingUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the SettingCreateBulk.OnConflict
// documentation for more info.
func (u *SettingUpsertBulk) Update(set func(*SettingUpsert)) *SettingUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&SettingUpsert{UpdateSet: update})
}))
return u
}
// SetKey sets the "key" field.
func (u *SettingUpsertBulk) SetKey(v string) *SettingUpsertBulk {
return u.Update(func(s *SettingUpsert) {
s.SetKey(v)
})
}
// UpdateKey sets the "key" field to the value that was provided on create.
func (u *SettingUpsertBulk) UpdateKey() *SettingUpsertBulk {
return u.Update(func(s *SettingUpsert) {
s.UpdateKey()
})
}
// SetValue sets the "value" field.
func (u *SettingUpsertBulk) SetValue(v string) *SettingUpsertBulk {
return u.Update(func(s *SettingUpsert) {
s.SetValue(v)
})
}
// UpdateValue sets the "value" field to the value that was provided on create.
func (u *SettingUpsertBulk) UpdateValue() *SettingUpsertBulk {
return u.Update(func(s *SettingUpsert) {
s.UpdateValue()
})
}
// SetUpdatedAt sets the "updated_at" field.
func (u *SettingUpsertBulk) SetUpdatedAt(v time.Time) *SettingUpsertBulk {
return u.Update(func(s *SettingUpsert) {
s.SetUpdatedAt(v)
})
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *SettingUpsertBulk) UpdateUpdatedAt() *SettingUpsertBulk {
return u.Update(func(s *SettingUpsert) {
s.UpdateUpdatedAt()
})
}
// Exec executes the query.
func (u *SettingUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
return u.create.err
}
for i, b := range u.create.builders {
if len(b.conflict) != 0 {
return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the SettingCreateBulk instead", i)
}
}
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for SettingCreateBulk.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *SettingUpsertBulk) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// 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/setting"
)
// SettingDelete is the builder for deleting a Setting entity.
type SettingDelete struct {
config
hooks []Hook
mutation *SettingMutation
}
// Where appends a list predicates to the SettingDelete builder.
func (_d *SettingDelete) Where(ps ...predicate.Setting) *SettingDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *SettingDelete) 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 *SettingDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *SettingDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(setting.Table, sqlgraph.NewFieldSpec(setting.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
}
// SettingDeleteOne is the builder for deleting a single Setting entity.
type SettingDeleteOne struct {
_d *SettingDelete
}
// Where appends a list predicates to the SettingDelete builder.
func (_d *SettingDeleteOne) Where(ps ...predicate.Setting) *SettingDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *SettingDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{setting.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *SettingDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"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/setting"
)
// SettingQuery is the builder for querying Setting entities.
type SettingQuery struct {
config
ctx *QueryContext
order []setting.OrderOption
inters []Interceptor
predicates []predicate.Setting
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the SettingQuery builder.
func (_q *SettingQuery) Where(ps ...predicate.Setting) *SettingQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *SettingQuery) Limit(limit int) *SettingQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *SettingQuery) Offset(offset int) *SettingQuery {
_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 *SettingQuery) Unique(unique bool) *SettingQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *SettingQuery) Order(o ...setting.OrderOption) *SettingQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Setting entity from the query.
// Returns a *NotFoundError when no Setting was found.
func (_q *SettingQuery) First(ctx context.Context) (*Setting, 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{setting.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *SettingQuery) FirstX(ctx context.Context) *Setting {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Setting ID from the query.
// Returns a *NotFoundError when no Setting ID was found.
func (_q *SettingQuery) 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{setting.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *SettingQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Setting entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Setting entity is found.
// Returns a *NotFoundError when no Setting entities are found.
func (_q *SettingQuery) Only(ctx context.Context) (*Setting, 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{setting.Label}
default:
return nil, &NotSingularError{setting.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *SettingQuery) OnlyX(ctx context.Context) *Setting {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Setting ID in the query.
// Returns a *NotSingularError when more than one Setting ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *SettingQuery) 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{setting.Label}
default:
err = &NotSingularError{setting.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *SettingQuery) 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 Settings.
func (_q *SettingQuery) All(ctx context.Context) ([]*Setting, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Setting, *SettingQuery]()
return withInterceptors[[]*Setting](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *SettingQuery) AllX(ctx context.Context) []*Setting {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Setting IDs.
func (_q *SettingQuery) 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(setting.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *SettingQuery) 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 *SettingQuery) 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[*SettingQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *SettingQuery) 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 *SettingQuery) 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 *SettingQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the SettingQuery 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 *SettingQuery) Clone() *SettingQuery {
if _q == nil {
return nil
}
return &SettingQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]setting.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Setting{}, _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 {
// Key string `json:"key,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Setting.Query().
// GroupBy(setting.FieldKey).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *SettingQuery) GroupBy(field string, fields ...string) *SettingGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &SettingGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = setting.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 {
// Key string `json:"key,omitempty"`
// }
//
// client.Setting.Query().
// Select(setting.FieldKey).
// Scan(ctx, &v)
func (_q *SettingQuery) Select(fields ...string) *SettingSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &SettingSelect{SettingQuery: _q}
sbuild.label = setting.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a SettingSelect configured with the given aggregations.
func (_q *SettingQuery) Aggregate(fns ...AggregateFunc) *SettingSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *SettingQuery) 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 !setting.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 *SettingQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Setting, error) {
var (
nodes = []*Setting{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Setting).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Setting{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *SettingQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *SettingQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.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, setting.FieldID)
for i := range fields {
if fields[i] != setting.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 *SettingQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(setting.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = setting.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// SettingGroupBy is the group-by builder for Setting entities.
type SettingGroupBy struct {
selector
build *SettingQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *SettingGroupBy) Aggregate(fns ...AggregateFunc) *SettingGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *SettingGroupBy) 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[*SettingQuery, *SettingGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *SettingGroupBy) sqlScan(ctx context.Context, root *SettingQuery, 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)
}
// SettingSelect is the builder for selecting fields of Setting entities.
type SettingSelect struct {
*SettingQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *SettingSelect) Aggregate(fns ...AggregateFunc) *SettingSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *SettingSelect) 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[*SettingQuery, *SettingSelect](ctx, _s.SettingQuery, _s, _s.inters, v)
}
func (_s *SettingSelect) sqlScan(ctx context.Context, root *SettingQuery, 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)
}

View File

@@ -0,0 +1,316 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"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/setting"
)
// SettingUpdate is the builder for updating Setting entities.
type SettingUpdate struct {
config
hooks []Hook
mutation *SettingMutation
}
// Where appends a list predicates to the SettingUpdate builder.
func (_u *SettingUpdate) Where(ps ...predicate.Setting) *SettingUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetKey sets the "key" field.
func (_u *SettingUpdate) SetKey(v string) *SettingUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *SettingUpdate) SetNillableKey(v *string) *SettingUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *SettingUpdate) SetValue(v string) *SettingUpdate {
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *SettingUpdate) SetNillableValue(v *string) *SettingUpdate {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *SettingUpdate) SetUpdatedAt(v time.Time) *SettingUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// Mutation returns the SettingMutation object of the builder.
func (_u *SettingUpdate) Mutation() *SettingMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *SettingUpdate) Save(ctx context.Context) (int, error) {
_u.defaults()
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *SettingUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *SettingUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *SettingUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *SettingUpdate) defaults() {
if _, ok := _u.mutation.UpdatedAt(); !ok {
v := setting.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *SettingUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if v, ok := _u.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_u *SettingUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(setting.FieldUpdatedAt, field.TypeTime, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{setting.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// SettingUpdateOne is the builder for updating a single Setting entity.
type SettingUpdateOne struct {
config
fields []string
hooks []Hook
mutation *SettingMutation
}
// SetKey sets the "key" field.
func (_u *SettingUpdateOne) SetKey(v string) *SettingUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *SettingUpdateOne) SetNillableKey(v *string) *SettingUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *SettingUpdateOne) SetValue(v string) *SettingUpdateOne {
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *SettingUpdateOne) SetNillableValue(v *string) *SettingUpdateOne {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *SettingUpdateOne) SetUpdatedAt(v time.Time) *SettingUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// Mutation returns the SettingMutation object of the builder.
func (_u *SettingUpdateOne) Mutation() *SettingMutation {
return _u.mutation
}
// Where appends a list predicates to the SettingUpdate builder.
func (_u *SettingUpdateOne) Where(ps ...predicate.Setting) *SettingUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *SettingUpdateOne) Select(field string, fields ...string) *SettingUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Setting entity.
func (_u *SettingUpdateOne) Save(ctx context.Context) (*Setting, error) {
_u.defaults()
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *SettingUpdateOne) SaveX(ctx context.Context) *Setting {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *SettingUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *SettingUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *SettingUpdateOne) defaults() {
if _, ok := _u.mutation.UpdatedAt(); !ok {
v := setting.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *SettingUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if v, ok := _u.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_u *SettingUpdateOne) sqlSave(ctx context.Context) (_node *Setting, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Setting.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
for _, f := range fields {
if !setting.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != setting.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(setting.FieldUpdatedAt, field.TypeTime, value)
}
_node = &Setting{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{setting.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

237
backend/ent/tx.go Normal file
View File

@@ -0,0 +1,237 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Account is the client for interacting with the Account builders.
Account *AccountClient
// AccountGroup is the client for interacting with the AccountGroup builders.
AccountGroup *AccountGroupClient
// ApiKey is the client for interacting with the ApiKey builders.
ApiKey *ApiKeyClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Proxy is the client for interacting with the Proxy builders.
Proxy *ProxyClient
// RedeemCode is the client for interacting with the RedeemCode builders.
RedeemCode *RedeemCodeClient
// Setting is the client for interacting with the Setting builders.
Setting *SettingClient
// User is the client for interacting with the User builders.
User *UserClient
// UserAllowedGroup is the client for interacting with the UserAllowedGroup builders.
UserAllowedGroup *UserAllowedGroupClient
// UserSubscription is the client for interacting with the UserSubscription builders.
UserSubscription *UserSubscriptionClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Account = NewAccountClient(tx.config)
tx.AccountGroup = NewAccountGroupClient(tx.config)
tx.ApiKey = NewApiKeyClient(tx.config)
tx.Group = NewGroupClient(tx.config)
tx.Proxy = NewProxyClient(tx.config)
tx.RedeemCode = NewRedeemCodeClient(tx.config)
tx.Setting = NewSettingClient(tx.config)
tx.User = NewUserClient(tx.config)
tx.UserAllowedGroup = NewUserAllowedGroupClient(tx.config)
tx.UserSubscription = NewUserSubscriptionClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Account.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

338
backend/ent/user.go Normal file
View File

@@ -0,0 +1,338 @@
// 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/user"
)
// User is the model entity for the User schema.
type User 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"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// Email holds the value of the "email" field.
Email string `json:"email,omitempty"`
// PasswordHash holds the value of the "password_hash" field.
PasswordHash string `json:"password_hash,omitempty"`
// Role holds the value of the "role" field.
Role string `json:"role,omitempty"`
// Balance holds the value of the "balance" field.
Balance float64 `json:"balance,omitempty"`
// Concurrency holds the value of the "concurrency" field.
Concurrency int `json:"concurrency,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Username holds the value of the "username" field.
Username string `json:"username,omitempty"`
// Wechat holds the value of the "wechat" field.
Wechat string `json:"wechat,omitempty"`
// Notes holds the value of the "notes" field.
Notes string `json:"notes,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// APIKeys holds the value of the api_keys edge.
APIKeys []*ApiKey `json:"api_keys,omitempty"`
// RedeemCodes holds the value of the redeem_codes edge.
RedeemCodes []*RedeemCode `json:"redeem_codes,omitempty"`
// Subscriptions holds the value of the subscriptions edge.
Subscriptions []*UserSubscription `json:"subscriptions,omitempty"`
// AssignedSubscriptions holds the value of the assigned_subscriptions edge.
AssignedSubscriptions []*UserSubscription `json:"assigned_subscriptions,omitempty"`
// AllowedGroups holds the value of the allowed_groups edge.
AllowedGroups []*Group `json:"allowed_groups,omitempty"`
// UserAllowedGroups holds the value of the user_allowed_groups edge.
UserAllowedGroups []*UserAllowedGroup `json:"user_allowed_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [6]bool
}
// APIKeysOrErr returns the APIKeys value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) APIKeysOrErr() ([]*ApiKey, error) {
if e.loadedTypes[0] {
return e.APIKeys, nil
}
return nil, &NotLoadedError{edge: "api_keys"}
}
// RedeemCodesOrErr returns the RedeemCodes value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) RedeemCodesOrErr() ([]*RedeemCode, error) {
if e.loadedTypes[1] {
return e.RedeemCodes, nil
}
return nil, &NotLoadedError{edge: "redeem_codes"}
}
// SubscriptionsOrErr returns the Subscriptions value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) SubscriptionsOrErr() ([]*UserSubscription, error) {
if e.loadedTypes[2] {
return e.Subscriptions, nil
}
return nil, &NotLoadedError{edge: "subscriptions"}
}
// AssignedSubscriptionsOrErr returns the AssignedSubscriptions value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) AssignedSubscriptionsOrErr() ([]*UserSubscription, error) {
if e.loadedTypes[3] {
return e.AssignedSubscriptions, nil
}
return nil, &NotLoadedError{edge: "assigned_subscriptions"}
}
// AllowedGroupsOrErr returns the AllowedGroups value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) AllowedGroupsOrErr() ([]*Group, error) {
if e.loadedTypes[4] {
return e.AllowedGroups, nil
}
return nil, &NotLoadedError{edge: "allowed_groups"}
}
// UserAllowedGroupsOrErr returns the UserAllowedGroups value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) UserAllowedGroupsOrErr() ([]*UserAllowedGroup, error) {
if e.loadedTypes[5] {
return e.UserAllowedGroups, nil
}
return nil, &NotLoadedError{edge: "user_allowed_groups"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldBalance:
values[i] = new(sql.NullFloat64)
case user.FieldID, user.FieldConcurrency:
values[i] = new(sql.NullInt64)
case user.FieldEmail, user.FieldPasswordHash, user.FieldRole, user.FieldStatus, user.FieldUsername, user.FieldWechat, user.FieldNotes:
values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt, user.FieldDeletedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the User fields.
func (_m *User) 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 user.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 user.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 user.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 user.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(time.Time)
*_m.DeletedAt = value.Time
}
case user.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 = value.String
}
case user.FieldPasswordHash:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password_hash", values[i])
} else if value.Valid {
_m.PasswordHash = value.String
}
case user.FieldRole:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field role", values[i])
} else if value.Valid {
_m.Role = value.String
}
case user.FieldBalance:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field balance", values[i])
} else if value.Valid {
_m.Balance = value.Float64
}
case user.FieldConcurrency:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field concurrency", values[i])
} else if value.Valid {
_m.Concurrency = int(value.Int64)
}
case user.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
case user.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 = value.String
}
case user.FieldWechat:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field wechat", values[i])
} else if value.Valid {
_m.Wechat = value.String
}
case user.FieldNotes:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[i])
} else if value.Valid {
_m.Notes = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the User.
// This includes values selected through modifiers, order, etc.
func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryAPIKeys queries the "api_keys" edge of the User entity.
func (_m *User) QueryAPIKeys() *ApiKeyQuery {
return NewUserClient(_m.config).QueryAPIKeys(_m)
}
// QueryRedeemCodes queries the "redeem_codes" edge of the User entity.
func (_m *User) QueryRedeemCodes() *RedeemCodeQuery {
return NewUserClient(_m.config).QueryRedeemCodes(_m)
}
// QuerySubscriptions queries the "subscriptions" edge of the User entity.
func (_m *User) QuerySubscriptions() *UserSubscriptionQuery {
return NewUserClient(_m.config).QuerySubscriptions(_m)
}
// QueryAssignedSubscriptions queries the "assigned_subscriptions" edge of the User entity.
func (_m *User) QueryAssignedSubscriptions() *UserSubscriptionQuery {
return NewUserClient(_m.config).QueryAssignedSubscriptions(_m)
}
// QueryAllowedGroups queries the "allowed_groups" edge of the User entity.
func (_m *User) QueryAllowedGroups() *GroupQuery {
return NewUserClient(_m.config).QueryAllowedGroups(_m)
}
// QueryUserAllowedGroups queries the "user_allowed_groups" edge of the User entity.
func (_m *User) QueryUserAllowedGroups() *UserAllowedGroupQuery {
return NewUserClient(_m.config).QueryUserAllowedGroups(_m)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *User) Update() *UserUpdateOne {
return NewUserClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the User 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 *User) Unwrap() *User {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
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(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("email=")
builder.WriteString(_m.Email)
builder.WriteString(", ")
builder.WriteString("password_hash=")
builder.WriteString(_m.PasswordHash)
builder.WriteString(", ")
builder.WriteString("role=")
builder.WriteString(_m.Role)
builder.WriteString(", ")
builder.WriteString("balance=")
builder.WriteString(fmt.Sprintf("%v", _m.Balance))
builder.WriteString(", ")
builder.WriteString("concurrency=")
builder.WriteString(fmt.Sprintf("%v", _m.Concurrency))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
builder.WriteString("username=")
builder.WriteString(_m.Username)
builder.WriteString(", ")
builder.WriteString("wechat=")
builder.WriteString(_m.Wechat)
builder.WriteString(", ")
builder.WriteString("notes=")
builder.WriteString(_m.Notes)
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

365
backend/ent/user/user.go Normal file
View File

@@ -0,0 +1,365 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// 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"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldEmail holds the string denoting the email field in the database.
FieldEmail = "email"
// FieldPasswordHash holds the string denoting the password_hash field in the database.
FieldPasswordHash = "password_hash"
// FieldRole holds the string denoting the role field in the database.
FieldRole = "role"
// FieldBalance holds the string denoting the balance field in the database.
FieldBalance = "balance"
// FieldConcurrency holds the string denoting the concurrency field in the database.
FieldConcurrency = "concurrency"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldWechat holds the string denoting the wechat field in the database.
FieldWechat = "wechat"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.
EdgeAPIKeys = "api_keys"
// EdgeRedeemCodes holds the string denoting the redeem_codes edge name in mutations.
EdgeRedeemCodes = "redeem_codes"
// EdgeSubscriptions holds the string denoting the subscriptions edge name in mutations.
EdgeSubscriptions = "subscriptions"
// EdgeAssignedSubscriptions holds the string denoting the assigned_subscriptions edge name in mutations.
EdgeAssignedSubscriptions = "assigned_subscriptions"
// EdgeAllowedGroups holds the string denoting the allowed_groups edge name in mutations.
EdgeAllowedGroups = "allowed_groups"
// EdgeUserAllowedGroups holds the string denoting the user_allowed_groups edge name in mutations.
EdgeUserAllowedGroups = "user_allowed_groups"
// Table holds the table name of the user in the database.
Table = "users"
// APIKeysTable is the table that holds the api_keys relation/edge.
APIKeysTable = "api_keys"
// APIKeysInverseTable is the table name for the ApiKey entity.
// It exists in this package in order to avoid circular dependency with the "apikey" package.
APIKeysInverseTable = "api_keys"
// APIKeysColumn is the table column denoting the api_keys relation/edge.
APIKeysColumn = "user_id"
// RedeemCodesTable is the table that holds the redeem_codes relation/edge.
RedeemCodesTable = "redeem_codes"
// RedeemCodesInverseTable is the table name for the RedeemCode entity.
// It exists in this package in order to avoid circular dependency with the "redeemcode" package.
RedeemCodesInverseTable = "redeem_codes"
// RedeemCodesColumn is the table column denoting the redeem_codes relation/edge.
RedeemCodesColumn = "used_by"
// SubscriptionsTable is the table that holds the subscriptions relation/edge.
SubscriptionsTable = "user_subscriptions"
// SubscriptionsInverseTable is the table name for the UserSubscription entity.
// It exists in this package in order to avoid circular dependency with the "usersubscription" package.
SubscriptionsInverseTable = "user_subscriptions"
// SubscriptionsColumn is the table column denoting the subscriptions relation/edge.
SubscriptionsColumn = "user_id"
// AssignedSubscriptionsTable is the table that holds the assigned_subscriptions relation/edge.
AssignedSubscriptionsTable = "user_subscriptions"
// AssignedSubscriptionsInverseTable is the table name for the UserSubscription entity.
// It exists in this package in order to avoid circular dependency with the "usersubscription" package.
AssignedSubscriptionsInverseTable = "user_subscriptions"
// AssignedSubscriptionsColumn is the table column denoting the assigned_subscriptions relation/edge.
AssignedSubscriptionsColumn = "assigned_by"
// AllowedGroupsTable is the table that holds the allowed_groups relation/edge. The primary key declared below.
AllowedGroupsTable = "user_allowed_groups"
// AllowedGroupsInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
AllowedGroupsInverseTable = "groups"
// UserAllowedGroupsTable is the table that holds the user_allowed_groups relation/edge.
UserAllowedGroupsTable = "user_allowed_groups"
// UserAllowedGroupsInverseTable is the table name for the UserAllowedGroup entity.
// It exists in this package in order to avoid circular dependency with the "userallowedgroup" package.
UserAllowedGroupsInverseTable = "user_allowed_groups"
// UserAllowedGroupsColumn is the table column denoting the user_allowed_groups relation/edge.
UserAllowedGroupsColumn = "user_id"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldEmail,
FieldPasswordHash,
FieldRole,
FieldBalance,
FieldConcurrency,
FieldStatus,
FieldUsername,
FieldWechat,
FieldNotes,
}
var (
// AllowedGroupsPrimaryKey and AllowedGroupsColumn2 are the table columns denoting the
// primary key for the allowed_groups relation (M2M).
AllowedGroupsPrimaryKey = []string{"user_id", "group_id"}
)
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "github.com/Wei-Shaw/sub2api/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
// 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
// EmailValidator is a validator for the "email" field. It is called by the builders before save.
EmailValidator func(string) error
// PasswordHashValidator is a validator for the "password_hash" field. It is called by the builders before save.
PasswordHashValidator func(string) error
// DefaultRole holds the default value on creation for the "role" field.
DefaultRole string
// RoleValidator is a validator for the "role" field. It is called by the builders before save.
RoleValidator func(string) error
// DefaultBalance holds the default value on creation for the "balance" field.
DefaultBalance float64
// DefaultConcurrency holds the default value on creation for the "concurrency" field.
DefaultConcurrency int
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DefaultUsername holds the default value on creation for the "username" field.
DefaultUsername string
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// DefaultWechat holds the default value on creation for the "wechat" field.
DefaultWechat string
// WechatValidator is a validator for the "wechat" field. It is called by the builders before save.
WechatValidator func(string) error
// DefaultNotes holds the default value on creation for the "notes" field.
DefaultNotes string
)
// OrderOption defines the ordering options for the User 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()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByEmail orders the results by the email field.
func ByEmail(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEmail, opts...).ToFunc()
}
// ByPasswordHash orders the results by the password_hash field.
func ByPasswordHash(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPasswordHash, opts...).ToFunc()
}
// ByRole orders the results by the role field.
func ByRole(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRole, opts...).ToFunc()
}
// ByBalance orders the results by the balance field.
func ByBalance(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBalance, opts...).ToFunc()
}
// ByConcurrency orders the results by the concurrency field.
func ByConcurrency(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldConcurrency, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByWechat orders the results by the wechat field.
func ByWechat(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWechat, opts...).ToFunc()
}
// ByNotes orders the results by the notes field.
func ByNotes(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotes, opts...).ToFunc()
}
// ByAPIKeysCount orders the results by api_keys count.
func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAPIKeysStep(), opts...)
}
}
// ByAPIKeys orders the results by api_keys terms.
func ByAPIKeys(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAPIKeysStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByRedeemCodesCount orders the results by redeem_codes count.
func ByRedeemCodesCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newRedeemCodesStep(), opts...)
}
}
// ByRedeemCodes orders the results by redeem_codes terms.
func ByRedeemCodes(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newRedeemCodesStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// BySubscriptionsCount orders the results by subscriptions count.
func BySubscriptionsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newSubscriptionsStep(), opts...)
}
}
// BySubscriptions orders the results by subscriptions terms.
func BySubscriptions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newSubscriptionsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAssignedSubscriptionsCount orders the results by assigned_subscriptions count.
func ByAssignedSubscriptionsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAssignedSubscriptionsStep(), opts...)
}
}
// ByAssignedSubscriptions orders the results by assigned_subscriptions terms.
func ByAssignedSubscriptions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAssignedSubscriptionsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAllowedGroupsCount orders the results by allowed_groups count.
func ByAllowedGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAllowedGroupsStep(), opts...)
}
}
// ByAllowedGroups orders the results by allowed_groups terms.
func ByAllowedGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAllowedGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByUserAllowedGroupsCount orders the results by user_allowed_groups count.
func ByUserAllowedGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUserAllowedGroupsStep(), opts...)
}
}
// ByUserAllowedGroups orders the results by user_allowed_groups terms.
func ByUserAllowedGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserAllowedGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newAPIKeysStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(APIKeysInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn),
)
}
func newRedeemCodesStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(RedeemCodesInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, RedeemCodesTable, RedeemCodesColumn),
)
}
func newSubscriptionsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(SubscriptionsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn),
)
}
func newAssignedSubscriptionsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AssignedSubscriptionsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, AssignedSubscriptionsTable, AssignedSubscriptionsColumn),
)
}
func newAllowedGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AllowedGroupsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, AllowedGroupsTable, AllowedGroupsPrimaryKey...),
)
}
func newUserAllowedGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserAllowedGroupsInverseTable, UserAllowedGroupsColumn),
sqlgraph.Edge(sqlgraph.O2M, true, UserAllowedGroupsTable, UserAllowedGroupsColumn),
)
}

934
backend/ent/user/where.go Normal file
View File

@@ -0,0 +1,934 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldDeletedAt, v))
}
// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
func Email(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldEmail, v))
}
// PasswordHash applies equality check predicate on the "password_hash" field. It's identical to PasswordHashEQ.
func PasswordHash(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPasswordHash, v))
}
// Role applies equality check predicate on the "role" field. It's identical to RoleEQ.
func Role(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldRole, v))
}
// Balance applies equality check predicate on the "balance" field. It's identical to BalanceEQ.
func Balance(v float64) predicate.User {
return predicate.User(sql.FieldEQ(FieldBalance, v))
}
// Concurrency applies equality check predicate on the "concurrency" field. It's identical to ConcurrencyEQ.
func Concurrency(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldConcurrency, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldStatus, v))
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// Wechat applies equality check predicate on the "wechat" field. It's identical to WechatEQ.
func Wechat(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldWechat, v))
}
// Notes applies equality check predicate on the "notes" field. It's identical to NotesEQ.
func Notes(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldNotes, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.User {
return predicate.User(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.User {
return predicate.User(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.User {
return predicate.User(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.User {
return predicate.User(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.User {
return predicate.User(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.User {
return predicate.User(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.User {
return predicate.User(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.User {
return predicate.User(sql.FieldLTE(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v time.Time) predicate.User {
return predicate.User(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v time.Time) predicate.User {
return predicate.User(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v time.Time) predicate.User {
return predicate.User(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v time.Time) predicate.User {
return predicate.User(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldDeletedAt))
}
// EmailEQ applies the EQ predicate on the "email" field.
func EmailEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldEmail, v))
}
// EmailNEQ applies the NEQ predicate on the "email" field.
func EmailNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldEmail, v))
}
// EmailIn applies the In predicate on the "email" field.
func EmailIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldEmail, vs...))
}
// EmailNotIn applies the NotIn predicate on the "email" field.
func EmailNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldEmail, vs...))
}
// EmailGT applies the GT predicate on the "email" field.
func EmailGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldEmail, v))
}
// EmailGTE applies the GTE predicate on the "email" field.
func EmailGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldEmail, v))
}
// EmailLT applies the LT predicate on the "email" field.
func EmailLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldEmail, v))
}
// EmailLTE applies the LTE predicate on the "email" field.
func EmailLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldEmail, v))
}
// EmailContains applies the Contains predicate on the "email" field.
func EmailContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldEmail, v))
}
// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
func EmailHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldEmail, v))
}
// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
func EmailHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldEmail, v))
}
// EmailEqualFold applies the EqualFold predicate on the "email" field.
func EmailEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldEmail, v))
}
// EmailContainsFold applies the ContainsFold predicate on the "email" field.
func EmailContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldEmail, v))
}
// PasswordHashEQ applies the EQ predicate on the "password_hash" field.
func PasswordHashEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPasswordHash, v))
}
// PasswordHashNEQ applies the NEQ predicate on the "password_hash" field.
func PasswordHashNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldPasswordHash, v))
}
// PasswordHashIn applies the In predicate on the "password_hash" field.
func PasswordHashIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldPasswordHash, vs...))
}
// PasswordHashNotIn applies the NotIn predicate on the "password_hash" field.
func PasswordHashNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldPasswordHash, vs...))
}
// PasswordHashGT applies the GT predicate on the "password_hash" field.
func PasswordHashGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldPasswordHash, v))
}
// PasswordHashGTE applies the GTE predicate on the "password_hash" field.
func PasswordHashGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldPasswordHash, v))
}
// PasswordHashLT applies the LT predicate on the "password_hash" field.
func PasswordHashLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldPasswordHash, v))
}
// PasswordHashLTE applies the LTE predicate on the "password_hash" field.
func PasswordHashLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldPasswordHash, v))
}
// PasswordHashContains applies the Contains predicate on the "password_hash" field.
func PasswordHashContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldPasswordHash, v))
}
// PasswordHashHasPrefix applies the HasPrefix predicate on the "password_hash" field.
func PasswordHashHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldPasswordHash, v))
}
// PasswordHashHasSuffix applies the HasSuffix predicate on the "password_hash" field.
func PasswordHashHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldPasswordHash, v))
}
// PasswordHashEqualFold applies the EqualFold predicate on the "password_hash" field.
func PasswordHashEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldPasswordHash, v))
}
// PasswordHashContainsFold applies the ContainsFold predicate on the "password_hash" field.
func PasswordHashContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldPasswordHash, v))
}
// RoleEQ applies the EQ predicate on the "role" field.
func RoleEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldRole, v))
}
// RoleNEQ applies the NEQ predicate on the "role" field.
func RoleNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldRole, v))
}
// RoleIn applies the In predicate on the "role" field.
func RoleIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldRole, vs...))
}
// RoleNotIn applies the NotIn predicate on the "role" field.
func RoleNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldRole, vs...))
}
// RoleGT applies the GT predicate on the "role" field.
func RoleGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldRole, v))
}
// RoleGTE applies the GTE predicate on the "role" field.
func RoleGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldRole, v))
}
// RoleLT applies the LT predicate on the "role" field.
func RoleLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldRole, v))
}
// RoleLTE applies the LTE predicate on the "role" field.
func RoleLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldRole, v))
}
// RoleContains applies the Contains predicate on the "role" field.
func RoleContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldRole, v))
}
// RoleHasPrefix applies the HasPrefix predicate on the "role" field.
func RoleHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldRole, v))
}
// RoleHasSuffix applies the HasSuffix predicate on the "role" field.
func RoleHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldRole, v))
}
// RoleEqualFold applies the EqualFold predicate on the "role" field.
func RoleEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldRole, v))
}
// RoleContainsFold applies the ContainsFold predicate on the "role" field.
func RoleContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldRole, v))
}
// BalanceEQ applies the EQ predicate on the "balance" field.
func BalanceEQ(v float64) predicate.User {
return predicate.User(sql.FieldEQ(FieldBalance, v))
}
// BalanceNEQ applies the NEQ predicate on the "balance" field.
func BalanceNEQ(v float64) predicate.User {
return predicate.User(sql.FieldNEQ(FieldBalance, v))
}
// BalanceIn applies the In predicate on the "balance" field.
func BalanceIn(vs ...float64) predicate.User {
return predicate.User(sql.FieldIn(FieldBalance, vs...))
}
// BalanceNotIn applies the NotIn predicate on the "balance" field.
func BalanceNotIn(vs ...float64) predicate.User {
return predicate.User(sql.FieldNotIn(FieldBalance, vs...))
}
// BalanceGT applies the GT predicate on the "balance" field.
func BalanceGT(v float64) predicate.User {
return predicate.User(sql.FieldGT(FieldBalance, v))
}
// BalanceGTE applies the GTE predicate on the "balance" field.
func BalanceGTE(v float64) predicate.User {
return predicate.User(sql.FieldGTE(FieldBalance, v))
}
// BalanceLT applies the LT predicate on the "balance" field.
func BalanceLT(v float64) predicate.User {
return predicate.User(sql.FieldLT(FieldBalance, v))
}
// BalanceLTE applies the LTE predicate on the "balance" field.
func BalanceLTE(v float64) predicate.User {
return predicate.User(sql.FieldLTE(FieldBalance, v))
}
// ConcurrencyEQ applies the EQ predicate on the "concurrency" field.
func ConcurrencyEQ(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldConcurrency, v))
}
// ConcurrencyNEQ applies the NEQ predicate on the "concurrency" field.
func ConcurrencyNEQ(v int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldConcurrency, v))
}
// ConcurrencyIn applies the In predicate on the "concurrency" field.
func ConcurrencyIn(vs ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldConcurrency, vs...))
}
// ConcurrencyNotIn applies the NotIn predicate on the "concurrency" field.
func ConcurrencyNotIn(vs ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldConcurrency, vs...))
}
// ConcurrencyGT applies the GT predicate on the "concurrency" field.
func ConcurrencyGT(v int) predicate.User {
return predicate.User(sql.FieldGT(FieldConcurrency, v))
}
// ConcurrencyGTE applies the GTE predicate on the "concurrency" field.
func ConcurrencyGTE(v int) predicate.User {
return predicate.User(sql.FieldGTE(FieldConcurrency, v))
}
// ConcurrencyLT applies the LT predicate on the "concurrency" field.
func ConcurrencyLT(v int) predicate.User {
return predicate.User(sql.FieldLT(FieldConcurrency, v))
}
// ConcurrencyLTE applies the LTE predicate on the "concurrency" field.
func ConcurrencyLTE(v int) predicate.User {
return predicate.User(sql.FieldLTE(FieldConcurrency, v))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldStatus, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldUsername, v))
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldUsername, vs...))
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldUsername, vs...))
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldUsername, v))
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldUsername, v))
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldUsername, v))
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldUsername, v))
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldUsername, v))
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldUsername, v))
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldUsername, v))
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldUsername, v))
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldUsername, v))
}
// WechatEQ applies the EQ predicate on the "wechat" field.
func WechatEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldWechat, v))
}
// WechatNEQ applies the NEQ predicate on the "wechat" field.
func WechatNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldWechat, v))
}
// WechatIn applies the In predicate on the "wechat" field.
func WechatIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldWechat, vs...))
}
// WechatNotIn applies the NotIn predicate on the "wechat" field.
func WechatNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldWechat, vs...))
}
// WechatGT applies the GT predicate on the "wechat" field.
func WechatGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldWechat, v))
}
// WechatGTE applies the GTE predicate on the "wechat" field.
func WechatGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldWechat, v))
}
// WechatLT applies the LT predicate on the "wechat" field.
func WechatLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldWechat, v))
}
// WechatLTE applies the LTE predicate on the "wechat" field.
func WechatLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldWechat, v))
}
// WechatContains applies the Contains predicate on the "wechat" field.
func WechatContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldWechat, v))
}
// WechatHasPrefix applies the HasPrefix predicate on the "wechat" field.
func WechatHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldWechat, v))
}
// WechatHasSuffix applies the HasSuffix predicate on the "wechat" field.
func WechatHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldWechat, v))
}
// WechatEqualFold applies the EqualFold predicate on the "wechat" field.
func WechatEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldWechat, v))
}
// WechatContainsFold applies the ContainsFold predicate on the "wechat" field.
func WechatContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldWechat, v))
}
// NotesEQ applies the EQ predicate on the "notes" field.
func NotesEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldNotes, v))
}
// NotesNEQ applies the NEQ predicate on the "notes" field.
func NotesNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldNotes, v))
}
// NotesIn applies the In predicate on the "notes" field.
func NotesIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldNotes, vs...))
}
// NotesNotIn applies the NotIn predicate on the "notes" field.
func NotesNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldNotes, vs...))
}
// NotesGT applies the GT predicate on the "notes" field.
func NotesGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldNotes, v))
}
// NotesGTE applies the GTE predicate on the "notes" field.
func NotesGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldNotes, v))
}
// NotesLT applies the LT predicate on the "notes" field.
func NotesLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldNotes, v))
}
// NotesLTE applies the LTE predicate on the "notes" field.
func NotesLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldNotes, v))
}
// NotesContains applies the Contains predicate on the "notes" field.
func NotesContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldNotes, v))
}
// NotesHasPrefix applies the HasPrefix predicate on the "notes" field.
func NotesHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldNotes, v))
}
// NotesHasSuffix applies the HasSuffix predicate on the "notes" field.
func NotesHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldNotes, v))
}
// NotesEqualFold applies the EqualFold predicate on the "notes" field.
func NotesEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldNotes, v))
}
// NotesContainsFold applies the ContainsFold predicate on the "notes" field.
func NotesContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldNotes, v))
}
// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.
func HasAPIKeys() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAPIKeysWith applies the HasEdge predicate on the "api_keys" edge with a given conditions (other predicates).
func HasAPIKeysWith(preds ...predicate.ApiKey) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newAPIKeysStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasRedeemCodes applies the HasEdge predicate on the "redeem_codes" edge.
func HasRedeemCodes() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, RedeemCodesTable, RedeemCodesColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasRedeemCodesWith applies the HasEdge predicate on the "redeem_codes" edge with a given conditions (other predicates).
func HasRedeemCodesWith(preds ...predicate.RedeemCode) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newRedeemCodesStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasSubscriptions applies the HasEdge predicate on the "subscriptions" edge.
func HasSubscriptions() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasSubscriptionsWith applies the HasEdge predicate on the "subscriptions" edge with a given conditions (other predicates).
func HasSubscriptionsWith(preds ...predicate.UserSubscription) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newSubscriptionsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAssignedSubscriptions applies the HasEdge predicate on the "assigned_subscriptions" edge.
func HasAssignedSubscriptions() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, AssignedSubscriptionsTable, AssignedSubscriptionsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAssignedSubscriptionsWith applies the HasEdge predicate on the "assigned_subscriptions" edge with a given conditions (other predicates).
func HasAssignedSubscriptionsWith(preds ...predicate.UserSubscription) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newAssignedSubscriptionsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAllowedGroups applies the HasEdge predicate on the "allowed_groups" edge.
func HasAllowedGroups() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, AllowedGroupsTable, AllowedGroupsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAllowedGroupsWith applies the HasEdge predicate on the "allowed_groups" edge with a given conditions (other predicates).
func HasAllowedGroupsWith(preds ...predicate.Group) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newAllowedGroupsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasUserAllowedGroups applies the HasEdge predicate on the "user_allowed_groups" edge.
func HasUserAllowedGroups() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, UserAllowedGroupsTable, UserAllowedGroupsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserAllowedGroupsWith applies the HasEdge predicate on the "user_allowed_groups" edge with a given conditions (other predicates).
func HasUserAllowedGroupsWith(preds ...predicate.UserAllowedGroup) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newUserAllowedGroupsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(sql.NotPredicates(p))
}

1391
backend/ent/user_create.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
// 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/user"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserDelete) 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 *UserDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.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
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
_d *UserDelete
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{user.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

1014
backend/ent/user_query.go Normal file

File diff suppressed because it is too large Load Diff

1536
backend/ent/user_update.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,165 @@
// 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/group"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
)
// UserAllowedGroup is the model entity for the UserAllowedGroup schema.
type UserAllowedGroup struct {
config `json:"-"`
// UserID holds the value of the "user_id" field.
UserID int64 `json:"user_id,omitempty"`
// GroupID holds the value of the "group_id" field.
GroupID int64 `json:"group_id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserAllowedGroupQuery when eager-loading is set.
Edges UserAllowedGroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserAllowedGroupEdges holds the relations/edges for other nodes in the graph.
type UserAllowedGroupEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserAllowedGroupEdges) UserOrErr() (*User, error) {
if e.User != nil {
return e.User, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "user"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserAllowedGroupEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*UserAllowedGroup) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case userallowedgroup.FieldUserID, userallowedgroup.FieldGroupID:
values[i] = new(sql.NullInt64)
case userallowedgroup.FieldCreatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the UserAllowedGroup fields.
func (_m *UserAllowedGroup) 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 userallowedgroup.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = value.Int64
}
case userallowedgroup.FieldGroupID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field group_id", values[i])
} else if value.Valid {
_m.GroupID = value.Int64
}
case userallowedgroup.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the UserAllowedGroup.
// This includes values selected through modifiers, order, etc.
func (_m *UserAllowedGroup) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the UserAllowedGroup entity.
func (_m *UserAllowedGroup) QueryUser() *UserQuery {
return NewUserAllowedGroupClient(_m.config).QueryUser(_m)
}
// QueryGroup queries the "group" edge of the UserAllowedGroup entity.
func (_m *UserAllowedGroup) QueryGroup() *GroupQuery {
return NewUserAllowedGroupClient(_m.config).QueryGroup(_m)
}
// Update returns a builder for updating this UserAllowedGroup.
// Note that you need to call UserAllowedGroup.Unwrap() before calling this method if this UserAllowedGroup
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *UserAllowedGroup) Update() *UserAllowedGroupUpdateOne {
return NewUserAllowedGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the UserAllowedGroup 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 *UserAllowedGroup) Unwrap() *UserAllowedGroup {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: UserAllowedGroup is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *UserAllowedGroup) String() string {
var builder strings.Builder
builder.WriteString("UserAllowedGroup(")
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("group_id=")
builder.WriteString(fmt.Sprintf("%v", _m.GroupID))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// UserAllowedGroups is a parsable slice of UserAllowedGroup.
type UserAllowedGroups []*UserAllowedGroup

View File

@@ -0,0 +1,113 @@
// Code generated by ent, DO NOT EDIT.
package userallowedgroup
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the userallowedgroup type in the database.
Label = "user_allowed_group"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldGroupID holds the string denoting the group_id field in the database.
FieldGroupID = "group_id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// UserFieldID holds the string denoting the ID field of the User.
UserFieldID = "id"
// GroupFieldID holds the string denoting the ID field of the Group.
GroupFieldID = "id"
// Table holds the table name of the userallowedgroup in the database.
Table = "user_allowed_groups"
// UserTable is the table that holds the user relation/edge.
UserTable = "user_allowed_groups"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_id"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "user_allowed_groups"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
)
// Columns holds all SQL columns for userallowedgroup fields.
var Columns = []string{
FieldUserID,
FieldGroupID,
FieldCreatedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the UserAllowedGroup queries.
type OrderOption func(*sql.Selector)
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByGroupID orders the results by the group_id field.
func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGroupID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, UserColumn),
sqlgraph.To(UserInverseTable, UserFieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, GroupColumn),
sqlgraph.To(GroupInverseTable, GroupFieldID),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
}

View File

@@ -0,0 +1,167 @@
// Code generated by ent, DO NOT EDIT.
package userallowedgroup
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldEQ(FieldUserID, v))
}
// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
func GroupID(v int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldEQ(FieldGroupID, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldEQ(FieldCreatedAt, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldNotIn(FieldUserID, vs...))
}
// GroupIDEQ applies the EQ predicate on the "group_id" field.
func GroupIDEQ(v int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldEQ(FieldGroupID, v))
}
// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
func GroupIDNEQ(v int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldNEQ(FieldGroupID, v))
}
// GroupIDIn applies the In predicate on the "group_id" field.
func GroupIDIn(vs ...int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldIn(FieldGroupID, vs...))
}
// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
func GroupIDNotIn(vs ...int64) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldNotIn(FieldGroupID, vs...))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.FieldLTE(FieldCreatedAt, v))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, UserColumn),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(func(s *sql.Selector) {
step := newUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, GroupColumn),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.UserAllowedGroup) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.UserAllowedGroup) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.UserAllowedGroup) predicate.UserAllowedGroup {
return predicate.UserAllowedGroup(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,568 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
)
// UserAllowedGroupCreate is the builder for creating a UserAllowedGroup entity.
type UserAllowedGroupCreate struct {
config
mutation *UserAllowedGroupMutation
hooks []Hook
conflict []sql.ConflictOption
}
// SetUserID sets the "user_id" field.
func (_c *UserAllowedGroupCreate) SetUserID(v int64) *UserAllowedGroupCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetGroupID sets the "group_id" field.
func (_c *UserAllowedGroupCreate) SetGroupID(v int64) *UserAllowedGroupCreate {
_c.mutation.SetGroupID(v)
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *UserAllowedGroupCreate) SetCreatedAt(v time.Time) *UserAllowedGroupCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *UserAllowedGroupCreate) SetNillableCreatedAt(v *time.Time) *UserAllowedGroupCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUser sets the "user" edge to the User entity.
func (_c *UserAllowedGroupCreate) SetUser(v *User) *UserAllowedGroupCreate {
return _c.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_c *UserAllowedGroupCreate) SetGroup(v *Group) *UserAllowedGroupCreate {
return _c.SetGroupID(v.ID)
}
// Mutation returns the UserAllowedGroupMutation object of the builder.
func (_c *UserAllowedGroupCreate) Mutation() *UserAllowedGroupMutation {
return _c.mutation
}
// Save creates the UserAllowedGroup in the database.
func (_c *UserAllowedGroupCreate) Save(ctx context.Context) (*UserAllowedGroup, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserAllowedGroupCreate) SaveX(ctx context.Context) *UserAllowedGroup {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserAllowedGroupCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserAllowedGroupCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *UserAllowedGroupCreate) defaults() {
if _, ok := _c.mutation.CreatedAt(); !ok {
v := userallowedgroup.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserAllowedGroupCreate) check() error {
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserAllowedGroup.user_id"`)}
}
if _, ok := _c.mutation.GroupID(); !ok {
return &ValidationError{Name: "group_id", err: errors.New(`ent: missing required field "UserAllowedGroup.group_id"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "UserAllowedGroup.created_at"`)}
}
if len(_c.mutation.UserIDs()) == 0 {
return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserAllowedGroup.user"`)}
}
if len(_c.mutation.GroupIDs()) == 0 {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "UserAllowedGroup.group"`)}
}
return nil
}
func (_c *UserAllowedGroupCreate) sqlSave(ctx context.Context) (*UserAllowedGroup, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}
func (_c *UserAllowedGroupCreate) createSpec() (*UserAllowedGroup, *sqlgraph.CreateSpec) {
var (
_node = &UserAllowedGroup{config: _c.config}
_spec = sqlgraph.NewCreateSpec(userallowedgroup.Table, nil)
)
_spec.OnConflict = _c.conflict
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(userallowedgroup.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.UserTable,
Columns: []string{userallowedgroup.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.UserID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.GroupTable,
Columns: []string{userallowedgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.GroupID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.UserAllowedGroup.Create().
// SetUserID(v).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.UserAllowedGroupUpsert) {
// SetUserID(v+v).
// }).
// Exec(ctx)
func (_c *UserAllowedGroupCreate) OnConflict(opts ...sql.ConflictOption) *UserAllowedGroupUpsertOne {
_c.conflict = opts
return &UserAllowedGroupUpsertOne{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.UserAllowedGroup.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *UserAllowedGroupCreate) OnConflictColumns(columns ...string) *UserAllowedGroupUpsertOne {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &UserAllowedGroupUpsertOne{
create: _c,
}
}
type (
// UserAllowedGroupUpsertOne is the builder for "upsert"-ing
// one UserAllowedGroup node.
UserAllowedGroupUpsertOne struct {
create *UserAllowedGroupCreate
}
// UserAllowedGroupUpsert is the "OnConflict" setter.
UserAllowedGroupUpsert struct {
*sql.UpdateSet
}
)
// SetUserID sets the "user_id" field.
func (u *UserAllowedGroupUpsert) SetUserID(v int64) *UserAllowedGroupUpsert {
u.Set(userallowedgroup.FieldUserID, v)
return u
}
// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *UserAllowedGroupUpsert) UpdateUserID() *UserAllowedGroupUpsert {
u.SetExcluded(userallowedgroup.FieldUserID)
return u
}
// SetGroupID sets the "group_id" field.
func (u *UserAllowedGroupUpsert) SetGroupID(v int64) *UserAllowedGroupUpsert {
u.Set(userallowedgroup.FieldGroupID, v)
return u
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *UserAllowedGroupUpsert) UpdateGroupID() *UserAllowedGroupUpsert {
u.SetExcluded(userallowedgroup.FieldGroupID)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
// client.UserAllowedGroup.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *UserAllowedGroupUpsertOne) UpdateNewValues() *UserAllowedGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
if _, exists := u.create.mutation.CreatedAt(); exists {
s.SetIgnore(userallowedgroup.FieldCreatedAt)
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.UserAllowedGroup.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *UserAllowedGroupUpsertOne) Ignore() *UserAllowedGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *UserAllowedGroupUpsertOne) DoNothing() *UserAllowedGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the UserAllowedGroupCreate.OnConflict
// documentation for more info.
func (u *UserAllowedGroupUpsertOne) Update(set func(*UserAllowedGroupUpsert)) *UserAllowedGroupUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&UserAllowedGroupUpsert{UpdateSet: update})
}))
return u
}
// SetUserID sets the "user_id" field.
func (u *UserAllowedGroupUpsertOne) SetUserID(v int64) *UserAllowedGroupUpsertOne {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.SetUserID(v)
})
}
// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *UserAllowedGroupUpsertOne) UpdateUserID() *UserAllowedGroupUpsertOne {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.UpdateUserID()
})
}
// SetGroupID sets the "group_id" field.
func (u *UserAllowedGroupUpsertOne) SetGroupID(v int64) *UserAllowedGroupUpsertOne {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.SetGroupID(v)
})
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *UserAllowedGroupUpsertOne) UpdateGroupID() *UserAllowedGroupUpsertOne {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.UpdateGroupID()
})
}
// Exec executes the query.
func (u *UserAllowedGroupUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for UserAllowedGroupCreate.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *UserAllowedGroupUpsertOne) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}
// UserAllowedGroupCreateBulk is the builder for creating many UserAllowedGroup entities in bulk.
type UserAllowedGroupCreateBulk struct {
config
err error
builders []*UserAllowedGroupCreate
conflict []sql.ConflictOption
}
// Save creates the UserAllowedGroup entities in the database.
func (_c *UserAllowedGroupCreateBulk) Save(ctx context.Context) ([]*UserAllowedGroup, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*UserAllowedGroup, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserAllowedGroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
spec.OnConflict = _c.conflict
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *UserAllowedGroupCreateBulk) SaveX(ctx context.Context) []*UserAllowedGroup {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserAllowedGroupCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserAllowedGroupCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.UserAllowedGroup.CreateBulk(builders...).
// OnConflict(
// // Update the row with the new values
// // the was proposed for insertion.
// sql.ResolveWithNewValues(),
// ).
// // Override some of the fields with custom
// // update values.
// Update(func(u *ent.UserAllowedGroupUpsert) {
// SetUserID(v+v).
// }).
// Exec(ctx)
func (_c *UserAllowedGroupCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserAllowedGroupUpsertBulk {
_c.conflict = opts
return &UserAllowedGroupUpsertBulk{
create: _c,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.UserAllowedGroup.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (_c *UserAllowedGroupCreateBulk) OnConflictColumns(columns ...string) *UserAllowedGroupUpsertBulk {
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
return &UserAllowedGroupUpsertBulk{
create: _c,
}
}
// UserAllowedGroupUpsertBulk is the builder for "upsert"-ing
// a bulk of UserAllowedGroup nodes.
type UserAllowedGroupUpsertBulk struct {
create *UserAllowedGroupCreateBulk
}
// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
// client.UserAllowedGroup.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// ).
// Exec(ctx)
func (u *UserAllowedGroupUpsertBulk) UpdateNewValues() *UserAllowedGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
for _, b := range u.create.builders {
if _, exists := b.mutation.CreatedAt(); exists {
s.SetIgnore(userallowedgroup.FieldCreatedAt)
}
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.UserAllowedGroup.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *UserAllowedGroupUpsertBulk) Ignore() *UserAllowedGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
return u
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *UserAllowedGroupUpsertBulk) DoNothing() *UserAllowedGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the UserAllowedGroupCreateBulk.OnConflict
// documentation for more info.
func (u *UserAllowedGroupUpsertBulk) Update(set func(*UserAllowedGroupUpsert)) *UserAllowedGroupUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&UserAllowedGroupUpsert{UpdateSet: update})
}))
return u
}
// SetUserID sets the "user_id" field.
func (u *UserAllowedGroupUpsertBulk) SetUserID(v int64) *UserAllowedGroupUpsertBulk {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.SetUserID(v)
})
}
// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *UserAllowedGroupUpsertBulk) UpdateUserID() *UserAllowedGroupUpsertBulk {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.UpdateUserID()
})
}
// SetGroupID sets the "group_id" field.
func (u *UserAllowedGroupUpsertBulk) SetGroupID(v int64) *UserAllowedGroupUpsertBulk {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.SetGroupID(v)
})
}
// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *UserAllowedGroupUpsertBulk) UpdateGroupID() *UserAllowedGroupUpsertBulk {
return u.Update(func(s *UserAllowedGroupUpsert) {
s.UpdateGroupID()
})
}
// Exec executes the query.
func (u *UserAllowedGroupUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
return u.create.err
}
for i, b := range u.create.builders {
if len(b.conflict) != 0 {
return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the UserAllowedGroupCreateBulk instead", i)
}
}
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for UserAllowedGroupCreateBulk.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *UserAllowedGroupUpsertBulk) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,87 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
)
// UserAllowedGroupDelete is the builder for deleting a UserAllowedGroup entity.
type UserAllowedGroupDelete struct {
config
hooks []Hook
mutation *UserAllowedGroupMutation
}
// Where appends a list predicates to the UserAllowedGroupDelete builder.
func (_d *UserAllowedGroupDelete) Where(ps ...predicate.UserAllowedGroup) *UserAllowedGroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserAllowedGroupDelete) 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 *UserAllowedGroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserAllowedGroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(userallowedgroup.Table, nil)
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
}
// UserAllowedGroupDeleteOne is the builder for deleting a single UserAllowedGroup entity.
type UserAllowedGroupDeleteOne struct {
_d *UserAllowedGroupDelete
}
// Where appends a list predicates to the UserAllowedGroupDelete builder.
func (_d *UserAllowedGroupDeleteOne) Where(ps ...predicate.UserAllowedGroup) *UserAllowedGroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserAllowedGroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{userallowedgroup.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserAllowedGroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,603 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
)
// UserAllowedGroupQuery is the builder for querying UserAllowedGroup entities.
type UserAllowedGroupQuery struct {
config
ctx *QueryContext
order []userallowedgroup.OrderOption
inters []Interceptor
predicates []predicate.UserAllowedGroup
withUser *UserQuery
withGroup *GroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserAllowedGroupQuery builder.
func (_q *UserAllowedGroupQuery) Where(ps ...predicate.UserAllowedGroup) *UserAllowedGroupQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserAllowedGroupQuery) Limit(limit int) *UserAllowedGroupQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserAllowedGroupQuery) Offset(offset int) *UserAllowedGroupQuery {
_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 *UserAllowedGroupQuery) Unique(unique bool) *UserAllowedGroupQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserAllowedGroupQuery) Order(o ...userallowedgroup.OrderOption) *UserAllowedGroupQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUser chains the current query on the "user" edge.
func (_q *UserAllowedGroupQuery) QueryUser() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(userallowedgroup.Table, userallowedgroup.UserColumn, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, userallowedgroup.UserTable, userallowedgroup.UserColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryGroup chains the current query on the "group" edge.
func (_q *UserAllowedGroupQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(userallowedgroup.Table, userallowedgroup.GroupColumn, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, userallowedgroup.GroupTable, userallowedgroup.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first UserAllowedGroup entity from the query.
// Returns a *NotFoundError when no UserAllowedGroup was found.
func (_q *UserAllowedGroupQuery) First(ctx context.Context) (*UserAllowedGroup, 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{userallowedgroup.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserAllowedGroupQuery) FirstX(ctx context.Context) *UserAllowedGroup {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// Only returns a single UserAllowedGroup entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one UserAllowedGroup entity is found.
// Returns a *NotFoundError when no UserAllowedGroup entities are found.
func (_q *UserAllowedGroupQuery) Only(ctx context.Context) (*UserAllowedGroup, 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{userallowedgroup.Label}
default:
return nil, &NotSingularError{userallowedgroup.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserAllowedGroupQuery) OnlyX(ctx context.Context) *UserAllowedGroup {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// All executes the query and returns a list of UserAllowedGroups.
func (_q *UserAllowedGroupQuery) All(ctx context.Context) ([]*UserAllowedGroup, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*UserAllowedGroup, *UserAllowedGroupQuery]()
return withInterceptors[[]*UserAllowedGroup](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserAllowedGroupQuery) AllX(ctx context.Context) []*UserAllowedGroup {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// Count returns the count of the given query.
func (_q *UserAllowedGroupQuery) 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[*UserAllowedGroupQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserAllowedGroupQuery) 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 *UserAllowedGroupQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.First(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 *UserAllowedGroupQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserAllowedGroupQuery 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 *UserAllowedGroupQuery) Clone() *UserAllowedGroupQuery {
if _q == nil {
return nil
}
return &UserAllowedGroupQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]userallowedgroup.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.UserAllowedGroup{}, _q.predicates...),
withUser: _q.withUser.Clone(),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserAllowedGroupQuery) WithUser(opts ...func(*UserQuery)) *UserAllowedGroupQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUser = query
return _q
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserAllowedGroupQuery) WithGroup(opts ...func(*GroupQuery)) *UserAllowedGroupQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// UserID int64 `json:"user_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.UserAllowedGroup.Query().
// GroupBy(userallowedgroup.FieldUserID).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *UserAllowedGroupQuery) GroupBy(field string, fields ...string) *UserAllowedGroupGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserAllowedGroupGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = userallowedgroup.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// UserID int64 `json:"user_id,omitempty"`
// }
//
// client.UserAllowedGroup.Query().
// Select(userallowedgroup.FieldUserID).
// Scan(ctx, &v)
func (_q *UserAllowedGroupQuery) Select(fields ...string) *UserAllowedGroupSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserAllowedGroupSelect{UserAllowedGroupQuery: _q}
sbuild.label = userallowedgroup.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserAllowedGroupSelect configured with the given aggregations.
func (_q *UserAllowedGroupQuery) Aggregate(fns ...AggregateFunc) *UserAllowedGroupSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserAllowedGroupQuery) 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 !userallowedgroup.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 *UserAllowedGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserAllowedGroup, error) {
var (
nodes = []*UserAllowedGroup{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withUser != nil,
_q.withGroup != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*UserAllowedGroup).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &UserAllowedGroup{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUser; query != nil {
if err := _q.loadUser(ctx, query, nodes, nil,
func(n *UserAllowedGroup, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
if query := _q.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes, nil,
func(n *UserAllowedGroup, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserAllowedGroupQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserAllowedGroup, init func(*UserAllowedGroup), assign func(*UserAllowedGroup, *User)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*UserAllowedGroup)
for i := range nodes {
fk := nodes[i].UserID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *UserAllowedGroupQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*UserAllowedGroup, init func(*UserAllowedGroup), assign func(*UserAllowedGroup, *Group)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*UserAllowedGroup)
for i := range nodes {
fk := nodes[i].GroupID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *UserAllowedGroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Unique = false
_spec.Node.Columns = nil
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *UserAllowedGroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(userallowedgroup.Table, userallowedgroup.Columns, nil)
_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))
for i := range fields {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
if _q.withUser != nil {
_spec.Node.AddColumnOnce(userallowedgroup.FieldUserID)
}
if _q.withGroup != nil {
_spec.Node.AddColumnOnce(userallowedgroup.FieldGroupID)
}
}
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 *UserAllowedGroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(userallowedgroup.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = userallowedgroup.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UserAllowedGroupGroupBy is the group-by builder for UserAllowedGroup entities.
type UserAllowedGroupGroupBy struct {
selector
build *UserAllowedGroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserAllowedGroupGroupBy) Aggregate(fns ...AggregateFunc) *UserAllowedGroupGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserAllowedGroupGroupBy) 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[*UserAllowedGroupQuery, *UserAllowedGroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserAllowedGroupGroupBy) sqlScan(ctx context.Context, root *UserAllowedGroupQuery, 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)
}
// UserAllowedGroupSelect is the builder for selecting fields of UserAllowedGroup entities.
type UserAllowedGroupSelect struct {
*UserAllowedGroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserAllowedGroupSelect) Aggregate(fns ...AggregateFunc) *UserAllowedGroupSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserAllowedGroupSelect) 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[*UserAllowedGroupQuery, *UserAllowedGroupSelect](ctx, _s.UserAllowedGroupQuery, _s, _s.inters, v)
}
func (_s *UserAllowedGroupSelect) sqlScan(ctx context.Context, root *UserAllowedGroupQuery, 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)
}

View File

@@ -0,0 +1,423 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
)
// UserAllowedGroupUpdate is the builder for updating UserAllowedGroup entities.
type UserAllowedGroupUpdate struct {
config
hooks []Hook
mutation *UserAllowedGroupMutation
}
// Where appends a list predicates to the UserAllowedGroupUpdate builder.
func (_u *UserAllowedGroupUpdate) Where(ps ...predicate.UserAllowedGroup) *UserAllowedGroupUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUserID sets the "user_id" field.
func (_u *UserAllowedGroupUpdate) SetUserID(v int64) *UserAllowedGroupUpdate {
_u.mutation.SetUserID(v)
return _u
}
// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *UserAllowedGroupUpdate) SetNillableUserID(v *int64) *UserAllowedGroupUpdate {
if v != nil {
_u.SetUserID(*v)
}
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *UserAllowedGroupUpdate) SetGroupID(v int64) *UserAllowedGroupUpdate {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *UserAllowedGroupUpdate) SetNillableGroupID(v *int64) *UserAllowedGroupUpdate {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// SetUser sets the "user" edge to the User entity.
func (_u *UserAllowedGroupUpdate) SetUser(v *User) *UserAllowedGroupUpdate {
return _u.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *UserAllowedGroupUpdate) SetGroup(v *Group) *UserAllowedGroupUpdate {
return _u.SetGroupID(v.ID)
}
// Mutation returns the UserAllowedGroupMutation object of the builder.
func (_u *UserAllowedGroupUpdate) Mutation() *UserAllowedGroupMutation {
return _u.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (_u *UserAllowedGroupUpdate) ClearUser() *UserAllowedGroupUpdate {
_u.mutation.ClearUser()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *UserAllowedGroupUpdate) ClearGroup() *UserAllowedGroupUpdate {
_u.mutation.ClearGroup()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserAllowedGroupUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserAllowedGroupUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UserAllowedGroupUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserAllowedGroupUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserAllowedGroupUpdate) check() error {
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "UserAllowedGroup.user"`)
}
if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "UserAllowedGroup.group"`)
}
return nil
}
func (_u *UserAllowedGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(userallowedgroup.Table, userallowedgroup.Columns, sqlgraph.NewFieldSpec(userallowedgroup.FieldUserID, field.TypeInt64), sqlgraph.NewFieldSpec(userallowedgroup.FieldGroupID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if _u.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.UserTable,
Columns: []string{userallowedgroup.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.UserTable,
Columns: []string{userallowedgroup.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.GroupTable,
Columns: []string{userallowedgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.GroupTable,
Columns: []string{userallowedgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{userallowedgroup.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UserAllowedGroupUpdateOne is the builder for updating a single UserAllowedGroup entity.
type UserAllowedGroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserAllowedGroupMutation
}
// SetUserID sets the "user_id" field.
func (_u *UserAllowedGroupUpdateOne) SetUserID(v int64) *UserAllowedGroupUpdateOne {
_u.mutation.SetUserID(v)
return _u
}
// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *UserAllowedGroupUpdateOne) SetNillableUserID(v *int64) *UserAllowedGroupUpdateOne {
if v != nil {
_u.SetUserID(*v)
}
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *UserAllowedGroupUpdateOne) SetGroupID(v int64) *UserAllowedGroupUpdateOne {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *UserAllowedGroupUpdateOne) SetNillableGroupID(v *int64) *UserAllowedGroupUpdateOne {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// SetUser sets the "user" edge to the User entity.
func (_u *UserAllowedGroupUpdateOne) SetUser(v *User) *UserAllowedGroupUpdateOne {
return _u.SetUserID(v.ID)
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *UserAllowedGroupUpdateOne) SetGroup(v *Group) *UserAllowedGroupUpdateOne {
return _u.SetGroupID(v.ID)
}
// Mutation returns the UserAllowedGroupMutation object of the builder.
func (_u *UserAllowedGroupUpdateOne) Mutation() *UserAllowedGroupMutation {
return _u.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (_u *UserAllowedGroupUpdateOne) ClearUser() *UserAllowedGroupUpdateOne {
_u.mutation.ClearUser()
return _u
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *UserAllowedGroupUpdateOne) ClearGroup() *UserAllowedGroupUpdateOne {
_u.mutation.ClearGroup()
return _u
}
// Where appends a list predicates to the UserAllowedGroupUpdate builder.
func (_u *UserAllowedGroupUpdateOne) Where(ps ...predicate.UserAllowedGroup) *UserAllowedGroupUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *UserAllowedGroupUpdateOne) Select(field string, fields ...string) *UserAllowedGroupUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated UserAllowedGroup entity.
func (_u *UserAllowedGroupUpdateOne) Save(ctx context.Context) (*UserAllowedGroup, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserAllowedGroupUpdateOne) SaveX(ctx context.Context) *UserAllowedGroup {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UserAllowedGroupUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserAllowedGroupUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserAllowedGroupUpdateOne) check() error {
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "UserAllowedGroup.user"`)
}
if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "UserAllowedGroup.group"`)
}
return nil
}
func (_u *UserAllowedGroupUpdateOne) sqlSave(ctx context.Context) (_node *UserAllowedGroup, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(userallowedgroup.Table, userallowedgroup.Columns, sqlgraph.NewFieldSpec(userallowedgroup.FieldUserID, field.TypeInt64), sqlgraph.NewFieldSpec(userallowedgroup.FieldGroupID, field.TypeInt64))
if id, ok := _u.mutation.UserID(); !ok {
return nil, &ValidationError{Name: "user_id", err: errors.New(`ent: missing "UserAllowedGroup.user_id" for update`)}
} else {
_spec.Node.CompositeID[0].Value = id
}
if id, ok := _u.mutation.GroupID(); !ok {
return nil, &ValidationError{Name: "group_id", err: errors.New(`ent: missing "UserAllowedGroup.group_id" for update`)}
} else {
_spec.Node.CompositeID[1].Value = id
}
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, len(fields))
for i, f := range fields {
if !userallowedgroup.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
_spec.Node.Columns[i] = f
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if _u.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.UserTable,
Columns: []string{userallowedgroup.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.UserTable,
Columns: []string{userallowedgroup.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.GroupTable,
Columns: []string{userallowedgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: userallowedgroup.GroupTable,
Columns: []string{userallowedgroup.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &UserAllowedGroup{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{userallowedgroup.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,354 @@
// 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/group"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
)
// UserSubscription is the model entity for the UserSubscription schema.
type UserSubscription 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"`
// UserID holds the value of the "user_id" field.
UserID int64 `json:"user_id,omitempty"`
// GroupID holds the value of the "group_id" field.
GroupID int64 `json:"group_id,omitempty"`
// StartsAt holds the value of the "starts_at" field.
StartsAt time.Time `json:"starts_at,omitempty"`
// ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// DailyWindowStart holds the value of the "daily_window_start" field.
DailyWindowStart *time.Time `json:"daily_window_start,omitempty"`
// WeeklyWindowStart holds the value of the "weekly_window_start" field.
WeeklyWindowStart *time.Time `json:"weekly_window_start,omitempty"`
// MonthlyWindowStart holds the value of the "monthly_window_start" field.
MonthlyWindowStart *time.Time `json:"monthly_window_start,omitempty"`
// DailyUsageUsd holds the value of the "daily_usage_usd" field.
DailyUsageUsd float64 `json:"daily_usage_usd,omitempty"`
// WeeklyUsageUsd holds the value of the "weekly_usage_usd" field.
WeeklyUsageUsd float64 `json:"weekly_usage_usd,omitempty"`
// MonthlyUsageUsd holds the value of the "monthly_usage_usd" field.
MonthlyUsageUsd float64 `json:"monthly_usage_usd,omitempty"`
// AssignedBy holds the value of the "assigned_by" field.
AssignedBy *int64 `json:"assigned_by,omitempty"`
// AssignedAt holds the value of the "assigned_at" field.
AssignedAt time.Time `json:"assigned_at,omitempty"`
// Notes holds the value of the "notes" field.
Notes *string `json:"notes,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserSubscriptionQuery when eager-loading is set.
Edges UserSubscriptionEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserSubscriptionEdges holds the relations/edges for other nodes in the graph.
type UserSubscriptionEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// AssignedByUser holds the value of the assigned_by_user edge.
AssignedByUser *User `json:"assigned_by_user,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [3]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserSubscriptionEdges) UserOrErr() (*User, error) {
if e.User != nil {
return e.User, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "user"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserSubscriptionEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// AssignedByUserOrErr returns the AssignedByUser value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserSubscriptionEdges) AssignedByUserOrErr() (*User, error) {
if e.AssignedByUser != nil {
return e.AssignedByUser, nil
} else if e.loadedTypes[2] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "assigned_by_user"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*UserSubscription) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case usersubscription.FieldDailyUsageUsd, usersubscription.FieldWeeklyUsageUsd, usersubscription.FieldMonthlyUsageUsd:
values[i] = new(sql.NullFloat64)
case usersubscription.FieldID, usersubscription.FieldUserID, usersubscription.FieldGroupID, usersubscription.FieldAssignedBy:
values[i] = new(sql.NullInt64)
case usersubscription.FieldStatus, usersubscription.FieldNotes:
values[i] = new(sql.NullString)
case usersubscription.FieldCreatedAt, usersubscription.FieldUpdatedAt, usersubscription.FieldStartsAt, usersubscription.FieldExpiresAt, usersubscription.FieldDailyWindowStart, usersubscription.FieldWeeklyWindowStart, usersubscription.FieldMonthlyWindowStart, usersubscription.FieldAssignedAt:
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 UserSubscription fields.
func (_m *UserSubscription) 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 usersubscription.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 usersubscription.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 usersubscription.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 usersubscription.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = value.Int64
}
case usersubscription.FieldGroupID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field group_id", values[i])
} else if value.Valid {
_m.GroupID = value.Int64
}
case usersubscription.FieldStartsAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field starts_at", values[i])
} else if value.Valid {
_m.StartsAt = value.Time
}
case usersubscription.FieldExpiresAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
} else if value.Valid {
_m.ExpiresAt = value.Time
}
case usersubscription.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
case usersubscription.FieldDailyWindowStart:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field daily_window_start", values[i])
} else if value.Valid {
_m.DailyWindowStart = new(time.Time)
*_m.DailyWindowStart = value.Time
}
case usersubscription.FieldWeeklyWindowStart:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field weekly_window_start", values[i])
} else if value.Valid {
_m.WeeklyWindowStart = new(time.Time)
*_m.WeeklyWindowStart = value.Time
}
case usersubscription.FieldMonthlyWindowStart:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field monthly_window_start", values[i])
} else if value.Valid {
_m.MonthlyWindowStart = new(time.Time)
*_m.MonthlyWindowStart = value.Time
}
case usersubscription.FieldDailyUsageUsd:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field daily_usage_usd", values[i])
} else if value.Valid {
_m.DailyUsageUsd = value.Float64
}
case usersubscription.FieldWeeklyUsageUsd:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field weekly_usage_usd", values[i])
} else if value.Valid {
_m.WeeklyUsageUsd = value.Float64
}
case usersubscription.FieldMonthlyUsageUsd:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field monthly_usage_usd", values[i])
} else if value.Valid {
_m.MonthlyUsageUsd = value.Float64
}
case usersubscription.FieldAssignedBy:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field assigned_by", values[i])
} else if value.Valid {
_m.AssignedBy = new(int64)
*_m.AssignedBy = value.Int64
}
case usersubscription.FieldAssignedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field assigned_at", values[i])
} else if value.Valid {
_m.AssignedAt = value.Time
}
case usersubscription.FieldNotes:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[i])
} else if value.Valid {
_m.Notes = new(string)
*_m.Notes = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the UserSubscription.
// This includes values selected through modifiers, order, etc.
func (_m *UserSubscription) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the UserSubscription entity.
func (_m *UserSubscription) QueryUser() *UserQuery {
return NewUserSubscriptionClient(_m.config).QueryUser(_m)
}
// QueryGroup queries the "group" edge of the UserSubscription entity.
func (_m *UserSubscription) QueryGroup() *GroupQuery {
return NewUserSubscriptionClient(_m.config).QueryGroup(_m)
}
// QueryAssignedByUser queries the "assigned_by_user" edge of the UserSubscription entity.
func (_m *UserSubscription) QueryAssignedByUser() *UserQuery {
return NewUserSubscriptionClient(_m.config).QueryAssignedByUser(_m)
}
// Update returns a builder for updating this UserSubscription.
// Note that you need to call UserSubscription.Unwrap() before calling this method if this UserSubscription
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *UserSubscription) Update() *UserSubscriptionUpdateOne {
return NewUserSubscriptionClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the UserSubscription 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 *UserSubscription) Unwrap() *UserSubscription {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: UserSubscription is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *UserSubscription) String() string {
var builder strings.Builder
builder.WriteString("UserSubscription(")
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("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("group_id=")
builder.WriteString(fmt.Sprintf("%v", _m.GroupID))
builder.WriteString(", ")
builder.WriteString("starts_at=")
builder.WriteString(_m.StartsAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("expires_at=")
builder.WriteString(_m.ExpiresAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
if v := _m.DailyWindowStart; v != nil {
builder.WriteString("daily_window_start=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.WeeklyWindowStart; v != nil {
builder.WriteString("weekly_window_start=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.MonthlyWindowStart; v != nil {
builder.WriteString("monthly_window_start=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("daily_usage_usd=")
builder.WriteString(fmt.Sprintf("%v", _m.DailyUsageUsd))
builder.WriteString(", ")
builder.WriteString("weekly_usage_usd=")
builder.WriteString(fmt.Sprintf("%v", _m.WeeklyUsageUsd))
builder.WriteString(", ")
builder.WriteString("monthly_usage_usd=")
builder.WriteString(fmt.Sprintf("%v", _m.MonthlyUsageUsd))
builder.WriteString(", ")
if v := _m.AssignedBy; v != nil {
builder.WriteString("assigned_by=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("assigned_at=")
builder.WriteString(_m.AssignedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := _m.Notes; v != nil {
builder.WriteString("notes=")
builder.WriteString(*v)
}
builder.WriteByte(')')
return builder.String()
}
// UserSubscriptions is a parsable slice of UserSubscription.
type UserSubscriptions []*UserSubscription

View File

@@ -0,0 +1,260 @@
// Code generated by ent, DO NOT EDIT.
package usersubscription
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the usersubscription type in the database.
Label = "user_subscription"
// 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"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldGroupID holds the string denoting the group_id field in the database.
FieldGroupID = "group_id"
// FieldStartsAt holds the string denoting the starts_at field in the database.
FieldStartsAt = "starts_at"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldDailyWindowStart holds the string denoting the daily_window_start field in the database.
FieldDailyWindowStart = "daily_window_start"
// FieldWeeklyWindowStart holds the string denoting the weekly_window_start field in the database.
FieldWeeklyWindowStart = "weekly_window_start"
// FieldMonthlyWindowStart holds the string denoting the monthly_window_start field in the database.
FieldMonthlyWindowStart = "monthly_window_start"
// FieldDailyUsageUsd holds the string denoting the daily_usage_usd field in the database.
FieldDailyUsageUsd = "daily_usage_usd"
// FieldWeeklyUsageUsd holds the string denoting the weekly_usage_usd field in the database.
FieldWeeklyUsageUsd = "weekly_usage_usd"
// FieldMonthlyUsageUsd holds the string denoting the monthly_usage_usd field in the database.
FieldMonthlyUsageUsd = "monthly_usage_usd"
// FieldAssignedBy holds the string denoting the assigned_by field in the database.
FieldAssignedBy = "assigned_by"
// FieldAssignedAt holds the string denoting the assigned_at field in the database.
FieldAssignedAt = "assigned_at"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeAssignedByUser holds the string denoting the assigned_by_user edge name in mutations.
EdgeAssignedByUser = "assigned_by_user"
// Table holds the table name of the usersubscription in the database.
Table = "user_subscriptions"
// UserTable is the table that holds the user relation/edge.
UserTable = "user_subscriptions"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_id"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "user_subscriptions"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
// AssignedByUserTable is the table that holds the assigned_by_user relation/edge.
AssignedByUserTable = "user_subscriptions"
// AssignedByUserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
AssignedByUserInverseTable = "users"
// AssignedByUserColumn is the table column denoting the assigned_by_user relation/edge.
AssignedByUserColumn = "assigned_by"
)
// Columns holds all SQL columns for usersubscription fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldUserID,
FieldGroupID,
FieldStartsAt,
FieldExpiresAt,
FieldStatus,
FieldDailyWindowStart,
FieldWeeklyWindowStart,
FieldMonthlyWindowStart,
FieldDailyUsageUsd,
FieldWeeklyUsageUsd,
FieldMonthlyUsageUsd,
FieldAssignedBy,
FieldAssignedAt,
FieldNotes,
}
// 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
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DefaultDailyUsageUsd holds the default value on creation for the "daily_usage_usd" field.
DefaultDailyUsageUsd float64
// DefaultWeeklyUsageUsd holds the default value on creation for the "weekly_usage_usd" field.
DefaultWeeklyUsageUsd float64
// DefaultMonthlyUsageUsd holds the default value on creation for the "monthly_usage_usd" field.
DefaultMonthlyUsageUsd float64
// DefaultAssignedAt holds the default value on creation for the "assigned_at" field.
DefaultAssignedAt func() time.Time
)
// OrderOption defines the ordering options for the UserSubscription 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()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByGroupID orders the results by the group_id field.
func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGroupID, opts...).ToFunc()
}
// ByStartsAt orders the results by the starts_at field.
func ByStartsAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStartsAt, opts...).ToFunc()
}
// ByExpiresAt orders the results by the expires_at field.
func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByDailyWindowStart orders the results by the daily_window_start field.
func ByDailyWindowStart(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDailyWindowStart, opts...).ToFunc()
}
// ByWeeklyWindowStart orders the results by the weekly_window_start field.
func ByWeeklyWindowStart(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWeeklyWindowStart, opts...).ToFunc()
}
// ByMonthlyWindowStart orders the results by the monthly_window_start field.
func ByMonthlyWindowStart(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMonthlyWindowStart, opts...).ToFunc()
}
// ByDailyUsageUsd orders the results by the daily_usage_usd field.
func ByDailyUsageUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDailyUsageUsd, opts...).ToFunc()
}
// ByWeeklyUsageUsd orders the results by the weekly_usage_usd field.
func ByWeeklyUsageUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWeeklyUsageUsd, opts...).ToFunc()
}
// ByMonthlyUsageUsd orders the results by the monthly_usage_usd field.
func ByMonthlyUsageUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMonthlyUsageUsd, opts...).ToFunc()
}
// ByAssignedBy orders the results by the assigned_by field.
func ByAssignedBy(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAssignedBy, opts...).ToFunc()
}
// ByAssignedAt orders the results by the assigned_at field.
func ByAssignedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAssignedAt, opts...).ToFunc()
}
// ByNotes orders the results by the notes field.
func ByNotes(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotes, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
// ByAssignedByUserField orders the results by assigned_by_user field.
func ByAssignedByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAssignedByUserStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
}
func newAssignedByUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AssignedByUserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, AssignedByUserTable, AssignedByUserColumn),
)
}

View File

@@ -0,0 +1,900 @@
// Code generated by ent, DO NOT EDIT.
package usersubscription
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldUpdatedAt, v))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldUserID, v))
}
// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
func GroupID(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldGroupID, v))
}
// StartsAt applies equality check predicate on the "starts_at" field. It's identical to StartsAtEQ.
func StartsAt(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldStartsAt, v))
}
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
func ExpiresAt(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldExpiresAt, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldStatus, v))
}
// DailyWindowStart applies equality check predicate on the "daily_window_start" field. It's identical to DailyWindowStartEQ.
func DailyWindowStart(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldDailyWindowStart, v))
}
// WeeklyWindowStart applies equality check predicate on the "weekly_window_start" field. It's identical to WeeklyWindowStartEQ.
func WeeklyWindowStart(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldWeeklyWindowStart, v))
}
// MonthlyWindowStart applies equality check predicate on the "monthly_window_start" field. It's identical to MonthlyWindowStartEQ.
func MonthlyWindowStart(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldMonthlyWindowStart, v))
}
// DailyUsageUsd applies equality check predicate on the "daily_usage_usd" field. It's identical to DailyUsageUsdEQ.
func DailyUsageUsd(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldDailyUsageUsd, v))
}
// WeeklyUsageUsd applies equality check predicate on the "weekly_usage_usd" field. It's identical to WeeklyUsageUsdEQ.
func WeeklyUsageUsd(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldWeeklyUsageUsd, v))
}
// MonthlyUsageUsd applies equality check predicate on the "monthly_usage_usd" field. It's identical to MonthlyUsageUsdEQ.
func MonthlyUsageUsd(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldMonthlyUsageUsd, v))
}
// AssignedBy applies equality check predicate on the "assigned_by" field. It's identical to AssignedByEQ.
func AssignedBy(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldAssignedBy, v))
}
// AssignedAt applies equality check predicate on the "assigned_at" field. It's identical to AssignedAtEQ.
func AssignedAt(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldAssignedAt, v))
}
// Notes applies equality check predicate on the "notes" field. It's identical to NotesEQ.
func Notes(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldNotes, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldUpdatedAt, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldUserID, vs...))
}
// GroupIDEQ applies the EQ predicate on the "group_id" field.
func GroupIDEQ(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldGroupID, v))
}
// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
func GroupIDNEQ(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldGroupID, v))
}
// GroupIDIn applies the In predicate on the "group_id" field.
func GroupIDIn(vs ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldGroupID, vs...))
}
// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
func GroupIDNotIn(vs ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldGroupID, vs...))
}
// StartsAtEQ applies the EQ predicate on the "starts_at" field.
func StartsAtEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldStartsAt, v))
}
// StartsAtNEQ applies the NEQ predicate on the "starts_at" field.
func StartsAtNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldStartsAt, v))
}
// StartsAtIn applies the In predicate on the "starts_at" field.
func StartsAtIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldStartsAt, vs...))
}
// StartsAtNotIn applies the NotIn predicate on the "starts_at" field.
func StartsAtNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldStartsAt, vs...))
}
// StartsAtGT applies the GT predicate on the "starts_at" field.
func StartsAtGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldStartsAt, v))
}
// StartsAtGTE applies the GTE predicate on the "starts_at" field.
func StartsAtGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldStartsAt, v))
}
// StartsAtLT applies the LT predicate on the "starts_at" field.
func StartsAtLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldStartsAt, v))
}
// StartsAtLTE applies the LTE predicate on the "starts_at" field.
func StartsAtLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldStartsAt, v))
}
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
func ExpiresAtEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldExpiresAt, v))
}
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
func ExpiresAtNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldExpiresAt, v))
}
// ExpiresAtIn applies the In predicate on the "expires_at" field.
func ExpiresAtIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldExpiresAt, vs...))
}
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
func ExpiresAtNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldExpiresAt, vs...))
}
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
func ExpiresAtGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldExpiresAt, v))
}
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
func ExpiresAtGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldExpiresAt, v))
}
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
func ExpiresAtLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldExpiresAt, v))
}
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
func ExpiresAtLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldExpiresAt, v))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldContainsFold(FieldStatus, v))
}
// DailyWindowStartEQ applies the EQ predicate on the "daily_window_start" field.
func DailyWindowStartEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldDailyWindowStart, v))
}
// DailyWindowStartNEQ applies the NEQ predicate on the "daily_window_start" field.
func DailyWindowStartNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldDailyWindowStart, v))
}
// DailyWindowStartIn applies the In predicate on the "daily_window_start" field.
func DailyWindowStartIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldDailyWindowStart, vs...))
}
// DailyWindowStartNotIn applies the NotIn predicate on the "daily_window_start" field.
func DailyWindowStartNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldDailyWindowStart, vs...))
}
// DailyWindowStartGT applies the GT predicate on the "daily_window_start" field.
func DailyWindowStartGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldDailyWindowStart, v))
}
// DailyWindowStartGTE applies the GTE predicate on the "daily_window_start" field.
func DailyWindowStartGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldDailyWindowStart, v))
}
// DailyWindowStartLT applies the LT predicate on the "daily_window_start" field.
func DailyWindowStartLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldDailyWindowStart, v))
}
// DailyWindowStartLTE applies the LTE predicate on the "daily_window_start" field.
func DailyWindowStartLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldDailyWindowStart, v))
}
// DailyWindowStartIsNil applies the IsNil predicate on the "daily_window_start" field.
func DailyWindowStartIsNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIsNull(FieldDailyWindowStart))
}
// DailyWindowStartNotNil applies the NotNil predicate on the "daily_window_start" field.
func DailyWindowStartNotNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotNull(FieldDailyWindowStart))
}
// WeeklyWindowStartEQ applies the EQ predicate on the "weekly_window_start" field.
func WeeklyWindowStartEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldWeeklyWindowStart, v))
}
// WeeklyWindowStartNEQ applies the NEQ predicate on the "weekly_window_start" field.
func WeeklyWindowStartNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldWeeklyWindowStart, v))
}
// WeeklyWindowStartIn applies the In predicate on the "weekly_window_start" field.
func WeeklyWindowStartIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldWeeklyWindowStart, vs...))
}
// WeeklyWindowStartNotIn applies the NotIn predicate on the "weekly_window_start" field.
func WeeklyWindowStartNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldWeeklyWindowStart, vs...))
}
// WeeklyWindowStartGT applies the GT predicate on the "weekly_window_start" field.
func WeeklyWindowStartGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldWeeklyWindowStart, v))
}
// WeeklyWindowStartGTE applies the GTE predicate on the "weekly_window_start" field.
func WeeklyWindowStartGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldWeeklyWindowStart, v))
}
// WeeklyWindowStartLT applies the LT predicate on the "weekly_window_start" field.
func WeeklyWindowStartLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldWeeklyWindowStart, v))
}
// WeeklyWindowStartLTE applies the LTE predicate on the "weekly_window_start" field.
func WeeklyWindowStartLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldWeeklyWindowStart, v))
}
// WeeklyWindowStartIsNil applies the IsNil predicate on the "weekly_window_start" field.
func WeeklyWindowStartIsNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIsNull(FieldWeeklyWindowStart))
}
// WeeklyWindowStartNotNil applies the NotNil predicate on the "weekly_window_start" field.
func WeeklyWindowStartNotNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotNull(FieldWeeklyWindowStart))
}
// MonthlyWindowStartEQ applies the EQ predicate on the "monthly_window_start" field.
func MonthlyWindowStartEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldMonthlyWindowStart, v))
}
// MonthlyWindowStartNEQ applies the NEQ predicate on the "monthly_window_start" field.
func MonthlyWindowStartNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldMonthlyWindowStart, v))
}
// MonthlyWindowStartIn applies the In predicate on the "monthly_window_start" field.
func MonthlyWindowStartIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldMonthlyWindowStart, vs...))
}
// MonthlyWindowStartNotIn applies the NotIn predicate on the "monthly_window_start" field.
func MonthlyWindowStartNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldMonthlyWindowStart, vs...))
}
// MonthlyWindowStartGT applies the GT predicate on the "monthly_window_start" field.
func MonthlyWindowStartGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldMonthlyWindowStart, v))
}
// MonthlyWindowStartGTE applies the GTE predicate on the "monthly_window_start" field.
func MonthlyWindowStartGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldMonthlyWindowStart, v))
}
// MonthlyWindowStartLT applies the LT predicate on the "monthly_window_start" field.
func MonthlyWindowStartLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldMonthlyWindowStart, v))
}
// MonthlyWindowStartLTE applies the LTE predicate on the "monthly_window_start" field.
func MonthlyWindowStartLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldMonthlyWindowStart, v))
}
// MonthlyWindowStartIsNil applies the IsNil predicate on the "monthly_window_start" field.
func MonthlyWindowStartIsNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIsNull(FieldMonthlyWindowStart))
}
// MonthlyWindowStartNotNil applies the NotNil predicate on the "monthly_window_start" field.
func MonthlyWindowStartNotNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotNull(FieldMonthlyWindowStart))
}
// DailyUsageUsdEQ applies the EQ predicate on the "daily_usage_usd" field.
func DailyUsageUsdEQ(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldDailyUsageUsd, v))
}
// DailyUsageUsdNEQ applies the NEQ predicate on the "daily_usage_usd" field.
func DailyUsageUsdNEQ(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldDailyUsageUsd, v))
}
// DailyUsageUsdIn applies the In predicate on the "daily_usage_usd" field.
func DailyUsageUsdIn(vs ...float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldDailyUsageUsd, vs...))
}
// DailyUsageUsdNotIn applies the NotIn predicate on the "daily_usage_usd" field.
func DailyUsageUsdNotIn(vs ...float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldDailyUsageUsd, vs...))
}
// DailyUsageUsdGT applies the GT predicate on the "daily_usage_usd" field.
func DailyUsageUsdGT(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldDailyUsageUsd, v))
}
// DailyUsageUsdGTE applies the GTE predicate on the "daily_usage_usd" field.
func DailyUsageUsdGTE(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldDailyUsageUsd, v))
}
// DailyUsageUsdLT applies the LT predicate on the "daily_usage_usd" field.
func DailyUsageUsdLT(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldDailyUsageUsd, v))
}
// DailyUsageUsdLTE applies the LTE predicate on the "daily_usage_usd" field.
func DailyUsageUsdLTE(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldDailyUsageUsd, v))
}
// WeeklyUsageUsdEQ applies the EQ predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdEQ(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldWeeklyUsageUsd, v))
}
// WeeklyUsageUsdNEQ applies the NEQ predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdNEQ(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldWeeklyUsageUsd, v))
}
// WeeklyUsageUsdIn applies the In predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdIn(vs ...float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldWeeklyUsageUsd, vs...))
}
// WeeklyUsageUsdNotIn applies the NotIn predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdNotIn(vs ...float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldWeeklyUsageUsd, vs...))
}
// WeeklyUsageUsdGT applies the GT predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdGT(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldWeeklyUsageUsd, v))
}
// WeeklyUsageUsdGTE applies the GTE predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdGTE(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldWeeklyUsageUsd, v))
}
// WeeklyUsageUsdLT applies the LT predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdLT(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldWeeklyUsageUsd, v))
}
// WeeklyUsageUsdLTE applies the LTE predicate on the "weekly_usage_usd" field.
func WeeklyUsageUsdLTE(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldWeeklyUsageUsd, v))
}
// MonthlyUsageUsdEQ applies the EQ predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdEQ(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldMonthlyUsageUsd, v))
}
// MonthlyUsageUsdNEQ applies the NEQ predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdNEQ(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldMonthlyUsageUsd, v))
}
// MonthlyUsageUsdIn applies the In predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdIn(vs ...float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldMonthlyUsageUsd, vs...))
}
// MonthlyUsageUsdNotIn applies the NotIn predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdNotIn(vs ...float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldMonthlyUsageUsd, vs...))
}
// MonthlyUsageUsdGT applies the GT predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdGT(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldMonthlyUsageUsd, v))
}
// MonthlyUsageUsdGTE applies the GTE predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdGTE(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldMonthlyUsageUsd, v))
}
// MonthlyUsageUsdLT applies the LT predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdLT(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldMonthlyUsageUsd, v))
}
// MonthlyUsageUsdLTE applies the LTE predicate on the "monthly_usage_usd" field.
func MonthlyUsageUsdLTE(v float64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldMonthlyUsageUsd, v))
}
// AssignedByEQ applies the EQ predicate on the "assigned_by" field.
func AssignedByEQ(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldAssignedBy, v))
}
// AssignedByNEQ applies the NEQ predicate on the "assigned_by" field.
func AssignedByNEQ(v int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldAssignedBy, v))
}
// AssignedByIn applies the In predicate on the "assigned_by" field.
func AssignedByIn(vs ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldAssignedBy, vs...))
}
// AssignedByNotIn applies the NotIn predicate on the "assigned_by" field.
func AssignedByNotIn(vs ...int64) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldAssignedBy, vs...))
}
// AssignedByIsNil applies the IsNil predicate on the "assigned_by" field.
func AssignedByIsNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIsNull(FieldAssignedBy))
}
// AssignedByNotNil applies the NotNil predicate on the "assigned_by" field.
func AssignedByNotNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotNull(FieldAssignedBy))
}
// AssignedAtEQ applies the EQ predicate on the "assigned_at" field.
func AssignedAtEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldAssignedAt, v))
}
// AssignedAtNEQ applies the NEQ predicate on the "assigned_at" field.
func AssignedAtNEQ(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldAssignedAt, v))
}
// AssignedAtIn applies the In predicate on the "assigned_at" field.
func AssignedAtIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldAssignedAt, vs...))
}
// AssignedAtNotIn applies the NotIn predicate on the "assigned_at" field.
func AssignedAtNotIn(vs ...time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldAssignedAt, vs...))
}
// AssignedAtGT applies the GT predicate on the "assigned_at" field.
func AssignedAtGT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldAssignedAt, v))
}
// AssignedAtGTE applies the GTE predicate on the "assigned_at" field.
func AssignedAtGTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldAssignedAt, v))
}
// AssignedAtLT applies the LT predicate on the "assigned_at" field.
func AssignedAtLT(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldAssignedAt, v))
}
// AssignedAtLTE applies the LTE predicate on the "assigned_at" field.
func AssignedAtLTE(v time.Time) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldAssignedAt, v))
}
// NotesEQ applies the EQ predicate on the "notes" field.
func NotesEQ(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEQ(FieldNotes, v))
}
// NotesNEQ applies the NEQ predicate on the "notes" field.
func NotesNEQ(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNEQ(FieldNotes, v))
}
// NotesIn applies the In predicate on the "notes" field.
func NotesIn(vs ...string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIn(FieldNotes, vs...))
}
// NotesNotIn applies the NotIn predicate on the "notes" field.
func NotesNotIn(vs ...string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotIn(FieldNotes, vs...))
}
// NotesGT applies the GT predicate on the "notes" field.
func NotesGT(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGT(FieldNotes, v))
}
// NotesGTE applies the GTE predicate on the "notes" field.
func NotesGTE(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldGTE(FieldNotes, v))
}
// NotesLT applies the LT predicate on the "notes" field.
func NotesLT(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLT(FieldNotes, v))
}
// NotesLTE applies the LTE predicate on the "notes" field.
func NotesLTE(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldLTE(FieldNotes, v))
}
// NotesContains applies the Contains predicate on the "notes" field.
func NotesContains(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldContains(FieldNotes, v))
}
// NotesHasPrefix applies the HasPrefix predicate on the "notes" field.
func NotesHasPrefix(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldHasPrefix(FieldNotes, v))
}
// NotesHasSuffix applies the HasSuffix predicate on the "notes" field.
func NotesHasSuffix(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldHasSuffix(FieldNotes, v))
}
// NotesIsNil applies the IsNil predicate on the "notes" field.
func NotesIsNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldIsNull(FieldNotes))
}
// NotesNotNil applies the NotNil predicate on the "notes" field.
func NotesNotNil() predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldNotNull(FieldNotes))
}
// NotesEqualFold applies the EqualFold predicate on the "notes" field.
func NotesEqualFold(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldEqualFold(FieldNotes, v))
}
// NotesContainsFold applies the ContainsFold predicate on the "notes" field.
func NotesContainsFold(v string) predicate.UserSubscription {
return predicate.UserSubscription(sql.FieldContainsFold(FieldNotes, v))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.UserSubscription {
return predicate.UserSubscription(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.UserSubscription {
return predicate.UserSubscription(func(s *sql.Selector) {
step := newUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.UserSubscription {
return predicate.UserSubscription(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.UserSubscription {
return predicate.UserSubscription(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAssignedByUser applies the HasEdge predicate on the "assigned_by_user" edge.
func HasAssignedByUser() predicate.UserSubscription {
return predicate.UserSubscription(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, AssignedByUserTable, AssignedByUserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAssignedByUserWith applies the HasEdge predicate on the "assigned_by_user" edge with a given conditions (other predicates).
func HasAssignedByUserWith(preds ...predicate.User) predicate.UserSubscription {
return predicate.UserSubscription(func(s *sql.Selector) {
step := newAssignedByUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.UserSubscription) predicate.UserSubscription {
return predicate.UserSubscription(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.UserSubscription) predicate.UserSubscription {
return predicate.UserSubscription(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.UserSubscription) predicate.UserSubscription {
return predicate.UserSubscription(sql.NotPredicates(p))
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More